def _build_colocation_attr_map(input_map, absolute_import_scope):

  colocation_attr_map = collections.defaultdict(_ConsistentValue)
  used_outputs_of_imported_ops = collections.defaultdict(set)

  for imported_tensor_name, mapped_tensor in input_map.items():
    imported_tensor_name = absolute_import_scope + "/" + imported_tensor_name
    imported_op_name, imported_index = _split_tensor_name(imported_tensor_name)
    key = tf.compat.as_bytes("loc:@" + imported_op_name)
    colocation_attr_map[key].Set(
        mapped_tensor.op.colocation_groups(),
        {"reason": "input '%s' is substituted by '%s'" % (
            imported_tensor_name, mapped_tensor.name)})
    used_outputs_of_imported_ops[imported_op_name].add(imported_index)

  for imported_op_name, used_outputs in used_outputs_of_imported_ops.items():
    imported_op = tf_v1.get_default_graph().get_operation_by_name(
        imported_op_name)
    unused_outputs = set(range(len(imported_op.outputs))) - used_outputs
    if not unused_outputs: continue
    key = tf.compat.as_bytes("loc:@" + imported_op_name)
    if imported_op.colocation_groups() != [key]:

      raise ValueError(
          "Internal error: tensors from op '%s' are partially remapped in "
          "import but op.colocation_groups=%s cannot be captured in a "
          "simple rewrite rule." %
          (imported_op_name, imported_op.colocation_groups()))
    colocation_attr_map[key].Set(
        [key],
        {"reason": "tensor '%s:%s' is not substituted by inputs" % (
            imported_op_name,
            ",".join(str(i) for i in sorted(unused_outputs)))})

  return colocation_attr_map

Returns a dict mapping from pre-import to post-import colocation attrs.

Args:
input_map: as for fix_colocation_after_import.
absolute_import_scope: as for fix_colocation_after_import.

Returns:
A dict that maps bytes `"loc:@" + absolute_import_scope + "/foo"`
to _ConsistentValues set to the lists of bytes `["loc:@...", ...]`
according to the rewriting scheme of fix_colocation_after_import.
In case of an inconsistent rewriting, _ConsistentValue.has_error is true.


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 random_shift(image, wsr=0.1, hsr=0.1):

  height, width, _ = common_layers.shape_list(image)
  width_range, height_range = wsr*width, hsr*height
  height_translations = tf.random_uniform((1,), -height_range, height_range)
  width_translations = tf.random_uniform((1,), -width_range, width_range)
  translations = tf.concat((height_translations, width_translations), axis=0)
  return tf.contrib.image.translate(image, translations=translations)

Apply random horizontal and vertical shift to images.

This is the default data-augmentation strategy used on CIFAR in Glow.

Args:
image: a 3-D Tensor
wsr: Width shift range, as a float fraction of the width.
hsr: Height shift range, as a float fraction of the width.
Returns:
images: images translated by the provided wsr and hsr.


def get_2d_local_memory(x, query_shape, memory_flange):

  (_, height, width, depth_x) = common_layers.shape_list(x)
  x_center_blocks = _extract_blocks(x, query_shape[0], query_shape[1])

  paddings = [[0, 0], [memory_flange[0], memory_flange[0]],
              [memory_flange[1], memory_flange[1]], [0, 0]]
  padded_x = tf.pad(x, paddings)
  padded_x.set_shape([None, height+2*memory_flange[0],
                      width+2*memory_flange[1], depth_x])
  x_outer_memory_blocks = _extract_blocks(padded_x,
                                          memory_flange[0], memory_flange[1])

  x_left_blocks, x_right_blocks = _get_left_right_blocks(
      x_outer_memory_blocks)
  t_hw_block = lambda x: tf.transpose(x, [0, 2, 1, 4, 3, 5])

  x_top_center_blocks, x_bottom_center_blocks = (
      map(t_hw_block, _get_left_right_blocks(
          t_hw_block(x_outer_memory_blocks))))

  x_left_corner_blocks, x_right_corner_blocks = _split_along_width(
      x_outer_memory_blocks)

  t_hw = lambda x: tf.transpose(x, [0, 2, 1, 3, 4, 5])
  x_top_left_corner_blocks, x_bottom_left_corner_blocks = (
      map(t_hw, _split_along_width(t_hw(x_left_corner_blocks))))
  x_top_right_corner_blocks, x_bottom_right_corner_blocks = (
      map(t_hw, _split_along_width(t_hw(x_right_corner_blocks))))

  x_top_memory = tf.concat(
      [x_top_left_corner_blocks,
       x_top_center_blocks,
       x_top_right_corner_blocks], axis=4)
  x_middle_memory = tf.concat(
      [x_left_blocks, x_center_blocks, x_right_blocks], axis=4)
  x_bottom_memory = tf.concat(
      [x_bottom_left_corner_blocks,
       x_bottom_center_blocks,
       x_bottom_right_corner_blocks], axis=4)

  x = tf.concat([x_top_memory, x_middle_memory, x_bottom_memory], axis=3)
  return x

Stitches together the local 2d memory blocks.

Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d integer list of memory flanges

Returns:
x: A [batch, num_h_blocks, num_w_blocks,
query_shape[0]+2*memory_flange[0],query_shape[1]+2*memory_flange[1]]
tensor.


def get_ops_from_nodedef(node_def):
    if not node_def.device:
        node_def.device = '/cpu:0'
    kernel_class = _pywrap_kernel_registry.TryFindKernelClass(node_def.SerializeToString())
    op = str(node_def.op)
    if kernel_class or op in OPS_WITHOUT_KERNEL_ALLOWLIST:
        return (op, str(kernel_class.decode('utf-8')) if kernel_class else None)
    else:
        tf_logging.warning('Warning: no kernel found for op %s', op)
        return None

Gets the op and kernel needed from the given NodeDef.

Args:
node_def: TF NodeDef to get op/kernel information.

Returns:
A tuple of (op_name, kernel_name). If the op is not in the allowlist of ops
without kernel and there is no kernel found, then return None.


def __init__(self, filename, compression_type=None):
    self._filename = ops.convert_to_tensor(filename, dtypes.string, name='filename')
    self._compression_type = convert.optional_param_to_tensor('compression_type', compression_type, argument_default='', argument_dtype=dtypes.string)

Initializes a `TFRecordWriter`.

Args:
filename: a string path indicating where to write the TFRecord data.
compression_type: (Optional.) a string indicating what type of compression
to use when writing the file. See `tf.io.TFRecordCompressionType` for
what types of compression are available. Defaults to `None`.


def read_full(fileobj, size):

    if size < 0:
        raise ValueError("size must not be negative")

    data = fileobj.read(size)
    if len(data) != size:
        raise IOError
    return data

Like fileobj.read but raises IOError if not all requested data is
returned.

If you want to distinguish IOError and the EOS case, better handle
the error yourself instead of using this.

Args:
fileobj (fileobj)
size (int): amount of bytes to read
Raises:
IOError: In case read fails or not enough data is read


