def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):
    src_r = RasterUtilClass.read_raster(srcfile)
    src_data = src_r.data
    dst_data = numpy.copy(src_data)
    if ((gdaltype == GDT_Float32) and (src_r.dataType != GDT_Float32)):
        gdaltype = src_r.dataType
    no_data = src_r.noDataValue
    new_no_data = DEFAULT_NODATA
    if (gdaltype in [GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_UInt32]):
        new_no_data = 0
    if (not MathClass.floatequal(new_no_data, src_r.noDataValue)):
        if (src_r.noDataValue not in v_dict):
            v_dict[src_r.noDataValue] = new_no_data
            no_data = new_no_data
    for (k, v) in iteritems(v_dict):
        dst_data[(src_data == k)] = v
    RasterUtilClass.write_gtiff_file(dstfile, src_r.nRows, src_r.nCols, dst_data, src_r.geotrans, src_r.srs, no_data, gdaltype)

Reclassify raster by given classifier dict.

Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default.


def get_embedded_object(self, signature_id):
    request = self._get_request()
    return request.get((self.EMBEDDED_OBJECT_GET_URL + signature_id))

Retrieves a embedded signing object

Retrieves an embedded object containing a signature url that can be opened in an iFrame.

Args:

signature_id (str): The id of the signature to get a signature url for

Returns:
An Embedded object


def fastcc_consistent_subset(model, epsilon, solver):
    reaction_set = set(model.reactions)
    return reaction_set.difference(fastcc(model, epsilon, solver))

Return consistent subset of model.

The largest consistent subset is returned as
a set of reaction names.

Args:
model: :class:`MetabolicModel` to solve.
epsilon: Flux threshold value.
solver: LP solver instance to use.

Returns:
Set of reaction IDs in the consistent reaction subset.


def clone(self, *args, **overrides):
    clone = super(NdLayout, self).clone(*args, **overrides)
    clone._max_cols = self._max_cols
    clone.id = self.id
    return clone

Clones the NdLayout, overriding data and parameters.

Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
**overrides: New keyword arguments to pass to constructor

Returns:
Cloned NdLayout object


