def forward(ctx, scores: torch.Tensor, multiplier: torch.Tensor, selected_experts: torch.Tensor, masked_gates: torch.Tensor, mask_for_one: torch.Tensor):
    ctx.save_for_backward(multiplier, selected_experts, masked_gates)
    return multiplier * mask_for_one

Forward pass for the custom autograd function.

Args:
ctx: Context object to save information for backward computation.
scores (torch.Tensor): Input scores tensor.
multiplier (torch.Tensor): Multiplier tensor.
selected_experts (torch.Tensor): Tensor of selected experts.
masked_gates (torch.Tensor): Masked gates tensor.
mask_for_one (torch.Tensor): Mask for one tensor.

Returns:
torch.Tensor: Result of the forward pass.


def center_crop(self, image: np.ndarray, crop_size: Dict[str, int], data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
    crop_size = get_size_dict(crop_size, default_to_square=True)
    if 'height' not in crop_size or 'width' not in crop_size:
        raise ValueError('crop_size dictionary must contain height and width keys')
    return center_crop(image, (crop_size['height'], crop_size['width']), data_format=data_format, input_data_format=input_data_format, **kwargs)

Center crop an image to a certain size.

Args:
image (`np.ndarray`):
Image to center crop.
crop_size (`Dict[str, int]`):
The size to center crop the image to. Must contain height and width keys.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. If unset, the channel dimension format of the input
image is used.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.


def populate_request_data(self, request_args):

        request_args['auth'] = HTTPBasicAuth(
            self._username, self._password)
        return request_args

Add the authentication info to the supplied dictionary.

We use the `requests.HTTPBasicAuth` class as the `auth` param.

Args:
`request_args`: The arguments that will be passed to the request.
Returns:
The updated arguments for the request.


def from_object(cls, o, base_uri):

        if isinstance(o, list):
            if len(o) == 1:
                return cls.from_object(o[0], base_uri)

            return [cls.from_object(x, base_uri) for x in o]

        return cls(o, base_uri)

Returns a new ``Link`` based on a JSON object or array.

Arguments:

- ``o``: a dictionary holding the deserializated JSON for the new
``Link``, or a ``list`` of such documents.
- ``base_uri``: optional URL used as the basis when expanding
relative URLs in the link.


def __init__(self, html_template_path, export_report_path):
    if not _file_io.file_exists(html_template_path):
        raise IOError("File '{0}' does not exist.".format(html_template_path))
    with _file_io.FileIO(html_template_path, 'r') as f:
        self.html_template = f.read()
    _file_io.recursive_create_dir(os.path.dirname(export_report_path))
    self.export_report_path = export_report_path

Reads the HTML template content.

Args:
html_template_path: A string, path to the template HTML file.
export_report_path: A string, path to the generated HTML report. This path
should point to a '.html' file with date and time in its name.
e.g. 2019-01-01-10:05.toco_report.html.

Raises:
IOError: File doesn't exist.


def credits(self, **kwargs):
    path = self._get_series_id_season_number_path('credits')
    response = self._GET(path, kwargs)
    self._set_attrs_to_values(response)
    return response

Get the cast & crew credits for a TV season by season number.

Returns:
A dict respresentation of the JSON returned from the API.


def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None):
    coin = Coin(coin_reference=coin_ref, tx_output=tx_output, state=state)
    coin._transaction = transaction
    return coin

Get a Coin object using a CoinReference.

Args:
coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input.
tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction output.
state (neo.Core.State.CoinState):

Returns:
Coin: self.


def success(channel, stats, name, platform, dp):
    datapacks = [('Platform', platform, False)]
    for stat in stats:
        if (stat[0] in ('Duel 1v1', 'Doubles 2v2', 'Solo Standard 3v3', 'Standard 3v3')):
            stat_name = (('__' + stat[0]) + '__')
            stat_value = (('**' + stat[1]) + '**')
        else:
            stat_name = stat[0]
            stat_value = stat[1]
        if stat[2]:
            stat_value += ((' *(Top ' + stat[2]) + '%)*')
        datapacks.append((stat_name, stat_value, True))
    gui = ui_embed.UI(channel, 'Rocket League Stats: {}'.format(name), '*Stats obtained from [Rocket League Tracker Network](https:
    return gui

Creates an embed UI containing the Rocket League stats

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

Returns:
(discord.Embed): The created embed


def get_version(self, timestamp):
    if timestamp != 0 and timestamp != self.current_timestamp:
        assert timestamp > self.current_timestamp
        self.current_version = self.current_version + 1
        self.current_timestamp = timestamp
    return self.current_version

Updates version if necessary and returns the version number.

Args:
timestamp: (int) unix timestamp when the cache is updated. This value is
zero if the cache has been evicted or doesn't exist.


def _AddSerializedEvent(self, event):
    identifier = identifiers.SQLTableIdentifier(self._CONTAINER_TYPE_EVENT, (self._serialized_event_heap.number_of_events + 1))
    event.SetIdentifier(identifier)
    serialized_data = self._SerializeAttributeContainer(event)
    self._serialized_event_heap.PushEvent(event.timestamp, serialized_data)
    if (self._serialized_event_heap.data_size > self._maximum_buffer_size):
        self._WriteSerializedAttributeContainerList(self._CONTAINER_TYPE_EVENT)

Adds an serialized event.

Args:
event (EventObject): event.

Raises:
IOError: if the event cannot be serialized.
OSError: if the event cannot be serialized.


def has_overlap(self, interval: 'Interval') -> bool:
    if ((self.begin < interval.end) and (interval.begin < self.end)):
        return True
    return False

Check if self has overlap with `interval`.

Args:
interval: interval to be examined

Returns:
bool: True if self has overlap with `interval` otherwise False


def ragged_rank(self):
    return self._ragged_rank

The number of times the RaggedTensor's flat_values is partitioned.

Defaults to `shape.ndims - 1`.

Examples:

>>> values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]])
>>> tf.type_spec_from_value(values).ragged_rank
1

>>> rt1 = tf.RaggedTensor.from_uniform_row_length(values, 2)
>>> tf.type_spec_from_value(rt1).ragged_rank
2

Returns:
A Python `int` indicating the number of times the underlying `flat_values`
Tensor has been partitioned to add a new dimension.
I.e., `tf.rank(rt) = tf.rank(rt.flat_values) + rt.ragged_rank`.


def __init__(self, performed_action, run_metadata=None, client_graph_def=None, tf_error=None):
    _check_type(performed_action, str)
    self.performed_action = performed_action
    if run_metadata is not None:
        _check_type(run_metadata, config_pb2.RunMetadata)
    self.run_metadata = run_metadata
    self.client_graph_def = client_graph_def
    self.tf_error = tf_error

Constructor for `OnRunEndRequest`.

Args:
performed_action: (`OnRunStartAction`) Actually-performed action by the
debug-wrapper session.
run_metadata: run_metadata output from the run() call (if any).
client_graph_def: (GraphDef) GraphDef from the client side, i.e., from
the python front end of TensorFlow. Can be obtained with
session.graph.as_graph_def().
tf_error: (errors.OpError subtypes) TensorFlow OpError that occurred
during the run (if any).


def get_groups(self, **kwargs):
    params = {'cultureInfo': util.language_code(kwargs.get('lang'))}
    result = self.make_request('geo', 'get_groups', **params)
    if (not util.check_result(result)):
        return (False, result.get('resultDescription', 'UNKNOWN ERROR'))
    values = util.response_list(result, 'resultValues')
    return (True, [emtype.GeoGroupItem(**a) for a in values])

Obtain line types and details.

Args:
lang (str): Language code (*es* or *en*).

Returns:
Status boolean and parsed response (list[GeoGroupItem]), or message
string in case of error.


def Selector(fields):

    check_user_facing_fields_dict(fields, 'Selector')

    class _Selector(_ConfigSelector):
        def __init__(self):
            key = 'Selector.' + str(DictCounter.get_next_count())
            super(_Selector, self).__init__(
                key=key,
                name=None,
                fields=fields,

                type_attributes=ConfigTypeAttributes(is_builtin=True),
            )

    return _Selector

Selectors are used when you want to be able present several different options to the user but
force them to select one. For example, it would not make much sense to allow them
to say that a single input should be sourced from a csv and a parquet file: They must choose.

Note that in other type systems this might be called an "input union."

Args:
fields (Dict[str, Field]):


def sanity_check_states(states_spec):
    states = copy.deepcopy(states_spec)
    is_unique = ('shape' in states)
    if is_unique:
        states = dict(state=states)
    for (name, state) in states.items():
        if isinstance(state['shape'], int):
            state['shape'] = (state['shape'],)
        if ('type' not in state):
            state['type'] = 'float'
    return (states, is_unique)

Sanity checks a states dict, used to define the state space for an MDP.
Throws an error or warns if mismatches are found.

Args:
states_spec (Union[None,dict]): The spec-dict to check (or None).

Returns: Tuple of 1) the state space desc and 2) whether there is only one component in the state space.


def _set_current(self, new_current):
    new_cur_full_path = self.join(new_current)
    if (not os.path.exists(new_cur_full_path)):
        raise PrefixNotFound(('Prefix "%s" does not exist in workdir %s' % (new_current, self.path)))
    if os.path.lexists(self.join('current')):
        os.unlink(self.join('current'))
    os.symlink(new_current, self.join('current'))
    self.current = new_current

Change the current default prefix, for internal usage

Args:
new_current(str): Name of the new current prefix, it must already
exist

Returns:
None

Raises:
PrefixNotFound: if the given prefix name does not exist in the
workdir