def stat(self, path=None, client_kwargs=None, header=None):

        stat = OrderedDict((
            ("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
            ("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
            ("st_mtime", 0), ("st_ctime", 0)))

        header = self.head(path, client_kwargs, header)
        for key, method in (
                ('st_size', self._getsize_from_header),
                ('st_ctime', self._getctime_from_header),
                ('st_mtime', self._getmtime_from_header),):
            try:
                stat[key] = int(method(header))
            except UnsupportedOperation:
                continue

        if self.islink(path=path, header=header):

            stat['st_mode'] = S_IFLNK
        elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
                stat['st_size']):

            stat['st_mode'] = S_IFDIR
        else:

            stat['st_mode'] = S_IFREG

        sub = self._CHAR_FILTER.sub
        for key, value in tuple(header.items()):
            stat['st_' + sub('', key.lower())] = value

        stat_result = namedtuple('stat_result', tuple(stat))
        stat_result.__name__ = 'os.stat_result'
        stat_result.__module__ = 'pycosio'
        return stat_result(**stat)

Get the status of an object.

Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.

Returns:
os.stat_result: Stat result object


def mtr_tr_dense(sz):
    n = (2 ** sz)
    hparams = mtf_bitransformer_base()
    hparams.d_model = 1024
    hparams.max_length = 256
    hparams.batch_size = 128
    hparams.d_ff = int((4096 * n))
    hparams.d_kv = 128
    hparams.encoder_num_heads = int((8 * n))
    hparams.decoder_num_heads = int((8 * n))
    hparams.learning_rate_decay_steps = 51400
    hparams.layout = 'batch:batch;vocab:model;d_ff:model;heads:model'
    hparams.mesh_shape = 'batch:32'
    hparams.label_smoothing = 0.1
    hparams.layer_prepostprocess_dropout = 0.1
    hparams.attention_dropout = 0.1
    hparams.relu_dropout = 0.1
    return hparams

Series of machine translation models.

All models are trained on sequences of 256 tokens.

You can use the dataset translate_enfr_wmt32k_packed.
154000 steps = 3 epochs.

Args:
sz: an integer

Returns:
a hparams


def insert(self, keys, values, name=None):
    with ops.name_scope(name, '%s_lookup_table_insert' % self.name, [self.resource_handle, keys, values]):
        keys = ops.convert_to_tensor(keys, self._key_dtype, name='keys')
        values = ops.convert_to_tensor(values, self._value_dtype, name='values')
        with ops.colocate_with(self.resource_handle):
            op = gen_lookup_ops.lookup_table_insert_v2(self.resource_handle, keys, values)
    return op

Associates `keys` with `values`.

Args:
keys: Keys to insert. Can be a tensor of any shape. Must match the table's
key type.
values: Values to be associated with keys. Must be a tensor of the same
shape as `keys` and match the table's value type.
name: A name for the operation (optional).

Returns:
The created Operation.

Raises:
TypeError: when `keys` or `values` doesn't match the table data
types.


def delete_node(self, node_name):

        graph = self.graph
        if node_name not in graph:
            raise KeyError('node %s does not exist' % node_name)
        graph.pop(node_name)

        for node, edges in graph.items():
            if node_name in edges:
                edges.remove(node_name)

Deletes this node and all edges referencing it.

Args:
node_name (str): The name of the node to delete.

Raises:
KeyError: Raised if the node does not exist in the graph.


def default_local_init_op():
    return control_flow_ops.group(variables.local_variables_initializer(), lookup_ops.tables_initializer(), resources.initialize_resources(resources.local_resources()))

Returns an op that groups the default local init ops.

This op is used during session initialization when a Scaffold is
initialized without specifying the local_init_op arg. It includes
`tf.compat.v1.local_variables_initializer`,
`tf.compat.v1.tables_initializer`, and also
initializes local session resources.

Returns:
The default Scaffold local init op.


def IsEquivalent(self, other):
    if (self.name and other.name):
        return (self.name == other.name)
    if self.name:
        (self_family, self_version_tuple) = self._FAMILY_AND_VERSION_PER_NAME.get(self.name, self._DEFAULT_FAMILY_AND_VERSION)
        return ((self_family == other.family) and (self_version_tuple == other.version_tuple))
    if (self.family and self.version):
        if other.name:
            (other_family, other_version_tuple) = self._FAMILY_AND_VERSION_PER_NAME.get(other.name, self._DEFAULT_FAMILY_AND_VERSION)
        else:
            other_family = other.family
            other_version_tuple = other.version_tuple
        return ((self.family == other_family) and (self.version_tuple == other_version_tuple))
    if self.family:
        if other.name:
            (other_family, _) = self._FAMILY_AND_VERSION_PER_NAME.get(other.name, self._DEFAULT_FAMILY_AND_VERSION)
        else:
            other_family = other.family
        return (self.family == other_family)
    return False

Determines if 2 operating system artifacts are equivalent.

This function compares the operating systems based in order of:
* name derived from product
* family and version
* family

Args:
other (OperatingSystemArtifact): operating system artifact attribute
container to compare with.

Returns:
bool: True if the operating systems are considered equivalent, False if
the most specific criteria do no match, or no criteria are available.


def load_values(self, dictionary, as_defaults=False, flat=False):
    if flat:
        separator = self.settings.str_path_separator
        flat_dictionary = dictionary
        dictionary = collections.OrderedDict()
        for (k, v) in flat_dictionary.items():
            k_parts = k.split(separator)
            c = dictionary
            for (i, kp) in enumerate(k_parts):
                if (i >= (len(k_parts) - 1)):
                    c[kp] = v
                else:
                    if (kp not in c):
                        c[kp] = collections.OrderedDict()
                    c = c[kp]
    for (name, value) in dictionary.items():
        if (name not in self):
            if as_defaults:
                if isinstance(value, dict):
                    self[name] = self.create_section()
                    self[name].load_values(value, as_defaults=as_defaults)
                else:
                    self[name] = self.create_item(name, default=value)
            else:
                pass
            continue
        resolution = self._get_item_or_section(name, handle_not_found=False)
        if is_config_item(resolution):
            if as_defaults:
                resolution.default = value
            else:
                resolution.value = value
        else:
            resolution.load_values(value, as_defaults=as_defaults)

Import config values from a dictionary.

When ``as_defaults`` is set to ``True``, the values
imported will be set as defaults. This can be used to
declare the sections and items of configuration.
Values of sections and items in ``dictionary`` can be
dictionaries as well as instances of :class:`.Item` and
:class:`.Config`.

Args:
dictionary:
as_defaults: if ``True``, the imported values will be set as defaults.


def length(self, rows=None):
    rows = (tf.range(self._capacity) if (rows is None) else rows)
    return tf.gather(self._length, rows)

Tensor holding the current length of episodes.

Args:
rows: Episodes to select length from, defaults to all.

Returns:
Batch tensor of sequence lengths.


def update(self, config_dict: dict[str, Any]):
    for key, value in config_dict.items():
        setattr(self, key, value)

Updates attributes of this class with attributes from `config_dict`.

Args:
config_dict (`Dict[str, Any]`): Dictionary of attributes that should be updated for this class.


def return_selected_form_items(form_info):

        selected_keys = []
        selected_names = []
        for chosen in form_info:
            if chosen['choice']:
                selected_keys.append(chosen['key'])
                selected_names.append(chosen['name'])

        return selected_keys, selected_names

It returns chosen keys list from a given form.

Args:
form_info: serialized list of dict form data
Returns:
selected_keys(list): Chosen keys list
selected_names(list): Chosen channels' or subscribers' names.


def random_name(num_surnames=2):

    a = []

    if random.random() < _PROB_PREF:
        a.append(_prefixes[random.randint(0, len(_prefixes) - 1)])

    a.append(_forenames[random.randint(0, len(_forenames) - 1)])

    for i in range(num_surnames):
        a.append(_surnames[random.randint(0, len(_surnames) - 1)])

    if random.random() < _PROB_SUFF:
        a.append(_suffixes[random.randint(0, len(_suffixes) - 1)])

    return " ".join(a)

Returns a random person name

Arguments:
num_surnames -- number of surnames


def ring_position(self):
    if (self.type != EventType.TABLET_PAD_RING):
        raise AttributeError(_wrong_prop.format(self.type))
    return self._libinput.libinput_event_tablet_pad_get_ring_position(self._handle)

The current position of the ring, in degrees
counterclockwise from the northern-most point of the ring in
the tablet's current logical orientation.

If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a terminating event with a ring value of -1 when
the finger is lifted from the ring. A caller may use this information
to e.g. determine if kinetic scrolling should be triggered.

For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.

Returns:
float: The current value of the the axis. -1 if the finger was
lifted.
Raises:
AttributeError


def agent_heartbeat(self, agent_id, metrics, run_states):
    mutation = gql('\n        mutation Heartbeat(\n            $id: ID!,\n            $metrics: JSONString,\n            $runState: JSONString\n        ) {\n            agentHeartbeat(input: {\n                id: $id,\n                metrics: $metrics,\n                runState: $runState\n            }) {\n                agent {\n                    id\n                }\n                commands\n            }\n        }\n        ')
    try:
        response = self.gql(mutation, variable_values={'id': agent_id, 'metrics': json.dumps(metrics), 'runState': json.dumps(run_states)})
    except Exception as e:
        message = ast.literal_eval(e.args[0])['message']
        logger.error('Error communicating with W&B: %s', message)
        return []
    else:
        return json.loads(response['agentHeartbeat']['commands'])

Notify server about agent state, receive commands.

Args:
agent_id (str): agent_id
metrics (dict): system metrics
run_states (dict): run_id: state mapping
Returns:
List of commands to execute.


def flip(x, axis=None):
    if any_symbolic_tensors((x,)):
        return Flip(axis=axis).symbolic_call(x)
    return backend.numpy.flip(x, axis=axis)

Reverse the order of elements in the tensor along the given axis.

The shape of the tensor is preserved, but the elements are reordered.

Args:
x: Input tensor.
axis: Axis or axes along which to flip the tensor. The default,
`axis=None`, will flip over all of the axes of the input tensor.

Returns:
Output tensor with entries of `axis` reversed.


def get_parent(self, tree, alt=None):
    parent = self.parent_db.get(tree.path)
    if (not parent):
        return alt
    return list(parent)[0]

Get parent for given `tree` or `alt` if not found.

Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.

Returns:
obj: :class:`.Tree` parent to given `tree`.


def _render_fluent_timestep(self, fluent_type: str, fluents: Sequence[Tuple[(str, np.array)]], fluent_variables: Sequence[Tuple[(str, List[str])]]) -> None:
    for (fluent_pair, variable_list) in zip(fluents, fluent_variables):
        (name, fluent) = fluent_pair
        (_, variables) = variable_list
        print(name)
        fluent = fluent.flatten()
        for (variable, value) in zip(variables, fluent):
            print('- {}: {} = {}'.format(fluent_type, variable, value))
    print()

Prints `fluents` of given `fluent_type` as list of instantiated variables
with corresponding values.

Args:
fluent_type (str): Fluent type.
fluents (Sequence[Tuple[str, np.array]]): List of pairs (fluent_name, fluent_values).
fluent_variables (Sequence[Tuple[str, List[str]]]): List of pairs (fluent_name, args).


def handler(self, direction, verb, priority=10):

    def parent_fn(func):

        @functools.wraps(func)
        def child_fn(msg):
            func(msg)
        self.register_event(direction, verb, child_fn, priority=priority)
        return child_fn
    return parent_fn

Register this function as an event handler.

Args:
direction (str): ``in``, ``out``, ``both``, ``raw``.
verb (str): Event name.
priority (int): Handler priority (lower priority executes first).

Example:
These handlers print out a pretty raw log::

reactor = girc.Reactor()

@reactor.handler('in', 'raw', priority=1)
def handle_raw_in(event):
print(event['server'].name, ' ->', escape(event['data']))

@reactor.handler('out', 'raw', priority=1)
def handle_raw_out(event):
print(event['server'].name, '<- ', escape(event['data']))


def from_file(cls, path):
    with open(path, 'r', errors='replace') as f:
        return cls(f.read())

Create a text from a file.

Args:
path (str): The file path.


def start(self, host, nornir):

        self.host = host
        self.nornir = nornir

        try:
            logger.debug("Host %r: running task %r", self.host.name, self.name)
            r = self.task(self, **self.params)
            if not isinstance(r, Result):
                r = Result(host=host, result=r)

        except NornirSubTaskError as e:
            tb = traceback.format_exc()
            logger.error(
                "Host %r: task %r failed with traceback:\n%s",
                self.host.name,
                self.name,
                tb,
            )
            r = Result(host, exception=e, result=str(e), failed=True)

        except Exception as e:
            tb = traceback.format_exc()
            logger.error(
                "Host %r: task %r failed with traceback:\n%s",
                self.host.name,
                self.name,
                tb,
            )
            r = Result(host, exception=e, result=tb, failed=True)

        r.name = self.name
        r.severity_level = logging.ERROR if r.failed else self.severity_level

        self.results.insert(0, r)
        return self.results

Run the task for the given host.

Arguments:
host (:obj:`nornir.core.inventory.Host`): Host we are operating with. Populated right
before calling the ``task``
nornir(:obj:`nornir.core.Nornir`): Populated right before calling
the ``task``

Returns:
host (:obj:`nornir.core.task.MultiResult`): Results of the task and its subtasks


def query(starttime, endtime, output=None, *filenames):
    if (not output):
        output = ((((filenames[0].replace('.pcap', '') + starttime.isoformat()) + '-') + endtime.isoformat()) + '.pcap')
    else:
        output = output
    with open(output, 'w') as outfile:
        for filename in filenames:
            log.info(('pcap.query: processing %s...' % filename))
            with open(filename, 'r') as stream:
                for (header, packet) in stream:
                    if (packet is not None):
                        if ((header.timestamp >= starttime) and (header.timestamp <= endtime)):
                            outfile.write(packet, header=header)

Given a time range and input file, query creates a new file with only
that subset of data. If no outfile name is given, the new file name is the
old file name with the time range appended.

Args:
starttime:
The datetime of the beginning time range to be extracted from the files.
endtime:
The datetime of the end of the time range to be extracted from the files.
output:
Optional: The output file name. Defaults to
[first filename in filenames][starttime]-[endtime].pcap
filenames:
A tuple of one or more file names to extract data from.


def check_interactive_docker_worker(link):
    errors = []
    log.info('Checking for {} {} interactive docker-worker'.format(link.name, link.task_id))
    try:
        if link.task['payload']['features'].get('interactive'):
            errors.append('{} is interactive: task.payload.features.interactive!'.format(link.name))
        if link.task['payload']['env'].get('TASKCLUSTER_INTERACTIVE'):
            errors.append('{} is interactive: task.payload.env.TASKCLUSTER_INTERACTIVE!'.format(link.name))
    except KeyError:
        errors.append('check_interactive_docker_worker: {} task definition is malformed!'.format(link.name))
    return errors

Given a task, make sure the task was not defined as interactive.

* ``task.payload.features.interactive`` must be absent or False.
* ``task.payload.env.TASKCLUSTER_INTERACTIVE`` must be absent or False.

Args:
link (LinkOfTrust): the task link we're checking.

Returns:
list: the list of error errors.  Success is an empty list.


def _expand_json(self, j):

        decompressed_json = copy.copy(j)
        decompressed_json.pop('blob', None)

        compressed_data = base64.b64decode(j['blob'])
        original_json = zlib.decompress(compressed_data).decode('utf-8')

        decompressed_json['users'] = json.loads(original_json)

        return decompressed_json

Decompress the BLOB portion of the usernotes.

Arguments:
j: the JSON returned from the wiki page (dict)

Returns a Dict with the 'blob' key removed and a 'users' key added


def _assert_same_graph(original_item, item) -> None:
    original_graph = getattr(original_item, 'graph', None)
    graph = getattr(item, 'graph', None)
    if original_graph and graph and (original_graph is not graph):
        raise ValueError('%s must be from the same graph as %s (graphs are %s and %s).' % (item, original_item, graph, original_graph))

Fail if the 2 items are from different graphs.

Args:
original_item: Original item to check against.
item: Item to check.

Raises:
ValueError: if graphs do not match.


def list_vmss(access_token, subscription_id, resource_group):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Compute/virtualMachineScaleSets',
                        '?api-version=', COMP_API])
    return do_get_next(endpoint, access_token)