def notify(self, subsystem, recipient, subject, body_html, body_text):
    if (not re.match(self.validation, recipient, re.I)):
        raise ValueError('Invalid recipient provided')
    if recipient.startswith('
        target_type = 'channel'
    elif (recipient.find('@') != (- 1)):
        target_type = 'user'
    else:
        self.log.error('Unknown contact type for Slack: {}'.format(recipient))
        return
    try:
        self._send_message(target_type=target_type, target=recipient, message=body_text, title=subject)
    except SlackError as ex:
        self.log.error('Failed sending message to {}: {}'.format(recipient, ex))

You can send messages either to channels and private groups by using the following formats

#channel-name
@username-direct-message

Args:
subsystem (`str`): Name of the subsystem originating the notification
recipient (`str`): Recipient
subject (`str`): Subject / title of the notification, not used for this notifier
body_html (`str)`: HTML formatted version of the message, not used for this notifier
body_text (`str`): Text formatted version of the message

Returns:
`None`


def cancel(**kwargs):
    task_list = _query(**kwargs)
    for task in task_list:
        task.status = WorkQueue.CANCELED
        task.finished = datetime.datetime.utcnow()
        db.session.add(task)
    return len(task_list)

Cancels work items based on their criteria.

Args:
**kwargs: Same parameters as the query() method.

Returns:
The number of tasks that were canceled.


def __eq__(self, other: Any) -> bool:
    if isinstance(other, str):
        return self.path == other
    return isinstance(other, KeyPath) and self.keys == other.keys

Equality check.

Args:
other: A string or a KeyPath.

Returns:
Whether JSON-path representation (either absolute or relative form)
of current path equals to other.


def device_name(self):
    return self._device_name

Name of the device that the tensor belongs to.

Returns:
(`str`) device name.


def remove_unused_links(self, used):
    unused = []
    self._execute('SELECT * FROM {}'.format(self.LINK_STATE_TABLE))
    for row in self.cursor:
        (relpath, inode, mtime) = row
        inode = self._from_sqlite(inode)
        path = os.path.join(self.root_dir, relpath)
        if (path in used):
            continue
        if (not os.path.exists(path)):
            continue
        actual_inode = get_inode(path)
        (actual_mtime, _) = get_mtime_and_size(path)
        if ((inode == actual_inode) and (mtime == actual_mtime)):
            logger.debug("Removing '{}' as unused link.".format(path))
            remove(path)
            unused.append(relpath)
    for relpath in unused:
        cmd = 'DELETE FROM {} WHERE path = "{}"'
        self._execute(cmd.format(self.LINK_STATE_TABLE, relpath))

Removes all saved links except the ones that are used.

Args:
used (list): list of used links that should not be removed.


def allow_partial(allow: Optional[bool]=True) -> ContextManager[None]:
    return thread_local.thread_local_value_scope(_TLS_ALLOW_PARTIAL, allow, None)

Returns a context manager that allows partial values in scope.

This function is thread-safe and can be nested. In the nested use case, the
allow flag of immediate parent context is effective.

Example::

@pg.members([
('x', pg.typing.Int()),
('y', pg.typing.Int())
])
class A(pg.Object):
pass

with pg.allow_partial(True):
a = A(x=1)  # Missing `y`, but OK
with pg.allow_partial(False):
a.rebind(x=pg.MISSING_VALUE)  # NOT OK
a.rebind(x=pg.MISSING_VALUE)  # OK

Args:
allow: If True, allow partial symbolic values in scope.
If False, do not allow partial symbolic values in scope even if
individual objects allow so. If None, honor object-level
`allow_partial` property.

Returns:
A context manager that allows/disallow partial symbolic values in scope.
After leaving the scope, the `allow_partial` state of individual objects
will remain intact.


def update_estimator_from_task(estimator, task_id, task_type):
    if (task_type is None):
        return
    if (task_type.lower() == 'training'):
        training_job = ("{{ ti.xcom_pull(task_ids='%s')['Training']['TrainingJobName'] }}" % task_id)
        job_name = training_job
    elif (task_type.lower() == 'tuning'):
        training_job = ("{{ ti.xcom_pull(task_ids='%s')['Tuning']['BestTrainingJob']['TrainingJobName'] }}" % task_id)
        job_name = ("{{ ti.xcom_pull(task_ids='%s')['Tuning']['TrainingJobDefinition']['StaticHyperParameters']['sagemaker_job_name'].strip('%s') }}" % (task_id, '"'))
    else:
        raise ValueError("task_type must be either 'training', 'tuning' or None.")
    estimator._current_job_name = training_job
    if isinstance(estimator, sagemaker.estimator.Framework):
        update_submit_s3_uri(estimator, job_name)

Update training job of the estimator from a task in the DAG

Args:
estimator (sagemaker.estimator.EstimatorBase): The estimator to update
task_id (str): The task id of any airflow.contrib.operators.SageMakerTrainingOperator or
airflow.contrib.operators.SageMakerTuningOperator that generates training jobs in the DAG.
task_type (str): Whether the task is from SageMakerTrainingOperator or SageMakerTuningOperator. Values can be
'training', 'tuning' or None (which means training job is not from any task).


def scale_translation(self, trans_scale_factor: float) -> Rigid:
    return self.apply_trans_fn(lambda t: t * trans_scale_factor)

Scales the translation by a constant factor.

Args:
trans_scale_factor:
The constant factor
Returns:
A transformation object with a scaled translation.


def mac_app_exists(app):

	APP_CHECK_APPLESCRIPT =

	with open('/tmp/app_check.AppleScript', 'w') as f:
		f.write(APP_CHECK_APPLESCRIPT % app)

	app_check_proc = sp.Popen(
		['osascript', '-e', '/tmp/app_check.AppleScript'])

	if app_check_proc.wait() != 0:
		return False

	else:
		return True

Check if 'app' is installed (OS X).

Check if the given applications is installed on this OS X system.

Args:
app (str): The application name.

Returns:
bool: Is the app installed or not?


def key_for_namespace(cls, namespace):
    if namespace:
        return model.Key(cls.KIND_NAME, namespace)
    else:
        return model.Key(cls.KIND_NAME, cls.EMPTY_NAMESPACE_ID)

Return the Key for a namespace.

Args:
namespace: A string giving the namespace whose key is requested.

Returns:
The Key for the namespace.


def RemoveKeywordsForName(self, name, keywords):
    data_store.DB.IndexRemoveKeywordsForName(self.urn, name, keywords)

Removes keywords for a name.

Args:
name: A name which should not be associated with some keywords anymore.
keywords: A collection of keywords.


def _verify_static_batch_size_equality(tensors, columns):
    expected_batch_size = None
    for i in range(0, len(tensors)):
        batch_size = tensor_shape.Dimension(tensor_shape.dimension_value(tensors[i].shape[0]))
        if batch_size.value is not None:
            if expected_batch_size is None:
                bath_size_column_index = i
                expected_batch_size = batch_size
            elif not expected_batch_size.is_compatible_with(batch_size):
                raise ValueError('Batch size (first dimension) of each feature must be same. Batch size of columns ({}, {}): ({}, {})'.format(columns[bath_size_column_index].name, columns[i].name, expected_batch_size, batch_size))

Verify equality between static batch sizes.

Args:
tensors: iterable of input tensors.
columns: Corresponding feature columns.

Raises:
ValueError: in case of mismatched batch sizes.


def usergroups_create(self, *, name: str, **kwargs) -> SlackResponse:

        self._validate_xoxp_token()
        kwargs.update({"name": name})
        return self.api_call("usergroups.create", json=kwargs)

Create a User Group

Args:
name (str): A name for the User Group. Must be unique among User Groups.
e.g. 'My Test Team'


def update_port_monitor(self, resource, timeout=(- 1)):
    data = resource.copy()
    if ('type' not in data):
        data['type'] = 'port-monitor'
    uri = '{}{}'.format(self.data['uri'], self.PORT_MONITOR_PATH)
    return self._helper.update(data, uri=uri, timeout=timeout)

Updates the port monitor configuration of a logical interconnect.

Args:
resource: Port monitor configuration.

Returns:
dict: Port monitor configuration.


def replaceext(filepath, new_ext):

    if new_ext and new_ext[0] != '.':
        new_ext = '.' + new_ext

    root, ext = os.path.splitext(safepath(filepath))
    return root + new_ext

Replace any existing file extension with a new one

Example::

>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'

Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is not included,
it will be added.

Returns:
Tuple[str]


def update_nsval(self, *, nsval: str=None, ns: str=None, val: str=None) -> None:
    if ((not (ns and val)) and nsval):
        (ns, val) = nsval.split(':', 1)
    elif ((not (ns and val)) and (not nsval)):
        log.error('Did not update NSArg - no ns:val or nsval provided')
    self.namespace = ns
    self.value = val

Update Namespace and valueast.

Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity


def calc_copulas(self,
                     output_file,
                     model_names=("start-time", "translation-x", "translation-y"),
                     label_columns=("Start_Time_Error", "Translation_Error_X", "Translation_Error_Y")):

        if len(self.data['train']) == 0:
            self.load_data()
        groups = self.data["train"]["member"][self.group_col].unique()
        copulas = {}
        label_columns = list(label_columns)
        for group in groups:
            print(group)
            group_data = self.data["train"]["total_group"].loc[
                self.data["train"]["total_group"][self.group_col] == group]
            group_data = group_data.dropna()
            group_data.reset_index(drop=True, inplace=True)
            copulas[group] = {}
            copulas[group]["mean"] = group_data[label_columns].mean(axis=0).values
            copulas[group]["cov"] = np.cov(group_data[label_columns].values.T)
            copulas[group]["model_names"] = list(model_names)
            del group_data
        pickle.dump(copulas, open(output_file, "w"), pickle.HIGHEST_PROTOCOL)

Calculate a copula multivariate normal distribution from the training data for each group of ensemble members.
Distributions are written to a pickle file for later use.
Args:
output_file: Pickle file
model_names: Names of the tracking models
label_columns: Names of the data columns used for labeling
Returns:


def visibility(self, value=9999.0):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError('value {} need to be of type float '
                                 'for field `visibility`'.format(value))

        self._visibility = value

Corresponds to IDD Field `visibility` This is the value for
visibility in km. (Horizontal visibility at the time indicated.)

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

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


def _resize_for_patching(self, image: np.array, target_resolution: tuple, resample, input_data_format: ChannelDimension) -> np.array:
    new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
    resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format)
    return resized_image

Resizes an image to a target resolution while maintaining aspect ratio.

Args:
image (np.array):
The input image.
target_resolution (tuple):
The target resolution (height, width) of the image.
resample (`PILImageResampling`):
Resampling filter to use if resizing the image.
input_data_format (`ChannelDimension` or `str`):
The channel dimension format of the input image.

Returns:
np.array: The resized and padded image.


def get_template_edit_url(self, template_id):
    request = self._get_request()
    return request.get((self.EMBEDDED_TEMPLATE_EDIT_URL + template_id))

Retrieves a embedded template for editing

Retrieves an embedded object containing a template url that can be opened in an iFrame.

Args:

template_id (str): The id of the template to get a signature url for

Returns:
An Embedded object


def find_next(self, *strings, **kwargs):

        start = kwargs.pop("start", None)
        keys_only = kwargs.pop("keys_only", False)
        staht = start if start is not None else self.cursor
        for start, stop in [(staht, len(self)), (0, staht)]:
            for i in range(start, stop):
                for string in strings:
                    if string in self[i]:
                        tup = (i, self[i])
                        self.cursor = i + 1
                        if keys_only: return i
                        return tup

From the editor's current cursor position find the next instance of the
given string.

Args:
strings (iterable): String or strings to search for

Returns:
tup (tuple): Tuple of cursor position and line or None if not found

Note:
This function cycles the entire editor (i.e. cursor to length of
editor to zero and back to cursor position).


def __init__(self, value: T, proxy: Optional[T]=None):
    if proxy is None:
        proxy = value
    super().__init__('constant', proxy)
    self._value = value

Initialize a constant expression.

Args:
value: The constant value to be produced by this expression.
proxy: (Optional) a proxy object with same type as `value` to use for
rapid type checking at pipeline construction time. If not provided,
`value` will be used directly.


def decode_image_tokens(self, image_tokens: torch.Tensor):
    decoded_image = self.model.vqmodel.decode(image_tokens)
    decoded_image = decoded_image.permute(0, 2, 3, 1)
    return decoded_image

Decodes generated image tokens from language model to continuous pixel values
with VQGAN module via upsampling.
Args:
image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
The tensors corresponding to the input images.


def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')):
    tuple_list = []
    if (not key_vals_dict):
        return tuple_list
    vlen = max([len(vs) for vs in itertools.chain(*key_vals_dict.values())])
    for (k, vs) in key_vals_dict.items():
        try:
            tuple_list.extend([((k + tuple(v)) + ((fill,) * (vlen - len(v)))) for v in vs])
        except TypeError:
            tuple_list.extend([(((k,) + tuple(v)) + ((fill,) * (vlen - len(v)))) for v in vs])
    return tuple_list

Convert ``key_vals_dict`` to `tuple_list``.

Args:
key_vals_dict (dict): The first parameter.
fill: a value to fill missing data

Returns:
A list of tuples


def save_publication(pub):
    _assert_obj_type(pub)
    _get_handler().store_object(pub)
    return pub.to_comm(light_request=True)

Save `pub` into database and into proper indexes.

Attr:
pub (obj): Instance of the :class:`.DBPublication`.

Returns:
obj: :class:`.DBPublication` without data.

Raises:
InvalidType: When the `pub` is not instance of :class:`.DBPublication`.
UnindexablePublication: When there is no index (property) which can be
used to index `pub` in database.


def __init__(self, watch_paths, on_changed=None, interval=1.0, recursive=True):

        if isinstance(watch_paths, basestring):
            watch_paths = [watch_paths]

        watch_paths = [os.path.abspath(path) for path in watch_paths]
        for path in watch_paths:
            if not os.path.exists(path) or not os.path.isdir(path):
                raise MissingFolderError(path)

        self.watch_paths = watch_paths
        self.interval = interval * 1000.0
        self.recursive = recursive
        self.periodic_callback = PeriodicCallback(self.check_fs_events, self.interval)
        self.on_changed = on_changed
        self.observer = Observer()
        for path in self.watch_paths:
            self.observer.schedule(
                WatcherEventHandler(self),
                path,
                self.recursive
            )
        self.started = False
        self.fs_event_queue = Queue()

Constructor.

Args:
watch_paths: A list of filesystem paths to watch for changes.
on_changed: Callback to call when one or more changes to the watch path are detected.
interval: The minimum interval at which to notify about changes (in seconds).
recursive: Should the watch path be monitored recursively for changes?


def hardware_status(self):
    stat = structs.JLinkHardwareStatus()
    res = self._dll.JLINKARM_GetHWStatus(ctypes.byref(stat))
    if (res == 1):
        raise errors.JLinkException('Error in reading hardware status.')
    return stat

Retrieves and returns the hardware status.

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

Returns:
A ``JLinkHardwareStatus`` describing the J-Link hardware.


def set_acl(self, role, users):
    acl_updates = [{'user': user, 'role': role} for user in users]
    r = fapi.update_repository_method_acl(self.namespace, self.name, self.snapshot_id, acl_updates, self.api_url)
    fapi._check_response_code(r, 200)

Set permissions for this method.

Args:
role (str): Access level
one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"}
users (list(str)): List of users to give role to


def _entry_allocated_bitmap(self, entry_number):

    index, offset = divmod(entry_number, 8)
    return bool(self._bitmap[index] & (1 << offset))

Checks if a particular index is allocated.

Args:
entry_number (int): Index to verify

Returns:
bool: True if it is allocated, False otherwise.


def expand_dims(a, axis):

    if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'):
        return a.expand_dims(axis)
    else:
        return np.expand_dims(a, axis)

Insert a new axis, corresponding to a given position in the array shape

Args:
a (array_like): Input array.
axis (int): Position (amongst axes) where new axis is to be inserted.


def fill(self, background_shape, img):
    background_shape = tuple(background_shape)
    return self._fill(background_shape, img)

Return a proper background image of background_shape, given img.

Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image


def get_display_name(self, room=None):
    if room:
        try:
            return room.members_displaynames[self.user_id]
        except KeyError:
            return self.user_id
    if (not self.displayname):
        self.displayname = self.api.get_display_name(self.user_id)
    return (self.displayname or self.user_id)

Get this user's display name.

Args:
room (Room): Optional. When specified, return the display name of the user
in this room.

Returns:
The display name. Defaults to the user ID if not set.


def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
    default_to_square = True
    if 'shortest_edge' in size:
        size = size['shortest_edge']
        default_to_square = False
    elif 'height' in size and 'width' in size:
        size = (size['height'], size['width'])
    else:
        raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
    output_size = get_resize_output_image_size(image, size=size, default_to_square=default_to_square, input_data_format=input_data_format)
    return resize(image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)

Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
resized to keep the input aspect ratio.

Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Size of the output image.
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
Resampling filter to use when resiizing the image.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.


def join(self):
    self._cluster.join()

Blocks until all the scheduled functions have finished execution.

If any previously scheduled function raises an error, `join` will fail by
raising any one of those errors, and clear the errors collected so far. If
this happens, some of the previously scheduled functions may have not been
executed. Users can call `fetch` on the returned
`tf.distribute.experimental.coordinator.RemoteValue` to inspect if they have
executed, failed, or cancelled. If some that have been cancelled need to be
rescheduled, users should call `schedule` with the function again.

When `join` returns or raises, it guarantees that there is no function that
is still being executed.

Raises:
Exception: one of the exceptions caught by the coordinator by any
previously scheduled function since the last time an error was thrown or
since the beginning of the program.


def set_tuple_shapes(self, tuple_shapes):
    if len(tuple_shapes) != self.number_of_tuple_elements:
        raise ValueError(f'tuple_shapes is {str(tuple_shapes)}, but must be a list of length {self.number_of_tuple_elements}')
    try:
        tuple_shapes = [tensor_shape.as_shape(shape) for shape in tuple_shapes]
    except (ValueError, TypeError) as e:
        raise TypeError(f'tuple_shapes is {str(tuple_shapes)}, but must be a list of elements each convertible to TensorShape: got error {str(e)}') from e
    if self._frozen:
        for frozen, updated in zip(self._tuple_shapes, tuple_shapes):
            if frozen != updated:
                raise ValueError(f'Trying to update InfeedQueue with frozen configuration with an incompatible shape. Frozen shapes are {str(self._tuple_shapes)}, updated shapes are {str(tuple_shapes)}')
    else:
        self._tuple_shapes = tuple_shapes
    self._validate()

Sets the shape of each element of the queue.

tuple_shapes must be a list of length
self.number_of_tuple_elements, and each element must be
convertible to a TensorShape.

Args:
tuple_shapes: the shapes of each queue element.

Raises:
ValueError: if tuple_shapes is not of length
self.number_of_tuple_elements.
TypeError: if an element of tuple_shapes cannot be converted to
a TensorShape.


def selection_error_control(self, form_info):

        keys, names = self.return_selected_form_items(form_info['ChannelList'])
        chosen_channels_number = len(keys)

        if form_info['new_channel'] and chosen_channels_number < 2:
            return False, _(
                u"You should choose at least two channel to merge operation at a new channel.")
        elif form_info['existing_channel'] and chosen_channels_number == 0:
            return False, _(
                u"You should choose at least one channel to merge operation with existing channel.")
        elif form_info['find_chosen_channel'] and chosen_channels_number != 1:
            return False, _(u"You should choose one channel for split operation.")

        return True, None

It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.

Args:
form_info: Channel or subscriber form from the user

Returns: True or False
error message


def unparse_range(obj):
    if isinstance(obj, (int, long)):
        return str(obj)
    if isinstance(obj, tuple):
        arg = (str(obj[0]) + '-')
        if (len(obj) > 1):
            arg += str(obj[1])
        return arg
    raise ValueError('Must be an integer or tuple')

Unparse a range argument.

Args:
obj: An article range. There are a number of valid formats; an integer
specifying a single article or a tuple specifying an article range.
If the range doesn't give a start article then all articles up to
the specified last article are included. If the range doesn't
specify a last article then all articles from the first specified
article up to the current last article for the group are included.

Returns:
The range as a string that can be used by an NNTP command.

Note: Sample valid formats.
4678
(,5234)
(4245,)
(4245, 5234)


def _scalar_operations(self, axis, scalar, func):
    if isinstance(scalar, (list, np.ndarray, pandas.Series)):
        new_index = (self.index if (axis == 0) else self.columns)

        def list_like_op(df):
            if (axis == 0):
                df.index = new_index
            else:
                df.columns = new_index
            return func(df)
        new_data = self._map_across_full_axis(axis, self._prepare_method(list_like_op))
        return self.__constructor__(new_data, self.index, self.columns)
    else:
        return self._map_partitions(self._prepare_method(func))

Handler for mapping scalar operations across a Manager.

Args:
axis: The axis index object to execute the function on.
scalar: The scalar value to map.
func: The function to use on the Manager with the scalar.

Returns:
A new QueryCompiler with updated data and new index.


def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs):
    return hooks.ExamplesPerSecondHook(every_n_steps=every_n_steps, batch_size=batch_size, warm_steps=warm_steps)

Function to get ExamplesPerSecondHook.

Args:
every_n_steps: `int`, print current and average examples per second every
N steps.
batch_size: `int`, total batch size used to calculate examples/second from
global time.
warm_steps: skip this number of steps before logging and running average.
**kwargs: a dictionary of arguments to ExamplesPerSecondHook.

Returns:
Returns a ProfilerHook that writes out timelines that can be loaded into
profiling tools like chrome://tracing.


def add_test_class(self, clazz, config=None, tests=None, name_suffix=None):
    if self._test_selector:
        cls_name = clazz.__name__
        if (cls_name, name_suffix) in self._test_selector:
            tests = self._test_selector[cls_name, name_suffix]
        elif cls_name in self._test_selector:
            tests = self._test_selector[cls_name]
        else:
            logging.info('Skipping test class %s due to CLI argument `tests`.', cls_name)
            return
    if not config:
        config = self._config
    self._runner.add_test_class(config, clazz, tests, name_suffix)

Adds a test class to the suite.

Args:
clazz: class, a Mobly test class.
config: config_parser.TestRunConfig, the config to run the class with. If
not specified, the default config passed from google3 infra is used.
tests: list of strings, names of the tests to run in this test class, in
the execution order. Or a string with prefix `re:` for full regex match
of test cases; all matched test cases will be executed; an error is
raised if no match is found.
If not specified, all tests in the class are executed.
CLI argument `tests` takes precedence over this argument.
name_suffix: string, suffix to append to the class name for reporting.
This is used for differentiating the same class executed with different
parameters in a suite.


def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    super(ArchiveResponsePayload, self).read(input_stream, kmip_version=kmip_version)
    local_stream = utils.BytearrayStream(input_stream.read(self.length))
    if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
        self._unique_identifier = primitives.TextString(tag=enums.Tags.UNIQUE_IDENTIFIER)
        self._unique_identifier.read(local_stream, kmip_version=kmip_version)
    self.is_oversized(local_stream)

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

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

Raises:
ValueError: Raised if the data attribute is missing from the
encoded payload.


def italic(self, action):

        if action =='on':
            action = '4'
        elif action=='off':
            action = '5'
        else:
            raise RuntimeError('Invalid action for function italic. Options are on and off')
        self.send(chr(27)+action)

Enable/cancel italic printing

Args:
action: Enable or disable italic printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.


def __init__(
            self,
            expr,
            grouping_column_names,
            column_names,
            grouping_column_types,
            column_types):

        self.expr = expr
        self.grouping_column_name = grouping_column_names
        self.column_names = column_names
        self.grouping_column_types = grouping_column_types
        self.column_types = column_types

        if isinstance(self.column_types, list):
            if len(self.column_types) == 1:
                column_types = self.column_types[0]
            else:
                column_types = WeldStruct(self.column_types)

        if len(self.grouping_column_types) == 1:
            grouping_column_types = self.grouping_column_types[0]
        else:
            grouping_column_types = WeldStruct(self.grouping_column_types)
        self.weld_type = WeldStruct([grouping_column_types, column_types])

Summary

Args:
expr (TYPE): Description
grouping_column_name (TYPE): Description
column_names (TYPE): Description
grouping_column_type (TYPE): Description
column_types (TYPE): Description


def __init__(self, tcex, main_type, api_type, sub_type, api_entity, owner):

        self._tcex = tcex
        self._data = {}

        self._owner = owner
        self._type = main_type
        self._api_sub_type = sub_type
        self._api_type = api_type
        self._unique_id = None
        self._api_entity = api_entity

        self._utils = TcExUtils()
        self._tc_requests = TiTcRequest(self._tcex)

Initialize Class Properties.

Args:
tcex:
main_type:
api_type:
sub_type:
api_entity:


def get(self, key):
    match = self._get_match(key=key)
    if (not match):
        return None
    return self._get_value_from_match(key=key, match=match)

Gets the value of the property of the given key.

Args:
key (str): Key of the property to look-up.


def print_projects(projects=None):
    grouped_by = {}
    if (not projects):
        print("Your selection didn't include any projects for this experiment.")
        return
    for name in projects:
        prj = projects[name]
        if (prj.GROUP not in grouped_by):
            grouped_by[prj.GROUP] = []
        grouped_by[prj.GROUP].append('{name}/{group}'.format(name=prj.NAME, group=prj.GROUP))
    for name in grouped_by:
        print('group: {0}'.format(name))
        group_projects = sorted(grouped_by[name])
        for prj in group_projects:
            prj_cls = projects[prj]
            version_str = None
            if hasattr(prj_cls, 'versions'):
                version_str = ', '.join(prj_cls.versions())
            project_id = '{0}/{1}'.format(prj_cls.NAME, prj_cls.GROUP)
            project_str = '  name: {id:<32} version: {version:<24} source: {src}'.format(id=str(project_id), version=str(prj_cls.VERSION), src=str(prj_cls.SRC_FILE))
            print(project_str)
            if prj_cls.__doc__:
                docstr = prj_cls.__doc__.strip('\n ')
                print('    description: {desc}'.format(desc=docstr))
            if version_str:
                print('    versions: {versions}'.format(versions=version_str))
        print()

Print a list of projects registered for that experiment.

Args:
exp: The experiment to print all projects for.


def _CalculateElementsDataSize(self, context):

    elements_data_size = None

    if self._HasElementsDataSize():
      elements_data_size = self._EvaluateElementsDataSize(context)

    elif self._HasNumberOfElements():
      element_byte_size = self._element_data_type_definition.GetByteSize()
      if element_byte_size is not None:
        number_of_elements = self._EvaluateNumberOfElements(context)
        elements_data_size = number_of_elements * element_byte_size

    return elements_data_size

Calculates the elements data size.

Args:
context (Optional[DataTypeMapContext]): data type map context, used to
determine the size hint.

Returns:
int: the elements data size or None if not available.


def normalize_input(data: str) -> typing.Tuple[str, typing.Set[int]]:
    chunks = data.replace('\n', utils.SEP).strip().split(utils.SEP)
    chunk_lengths = [len(chunk) for chunk in chunks]
    sep_indices = set(itertools.accumulate(chunk_lengths, lambda x, y: x + y))
    sentence = ''.join(chunks)
    return (sentence, sep_indices)

Normalizes the input to one line with separators.

Args:
data(str): Source input

Returns:
typing.Tuple[str, typing.Set[int]]: A tuple of the sentence and the
separator indices.


def delete(self, addon_id, data={}, **kwargs):
    return super(Addon, self).delete(addon_id, data, **kwargs)

Delete addon for given id

Args:
addon_id : Id for which addon object has to be deleted


def kill_all_processes(self, check_alive=True, allow_graceful=False):

        if ray_constants.PROCESS_TYPE_RAYLET in self.all_processes:
            self._kill_process_type(
                ray_constants.PROCESS_TYPE_RAYLET,
                check_alive=check_alive,
                allow_graceful=allow_graceful)

        for process_type in list(self.all_processes.keys()):
            self._kill_process_type(
                process_type,
                check_alive=check_alive,
                allow_graceful=allow_graceful)

Kill all of the processes.

Note that This is slower than necessary because it calls kill, wait,
kill, wait, ... instead of kill, kill, ..., wait, wait, ...

Args:
check_alive (bool): Raise an exception if any of the processes were
already dead.


def sample(self, nmr_samples, burnin=0, thinning=1):
    if ((not thinning) or (thinning < 1)):
        thinning = 1
    if ((not burnin) or (burnin < 0)):
        burnin = 0
    max_samples_per_batch = max((1000
    with self._logging(nmr_samples, burnin, thinning):
        if (burnin > 0):
            for (batch_start, batch_end) in split_in_batches(burnin, max_samples_per_batch):
                self._sample((batch_end - batch_start), return_output=False)
        if (nmr_samples > 0):
            outputs = []
            for (batch_start, batch_end) in split_in_batches(nmr_samples, max_samples_per_batch):
                outputs.append(self._sample((batch_end - batch_start), thinning=thinning))
            return SimpleSampleOutput(*[np.concatenate([o[ind] for o in outputs], axis=(- 1)) for ind in range(3)])

Take additional samples from the given likelihood and prior, using this sampler.

This method can be called multiple times in which the sample state is stored in between.

Args:
nmr_samples (int): the number of samples to return
burnin (int): the number of samples to discard before returning samples
thinning (int): how many sample we wait before storing a new one. This will draw extra samples such that
the total number of samples generated is ``nmr_samples * (thinning)`` and the number of samples
stored is ``nmr_samples``. If set to one or lower we store every sample after the burn in.

Returns:
SamplingOutput: the sample output object


def _select_helper(args, kwargs):
    if (len(args) > 1):
        raise TypeError('select accepts at most ONE positional argument.')
    if ((len(args) > 0) and (len(kwargs) > 0)):
        raise TypeError('select accepts EITHER a positional argument, OR keyword arguments (not both).')
    if ((len(args) == 0) and (len(kwargs) == 0)):
        raise TypeError('select requires EITHER a positional argument, OR keyword arguments.')
    if args:
        arg = args[0]
        if isinstance(arg, dict):
            selector = arg
        elif isinstance(arg, string_types):
            selector = dict(name=arg)
        elif (isinstance(arg, type) and issubclass(arg, Model)):
            selector = {'type': arg}
        else:
            raise TypeError('selector must be a dictionary, string or plot object.')
    elif ('selector' in kwargs):
        if (len(kwargs) == 1):
            selector = kwargs['selector']
        else:
            raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present")
    else:
        selector = kwargs
    return selector

Allow flexible selector syntax.

Returns:
dict


def find_sorted_task_dependencies(task, task_name, task_id):
    log.info('find_sorted_task_dependencies {} {}'.format(task_name, task_id))
    cot_input_dependencies = [_craft_dependency_tuple(task_name, task_type, task_id) for (task_type, task_id) in task['extra'].get('chainOfTrust', {}).get('inputs', {}).items()]
    upstream_artifacts_dependencies = [_craft_dependency_tuple(task_name, artifact_dict['taskType'], artifact_dict['taskId']) for artifact_dict in task.get('payload', {}).get('upstreamArtifacts', [])]
    dependencies = [*cot_input_dependencies, *upstream_artifacts_dependencies]
    dependencies = _sort_dependencies_by_name_then_task_id(dependencies)
    parent_task_id = (get_parent_task_id(task) or get_decision_task_id(task))
    parent_task_type = 'parent'
    parent_tuple = _craft_dependency_tuple(task_name, parent_task_type, parent_task_id)
    dependencies.insert(0, parent_tuple)
    log.info('found dependencies: {}'.format(dependencies))
    return dependencies

Find the taskIds of the chain of trust dependencies of a given task.

Args:
task (dict): the task definition to inspect.
task_name (str): the name of the task, for logging and naming children.
task_id (str): the taskId of the task.

Returns:
list: tuples associating dependent task ``name`` to dependent task ``taskId``.


def rabi_oscillations(sampler: sim.Sampler, qubit: devices.GridQubit, max_angle: float=(2 * np.pi), *, repetitions: int=1000, num_points: int=200) -> RabiResult:
    theta = sympy.Symbol('theta')
    circuit = circuits.Circuit.from_ops((ops.X(qubit) ** theta))
    circuit.append(ops.measure(qubit, key='z'))
    sweep = study.Linspace(key='theta', start=0.0, stop=(max_angle / np.pi), length=num_points)
    results = sampler.run_sweep(circuit, params=sweep, repetitions=repetitions)
    angles = np.linspace(0.0, max_angle, num_points)
    excited_state_probs = np.zeros(num_points)
    for i in range(num_points):
        excited_state_probs[i] = np.mean(results[i].measurements['z'])
    return RabiResult(angles, excited_state_probs)

Runs a Rabi oscillation experiment.

Rotates a qubit around the x-axis of the Bloch sphere by a sequence of Rabi
angles evenly spaced between 0 and max_angle. For each rotation, repeat
the circuit a number of times and measure the average probability of the
qubit being in the |1> state.

Args:
sampler: The quantum engine or simulator to run the circuits.
qubit: The qubit under test.
max_angle: The final Rabi angle in radians.
repetitions: The number of repetitions of the circuit for each Rabi
angle.
num_points: The number of Rabi angles.

Returns:
A RabiResult object that stores and plots the result.


def method_exists(cls, method):
    methods = cls.API_METHODS
    for key in method.split('.'):
        methods = methods.get(key)
        if (methods is None):
            break
    if isinstance(methods, str):
        logger.debug('%r: %r', method, methods)
        return True
    return False

Whether a given method exists in the known API.

Arguments:
method (:py:class:`str`): The name of the method.

Returns:
:py:class:`bool`: Whether the method is in the known API.


def _definition_from_example(example):

        assert isinstance(example, dict)

        def _has_simple_type(value):
            accepted = (str, int, float, bool)
            return isinstance(value, accepted)

        definition = {
            'type': 'object',
            'properties': {},
        }
        for key, value in example.items():
            if not _has_simple_type(value):
                raise Exception("Not implemented yet")
            ret_value = None
            if isinstance(value, str):
                ret_value = {'type': 'string'}
            elif isinstance(value, int):
                ret_value = {'type': 'integer', 'format': 'int64'}
            elif isinstance(value, float):
                ret_value = {'type': 'number', 'format': 'double'}
            elif isinstance(value, bool):
                ret_value = {'type': 'boolean'}
            else:
                raise Exception("Not implemented yet")
            definition['properties'][key] = ret_value

        return definition

Generates a swagger definition json from a given example
Works only for simple types in the dict

Args:
example: The example for which we want a definition
Type is DICT

Returns:
A dict that is the swagger definition json


def get_integrated_diff(self, ind, radius, nbins=1):
    if (not self.is_spin_polarized):
        radii = [((radius / nbins) * (i + 1)) for i in range(nbins)]
        data = np.zeros((nbins, 2))
        data[(:, 0)] = radii
        return data
    struct = self.structure
    a = self.dim
    if ((ind not in self._distance_matrix) or (self._distance_matrix[ind]['max_radius'] < radius)):
        coords = []
        for (x, y, z) in itertools.product(*[list(range(i)) for i in a]):
            coords.append([(x / a[0]), (y / a[1]), (z / a[2])])
        sites_dist = struct.lattice.get_points_in_sphere(coords, struct[ind].coords, radius)
        self._distance_matrix[ind] = {'max_radius': radius, 'data': np.array(sites_dist)}
    data = self._distance_matrix[ind]['data']
    inds = (data[(:, 1)] <= radius)
    dists = data[(inds, 1)]
    data_inds = np.rint((np.mod(list(data[(inds, 0)]), 1) * np.tile(a, (len(dists), 1)))).astype(int)
    vals = [self.data['diff'][(x, y, z)] for (x, y, z) in data_inds]
    (hist, edges) = np.histogram(dists, bins=nbins, range=[0, radius], weights=vals)
    data = np.zeros((nbins, 2))
    data[(:, 0)] = edges[1:]
    data[(:, 1)] = [(sum(hist[0:(i + 1)]) / self.ngridpts) for i in range(nbins)]
    return data

Get integrated difference of atom index ind up to radius. This can be
an extremely computationally intensive process, depending on how many
grid points are in the VolumetricData.

Args:
ind (int): Index of atom.
radius (float): Radius of integration.
nbins (int): Number of bins. Defaults to 1. This allows one to
obtain the charge integration up to a list of the cumulative
charge integration values for radii for [radius/nbins,
2 * radius/nbins, ....].

Returns:
Differential integrated charge as a np array of [[radius, value],
...]. Format is for ease of plotting. E.g., plt.plot(data[:,0],
data[:,1])


def get_cpu_isa_version():
    key = 'cpu_isa'
    out, err = run_shell_cmd(cmds_all[PLATFORM.lower()][key])
    if err and FLAGS.debug:
        print('Error in detecting supported ISA:\n %s' % str(err))
    ret_val = out
    required_isa = ['avx', 'avx2', 'avx512f', 'sse4', 'sse4_1']
    found = []
    missing = []
    for isa in required_isa:
        for sys_isa in ret_val.split(b' '):
            if isa == sys_isa:
                if isa not in found:
                    found.append(isa)
    missing = list(set(required_isa) - set(found))
    return (found, missing)

Retrieves all Instruction Set Architecture(ISA) available.

Required ISA(s): 'avx', 'avx2', 'avx512f', 'sse4', 'sse4_1'

Returns:
Tuple
(list of available ISA, list of missing ISA)


def __init__(self, action):
    _check_type(action, str)
    self.action = action

Constructor.

Args:
action: (`OnSessionInitAction`) Debugger action to take on session init.


def price(self, market: pmd.ProcessedMarketData, name: Optional[str]=None) -> types.FloatTensor:
    name = name or self._name + '_price'
    with tf.name_scope(name):
        discount_curve = get_discount_curve(self._discount_curve_type, market, self._mask)
        discount_factors = discount_curve.discount_factor(self._coupon_end_dates)
        _, cashflows = self.cashflows(market, past_fixing=self._past_fixing)
        cashflow_pvs = cashflows * discount_factors
        return tf.math.reduce_sum(cashflow_pvs, axis=1)

Returns the present value of the stream on the valuation date.

Args:
market: An instance of `ProcessedMarketData`.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.

Returns:
A `Tensor` of shape `batch_shape`  containing the modeled price of each
stream based on the input market data.


def volumes(self):
    if (not self.__volumes):
        self.__volumes = Volumes(self.__connection)
    return self.__volumes

Gets the Volumes API client.

Returns:
Volumes:


def parse_config_for_selected_keys(content, keys):
    config_items = {key: None for key in keys}
    if (not content):
        return (config_items, content)
    stripped = content.strip()
    if (len(stripped) == 0):
        return ({}, None)
    elif (stripped[0] == '{'):
        config = json.loads(content)
    else:
        config = yaml.load(content)
    if (not isinstance(config, dict)):
        raise ValueError('Invalid config.')
    for key in keys:
        config_items[key] = config.pop(key, None)
    if (not config):
        return (config_items, None)
    if (stripped[0] == '{'):
        content_out = json.dumps(config, indent=4)
    else:
        content_out = yaml.dump(config, default_flow_style=False)
    return (config_items, content_out)

Parse a config from a magic cell body for selected config keys.

For example, if 'content' is:
config_item1: value1
config_item2: value2
config_item3: value3
and 'keys' are: [config_item1, config_item3]

The results will be a tuple of
1. The parsed config items (dict): {config_item1: value1, config_item3: value3}
2. The remaining content (string): config_item2: value2

Args:
content: the input content. A string. It has to be a yaml or JSON string.
keys: a list of keys to retrieve from content. Note that it only checks top level keys
in the dict.

Returns:
A tuple. First is the parsed config including only selected keys. Second is
the remaining content.

Raises:
Exception if the content is not a valid yaml or JSON string.


def _is_txn_to_replay(self, txn_id, possible_successor, already_seen):
    is_successor = self._is_predecessor_of_possible_successor(txn_id, possible_successor)
    in_different_batch = (not self._is_in_same_batch(txn_id, possible_successor))
    has_not_been_seen = (possible_successor not in already_seen)
    return (is_successor and in_different_batch and has_not_been_seen)

Decide if possible_successor should be replayed.

Args:
txn_id (str): Id of txn in failed batch.
possible_successor (str): Id of txn to possibly replay.
already_seen (list): A list of possible_successors that have
been replayed.

Returns:
(bool): If the possible_successor should be replayed.


def __init__(self, resolver, mets_url, src_dir=None, skip=None, download=False, page_strictness='strict'):

        self.report = ValidationReport()
        self.skip = skip if skip else []
        log.debug('resolver=%s mets_url=%s src_dir=%s', resolver, mets_url, src_dir)
        self.resolver = resolver
        self.mets_url = mets_url
        self.download = download
        self.page_strictness = page_strictness

        self.src_dir = src_dir
        if mets_url is None and src_dir is not None:
            mets_url = '%s/mets.xml' % src_dir
        self.workspace = None
        self.mets = None

Construct a new WorkspaceValidator.

Args:
resolver (Resolver):
mets_url (string):
src_dir (string):
skip (list):
download (boolean):
page_strictness ("strict"|"lax"|"fix"|"off"):


def _create_conversion_trie(strict):
    t = pygtrie.CharTrie()
    for (beta, uni) in _map.BETACODE_MAP.items():
        if strict:
            t[beta] = uni
        else:
            diacritics = beta[1:]
            perms = itertools.permutations(diacritics)
            for perm in perms:
                perm_str = (beta[0] + ''.join(perm))
                t[perm_str.lower()] = uni
                t[perm_str.upper()] = uni
    return t

Create the trie for betacode conversion.

Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.

Returns:
The trie for conversion.


def __init__(self, item_type=None, min_length=None, max_length=None, empty=True):

        super(TupleTypeChecker, self).__init__(
            iter_type=tuple, item_type=item_type, min_length=min_length, max_length=max_length, empty=empty
        )

Initialization method.

Args:
item_type (type): the type of the items inside the tuple.
min_length (int): minimum length of the tuple (included).
max_length (int): maximum length of the tuple (included).
empty (bool): whether empty tuple is allowed.


def _get_attributes(self):
    return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())

Return a generator for instance and class attribute.

.. code-block:: python3

for instance_attribute, class_attribute in self._get_attributes():
print("Instance Attribute: {}".format(instance_attribute))
print("Class Attribute: {}".format(class_attribute))

Returns:
generator: Tuples with instance attribute and class attribute


def _get_var_info(var, prev_tensor_name=None):
    if checkpoint_utils._is_variable(var):
        current_var_name = _infer_var_name([var])
    elif isinstance(var, list) and all((checkpoint_utils._is_variable(v) for v in var)):
        current_var_name = _infer_var_name(var)
    elif isinstance(var, variables_lib.PartitionedVariable):
        current_var_name = _infer_var_name([var])
        var = var._get_variable_list()
    else:
        raise TypeError('var MUST be one of the following: a Variable, list of Variable or PartitionedVariable, but is {}'.format(type(var)))
    if not prev_tensor_name:
        prev_tensor_name = current_var_name
    return (prev_tensor_name, var)

Helper method for standarizing Variable and naming.

Args:
var: Current graph's variable that needs to be warm-started (initialized).
Can be either of the following: (i) `Variable` (ii) `ResourceVariable`
(iii) list of `Variable`: The list must contain slices of the same larger
variable. (iv) `PartitionedVariable`
prev_tensor_name: Name of the tensor to lookup in provided `prev_ckpt`. If
None, we lookup tensor with same name as given `var`.

Returns:
A tuple of the Tensor name and var.


class ConvNextStage(nn.Module):

    def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
        super().__init__()
        if in_channels != out_channels or stride > 1:
            self.downsampling_layer = nn.Sequential(ConvNextLayerNorm(in_channels, eps=1e-06, data_format='channels_first'), nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride))
        else:
            self.downsampling_layer = nn.Identity()
        drop_path_rates = drop_path_rates or [0.0] * depth
        self.layers = nn.Sequential(*[ConvNextLayer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)])

    def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
        hidden_states = self.downsampling_layer(hidden_states)
        hidden_states = self.layers(hidden_states)
        return hidden_states

ConvNeXT stage, consisting of an optional downsampling layer + multiple residual blocks.

Args:
config ([`ConvNextConfig`]): Model configuration class.
in_channels (`int`): Number of input channels.
out_channels (`int`): Number of output channels.
depth (`int`): Number of residual blocks.
drop_path_rates(`List[float]`): Stochastic depth rates for each layer.


def allclose_up_to_global_phase(
        a: np.ndarray,
        b: np.ndarray,
        *,
        rtol: float = 1.e-5,
        atol: float = 1.e-8,
        equal_nan: bool = False
) -> bool:

    a, b = transformations.match_global_phase(a, b)

    return np.allclose(a=a, b=b, rtol=rtol, atol=atol, equal_nan=equal_nan)

Determines if a ~= b * exp(i t) for some t.

Args:
a: A numpy array.
b: Another numpy array.
rtol: Relative error tolerance.
atol: Absolute error tolerance.
equal_nan: Whether or not NaN entries should be considered equal to
other NaN entries.


def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:

        self.logger.info(' IDENT %s as %s', service_name, source)
        self.messaging._address_map[service_name] = source

Perform identification of a service to a binary representation.

Args:
service_name: human readable name for service
source: zmq representation for the socket source


def add_mount_point(self, path, total_size=None):
    path = self.absnormpath(path)
    if (path in self.mount_points):
        self.raise_os_error(errno.EEXIST, path)
    self._last_dev += 1
    self.mount_points[path] = {'idev': self._last_dev, 'total_size': total_size, 'used_size': 0}
    root_dir = (self.root if (path == self.root.name) else self.create_dir(path))
    root_dir.st_dev = self._last_dev
    return self.mount_points[path]

Add a new mount point for a filesystem device.
The mount point gets a new unique device number.

Args:
path: The root path for the new mount path.

total_size: The new total size of the added filesystem device
in bytes. Defaults to infinite size.

Returns:
The newly created mount point dict.

Raises:
OSError: if trying to mount an existing mount point again.


def embedding_lookup(self, features: Any, weights: Optional[Any]=None) -> Any:
    return cpu_embedding_lookup(features, weights, self.embedding_tables, self._feature_config)

Apply standard lookup ops on CPU.

Args:
features: A nested structure of `tf.Tensor`s, `tf.SparseTensor`s or
`tf.RaggedTensor`s, with the same structure as `feature_config`. Inputs
will be downcast to `tf.int32`. Only one type out of `tf.SparseTensor`
or `tf.RaggedTensor` is supported per call.
weights: If not `None`, a nested structure of `tf.Tensor`s,
`tf.SparseTensor`s or `tf.RaggedTensor`s, matching the above, except
that the tensors should be of float type (and they will be downcast to
`tf.float32`). For `tf.SparseTensor`s we assume the `indices` are the
same for the parallel entries from `features` and similarly for
`tf.RaggedTensor`s we assume the row_splits are the same.

Returns:
A nested structure of Tensors with the same structure as input features.


def get_event_from_name(self, event_name):

        return next((e for e in self.events if e.name == event_name), None)

Return an event from a name
Args:
event_name (str): name of the event
Returns:
Event


def _default_tolerance(dtype):
    if dtype == np.float16:
        return 0.005
    elif dtype in (np.float32, np.complex64):
        return 0.001
    elif dtype in (np.float64, np.complex128):
        return 1e-05
    else:
        return None

Returns a sensible default tolerance for comparing results of a given type.

Args:
dtype: A datatype.


def set_property(self, name, value, update_session=True):

        if type(value) == datetime:
            value = value.isoformat()
        else:
            value = value

        try:
            prop = self.get_property(name)
            if prop.value == value:
                return False

            prop.value = value

        except AttributeError:
            prop = ResourceProperty()
            prop.resource_id = self.id
            prop.name = name
            prop.value = value

        if update_session:
            db.session.add(prop)

        return True

Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if
there were no changes to the value of the property.

Args:
name (str): Name of the property to create or update
value (any): Value of the property. This can be any type of JSON serializable data
update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True

Returns:
`bool`


def in_coord_list(coord_list, coord, atol=1e-08):
    return (len(find_in_coord_list(coord_list, coord, atol=atol)) > 0)

Tests if a particular coord is within 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:
True if coord is in the coord list.


def load_flag_values(self, flags=None):
    if (flags is None):
        flags = self._flags
    for keyval in flags.config_value:
        (k, v) = keyval.split('=', 1)
        v = (self._modules['yaml'].load(v) if isinstance(v, str) else v)
        k = (k.decode() if isinstance(k, bytes) else k)
        v = (v.decode() if isinstance(v, bytes) else v)
        self._flag_values.setdefault(k, v)

Load flag values given from command line flags.

Args:
flags: An argparse Namespace containing the command line flags.


def intersect_curves(nodes1, nodes2):
    nodes1 = _curve_helpers.full_reduce(nodes1)
    nodes2 = _curve_helpers.full_reduce(nodes2)
    (_, num_nodes1) = nodes1.shape
    (_, num_nodes2) = nodes2.shape
    swapped = False
    if (num_nodes1 > num_nodes2):
        (nodes1, nodes2) = (nodes2, nodes1)
        swapped = True
    coeffs = normalize_polynomial(to_power_basis(nodes1, nodes2))
    if np.all((coeffs == 0.0)):
        raise NotImplementedError(_COINCIDENT_ERR)
    _check_non_simple(coeffs)
    t_vals = roots_in_unit_interval(coeffs)
    final_s = []
    final_t = []
    for t_val in t_vals:
        ((x_val,), (y_val,)) = _curve_helpers.evaluate_multi(nodes2, np.asfortranarray([t_val]))
        s_val = locate_point(nodes1, x_val, y_val)
        if (s_val is not None):
            _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t)
    result = np.zeros((2, len(final_s)), order='F')
    if swapped:
        (final_s, final_t) = (final_t, final_s)
    result[(0, :)] = final_s
    result[(1, :)] = final_t
    return result

r"""Intersect two parametric B |eacute| zier curves.

Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
nodes2 (numpy.ndarray): The nodes in the second curve.

Returns:
numpy.ndarray: ``2 x N`` array of intersection parameters.
Each row contains a pair of values :math:`s` and :math:`t`
(each in :math:`\left[0, 1\right]`) such that the curves
intersect: :math:`B_1(s) = B_2(t)`.

Raises:
NotImplementedError: If the "intersection polynomial" is
all zeros -- which indicates coincident curves.


def time_to_jump( self ):

        k_tot = rate_prefactor * np.sum( self.p )
        return -( 1.0 / k_tot ) * math.log( random.random() )

The timestep until the next jump.

Args:
None

Returns:
(Float): The timestep until the next jump.


def find(self, package, **kwargs):

        if not exists(package):
            return None
        name, path = None, None
        enforce_init = kwargs.pop('enforce_init', True)
        if isdir(package):
            if isfile(join(package, '__init__.py')) or not enforce_init:
                name, path = basename(package), package
        elif isfile(package) and package.endswith('.py'):
            name, path = splitext(basename(package))[0], package
        if name and path:
            return PackageSpec(name, path)
        return None

Find method.

Args:
package (str): package to find.
**kwargs (): additional keyword arguments.

Returns:
PackageSpec: the PackageSpec corresponding to the package, or None.


def server_hardware(self):
    if (not self.__server_hardware):
        self.__server_hardware = ServerHardware(self.__connection)
    return self.__server_hardware

Gets the ServerHardware API client.

Returns:
ServerHardware:


def metamodel_from_str(lang_desc, metamodel=None, **kwargs):

    if not metamodel:
        metamodel = TextXMetaModel(**kwargs)

    language_from_str(lang_desc, metamodel)

    return metamodel

Creates a new metamodel from the textX description given as a string.

Args:
lang_desc(str): A textX language description.
metamodel(TextXMetaModel): A metamodel that should be used.
other params: See TextXMetaModel.


def _handle_deferred_dependencies(self, name, trackable):
    self._maybe_initialize_trackable()
    trackable._maybe_initialize_trackable()
    deferred_dependencies_list = self._deferred_dependencies.pop(name, ())
    for checkpoint_position in sorted(deferred_dependencies_list, key=lambda restore: restore.checkpoint.restore_uid, reverse=True):
        checkpoint_position.restore(trackable)
    for name_based_restore in sorted(self._self_name_based_restores, key=lambda checkpoint: checkpoint.restore_uid, reverse=True):
        trackable._name_based_attribute_restore(name_based_restore)

Pop and load any deferred checkpoint restores into `trackable`.

This method does not add a new dependency on `trackable`, but it does
check if any outstanding/deferred dependencies have been queued waiting for
this dependency to be added (matched based on `name`). If so,
`trackable` and its dependencies are restored. The restorations are
considered fulfilled and so are deleted.

`_track_trackable` is more appropriate for adding a
normal/unconditional dependency, and includes handling for deferred
restorations. This method allows objects such as `Optimizer` to use the same
restoration logic while managing conditional dependencies themselves, by
overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the
object's dependencies based on the context it is saved/restored in (a single
optimizer instance can have state associated with multiple graphs).

Args:
name: The name of the dependency within this object (`self`), used to
match `trackable` with values saved in a checkpoint.
trackable: The Trackable object to restore (inheriting from `Trackable`).


def seq(self, value):

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

The seq property.

Args:
value (string). the property value.


def sample_point(input_features: torch.Tensor, point_coordinates: torch.Tensor, add_dim=False, **kwargs) -> torch.Tensor:
    if point_coordinates.dim() == 3:
        add_dim = True
        point_coordinates = point_coordinates.unsqueeze(2)
    point_features = torch.nn.functional.grid_sample(input_features, 2.0 * point_coordinates - 1.0, **kwargs)
    if add_dim:
        point_features = point_features.squeeze(3)
    return point_features

A wrapper around `torch.nn.functional.grid_sample` to support 3D point_coordinates tensors.

Args:
input_features (`torch.Tensor` of shape (batch_size, channels, height, width)):
A tensor that contains features map on a height * width grid
point_coordinates (`torch.Tensor` of shape (batch_size, num_points, 2) or (batch_size, grid_height, grid_width,:
2)):
A tensor that contains [0, 1] * [0, 1] normalized point coordinates
add_dim (`bool`):
boolean value to keep track of added dimension

Returns:
point_features (`torch.Tensor` of shape (batch_size, channels, num_points) or (batch_size, channels,
height_grid, width_grid):
A tensor that contains features for points in `point_coordinates`.


def receive_datagram(self, data, address):

        if not self.app:
            logger.debug("Packet received", address, data)
            return False

        try:
            response = self.app.handle_message(data, address)
        except Exception as err:
            logger.error("Error processing message from " + str(address) +
                          ":" + str(data))
            logger.error(traceback.format_exc())
            return False

        if response:
            self.send_datagram(response, address)

Executes when UDP data has been received and sends the packet data
to our app to process the request.

Args:
data (str): The raw serialized packet data received.
address (tuple): The address and port of the origin of the received
packet. E.g. (address, port).

Returns:
None


def ensure_image_is_hex(input_path):
    family = utilities.get_family('module_settings.json')
    target = family.platform_independent_target()
    build_dir = target.build_dirs()['build']
    if (platform.system() == 'Windows'):
        env = Environment(tools=['mingw'], ENV=os.environ)
    else:
        env = Environment(tools=['default'], ENV=os.environ)
    input_path = str(input_path)
    image_name = os.path.basename(input_path)
    (root, ext) = os.path.splitext(image_name)
    if (len(ext) == 0):
        raise BuildError('Unknown file format or missing file extension in ensure_image_is_hex', file_name=input_path)
    file_format = ext[1:]
    if (file_format == 'hex'):
        return input_path
    if (file_format == 'elf'):
        new_file = os.path.join(build_dir, (root + '.hex'))
        if (new_file not in CONVERTED_HEX_FILES):
            env.Command(new_file, input_path, action=Action('arm-none-eabi-objcopy -O ihex $SOURCE $TARGET', 'Creating intel hex file from: $SOURCE'))
            CONVERTED_HEX_FILES.add(new_file)
        return new_file
    raise BuildError('Unknown file format extension in ensure_image_is_hex', file_name=input_path, extension=file_format)

Return a path to a hex version of a firmware image.

If the input file is already in hex format then input_path
is returned and nothing is done.  If it is not in hex format
then an SCons action is added to convert it to hex and the
target output file path is returned.

A cache is kept so that each file is only converted once.

Args:
input_path (str): A path to a firmware image.

Returns:
str: The path to a hex version of input_path, this may
be equal to input_path if it is already in hex format.


def __init__(self, recipe=None, project=None, user=None, service=None, client=None, filepath=None, key=None, verbose=False, trace_print=False, trace_file=False):
    starthinker_trace_start(trace_print, trace_file)
    self.recipe = recipe or {}
    self.verbose = verbose
    self.filepath = filepath
    if 'setup' not in self.recipe:
        self.recipe['setup'] = {}
    if 'auth' not in self.recipe['setup']:
        self.recipe['setup']['auth'] = {}
    if service:
        self.recipe['setup']['auth']['service'] = service
    if client:
        self.recipe['setup']['auth']['client'] = client
    if user:
        self.recipe['setup']['auth']['user'] = user
    if project:
        self.recipe['setup']['id'] = project
    if key:
        self.recipe['setup']['key'] = key
    self.project = self.recipe['setup'].get('project', self.recipe['setup'].get('id'))
    self.key = self.recipe['setup'].get('key')
    self.timezone = ZoneInfo(self.recipe['setup'].get('timezone', 'America/Los_Angeles'))
    self.now = datetime.now(self.timezone)
    self.date = self.now.date()
    self.hour = self.now.hour
    if self.verbose:
        print('DATE:', self.now.date())
        print('HOUR:', self.now.hour)

Used in StarThinker scripts as programmatic entry point.

Args:
* recipe: (dict) JSON object representing the recipe
* project: (string) See module description.
* user: (string) See module description.
* service: (string) See module description.
* client: (string) See module description.
* key: (string) See module description.
* verbose: (boolean) See module description.
* trace_print: (boolean) True if writing execution trace to stdout.
* trace_file: (boolean) True if writing execution trace to file.
* args: (dict) dictionary of arguments (used with argParse).

Returns:
Nothing.


def get_selector(self, name):
    try:
        return self.matcher.by_name[name]
    except (AttributeError, KeyError):
        if (self.base is not None):
            return self.base.get_selector(name)
        else:
            raise KeyError("No selector found for style '{}'".format(name))

Find a selector mapped to a style in this or a base style sheet.

Args:
name (str): a style name

Returns:
:class:`.Selector`: the selector mapped to the style `name`

Raises:
KeyError: if the style `name` was not found in this or a base
style sheet


def read_samples(self, sr=None, offset=0, duration=None):
    read_duration = self.duration
    if ((offset > 0) and (read_duration is not None)):
        read_duration -= offset
    if (duration is not None):
        if (read_duration is None):
            read_duration = duration
        else:
            read_duration = min(duration, read_duration)
    return self.track.read_samples(sr=sr, offset=(self.start + offset), duration=read_duration)

Read the samples of the utterance.

Args:
sr (int): If None uses the sampling rate given by the track,
otherwise resamples to the given sampling rate.
offset (float): Offset in seconds to read samples from.
duration (float): If not ``None`` read only this
number of seconds in maximum.

Returns:
np.ndarray: A numpy array containing the samples
as a floating point (numpy.float32) time series.


def ip_network(address, strict=True):

    try:
        return IPv4Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    try:
        return IPv6Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
                     address)

Take an IP string/int and return an object of the correct type.

Args:
address: A string or integer, the IP network.  Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.

Returns:
An IPv4Network or IPv6Network object.

Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. Or if the network has host bits set.


def __init__(self, field=None):

        super().__init__(action_type=ActionType.OFPAT_SET_FIELD)
        self.field = OxmTLV() if field is None else field

Create a ActionSetField with the optional parameters below.

Args:
length (int): length padded to 64 bits, followed by exactly
oxm_len bytes containing a single OXM TLV, then
exactly ((oxm_len + 4) + 7)/8*8 - (oxm_len + 4)
(between 0 and 7) bytes of all-zero bytes
field (:class:`OxmTLV`): OXM field and value.


def sample(self, n):

    total = bq.Query('select count(*) from %s' %
                     self._get_source()).execute().result()[0].values()[0]
    if n > total:
      raise ValueError('sample larger than population')
    sampling = bq.Sampling.random(percent=n * 100.0 / float(total))
    if self._query is not None:
      source = self._query
    else:
      source = 'SELECT * FROM `%s`' % self._table
    sample = bq.Query(source).execute(sampling=sampling).result()
    df = sample.to_dataframe()
    return df

Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will
incur cost.

Args:
n: number of sampled counts. Note that the number of counts returned is approximated.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows.


def UpdateBudget(self, client_customer_id, budget_id, micro_amount,
                   delivery_method):

    self.client.SetClientCustomerId(client_customer_id)
    operations = [{
        'operator': 'SET',
        'operand': {
            'budgetId': budget_id,
            'amount': {
                'microAmount': micro_amount
            },
            'deliveryMethod': delivery_method
        }
    }]
    self.client.GetService('BudgetService').mutate(operations)

Update a Budget with the given budgetId.

Args:
client_customer_id: str Client Customer Id used to update Budget.
budget_id: str Id of the budget to be updated.
micro_amount: str New value for the microAmount field.
delivery_method: str New value for the deliveryMethod field.


def _convert_row_partition(cls, partition, name, dtype=None, dtype_hint=None):
    if dtype_hint is None:
        dtype_hint = dtypes.int64
    if isinstance(partition, np.ndarray) and partition.dtype == np.int32 and (dtype is None):
        partition = ops.convert_to_tensor(partition, name=name)
    else:
        partition = tensor_conversion.convert_to_tensor_v2(partition, dtype_hint=dtype_hint, dtype=dtype, name=name)
    if partition.dtype not in (dtypes.int32, dtypes.int64):
        raise ValueError('%s must have dtype int32 or int64' % name)
    return partition

Converts `partition` to Tensors.

Args:
partition: A row-partitioning tensor for the `RowPartition` being
constructed.  I.e., one of: row_splits, row_lengths, row_starts,
row_limits, value_rowids, uniform_row_length.
name: The name of the row-partitioning tensor.
dtype: Optional dtype for the RowPartition. If missing, the type
is inferred from the type of `uniform_row_length`, dtype_hint,
or tf.int64.
dtype_hint: Optional dtype for the RowPartition, used when dtype
is None. In some cases, a caller may not have a dtype in mind when
converting to a tensor, so dtype_hint can be used as a soft preference.
If the conversion to `dtype_hint` is not possible, this argument has no
effect.

Returns:
A tensor equivalent to partition.

Raises:
ValueError: if dtype is not int32 or int64.


def get_value_by_row_col(self, row, col):

        if row < 0 or row >= self.nRows or col < 0 or col >= self.nCols:
            raise ValueError("The row or col must be >=0 and less than "
                             "nRows (%d) or nCols (%d)!" % (self.nRows, self.nCols))
        else:
            value = self.data[int(round(row))][int(round(col))]
            if value == self.noDataValue:
                return None
            else:
                return value

Get raster value by (row, col).

Args:
row: row number.
col: col number.

Returns:
raster value, None if the input are invalid.


def create_local_scope_from_def_args(self, call_args, def_args, line_number, saved_function_call_index):
    for i in range(len(call_args)):
        def_arg_local_name = def_args[i]
        def_arg_temp_name = ((('temp_' + str(saved_function_call_index)) + '_') + def_args[i])
        local_scope_node = RestoreNode(((def_arg_local_name + ' = ') + def_arg_temp_name), def_arg_local_name, [def_arg_temp_name], line_number=line_number, path=self.filenames[(- 1)])
        self.nodes[(- 1)].connect(local_scope_node)
        self.nodes.append(local_scope_node)

Create the local scope before entering the body of a function call.

Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.

Note: We do not need a connect_if_allowed because of the
preceding call to save_def_args_in_temp.


def _ScanFileSystem(self, scan_node, base_path_specs):

    if not scan_node or not scan_node.path_spec:
      raise errors.ScannerError('Invalid or missing file system scan node.')

    file_system = resolver.Resolver.OpenFileSystem(scan_node.path_spec)
    if not file_system:
      return

    try:
      path_resolver = windows_path_resolver.WindowsPathResolver(
          file_system, scan_node.path_spec.parent)

      if self._ScanFileSystemForWindowsDirectory(path_resolver):
        base_path_specs.append(scan_node.path_spec)

    finally:
      file_system.Close()

Scans a file system scan node for file systems.

This method checks if the file system contains a known Windows directory.

Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.

Raises:
ScannerError: if the scan node is invalid.


def _WriteIfcfg(self, interfaces, logger):
    for interface in interfaces:
        interface_config = os.path.join(self.network_path, ('ifcfg-%s' % interface))
        interface_content = ['
        with open(interface_config, 'w') as interface_file:
            interface_file.write('\n'.join(interface_content))
        logger.info('Created ifcfg file for interface %s.', interface)

Write ifcfg files for multi-NIC support.

Overwrites the files. This allows us to update ifcfg-* in the future.
Disable the network setup to override this behavior and customize the
configurations.

Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.


def run_command(self, command, arg=None, is_eval=False, member_id=None):
    logger.debug('run_command({command}, {arg}, {is_eval}, {member_id})'.format(**locals()))
    mode = ((is_eval and 'eval') or 'command')
    hostname = None
    if isinstance(member_id, int):
        hostname = self.member_id_to_host(member_id)
    result = getattr(self.connection(hostname=hostname).admin, mode)(command, arg)
    logger.debug('command result: {result}'.format(result=result))
    return result

run command on replica set
if member_id is specified command will be execute on this server
if member_id is not specified command will be execute on the primary

Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
member_id - member id

return command's result


def _GetDaysPerMonth(self, year, month):
    if (month not in range(1, 13)):
        raise ValueError('Month value out of bounds.')
    days_per_month = self._DAYS_PER_MONTH[(month - 1)]
    if ((month == 2) and self._IsLeapYear(year)):
        days_per_month += 1
    return days_per_month

Retrieves the number of days in a month of a specific year.

Args:
year (int): year e.g. 1970.
month (int): month, where 1 represents January.

Returns:
int: number of days in the month.

Raises:
ValueError: if the month value is out of bounds.


def _hexvalue_to_hsv(hexvalue):

        h = int(hexvalue[7:10], 16) / 360
        s = int(hexvalue[10:12], 16) / 255
        v = int(hexvalue[12:14], 16) / 255

        return (h, s, v)

Converts the hexvalue used by tuya for colour representation into
an HSV value.

Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()


def zoom_blur(x, severity=1):
    c = [np.arange(1, 1.11, 0.01), np.arange(1, 1.16, 0.01), np.arange(1, 1.21, 0.02), np.arange(1, 1.26, 0.02), np.arange(1, 1.31, 0.03)][(severity - 1)]
    x = (np.array(x) / 255.0).astype(np.float32)
    out = np.zeros_like(x)
    for zoom_factor in c:
        out += clipped_zoom(x, zoom_factor)
    x = ((x + out) / (len(c) + 1))
    x_clip = (np.clip(x, 0, 1) * 255)
    return around_and_astype(x_clip)

Zoom blurring to images.

Applying zoom blurring to images by zooming the central part of the images.

Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.

Returns:
numpy array, image with uint8 pixels in [0,255]. Applied zoom blur.


def get_shreds(self, feature_extractors, sheet_name):
    if (self._shreds is None):
        shreds = []
        (_, contours, _) = cv2.findContours(self._foreground_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for (i, contour) in enumerate(contours):
            shred = self._make_shred(contour, i, feature_extractors, sheet_name)
            if (shred is not None):
                shreds.append(shred)
        self._shreds = shreds
    return self._shreds

Detects shreds in the current sheet and constructs Shred instances.

Caches the results for further invocations.

Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attributes.

Returns:
list of Shred instances.


def get_wells(self, uwis=None):
    if (uwis is None):
        return Project(self.__list)
    return Project([w for w in self if (w.uwi in uwis)])

Returns a new Project with only the wells named by UWI.

Args:
uwis (list): list or tuple of UWI strings.

Returns:
project.


def get_collection(self, name, scope=None) -> list[Any]:
    with self._lock:
        collection = self._collections.get(name, None)
        if collection is None:
            return []
        if scope is None:
            return list(collection)
        else:
            c = []
            regex = re.compile(scope)
            for item in collection:
                try:
                    if regex.match(item.name):
                        c.append(item)
                except AttributeError:
                    pass
            return c

Returns a list of values in the collection with the given `name`.

This is different from `get_collection_ref()` which always returns the
actual collection list if it exists in that it returns a new list each time
it is called.

Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.

Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.


def add_input(self, input_):

        if not isinstance(input_, Input):
            raise TypeError('`input_` must be a Input instance')
        self.inputs.append(input_)

Adds an input to a Transaction's list of inputs.

Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`): An Input to be added to the Transaction.