def RotateServerKey(cn=u'grr', keylength=4096):
    ca_certificate = config.CONFIG['CA.certificate']
    ca_private_key = config.CONFIG['PrivateKeys.ca_key']
    if ((not ca_certificate) or (not ca_private_key)):
        raise ValueError('No existing CA certificate found.')
    existing_cert = config.CONFIG['Frontend.certificate']
    serial_number = (existing_cert.GetSerialNumber() + 1)
    EPrint(("Generating new server key (%d bits, cn '%s', serial
    server_private_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=keylength)
    server_cert = key_utils.MakeCASignedCert(str(cn), server_private_key, ca_certificate, ca_private_key, serial_number=serial_number)
    EPrint('Updating configuration.')
    config.CONFIG.Set('Frontend.certificate', server_cert.AsPEM())
    config.CONFIG.Set('PrivateKeys.server_key', server_private_key.AsPEM())
    config.CONFIG.Write()
    EPrint('Server key rotated, please restart the GRR Frontends.')

This function creates and installs a new server key.

Note that

- Clients might experience intermittent connection problems after
the server keys rotated.

- It's not possible to go back to an earlier key. Clients that see a
new certificate will remember the cert's serial number and refuse
to accept any certificate with a smaller serial number from that
point on.

Args:
cn: The common name for the server to use.
keylength: Length in bits for the new server key.

Raises:
ValueError: There is no CA cert in the config. Probably the server
still needs to be initialized.


def _HasSelf(self, sig):
    return sig.params and sig.params[0].name == 'self'

True if a signature has a self parameter.

This only checks for the name, since the type can be too many different
things (type of the method, type of the base class, object, unknown etc.)
and doesn't carry over to the simplified version, anyway.

Arguments:
sig: Function signature (instance of pytd.Signature)

Returns:
True if the signature has "self".


def add_method(self, m, **kwargs):
    if isinstance(m, types.FunctionType):
        self[('function', id(m))] = m
    else:
        (f, obj) = get_method_vars(m)
        wrkey = (f, id(obj))
        self[wrkey] = obj

Add an instance method or function

Args:
m: The instance method or function to store


def set_number_of_shards(self, number_of_shards):
    if self._frozen:
        if self._number_of_shards != number_of_shards:
            raise ValueError(f"Can't set sharding policy to use {number_of_shards} shards since it has been frozen to use {self._number_of_shards}")
    elif number_of_shards > 0:
        self._number_of_shards = number_of_shards
    else:
        raise ValueError(f"Can't set sharding policy to use {number_of_shards} shards; value must be > 0")

Sets the number of shards for the current policy.

If the policy has been frozen then number_of_shards must match the
existing setting.

Args:
number_of_shards: The number of shards to use in the policy.

Raises:
ValueError: If the policy has been frozen and number_of_shards
differs from the frozen value; or number_of_shards <= 0.


def delete_variant(self, variant):

        mongo_variant = self.get_variant(variant)

        if mongo_variant:

            if mongo_variant['observations'] == 1:
                LOG.debug("Removing variant {0}".format(
                    mongo_variant.get('_id')
                ))
                message = self.db.variant.delete_one({'_id': variant['_id']})
            else:
                LOG.debug("Decreasing observations for {0}".format(
                    mongo_variant.get('_id')
                ))
                message = self.db.variant.update_one({
                    '_id': mongo_variant['_id']
                    },{
                        '$inc': {
                            'observations': -1,
                            'homozygote': - (variant.get('homozygote', 0)),
                            'hemizygote': - (variant.get('hemizygote', 0)),
                        },
                        '$pull': {
                            'families': variant.get('case_id')
                        }
                    }, upsert=False)
        return

Delete observation in database

This means that we take down the observations variable with one.
If 'observations' == 1 we remove the variant. If variant was homozygote
we decrease 'homozygote' with one.
Also remove the family from array 'families'.

Args:
variant (dict): A variant dictionary


def _map_across_full_axis_select_indices(
        self, axis, func, indices, keep_remaining=False
    ):

        return self.data.apply_func_to_select_indices_along_full_axis(
            axis, func, indices, keep_remaining
        )

Maps function to select indices along full axis.

Args:
axis: 0 for columns and 1 for rows.
func: Callable mapping function over the BlockParitions.
indices: indices along axis to map over.
keep_remaining: True if keep indices where function was not applied.

Returns:
BaseFrameManager containing the result of mapping func over axis on indices.


def _FormatAttrToken(self, token_data):

    return {
        'mode': token_data.file_mode,
        'uid': token_data.user_identifier,
        'gid': token_data.group_identifier,
        'system_id': token_data.file_system_identifier,
        'node_id': token_data.file_identifier,
        'device': token_data.device}

Formats an attribute token as a dictionary of values.

Args:
token_data (bsm_token_data_attr32|bsm_token_data_attr64): AUT_ATTR32 or
AUT_ATTR64 token data.

Returns:
dict[str, str]: token values.


def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None):
    input_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor(input_tensor)
    if isinstance(input_tensor, sparse_tensor_lib.SparseTensor):
        return input_tensor
    with ops.name_scope(None, 'to_sparse_input', (input_tensor, ignore_value)):
        if ignore_value is None:
            if input_tensor.dtype == dtypes.string:
                ignore_value = ''
            elif input_tensor.dtype.is_integer:
                ignore_value = -1
            else:
                ignore_value = input_tensor.dtype.as_numpy_dtype()
        ignore_value = math_ops.cast(ignore_value, input_tensor.dtype, name='ignore_value')
        indices = array_ops.where_v2(math_ops.not_equal(input_tensor, ignore_value), name='indices')
        return sparse_tensor_lib.SparseTensor(indices=indices, values=array_ops.gather_nd(input_tensor, indices, name='values'), dense_shape=array_ops.shape(input_tensor, out_type=dtypes.int64, name='dense_shape'))

Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells.

If `input_tensor` is already a `SparseTensor`, just return it.

Args:
input_tensor: A string or integer `Tensor`.
ignore_value: Entries in `dense_tensor` equal to this value will be absent
from the resulting `SparseTensor`. If `None`, default value of
`dense_tensor`'s dtype will be used ('' for `str`, -1 for `int`).

Returns:
A `SparseTensor` with the same shape as `input_tensor`.

Raises:
ValueError: when `input_tensor`'s rank is `None`.


def find_untranscribed_wavs(wav_path: Path, transcription_path: Path, label_type: str) -> List[str]:

    audio_files = wav_path.glob("***.{}".format(label_type))

    transcription_file_prefixes = [t_file.stem for t_file in transcription_files]

    untranscribed_prefixes = []
    for a_file in audio_files:
        if a_file.stem not in transcription_file_prefixes:
            untranscribed_prefixes.append(a_file.stem)
    return untranscribed_prefixes

Find the prefixes for all the wav files that do not have an associated transcription
Args:
wav_path: Path to search for wav files in
transcription_path: Path to search for transcriptions in
label_type: The type of labels for transcriptions. Eg "phonemes" "phonemes_and_tones"
Returns:
A list of all untranscribed prefixes


def AddNewSignature(self, pattern, offset=None):
    self.signatures.append(Signature(pattern, offset=offset))

Adds a signature.

Args:
pattern (bytes): pattern of the signature.
offset (int): offset of the signature. None is used to indicate
the signature has no offset. A positive offset is relative from
the start of the data a negative offset is relative from the end
of the data.


def round(cls, x: 'TensorFluent') -> 'TensorFluent':
    return cls._unary_op(x, tf.round, tf.float32)

Returns a TensorFluent for the round function.

Args:
x: The input fluent.

Returns:
A TensorFluent wrapping the round function.


def header(self, sheet, name):

        header = sheet.row(0)
        for i, column in enumerate(self.headers[name]):
            header.write(i, self.headers[name][i])

Write sheet header.
Args:
sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet.
name: (unicode) name of sheet.


def write_signatures(self, signatures):
    self.fileobj.seek(self.signature_offset)
    sig_entries = [dict(algorithm_id=id_, size=len(sig), signature=sig) for (id_, sig) in signatures]
    sigs = sigs_header.build(dict(filesize=self.filesize, count=len(signatures), sigs=sig_entries))
    self.fileobj.write(sigs)
    signatures_len = len(sigs)
    self.additional_offset = (self.signature_offset + signatures_len)
    if (not (self.additional_offset == self.fileobj.tell())):
        raise IOError('ended up at unexpected offset')

Write signature data to the MAR file.

Args:
signatures (list): list of signature tuples of the form
(algorithm_id, signature_data)


def is_null_merge(self):
    return not bool(self._spec.to_string())

Indicate whether the wrapped spec is empty.

In the degenerate case where self._spec is an empty specification, a caller
may wish to skip a merge step entirely. (However this class does not have
enough information to make that determination.)

Returns:
A boolean indicating whether a device merge will be trivial.


def read_tracers_h5(xdmf_file, infoname, snapshot, position):

    xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
    tra = {}
    tra[infoname] = [{}, {}]
    if position:
        for axis in 'xyz':
            tra[axis] = [{}, {}]
    for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
        ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
        if position:
            for data_attr in elt_subdomain.findall('Geometry'):
                for data_item, axis in zip(data_attr.findall('DataItem'),
                                           'xyz'):
                    icore, data = _get_field(xdmf_file, data_item)
                    tra[axis][ibk][icore] = data
        for data_attr in elt_subdomain.findall('Attribute'):
            if data_attr.get('Name') != infoname:
                continue
            icore, data = _get_field(xdmf_file, data_attr.find('DataItem'))
            tra[infoname][ibk][icore] = data
    for info in tra:
        tra[info] = [trab for trab in tra[info] if trab]
        for iblk, trab in enumerate(tra[info]):
            tra[info][iblk] = np.concatenate([trab[icore]
                                              for icore in range(len(trab))])
    return tra

Extract tracers data from hdf5 files.

Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to extract position of tracers.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.


def copyglob(src: str, dest: str, allow_nothing: bool=False, allow_nonfiles: bool=False) -> None:
    something = False
    for filename in glob.glob(src):
        if (allow_nonfiles or os.path.isfile(filename)):
            shutil.copy(filename, dest)
            something = True
    if (something or allow_nothing):
        return
    raise ValueError('No files found matching: {}'.format(src))

Copies files whose filenames match the glob src" into the directory
"dest". Raises an error if no files are copied, unless allow_nothing is
True.

