def convert_variables_to_constants(sess, input_graph_def, output_node_names, variable_names_whitelist=None, variable_names_blacklist=None):
    ret = convert_variables_to_constants_from_session_graph(session=sess, graph_def=input_graph_def, output_node_names=output_node_names, variable_names_allowlist=variable_names_whitelist, variable_names_denylist=variable_names_blacklist)
    return ret

Replaces all the variables in a graph with constants of the same values.

If you have a trained graph containing Variable ops, it can be convenient to
convert them all to Const ops holding the same values. This makes it possible
to describe the network fully with a single GraphDef file, and allows the
removal of a lot of ops related to loading and saving the variables.

Args:
sess: Active TensorFlow session containing the variables.
input_graph_def: GraphDef object holding the network.
output_node_names: List of name strings for the result nodes of the graph.
variable_names_whitelist: The set of variable names to convert (by default,
all variables are converted).
variable_names_blacklist: The set of variable names to omit converting to
constants.

Returns:
GraphDef containing a simplified version of the original.

Raises:
RuntimeError: if a DT_RESOURCE op is found whose ancestor Variables are both
denylisted AND whitelisted for freezing.


def dfa(self, ttab: TransitionTable, init: int = 0) -> int:

        state = init
        while True:
            disp = ttab[state]
            ch = self.peek()
            state = disp.get(ch, disp[""])()
            if state < 0:
                return state
            self.offset += 1

Run a DFA and return the final (negative) state.

Args:
ttab: Transition table (with possible side-effects).
init: Initial state.

Raises:
EndOfInput: If past the end of `self.input`.


def waitForEvent(self, event_name, predicate, timeout=None):
    if timeout is None:
        timeout = self.default_timeout_sec
    deadline = time.perf_counter() + timeout
    while time.perf_counter() <= deadline:
        single_rpc_timeout = deadline - time.perf_counter()
        if single_rpc_timeout < 0:
            break
        single_rpc_timeout = min(single_rpc_timeout, self.rpc_max_timeout_sec)
        try:
            event = self.waitAndGet(event_name, single_rpc_timeout)
        except errors.CallbackHandlerTimeoutError:
            break
        if predicate(event):
            return event
    raise errors.CallbackHandlerTimeoutError(self._device, f'Timed out after {timeout}s waiting for an "{event_name}" event that satisfies the predicate "{predicate.__name__}".')

Waits for an event of the specific name that satisfies the predicate.

This call will block until the expected event has been received or time
out.

The predicate function defines the condition the event is expected to
satisfy. It takes an event and returns True if the condition is
satisfied, False otherwise.

Note all events of the same name that are received but don't satisfy
the predicate will be discarded and not be available for further
consumption.

Args:
event_name: str, the name of the event to wait for.
predicate: function, a function that takes an event (dictionary) and
returns a bool.
timeout: float, the number of seconds to wait before giving up. If None,
it will be set to self.default_timeout_sec.

Returns:
dictionary, the event that satisfies the predicate if received.

Raises:
errors.CallbackHandlerTimeoutError: raised if no event that satisfies the
predicate is received after timeout seconds.


def check(self, dsm, simplicity_factor=2, **kwargs):

        economy_of_mechanism = False
        message = ''
        data = dsm.data
        categories = dsm.categories
        dsm_size = dsm.size[0]

        if not categories:
            categories = ['appmodule'] * dsm_size

        dependency_number = 0

        for i in range(0, dsm_size):
            for j in range(0, dsm_size):
                if (categories[i] not in ('framework', 'corelib') and
                        categories[j] not in ('framework', 'corelib') and
                        data[i][j] > 0):
                    dependency_number += 1

        if dependency_number < dsm_size * simplicity_factor:
            economy_of_mechanism = True
        else:
            message = ' '.join([
                'Number of dependencies (%s)' % dependency_number,
                '> number of rows (%s)' % dsm_size,
                '* simplicity factor (%s) = %s' % (
                    simplicity_factor, dsm_size * simplicity_factor)])
        return economy_of_mechanism, message

Check economy of mechanism.

As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).

Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
simplicity_factor (int): simplicity factor.

Returns:
bool: True if economic, else False


def configure_profile(msg_type, profile_name, data, auth):
    with jsonconfig.Config('messages', indent=4) as cfg:
        write_data(msg_type, profile_name, data, cfg)
        write_auth(msg_type, profile_name, auth, cfg)
    print((('[+] Configuration entry for <' + profile_name) + '> created.'))
    print(('[+] Configuration file location: ' + cfg.filename))

Create the profile entry.

Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters


def post_process_segmentation(self, outputs: 'MaskFormerForInstanceSegmentationOutput', target_size: Optional[Tuple[int, int]]=None) -> 'torch.Tensor':
    warnings.warn('`post_process_segmentation` is deprecated and will be removed in v5 of Transformers, please use `post_process_instance_segmentation`', FutureWarning)
    class_queries_logits = outputs.class_queries_logits
    masks_queries_logits = outputs.masks_queries_logits
    if target_size is not None:
        masks_queries_logits = torch.nn.functional.interpolate(masks_queries_logits, size=target_size, mode='bilinear', align_corners=False)
    masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
    masks_probs = masks_queries_logits.sigmoid()
    segmentation = torch.einsum('bqc, bqhw -> bchw', masks_classes, masks_probs)
    return segmentation

Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into image segmentation predictions. Only
supports PyTorch.

Args:
outputs ([`MaskFormerForInstanceSegmentationOutput`]):
The outputs from [`MaskFormerForInstanceSegmentation`].

target_size (`Tuple[int, int]`, *optional*):
If set, the `masks_queries_logits` will be resized to `target_size`.

Returns:
`torch.Tensor`:
A tensor of shape (`batch_size, num_class_labels, height, width`).


def find_in_coord_list(coord_list, coord, atol=1e-08):
    if (len(coord_list) == 0):
        return []
    diff = (np.array(coord_list) - np.array(coord)[(None, :)])
    return np.where(np.all((np.abs(diff) < atol), axis=1))[0]

Find the indices of matches of a particular coord in a coord_list.

Args:
coord_list: List of coords to test
coord: Specific coordinates
atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and
array.

Returns:
Indices of matches, e.g., [0, 1, 2, 3]. Empty list if not found.


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

Corresponds to IDD Field `aerosol_optical_depth`

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

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


def GetSectionByIndex(self, section_index):
    if (not self._is_parsed):
        self._Parse()
        self._is_parsed = True
    if ((section_index < 0) or (section_index >= len(self._sections))):
        return None
    return self._sections[section_index]

Retrieves a specific section based on the index.

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

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


def every_other(x, name=None):

  with tf.name_scope(name, 'every_other', [x]) as scope:
    x = tf.convert_to_tensor(x, name='x')
    return tf.reshape(
        tf.slice(
            tf.reshape(x, [-1, 2]), [0, 0], [-1, 1]),
        [-1],
        name=scope)

Drops every other value from the tensor and returns a 1D tensor.

This is useful if you are running multiple inputs through a model tower
before splitting them and you want to line it up with some other data.

Args:
x: the target tensor.
name: the name for this op, defaults to every_other
Returns:
A tensorflow op.


def make_seeds(self, count=1):
    alg = self.algorithm
    if alg in (a.value for a in random_ops_util.Algorithm):
        keys = self._make_int64_keys(shape=[count])
        zeros = array_ops.zeros_like(keys)
        return array_ops_stack.stack([keys, zeros])
    else:
        raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg))

Generates seeds for stateless random ops.

For example:

```python
seeds = get_global_generator().make_seeds(count=10)
for i in range(10):
seed = seeds[:, i]
numbers = stateless_random_normal(shape=[2, 3], seed=seed)
...
```

Args:
count: the number of seed pairs (note that stateless random ops need a
pair of seeds to invoke).

Returns:
A tensor of shape [2, count] and dtype int64.


def parallel(processor_list: Sequence[PartProcessor]) -> PartProcessor:
    if not processor_list:
        raise ValueError('processor_list is empty')
    return _ParallelPartProcessor(processor_list)

Create a sequence of part processors to be run in parallel.

Args:
processor_list: list of part processors.

Returns:
A processor consisting of the parallel run of all the processors in the
list. The execution is sequential from the first processor to the last but
parts are processed concurrently overall.


def get_metrics_namespace(self) -> str:
    return 'RunInference'

Returns:
A namespace for metrics collected by the RunInference transform.


def product_category(request, category_id):
    PRODUCTS_FORM_PREFIX = 'products'
    VOUCHERS_FORM_PREFIX = 'vouchers'
    v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
    (voucher_form, voucher_handled) = v
    category_id = int(category_id)
    category = inventory.Category.objects.get(pk=category_id)
    with BatchController.batch(request.user):
        products = ProductController.available_products(request.user, category=category)
        if (not products):
            messages.warning(request, ('There are no products available from category: ' + category.name))
            return redirect('dashboard')
        p = _handle_products(request, category, products, PRODUCTS_FORM_PREFIX)
        (products_form, discounts, products_handled) = p
    if (request.POST and (not voucher_handled) and (not products_form.errors)):
        if products_form.has_changed():
            messages.success(request, 'Your reservations have been updated.')
        return redirect(review)
    data = {'category': category, 'discounts': discounts, 'form': products_form, 'voucher_form': voucher_form}
    return render(request, 'registrasion/product_category.html', data)

Form for selecting products from an individual product category.

Arguments:
category_id (castable to int): The id of the category to display.

Returns:
redirect or render:
If the form has been sucessfully submitted, redirect to
``dashboard``. Otherwise, render
``registrasion/product_category.html`` with data::

{
"category": category,         # An inventory.Category for
# category_id
"discounts": discounts,       # A list of
# DiscountAndQuantity
"form": products_form,        # A form for selecting
# products
"voucher_form": voucher_form, # A form for entering a
# voucher code
}