def swo_flush(self, num_bytes=None):

        if num_bytes is None:
            num_bytes = self.swo_num_bytes()

        buf = ctypes.c_uint32(num_bytes)
        res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH,
                                             ctypes.byref(buf))
        if res < 0:
            raise errors.JLinkException(res)

        return None

Flushes data from the SWO buffer.

After this method is called, the flushed part of the SWO buffer is
empty.

If ``num_bytes`` is not present, flushes all data currently in the SWO
buffer.

Args:
self (JLink): the ``JLink`` instance
num_bytes (int): the number of bytes to flush

Returns:
``None``

Raises:
JLinkException: on error


def resolve_theme(self, name):

        if name not in settings.CODEMIRROR_THEMES:
            msg = ("Given theme name '{}' does not exists in "
                   "'settings.CODEMIRROR_THEMES'.")
            raise UnknowThemeError(msg.format(name))

        return settings.CODEMIRROR_THEMES.get(name)

From given theme name, return theme file path from
``settings.CODEMIRROR_THEMES`` map.

Arguments:
name (string): Theme name.

Raises:
KeyError: When given name does not exist in
``settings.CODEMIRROR_THEMES``.

Returns:
string: Theme file path.


def _GetNextPath(self):
    paths = sorted((path for path in io_wrapper.ListDirectoryAbsolute(self._directory) if self._path_filter(path)))
    if (not paths):
        return None
    if (self._path is None):
        return paths[0]
    if ((not io_wrapper.IsCloudPath(paths[0])) and (not self._ooo_writes_detected)):
        current_path_index = bisect.bisect_left(paths, self._path)
        ooo_check_start = max(0, (current_path_index - self._OOO_WRITE_CHECK_COUNT))
        for path in paths[ooo_check_start:current_path_index]:
            if self._HasOOOWrite(path):
                self._ooo_writes_detected = True
                break
    next_paths = list((path for path in paths if ((self._path is None) or (path > self._path))))
    if next_paths:
        return min(next_paths)
    else:
        return None