Args:
src: source glob (e.g. ``/somewhere/*.txt``)
dest: destination directory
allow_nothing: don't raise an exception if no files are found
allow_nonfiles: copy things that are not files too (as judged by
:func:`os.path.isfile`).

Raises:
ValueError: if no files are found and ``allow_nothing`` is not set


async def _call_rpc(self, header):
    (length, _, cmd, feature, address) = struct.unpack('<BBBBB', bytes(header))
    rpc_id = ((feature << 8) | cmd)
    payload = self.rpc_payload[:length]
    self._logger.debug('Calling RPC %d:%04X with %s', address, rpc_id, binascii.hexlify(payload))
    exception = None
    response = None
    try:
        response = (await self.send_rpc(self.CLIENT_ID, str(self.device.iotile_id), address, rpc_id, bytes(payload), timeout=30.0))
    except VALID_RPC_EXCEPTIONS as err:
        exception = err
    except Exception as err:
        self._logger.exception('Error calling RPC %d:%04X', address, rpc_id)
        exception = err
    (status, response) = pack_rpc_response(response, exception)
    resp_header = struct.pack('<BBBB', status, 0, 0, len(response))
    (await self._send_notification(self.ReceiveHeaderHandle, resp_header))
    if (len(response) > 0):
        (await self._send_notification(self.ReceivePayloadHandle, response))

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

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


def create(filename: str, layers: Union[(np.ndarray, Dict[(str, np.ndarray)], loompy.LayerManager)], row_attrs: Union[(loompy.AttributeManager, Dict[(str, np.ndarray)])], col_attrs: Union[(loompy.AttributeManager, Dict[(str, np.ndarray)])], *, file_attrs: Dict[(str, str)]=None) -> None:
    if isinstance(row_attrs, loompy.AttributeManager):
        row_attrs = {k: v[:] for (k, v) in row_attrs.items()}
    if isinstance(col_attrs, loompy.AttributeManager):
        col_attrs = {k: v[:] for (k, v) in col_attrs.items()}
    if (isinstance(layers, np.ndarray) or scipy.sparse.issparse(layers)):
        layers = {'': layers}
    elif isinstance(layers, loompy.LayerManager):
        layers = {k: v[(:, :)] for (k, v) in layers.items()}
    if ('' not in layers):
        raise ValueError('Data for default layer must be provided')
    shape = layers[''].shape
    if ((shape[0] == 0) or (shape[1] == 0)):
        raise ValueError('Main matrix cannot be empty')
    for (name, layer) in layers.items():
        if (layer.shape != shape):
            raise ValueError(f"Layer '{name}' is not the same shape as the main matrix")
    for (name, ra) in row_attrs.items():
        if (ra.shape[0] != shape[0]):
            raise ValueError(f"Row attribute '{name}' is not the same length ({ra.shape[0]}) as number of rows in main matrix ({shape[0]})")
    for (name, ca) in col_attrs.items():
        if (ca.shape[0] != shape[1]):
            raise ValueError(f"Column attribute '{name}' is not the same length ({ca.shape[0]}) as number of columns in main matrix ({shape[1]})")
    try:
        with new(filename, file_attrs=file_attrs) as ds:
            for (key, vals) in layers.items():
                ds.layer[key] = vals
            for (key, vals) in row_attrs.items():
                ds.ra[key] = vals
            for (key, vals) in col_attrs.items():
                ds.ca[key] = vals
    except ValueError as ve:
        if os.path.exists(filename):
            os.remove(filename)
        raise ve

Create a new Loom file from the given data.

Args:
filename (str):         The filename (typically using a ``.loom`` file extension)
layers:					One of the following:

* Two-dimensional (N-by-M) numpy ndarray of float values
* Sparse matrix (e.g. :class:`scipy.sparse.csr_matrix`)
* Dictionary of named layers, each an N-by-M ndarray or sparse matrix
* A :class:`.LayerManager`, with each layer an N-by-M ndarray
row_attrs (dict):       Row attributes, where keys are attribute names and values
are numpy arrays (float or string) of length N
col_attrs (dict):       Column attributes, where keys are attribute names and
values are numpy arrays (float or string) of length M
file_attrs (dict):      Global attributes, where keys are attribute names and
values are strings
Returns:
Nothing

Remarks:
If the file exists, it will be overwritten.


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

Retrieve the tensor events associated with a run and tag.

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

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

Returns:
An array of `event_accumulator.TensorEvent`s.


def create_from_json(cls, json_data):

        prop = Property()
        address_info = json_data["address_info"]
        prop.address = address_info["address"]
        prop.block_id = address_info["block_id"]
        prop.zipcode = address_info["zipcode"]
        prop.zipcode_plus4 = address_info["zipcode_plus4"]
        prop.address_full = address_info["address_full"]
        prop.city = address_info["city"]
        prop.county_fips = address_info["county_fips"]
        prop.geo_precision = address_info["geo_precision"]
        prop.lat = address_info["lat"]
        prop.lng = address_info["lng"]
        prop.slug = address_info["slug"]
        prop.state = address_info["state"]
        prop.unit = address_info["unit"]

        prop.meta = None
        if "meta" in json_data:
            prop.meta = json_data["meta"]

        prop.component_results = _create_component_results(json_data, "address_info")

        return prop

Deserialize property json data into a Property object

Args:
json_data (dict): The json data for this property

Returns:
Property object


def AddNEP5Token(self, token):

        if token.ScriptHash.ToBytes() in self._tokens.keys():
            logger.error("Token already in wallet")
            return
        self._tokens[token.ScriptHash.ToBytes()] = token

Add a NEP-5 compliant token to the wallet.

Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token.

Note:
Prints a warning to the console if the token already exists in the wallet.


def __init__(self, storage_writer):

    super(StorageMergeReader, self).__init__()
    self._storage_writer = storage_writer

Initializes a storage merge reader.

Args:
storage_writer (StorageWriter): storage writer.


def publish(self, object_id: str, event_type: str, event_data: dict=None):
    object_key = SchedulingObject.get_key(self.type, object_id)
    publish(event_type=event_type, event_data=event_data, object_type=self.type, object_id=object_id, object_key=object_key, origin=None)

Publish a scheduling object event.

Args:
object_id (str): ID of the scheduling object
event_type (str): Type of event.
event_data (dict, optional): Event data.


def indent_css(f, output):

    line_count = get_line_count(f)
    f = open(f, 'r+')
    output = open(output, 'r+')
    for line in range(line_count):
        string = f.readline().rstrip()
        if len(string) > 0:
            if string[-1] == ";":
                output.write("    " + string + "\n")
            else:
                output.write(string + "\n")
    output.close()
    f.close()

Indentes css that has not been indented and saves it to a new file.
A new file is created if the output destination does not already exist.

Args:
f: string, path to file.

output: string, path/name of the output file (e.g. /directory/output.css).
print type(response.read())

Returns:
None.


def list_channels(self, collection_name, experiment_name):

        dont_care = 'image'
        chan = ChannelResource(
            name='', collection_name=collection_name,
            experiment_name=experiment_name, type=dont_care)
        return self._list_resource(chan)

List all channels belonging to the named experiment that is part
of the named collection.

Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.

Returns:
(list)

Raises:
requests.HTTPError on failure.


class TFCvtStage(keras.layers.Layer):

    def __init__(self, config: CvtConfig, stage: int, **kwargs):
        super().__init__(**kwargs)
        self.config = config
        self.stage = stage
        if self.config.cls_token[self.stage]:
            self.cls_token = self.add_weight(shape=(1, 1, self.config.embed_dim[-1]), initializer=get_initializer(self.config.initializer_range), trainable=True, name='cvt.encoder.stages.2.cls_token')
        self.embedding = TFCvtEmbeddings(self.config, patch_size=config.patch_sizes[self.stage], num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1], stride=config.patch_stride[self.stage], embed_dim=config.embed_dim[self.stage], padding=config.patch_padding[self.stage], dropout_rate=config.drop_rate[self.stage], name='embedding')
        drop_path_rates = tf.linspace(0.0, config.drop_path_rate[self.stage], config.depth[stage])
        drop_path_rates = [x.numpy().item() for x in drop_path_rates]
        self.layers = [TFCvtLayer(config, num_heads=config.num_heads[self.stage], embed_dim=config.embed_dim[self.stage], kernel_size=config.kernel_qkv[self.stage], stride_q=config.stride_q[self.stage], stride_kv=config.stride_kv[self.stage], padding_q=config.padding_q[self.stage], padding_kv=config.padding_kv[self.stage], qkv_projection_method=config.qkv_projection_method[self.stage], qkv_bias=config.qkv_bias[self.stage], attention_drop_rate=config.attention_drop_rate[self.stage], drop_rate=config.drop_rate[self.stage], mlp_ratio=config.mlp_ratio[self.stage], drop_path_rate=drop_path_rates[self.stage], with_cls_token=config.cls_token[self.stage], name=f'layers.{j}') for j in range(config.depth[self.stage])]

    def call(self, hidden_state: tf.Tensor, training: bool=False):
        cls_token = None
        hidden_state = self.embedding(hidden_state, training)
        batch_size, height, width, num_channels = shape_list(hidden_state)
        hidden_size = height * width
        hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, num_channels))
        if self.config.cls_token[self.stage]:
            cls_token = tf.repeat(self.cls_token, repeats=batch_size, axis=0)
            hidden_state = tf.concat((cls_token, hidden_state), axis=1)
        for layer in self.layers:
            layer_outputs = layer(hidden_state, height, width, training=training)
            hidden_state = layer_outputs
        if self.config.cls_token[self.stage]:
            cls_token, hidden_state = tf.split(hidden_state, [1, height * width], 1)
        hidden_state = tf.reshape(hidden_state, shape=(batch_size, height, width, num_channels))
        return (hidden_state, cls_token)

    def build(self, input_shape=None):
        if self.built:
            return
        self.built = True
        if getattr(self, 'embedding', None) is not None:
            with tf.name_scope(self.embedding.name):
                self.embedding.build(None)
        if getattr(self, 'layers', None) is not None:
            for layer in self.layers:
                with tf.name_scope(layer.name):
                    layer.build(None)

Cvt stage (encoder block). Each stage has 2 parts :
- (1) A Convolutional Token Embedding layer
- (2) A Convolutional Transformer Block (layer).
The classification token is added only in the last stage.

Args:
config ([`CvtConfig`]): Model configuration class.
stage (`int`): Stage number.


def by_geopoint(self, lat, long):
    (header, content) = self._http_request(self.BASE_URL, lat=lat, long=long)
    return json.loads(content)

Perform a Yelp Neighborhood API Search based on a geopoint.

Args:
lat      - geopoint latitude
long     - geopoint longitude


def init(self, force_deploy=False, client=None):
    _force_deploy = self.provider_conf.force_deploy
    self.provider_conf.force_deploy = (_force_deploy or force_deploy)
    self._provider_conf = self.provider_conf.to_dict()
    r = api.Resources(self._provider_conf, client=client)
    r.launch()
    roles = r.get_roles()
    networks = r.get_networks()
    return (_to_enos_roles(roles), _to_enos_networks(networks))

Reserve and deploys the nodes according to the resources section

In comparison to the vagrant provider, networks must be characterized
as in the networks key.

Args:
force_deploy (bool): True iff the environment must be redeployed
Raises:
MissingNetworkError: If one network is missing in comparison to
what is claimed.
NotEnoughNodesError: If the `min` constraints can't be met.


def delete(filething):

    dsf_file = DSFFile(filething.fileobj)

    if dsf_file.dsd_chunk.offset_metdata_chunk != 0:
        id3_location = dsf_file.dsd_chunk.offset_metdata_chunk
        dsf_file.dsd_chunk.offset_metdata_chunk = 0
        dsf_file.dsd_chunk.write()

        filething.fileobj.seek(id3_location)
        filething.fileobj.truncate()

Remove tags from a file.

Args:
filething (filething)
Raises:
mutagen.MutagenError


def timeout(seconds=0, minutes=0, hours=0):

    limit = seconds + 60 * minutes + 3600 * hours

    def handler(signum, frame):
        raise TimeoutError('timed out after {} seconds'.format(limit))

    try:
        signal.signal(signal.SIGALRM, handler)
        signal.setitimer(signal.ITIMER_REAL, limit)
        yield
    finally:
        signal.alarm(0)

Add a signal-based timeout to any block of code.
If multiple time units are specified, they will be added together to determine time limit.
Usage:
with timeout(seconds=5):
my_slow_function(...)
Args:
- seconds: The time limit, in seconds.
- minutes: The time limit, in minutes.
- hours: The time limit, in hours.


def _static_check(self):
    my_dtype = self.dtype
    if self._uniform_row_length is not None:
        if self._uniform_row_length.dtype != my_dtype:
            raise ValueError('_uniform_row_length.dtype=' + str(self._uniform_row_length.dtype) + ', not ' + str(my_dtype))
    if self._row_lengths is not None and self._row_lengths.dtype != my_dtype:
        raise ValueError('_row_lengths.dtype=' + str(self._row_lengths.dtype) + ', not ' + str(my_dtype))
    if self._value_rowids is not None and self._value_rowids.dtype != my_dtype:
        raise ValueError('_value_rowids.dtype=' + str(self._value_rowids.dtype) + ', not ' + str(my_dtype))
    if self._nrows is not None and self._nrows.dtype != my_dtype:
        raise ValueError('_nrows.dtype=' + str(self._nrows.dtype) + ', not ' + str(my_dtype))

Checks if the object is internally consistent.

Raises:
ValueError if inconsistent.


def compile_function(node, globals_=None):
    if (not isinstance(node, gast.AST)):
        if (not isinstance(node, six.string_types)):
            raise TypeError
        node = gast.parse(node)
    if isinstance(node, gast.Module):
        for succ in node.body:
            if isinstance(succ, gast.FunctionDef):
                name = succ.name
                break
        else:
            raise ValueError('no function found')
    elif isinstance(node, gast.FunctionDef):
        name = node.name
    else:
        raise TypeError
    module = compile_file(node, globals_)
    return getattr(module, name)

Convert an AST or string into a function with inspectable source.

This function uses `compile_file` internally, but instead of returning the
entire module it will return the function only.

Args:
node: A `FunctionDef` node or a `Module` node which contains at least one
`FunctionDef` node. If a module contains multiple functions, a handle
to the first one will be returned.
globals_: See `compile_file`

Returns:
A handle to the compiled function.

Raises:
TypeError: If the input is not a string or AST.
ValueError: If no function can be found.


def get_effect(self, label: str) -> Effect:

        return self._get_resource(label, self._effects, "effect")

Get an effect instance by label

Args:
label (str): The label for the effect instance

Returns:
Effect class instance


def _batch_prepare_for_model(self, batch_text_or_text_pairs, is_pair: Optional[bool]=None, xpaths: Optional[List[List[int]]]=None, node_labels: Optional[List[List[int]]]=None, add_special_tokens: bool=True, padding_strategy: PaddingStrategy=PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy=TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int]=None, stride: int=0, pad_to_multiple_of: Optional[int]=None, padding_side: Optional[str]=None, return_tensors: Optional[str]=None, return_token_type_ids: Optional[bool]=None, return_attention_mask: Optional[bool]=None, return_overflowing_tokens: bool=False, return_special_tokens_mask: bool=False, return_length: bool=False, verbose: bool=True) -> BatchEncoding:
    batch_outputs = {}
    for idx, example in enumerate(zip(batch_text_or_text_pairs, xpaths)):
        batch_text_or_text_pair, xpaths_example = example
        outputs = self.prepare_for_model(batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair, batch_text_or_text_pair[1] if is_pair else None, xpaths_example, node_labels=node_labels[idx] if node_labels is not None else None, add_special_tokens=add_special_tokens, padding=PaddingStrategy.DO_NOT_PAD.value, truncation=truncation_strategy.value, max_length=max_length, stride=stride, pad_to_multiple_of=None, padding_side=None, return_attention_mask=False, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, return_tensors=None, prepend_batch_axis=False, verbose=verbose)
        for key, value in outputs.items():
            if key not in batch_outputs:
                batch_outputs[key] = []
            batch_outputs[key].append(value)
    batch_outputs = self.pad(batch_outputs, padding=padding_strategy.value, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_attention_mask=return_attention_mask)
    batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
    return batch_outputs

Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
manages a moving window (with user defined stride) for overflowing tokens.

Args:
batch_ids_pairs: list of tokenized input ids or input ids pairs


async def get_pushlog_info(decision_link):
    source_env_prefix = decision_link.context.config['source_env_prefix']
    repo = get_repo(decision_link.task, source_env_prefix)
    rev = get_revision(decision_link.task, source_env_prefix)
    context = decision_link.context
    pushlog_url = context.config['pushlog_url'].format(repo=repo, revision=rev)
    log.info('Pushlog url {}'.format(pushlog_url))
    file_path = os.path.join(context.config['work_dir'], '{}_push_log.json'.format(decision_link.name))
    pushlog_info = (await load_json_or_yaml_from_url(context, pushlog_url, file_path, overwrite=False))
    if (len(pushlog_info['pushes']) != 1):
        log.warning('Pushlog error: expected a single push at {} but got {}!'.format(pushlog_url, pushlog_info['pushes']))
    return pushlog_info

Get pushlog info for a decision LinkOfTrust.

Args:
decision_link (LinkOfTrust): the decision link to get pushlog info about.

Returns:
dict: pushlog info.


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

Corresponds to IDD Field `wb020`
Wet-bulb temperature corresponding to 02.0% annual cumulative frequency of occurrence

Args:
value (float): value for IDD Field `wb020`
Unit: C
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 prune_graph(graph_str, package_name):
    g = read_dot(graph_str)
    nodes = set()
    for (node, attrs) in g.node_attr.iteritems():
        attr = [x for x in attrs if (x[0] == 'label')]
        if attr:
            label = attr[0][1]
            try:
                req_str = _request_from_label(label)
                request = PackageRequest(req_str)
            except PackageRequestError:
                continue
            if (request.name == package_name):
                nodes.add(node)
    if (not nodes):
        raise ValueError(('The package %r does not appear in the graph.' % package_name))
    g_rev = g.reverse()
    accessible_nodes = set()
    access = accessibility(g_rev)
    for node in nodes:
        nodes_ = access.get(node, [])
        accessible_nodes |= set(nodes_)
    inaccessible_nodes = (set(g.nodes()) - accessible_nodes)
    for node in inaccessible_nodes:
        g.del_node(node)
    return write_dot(g)

Prune a package graph so it only contains nodes accessible from the
given package.

Args:
graph_str (str): Dot-language graph string.
package_name (str): Name of package of interest.

Returns:
Pruned graph, as a string.


def add(self, layer):
    if hasattr(layer, '_keras_history'):
        origin_layer = layer._keras_history[0]
        if isinstance(origin_layer, input_layer.InputLayer):
            layer = origin_layer
            logging.warning('Please add `keras.layers.InputLayer` instead of `keras.Input` to Sequential model. `keras.Input` is intended to be used by Functional model.')
    if isinstance(layer, module.Module):
        if not isinstance(layer, base_layer.Layer):
            layer = functional.ModuleWrapper(layer)
    else:
        raise TypeError('The added layer must be an instance of class Layer. Found: ' + str(layer))
    tf_utils.assert_no_legacy_layers([layer])
    if not self._is_layer_name_unique(layer):
        raise ValueError('All layers added to a Sequential model should have unique names. Name "%s" is already the name of a layer in this model. Update the `name` argument to pass a unique name.' % (layer.name,))
    self.built = False
    set_inputs = False
    self._maybe_create_attribute('_self_tracked_trackables', [])
    if not self._self_tracked_trackables:
        if isinstance(layer, input_layer.InputLayer):
            set_inputs = True
        else:
            batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer)
            if batch_shape:
                x = input_layer.Input(batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input')
                layer(x)
                set_inputs = True
        if set_inputs:
            outputs = nest.flatten(layer._inbound_nodes[-1].outputs)
            if len(outputs) != 1:
                raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG)
            self.outputs = outputs
            self.inputs = layer_utils.get_source_inputs(self.outputs[0])
            self.built = True
            self._has_explicit_input_shape = True
    elif self.outputs:
        output_tensor = layer(self.outputs[0])
        if len(nest.flatten(output_tensor)) != 1:
            raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG)
        self.outputs = [output_tensor]
        self.built = True
    if set_inputs or self._graph_initialized:
        self._init_graph_network(self.inputs, self.outputs)
        self._graph_initialized = True
    else:
        self._self_tracked_trackables.append(layer)
        self._handle_deferred_layer_dependencies([layer])
    self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call)

Adds a layer instance on top of the layer stack.

Args:
layer: layer instance.

Raises:
TypeError: If `layer` is not a layer instance.
ValueError: In case the `layer` argument does not
know its input shape.
ValueError: In case the `layer` argument has
multiple output tensors, or is already connected
somewhere else (forbidden in `Sequential` models).


def _InfoBackup(component):
    info = {}
    info['type_name'] = type(component).__name__
    info['string_form'] = str(component)
    filename, lineno = GetFileAndLine(component)
    info['file'] = filename
    info['line'] = lineno
    info['docstring'] = inspect.getdoc(component)
    try:
        info['length'] = str(len(component))
    except (TypeError, AttributeError):
        pass
    return info

Returns a dict with information about the given component.

This function is to be called only in the case that IPython's
oinspect module is not available. The info dict it produces may
contain less information that contained in the info dict produced
by oinspect.

Args:
component: The component to analyze.
Returns:
A dict with information about the component.


def selfSignCert(self, cert, pkey):

        cert.set_issuer(cert.get_subject())
        cert.sign(pkey, self.signing_digest)

Self-sign a certificate.

Args:
cert (OpenSSL.crypto.X509): The certificate to sign.
pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate.

Examples:
Sign a given certificate with a given private key:

cdir.selfSignCert(mycert, myotherprivatekey)

Returns:
None


def data(self, rows=None):

    rows = tf.range(self._capacity) if rows is None else rows
    assert rows.shape.ndims == 1
    episode = tools.nested.map(lambda var: tf.gather(var, rows), self._buffers)
    length = tf.gather(self._length, rows)
    return episode, length

Access a batch of episodes from the memory.

Padding elements after the length of each episode are unspecified and might
contain old data.

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

Returns:
Tuple containing a tuple of transition quantities with batch and time
dimensions, and a batch of sequence lengths.


def bind_parameters(self, value_dict):
    new_circuit = self.copy()
    if (value_dict.keys() > self.parameters):
        raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format([str(p) for p in (value_dict.keys() - self.parameters)]))
    for (parameter, value) in value_dict.items():
        new_circuit._bind_parameter(parameter, value)
    for parameter in value_dict:
        del new_circuit._parameter_table[parameter]
    return new_circuit

Assign parameters to values yielding a new circuit.

Args:
value_dict (dict): {parameter: value, ...}

Raises:
QiskitError: If value_dict contains parameters not present in the circuit

Returns:
QuantumCircuit: copy of self with assignment substitution.


def acos(cls, x: 'TensorFluent') -> 'TensorFluent':

        return cls._unary_op(x, tf.acos, tf.float32)

Returns a TensorFluent for the arccos function.

Args:
x: The input fluent.

Returns:
A TensorFluent wrapping the arccos function.


def get_array_for_fit(observables: dict, track_pt_bin: int, jet_pt_bin: int) -> histogram.Histogram1D:
    for (name, observable) in observables.items():
        if ((observable.track_pt_bin == track_pt_bin) and (observable.jet_pt_bin == jet_pt_bin)):
            return histogram.Histogram1D.from_existing_hist(observable.hist)
    raise ValueError('Cannot find fit with jet pt bin {jet_pt_bin} and track pt bin {track_pt_bin}')

Get a Histogram1D associated with the selected jet and track pt bins.

This is often used to retrieve data for fitting.

Args:
observables (dict): The observables from which the hist should be retrieved.
track_pt_bin (int): Track pt bin of the desired hist.
jet_ptbin (int): Jet pt bin of the desired hist.
Returns:
Histogram1D: Converted TH1 or uproot histogram.
Raises:
ValueError: If the requested observable couldn't be found.


def GetNumberOfEventSources(self):
    number_of_event_sources = self._CountStoredAttributeContainers(self._CONTAINER_TYPE_EVENT_SOURCE)
    number_of_event_sources += self._GetNumberOfSerializedAttributeContainers(self._CONTAINER_TYPE_EVENT_SOURCE)
    return number_of_event_sources

Retrieves the number event sources.

Returns:
int: number of event sources.


def index_buffer(self, buffer, index_element_size=4):
    if (not (type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes])):
        raise VAOError('buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance')
    if isinstance(buffer, numpy.ndarray):
        buffer = self.ctx.buffer(buffer.tobytes())
    if isinstance(buffer, bytes):
        buffer = self.ctx.buffer(data=buffer)
    self._index_buffer = buffer
    self._index_element_size = index_element_size

Set the index buffer for this VAO

Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``

Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4


def get_image_features(self, pixel_values: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]]=None, vision_feature_select_strategy: Optional[str]=None, **kwargs):
    vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
    vision_feature_select_strategy = vision_feature_select_strategy if vision_feature_select_strategy is not None else self.config.vision_feature_select_strategy
    if vision_feature_select_strategy not in ['default', 'full']:
        raise ValueError(f'Unexpected select feature strategy: {self.config.vision_feature_select_strategy}')
    kwargs = {k: v for k, v in kwargs.items() if v is not None}
    image_outputs = self.vision_tower(pixel_values, output_hidden_states=True, **kwargs)
    if isinstance(vision_feature_layer, int):
        selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
        if vision_feature_select_strategy == 'default':
            selected_image_feature = selected_image_feature[:, 1:]
    else:
        hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
        if vision_feature_select_strategy == 'default':
            hs_pool = [hs[:, 1:] for hs in hs_pool]
        selected_image_feature = torch.cat(hs_pool, dim=-1)
    image_features = self.multi_modal_projector(selected_image_feature)
    if 'image_sizes' in kwargs:
        split_sizes = [height
        image_features = torch.split(image_features.squeeze(0), split_sizes)
    else:
        image_features = list(image_features)
    return image_features

Obtains image last hidden states from the vision tower and apply multimodal projection.

Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
The tensors corresponding to the input images.
vision_feature_layer (`Union[int, List[int]]`, *optional*):
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
vision_feature_select_strategy (`str`, *optional*):
The feature selection strategy used to select the vision feature from the vision backbone.
Can be one of `"default"` or `"full"`
Returns:
image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).


def get_changeset(changeset):
    url = 'https:
    return ET.fromstring(requests.get(url).content)

Get the changeset using the OSM API and return the content as a XML
ElementTree.

Args:
changeset: the id of the changeset.


def stitch_values(values_and_indices_list):
    length = 0
    for values_and_indices in values_and_indices_list:
        length += len(values_and_indices[0])
    result = [None] * length
    for values_and_indices in values_and_indices_list:
        if values_and_indices and values_and_indices[0]:
            for v, i in zip(*values_and_indices):
                assert result[i] is None
                result[i] = v
    return result

Stitch values together according to their indices.

Args:
values_and_indices_list: a list of tuples of values and indices indicating
the values and positions in the returned list.

Returns:
a stitched list of values.


def _ref(self):
    return self._variable

Returns a reference to this variable.

You usually do not need to call this method as all ops that need a reference
to the variable call it automatically.

Returns is a `Tensor` which holds a reference to the variable.  You can
assign a new value to the variable by passing the tensor to an assign op.
See `tf.Variable.value` if you want to get the value of the
variable.

Returns:
A `Tensor` that is a reference to the variable.


def peek(self) -> str:
    try:
        return self.input[self.offset]
    except IndexError:
        raise EndOfInput(self)

Return the next character without advancing offset.

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


def device_id_to_slug(did):
    try:
        device_slug = IOTileDeviceSlug(did, allow_64bits=False)
    except ValueError:
        raise ArgumentError('Unable to recognize {} as a device id'.format(did))
    return str(device_slug)

Converts a device id into a correct device slug.

Args:
did (long) : A device id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX
Returns:
str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format
Raises:
ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string


def _detect(self):
    results = []
    for c in self.contracts:
        for f in c.functions:
            if (f.contract != c):
                continue
            if (f.view or f.pure):
                if f.contains_assembly:
                    attr = ('view' if f.view else 'pure')
                    info = '{}.{} ({}) is declared {} but contains assembly code\n'
                    info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
                    json = self.generate_json_result(info)
                    self.add_function_to_json(f, json)
                    json['elements'].append({'type': 'info', 'contains_assembly': True})
                    results.append(json)
                variables_written = f.all_state_variables_written()
                if variables_written:
                    attr = ('view' if f.view else 'pure')
                    info = '{}.{} ({}) is declared {} but changes state variables:\n'
                    info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
                    for variable_written in variables_written:
                        info += '\t- {}.{}\n'.format(variable_written.contract.name, variable_written.name)
                    json = self.generate_json_result(info)
                    self.add_function_to_json(f, json)
                    self.add_variables_to_json(variables_written, json)
                    json['elements'].append({'type': 'info', 'contains_assembly': False})
                    results.append(json)
    return results

Detect the constant function changing the state

Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'}


def extract_cookies(self, response, request, referrer_host=None):
    new_response = HTTPResponseInfoWrapper(response)
    new_request = convert_http_request(request, referrer_host)
    self._cookie_jar.extract_cookies(new_response, new_request)

Wrapped ``extract_cookies``.

Args:
response: An instance of :class:`.http.request.Response`.
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.


def Serialize(self, writer):

        writer.WriteHashes(self.HashStart)
        if self.HashStop is not None:
            writer.WriteUInt256(self.HashStop)

Serialize object.

Args:
writer (neo.IO.BinaryWriter):


def save_checkpoint(model, filename, optimizer=None, meta=None):

    if meta is None:
        meta = {}
    elif not isinstance(meta, dict):
        raise TypeError('meta must be a dict or None, but got {}'.format(
            type(meta)))
    meta.update(mmcv_version=mmcv.__version__, time=time.asctime())

    mmcv.mkdir_or_exist(osp.dirname(filename))
    if hasattr(model, 'module'):
        model = model.module

    checkpoint = {
        'meta': meta,
        'state_dict': weights_to_cpu(model.state_dict())
    }
    if optimizer is not None:
        checkpoint['optimizer'] = optimizer.state_dict()

    torch.save(checkpoint, filename)

Save checkpoint to file.

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

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


def create_alias(alias_name, alias_command):
    (alias_name, alias_command) = (alias_name.strip(), alias_command.strip())
    alias_table = get_alias_table()
    if (alias_name not in alias_table.sections()):
        alias_table.add_section(alias_name)
    alias_table.set(alias_name, 'command', alias_command)
    _commit_change(alias_table)

Create an alias.

Args:
alias_name: The name of the alias.
alias_command: The command that the alias points to.


def sg_transpose(tensor, opt):
    assert (opt.perm is not None), 'perm is mandatory'
    return tf.transpose(tensor, opt.perm, name=opt.name)

r"""Permutes the dimensions according to `opt.perm`.

See `tf.transpose()` in tensorflow.

Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace current tensor's name.

Returns:
A `Tensor`.


def _get_format(format, fname, inp=None):
    fmt = None
    err = True
    if (format is not None):
        if (format in fmt_to_exts):
            fmt = format
            err = False
    elif fname:
        file_ext = os.path.splitext(fname)[1][len(os.path.extsep):]
        for (fmt_name, exts) in fmt_to_exts.items():
            if (file_ext in exts):
                fmt = fmt_name
                err = False
    if (fmt is None):
        if (inp is not None):
            fmt = _guess_fmt_from_bytes(inp)
            err = False
    if err:
        err_string = 'Failed to guess markup format based on: '
        what = []
        for (k, v) in {format: 'specified format argument', fname: 'filename', inp: 'input string'}.items():
            if k:
                what.append(v)
        if (not what):
            what.append('nothing to guess format from!')
        err_string += ', '.join(what)
        raise AnyMarkupError(err_string)
    return fmt

Try to guess markup format of given input.

Args:
format: explicit format override to use
fname: name of file, if a file was used to read `inp`
inp: optional bytestring to guess format of (can be None, if markup
format is to be guessed only from `format` and `fname`)
Returns:
guessed format (a key of fmt_to_exts dict)
Raises:
AnyMarkupError if explicit format override has unsupported value
or if it's impossible to guess the format


def accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float:
    examples_len = len(y_true)
    correct = sum([(y1 == y2) for (y1, y2) in zip(y_true, y_predicted)])
    return ((correct / examples_len) if examples_len else 0)

Calculate accuracy in terms of absolute coincidence

Args:
y_true: array of true values
y_predicted: array of predicted values

Returns:
portion of absolutely coincidental samples


def AddForwardedIp(self, address, interface):

    address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address
    args = ['add', 'to', 'local', address]
    options = self._CreateRouteOptions(dev=interface)
    self._RunIpRoute(args=args, options=options)

Configure a new IP address on the network interface.

Args:
address: string, the IP address to configure.
interface: string, the output device to use.


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

Return converted `PulseInstruction`.

Args:
shift(int): Offset time.
instruction (PulseInstruction): drive instruction.
Returns:
dict: Dictionary of required parameters.


def __directory_list_descriptor(self, configs):
    descriptor = {'kind': 'discovery
    items = []
    for config in configs:
        item_descriptor = self.__item_descriptor(config)
        if item_descriptor:
            items.append(item_descriptor)
    if items:
        descriptor['items'] = items
    return descriptor

Builds a directory list for an API.

Args:
configs: List of dicts containing the service configurations to list.

Returns:
A dictionary that can be deserialized into JSON in discovery list format.

Raises:
ApiConfigurationError: If there's something wrong with the API
configuration, such as a multiclass API decorated with different API
descriptors (see the docstring for api()), or a repeated method
signature.


def _LastEntryTimestamp(dct, upper_bound_timestamp):

    if upper_bound_timestamp is None:
      upper_bound = lambda _: True
    else:
      upper_bound = lambda key: key <= upper_bound_timestamp

    try:
      return max(filter(upper_bound, iterkeys(dct)))
    except ValueError:
      return None

Searches for greatest timestamp lower than the specified one.

Args:
dct: A dictionary from timestamps to some items.
upper_bound_timestamp: An upper bound for timestamp to be returned.

Returns:
Greatest timestamp that is lower than the specified one. If no such value
exists, `None` is returned.


def AddSerializedFile(self, serialized_file_desc_proto):
    from google.protobuf import descriptor_pb2
    file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(serialized_file_desc_proto)
    self.Add(file_desc_proto)

Adds the FileDescriptorProto and its types to this pool.

Args:
serialized_file_desc_proto: A bytes string, serialization of the
FileDescriptorProto to add.


def _parse_description(details):

    description = details.find("div", {"class": "detailPopis"})

    if not description:
        return None

    ekniha = description[0].find("div", {"class": "ekniha"})
    if ekniha:
        ekniha[0].replaceWith(dhtmlparser.HTMLElement(""))

    detail = description[0].find("p", {"class": "detailKat"})
    if detail:
        detail[0].replaceWith(dhtmlparser.HTMLElement(""))

    description = dhtmlparser.removeTags(description[0]).strip()

    if not description:
        return None

    return description

Parse description of the book.

Args:
details (obj): HTMLElement containing slice of the page with details.

Returns:
str/None: Details as string with currency or None if not found.


def encode(self):
    blob = bytearray()
    for record in self.records:
        blob += record.encode()
    header = struct.pack('<LL', self.SCRIPT_MAGIC, (len(blob) + self.SCRIPT_HEADER_LENGTH))
    blob = (header + blob)
    sha = hashlib.sha256()
    sha.update(blob)
    hash_value = sha.digest()[:16]
    return (bytearray(hash_value) + blob)

Encode this record into a binary blob.

This binary blob could be parsed via a call to FromBinary().

Returns:
bytearray: The binary encoded script.


def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3):
    if (api_version not in [3]):
        raise RuntimeError(('Unsupported api version: %s, expected 3.' % api_version))
    if (destination is None):
        destination = self.server_name
        cipher = self._GetServerCipher()
    else:
        remote_public_key = self._GetRemotePublicKey(destination)
        cipher = Cipher(self.common_name, self.private_key, remote_public_key)
    if (timestamp is None):
        self.timestamp = timestamp = int((time.time() * 1000000))
    packed_message_list = rdf_flows.PackedMessageList(timestamp=timestamp)
    self.EncodeMessageList(message_list, packed_message_list)
    result.encrypted_cipher_metadata = cipher.encrypted_cipher_metadata
    result.encrypted_cipher = cipher.encrypted_cipher
    serialized_message_list = packed_message_list.SerializeToString()
    (result.packet_iv, result.encrypted) = cipher.Encrypt(serialized_message_list)
    result.hmac = cipher.HMAC(result.encrypted)
    result.full_hmac = cipher.HMAC(result.encrypted, result.encrypted_cipher, result.encrypted_cipher_metadata, result.packet_iv.SerializeToString(), struct.pack('<I', api_version))
    result.api_version = api_version
    if isinstance(result, rdfvalue.RDFValue):
        result.num_messages = len(message_list)
    return timestamp

Accepts a list of messages and encodes for transmission.

This function signs and then encrypts the payload.

Args:
message_list: A MessageList rdfvalue containing a list of GrrMessages.
result: A ClientCommunication rdfvalue which will be filled in.
destination: The CN of the remote system this should go to.
timestamp: A timestamp to use for the signed messages. If None - use the
current time.
api_version: The api version which this should be encoded in.

Returns:
A nonce (based on time) which is inserted to the encrypted payload. The
client can verify that the server is able to decrypt the message and
return the nonce.

Raises:
RuntimeError: If we do not support this api version.


def get_poi_types(self, **kwargs):

        params = {
            'cultureInfo': util.language_code(kwargs.get('lang'))
        }

        result = self.make_request('geo', 'get_poi_types', **params)

        values = result.get('types', [])
        return True, [emtype.PoiType(**a) for a in values]

Obtain POI types.

Args:
lang (str): Language code (*es* or *en*).

Returns:
Status boolean and parsed response (list[PoiType]), or message string
in case of error.


def lookup_symbol(self, name, namespace_stack):
    symbol = Symbol(name, name.split('::'), namespace_stack)
    assert symbol.parts
    if (symbol.parts[0] == ''):
        symbol.parts = symbol.parts[1:]
    elif (namespace_stack is not None):
        result = self._lookup_in_all_namespaces(symbol)
        if result:
            return result
    return self._lookup_global(symbol)

Returns AST node and module for symbol if found.

Args:
name: 'name of the symbol to lookup'
namespace_stack: None or ['namespaces', 'in', 'current', 'scope']

Returns:
(ast.Node, module (ie, any object stored with symbol)) if found

Raises:
Error if the symbol cannot be found.


def get_summary(self):
    func_summaries = [f.get_summary() for f in self.functions]
    modif_summaries = [f.get_summary() for f in self.modifiers]
    return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries)

Return the function summary

Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)


def join_dags(self, names=None):
    return self._client.send(Request(action='join_dags', payload={'names': names})).success

Wait for the specified dags to terminate.

This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.

Args:
names (list): The names of the dags that have to terminate.

Returns:
bool: True if all the signal was sent successfully.


def ParseLines(lines, message, allow_unknown_extension=False,
               allow_field_number=False):

  parser = _Parser(allow_unknown_extension, allow_field_number)
  return parser.ParseLines(lines, message)

Parses an text representation of a protocol message into a message.

Args:
lines: An iterable of lines of a message's text representation.
message: A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing extensions and keep
parsing
allow_field_number: if True, both field number and field name are allowed.

Returns:
The same message passed as argument.

Raises:
ParseError: On text parsing problems.


def getUserForHost(self, user, host):

        for name in iterFqdnUp(host):
            usercert = '%s@%s' % (user, name)
            if self.isUserCert(usercert):
                return usercert

Gets the name of the first existing user cert for a given user and host.

Args:
user (str): The name of the user.
host (str): The name of the host.

Examples:
Get the name for the "myuser" user cert at "cool.vertex.link":

usercertname = cdir.getUserForHost('myuser', 'cool.vertex.link')

Returns:
str: The cert name, if exists.


def postprocess(self, args: argparse.Namespace):
    names = {k for k in self.pytype_single_args if hasattr(args, k)}
    opt_map = {k: self._pytype_arg_map[k].long_opt for k in names}
    pytype_config.Postprocessor(names, opt_map, args).process()

Postprocesses the subset of pytype_single_args that appear in args.

Args:
args: an argparse.Namespace.


def get_controller(self, path):
    path_info = path.lstrip('/').split('/', 2)
    try:
        return self._routes.get(((path_info[0] + '/') + path_info[1]))
    except (IndexError, KeyError):
        return self._routes.get((path_info[0] or 'index'))

Return controller that handle given path.

Args:
- path: requested path, like: /blog/post_view/15


def plot_title(ax, pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None):
    current_title = ax.get_title()
    if (not current_title):
        current_title = ((pretitle + title) + posttitle)
    title_arg = dict_if_none(title_arg)
    ax.set_title(current_title, fontsize=title_fontsize, **title_arg)

Set title options of a matplotlib plot

Args:
ax: matplotlib axes
pretitle(str): String to include before the general title of the figure
posttitle (str): String to include after the general title of the figure
title (str): Set the title for the figure
title_fontsize (int): Defines the size of the title's font
title_arg (dict): Addition arguments for matplotlib.title() call


def get_available_palettes(chosen_palette):
    result = None
    try:
        result = ALL_PALETTES[:(ALL_PALETTES.index(chosen_palette) + 1)]
    except ValueError:
        pass
    return result

Given a chosen palette, returns tuple of those available,
or None when not found.

Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.

Returns:
Boolean, None: is tty or None if not found.


def load(cls, fh):

        dat = fh.read()
        try:
            ret = cls.from_json(dat)
        except:
            ret = cls.from_yaml(dat)
        return ret

Load json or yaml data from file handle.

Args:
fh (file): File handle to load from.

Examlple:
>>> with open('data.json', 'r') as json:
>>>    jsdata = composite.load(json)
>>>
>>> with open('data.yml', 'r') as yml:
>>>    ymldata = composite.load(yml)


def sample(self, num_rows=1):

        self.check_fit()

        res = {}
        means = np.zeros(self.covariance.shape[0])
        size = (num_rows,)

        clean_cov = np.nan_to_num(self.covariance)
        samples = np.random.multivariate_normal(means, clean_cov, size=size)

        for i, (label, distrib) in enumerate(self.distribs.items()):
            cdf = stats.norm.cdf(samples[:, i])
            res[label] = distrib.percent_point(cdf)

        return pd.DataFrame(data=res)

Creates sintentic values stadistically similar to the original dataset.

Args:
num_rows: `int` amount of samples to generate.

Returns:
np.ndarray: Sampled data.


def image_summary(predictions, targets, hparams):

  del hparams
  results = tf.cast(tf.argmax(predictions, axis=-1), tf.uint8)
  gold = tf.cast(targets, tf.uint8)
  summary1 = tf.summary.image("prediction", results, max_outputs=2)
  summary2 = tf.summary.image("data", gold, max_outputs=2)
  summary = tf.summary.merge([summary1, summary2])
  return summary, tf.zeros_like(predictions)

Reshapes predictions and passes it to tensorboard.

Args:
predictions : The predicted image (logits).
targets : The ground truth.
hparams: model hparams.

Returns:
summary_proto: containing the summary images.
weights: A Tensor of zeros of the same shape as predictions.


def get_status(self, batch_id):
    with self._lock:
        if self._batch_committed(batch_id):
            return ClientBatchStatus.COMMITTED
        if (batch_id in self._invalid):
            return ClientBatchStatus.INVALID
        if (batch_id in self._pending):
            return ClientBatchStatus.PENDING
        return ClientBatchStatus.UNKNOWN

Returns the status enum for a batch.

Args:
batch_id (str): The id of the batch to get the status for

Returns:
int: The status enum


class IntSoftmax(nn.Module):

    def __init__(self, output_bit, quant_mode=False, force_dequant='none'):
        super().__init__()
        self.output_bit = output_bit
        self.max_bit = 32
        self.quant_mode = quant_mode
        if force_dequant in ['nonlinear', 'softmax']:
            logger.info('Force dequantize softmax')
            self.quant_mode = False
        self.act = QuantAct(16, quant_mode=self.quant_mode)
        self.x0 = -0.6931
        self.const = 30
        self.coef = [0.35815147, 0.96963238, 1.0]
        self.coef[1] /= self.coef[0]
        self.coef[2] /= self.coef[0]

    def int_polynomial(self, x_int, scaling_factor):
        with torch.no_grad():
            b_int = torch.floor(self.coef[1] / scaling_factor)
            c_int = torch.floor(self.coef[2] / scaling_factor ** 2)
        z = (x_int + b_int) * x_int + c_int
        scaling_factor = self.coef[0] * scaling_factor ** 2
        return (z, scaling_factor)

    def int_exp(self, x_int, scaling_factor):
        with torch.no_grad():
            x0_int = torch.floor(self.x0 / scaling_factor)
        x_int = torch.max(x_int, self.const * x0_int)
        q = floor_ste.apply(x_int / x0_int)
        r = x_int - x0_int * q
        exp_int, exp_scaling_factor = self.int_polynomial(r, scaling_factor)
        exp_int = torch.clamp(floor_ste.apply(exp_int * 2 ** (self.const - q)), min=0)
        scaling_factor = exp_scaling_factor / 2 ** self.const
        return (exp_int, scaling_factor)

    def forward(self, x, scaling_factor):
        if not self.quant_mode:
            return (nn.functional.softmax(x, dim=-1), None)
        x_int = x / scaling_factor
        x_int_max, _ = x_int.max(dim=-1, keepdim=True)
        x_int = x_int - x_int_max
        exp_int, exp_scaling_factor = self.int_exp(x_int, scaling_factor)
        exp, exp_scaling_factor = self.act(exp_int, exp_scaling_factor)
        exp_int = exp / exp_scaling_factor
        exp_int_sum = exp_int.sum(dim=-1, keepdim=True)
        factor = floor_ste.apply(2 ** self.max_bit / exp_int_sum)
        exp_int = floor_ste.apply(exp_int * factor / 2 ** (self.max_bit - self.output_bit))
        scaling_factor = 1 / 2 ** self.output_bit
        return (exp_int * scaling_factor, scaling_factor)

Quantized version of `torch.nn.Softmax`. Adds quantization-specific arguments on top of `torch.nn.Softmax`.

Args:
output_bit (`int`):
Bitwidth for the layer output activation.
quant_mode (`bool`, *optional*, defaults to `False`):
Whether or not the layer is quantized.
force_dequant (`str`, *optional*, defaults to `"none"`):
Force dequantize the layer if either "softmax" or "nonlinear" is given.


def _merge_doc(original, to_merge):

    if not original:
        return to_merge or ''
    if not to_merge:
        return original or ''
    sections = []
    for name in ('usage', 'arguments', 'options'):
        sections.append(_merge_section(
            _get_section(name, original),
            _get_section(name, to_merge)
        ))
    return format_usage('\n\n'.join(s for s in sections).rstrip())

Merge two usage strings together.

Args:
original: The source of headers and initial section lines.
to_merge: The source for the additional section lines to append.

Returns:
A new usage string that contains information from both usage strings.


def recipe_dynamic_costs(config, dcm_account, auth_read, configuration_sheet_url, auth_write, bigquery_dataset):
    dynamic_costs(config, {'auth': auth_read, 'account': dcm_account, 'sheet': {'template': {'url': 'https:

Calculate DV360 cost at the dynamic creative combination level.

Args:
dcm_account (string) - NA
auth_read (authentication) - Credentials used for reading data.
configuration_sheet_url (string) - NA
auth_write (authentication) - Credentials used for writing data.
bigquery_dataset (string) - NA


def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1):

  if temperature == 0.0:

    logits_shape = shape_list(logits)
    argmax = tf.argmax(tf.reshape(logits, [-1, logits_shape[-1]]), axis=1)
    return tf.reshape(argmax, logits_shape[:-1])
  else:
    assert temperature > 0.0

    if sampling_keep_top_k != -1:
      if sampling_keep_top_k <= 0:
        raise ValueError("sampling_keep_top_k must either be -1 or positive.")

      vocab_size = shape_list(logits)[1]

      k_largest = tf.contrib.nn.nth_element(
          logits, n=sampling_keep_top_k, reverse=True)
      k_largest = tf.tile(tf.reshape(k_largest, [-1, 1]), [1, vocab_size])

      logits = tf.where(tf.less_equal(logits, k_largest),
                        tf.ones_like(logits)*-1e6, logits)

    reshaped_logits = (
        tf.reshape(logits, [-1, shape_list(logits)[-1]]) / temperature)
    choices = tf.multinomial(reshaped_logits, 1)
    choices = tf.reshape(choices,
                         shape_list(logits)[:logits.get_shape().ndims - 1])
    return choices

Either argmax or random sampling.

Args:
logits: a Tensor.
temperature: a float  0.0=argmax 1.0=random
sampling_keep_top_k: If not -1, only sample from the top k logits.
Returns:
a Tensor with one fewer dimension than logits.


def unzip_file(source_file, dest_dir=None, mkdir=False):

    if dest_dir is None:
        dest_dir, fname = os.path.split(source_file)
    elif not os.path.isdir(dest_dir):
        if mkdir:
            preparedir(dest_dir)
        else:
            created = preparedir(dest_dir, False)
            if not created:
                raise ValueError("Failed to find %s." % dest_dir)

    with zipfile.ZipFile(source_file) as zf:
        for member in zf.infolist():
            words = member.filename.split('\\')
            for word in words[:-1]:
                drive, word = os.path.splitdrive(word)
                head, word = os.path.split(word)
                if word in (os.curdir, os.pardir, ''):
                    continue
                dest_dir = os.path.join(dest_dir, word)
            zf.extract(member, dest_dir)

Unzip a compressed file.

Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't exist (Default: False)


def best_case(self, matrix, m_list, indices_left):

        m_indices = []
        fraction_list = []
        for m in m_list:
            m_indices.extend(m[2])
            fraction_list.extend([m[0]] * m[1])

        indices = list(indices_left.intersection(m_indices))

        interaction_matrix = matrix[indices, :][:, indices]

        fractions = np.zeros(len(interaction_matrix)) + 1
        fractions[:len(fraction_list)] = fraction_list
        fractions = np.sort(fractions)

        sums = 2 * np.sum(matrix[indices], axis=1)
        sums = np.sort(sums)

        step1 = np.sort(interaction_matrix) * (1 - fractions)
        step2 = np.sort(np.sum(step1, axis=1))
        step3 = step2 * (1 - fractions)
        interaction_correction = np.sum(step3)

        if self._algo == self.ALGO_TIME_LIMIT:
            elapsed_time = datetime.utcnow() - self._start_time
            speedup_parameter = elapsed_time.total_seconds() / 1800
            avg_int = np.sum(interaction_matrix, axis=None)
            avg_frac = np.average(np.outer(1 - fractions, 1 - fractions))
            average_correction = avg_int * avg_frac

            interaction_correction = average_correction * speedup_parameter \
                + interaction_correction * (1 - speedup_parameter)

        best_case = np.sum(matrix) + np.inner(sums[::-1], fractions - 1) \
            + interaction_correction

        return best_case

Computes a best case given a matrix and manipulation list.

Args:
matrix: the current matrix (with some permutations already
performed)
m_list: [(multiplication fraction, number_of_indices, indices,
species)] describing the manipulation
indices: Set of indices which haven't had a permutation
performed on them.


def get_tag(self, main_type, sub_type, unique_id, tag, owner=None, params=None):

        params = params or {}

        return self.tag(main_type, sub_type, unique_id, tag, owner=owner, params=params)

Args:
owner:
main_type:
sub_type:
unique_id:
tag:
params:

Return:


def get_component(self, colour, tolerance=0, default=None):

        if not (0 <= tolerance <= np.sqrt(195075)):
            raise LegendError('Tolerance must be between 0 and 441.67')

        for decor in self.__list:
            if colour.lower() == decor.colour:
                return decor.component

        r1, g1, b1 = utils.hex_to_rgb(colour)

        best_match = '
        best_match_dist = np.sqrt(r1**2. + g1**2. + b1**2.)

        for decor in self.__list:
            r2, g2, b2 = decor.rgb
            distance = np.sqrt((r2-r1)**2. + (g2-g1)**2. + (b2-b1)**2.)
            if distance < best_match_dist:
                best_match = decor.component
                best_match_dist = distance
                best_match_colour = decor.colour

        if best_match_dist <= tolerance:
            return best_match
        else:
            with warnings.catch_warnings():
                warnings.simplefilter("always")
                w = "No match found for {0} ".format(colour.lower())
                w += "with tolerance of {0}. Best match is ".format(tolerance)
                w += "{0}, {1}".format(best_match.summary(), best_match_colour)
                w += ", d={0}".format(best_match_dist)
                warnings.warn(w)

            return default

Get the component corresponding to a display colour. This is for
generating a Striplog object from a colour image of a striplog.

Args:
colour (str): The hex colour string to look up.
tolerance (float): The colourspace distance within which to match.
default (component or None): The component to return in the event
of no match.

Returns:
component. The component best matching the provided colour.


def load(hdf5_filename):

    hdf5_filename = os.path.expanduser(hdf5_filename)

    try:
        f = h5py.File(hdf5_filename, "r")

        data_layers = f.get('image').get('CUTOUT')
    except Exception as e:
        raise ValueError("Could not load file {0} for conversion. {}".format(
                         hdf5_filename, e))
        raise

    return numpy.array(data_layers)

Import a HDF5 file into a numpy array.

Arguments:
hdf5_filename:  A string filename of a HDF5 datafile

Returns:
A numpy array with data from the HDF5 file


def search(self, resources_request=None):

        name_pattern, version_range = self._parse_request(resources_request)

        family_names = set(
            x.name for x in iter_package_families(paths=self.package_paths)
            if fnmatch.fnmatch(x.name, name_pattern)
        )

        family_names = sorted(family_names)

        if self.resource_type:
            resource_type = self.resource_type
        elif version_range or len(family_names) == 1:
            resource_type = "package"
        else:
            resource_type = "family"

        if not family_names:
            return resource_type, []

        if resource_type == "family":
            results = [ResourceSearchResult(x, "family") for x in family_names]
            return "family", results

        results = []

        for name in family_names:
            it = iter_packages(name, version_range, paths=self.package_paths)
            packages = sorted(it, key=lambda x: x.version)

            if self.latest and packages:
                packages = [packages[-1]]

            for package in packages:

                try:
                    if package.timestamp:
                        if self.after_time and package.timestamp < self.after_time:
                            continue
                        if self.before_time and package.timestamp >= self.before_time:
                            continue

                    if self.validate:
                        package.validate_data()

                except ResourceContentError as e:
                    if resource_type == "package":
                        result = ResourceSearchResult(package, "package", str(e))
                        results.append(result)

                    continue

                if resource_type == "package":
                    result = ResourceSearchResult(package, "package")
                    results.append(result)
                    continue

                try:
                    for variant in package.iter_variants():
                        if self.validate:
                            try:
                                variant.validate_data()
                            except ResourceContentError as e:
                                result = ResourceSearchResult(
                                    variant, "variant", str(e))
                                results.append(result)
                                continue

                        result = ResourceSearchResult(variant, "variant")
                        results.append(result)

                except ResourceContentError:

                    continue

        return resource_type, results

Search for resources.

Args:
resources_request (str): Resource to search, glob-style patterns
are supported. If None, returns all matching resource types.

Returns:
2-tuple:
- str: resource type (family, package, variant);
- List of `ResourceSearchResult`: Matching resources. Will be in
alphabetical order if families, and version ascending for
packages or variants.


def not_storable(_type):

    return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type)))

Helper for tagging unserializable types.

Arguments:

_type (type): type to be ignored.

Returns:

Storable: storable instance that does not poke.


def read_from_file(self, filename, negative_occupancies='warn'):
    valid_negative_occupancies = ['warn', 'raise', 'ignore', 'zero']
    if (negative_occupancies not in valid_negative_occupancies):
        raise ValueError('"{}" is not a valid value for the keyword `negative_occupancies`.'.format(negative_occupancies))
    with open(filename, 'r') as file_in:
        file_in.readline()
        (self.number_of_k_points, self.number_of_bands, self.number_of_ions) = [int(f) for f in get_numbers_from_string(file_in.readline())]
        self.read_in = file_in.read()
    self.parse_k_points()
    self.parse_bands()
    self.parse_occupancy()
    if np.any((self.occupancy[(:, 1)] < 0)):
        if (negative_occupancies == 'warn'):
            warnings.warn('One or more occupancies in your PROCAR file are negative.')
        elif (negative_occupancies == 'raise'):
            raise ValueError('One or more occupancies in your PROCAR file are negative.')
        elif (negative_occupancies == 'zero'):
            self.occupancy[(self.occupancy < 0)] = 0.0
    self.parse_projections()
    self.sanity_check()
    self.read_in = None
    if self.calculation['spin_polarised']:
        self.data = self.projection_data.reshape(self.spin_channels, self.number_of_k_points, self.number_of_bands, (self.number_of_ions + 1), self.number_of_projections)[(:, :, :, :, 1:)].swapaxes(0, 1).swapaxes(1, 2)
    else:
        self.data = self.projection_data.reshape(self.number_of_k_points, self.number_of_bands, self.spin_channels, (self.number_of_ions + 1), self.number_of_projections)[(:, :, :, :, 1:)]

Reads the projected wavefunction character of each band from a VASP PROCAR file.

Args:
filename (str): Filename of the PROCAR file.
negative_occupancies (:obj:Str, optional): Sets the behaviour for handling
negative occupancies. Default is `warn`.

Returns:
None

Note:
Valid options for `negative_occupancies` are:
`warn` (default): Warn that some partial occupancies are negative,
but do not alter any values.
`raise`:          Raise an AttributeError.
`ignore`:         Do nothing.
`zero`:           Negative partial occupancies will be set to zero.


def regroup_if_changed(group, op_list, name=None):

  has_deltas = isinstance(op_list, sequence_with_deltas.SequenceWithDeltas)
  if (group is None or len(group.control_inputs) != len(op_list) or
      (has_deltas and op_list.has_changed())):
    if has_deltas:
      op_list.mark()
    if op_list:
      return tf.group(*op_list, name=name)
    else:
      return tf.no_op(name=name)
  else:
    return group

Creates a new group for op_list if it has changed.

Args:
group: The current group. It is returned if op_list is unchanged.
op_list: The list of operations to check.
name: The name to use if a new group is created.
Returns:
Either group or a new group (or if op_list is empty then no_op).


def Scalars(self, run, tag):

    accumulator = self.GetAccumulator(run)
    return accumulator.Scalars(tag)

Retrieve the scalar events associated with a run and tag.

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

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

Returns:
An array of `event_accumulator.ScalarEvents`.


def period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time):

        neighbor_x = self.x[::stride, ::stride]
        neighbor_y = self.y[::stride, ::stride]
        neighbor_kd_tree = cKDTree(np.vstack((neighbor_x.ravel(), neighbor_y.ravel())).T)
        neighbor_prob = np.zeros((self.data.shape[0], neighbor_x.shape[0], neighbor_x.shape[1]))
        print('Forecast Hours: {0}-{1}'.format(start_time, end_time))
        for m in range(len(self.members)):
            period_max = self.data[m,start_time:end_time,:,:].max(axis=0)
            valid_i, valid_j = np.where(period_max >= threshold)
            print(self.members[m], len(valid_i))
            if len(valid_i) > 0:
                var_kd_tree = cKDTree(np.vstack((self.x[valid_i, valid_j], self.y[valid_i, valid_j])).T)
                exceed_points = np.unique(np.concatenate(var_kd_tree.query_ball_tree(neighbor_kd_tree, radius))).astype(int)
                exceed_i, exceed_j = np.unravel_index(exceed_points, neighbor_x.shape)
                neighbor_prob[m][exceed_i, exceed_j] = 1
                if smoothing > 0:
                    neighbor_prob[m] = gaussian_filter(neighbor_prob[m], smoothing,mode='constant')
        return neighbor_prob

Calculate the neighborhood probability over the full period of the forecast

Args:
radius: circular radius from each point in km
smoothing: width of Gaussian smoother in km
threshold: intensity of exceedance
stride: number of grid points to skip for reduced neighborhood grid

Returns:
(neighborhood probabilities)


def _convert_to_sparse_tensors(sp_inputs):
    if isinstance(sp_inputs, list):
        return [_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs]
    if isinstance(sp_inputs, tuple):
        return (_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs)
    raise TypeError('Inputs must be a list or tuple.')

Convert `sp_inputs` to `SparseTensor` objects and return them.

Args:
sp_inputs: `list` or `tuple` of `SparseTensor` or `SparseTensorValue`
objects.

Returns:
`sp_inputs` converted to `SparseTensor` objects.

Raises:
ValueError: if any item in `sp_inputs` is neither `SparseTensor` nor
`SparseTensorValue`.


def depth_june_average_ground_temperature(self, value=None):

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

        self._depth_june_average_ground_temperature = value

Corresponds to IDD Field `depth_june_average_ground_temperature`

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

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


def write(self, brightness):

        if not isinstance(brightness, (bool, int)):
            raise TypeError("Invalid brightness type, should be bool or int.")

        if isinstance(brightness, bool):
            brightness = self._max_brightness if brightness else 0
        else:
            if not 0 <= brightness <= self._max_brightness:
                raise ValueError("Invalid brightness value, should be between 0 and %d." % self._max_brightness)

        try:
            os.write(self._fd, b"%d\n" % brightness)
        except OSError as e:
            raise LEDError(e.errno, "Writing LED brightness: " + e.strerror)

        try:
            os.lseek(self._fd, 0, os.SEEK_SET)
        except OSError as e:
            raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror)

Set the brightness of the LED to `brightness`.

`brightness` can be a boolean for on/off, or integer value for a
specific brightness.

Args:
brightness (bool, int): Brightness value to set.

Raises:
LEDError: if an I/O or OS error occurs.
TypeError: if `brightness` type is not bool or int.


def __contains__(self, nurest_object):

        for obj in self:
            if obj.equals(nurest_object):
                return True

        return False

Verify if the fetcher contains the given NURESTObject

Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to verify

Returns:
Returns True if the object has been found. False otherwise


def fuzzy_match(self, proc):
    return any(((proc in row[self.command_name]) for row in self.data))

Are there any commands that contain the given text?

Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.

.. note::
'proc' can match anywhere in the command path, name or arguments.


def _linear(self, inputs):
    first_dims = shape_list(inputs)[:-1]
    x = tf.reshape(inputs, [-1, self.hidden_size])
    logits = tf.matmul(x, self.weight, transpose_b=True)
    return tf.reshape(logits, first_dims + [self.vocab_size])

Computes logits by running inputs through a linear layer.

Args:
inputs: A float32 tensor with shape [..., hidden_size]

Returns:
float32 tensor with shape [..., vocab_size].


def write_compartments(self, stream, compartments, adjacencies, properties=None):

    def convert(entry):
        return self.convert_compartment_entry(entry, adjacencies.get(entry.id))
    self._write_entries(stream, compartments, convert, properties)

Write iterable of compartments as YAML object to stream.

Args:
stream: File-like object.
compartments: Iterable of compartment entries.
adjacencies: Dictionary mapping IDs to adjacent compartment IDs.
properties: Set of compartment properties to output (or None to
output all).


def get():
    result = runCommand('facter --json', raise_error_on_fail=True)
    json_facts = result[1]
    facts = json.loads(json_facts)
    return facts

Get local facts about this machine.

Returns:
json-compatible dict with all facts of this host


def take_profit_replace(self, accountID, orderID, **kwargs):

        return self.replace(
            accountID,
            orderID,
            order=TakeProfitOrderRequest(**kwargs)
        )

Shortcut to replace a pending Take Profit Order in an Account

Args:
accountID : The ID of the Account
orderID : The ID of the Take Profit Order to replace
kwargs : The arguments to create a TakeProfitOrderRequest

Returns:
v20.response.Response containing the results from submitting
the request