List VM Scale Sets in a resource group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.

Returns:
HTTP response. JSON body of a list of scale set model views.


def get_user(self, identified_with, identifier, req, resp, resource, uri_kwargs):
    stored_value = self.kv_store.get(self._get_storage_key(identified_with, identifier))
    if (stored_value is not None):
        user = self.serialization.loads(stored_value.decode())
    else:
        user = None
    return user

Get user object for given identifier.

Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user identifier (string or tuple
in case of all built in authentication middleware classes).

Returns:
dict: user object stored in Redis if it exists, otherwise ``None``


def export_as_file(self, file_path, cv_source):
    if os.path.exists(file_path):
        raise exceptions.UserError('{} already exists'.format(file_path))
    with open(file_path, 'wb') as f:
        f.write(self.export_as_code(cv_source).encode('utf8'))

Export the ensemble as a single Python file and saves it to `file_path`.

This is EXPERIMENTAL as putting different modules together would probably wreak havoc
especially on modules that make heavy use of global variables.

Args:
file_path (str, unicode): Absolute/local path of place to save file in

cv_source (str, unicode): String containing actual code for base learner
cross-validation used to generate secondary meta-features.


def add_topic(self, topic):
    if (topic in self._topics):
        return Future().success(set(self._topics))
    self._topics.add(topic)
    return self.cluster.request_update()

Add a topic to the list of topics tracked via metadata.

Arguments:
topic (str): topic to track

Returns:
Future: resolves after metadata request/response


def forward(self, hidden_states: torch.Tensor, prev_group_token: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=False) -> Tuple[torch.FloatTensor]:
    if self.with_group_token:
        group_token = self.group_token.expand(hidden_states.size(0), -1, -1)
        if self.group_projector is not None:
            group_token = group_token + self.group_projector(prev_group_token)
    else:
        group_token = None
    x = hidden_states
    cat_x = self.concat_x(x, group_token)
    for layer in self.layers:
        layer_out = layer(cat_x, attention_mask=None, causal_attention_mask=None)
        cat_x = layer_out[0]
    x, group_token = self.split_x(cat_x)
    attention = None
    if self.downsample is not None:
        x, attention = self.downsample(x, group_token)
    outputs = (x, group_token)
    if output_attentions:
        outputs = outputs + (attention,)
    return outputs

Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
`(config.encoder_attention_heads,)`.
output_attentions (`bool`, *optional*):
Whether or not to return the grouping tensors of Grouping block.


def get_tensor_layout(self, path):
    raise NotImplementedError()

Retrieve the `TensorLayout` for the intermediate tensor.

Args:
path: a string path for the corresponding tensor.

return:
The `TensorLayout` for the intermediate tensor, which can be used
by `backend.relayout()` to reshard the tensor. Could also return
None.


def __getitem__(self, id):

        if not isinstance(id, int):
            raise TypeError(id)
        return self._map[id]

Return the worksheet with the given id.

Args:
id: numeric id of the worksheet
Returns:
WorkSheet: contained worksheet object
Raises:
TypeError: if ``id`` is not an ``int``
KeyError: if the spreadsheet has no worksheet with the given ``id``


def set_distribution(value):
    global_state.set_global_attribute(GLOBAL_ATTRIBUTE_NAME, value)

Set the distribution as the global distribution setting.

Args:
value: a `Distribution` instance.


def _ExtractExtensionInstallEvents(self, settings_dict, parser_mediator):
    for (extension_id, extension) in sorted(settings_dict.items()):
        install_time = extension.get('install_time', None)
        if (not install_time):
            parser_mediator.ProduceExtractionWarning('installation time missing for extension ID {0:s}'.format(extension_id))
            continue
        try:
            install_time = int(install_time, 10)
        except ValueError:
            parser_mediator.ProduceExtractionWarning('unable to convert installation time for extension ID {0:s}'.format(extension_id))
            continue
        manifest = extension.get('manifest', None)
        if (not manifest):
            parser_mediator.ProduceExtractionWarning('manifest missing for extension ID {0:s}'.format(extension_id))
            continue
        event_data = ChromeExtensionInstallationEventData()
        event_data.extension_id = extension_id
        event_data.extension_name = manifest.get('name', None)
        event_data.path = extension.get('path', None)
        date_time = dfdatetime_webkit_time.WebKitTime(timestamp=install_time)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_ADDED)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Extract extension installation events.

Args:
settings_dict (dict[str: object]): settings data from a Preferences file.
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.


def node_name(self):
    return self._node_name

Name of the node from which the tensor value was dumped.

Returns:
(`str`) name of the node watched by the debug op.


def modify_site(name, sourcepath=None, apppool=None, preload=None):
    site_path = 'IIS:\\Sites\\{0}'.format(name)
    current_sites = list_sites()
    if (name not in current_sites):
        log.debug("Site '%s' not defined.", name)
        return False
    ps_cmd = list()
    if sourcepath:
        ps_cmd.extend(['Set-ItemProperty', '-Path', "'{0}'".format(site_path), '-Name', 'PhysicalPath', '-Value', "'{0}'".format(sourcepath)])
    if apppool:
        if (apppool in list_apppools()):
            log.debug('Utilizing pre-existing application pool: %s', apppool)
        else:
            log.debug('Application pool will be created: %s', apppool)
            create_apppool(apppool)
        if ps_cmd:
            ps_cmd.append(';')
        ps_cmd.extend(['Set-ItemProperty', '-Path', "'{0}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{0}'".format(apppool)])
    if preload:
        ps_cmd.extend(['Set-ItemProperty', '-Path', "'{0}'".format(site_path), '-Name', 'applicationDefaults.preloadEnabled', '-Value', '{0};'.format(preload)])
    cmd_ret = _srvmgr(ps_cmd)
    if (cmd_ret['retcode'] != 0):
        msg = 'Unable to modify site: {0}\nError: {1}'.format(name, cmd_ret['stderr'])
        raise CommandExecutionError(msg)
    log.debug('Site modified successfully: %s', name)
    return True

Modify a basic website in IIS.

.. versionadded:: 2017.7.0

Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
preload (bool): Whether preloading should be enabled

Returns:
bool: True if successful, otherwise False.

.. note::

If an application pool is specified, and that application pool does not
already exist, it will be created.

CLI Example:

.. code-block:: bash

salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool' preload=True


def aggregate_global_cache(self, global_tt_summary_cache):
    agg_fn_map = self._parameters.get_signature_to_agg_fn_map()
    signature_idx_map = self._signature_types()
    aggregation_result = []
    for signature, idx in sorted(signature_idx_map.items(), key=operator.itemgetter(1)):
        if signature not in agg_fn_map:
            raise RuntimeError('No aggregation function is defined for signature %s.' % signature)
        signature_tensor = global_tt_summary_cache[:, :, idx]
        agg_fn = agg_fn_map[signature]
        agg_tensor = agg_fn(signature_tensor, axis=0)
        aggregation_result.append(agg_tensor)
    merged_signatures = array_ops_stack.stack(aggregation_result)
    transposed_signatures = array_ops.transpose(merged_signatures)
    return array_ops.expand_dims(transposed_signatures, axis=0)

Merges the given caches on tpu.

Args:
global_tt_summary_cache: The global tensor tracer summary cache tensor
with shape (num_cores, num_traced_tensors, num_traced_signatures). First
dimension corresponds to core_id, where global_tpu_cache_tensor[i]
correspond to the local cache from core-i.
Returns:
An aggregated tf.Tensor.
Raises:
RuntimeError: if there is no aggregate function defined for a signature.


def _log_every_n_to_logger(n, logger, level, message, *args):
    logger = (logger or logging.getLogger())

    def _gen():
        while True:
            for _ in range(n):
                (yield False)
            logger.log(level, message, *args)
            (yield True)
    gen = _gen()
    return (lambda : six.next(gen))

Logs the given message every n calls to a logger.

Args:
n: Number of calls before logging.
logger: The logger to which to log.
level: The logging level (e.g. logging.INFO).
message: A message to log
*args: Any format args for the message.
Returns:
A method that logs and returns True every n calls.


def _qInstallMessageHandler(handler):

    def messageOutputHandler(*args):
        if (len(args) == 3):
            (msgType, logContext, msg) = args
        elif (len(args) == 2):
            (msgType, msg) = args
            logContext = None
        else:
            raise TypeError('handler expected 2 or 3 arguments, got {0}'.format(len(args)))
        if isinstance(msg, bytes):
            msg = msg.decode()
        handler(msgType, logContext, msg)
    passObject = (messageOutputHandler if handler else handler)
    if (Qt.IsPySide or Qt.IsPyQt4):
        return Qt._QtCore.qInstallMsgHandler(passObject)
    elif (Qt.IsPySide2 or Qt.IsPyQt5):
        return Qt._QtCore.qInstallMessageHandler(passObject)