Gets the next path to load from.

This function also does the checking for out-of-order writes as it iterates
through the paths.

Returns:
The next path to load events from, or None if there are no more paths.


def __init__(self, sess, bad_init_action=None, bad_run_start_action=None, bad_debug_urls=None):
    self._bad_init_action = bad_init_action
    self._bad_run_start_action = bad_run_start_action
    self._bad_debug_urls = bad_debug_urls
    framework.BaseDebugWrapperSession.__init__(self, sess)

Constructor.

Args:
sess: The TensorFlow Session object to be wrapped.
bad_init_action: (str) bad action value to be returned during the
on-session-init callback.
bad_run_start_action: (str) bad action value to be returned during the
the on-run-start callback.
bad_debug_urls: Bad URL values to be returned during the on-run-start
callback.


def assert_eventual(self, func, required, allowed, timeout_secs=300.0):
    required = set(required)
    assert required
    seen = set()
    start_time = time.time()
    while timeout_secs is None or time.time() - start_time < timeout_secs:
        if seen == required:
            return
        value = func()
        if value not in allowed:
            self.fail(msg=f'Disallowed value: {value}.')
        if value in required:
            seen.add(value)
    missing = [v for v in required if v not in seen]
    self.fail(msg=f'Timed out. Missing values: {str([str(v) for v in missing])}.')