def generate_defect_structure(self, supercell=(1, 1, 1)):

        defect_structure = self.bulk_structure.copy()
        defect_structure.make_supercell(supercell)

        defect_properties = self.site.properties.copy()
        if ('velocities' in self.bulk_structure.site_properties) and \
            'velocities' not in defect_properties:
            if all( vel == self.bulk_structure.site_properties['velocities'][0]
                    for vel in self.bulk_structure.site_properties['velocities']):
                defect_properties['velocities'] = self.bulk_structure.site_properties['velocities'][0]
            else:
                raise ValueError("No velocity property specified for defect site and "
                                 "bulk_structure velocities are not homogeneous. Please specify this "
                                 "property within the initialized defect_site object.")

        site_properties_for_fake_struct = {prop: [val] for prop,val in defect_properties.items()}
        struct_for_defect_site = Structure( self.bulk_structure.copy().lattice,
                                             [self.site.specie],
                                             [self.site.frac_coords],
                                             to_unit_cell=True,
                                             site_properties = site_properties_for_fake_struct)
        struct_for_defect_site.make_supercell(supercell)
        defect_site = struct_for_defect_site[0]

        poss_deflist = sorted(
            defect_structure.get_sites_in_sphere(defect_site.coords, 2, include_index=True), key=lambda x: x[1])
        defindex = poss_deflist[0][2]

        subsite = defect_structure.pop(defindex)
        defect_structure.append(self.site.specie.symbol, subsite.coords, coords_are_cartesian=True,
                                properties = defect_site.properties)
        defect_structure.set_charge(self.charge)
        return defect_structure

Returns Defective Substitution structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix


def export(self, top=True):

        out = []
        if top:
            out.append(self._internal_name)
        out.append(self._to_str(self.holiday_name))
        out.append(self._to_str(self.holiday_day))
        return ",".join(out)

Exports object to its string representation.

Args:
top (bool):  if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be exported with `top`=False

Returns:
str: The objects string representation


def on_connection_state_change(self, event_type, callback):
    listeners = self._connection_state_listeners.get(event_type, [])
    listeners.append(callback)
    self._connection_state_listeners[event_type] = listeners

Register a callback for a specific connection state change.

Register a callback to be triggered when the connection changes to
the specified state, signified by a ConnectionEvent.

The callback must be a coroutine.

Args:
event_type (ConnectionEvent): the connection event to listen for
callback (coroutine): a coroutine to call on the event occurrence


def get_log(self):
    log_path = self.meta_data['logs_resource']
    conn = Qubole.agent()
    r = conn.get_raw(log_path)
    return r.text

Fetches log for the command represented by this object

Returns:
The log as a string


def reinforce_grid(self):

        for grid_district in self.mv_grid_districts():

            grid_district.mv_grid.reinforce_grid()

            for lv_load_area in grid_district.lv_load_areas():
                if not lv_load_area.is_aggregated:
                    for lv_grid_district in lv_load_area.lv_grid_districts():
                        lv_grid_district.lv_grid.reinforce_grid()

Performs grid reinforcement measures for all MV and LV grids
Args:

Returns:


def setup_data_stream(self, connection_factory: Callable[([tuple], Connection)], data_stream_factory: Callable[([Connection], DataStream)]=DataStream) -> DataStream:
    (yield from self._control_stream.write_command(Command('TYPE', 'I')))
    reply = (yield from self._control_stream.read_reply())
    self.raise_if_not_match('Binary mode', ReplyCodes.command_okay, reply)
    address = (yield from self.passive_mode())
    connection = (yield from connection_factory(address))
    connection.reset()
    (yield from connection.connect())
    data_stream = data_stream_factory(connection)
    return data_stream

Create and setup a data stream.

This function will set up passive and binary mode and handle
connecting to the data connection.

Args:
connection_factory: A coroutine callback that returns a connection
data_stream_factory: A callback that returns a data stream

Coroutine.

Returns:
DataStream


def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.LANCZOS, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
    if input_data_format is None:
        input_data_format = infer_channel_dimension_format(image, num_channels=(1, 3, 4))
    data_format = input_data_format if data_format is None else data_format
    if 'longest_edge' in size:
        size = get_resize_output_image_size(image, resolution_max_side=size['longest_edge'], input_data_format=input_data_format)
    elif 'height' in size and 'width' in size:
        size = (size['height'], size['width'])
    else:
        raise ValueError("size must be a dictionary with key 'longest_edge' or 'height' and 'width'.")
    image_mode = None
    if image.ndim == 2 or image.shape[-1] == 1:
        image_mode = 'P'
    image = to_pil_image(image, image_mode=image_mode, input_data_format=input_data_format)
    resized_image = image.resize((size[1], size[0]), resample=resample)
    resized_image = np.array(resized_image)
    resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image
    resized_image = to_channel_dimension_format(resized_image, data_format, input_channel_dim=ChannelDimension.LAST)
    return resized_image