Install a message handler that works in all bindings

Args:
handler: A function that takes 3 arguments, or None


def log_get(recipe_id=[], timezone='America/Los_Angeles', days=1):
    body = {'resourceNames': ['projects/%s' % UI_PROJECT], 'filter': '       logName="projects/%s/logs/StarThinker"        AND labels.version="%s"        AND labels.layer="JOB"     ' % (UI_PROJECT, LOG_VERSION), 'orderBy': 'timestamp desc', 'pageSize': 1000}
    if recipe_id:
        if isinstance(recipe_id, str):
            recipe_id = [recipe_id]
        body['filter'] += ' AND ( %s )' % ' OR '.join(('operation.id="%s"' % r for r in recipe_id))
    for entry in API_StackDriver(Configuration(service=UI_SERVICE, project=UI_PROJECT), 'service', iterate=True).entries().list(body=body).execute():
        yield entry

Returns last actionable job run for a specific recipe or all recipes.

Pulls status entries from StackDriver in reverse order.  A single recipe may
be run multiple times for multiple tasks at different hours, do not
assume a JOB_END means a recipe is complete.  Only way to ensure a recipe is
complete
is to compare all tasks run against all tasks in recipe ( not done by log
code).

Args: - recipe_id ( string or list ) - Optional, if provided returns a single
record for a single job. - timezone ( string ) - The local timezone to cast
all record times into.

Returns:
- ( iterator ) - Each log entry.


def __init__(self, parser, *, pytype_single_args=None, overrides=None):
    self._parser = parser
    self._overrides = overrides or []
    self.pytype_single_args = pytype_single_args or {}

Initialize a parser.

Args:
parser: An argparse.ArgumentParser or compatible object
pytype_single_args: Args passed to pytype
overrides: Pytype args that the tool overrides (will be put into the tool
args, with the corresponding pytype opts getting their default values)


def optimizer(name):

  warn_msg = ("Please update `registry.optimizer` callsite "
              "(likely due to a `HParams.optimizer` value)")
  if name == "SGD":
    name = "sgd"
    tf.logging.warning("'SGD' optimizer now keyed by 'sgd'. %s" % warn_msg)
  elif name == "RMSProp":
    name = "rms_prop"
    tf.logging.warning(
        "'RMSProp' optimizer now keyed by 'rms_prop'. %s" % warn_msg)
  else:
    snake_name = misc_utils.camelcase_to_snakecase(name)
    if name != snake_name:
      tf.logging.warning(
          "optimizer names now keyed by snake_case names. %s" % warn_msg)
      name = snake_name
  return Registries.optimizers[name]

Get pre-registered optimizer keyed by name.