Tests that calls to the given function meet required and allowed values.

Args:
func: function to test.
required: iterable of required values. Must be hashable and non-empty.
allowed: iterable of allowed values. Must be hashable and non-empty.
timeout_secs: fails if more than this time is required.


def _translate_to_fulltype_for_flat_tensors(spec: type_spec.TypeSpec) -> List[full_type_pb2.FullTypeDef]:
    if isinstance(spec, RaggedTensorSpec):
        dt = spec.dtype
        elem_t = _DT_TO_FT.get(dt)
        if elem_t is None:
            logging.vlog(1, 'dtype %s that has no conversion to fulltype.', dt)
        elif elem_t == full_type_pb2.TFT_LEGACY_VARIANT:
            logging.vlog(1, 'Ragged tensors containing variants are not supported.', dt)
        else:
            assert len(spec._flat_tensor_specs) == 1
            return [full_type_pb2.FullTypeDef(type_id=full_type_pb2.TFT_RAGGED, args=[full_type_pb2.FullTypeDef(type_id=elem_t)])]
    return [full_type_pb2.FullTypeDef(type_id=full_type_pb2.TFT_UNSET) for t in spec._flat_tensor_specs]

Convert a TypeSec to a list of FullTypeDef.

The FullTypeDef created corresponds to the encoding used with datasets
(and map_fn) that uses variants (and not FullTypeDef corresponding to the
default "component" encoding).