Resize an image. The longest edge of the image is resized to size["longest_edge"], with the shortest edge
resized to keep the input aspect ratio. Can also be used with size["height"] and size["width"].
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Size of the output image.
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.LANCZOS`):
Resampling filter to use when resizing the image.
data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the output image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.


def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=(- 0.05), half_kpts_first_relax=False, auto_continue=False):
    incar_update = {'ISTART': 1}
    if ediffg:
        incar_update['EDIFFG'] = ediffg
    settings_overide_1 = None
    settings_overide_2 = [{'dict': 'INCAR', 'action': {'_set': incar_update}}, {'file': 'CONTCAR', 'action': {'_file_copy': {'dest': 'POSCAR'}}}]
    if (half_kpts_first_relax and os.path.exists('KPOINTS') and os.path.exists('POSCAR')):
        kpts = Kpoints.from_file('KPOINTS')
        orig_kpts_dict = kpts.as_dict()
        kpts.kpts = np.round(np.maximum((np.array(kpts.kpts) / 2), 1)).astype(int).tolist()
        low_kpts_dict = kpts.as_dict()
        settings_overide_1 = [{'dict': 'KPOINTS', 'action': {'_set': low_kpts_dict}}]
        settings_overide_2.append({'dict': 'KPOINTS', 'action': {'_set': orig_kpts_dict}})
    return [VaspJob(vasp_cmd, final=False, suffix='.relax1', auto_npar=auto_npar, auto_continue=auto_continue, settings_override=settings_overide_1), VaspJob(vasp_cmd, final=True, backup=False, suffix='.relax2', auto_npar=auto_npar, auto_continue=auto_continue, settings_override=settings_overide_2)]

Returns a list of two jobs corresponding to an AFLOW style double
relaxation run.

Args:
vasp_cmd (str): Command to run vasp as a list of args. For example,
if you are using mpirun, it can be something like
["mpirun", "pvasp.5.2.11"]
auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
number of cores) as recommended by VASP for DFT calculations.
Generally, this results in significant speedups. Defaults to
True. Set to False for HF, GW and RPA calculations.
ediffg (float): Force convergence criteria for subsequent runs (
ignored for the initial run.)
half_kpts_first_relax (bool): Whether to halve the kpoint grid
for the first relaxation. Speeds up difficult convergence
considerably. Defaults to False.

Returns:
List of two jobs corresponding to an AFLOW style run.


def get_sketch(self, sketch_id):

    resource_url = '{0:s}/sketches/{1:d}/'.format(self.api_base_url, sketch_id)
    response = self.session.get(resource_url)
    response_dict = response.json()
    try:
      response_dict['objects']
    except KeyError:
      raise ValueError('Sketch does not exist or you have no access')
    return response_dict

Get information on the specified sketch.

Args:
sketch_id (int): ID of sketch

Returns:
dict: Dictionary of sketch information

Raises:
ValueError: Sketch is inaccessible


def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected, use_gpu):
    total_size_1 = 1
    total_size_2 = 1
    for s in tensor_in_sizes:
        total_size_1 *= s
    for s in filter_in_sizes:
        total_size_2 *= s
    x1 = [f * 1.0 for f in range(1, total_size_1 + 1)]
    x2 = [f * 1.0 for f in range(1, total_size_2 + 1)]
    with self.cached_session(use_gpu=use_gpu) as sess:
        t1 = constant_op.constant(x1, shape=tensor_in_sizes)
        t1.set_shape(tensor_in_sizes)
        t2 = constant_op.constant(x2, shape=filter_in_sizes)
        conv = nn_ops.depthwise_conv2d_native(t1, t2, strides=[1, stride, stride, 1], padding=padding)
        value = self.evaluate(conv)
    tf_logging.info('value = %r', value)
    self.assertArrayNear(expected, np.ravel(value), 1e-05)
    self.assertShapeEqual(value, conv)

Verifies the output values of the depthwise convolution function.

Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols,
input_depth, depth_multiplier].
stride: Stride.
padding: Padding type.
expected: An array containing the expected operation outputs.
use_gpu: Whether to use GPU.


class TrainState(train_state.TrainState):
    logits_fn: Callable = struct.field(pytree_node=False)
    loss_fn: Callable = struct.field(pytree_node=False)

Train state with an Optax optimizer.

The two functions below differ depending on whether the task is classification
or regression.

Args:
logits_fn: Applied to last layer to obtain the logits.
loss_fn: Function to compute the loss.


def filter_genes_and_strains(self, remove_genes_not_in_reference_model=True, remove_strains_with_no_orthology=True, remove_strains_with_no_differences=False, custom_keep_strains=None, custom_keep_genes=None):
    if (len(self.df_orthology_matrix) == 0):
        raise RuntimeError('Empty orthology matrix, please calculate first!')
    reference_strain_gene_ids = [x.id for x in self.reference_gempro.genes]
    initial_num_genes = len(reference_strain_gene_ids)
    initial_num_strains = len(self.strain_ids)
    to_remove_genes = []
    if custom_keep_genes:
        to_remove_genes.extend([x for x in reference_strain_gene_ids if (x not in custom_keep_genes)])
    if remove_genes_not_in_reference_model:
        to_remove_genes.extend([x for x in reference_strain_gene_ids if (x not in self.df_orthology_matrix.index.tolist())])
    to_remove_genes = list(set(to_remove_genes))
    if self.reference_gempro.model:
        cobra.manipulation.delete_model_genes(self.reference_gempro.model, to_remove_genes)
    else:
        for g_id in to_remove_genes:
            self.reference_gempro.genes.get_by_id(g_id).functional = False
    new_gene_subset = [x.id for x in self.reference_gempro.functional_genes]
    tmp_new_orthology_matrix = self.df_orthology_matrix[self.df_orthology_matrix.index.isin(new_gene_subset)]
    if (custom_keep_strains or remove_strains_with_no_orthology or remove_strains_with_no_differences):
        for strain_id in self.strain_ids:
            if custom_keep_strains:
                if (strain_id not in custom_keep_strains):
                    self.strain_ids.remove(strain_id)
                    continue
            if remove_strains_with_no_orthology:
                if (strain_id not in tmp_new_orthology_matrix.columns):
                    self.strain_ids.remove(strain_id)
                    log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
                    continue
                elif tmp_new_orthology_matrix[strain_id].isnull().all():
                    self.strain_ids.remove(strain_id)
                    log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
                    continue
            if remove_strains_with_no_differences:
                not_in_strain = tmp_new_orthology_matrix[pd.isnull(tmp_new_orthology_matrix[strain_id])][strain_id].index.tolist()
                if (len(not_in_strain) == 0):
                    self.strain_ids.remove(strain_id)
                    log.info('{}: strain has no differences from the base, removed from analysis.')
                    continue
    log.info('{} genes to be analyzed, originally {}'.format(len(self.reference_gempro.functional_genes), initial_num_genes))
    log.info('{} strains to be analyzed, originally {}'.format(len(self.strain_ids), initial_num_strains))

Filters the analysis by keeping a subset of strains or genes based on certain criteria.

Args:
remove_genes_not_in_reference_model (bool): Remove genes from reference model not in orthology matrix
remove_strains_with_no_orthology (bool): Remove strains which have no orthologous genes found
remove_strains_with_no_differences (bool): Remove strains which have all the same genes as the base model.
Default is False because since orthology is found using a PID cutoff, all genes may be present but
differences may be on the sequence level.
custom_keep_genes (list): List of gene IDs to keep in analysis
custom_keep_strains (list): List of strain IDs to keep in analysis


def replace_batch_norm(model):
    for name, module in model.named_children():
        if isinstance(module, nn.BatchNorm2d):
            new_module = DabDetrFrozenBatchNorm2d(module.num_features)
            if not module.weight.device == torch.device('meta'):
                new_module.weight.data.copy_(module.weight)
                new_module.bias.data.copy_(module.bias)
                new_module.running_mean.data.copy_(module.running_mean)
                new_module.running_var.data.copy_(module.running_var)
            model._modules[name] = new_module
        if len(list(module.children())) > 0:
            replace_batch_norm(module)

Recursively replace all `torch.nn.BatchNorm2d` with `DabDetrFrozenBatchNorm2d`.

Args:
model (torch.nn.Module):
input model


def get_event(self, event_name, event_history=None):
    if (event_history is None):
        event_history = (event_name + '_history')
    return self._db.rpoplpush(event_name, event_history)

Get an event from the database.

Gets an event from the named event list removing the event and
adding it to the event history.

Args:
event_name (str): Event list key.
event_history (str, optional): Event history list.

Returns:
str: string representation of the event object


def download_models(self, uniprot_acc, outdir='', force_rerun=False):
    downloaded = []
    subset = self.get_models(uniprot_acc)
    for entry in subset:
        ident = '{}_{}_{}_{}'.format(uniprot_acc, entry['template'], entry['from'], entry['to'])
        outfile = op.join(outdir, (ident + '.pdb'))
        if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
            response = requests.get(entry['url'])
            if (response.status_code == 404):
                log.error('{}: 404 returned, no model available.'.format(ident))
            else:
                with open(outfile, 'w') as f:
                    f.write(response.text)
                log.debug('{}: downloaded homology model'.format(ident))
                downloaded.append(outfile)
        else:
            downloaded.append(outfile)
    return downloaded

Download all models available for a UniProt accession number.

Args:
uniprot_acc (str): UniProt ACC/ID
outdir (str): Path to output directory, uses working directory if not set
force_rerun (bool): Force a redownload the models if they already exist

Returns:
list: Paths to the downloaded models


def set_interface(self, vrf_name, interface, default=False, disable=False):
    cmds = [('interface %s' % interface)]
    cmds.append(self.command_builder('vrf forwarding', value=vrf_name, default=default, disable=disable))
    return self.configure(cmds)

Adds a VRF to an interface

Notes:
Requires interface to be in routed mode. Must apply ip address
after VRF has been applied. This feature can also be accessed
through the interfaces api.

Args:
vrf_name (str): The VRF name to configure
interface (str): The interface to add the VRF too
default (bool): Set interface VRF forwarding to default
disable (bool): Negate interface VRF forwarding

Returns:
True if the operation was successful otherwise False


def get_sid_string(principal):
    if (principal is None):
        principal = 'NULL SID'
    try:
        return win32security.ConvertSidToStringSid(principal)
    except TypeError:
        principal = get_sid(principal)
    try:
        return win32security.ConvertSidToStringSid(principal)
    except pywintypes.error:
        log.exception('Invalid principal %s', principal)
        raise CommandExecutionError('Invalid principal {0}'.format(principal))

Converts a PySID object to a string SID.

Args:

principal(str):
The principal to lookup the sid. Must be a PySID object.

Returns:
str: A string sid

Usage:

.. code-block:: python

# Get a PySID object
py_sid = salt.utils.win_dacl.get_sid('jsnuffy')

# Get the string version of the SID
salt.utils.win_dacl.get_sid_string(py_sid)


def create_s3_event(app_name, env, region, bucket, triggers):

    session = boto3.Session(profile_name=env, region_name=region)
    s3_client = session.client('s3')

    lambda_alias_arn = get_lambda_alias_arn(app_name, env, region)

    LOG.debug("Lambda ARN for lambda function %s is %s.", app_name, lambda_alias_arn)
    LOG.debug("Creating S3 events for bucket %s", bucket)

    principal = 's3.amazonaws.com'
    statement_id = "{}_s3_{}".format(app_name, bucket).replace('.', '')
    source_arn = "arn:aws:s3:::{}".format(bucket)
    add_lambda_permissions(
        function=lambda_alias_arn,
        env=env,
        region=region,
        principal=principal,
        statement_id=statement_id,
        source_arn=source_arn)

    template_kwargs = {"lambda_arn": lambda_alias_arn, "triggers": triggers}
    config = get_template(template_file='infrastructure/lambda/s3_event.json.j2', **template_kwargs)
    s3_client.put_bucket_notification_configuration(Bucket=bucket, NotificationConfiguration=json.loads(config))

    LOG.info("Created lambda %s S3 event on bucket %s", app_name, bucket)

Create S3 lambda events from triggers

Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
triggers (list): List of triggers from the settings


def dump_tree(self, statement=None, indent_level=0):
    out = u''
    indent = (u' ' * indent_level)
    if (statement is None):
        for root_statement in self.statements:
            out += self.dump_tree(root_statement, indent_level)
    else:
        out += ((indent + str(statement)) + u'\n')
        if (len(statement.children) > 0):
            for child in statement.children:
                out += self.dump_tree(child, indent_level=(indent_level + 4))
    return out

Dump the AST for this parsed file.

Args:
statement (SensorGraphStatement): the statement to print
if this function is called recursively.
indent_level (int): The number of spaces to indent this
statement.  Used for recursively printing blocks of
statements.
Returns:
str: The AST for this parsed sg file as a nested
tree with one node per line and blocks indented.


def slice(self, start, end):

        reverse = False
        if start > end:
            temp = start
            start = end
            end = temp
            reverse = True

        seg = self.copy()
        seg.points = seg.points[start:end+1]
        if reverse:
            seg.points = list(reversed(seg.points))

        return seg

Creates a copy of the current segment between indexes. If end > start,
points are reverted

Args:
start (int): Start index
end (int): End index
Returns:
:obj:`Segment`


def create_bagit_stream(dir_name, payload_info_list):
    zip_file = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)
    _add_path(dir_name, payload_info_list)
    (payload_byte_count, payload_file_count) = _add_payload_files(zip_file, payload_info_list)
    tag_info_list = _add_tag_files(zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count)
    _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list)
    _add_tag_manifest_file(zip_file, dir_name, tag_info_list)
    return zip_file

Create a stream containing a BagIt zip archive.

Args:
dir_name : str
The name of the root directory in the zip file, under which all the files
are placed (avoids "zip bombs").

payload_info_list: list
List of payload_info_dict, each dict describing a file.

- keys: pid, filename, iter, checksum, checksum_algorithm
- If the filename is None, the pid is used for the filename.


def get_images_by_catid_and_aoi(self, catid, aoi_wkt):

        self.logger.debug('Retrieving IDAHO metadata')

        url = '%s/search' % self.base_url

        body = {"filters": ["catalogID = '%s'" % catid],
                "types": ["IDAHOImage"],
                "searchAreaWkt": aoi_wkt}

        r = self.gbdx_connection.post(url, data=json.dumps(body))

        r.raise_for_status()
        if r.status_code == 200:
            results = r.json()
            numresults = len(results['results'])
            self.logger.debug('%s IDAHO images found associated with catid %s'
                              % (numresults, catid))

            return results

Retrieves the IDAHO image records associated with a given catid.
Args:
catid (str): The source catalog ID from the platform catalog.
aoi_wkt (str): The well known text of the area of interest.
Returns:
results (json): The full catalog-search response for IDAHO images
within the catID.


def needle_statistics_alignio(infile):

    alignments = list(AlignIO.parse(infile, "emboss"))

    if len(alignments) > 1:
        raise ValueError('Alignment file contains more than one pairwise alignment')

    alignment = alignments[0]

    with open(infile) as f:
        line = f.readline()

        for i in range(len(alignments)):
            while line.rstrip() != "
                line = f.readline()
                if not line:
                    raise StopIteration

            while line[0] == "

                parts = line[1:].split(":", 1)
                key = parts[0].lower().strip()
                if key == 'identity':
                    ident_parse = parts[1].strip().replace('(','').replace(')','').replace('%','').split()
                    ident_num = int(ident_parse[0].split('/')[0])
                    ident_percent = float(ident_parse[1])
                    alignment.annotations['identity'] = ident_num
                    alignment.annotations['percent_identity'] = ident_percent
                if key == 'similarity':
                    sim_parse = parts[1].strip().replace('(','').replace(')','').replace('%','').split()
                    sim_num = int(sim_parse[0].split('/')[0])
                    sim_percent = float(sim_parse[1])
                    alignment.annotations['similarity'] = sim_num
                    alignment.annotations['percent_similarity'] = sim_percent
                if key == 'gaps':
                    gap_parse = parts[1].strip().replace('(','').replace(')','').replace('%','').split()
                    gap_num = int(gap_parse[0].split('/')[0])
                    gap_percent = float(gap_parse[1])
                    alignment.annotations['gaps'] = gap_num
                    alignment.annotations['percent_gaps'] = gap_percent
                if key == 'score':
                    score = float(parts[1].strip())
                    alignment.annotations['score'] = score

                line = f.readline()

    return alignment

Reads in a needle alignment file and returns an AlignIO object with annotations

Args:
infile (str): Alignment file name

Returns:
AlignIO: annotated AlignIO object


def success(channel, stats, name, platform, dp):

    datapacks = [("Platform", platform, False)]
    for stat in stats:

        if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"):
            stat_name = "__" + stat[0] + "__"
            stat_value = "**" + stat[1] + "**"
        else:
            stat_name = stat[0]
            stat_value = stat[1]

        if stat[2]:
            stat_value += " *(Top " + stat[2] + "%)*"

        datapacks.append((stat_name, stat_value, True))

    gui = ui_embed.UI(
        channel,
        "Rocket League Stats: {}".format(name),
        "*Stats obtained from [Rocket League Tracker Network](https:
        modulename=modulename,
        colour=0x0088FF,
        thumbnail=dp,
        datapacks=datapacks
    )

    return gui

Creates an embed UI containing the Rocket League stats

Args:
channel (discord.Channel): The Discord channel to bind the embed to
stats (tuple): Tuples of (field, value, percentile)
name (str): The name of the player
platform (str): The playfor to search on, can be 'steam', 'ps', or 'xbox'
dp (str): URL to the player's dp

Returns:
(discord.Embed): The created embed


def _set_device(self, device) -> None:
    self._set_device_from_string(compat.as_str(_device_string(device)))

Set the device of this operation.

Args:
device: string or device..  The device to set.


def create_image_uri(region, framework, instance_type, framework_version, py_version=None, account='520713654638', accelerator_type=None, optimized_families=None):
    optimized_families = (optimized_families or [])
    if (py_version and (py_version not in VALID_PY_VERSIONS)):
        raise ValueError('invalid py_version argument: {}'.format(py_version))
    account = VALID_ACCOUNTS_BY_REGION.get(region, account)
    if instance_type.startswith('local'):
        device_type = ('cpu' if (instance_type == 'local') else 'gpu')
    elif (not instance_type.startswith('ml.')):
        raise ValueError('{} is not a valid SageMaker instance type. See: https:
    else:
        family = instance_type.split('.')[1]
        if (family in optimized_families):
            device_type = family
        elif (family[0] in ['g', 'p']):
            device_type = 'gpu'
        else:
            device_type = 'cpu'
    if py_version:
        tag = '{}-{}-{}'.format(framework_version, device_type, py_version)
    else:
        tag = '{}-{}'.format(framework_version, device_type)
    if _accelerator_type_valid_for_framework(framework=framework, accelerator_type=accelerator_type, optimized_families=optimized_families):
        framework += '-eia'
    return '{}/sagemaker-{}:{}'.format(get_ecr_image_uri_prefix(account, region), framework, tag)

Return the ECR URI of an image.

Args:
region (str): AWS region where the image is uploaded.
framework (str): framework used by the image.
instance_type (str): SageMaker instance type. Used to determine device type (cpu/gpu/family-specific optimized).
framework_version (str): The version of the framework.
py_version (str): Optional. Python version. If specified, should be one of 'py2' or 'py3'.
If not specified, image uri will not include a python component.
account (str): AWS account that contains the image. (default: '520713654638')
accelerator_type (str): SageMaker Elastic Inference accelerator type.
optimized_families (str): Instance families for which there exist specific optimized images.

Returns:
str: The appropriate image URI based on the given parameters.


def load_variables(defines, config_file):

    if config_file is not None:
        with open(config_file, "r") as conf_file:
            variables = yaml.load(conf_file)
    else:
        variables = {}

    for define in defines:
        name, equ, value = define.partition('=')
        if equ != '=':
            print("Invalid variable definition")
            print("- expected name=value")
            print("- found: '%s'" % define)
            sys.exit(1)

        variables[name] = value

    return variables

Load all variables from cmdline args and/or a config file.

Args:
defines (list of str): A list of name=value pairs that
define free variables.
config_file (str): An optional path to a yaml config
file that defines a single dict with name=value
variable definitions.


def insert_before(self, value: Union[(RawValue, Value)], raw: bool=False) -> 'ArrayEntry':
    return ArrayEntry(self.index, self.before, self.after.cons(self.value), self._cook_value(value, raw), self.parinst, self.schema_node, datetime.now())

Insert a new entry before the receiver.

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

Returns:
An instance node of the new inserted entry.


def get_all_dataset_names(configuration=None, **kwargs):
    dataset = Dataset(configuration=configuration)
    dataset['id'] = 'all dataset names'
    return dataset._write_to_hdx('list', kwargs, 'id')

Get all dataset names in HDX

Args:
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.
**kwargs: See below
limit (int): Number of rows to return. Defaults to all dataset names.
offset (int): Offset in the complete result for where the set of returned dataset names should begin

Returns:
List[str]: list of all dataset names in HDX


def _estimate_data_distribution(c, num_examples_per_class_seen):
    num_classes = num_examples_per_class_seen.get_shape()[0]
    num_examples_per_class_seen = math_ops.add(num_examples_per_class_seen, math_ops.reduce_sum(array_ops.one_hot(c, num_classes, dtype=dtypes.int64), 0))
    init_prob_estimate = math_ops.truediv(num_examples_per_class_seen, math_ops.reduce_sum(num_examples_per_class_seen))
    dist = math_ops.cast(init_prob_estimate, dtypes.float32)
    return (num_examples_per_class_seen, dist)

Estimate data distribution as labels are seen.

Args:
c: The class labels.  Type `int32`, shape `[batch_size]`.
num_examples_per_class_seen: Type `int64`, shape `[num_classes]`, containing
counts.

Returns:
num_examples_per_lass_seen: Updated counts.  Type `int64`, shape
`[num_classes]`.
dist: The updated distribution.  Type `float32`, shape `[num_classes]`.


def cancel_id(cls, id):
    conn = Qubole.agent()
    data = {'status': 'kill'}
    return conn.put(cls.element_path(id), data)

Cancels command denoted by this id

Args:
`id`: command id


def render_registered(url_id, remote_info):
    return template(read_index_template(), registered=True, url=remote_info['url'], seeder_data=json.dumps(remote_info), url_id=url_id)

Render template file for the registered user, which has some of the values
prefilled.

Args:
url_id (str): Seeder URL id.
remote_info (dict): Informations read from Seeder.

Returns:
str: Template filled with data.


def forward_event_shape_tensor(self, input_shape, name='forward_event_shape_tensor'):
    with self._name_scope(name, [input_shape]):
        input_shape = ops.convert_to_tensor(input_shape, dtype=dtypes.int32, name='input_shape')
        return self._forward_event_shape_tensor(input_shape)

Shape of a single sample from a single batch as an `int32` 1D `Tensor`.

Args:
input_shape: `Tensor`, `int32` vector indicating event-portion shape
passed into `forward` function.
name: name to give to the op

Returns:
forward_event_shape_tensor: `Tensor`, `int32` vector indicating
event-portion shape after applying `forward`.


def suggestions(self, word):
    suggestions = set(self._misspelling_dict.get(word, [])).union(set(self._misspelling_dict.get(word.lower(), [])))
    return sorted([same_case(source=word, destination=w) for w in suggestions])

Returns a list of suggestions for a misspelled word.

Args:
word: The word to check.

Returns:
List of zero or more suggested replacements for word.


def set_napp(self, user, napp, version=None):

        self.user = user
        self.napp = napp
        self.version = version or 'latest'

Set info about NApp.

Args:
user (str): NApps Server username.
napp (str): NApp name.
version (str): NApp version.


def CheckEmptyBlockBody(filename, clean_lines, linenum, error):

  line = clean_lines.elided[linenum]
  matched = Match(r'\s*(for|while|if)\s*\(', line)
  if matched:

    (end_line, end_linenum, end_pos) = CloseExpression(
        clean_lines, linenum, line.find('('))

    if end_pos >= 0 and Match(r';', end_line[end_pos:]):
      if matched.group(1) == 'if':
        error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
              'Empty conditional bodies should use {}')
      else:
        error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
              'Empty loop bodies should use {} or continue')

Look for empty loop/conditional body with only a single semicolon.

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


def up(self) -> 'InstanceNode':
    ts = max(self.timestamp, self.parinst.timestamp)
    return self.parinst._copy(self._zip(), ts)

Return an instance node corresponding to the receiver's parent.

Raises:
NonexistentInstance: If there is no parent.


def log_transition(self, transition, from_state, instance, *args, **kwargs):
    logger = logging.getLogger('xworkflows.transitions')
    try:
        instance_repr = u(repr(instance), 'ignore')
    except (UnicodeEncodeError, UnicodeDecodeError):
        instance_repr = u('<bad repr>')
    logger.info(u('%s performed transition %s.%s (%s -> %s)'), instance_repr, self.__class__.__name__, transition.name, from_state.name, transition.target.name)

Log a transition.

Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object

Kwargs:
Any passed when calling the transition


def _on_scan(self, info):
    device_id = info['uuid']
    expiration_time = info.get('validity_period', 60)
    infocopy = deepcopy(info)
    infocopy['expiration_time'] = (monotonic() + expiration_time)
    with self._scan_lock:
        self._scanned_devices[device_id] = infocopy

Callback called when a new device is discovered on this CMDStream

Args:
info (dict): Information about the scanned device


def Images(self, run, tag):
    accumulator = self.GetAccumulator(run)
    return accumulator.Images(tag)

Retrieve the image events associated with a run and tag.

Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.

Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.

Returns:
An array of `event_accumulator.ImageEvents`.


def __init__(self, uid):

        message = 'Schema of UID "{}" is unrecognized.'.format(uid)
        super(UnknownUIDSchema, self).__init__(message)

Exception raised when a schema of a UID is unknown.

Args:
uid (string): given UID


def ensure_list_size(list_, size_):

    lendiff = (size_) - len(list_)
    if lendiff > 0:
        extension = [None for _ in range(lendiff)]
        list_.extend(extension)

Allocates more space if needbe.

Ensures len(``list_``) == ``size_``.

Args:
list_ (list): ``list`` to extend
size_ (int): amount to exent by


def CopyFromDict(self, attributes):

    for attribute_name, attribute_value in attributes.items():

      if attribute_name[0] == '_':
        continue
      setattr(self, attribute_name, attribute_value)

Copies the attribute container from a dictionary.

Args:
attributes (dict[str, object]): attribute values per name.


def __sub__(self, other):
    try:
        other = as_dimension(other)
    except (TypeError, ValueError):
        return NotImplemented
    if self._value is None or other.value is None:
        return Dimension(None)
    else:
        return Dimension(self._value - other.value)

Returns the subtraction of `other` from `self`.

Dimensions are subtracted as follows:

```python
tf.compat.v1.Dimension(m)    - tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m - n)
tf.compat.v1.Dimension(m)    - tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
```

Args:
other: Another Dimension, or a value accepted by `as_dimension`.

Returns:
A Dimension whose value is the subtraction of `other` from `self`.


def download_archive(self, id_or_uri, file_path):

        uri = self.URI + "/archive/" + extract_id_from_uri(id_or_uri)
        return self._client.download(uri, file_path)

Download the details of the Golden Image capture logs, which has been archived based on the specific attribute
ID.

Args:
id_or_uri: ID or URI of the Golden Image.
file_path (str): File name to save the archive.

Returns:
bool: Success.


def _from_keras_log_format(data, **kwargs):
    data_val = pd.DataFrame(data[['epoch']])
    data_val['acc'] = data['val_acc']
    data_val['loss'] = data['val_loss']
    data_val['data'] = 'validation'
    data_training = pd.DataFrame(data[['acc', 'loss', 'epoch']])
    data_training['data'] = 'training'
    result = pd.concat([data_training, data_val], sort=False)
    plot(result, **kwargs)

Plot accuracy and loss from a panda's dataframe.

Args:
data: Panda dataframe in the format of the Keras CSV log.
output_dir_path: The path to the directory where the resultings plots
should end up.


def alt40mcp(msg):

    d = hex2bin(data(msg))

    if d[0] == '0':
        return None

    alt = bin2int(d[1:13]) * 16
    return alt

Selected altitude, MCP/FCU

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

Returns:
int: altitude in feet


def _sample_row(self):
    unis = np.random.uniform(0, 1, self.n_var)
    first_ind = np.random.randint(0, self.n_var)
    adj = self.trees[0].get_adjacent_matrix()
    visited = []
    explore = [first_ind]
    sampled = np.zeros(self.n_var)
    itr = 0
    while explore:
        current = explore.pop(0)
        neighbors = np.where((adj[(current, :)] == 1))[0].tolist()
        if (itr == 0):
            new_x = self.ppfs[current](unis[current])
        else:
            for i in range((itr - 1), (- 1), (- 1)):
                current_ind = (- 1)
                if (i >= self.truncated):
                    continue
                current_tree = self.trees[i].edges
                for edge in current_tree:
                    if (i == 0):
                        if (((edge.L == current) and (edge.R == visited[0])) or ((edge.R == current) and (edge.L == visited[0]))):
                            current_ind = edge.index
                            break
                    elif ((edge.L == current) or (edge.R == current)):
                        condition = set(edge.D)
                        condition.add(edge.L)
                        condition.add(edge.R)
                        visit_set = set(visited)
                        visit_set.add(current)
                        if condition.issubset(visit_set):
                            current_ind = edge.index
                        break
                if (current_ind != (- 1)):
                    copula_type = current_tree[current_ind].name
                    copula = Bivariate(CopulaTypes(copula_type))
                    copula.theta = current_tree[current_ind].theta
                    derivative = copula.partial_derivative_scalar
                    if (i == (itr - 1)):
                        tmp = optimize.fminbound(derivative, EPSILON, 1.0, args=(unis[visited[0]], unis[current]))
                    else:
                        tmp = optimize.fminbound(derivative, EPSILON, 1.0, args=(unis[visited[0]], tmp))
                    tmp = min(max(tmp, EPSILON), 0.99)
            new_x = self.ppfs[current](tmp)
        sampled[current] = new_x
        for s in neighbors:
            if (s not in visited):
                explore.insert(0, s)
        itr += 1
        visited.insert(0, current)
    return sampled

Generate a single sampled row from vine model.

Returns:
numpy.ndarray


def build_relative_position(query_layer, key_layer):
    query_size = query_layer.size(-2)
    key_size = key_layer.size(-2)
    q_ids = torch.arange(query_size, dtype=torch.long, device=query_layer.device)
    k_ids = torch.arange(key_size, dtype=torch.long, device=key_layer.device)
    rel_pos_ids = q_ids[:, None] - k_ids.view(1, -1).repeat(query_size, 1)
    rel_pos_ids = rel_pos_ids[:query_size, :]
    rel_pos_ids = rel_pos_ids.unsqueeze(0)
    return rel_pos_ids

Build relative position according to the query and key

We assume the absolute position of query \(P_q\) is range from (0, query_size) and the absolute position of key
\(P_k\) is range from (0, key_size), The relative positions from query to key is \(R_{q \rightarrow k} = P_q -
P_k\)

Args:
query_size (int): the length of query
key_size (int): the length of key

Return:
`torch.LongTensor`: A tensor with shape [1, query_size, key_size]


def role_instance(self, value):

        if value == self._defaults['ai.cloud.roleInstance'] and 'ai.cloud.roleInstance' in self._values:
            del self._values['ai.cloud.roleInstance']
        else:
            self._values['ai.cloud.roleInstance'] = value

The role_instance property.

Args:
value (string). the property value.


def get_volume_list(self) -> list:
    volumes = []
    if (not self._manager):
        raise RuntimeError('Only the Swarm manager node can retrieve all the services.')
    volume_list = self._client.volumes.list()
    for v_list in volume_list:
        volumes.append(v_list.name)
    return volumes

Get a list of docker volumes.

Only the manager nodes can retrieve all the volumes

Returns:
list, all the names of the volumes in swarm


def chomp(text, max_len=280, split=None):

    split = split or '—;,.'
    while length(text) > max_len:
        try:
            text = re.split(r'[' + split + ']', text[::-1], 1)[1][::-1]
        except IndexError:
            return text

    return text

Shorten a string so that it fits under max_len, splitting it at 'split'.
Not guaranteed to return a string under max_len, as it may not be possible

Args:
text (str): String to shorten
max_len (int): maximum length. default 140
split (str): strings to split on (default is common punctuation: "-;,.")


def flatten(weights, start=0, stop=2):
    for (key, val) in weights.items():
        new_shape = ((val.shape[0:start] + ((- 1),)) + val.shape[stop:])
        weights[key] = val.reshape(new_shape)
    return weights

This methods reshapes all values in a dictionary.

The indices from start to stop will be flattened into a single index.

Args:
weights: A dictionary mapping keys to numpy arrays.
start: The starting index.
stop: The ending index.


def total_clicks(self, url):

        url = self.clean_url(url)
        clicks_url = f'{self.api_url}v3/link/clicks'
        params = {
            'link': url,
            'access_token': self.api_key,
            'format': 'txt'
        }
        response = self._get(clicks_url, params=params)
        if not response.ok:
            raise BadAPIResponseException(response.content)

        try:
            total_clicks = int(response.text)
        except (KeyError, TypeError) as e:
            logger.warning('Bad value from total_clicks response: %s', e)
            return 0

        return total_clicks

Total clicks implementation for Bit.ly
Args:
url: the URL you want to get the total clicks count

Returns:
An int containing the total clicks count

Raises:
BadAPIResponseException: If the API Returns an error as response


def shape_tensor(self, name='shape_tensor'):
    with self._name_scope(name):
        if self.shape.is_fully_defined():
            return linear_operator_util.shape_tensor(self.shape.as_list())
        else:
            return self._shape_tensor()

Shape of this `LinearOperator`, determined at runtime.

If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns a `Tensor` holding
`[B1,...,Bb, M, N]`, equivalent to `tf.shape(A)`.

Args:
name:  A name for this `Op`.

Returns:
`int32` `Tensor`


def jaccard_sims(feature_list):

    sim_info_list = []
    for feature_info in feature_list:
        md5_source = feature_info['md5']
        features_source = feature_info['features']
        for feature_info in feature_list:
            md5_target = feature_info['md5']
            features_target = feature_info['features']
            if md5_source == md5_target:
                continue
            sim = jaccard_sim(features_source, features_target)
            if sim > .5:
                sim_info_list.append({'source': md5_source, 'target': md5_target, 'sim': sim})

    return sim_info_list

Compute Jaccard similarities between all the observations in the feature list.

Args:
feature_list: a list of dictionaries, each having structure as
{ 'md5' : String, 'features': list of Strings }

Returns:
list of dictionaries with structure as
{'source': md5 String, 'target': md5 String, 'sim': Jaccard similarity Number}


def flatten(input_layer, preserve_batch=True):

  if preserve_batch:
    return reshape(input_layer, [DIM_SAME, -1])
  else:
    return reshape(input_layer, [-1])

Flattens this.

If preserve_batch is True, the result is rank 2 and the first dim (batch) is
unchanged. Otherwise the result is rank 1.

Args:
input_layer: The Pretty Tensor object, supplied.
preserve_batch: If True (the default), then preserve the first dimension.
Returns:
A LayerWrapper with the flattened tensor.


def _AlignDecodedDataOffset(self, decoded_data_offset):

    self._file_object.seek(0, os.SEEK_SET)

    self._decoder = self._GetDecoder()
    self._decoded_data = b''

    encoded_data_offset = 0
    encoded_data_size = self._file_object.get_size()

    while encoded_data_offset < encoded_data_size:
      read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
      if read_count == 0:
        break

      encoded_data_offset += read_count

      if decoded_data_offset < self._decoded_data_size:
        self._decoded_data_offset = decoded_data_offset
        break

      decoded_data_offset -= self._decoded_data_size

Aligns the encoded file with the decoded data offset.

Args:
decoded_data_offset (int): decoded data offset.


def run_multiple(self, eventLoops):

        self.nruns += len(eventLoops)
        return self.communicationChannel.put_multiple(eventLoops)

run the event loops in the background.

Args:
eventLoops (list): a list of event loops to run


def Wget(src_url, tgt_name, tgt_root=None):
    if (tgt_root is None):
        tgt_root = str(CFG['tmp_dir'])
    from benchbuild.utils.cmd import wget
    tgt_file = (local.path(tgt_root) / tgt_name)
    if (not source_required(tgt_file)):
        Copy(tgt_file, '.')
        return
    wget(src_url, '-O', tgt_file)
    update_hash(tgt_file)
    Copy(tgt_file, '.')

Download url, if required.

Args:
src_url (str): Our SOURCE url.
tgt_name (str): The filename we want to have on disk.
tgt_root (str): The TARGET directory for the download.
Defaults to ``CFG["tmpdir"]``.


def fit_truncated_gaussian(samples, lower_bounds, upper_bounds):
    if (len(samples.shape) == 1):
        return _TruncatedNormalFitter()((samples, lower_bounds, upper_bounds))

    def item_generator():
        for ind in range(samples.shape[0]):
            if is_scalar(lower_bounds):
                lower_bound = lower_bounds
            else:
                lower_bound = lower_bounds[ind]
            if is_scalar(upper_bounds):
                upper_bound = upper_bounds
            else:
                upper_bound = upper_bounds[ind]
            (yield (samples[ind], lower_bound, upper_bound))
    results = np.array(multiprocess_mapping(_TruncatedNormalFitter(), item_generator()))
    return (results[(:, 0)], results[(:, 1)])

Fits a truncated gaussian distribution on the given samples.

This will do a maximum likelihood estimation of a truncated Gaussian on the provided samples, with the
truncation points given by the lower and upper bounds.

Args:
samples (ndarray): a one or two dimensional array. If one dimensional we fit the truncated Gaussian on all
values. If two dimensional, we calculate the truncated Gaussian for every set of samples over the
first dimension.
lower_bounds (ndarray or float): the lower bound, either a scalar or a lower bound per problem (first index of
samples)
upper_bounds (ndarray or float): the upper bound, either a scalar or an upper bound per problem (first index of
samples)

Returns:
mean, std: the mean and std of the fitted truncated Gaussian


def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation:

    def raise_missing_fields(gate_name: str):
        raise ValueError(
            '{} missing required fields: {}'.format(gate_name, proto_dict))
    param = _parameterized_value_from_proto_dict
    qubit = devices.GridQubit.from_proto_dict
    if 'exp_w' in proto_dict:
        exp_w = proto_dict['exp_w']
        if ('half_turns' not in exp_w or 'axis_half_turns' not in exp_w
                or 'target' not in exp_w):
            raise_missing_fields('ExpW')
        return ops.PhasedXPowGate(
            exponent=param(exp_w['half_turns']),
            phase_exponent=param(exp_w['axis_half_turns']),
        ).on(qubit(exp_w['target']))
    elif 'exp_z' in proto_dict:
        exp_z = proto_dict['exp_z']
        if 'half_turns' not in exp_z or 'target' not in exp_z:
            raise_missing_fields('ExpZ')
        return ops.Z(qubit(exp_z['target']))**param(exp_z['half_turns'])
    elif 'exp_11' in proto_dict:
        exp_11 = proto_dict['exp_11']
        if ('half_turns' not in exp_11 or 'target1' not in exp_11
                or 'target2' not in exp_11):
            raise_missing_fields('Exp11')
        return ops.CZ(qubit(exp_11['target1']),
                      qubit(exp_11['target2']))**param(exp_11['half_turns'])
    elif 'measurement' in proto_dict:
        meas = proto_dict['measurement']
        invert_mask = cast(Tuple[Any, ...], ())
        if 'invert_mask' in meas:
            invert_mask = tuple(json.loads(x) for x in meas['invert_mask'])
        if 'key' not in meas or 'targets' not in meas:
            raise_missing_fields('Measurement')
        return ops.MeasurementGate(
            num_qubits=len(meas['targets']),
            key=meas['key'],
            invert_mask=invert_mask
        ).on(*[qubit(q) for q in meas['targets']])
    else:
        raise ValueError('invalid operation: {}'.format(proto_dict))

Convert the proto dictionary to the corresponding operation.

See protos in api/google/v1 for specification of the protos.

Args:
proto_dict: Dictionary representing the proto. Keys are always
strings, but values may be types correspond to a raw proto type
or another dictionary (for messages).

Returns:
The operation.

Raises:
ValueError if the dictionary does not contain required values
corresponding to the proto.


def query(self, object_class=None, json=None, **kwargs):
    path = '/directory-sync-service/v1/{}'.format(object_class)
    r = self._httpclient.request(method='POST', url=self.url, json=json, path=path, **kwargs)
    return r

Query data stored in directory.

Retrieves directory data by querying a Directory Sync Service
cloud-based instance. The directory data is stored with the
Directory Sync Service instance using an agent that is installed
in the customer's network.This agent retrieves directory data
from the customer's Active Directory, and then sends it to the
cloud-based Directory Sync Service instance.

Args:
object_class (str): Directory object class.
json (dict): Payload/request body.
**kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters.

Returns:
requests.Response: Requests Response() object.

Examples:
Coming soon.


def two_point_effective_mass( cartesian_k_points, eigenvalues ):

    assert( cartesian_k_points.shape[0] == 2 )
    assert( eigenvalues.size == 2 )
    dk = cartesian_k_points[ 1 ] - cartesian_k_points[ 0 ]
    mod_dk = np.sqrt( np.dot( dk, dk ) )
    delta_e = ( eigenvalues[ 1 ] - eigenvalues[ 0 ] ) * ev_to_hartree * 2.0
    effective_mass = mod_dk * mod_dk / delta_e
    return effective_mass

Calculate the effective mass given eigenvalues at two k-points.
Reimplemented from Aron Walsh's original effective mass Fortran code.

Args:
cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) Cartesian coordinates.
eigenvalues (np.array):        numpy array containing the eigenvalues at each k-point.

Returns:
(float): The effective mass


def name_scope_only_in_function_or_graph(name):
    if not context.executing_eagerly():
        return ops.name_scope_v1(name)
    else:
        return NullContextmanager()

Internal-only entry point for `name_scope*`.

Enters a compat.v1.name_scope only when in a function or graph,
not when running fully eagerly.

Args:
name: The name argument that is passed to the op function.

Returns:
`name_scope*` context manager.


def add_string_pairs_from_attributed_ui_element(results, ui_element, comment_prefix):
    attributed_strings = ui_element.getElementsByTagName('attributedString')
    if (attributed_strings.length == 0):
        return False
    attributed_element = attributed_strings[0]
    fragment_index = 1
    for fragment in attributed_element.getElementsByTagName('fragment'):
        try:
            label_entry_key = fragment.attributes['content'].value
        except KeyError:
            label_entry_key = fragment.getElementsByTagName('string')[0].firstChild.nodeValue
        comment = ('%s Part %d' % (comment_prefix, fragment_index))
        results.append((label_entry_key, comment))
        fragment_index += 1
    return (fragment_index > 1)

Adds string pairs from a UI element with attributed text

Args:
results (list): The list to add the results to.
attributed_element (element): The element from the xib that contains, to extract the fragments from.
comment_prefix (str): The prefix of the comment to use for extracted string
(will be appended "Part X" suffices)

Returns:
bool: Whether or not an attributed string was found.


def replace(self, pattern, replacement):

        for i, line in enumerate(self):
            if pattern in line:
                self[i] = line.replace(pattern, replacement)

Replace all instances of a pattern with a replacement.

Args:
pattern (str): Pattern to replace
replacement (str): Text to insert


def _paths_referenced_by(node: AbstractSyntaxTree) -> Tuple[Optional[str], Collection[str]]:
    if isinstance(node, Identifier):
        if node.value in ('$this', '$index', '$total'):
            return (None, ())
        else:
            return (node.value, ())
    if not node.children:
        return (None, ())
    context, paths = _paths_referenced_by(node.children[0])
    if isinstance(node, Function):
        context = None
    if isinstance(node, Invocation) and isinstance(node.rhs, Identifier):
        context = _append_path_to_context(context, node.rhs.value)
        return (context, paths)
    if context is not None:
        paths = paths + (context,)
    if isinstance(node, Invocation):
        child_paths = _get_paths_from_children_except_first(node)
        child_paths = tuple((_append_path_to_context(context, child_path) for child_path in child_paths))
        return (context, paths + child_paths)
    child_paths = _get_paths_from_children_except_first(node)
    return (context, paths + child_paths)

Finds paths for any fields referenced in the given tree.

Recursively builds paths by visitng the trees nodes depth-first in-order.
Returns a tuple of (context, paths) where `context` is an identifier which may
be part of a dotted path completed by its parent and `paths` are the full
dotted paths found so far.

Callers are responsible for attempting to either continue chaining successive
identifiers from invocations to the context or acknowledging it as completed
and adding it to `paths` if the caller has no identifiers to add to the chain.

Args:
node: The abstract syntax tree to search for paths.

Returns:
A tuple of (context, paths) as described above.


def _placeholder_value(like, shape_invariant, original=None):
    if like is None:
        return (original, None)
    elif isinstance(like, (variables.Undefined, variables.UndefinedReturnValue)):
        return (original, None)
    elif isinstance(like, (int, float, bool)):
        return (type(like)(0), None)
    elif tensor_util.is_tf_type(like):
        like_shape = shape_invariant if shape_invariant is not None else like.shape
        if like_shape is None or like_shape.rank is None:
            return (array_ops.zeros((), like.dtype), like_shape)
        placeholder_shape = []
        has_dynamic_dims = False
        for s, i in zip(like.shape, like_shape):
            if i is None:
                like_dim = 0
            elif isinstance(i, tensor_shape.Dimension):
                if i.value is None:
                    like_dim = 0
                else:
                    like_dim = i.value
            else:
                like_dim = i
            if s is None:
                placeholder_shape.append(like_dim)
                has_dynamic_dims = True
            elif isinstance(s, tensor_shape.Dimension):
                if s.value is None:
                    placeholder_shape.append(like_dim)
                    has_dynamic_dims = True
                else:
                    placeholder_shape.append(s.value)
            else:
                placeholder_shape.append(s)
        if has_dynamic_dims:
            invariant = like_shape
        else:
            invariant = None
        return (array_ops.zeros(placeholder_shape, like.dtype), invariant)
    elif isinstance(like, (list, tuple, dict)):
        if shape_invariant is None:
            zipped = nest.map_structure(lambda v: _placeholder_value(v, None), nest.flatten(like))
        else:
            zipped = nest.map_structure(_placeholder_value, nest.flatten(like), nest.flatten(shape_invariant))
        vals, invars = zip(*zipped)
        return (nest.pack_sequence_as(like, vals), nest.pack_sequence_as(like, invars))
    raise TypeError("Found an unsupported type '{}' while creating placeholder for {}. Supported types include Tensor, int, float, bool, list, tuple or dict.".format(type(like).__name__, like))

Constructs a (dummy) placeholder value for a loop-initialized variable.

Args:
like: Any object. The value created by the first iteration of the loop. If a
Python scalar, the placeholder will be the zero value of that type. If a
Tensor, the placeholder will be a zero tensor of matching shape and dtype.
If a list, dict or tuple, the placeholder will be an identical structure
of placeholders.
shape_invariant: The shape invariant specified by the user (or None, if
nothing was specified) for the respective variable.
original: Any object. The value of the variable prior to entering the loop.
Typically, this is one of the special "Undefined" value, because that's
when a placeholder is needed.

Returns:
Either a zero value of structure, shape and dtype matching 'like', or
'original', if no such zero value could be created.


def map_kegg_all_genes(organism_code, target_db):

    mapping = bs_kegg.conv(target_db, organism_code)

    new_mapping = {}
    for k,v in mapping.items():
        new_mapping[k.replace(organism_code + ':', '')] = str(v.split(':')[1])

    return new_mapping

Map all of an organism's gene IDs to the target database.

This is faster than supplying a specific list of genes to map,
plus there seems to be a limit on the number you can map with a manual REST query anyway.

Args:
organism_code: the three letter KEGG code of your organism
target_db: ncbi-proteinid | ncbi-geneid | uniprot

Returns:
Dictionary of ID mapping


def _run_graph(self, device, output_shape, variable, num_outputs, axis):
    graph = ops.Graph()
    with graph.as_default():
        if not variable:
            if axis == 0:
                input_shape = [output_shape[0] * num_outputs, output_shape[1]]
                sizes = [output_shape[0] for _ in range(num_outputs)]
            else:
                input_shape = [output_shape[0], output_shape[1] * num_outputs]
                sizes = [output_shape[1] for _ in range(num_outputs)]
        else:
            sizes = np.random.randint(low=max(1, output_shape[axis] - 2), high=output_shape[axis] + 2, size=num_outputs)
            total_size = np.sum(sizes)
            if axis == 0:
                input_shape = [total_size, output_shape[1]]
            else:
                input_shape = [output_shape[0], total_size]
        outputs = build_graph(device, input_shape, sizes, axis)
    config = config_pb2.ConfigProto(graph_options=config_pb2.GraphOptions(optimizer_options=config_pb2.OptimizerOptions(opt_level=config_pb2.OptimizerOptions.L0)))
    with session_lib.Session(graph=graph, config=config) as session:
        logging.set_verbosity('info')
        variables.global_variables_initializer().run()
        bench = benchmark.TensorFlowBenchmark()
        bench.run_op_benchmark(session, outputs, mbs=input_shape[0] * input_shape[1] * 4 * 2 * 100 / 1000000.0, extras={'input_shape': input_shape, 'variable': variable, 'axis': axis})

Run the graph and print its execution time.

Args:
device: string, the device to run on.
output_shape: shape of each output tensors.
variable: whether or not the output shape should be fixed
num_outputs: the number of outputs to split the input into
axis: axis to be split

Returns:
The duration of the run in seconds.


def recipe_fred_regional_to_bigquery(config, auth, fred_api_key, fred_series_group, fred_region_type, fred_units, fred_frequency, fred_season, fred_aggregation_method, project, dataset):
    fred(config, {'auth': auth, 'api_key': fred_api_key, 'frequency': fred_frequency, 'region_type': fred_region_type, 'regions': [{'series_group': fred_series_group, 'units': fred_units, 'season': fred_season, 'aggregation_method': fred_aggregation_method}], 'out': {'bigquery': {'project': project, 'dataset': dataset}}})

Download federal reserve region.

Args:
auth (authentication) - Credentials used for writing data.
fred_api_key (string) - 32 character alpha-numeric lowercase string.
fred_series_group (string) - The ID for a group of seriess found in GeoFRED.
fred_region_type (choice) - The region you want want to pull data for.
fred_units (choice) - A key that indicates a data value transformation.
fred_frequency (choice) - An optional parameter that indicates a lower frequency to aggregate values to.
fred_season (choice) - The seasonality of the series group.
fred_aggregation_method (choice) - A key that indicates the aggregation method used for frequency aggregation.
project (string) - Existing BigQuery project.
dataset (string) - Existing BigQuery dataset.


def join(self) -> None:
    self._is_thread_joined = True
    self._thread.join()
    if self._exception is not None:
        self._testcase.fail('Error in checkedThread: %s' % str(self._exception))

Blocks until the thread terminates.

Raises:
self._testcase.failureException: If the thread terminates with due to
an exception.


def compute_predicted_aligned_error(logits: torch.Tensor, max_bin: int=31, no_bins: int=64, **kwargs) -> Dict[str, torch.Tensor]:
    boundaries = torch.linspace(0, max_bin, steps=no_bins - 1, device=logits.device)
    aligned_confidence_probs = torch.nn.functional.softmax(logits, dim=-1)
    predicted_aligned_error, max_predicted_aligned_error = _calculate_expected_aligned_error(alignment_confidence_breaks=boundaries, aligned_distance_error_probs=aligned_confidence_probs)
    return {'aligned_confidence_probs': aligned_confidence_probs, 'predicted_aligned_error': predicted_aligned_error, 'max_predicted_aligned_error': max_predicted_aligned_error}

Computes aligned confidence metrics from logits.

Args:
logits: [*, num_res, num_res, num_bins] the logits output from
PredictedAlignedErrorHead.
max_bin: Maximum bin value
no_bins: Number of bins
Returns:
aligned_confidence_probs: [*, num_res, num_res, num_bins] the predicted
aligned error probabilities over bins for each residue pair.
predicted_aligned_error: [*, num_res, num_res] the expected aligned distance
error for each pair of residues.
max_predicted_aligned_error: [*] the maximum predicted error possible.


def set_xlim(self, xlim):

        if len(xlim) != 2:
            raise ValueError("xlim must contain two elements")

        if xlim[1] < xlim[0]:
            raise ValueError("Min must be less than Max")

        self.options["min_x"] = xlim[0]
        self.options["max_x"] = xlim[1]

Set x-axis limits.

Accepts a two-element list to set the x-axis limits.

Args:
xlim (list): lower and upper bounds

Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less than max


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

Args:
hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Input to the layer.
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Attention mask.
position_embeddings (`torch.FloatTensor`, *optional*):
Position embeddings, to be added to `hidden_states`.
reference_points (`torch.FloatTensor`, *optional*):
Reference points.
spatial_shapes (`torch.LongTensor`, *optional*):
Spatial shapes of the backbone feature maps.
level_start_index (`torch.LongTensor`, *optional*):
Level start index.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.


def uniform(self, low: float, high: float) -> float:

        return float(lib.TCOD_random_get_double(self.random_c, low, high))

Return a random floating number in the range: low <= n <= high.

Args:
low (float): The lower bound of the random range.
high (float): The upper bound of the random range.

Returns:
float: A random float.


def get_resource(self, resource_key, **variables):

        handle = self.make_resource_handle(resource_key, **variables)
        return self.get_resource_from_handle(handle, verify_repo=False)

Get a resource.

Attempts to get and return a cached version of the resource if
available, otherwise a new resource object is created and returned.

Args:
resource_key (`str`):  Name of the type of `Resources` to find
variables: data to identify / store on the resource

Returns:
`PackageRepositoryResource` instance.


def schema(self):

    def _info2columns(info):
        return tuple(((column['name'], column['type']) for column in info))

    def _table2tuple(table):
        return (table, _info2columns(self.table_info(table)))
    return [_table2tuple(table) for table in self.tables]

Returns the schema of all tables.

For each table, return the name, and a list of tuples
representing the columns. Each column tuple consists of a
(name, type) pair. Note that additional metadata, such as
whether a column may be null, or whether a column is a primary
key, is not returned.

Example:

>>> db.schema
[("bar", (("id", "integer"), ("name", "table"))]

Returns:

list of tuples: Each tuple has the format (name, columns), where
"columns" is a list of tuples of the form (name, type).


def WriteArtifactsFile(self, artifacts, filename):

    with open(filename, 'w') as file_object:
      file_object.write(self.FormatArtifacts(artifacts))

Writes artifact definitions to a file.

Args:
artifacts (list[ArtifactDefinition]): artifact definitions to be written.
filename (str): name of the file to write artifacts to.


def DecodeValueFromAttribute(self, attribute_name, value, ts):
    try:
        attribute = Attribute.PREDICATES[attribute_name]
        cls = attribute.attribute_type
        self._AddAttributeToCache(attribute, LazyDecoder(cls, value, ts), self.synced_attributes)
    except KeyError:
        pass
    except (ValueError, rdfvalue.DecodeError):
        logging.debug('%s: %s invalid encoding. Skipping.', self.urn, attribute_name)

Given a serialized value, decode the attribute.

Only attributes which have been previously defined are permitted.

Args:
attribute_name: The string name of the attribute.
value: The serialized attribute value.
ts: The timestamp of this attribute.


def write_bit(self, registeraddress, value, functioncode=5):
    _checkFunctioncode(functioncode, [5, 15])
    _checkInt(value, minvalue=0, maxvalue=1, description='input value')
    self._genericCommand(functioncode, registeraddress, value)

Write one bit to the slave.

Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int): 0 or 1
* functioncode (int): Modbus function code. Can be 5 or 15.

Returns:
None

Raises:
ValueError, TypeError, IOError


def get_all_pipelines(self):
    pipelines = list(map(self.get_pipeline, self.pipeline_dict.keys()))
    self._construct_solid_defs(pipelines)
    return pipelines

Return all pipelines as a list

Returns:
List[PipelineDefinition]:


def subproc_call(cmd, timeout=None):

    try:
        output = subprocess.check_output(
            cmd, stderr=subprocess.STDOUT,
            shell=True, timeout=timeout)
        return output, 0
    except subprocess.TimeoutExpired as e:
        logger.warn("Command '{}' timeout!".format(cmd))
        logger.warn(e.output.decode('utf-8'))
        return e.output, -1
    except subprocess.CalledProcessError as e:
        logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode))
        logger.warn(e.output.decode('utf-8'))
        return e.output, e.returncode
    except Exception:
        logger.warn("Command '{}' failed to run.".format(cmd))
        return "", -2

Execute a command with timeout, and return STDOUT and STDERR

Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.

Returns:
output(bytes), retcode(int). If timeout, retcode is -1.


def open_if_needed(self, mode=None):
    was_open = self.is_open()
    if (not was_open):
        self.open(mode=mode)
    try:
        (yield self)
    finally:
        if (not was_open):
            self.close()

Convenience context-manager for the use with ``with``.
Opens the container if not already done.
Only closes the container if it was opened within this context.

Args:
mode (str): Either 'r' for read-only, 'w' for truncate and write or
'a' for append. (default: 'a').
If ``None``, uses ``self.mode``.


def parse_json(self, values_json):

    values_map = json.loads(values_json)
    return self.override_from_dict(values_map)

Override existing hyperparameter values, parsing new values from a json object.

Args:
values_json: String containing a json object of name:value pairs.

Returns:
The `HParams` instance.

Raises:
KeyError: If a hyperparameter in `values_json` doesn't exist.
ValueError: If `values_json` cannot be parsed.


async def send_message(self, segments, image_file=None, image_id=None, image_user_id=None):
    async with self._send_message_lock:
        if image_file:
            try:
                uploaded_image = (await self._client.upload_image(image_file, return_uploaded_image=True))
            except exceptions.NetworkError as e:
                logger.warning('Failed to upload image: {}'.format(e))
                raise
            image_id = uploaded_image.image_id
        try:
            request = hangouts_pb2.SendChatMessageRequest(request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), message_content=hangouts_pb2.MessageContent(segment=[seg.serialize() for seg in segments]))
            if (image_id is not None):
                request.existing_media.photo.photo_id = image_id
            if (image_user_id is not None):
                request.existing_media.photo.user_id = image_user_id
                request.existing_media.photo.is_custom_user_id = True
            (await self._client.send_chat_message(request))
        except exceptions.NetworkError as e:
            logger.warning('Failed to send message: {}'.format(e))
            raise

Send a message to this conversation.

A per-conversation lock is acquired to ensure that messages are sent in
the correct order when this method is called multiple times
asynchronously.

Args:
segments: List of :class:`.ChatMessageSegment` objects to include
in the message.
image_file: (optional) File-like object containing an image to be
attached to the message.
image_id: (optional) ID of an Picasa photo to be attached to the
message. If you specify both ``image_file`` and ``image_id``
together, ``image_file`` takes precedence and ``image_id`` will
be ignored.
image_user_id: (optional) Picasa user ID, required only if
``image_id`` refers to an image from a different Picasa user,
such as Google's sticker user.

Raises:
.NetworkError: If the message cannot be sent.


def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
    input_ = deepcopy(input_)
    public_key = input_.owners_before[0]
    message = sha3_256(message.encode())
    if input_.fulfills:
        message.update('{}{}'.format(input_.fulfills.txid, input_.fulfills.output).encode())
    try:
        input_.fulfillment.sign(message.digest(), base58.b58decode(key_pairs[public_key].encode()))
    except KeyError:
        raise KeypairMismatchException('Public key {} is not a pair to any of the private keys'.format(public_key))
    return input_

Signs a Ed25519Fulfillment.

Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with.


def save(self, path):

        self.clip.write_videofile(path, audio_fps=self.clip.audio.fps)

Save source video to file.

Args:
path (str): Filename to save to.

Notes: Saves entire source video to file, not just currently selected
frames.


def print_matrix(self, format=None, output=sys.stdout, depth=0, **kwargs):

        matrix = self.as_matrix(depth=depth)
        matrix.print(format=format, output=output, **kwargs)

Print the matrix for self's nodes.

Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the matrix.


def _dominant_task_for_jobs(tasks):

  per_job = _group_tasks_by_jobid(tasks)

  ret = []
  for job_id in per_job.keys():
    tasks_in_salience_order = sorted(per_job[job_id], key=_importance_of_task)
    ret.append(tasks_in_salience_order[0])
  return ret

A list with, for each job, its dominant task.

The dominant task is the one that exemplifies its job's
status. It is either:
- the first (FAILURE or CANCELED) task, or if none
- the first RUNNING task, or if none
- the first SUCCESS task.

Args:
tasks: a list of tasks to consider

Returns:
A list with, for each job, its dominant task.


def __init__(self, conf, map_name, automount_mountpoint=None):
    super(FilesCache, self).__init__(conf, map_name, automount_mountpoint=automount_mountpoint)
    self.cache_filename_suffix = conf.get('cache_filename_suffix', 'cache')
    self._indices = {}
    if hasattr(self, '_INDEX_ATTRIBUTES'):
        for index in self._INDEX_ATTRIBUTES:
            self._indices[index] = {}

Create a handler for the given map type.

Args:
conf: a configuration object
map_name: a string representing the type of map we are
automount_mountpoint: A string containing the automount mountpoint, used
only by automount maps.


def speed_clustering(clf, points, min_time):

    changepoints = detect_changepoints(points, min_time)

    cp_info = []

    for i in range(0, len(changepoints) - 1):
        from_index = changepoints[i]
        to_index = changepoints[i+1]
        info = classify(clf, points[from_index:to_index], min_time, from_index, to_index)
        if info:
            cp_info.append(info)

    return group_modes(cp_info)

Transportation mode infering, based on changepoint segmentation

Args:
clf (:obj:`Classifier`): Classifier to use
points (:obj:`list` of :obj:`Point`)
min_time (float): Min time, in seconds, before do another segmentation
Returns:
:obj:`list` of :obj:`dict`


def expand_role(self, role):

        if '/' in role:
            return role
        else:
            return self.boto_session.resource('iam').Role(role).arn

Expand an IAM role name into an ARN.

If the role is already in the form of an ARN, then the role is simply returned. Otherwise we retrieve the full
ARN and return it.

Args:
role (str): An AWS IAM role (either name or full ARN).

Returns:
str: The corresponding AWS IAM role ARN.


def to_df(self, variables=None, format='wide', fillna=np.nan, **kwargs):
    if (variables is None):
        variables = list(self.variables.keys())
    if (not isinstance(variables[0], BIDSVariable)):
        variables = [v for v in self.variables.values() if (v.name in variables)]
    dfs = [v.to_df(**kwargs) for v in variables]
    df = pd.concat(dfs, axis=0, sort=True)
    if (format == 'long'):
        return df.reset_index(drop=True).fillna(fillna)
    ind_cols = list((set(df.columns) - {'condition', 'amplitude'}))
    df['amplitude'] = df['amplitude'].fillna('n/a')
    df = df.pivot_table(index=ind_cols, columns='condition', values='amplitude', aggfunc='first')
    df = df.reset_index().replace('n/a', fillna)
    df.columns.name = None
    return df

Merge variables into a single pandas DataFrame.

Args:
variables (list): Optional list of column names to retain; if None,
all variables are returned.
format (str): Whether to return a DataFrame in 'wide' or 'long'
format. In 'wide' format, each row is defined by a unique
onset/duration, and each variable is in a separate column. In
'long' format, each row is a unique combination of onset,
duration, and variable name, and a single 'amplitude' column
provides the value.
fillna: Replace missing values with the specified value.
kwargs: Optional keyword arguments to pass onto each Variable's
to_df() call (e.g., condition, entities, and timing).

Returns: A pandas DataFrame.


def CopyToProto(self, proto):
    if ((self.file is not None) and (self._serialized_start is not None) and (self._serialized_end is not None)):
        proto.ParseFromString(self.file.serialized_pb[self._serialized_start:self._serialized_end])
    else:
        raise Error('Descriptor does not contain serialization.')

Copies this to the matching proto in descriptor_pb2.

Args:
proto: An empty proto instance from descriptor_pb2.

Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.


def _set_unknown_flag(self, name, value):

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

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

Args:
name: str, name of the flag to set.
value: Value to set.

Returns:
Flag value on successful call.

Raises:
UnrecognizedFlagError
IllegalFlagValueError


def GetHasherNamesFromString(cls, hasher_names_string):
    hasher_names = []
    if ((not hasher_names_string) or (hasher_names_string.strip() == 'none')):
        return hasher_names
    if (hasher_names_string.strip() == 'all'):
        return cls.GetHasherNames()
    for hasher_name in hasher_names_string.split(','):
        hasher_name = hasher_name.strip()
        if (not hasher_name):
            continue
        hasher_name = hasher_name.lower()
        if (hasher_name in cls._hasher_classes):
            hasher_names.append(hasher_name)
    return hasher_names

Retrieves a list of a hasher names from a comma separated string.

Takes a string of comma separated hasher names transforms it to a list of
hasher names.

Args:
hasher_names_string (str): comma separated names of hashers to enable,
the string 'all' to enable all hashers or 'none' to disable all
hashers.

Returns:
list[str]: names of valid hashers from the string, or an empty list if no
valid names are found.


def _lsb_release_info(self):
    if (not self.include_lsb):
        return {}
    with open(os.devnull, 'w') as devnull:
        try:
            cmd = ('lsb_release', '-a')
            stdout = subprocess.check_output(cmd, stderr=devnull)
        except OSError:
            return {}
    content = stdout.decode(sys.getfilesystemencoding()).splitlines()
    return self._parse_lsb_release_content(content)

Get the information items from the lsb_release command output.

Returns:
A dictionary containing all information items.


def _add_partition(self, connection, partition):

        logger.debug('Creating virtual table for partition.\n    partition: {}'.format(partition.name))
        sqlite_med.add_partition(connection, partition.datafile, partition.vid+'_vt')

Creates sqlite virtual table for mpr file of the given partition.

Args:
connection: connection to the sqlite db who stores mpr data.
partition (orm.Partition):


def save_csv(X, y, path):

    if sparse.issparse(X):
        X = X.todense()

    np.savetxt(path, np.hstack((y.reshape((-1, 1)), X)), delimiter=',')

Save data as a CSV file.

Args:
X (numpy or scipy sparse matrix): Data matrix
y (numpy array): Target vector.
path (str): Path to the CSV file to save data.


def run_fetches_info(self):
    output = self._run_fetches_info
    return output[0] if len(output) == 1 else output

Get a str representation of the fetches used in the Session.run() call.

Returns:
If the information is available from one `Session.run` call, a `str`
obtained from `repr(fetches)`.
If the information is available from multiple `Session.run` calls, a
`list` of `str` from `repr(fetches)`.
If the information is not available, `None`.


def split_input(cls, mapper_spec):
    params = _get_params(mapper_spec)
    blob_keys = params[cls.BLOB_KEYS_PARAM]
    if isinstance(blob_keys, basestring):
        blob_keys = blob_keys.split(',')
    blob_sizes = {}
    for blob_key in blob_keys:
        blob_info = blobstore.BlobInfo.get(blobstore.BlobKey(blob_key))
        blob_sizes[blob_key] = blob_info.size
    shard_count = min(cls._MAX_SHARD_COUNT, mapper_spec.shard_count)
    shards_per_blob = (shard_count
    if (shards_per_blob == 0):
        shards_per_blob = 1
    chunks = []
    for (blob_key, blob_size) in blob_sizes.items():
        blob_chunk_size = (blob_size
        for i in xrange((shards_per_blob - 1)):
            chunks.append(BlobstoreLineInputReader.from_json({cls.BLOB_KEY_PARAM: blob_key, cls.INITIAL_POSITION_PARAM: (blob_chunk_size * i), cls.END_POSITION_PARAM: (blob_chunk_size * (i + 1))}))
        chunks.append(BlobstoreLineInputReader.from_json({cls.BLOB_KEY_PARAM: blob_key, cls.INITIAL_POSITION_PARAM: (blob_chunk_size * (shards_per_blob - 1)), cls.END_POSITION_PARAM: blob_size}))
    return chunks

Returns a list of shard_count input_spec_shards for input_spec.

Args:
mapper_spec: The mapper specification to split from. Must contain
'blob_keys' parameter with one or more blob keys.

Returns:
A list of BlobstoreInputReaders corresponding to the specified shards.


def get(self, item, default=None):

        if hasattr(self, item):
            return getattr(self, item)
        try:
            return self.__getitem__(item)

        except KeyError:
            return default

Returns the value ``item`` from the host or hosts group variables.

Arguments:
item(``str``): The variable to get
default(``any``): Return value if item not found