`name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and
UpperCamelCase -> snake_case conversions included for legacy support.

Args:
name: name of optimizer used in registration. This should be a snake case
identifier, though others supported for legacy reasons.

Returns:
optimizer


def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn):

    counts = collections.defaultdict(int)
    now = rdfvalue.RDFDatetime.Now()
    for info in self.IterateAllClientsFullInfo(batch_size=db.MAX_COUNT):
      if not info.metadata.ping:
        continue
      statistic_value = extract_statistic_fn(info)
      for client_label in info.GetLabelsNames(owner="GRR"):
        for day_bucket in day_buckets:
          time_boundary = now - rdfvalue.Duration.FromDays(day_bucket)
          if info.metadata.ping > time_boundary:

            counts[(statistic_value, client_label, day_bucket)] += 1
    return dict(counts)

Returns client-activity metrics for a particular statistic.

Args:
day_buckets: A set of n-day-active buckets.
extract_statistic_fn: A function that extracts the statistic's value from
a ClientFullInfo object.


def is_subgroup(self, supergroup):
    warnings.warn('This is not fully functional. Only trivial subsets are tested right now. ')
    return set(self.symmetry_ops).issubset(supergroup.symmetry_ops)

True if this group is a subgroup of the supplied group.

Args:
supergroup (SymmetryGroup): Supergroup to test.

Returns:
True if this group is a subgroup of the supplied group.


def FromTimestampToLdap(self, ts):
    if self.conf.get('ad'):
        t = time.strftime('%Y%m%d%H%M%S.0Z', time.gmtime(ts))
    else:
        t = time.strftime('%Y%m%d%H%M%SZ', time.gmtime(ts))
    return t

Transforms nss_cache internal timestamp into a LDAP timestamp.

Args:
ts: number of seconds since epoch

Returns:
LDAP format timestamp string.


def insert(self, index, value):
    if (value in self):
        raise ValueError
    index = self._fix_neg_index(index)
    self._dict[value] = index
    for elem in self._list[index:]:
        self._dict[elem] += 1
    self._list.insert(index, value)

Insert value at index.

Args:
index (int): Index to insert value at
value: Value to insert
Raises:
ValueError: If value already in self
IndexError: If start or end are out of range


def check_coordinates(chromosome, pos, coordinates):

    chrom_match = CHR_PATTERN.match(chromosome)
    chrom = chrom_match.group(2)

    if chrom != coordinates['chrom']:
        return False

    if (pos >= coordinates['start'] and pos <= coordinates['end']):
        return True

    return False

Check if the variant is in the interval given by the coordinates

Args:
chromosome(str): Variant chromosome
pos(int): Variant position
coordinates(dict): Dictionary with the region of interest


def get_ip_address(domain):

    if ":
        domain = "http:

    hostname = urlparse(domain).netloc

    if not hostname:
        raise ValueError("Can't parse hostname!")

    return socket.gethostbyname(hostname)

Get IP address for given `domain`. Try to do smart parsing.

Args:
domain (str): Domain or URL.

Returns:
str: IP address.

Raises:
ValueError: If can't parse the domain.


def update(self, forecasts, observations):

        if len(observations.shape) == 1:
            obs_cdfs = np.zeros((observations.size, self.thresholds.size))
            for o, observation in enumerate(observations):
                obs_cdfs[o, self.thresholds >= observation] = 1
        else:
            obs_cdfs = observations
        self.errors["F_2"] += np.sum(forecasts ** 2, axis=0)
        self.errors["F_O"] += np.sum(forecasts * obs_cdfs, axis=0)
        self.errors["O_2"] += np.sum(obs_cdfs ** 2, axis=0)
        self.errors["O"] += np.sum(obs_cdfs, axis=0)
        self.num_forecasts += forecasts.shape[0]

Update the statistics with forecasts and observations.

Args:
forecasts: The discrete Cumulative Distribution Functions of
observations:


def get(self, personId):
    check_type(personId, basestring, may_be_none=False)
    json_data = self._session.get(((API_ENDPOINT + '/') + personId))
    return self._object_factory(OBJECT_TYPE, json_data)

Get a person's details, by ID.

Args:
personId(basestring): The ID of the person to be retrieved.

Returns:
Person: A Person object with the details of the requested person.

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


def reformat_python_docstrings(top_dirs: List[str], correct_copyright_lines: List[str], show_only: bool=True, rewrite: bool=False, process_only_filenum: int=None) -> None:
    filenum = 0
    for top_dir in top_dirs:
        for (dirpath, dirnames, filenames) in walk(top_dir):
            for filename in filenames:
                fullname = join(dirpath, filename)
                extension = splitext(filename)[1]
                if (extension != PYTHON_EXTENSION):
                    continue
                filenum += 1
                if (process_only_filenum and (filenum != process_only_filenum)):
                    continue
                log.info('Processing file {}: {}', filenum, fullname)
                proc = PythonProcessor(full_path=fullname, top_dir=top_dir, correct_copyright_lines=correct_copyright_lines)
                if show_only:
                    proc.show()
                elif rewrite:
                    proc.rewrite_file()

Walk a directory, finding Python files and rewriting them.

Args:
top_dirs: list of directories to descend into
correct_copyright_lines:
list of lines (without newlines) representing the copyright
docstring block, including the transition lines of equals
symbols
show_only: show results (to stdout) only; don't rewrite
rewrite: write the changes
process_only_filenum: only process this file number (1-based index);
for debugging only


def chained(self, text=None, fore=None, back=None, style=None):

        self.data = ''.join((
            self.data,
            self.color(text=text, fore=fore, back=back, style=style),
        ))
        return self

Called by the various 'color' methods to colorize a single string.
The RESET_ALL code is appended to the string unless text is empty.
Raises ValueError on invalid color names.

Arguments:
text  : String to colorize, or None for  BG/Style change.
fore  : Name of fore color to use.
back  : Name of back color to use.
style : Name of style to use.


def get_nltk_builder(languages):

    all_stemmers = []
    all_stopwords_filters = []
    all_word_characters = set()

    for language in languages:
        if language == "en":

            all_stemmers.append(lunr.stemmer.stemmer)
            all_stopwords_filters.append(stop_word_filter)
            all_word_characters.update({r"\w"})
        else:
            stopwords, word_characters = _get_stopwords_and_word_characters(language)
            all_stemmers.append(
                Pipeline.registered_functions["stemmer-{}".format(language)]
            )
            all_stopwords_filters.append(
                generate_stop_word_filter(stopwords, language=language)
            )
            all_word_characters.update(word_characters)

    builder = Builder()
    multi_trimmer = generate_trimmer("".join(sorted(all_word_characters)))
    Pipeline.register_function(
        multi_trimmer, "lunr-multi-trimmer-{}".format("-".join(languages))
    )
    builder.pipeline.reset()

    for fn in chain([multi_trimmer], all_stopwords_filters, all_stemmers):
        builder.pipeline.add(fn)
    for fn in all_stemmers:
        builder.search_pipeline.add(fn)

    return builder

Returns a builder with stemmers for all languages added to it.

Args:
languages (list): A list of supported languages.


def getModPath(self, *paths):

        dirn = self.getModDir()
        return s_common.genpath(dirn, *paths)

Construct a path relative to this module's working directory.

Args:
*paths: A list of path strings

Notes:
This creates the module specific directory if it does not exist.

Returns:
(str): The full path (or None if no cortex dir is configured).


def _randomize_direction(base_heading, sigma) -> int:
    val = MissionWeather._gauss(base_heading, sigma)
    val = MissionWeather._normalize_direction(val)
    return val

Creates a variation in direction

Args:
base_heading: base direction
sigma: sigma value for gaussian variation

Returns: random direction


def get_slot(self, *args, **kwargs):
    return self._opt.get_slot(*args, **kwargs)

Return a slot named "name" created for "var" by the Optimizer.

This simply wraps the get_slot() from the actual optimizer.

Args:
*args: Arguments for get_slot().
**kwargs: Keyword arguments for get_slot().

Returns:
The `Variable` for the slot if it was created, `None` otherwise.


def verify(self, obj):

        if obj != self._literal:
            raise ValidationError("Object is not equal to literal",
                                  reason='%s is not equal to %s' % (str(obj), str(self._literal)), object=obj)

        return obj

Verify that the object conforms to this verifier's schema

Args:
obj (object): A python object to verify

Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason key set indicating
the reason for the lack of validation.


def model_from_json(json_string, custom_objects=None):
    from keras.src.saving import serialization_lib
    model_config = json.loads(json_string)
    return serialization_lib.deserialize_keras_object(model_config, custom_objects=custom_objects)

Parses a JSON model configuration string and returns a model instance.

Example:

>>> model = keras.Sequential([
...     keras.layers.Dense(5, input_shape=(3,)),
...     keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model = keras.models.model_from_json(config)

Args:
json_string: JSON string encoding a model configuration.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.

Returns:
A Keras model instance (uncompiled).


def dump_orm_object_as_insert_sql(engine: Engine, obj: object, fileobj: TextIO) -> None:
    insp = inspect(obj)
    meta = MetaData(bind=engine)
    table_name = insp.mapper.mapped_table.name
    table = Table(table_name, meta, autoload=True)
    query = select(table.columns)
    for orm_pkcol in insp.mapper.primary_key:
        core_pkcol = table.columns.get(orm_pkcol.name)
        pkval = getattr(obj, orm_pkcol.name)
        query = query.where((core_pkcol == pkval))
    cursor = engine.execute(query)
    row = cursor.fetchone()
    row_dict = dict(row)
    statement = table.insert(values=row_dict)
    insert_str = get_literal_query(statement, bind=engine)
    writeline_nl(fileobj, insert_str)

Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it
to the output file-like object.

Args:
engine: SQLAlchemy :class:`Engine`
obj: SQLAlchemy ORM object to write
fileobj: file-like object to write to


def from_voigt(cls, voigt_input):
    voigt_input = np.array(voigt_input)
    rank = (sum(voigt_input.shape)
    t = cls(np.zeros(([3] * rank)))
    if (voigt_input.shape != t._vscale.shape):
        raise ValueError('Invalid shape for voigt matrix')
    voigt_input = (voigt_input / t._vscale)
    this_voigt_map = t.get_voigt_dict(rank)
    for ind in this_voigt_map:
        t[ind] = voigt_input[this_voigt_map[ind]]
    return cls(t)

Constructor based on the voigt notation vector or matrix.

Args:
voigt_input (array-like): voigt input for a given tensor


def _client_send(self, msg):

        try:
            self._client.write(msg.encode("utf8") + b'\n')
            self._client.flush()
            self.log.debug('Snippet sent %s.', msg)
        except socket.error as e:
            raise Error(
                self._ad,
                'Encountered socket error "%s" sending RPC message "%s"' %
                (e, msg))

Sends an Rpc message through the connection.

Args:
msg: string, the message to send.

Raises:
Error: a socket error occurred during the send.


def FindCoinsByVins(self, vins):
    ret = []
    for coin in self.GetCoins():
        coinref = coin.Reference
        for vin in vins:
            if ((coinref.PrevIndex == vin.PrevIndex) and (coinref.PrevHash == vin.PrevHash)):
                ret.append(coin)
    return ret

Looks through the current collection of coins in a wallet
and chooses coins that match the specified CoinReference objects.

Args:
vins: A list of ``neo.Core.CoinReference`` objects.

Returns:
list: A list of ``neo.Wallet.Coin`` objects.


def is_match(self, subject: Union[(Expression, FlatTerm)]) -> bool:
    try:
        next(self.match(subject))
    except StopIteration:
        return False
    return True

Check if the given subject matches any pattern in the net.

Args:
subject:
The subject that is matched. Must be constant.

Returns:
True, if any pattern matches the subject.


def get_cosine_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float=0.5, last_epoch: int=-1):
    lr_lambda = partial(_get_cosine_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles)
    return LambdaLR(optimizer, lr_lambda, last_epoch)

Create a schedule with a learning rate that decreases following the values of the cosine function between the
initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the
initial lr set in the optimizer.

Args:
optimizer ([`~torch.optim.Optimizer`]):
The optimizer for which to schedule the learning rate.
num_warmup_steps (`int`):
The number of steps for the warmup phase.
num_training_steps (`int`):
The total number of training steps.
num_cycles (`float`, *optional*, defaults to 0.5):
The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
following a half-cosine).
last_epoch (`int`, *optional*, defaults to -1):
The index of the last epoch when resuming training.

Return:
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.


def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None,
                           old_style=False, for_msgpack=False, should_redact=False):

    serializer = StoneToPythonPrimitiveSerializer(
        caller_permissions, alias_validators, for_msgpack, old_style, should_redact)
    return serializer.encode(data_type, obj)

Encodes an object into a JSON-compatible dict based on its type.

Args:
data_type (Validator): Validator for obj.
obj (object): Object to be serialized.
caller_permissions (list): The list of raw-string caller permissions
with which to serialize.

Returns:
An object that when passed to json.dumps() will produce a string
giving the JSON-encoded object.

See json_encode() for additional information about validation.


def Run(self, request, global_params=None):
    config = self.GetMethodConfig('Run')
    return self._RunMethod(config, request, global_params=global_params)

Runs a `BuildTrigger` at a particular source revision.

Args:
request: (CloudbuildProjectsLocationsTriggersRunRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.


def call(self, batch_size: Optional[int], input_points: Optional[Tuple[tf.Tensor, tf.Tensor]], input_labels: tf.Tensor | None, input_boxes: tf.Tensor | None, input_masks: tf.Tensor | None) -> Tuple[tf.Tensor, tf.Tensor]:
    sparse_embeddings = None
    if input_points is not None:
        batch_size, point_batch_size = shape_list(input_points)[:2]
        if input_labels is None:
            raise ValueError('If points are provided, labels must also be provided.')
        point_embeddings = self._embed_points(input_points, input_labels, pad=input_boxes is None)
        sparse_embeddings = tf.zeros((batch_size, point_batch_size, 0, self.hidden_size), dtype=point_embeddings.dtype)
        sparse_embeddings = tf.concat([sparse_embeddings, point_embeddings], axis=2)
    if input_boxes is not None:
        batch_size = shape_list(input_boxes)[0]
        box_embeddings = self._embed_boxes(input_boxes)
        if sparse_embeddings is None:
            sparse_embeddings = box_embeddings
        else:
            sparse_embeddings = tf.concat([sparse_embeddings, box_embeddings], axis=2)
    if input_masks is not None:
        dense_embeddings = self.mask_embed(input_masks)
    else:
        dense_embeddings = self.no_mask_embed[0]
        dense_embeddings = tf.reshape(dense_embeddings, (1, -1, 1, 1))
        dense_embeddings = tf.tile(dense_embeddings, (batch_size, 1, self.image_embedding_size[0], self.image_embedding_size[1]))
    if sparse_embeddings is None:
        sparse_embeddings = tf.zeros((batch_size, 0, 1, self.hidden_size), dtype=dense_embeddings.dtype)
    return (sparse_embeddings, dense_embeddings)

Embeds different types of prompts, returning both sparse and dense embeddings.

Args:
points (`tf.Tensor`, *optional*):
point coordinates and labels to embed.
boxes (`tf.Tensor`, *optional*):
boxes to embed
masks (`tf.Tensor`, *optional*):
masks to embed


def get(self, container_id):
    resp = self.client.api.inspect_container(container_id)
    return self.prepare_model(resp)

Get a container by name or ID.

Args:
container_id (str): Container name or ID.

Returns:
A :py:class:`Container` object.

Raises:
:py:class:`docker.errors.NotFound`
If the container does not exist.
:py:class:`docker.errors.APIError`
If the server returns an error.


def padFrameRange(frange, zfill):

        def _do_pad(match):

            result = list(match.groups())
            result[1] = pad(result[1], zfill)
            if result[4]:
                result[4] = pad(result[4], zfill)
            return ''.join((i for i in result if i))
        return PAD_RE.sub(_do_pad, frange)

Return the zero-padded version of the frame range string.

Args:
frange (str): a frame range to test
zfill (int):

Returns:
str:


def _FormatForCommand(token):
    if not isinstance(token, str):
        token = str(token)
    if token.startswith('_'):
        return token
    return token.replace('_', '-')

Replaces underscores with hyphens, unless the token starts with a token.

This is because we typically prefer hyphens to underscores at the command
line, but we reserve hyphens at the start of a token for flags. This becomes
relevant when --verbose is activated, so that things like __str__ don't get
transformed into --str--, which would get confused for a flag.

Args:
token: The token to transform.
Returns:
The transformed token.


def request(self, send_terminator = False):

        try:
            retA = self.requestA()
            retB = self.requestB()
            if retA and retB:
                self.makeAB()
                self.calculateFields()
                self.updateObservers()
                return True
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        return False

Combined A and B read for V4 meter.

Args:
send_terminator (bool): Send termination string at end of read.

Returns:
bool: True on completion.


def file_modify(filename, settings):
    for (k, v) in settings.items():
        if (k == 'mode'):
            os.chmod(filename, v)
        if (k == 'owners'):
            os.chown(filename, v)

Modifies file access

Args:
filename (str): Filename.
settings (dict): Can be "mode" or "owners"


def Mint(self, wallet, mint_to_addr, attachment_args, invoke_attrs=None):
    invoke_args = [self.ScriptHash.ToString(), 'mintTokens', []]
    invoke_args = (invoke_args + attachment_args)
    (tx, fee, results, num_ops, engine_success) = TestInvokeContract(wallet, invoke_args, None, True, from_addr=mint_to_addr, invoke_attrs=invoke_attrs)
    return (tx, fee, results)

Call the "mintTokens" function of the smart contract.

Args:
wallet (neo.Wallets.Wallet): a wallet instance.
mint_to_addr (str): public address of the account to mint the tokens to.
attachment_args: (list): a list of arguments used to attach neo and/or gas to an invoke, eg ['--attach-gas=10.0','--attach-neo=3']
invoke_attrs: (list): a list of TransactionAttributes to be attached to the mint transaction
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results.


def raster_dilation(rasterfile):
    if is_string(rasterfile):
        origin_raster = RasterUtilClass.read_raster(str(rasterfile))
    elif isinstance(rasterfile, Raster):
        origin_raster = rasterfile.data
    elif isinstance(rasterfile, numpy.ndarray):
        origin_raster = rasterfile
    else:
        return 'Your rasterfile has a wrong type. Type must be string or numpy.array or class Raster in pygeoc.'
    min_value_raster = origin_raster.min()
    dilation_raster = numpy.zeros((origin_raster.shape[0], origin_raster.shape[1]))
    add_row = numpy.full((1, origin_raster.shape[1]), min_value_raster)
    temp_origin_raster = numpy.vstack((numpy.vstack((add_row, origin_raster)), add_row))
    add_col = numpy.full(((origin_raster.shape[0] + 2), 1), min_value_raster)
    expand_origin_raster = numpy.hstack((numpy.hstack((add_col, temp_origin_raster)), add_col))
    for i in range(origin_raster.shape[0]):
        for j in range(origin_raster.shape[1]):
            max_pixel_value = min_value_raster
            for k in range(3):
                for l in range(3):
                    if (expand_origin_raster[((i + k), (j + l))] >= max_pixel_value):
                        max_pixel_value = expand_origin_raster[((i + k), (j + l))]
                dilation_raster[(i, j)] = max_pixel_value
    return dilation_raster

Dilate the raster image.

Find the max pixel's value in 8-neighborhood. Then change the compute
pixel's value into the max pixel's value.

Args:
rasterfile: input original raster image, type can be filename(string,
like "test1.tif"), rasterfile(class Raster) or numpy.ndarray.

Returns:
dilation_raster: raster image after dilation, type is numpy.ndarray.


def dom_processing(self, value):

        if value == self._defaults['domProcessing'] and 'domProcessing' in self._values:
            del self._values['domProcessing']
        else:
            self._values['domProcessing'] = value

The dom_processing property.

Args:
value (string). the property value.


def __init__(self, app):

        self.app = app
        self.user_manager = app.user_manager

        self.password_crypt_context = CryptContext(
            schemes=self.user_manager.USER_PASSLIB_CRYPTCONTEXT_SCHEMES,
            **self.user_manager.USER_PASSLIB_CRYPTCONTEXT_KEYWORDS)

Create a passlib CryptContext.

Args:
password_hash(str): The name of a valid passlib password hash.
Examples: ``'bcrypt', 'pbkdf2_sha512', 'sha512_crypt' or 'argon2'``.

Example:
``password_manager = PasswordManager('bcrypt')``


def picture_view(request, user_id, year=None):
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        raise Http404
    default_image_path = os.path.join(settings.PROJECT_ROOT, 'static/img/default_profile_pic.png')
    if (user is None):
        raise Http404
    else:
        if (year is None):
            preferred = user.preferred_photo
            if (preferred is None):
                data = user.default_photo
                if (data is None):
                    image_buffer = io.open(default_image_path, mode='rb')
                else:
                    image_buffer = io.BytesIO(data)
            else:
                data = preferred.binary
                if data:
                    image_buffer = io.BytesIO(data)
                else:
                    image_buffer = io.open(default_image_path, mode='rb')
        else:
            grade_number = Grade.number_from_name(year)
            if user.photos.filter(grade_number=grade_number).exists():
                data = user.photos.filter(grade_number=grade_number).first().binary
            else:
                data = None
            if data:
                image_buffer = io.BytesIO(data)
            else:
                image_buffer = io.open(default_image_path, mode='rb')
        response = HttpResponse(content_type='image/jpeg')
        response['Content-Disposition'] = 'filename={}_{}.jpg'.format(user_id, (year or preferred))
        try:
            img = image_buffer.read()
        except UnicodeDecodeError:
            img = io.open(default_image_path, mode='rb').read()
        image_buffer.close()
        response.write(img)
        return response

Displays a view of a user's picture.

Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture.


def call_later(self, delay, callback):

        if hasattr(self._connection.ioloop, "call_later"):
            self._connection.ioloop.call_later(delay, callback)
        else:
            self._connection.ioloop.add_timeout(delay, callback)

Schedule a one-shot timeout given delay seconds.

This method is only useful for compatibility with older versions of pika.

Args:
delay (float): Non-negative number of seconds from now until
expiration
callback (method): The callback method, having the signature
`callback()`


def collect(val, collections, default_collections):
    if collections is None:
        collections = default_collections
    for key in collections:
        ops.add_to_collection(key, val)

Adds keys to a collection.

Args:
val: The value to add per each key.
collections: A collection of keys to add.
default_collections: Used if collections is None.


def __init__(self, user_assist_guid):

    key_path = self._KEY_PATH_FORMAT.format(user_assist_guid)
    super(UserAssistWindowsRegistryKeyPathFilter, self).__init__(key_path)

Initializes Windows Registry key filter.

Args:
user_assist_guid (str): UserAssist GUID.


def _GetTableNames(self, database):
    table_names = []
    for esedb_table in database.tables:
        table_names.append(esedb_table.name)
    return table_names

Retrieves the table names in a database.

Args:
database (pyesedb.file): ESE database.

Returns:
list[str]: table names.


def filter_lines(lines, filter_regex, groups=None):

    pattern = re.compile(filter_regex)
    for line in lines:
        match = pattern.search(line)
        if match:
            if groups is None:
                yield line
            elif len(groups) == 1:
                yield match.group(groups[0])
            else:
                matched_groups = match.groupdict()
                yield tuple(matched_groups.get(group) for group in groups)

Filters out the lines not matching the pattern.

Args:
lines: list[string]: lines to filter.
pattern: string: regular expression to filter out lines.

Returns: list[string]: the list of filtered lines.


def main(params=None):

    parser = getParser()

    if params != None:
        args = parser.parse_args(params)
    else:
        args = parser.parse_args()

    print(general.title(banner.text))

    sayingHello =  + general.LICENSE_URL + "\n"
    print(general.info(sayingHello))

    urlDict = {}
    if args.url !=None:
        urlDict[str(args.url)] = None
    elif args.platforms != None:
        for p in args.platforms:
            with open(args.config, "r") as iF:
                lines = iF.read().splitlines()
                for l in lines:
                    platform = l.split('\t')[0]
                    url = l.split('\t')[1]
                    notFound = l.split('\t')[2]
                    if p == platform:
                        urlDict[url] = notFound

    if not os.path.exists(args.output_folder):
        os.makedirs(args.output_folder)

    enumerateURL(urlDict, args.output_folder, startIndex = args.start_index, maxErrors = args.max_errors)

Main loop for the enumeration

Args:
-----
params: A list with the parameters as grabbed by the terminal. It is
None when this is called by an entry_point.


def _generate_key_map(entity_list, key, entity_class):

    key_map = {}
    for obj in entity_list:
      key_map[obj[key]] = entity_class(**obj)

    return key_map

Helper method to generate map from key to entity object for given list of dicts.

Args:
entity_list: List consisting of dict.
key: Key in each dict which will be key in the map.
entity_class: Class representing the entity.

Returns:
Map mapping key to entity object.


def type(self, value):

        if value == self._defaults['type'] and 'type' in self._values:
            del self._values['type']
        else:
            self._values['type'] = value

The type property.

Args:
value (string). the property value.


def register(self, name):

    def decorator(func):
        'Inner decorator, not used directly.\n\n            Args:\n                func: obj. Parameterless function to register.\n\n            Returns:\n                func: decorated function.\n            '
        self.logic[name] = func

        @wraps(func)
        def wrapper():
            'Wrapper, not used directly.'
            raise RuntimeError('working outside of request context')
        return wrapper
    return decorator

Decorator for registering a named function in the sesion logic.

Args:
name: str. Function name.
func: obj. Parameterless function to register.

The following named functions must be registered:
'LaunchRequest' - logic for launch request.
'SessionEndedRequest': logic for session ended request.

In addition, all intents must be registered by their names specified
in the intent schema.

The aliased decorators: @launch, @intent(name), and @session_ended exist
as a convenience for registering specific functions.


def stop_standing_subprocess(proc):
    import psutil
    pid = proc.pid
    logging.debug('Stopping standing subprocess %d', pid)
    process = psutil.Process(pid)
    failed = []
    try:
        children = process.children(recursive=True)
    except AttributeError:
        children = process.get_children(recursive=True)
    for child in children:
        try:
            child.kill()
            child.wait(timeout=10)
        except psutil.NoSuchProcess:
            pass
        except:
            failed.append(child.pid)
            logging.exception('Failed to kill standing subprocess %d', child.pid)
    try:
        process.kill()
        process.wait(timeout=10)
    except psutil.NoSuchProcess:
        pass
    except:
        failed.append(pid)
        logging.exception('Failed to kill standing subprocess %d', pid)
    if failed:
        raise Error(('Failed to kill standing subprocesses: %s' % failed))
    if proc.stdout:
        proc.stdout.close()
    if proc.stderr:
        proc.stderr.close()
    proc.wait()
    logging.debug('Stopped standing subprocess %d', pid)

Stops a subprocess started by start_standing_subprocess.

Before killing the process, we check if the process is running, if it has
terminated, Error is raised.

Catches and ignores the PermissionError which only happens on Macs.

Args:
proc: Subprocess to terminate.

Raises:
Error: if the subprocess could not be stopped.


def order_verification(self, institute, case, user, link, variant):

        LOG.info("Creating event for ordering validation for variant" \
                    " {0}".format(variant['display_name']))

        updated_variant = self.variant_collection.find_one_and_update(
            {'_id': variant['_id']},
            {'$set': {'sanger_ordered': True}},
            return_document=pymongo.ReturnDocument.AFTER
        )

        self.create_event(
            institute=institute,
            case=case,
            user=user,
            link=link,
            category='variant',
            verb='sanger',
            variant=variant,
            subject=variant['display_name'],
        )

        LOG.info("Creating event for ordering sanger for case" \
                    " {0}".format(case['display_name']))

        self.create_event(
            institute=institute,
            case=case,
            user=user,
            link=link,
            category='case',
            verb='sanger',
            variant=variant,
            subject=variant['display_name'],
        )
        return updated_variant

Create an event for a variant verification for a variant
and an event for a variant verification for a case

Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
variant (dict): A variant object

Returns:
updated_variant(dict)


def scalar_spec(value_spec: pg.typing.ValueSpec) -> pg.typing.ValueSpec:
    return pg.typing.Union([value_spec, pg.typing.Callable([pg.typing.Int()], returns=value_spec)])

Returns the value spec for a schedule scalar.

Args:
value_spec: a value spec for the schedule-based scalar type.

Returns:
A value spec for either the value itself or a callable that produces such
value based on a step (integer).


def fermi_fourier_trans_inverse_4(qubits):
    (yield (fswap(qubits[1], qubits[2]),))
    (yield fermi_fourier_trans_2(qubits[0], qubits[1]))
    (yield fermi_fourier_trans_2(qubits[2], qubits[3]))
    (yield fswap(qubits[1], qubits[2]))
    (yield fermi_fourier_trans_2(qubits[0], qubits[1]))
    (yield cirq.S(qubits[2]))
    (yield fermi_fourier_trans_2(qubits[2], qubits[3]))
    (yield fswap(qubits[1], qubits[2]))

The reverse fermionic Fourier transformation implemented on 4 qubits
on a line, which maps the momentum picture to the position picture.
Using the fast Fourier transformation algorithm, the circuit can be
decomposed into 2-mode fermionic Fourier transformation, the fermionic
SWAP gates, and single-qubit rotations.

Args:
qubits: list of four qubits


def load_tiff_multipage(tiff_filename, dtype='float32'):

    if not os.path.isfile(tiff_filename):
        raise RuntimeError('could not find file "%s"' % tiff_filename)

    data = tiff.imread(tiff_filename)

    im = []

    while True:

        Xi = numpy.array(data, dtype=dtype)
        if Xi.ndim == 2:
            Xi = Xi[numpy.newaxis, ...]
        im.append(Xi)

        try:
            data.seek(data.tell()+1)
        except EOFError:
            break

    im = numpy.concatenate(im, axis=0)
    im = numpy.rollaxis(im, 1)
    im = numpy.rollaxis(im, 2)

    return im

Load a multipage tiff into a single variable in x,y,z format.

Arguments:
tiff_filename:     Filename of source data
dtype:             data type to use for the returned tensor

Returns:
Array containing contents from input tiff file in xyz order


def read(self, queue, name=None):
    if isinstance(queue, tensor_lib.Tensor):
        queue_ref = queue
    else:
        queue_ref = queue.queue_ref
    if self._reader_ref.dtype == dtypes.resource:
        return gen_io_ops.reader_read_v2(self._reader_ref, queue_ref, name=name)
    else:
        old_queue_op = gen_data_flow_ops.fake_queue(queue_ref)
        return gen_io_ops.reader_read(self._reader_ref, old_queue_op, name=name)

Returns the next record (key, value) pair produced by a reader.

Will dequeue a work unit from queue if necessary (e.g. when the
Reader needs to start reading from a new file since it has
finished with the previous file).

Args:
queue: A Queue or a mutable string Tensor representing a handle
to a Queue, with string work items.
name: A name for the operation (optional).

Returns:
A tuple of Tensors (key, value).
key: A string scalar Tensor.
value: A string scalar Tensor.


def upload_file(filename: str, config: Config, full_table_id: str, action: Action=Action.APPEND, service_account_email: Optional[str]=None) -> None:
    if service_account_email:
        auth_config = AuthConfig(service_account_email=service_account_email)
    else:
        auth_config = None
    table_metadata = build_table_metadata(full_table_id)
    credentials = get_credentials(auth_config)
    bq_legacy_client = get_bq_legacy_client(table_metadata.project_id, credentials)
    table_exists = get_table(bq_legacy_client, table_metadata) is not None
    if table_exists and action == Action.REPLACE:
        bq_legacy_client.delete_table(table_metadata.full_table_id)
        table_exists = False
    if not table_exists:
        schema = generate_bigquery_schema(config)
        create_table(bq_legacy_client, table_metadata, schema)
    row_count = get_csv_row_count(filename)
    columns = [column.bq_name for column in config]
    with open(filename, 'r') as f:
        csv = DictReader(f, fieldnames=columns)
        buffer_: List[Row] = []
        buffer_size = row_count
        buffer = Buffer[Row](buffer_, buffer_size, lambda rows: upload_rows(bq_legacy_client, table_metadata, rows))
        for row in csv:
            buffer.push(row)
        buffer.flush(force=True)

Upload a data file conforming to the given config to BigQuery.

Args:
* filename: Local path to csv file to be uploaded
* config: Config key from configs.CONFIGS dictionary
* full_table_id: BigQuery table id
* action: APPEND to table or REPLACE table
* service_account_email: Email address of service account


def register_tensor_conversion_function_internal(base_type, conversion_func, priority=100):
    base_types = base_type if isinstance(base_type, tuple) else (base_type,)
    if any((not isinstance(x, type) for x in base_types)):
        raise TypeError(f'Argument `base_type` must be a type or a tuple of types. Obtained: {base_type}')
    del base_types
    if not callable(conversion_func):
        raise TypeError(f'Argument `conversion_func` must be callable. Received {conversion_func}.')
    with _tensor_conversion_func_lock:
        _tensor_conversion_func_registry[priority].append((base_type, conversion_func))
        _tensor_conversion_func_cache.clear()

Internal version of register_tensor_conversion_function.

See docstring of `register_tensor_conversion_function` for details.

The internal version of the function allows registering conversions
for types in the _UNCONVERTIBLE_TYPES tuple.

Args:
base_type: The base type or tuple of base types for all objects that
`conversion_func` accepts.
conversion_func: A function that converts instances of `base_type` to
`Tensor`.
priority: Optional integer that indicates the priority for applying this
conversion function. Conversion functions with smaller priority values run
earlier than conversion functions with larger priority values. Defaults to
100.

Raises:
TypeError: If the arguments do not have the appropriate type.


def LockRetryWrapper(self,
                       subject,
                       retrywrap_timeout=1,
                       retrywrap_max_timeout=10,
                       blocking=True,
                       lease_time=None):

    timeout = 0
    while timeout < retrywrap_max_timeout:
      try:
        return self.DBSubjectLock(subject, lease_time=lease_time)
      except DBSubjectLockError:
        if not blocking:
          raise
        stats_collector_instance.Get().IncrementCounter("datastore_retries")
        time.sleep(retrywrap_timeout)
        timeout += retrywrap_timeout

    raise DBSubjectLockError("Retry number exceeded.")

Retry a DBSubjectLock until it succeeds.

Args:
subject: The subject which the lock applies to.
retrywrap_timeout: How long to wait before retrying the lock.
retrywrap_max_timeout: The maximum time to wait for a retry until we
raise.
blocking: If False, raise on first lock failure.
lease_time: lock lease time in seconds.

Returns:
The DBSubjectLock object

Raises:
DBSubjectLockError: If the maximum retry count has been reached.


def run_user_main(wrapped_test_module):
    tree = ast.parse(tf_inspect.getsource(wrapped_test_module))
    target = ast.dump(ast.parse('if __name__ == "__main__": pass').body[0].test)
    for expr in reversed(tree.body):
        if isinstance(expr, ast.If) and ast.dump(expr.test) == target:
            break
    else:
        raise NotImplementedError(f'Could not find `if __name__ == "main":` block in {wrapped_test_module.__name__}.')
    new_ast = ast.Module(body=expr.body, type_ignores=[])
    exec(compile(new_ast, '<ast>', 'exec'), globals(), wrapped_test_module.__dict__)

Runs the "if __name__ == '__main__'" at the bottom of a module.

TensorFlow practice is to have a main if at the bottom of the module which
might call an API compat function before calling test.main().

Since this is a statement, not a function, we can't cleanly reference it, but
we can inspect it from the user module and run it in the context of that
module so all imports and variables are available to it.

Args:
wrapped_test_module: The user-provided test code to run.

Raises:
NotImplementedError: If main block was not found in module. This should not
be caught, as it is likely an error on the user's part -- absltest is all
too happy to report a successful status (and zero tests executed) if a
user forgets to end a class with "test.main()".


def get_reference_points(spatial_shapes, valid_ratios, device):
    reference_points_list = []
    for level, (height, width) in enumerate(spatial_shapes):
        ref_y, ref_x = meshgrid(torch.linspace(0.5, height - 0.5, height, dtype=torch.float32, device=device), torch.linspace(0.5, width - 0.5, width, dtype=torch.float32, device=device), indexing='ij')
        ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, level, 1] * height)
        ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, level, 0] * width)
        ref = torch.stack((ref_x, ref_y), -1)
        reference_points_list.append(ref)
    reference_points = torch.cat(reference_points_list, 1)
    reference_points = reference_points[:, :, None] * valid_ratios[:, None]
    return reference_points

Get reference points for each feature map. Used in decoder.

Args:
spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
Spatial shapes of each feature map.
valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
Valid ratios of each feature map.
device (`torch.device`):
Device on which to create the tensors.
Returns:
`torch.FloatTensor` of shape `(batch_size, num_queries, num_feature_levels, 2)`


def get(self):
    if self.call_queue:
        return self.apply((lambda df: df)).data
    else:
        return self.data.copy()

Flushes the call_queue and returns the data.

Note: Since this object is a simple wrapper, just return the data.

Returns:
The object that was `put`.


def wulff_from_chempot(self, delu_dict=None, delu_default=0, symprec=1e-05, no_clean=False, no_doped=False):
    latt = SpacegroupAnalyzer(self.ucell_entry.structure).get_conventional_standard_structure().lattice
    miller_list = self.all_slab_entries.keys()
    e_surf_list = []
    for hkl in miller_list:
        gamma = self.get_stable_entry_at_u(hkl, delu_dict=delu_dict, delu_default=delu_default, no_clean=no_clean, no_doped=no_doped)[1]
        e_surf_list.append(gamma)
    return WulffShape(latt, miller_list, e_surf_list, symprec=symprec)

Method to get the Wulff shape at a specific chemical potential.

Args:
delu_dict (Dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
delu_default (float): Default value for all unset chemical potentials
symprec (float): See WulffShape.
no_doped (bool): Consider stability of clean slabs only.
no_clean (bool): Consider stability of doped slabs only.

Returns:
(WulffShape): The WulffShape at u_ref and u_ads.


def destroy_walker(self, walker):

        if walker.buffered:
            self._queue_walkers.remove(walker)
        else:
            self._virtual_walkers.remove(walker)

Destroy a previously created stream walker.

Args:
walker (StreamWalker): The walker to remove from internal updating
lists.


def get_service_credentials(pipeline_options):
    return _Credentials.get_service_credentials(pipeline_options)

For internal use only; no backwards-compatibility guarantees.

Get credentials to access Google services.
Args:
pipeline_options: Pipeline options, used in creating credentials
like impersonated credentials.

Returns:
A ``_ApitoolsCredentialsAdapter`` object or None if credentials
not found. Returned object is thread-safe.


def __init__(self, devpath):

        self._fd = None
        self._devpath = None
        self._open(devpath)

Instantiate an I2C object and open the i2c-dev device at the
specified path.

Args:
devpath (str): i2c-dev device path.

Returns:
I2C: I2C object.

Raises:
I2CError: if an I/O or OS error occurs.


def is_valid_package_name(name, raise_error=False):
    is_valid = PACKAGE_NAME_REGEX.match(name)
    if (raise_error and (not is_valid)):
        raise PackageRequestError(('Not a valid package name: %r' % name))
    return is_valid

Test the validity of a package name string.

Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure

Returns:
bool.


def process_event(event):

    if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
        print()

    print(event)

    if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
            event.args and not event.args['with_follow_on_turn']):
        print()
    if event.type == EventType.ON_DEVICE_ACTION:
        for command, params in event.actions:
            print('Do command', command, 'with params', str(params))

Pretty prints events.

Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.

Args:
event(event.Event): The current event to process.


def retrieve_template(self):
    links = self.retrieve_instance_links()
    self.log.debug('Links is \n%s', pformat(links))
    self.pipeline_config['instance_links'].update(links)
    jsondata = get_template(template_file='infrastructure/app_data.json.j2', appinfo=self.appinfo, pipeline_config=self.pipeline_config, formats=self.generated, run_as_user=DEFAULT_RUN_AS_USER)
    self.log.debug('jsondata is %s', pformat(jsondata))
    return jsondata

Sets the instance links with pipeline_configs and then renders template files

Returns:
jsondata: A json objects containing templates


def value_report(self, address, zipcode, report_type="full", format_type="json"):

        query_params = {
            "report_type": report_type,
            "format": format_type,
            "address": address,
            "zipcode": zipcode
        }

        return self._api_client.fetch_synchronous("property/value_report", query_params)

Call the value_report component

Value Report only supports a single address.

Args:
- address
- zipcode

Kwargs:
- report_type - "full" or "summary". Default is "full".
- format_type - "json", "pdf", "xlsx" or "all". Default is "json".


def get_enterprise_customer_or_404(enterprise_uuid):
    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')
    try:
        enterprise_uuid = UUID(enterprise_uuid)
        return EnterpriseCustomer.objects.get(uuid=enterprise_uuid)
    except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist):
        LOGGER.error('Unable to find enterprise customer for UUID: [%s]', enterprise_uuid)
        raise Http404

Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.

Arguments:
enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.

Returns:
(EnterpriseCustomer): The EnterpriseCustomer given the UUID.


def create(cls, application_namespace, application_data):
    namespace = ApplicationNamespace(application_namespace)
    data = ApplicationData(application_data)
    return ApplicationSpecificInformation(application_namespace=namespace, application_data=data)

Construct an ApplicationSpecificInformation object from provided data
and namespace values.

Args:
application_namespace (str): The name of the application namespace.
application_data (str): Application data related to the namespace.

Returns:
ApplicationSpecificInformation: The newly created set of
application information.

Example:
>>> x = ApplicationSpecificInformation.create('namespace', 'data')
>>> x.application_namespace.value
'namespace'
>>> x.application_data.value
'data'


def set_quickchart_resource(self, resource):
    if (isinstance(resource, int) and (not isinstance(resource, bool))):
        resource = self.get_resources()[resource]
    if (isinstance(resource, hdx.data.resource.Resource) or isinstance(resource, dict)):
        res = resource.get('id')
        if (res is None):
            resource = resource['name']
        else:
            resource = res
    elif (not isinstance(resource, str)):
        raise hdx.data.hdxobject.HDXError(('Resource id cannot be found in type %s!' % type(resource).__name__))
    if (is_valid_uuid(resource) is True):
        search = 'id'
    else:
        search = 'name'
    changed = False
    for dataset_resource in self.resources:
        if (dataset_resource[search] == resource):
            dataset_resource.enable_dataset_preview()
            self.preview_resource()
            changed = True
        else:
            dataset_resource.disable_dataset_preview()
    return changed

Set the resource that will be used for displaying QuickCharts in dataset preview

Args:
resource (Union[hdx.data.resource.Resource,Dict,str,int]): Either resource id or name, resource metadata from a Resource object or a dictionary or position

Returns:
bool: Returns True if resource for QuickCharts in dataset preview set or False if not


def post_process_object_detection(self, outputs, threshold: float=0.5, target_sizes: Union[TensorType, List[Tuple]]=None):
    out_logits, out_bbox = (outputs.logits, outputs.pred_boxes)
    if target_sizes is not None:
        if len(out_logits) != len(target_sizes):
            raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the logits')
    prob = nn.functional.softmax(out_logits, -1)
    scores, labels = prob[..., :-1].max(-1)
    boxes = center_to_corners_format(out_bbox)
    if target_sizes is not None:
        if isinstance(target_sizes, List):
            img_h = torch.Tensor([i[0] for i in target_sizes])
            img_w = torch.Tensor([i[1] for i in target_sizes])
        else:
            img_h, img_w = target_sizes.unbind(1)
        scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
        boxes = boxes * scale_fct[:, None, :]
    results = []
    for s, l, b in zip(scores, labels, boxes):
        score = s[s > threshold]
        label = l[s > threshold]
        box = b[s > threshold]
        results.append({'scores': score, 'labels': label, 'boxes': box})
    return results

Converts the raw output of [`DetrForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format. Only supports PyTorch.