Currently, the only use of this is for information about the contents of
ragged tensors, so only ragged tensors return useful full type information
and other types return TFT_UNSET. While this could be improved in the future,
this function is intended for temporary use and expected to be removed
when type inference support is sufficient.

Args:
spec: A TypeSpec for one element of a dataset or map_fn.

Returns:
A list of FullTypeDef corresponding to SPEC. The length of this list
is always the same as the length of spec._flat_tensor_specs.


def draw_layer(ax, layer):

    ax.set_aspect('equal', 'datalim')
    ax.plot(*layer)
    ax.axis('off')

Draws a layer on the given matplotlib axis.

Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot


def send_rpc_request(self, request):
    self._client_send(request)
    response = self._client_receive()
    if not response:
        raise errors.ProtocolError(self._device, errors.ProtocolError.NO_RESPONSE_FROM_SERVER)
    return self._decode_socket_response_bytes(response)

Sends an RPC request to the server and receives a response.

Args:
request: str, the request to send the server.

Returns:
The string of the RPC response.

Raises:
errors.Error: if failed to send the request or receive a response.
errors.ProtocolError: if received an empty response from the server.
UnicodeError: if failed to decode the received response.


def expression_filter(self, name, **kwargs):

        def decorator(func):
            self.filters[name] = ExpressionFilter(name, func, **kwargs)

        return decorator

Returns a decorator function for adding an expression filter.

Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.

Returns:
Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator
function for adding an expression filter.


def set_all_xlims(self, xlim, dx, xscale, fontsize=None):
    self._set_all_lims('x', xlim, dx, xscale, fontsize)
    return

Set limits and ticks for x axis for whole figure.

This will set x axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.

Args:
xlim (len-2 list of floats): The limits for the axis.
dx (float): Amount to increment by between the limits.
xscale (str): Scale of the axis. Either `log` or `lin`.
fontsize (int, optional): Set fontsize for x axis tick marks.
Default is None.


def match(self, part: ProcessorPart) -> bool:
    ...

Returns True if `part` should be processed by this part processor.

Returns False if it sure that the part processor will not process the input
part and that the part processor should pass the part as is.

NOTE: the part processor `__call__` implementation should always skip the
part (i.e. return the part as is) when `match` returns False.

A typical example are part processors that are type-dependent, e.g. a part
processor that parses a specific proto from the part or that only parses
text.

Args:
part: the part to check.

Returns:
False if the part has no chance of being processed by this part
processor. True otherwise.


def remove_snippet_client(self, name):
    if name not in self._snippet_clients:
        raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)
    client = self._snippet_clients.pop(name)
    client.stop()

Removes a snippet client from management.