Args:
outputs ([`DetrObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*):
Score threshold to keep object detection predictions.
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
`(height, width)` of each image in the batch. If unset, predictions will not be resized.
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model.


def setup(self, socket_type, complete_or_error_queue):

        try:
            if self._secured:
                if self._server_public_key is None or \
                        self._server_private_key is None:
                    raise LocalConfigurationError(
                        "Attempting to start socket in secure mode, "
                        "but complete server keys were not provided")

            self._event_loop = zmq.asyncio.ZMQEventLoop()
            asyncio.set_event_loop(self._event_loop)
            self._context = zmq.asyncio.Context()
            self._socket = self._context.socket(socket_type)

            self._socket.set(zmq.TCP_KEEPALIVE, 1)
            self._socket.set(zmq.TCP_KEEPALIVE_IDLE, self._connection_timeout)
            self._socket.set(zmq.TCP_KEEPALIVE_INTVL, self._heartbeat_interval)

            if socket_type == zmq.DEALER:
                self._socket.identity = "{}-{}".format(
                    self._zmq_identity,
                    hashlib.sha512(uuid.uuid4().hex.encode()
                                   ).hexdigest()[:23]).encode('ascii')

                if self._secured:

                    public_key, secretkey = zmq.curve_keypair()
                    self._socket.curve_publickey = public_key
                    self._socket.curve_secretkey = secretkey
                    self._socket.curve_serverkey = self._server_public_key

                self._socket.connect(self._address)
            elif socket_type == zmq.ROUTER:
                if self._secured:
                    auth = AsyncioAuthenticator(self._context)
                    self._auth = auth
                    auth.start()
                    auth.configure_curve(domain='*',
                                         location=zmq.auth.CURVE_ALLOW_ANY)

                    self._socket.curve_secretkey = self._server_private_key
                    self._socket.curve_publickey = self._server_public_key
                    self._socket.curve_server = True

                try:
                    self._socket.bind(self._address)
                except zmq.error.ZMQError as e:
                    raise LocalConfigurationError(
                        "Can't bind to {}: {}".format(self._address,
                                                      str(e)))
                else:
                    LOGGER.info("Listening on %s", self._address)

            self._dispatcher.add_send_message(self._connection,
                                              self.send_message)
            self._dispatcher.add_send_last_message(self._connection,
                                                   self.send_last_message)

            asyncio.ensure_future(self._remove_expired_futures(),
                                  loop=self._event_loop)

            asyncio.ensure_future(self._receive_message(),
                                  loop=self._event_loop)

            asyncio.ensure_future(self._dispatch_message(),
                                  loop=self._event_loop)

            self._dispatcher_queue = asyncio.Queue()

            if self._monitor:
                self._monitor_fd = "inproc:
                    _generate_id()[0:5])
                self._monitor_sock = self._socket.get_monitor_socket(
                    zmq.EVENT_DISCONNECTED,
                    addr=self._monitor_fd)
                asyncio.ensure_future(self._monitor_disconnects(),
                                      loop=self._event_loop)

        except Exception as e:

            complete_or_error_queue.put_nowait(e)
            self._close_sockets()
            raise

        if self._heartbeat:
            asyncio.ensure_future(self._do_heartbeat(), loop=self._event_loop)

        complete_or_error_queue.put_nowait(_STARTUP_COMPLETE_SENTINEL)

        asyncio.ensure_future(self._notify_started(), loop=self._event_loop)

        self._event_loop.run_forever()

        self._event_loop.close()
        self._close_sockets()

Setup the asyncio event loop.

Args:
socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER
complete_or_error_queue (queue.Queue): A way to propagate errors
back to the calling thread. Needed since this function is
directly used in Thread.

Returns:
None


def enc(self, byts, asscd=None):
    iv = os.urandom(16)
    encryptor = AESGCM(self.ekey)
    byts = encryptor.encrypt(iv, byts, asscd)
    envl = {'iv': iv, 'data': byts, 'asscd': asscd}
    return s_msgpack.en(envl)

Encrypt the given bytes and return an envelope dict in msgpack form.

Args:
byts (bytes): The message to be encrypted.
asscd (bytes): Extra data that needs to be authenticated (but not encrypted).

Returns:
bytes: The encrypted message. This is a msgpacked dictionary
containing the IV, ciphertext, and associated data.


def __init__(self, name: str, snap_type: str):

        self._type = snap_type
        self._channel = SnapshotChannel()
        Command.__init__(self, duration=0, name=name)
        Instruction.__init__(self, self, self._channel, name=name)

Create new snapshot command.

Args:
name (str): Snapshot name which is used to identify the snapshot in the output.
snap_type (str): Type of snapshot, e.g., “state” (take a snapshot of the quantum state).
The types of snapshots offered are defined in a separate specification
document for simulators.


def step(self, actions):

    if self._store_rollouts and \
        self._rollouts_by_epoch_and_split[self.current_epoch]:
      raise ValueError(
          "Data for current epoch has already been loaded from disk."
      )
    (obs, unclipped_rewards, dones) = self._step(actions)
    obs = self._preprocess_observations(obs)
    (min_reward, max_reward) = self.reward_range
    rewards = np.around(np.clip(unclipped_rewards, min_reward, max_reward))
    if self._store_rollouts:
      unclipped_rewards = unclipped_rewards.astype(np.float64)
      encoded_obs = self._encode_observations(obs)
      for (rollout, frame, action) in zip(
          self._current_batch_rollouts, self._current_batch_frames, actions
      ):
        rollout.append(frame._replace(action=action))

      self._current_batch_frames = [
          Frame(*orud, action=None)
          for orud in zip(encoded_obs, rewards, unclipped_rewards, dones)
      ]
    return (obs, rewards, dones)

Makes a step in all environments.

Does any preprocessing and records frames.

Args:
actions: Batch of actions.

Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.

Raises:
ValueError: when the data for current epoch has already been loaded.