Args:
name: string, the name of the snippet client to remove.

Raises:
Error: if no snippet client is managed under the specified name.


def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
    vision_data = {}
    if image_sizes is not None:
        images_kwargs = InternVLProcessorKwargs._defaults.get('images_kwargs', {})
        images_kwargs.update(kwargs)
        num_image_patches = [self.image_processor.get_number_of_image_tokens(*image_size, images_kwargs) for image_size in image_sizes]
        num_image_tokens = [2 + self.image_seq_length * num_patches for num_patches in num_image_patches]
        vision_data.update({'num_image_tokens': num_image_tokens, 'num_image_patches': num_image_patches})
    return MultiModalData(**vision_data)

Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

Args:
image_sizes (`List[List[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.

Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.


def plot_dendrogram(ax, obj, show_diameters=True):

    dnd = Dendrogram(obj, show_diameters=show_diameters)
    dnd.generate()

    _render_dendrogram(dnd, ax, 0.)

    ax.set_title('Morphology Dendrogram')
    ax.set_xlabel('micrometers (um)')
    ax.set_ylabel('micrometers (um)')

    ax.set_aspect('auto')
    ax.legend()

Dendrogram of `obj`

Args:
obj: Neuron or tree \
neurom.Neuron, neurom.Tree
show_diameters : boolean \
Determines if node diameters will \
be show or not.


def _price_lognormal_rate(self, valuation_date, market, pricing_context):
    discount_curve = market.discount_curve
    discount_factors = tf.where(self._payment_dates > valuation_date, discount_curve.get_discount_factor(self._payment_dates), 0.0)
    forward_rates = self._get_forward_rate(valuation_date, market)
    if pricing_context is None:
        volatility_surface = market.volatility_curve
        black_vols = volatility_surface.interpolate(self._reset_dates, self._strike, self._term)
    else:
        black_vols = tf.convert_to_tensor(pricing_context, dtype=self._dtype)
    expiry_times = dates.daycount_actual_365_fixed(start_date=valuation_date, end_date=self._reset_dates, dtype=self._dtype)
    caplet_prices = black_scholes.option_price(forwards=forward_rates, strikes=self._strike, volatilities=black_vols, expiries=expiry_times, is_call_options=self._is_cap)
    intrinsic_value = tf.where(self._is_cap, tf.math.maximum(forward_rates - self._strike, 0.0), tf.math.maximum(self._strike - forward_rates, 0))
    caplet_prices = tf.where(self._payment_dates < valuation_date, tf.constant(0.0, dtype=self._dtype), tf.where(self._accrual_start_dates < valuation_date, intrinsic_value, caplet_prices))
    caplet_prices = self._notional * self._daycount_fractions * caplet_prices
    return discount_factors * caplet_prices

Computes caplet/floorlet prices using lognormal model for forward rates.

The function computes individual caplet prices for the batch of caps/floors
using the lognormal model for the forward rates. If the volatilities are
are supplied (through the input `pricing_context`) then they are used as
forward rate volatilies. Otherwise, volatilities are extracted using the
volatility surface for `market`.

Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the Cap/Floor.
pricing_context: An optional input containing the black volatility for
for the forward rates.

Returns:
A Rank 1 `Tensor` of real type containing the price of each caplet
(or floorlet) based using the lognormal model for forward rates.


def _put_into_indexes(self, obj):
    no_of_used_indexes = 0
    for (field_name, db_index) in list(self._get_db_fields(obj)):
        attr_value = getattr(obj, field_name)
        if (attr_value is None):
            continue
        container = db_index.get(attr_value, None)
        if (container is None):
            container = OOTreeSet()
            db_index[attr_value] = container
        container.insert(obj)
        no_of_used_indexes += 1
    if (no_of_used_indexes <= 0):
        raise UnindexableObject('You have to use atleast one of the identificators!')

Put publication into all indexes.

Attr:
obj (obj): Indexable object.

Raises:
UnindexableObject: When there is no index (property) which can be
used to index `obj` in database.


def create_resource(self, parent_id=""):

        resource_name = self.trigger_settings.get('resource', '')
        resource_name = resource_name.replace('/', '')
        if not self.resource_id:
            created_resource = self.client.create_resource(
                restApiId=self.api_id, parentId=parent_id, pathPart=resource_name)
            self.resource_id = created_resource['id']
            self.log.info("Successfully created resource")
        else:
            self.log.info("Resource already exists. To update resource please delete existing resource: %s",
                          resource_name)

Create the specified resource.

Args:
parent_id (str): The resource ID of the parent resource in API Gateway


def FlowAccumFromProps(props, weights=None, in_place=False):
    if (type(props) is not rd3array):
        raise Exception('A richdem.rd3array or numpy.ndarray is required!')
    if ((weights is not None) and in_place):
        accum = rdarray(weights, no_data=(- 1))
    elif ((weights is not None) and (not in_place)):
        accum = rdarray(weights, copy=True, meta_obj=props, no_data=(- 1))
    elif (weights is None):
        accum = rdarray(np.ones(shape=props.shape[0:2], dtype='float64'), meta_obj=props, no_data=(- 1))
    else:
        raise Exception('Execution should never reach this point!')
    if (accum.dtype != 'float64'):
        raise Exception("Accumulation array must be of type 'float64'!")
    accumw = accum.wrap()
    _AddAnalysis(accum, 'FlowAccumFromProps(dem, weights={weights}, in_place={in_place})'.format(weights=('None' if (weights is None) else 'weights'), in_place=in_place))
    _richdem.FlowAccumulation(props.wrap(), accumw)
    accum.copyFromWrapped(accumw)
    return accum

Calculates flow accumulation from flow proportions.

Args:
props    (rdarray): An elevation model
weights  (rdarray): Flow accumulation weights to use. This is the
amount of flow generated by each cell. If this is
not provided, each cell will generate 1 unit of
flow.
in_place (bool):    If True, then `weights` is modified in place. An
accumulation matrix is always returned, but it will
just be a view of the modified data if `in_place`
is True.

Returns:
A flow accumulation array. If `weights` was provided and `in_place` was
True, then this matrix is a view of the modified data.