def __init__(self, settings, room_id):

        StreamProcess.__init__(self, settings, room_id)
        self._reactor = self._connection.get_twisted_reactor()
        self._protocol = None

Initialize.

Args:
settings (dict): Settings used to create a :class:`Connection` instance
room_id (int): Room ID


def _somethingFound(self, data, mode='phonefy'):
    if data:
        try:
            for text in self.notFoundText[mode]:
                if (text in data):
                    return False
            return True
        except AttributeError as e:
            verifier = self.modes.get(mode)
            if verifier:
                if (verifier.get('not_found_text', '') in data):
                    return False
                else:
                    return True
    return False

Verifying if something was found.

Args:
-----
data: Data where the self.notFoundText will be searched.
mode: Mode to be executed.

Return:
-------
True if exists.


def consume(self, callback, queue):
    self.consumers[queue] = callback
    if self._client_ready.called:
        return self.client.consume(callback, queue)

Register a new consumer.

This consumer will be configured for every protocol this factory
produces so it will be reconfigured on network failures. If a connection
is already active, the consumer will be added to it.

Args:
callback (callable): The callback to invoke when a message arrives.
queue (str): The name of the queue to consume from.


def findAll(self, selfValue):

        resultList = []
        for element in selfValue:
            if isinstance(element, Single):
                resultList += element.findAll(element.value)
            else:
                resultList.append(element)
        return resultList

Looks for all the non single values(str, int) *recursively* and returns a list of them

Args:
selfValue: A list of single, str, int. Normally just ``self.value``

Returns:
list: A list contains only non singles(str, int).


def _subdivide_nodes(nodes, degree):
    if (degree == 1):
        nodes_a = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_A)
        nodes_b = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_B)
        nodes_c = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_C)
        nodes_d = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_D)
    elif (degree == 2):
        nodes_a = _helpers.matrix_product(nodes, QUADRATIC_SUBDIVIDE_A)
        nodes_b = _helpers.matrix_product(nodes, QUADRATIC_SUBDIVIDE_B)
        nodes_c = _helpers.matrix_product(nodes, QUADRATIC_SUBDIVIDE_C)
        nodes_d = _helpers.matrix_product(nodes, QUADRATIC_SUBDIVIDE_D)
    elif (degree == 3):
        nodes_a = _helpers.matrix_product(nodes, CUBIC_SUBDIVIDE_A)
        nodes_b = _helpers.matrix_product(nodes, CUBIC_SUBDIVIDE_B)
        nodes_c = _helpers.matrix_product(nodes, CUBIC_SUBDIVIDE_C)
        nodes_d = _helpers.matrix_product(nodes, CUBIC_SUBDIVIDE_D)
    elif (degree == 4):
        nodes_a = _helpers.matrix_product(nodes, QUARTIC_SUBDIVIDE_A)
        nodes_b = _helpers.matrix_product(nodes, QUARTIC_SUBDIVIDE_B)
        nodes_c = _helpers.matrix_product(nodes, QUARTIC_SUBDIVIDE_C)
        nodes_d = _helpers.matrix_product(nodes, QUARTIC_SUBDIVIDE_D)
    else:
        nodes_a = specialize_surface(nodes, degree, _WEIGHTS_SUBDIVIDE0, _WEIGHTS_SUBDIVIDE1, _WEIGHTS_SUBDIVIDE2)
        nodes_b = specialize_surface(nodes, degree, _WEIGHTS_SUBDIVIDE3, _WEIGHTS_SUBDIVIDE2, _WEIGHTS_SUBDIVIDE1)
        nodes_c = specialize_surface(nodes, degree, _WEIGHTS_SUBDIVIDE1, _WEIGHTS_SUBDIVIDE4, _WEIGHTS_SUBDIVIDE3)
        nodes_d = specialize_surface(nodes, degree, _WEIGHTS_SUBDIVIDE2, _WEIGHTS_SUBDIVIDE3, _WEIGHTS_SUBDIVIDE5)
    return (nodes_a, nodes_b, nodes_c, nodes_d)

Subdivide a surface into four sub-surfaces.

.. note::

There is also a Fortran implementation of this function, which
will be used if it can be built.

Does so by taking the unit triangle (i.e. the domain of the surface) and
splitting it into four sub-triangles by connecting the midpoints of each
side.

Args:
nodes (numpy.ndarray): Control points for a surface.
degree (int): The degree of the surface.

Returns:
Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]: The
nodes for the four sub-surfaces.


def setMinimum(self, minimum):

        if not isinstance(minimum, int):
            raise TypeError("Argument is not of type int or long")
        self._minimum = minimum

setter to _minimum.

Args:
minimum (int or long): new _minimum value.

Raises:
TypeError: If the given argument is not an integer.


def get_polling_override(self):
    polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE)
    if (polling_override is None):
        logger.warn('Failed to find handle for polling override')
        return None
    override_ms = self.dongle._read_attribute(self.conn_handle, polling_override, True)
    return (None if (override_ms is None) else ord(override_ms))

Get the current polling override value in milliseconds.

See :meth:`set_polling_override` for more information.

Returns:
None on error, otherwise the current override period in milliseconds
(0 = disabled).


def _DescriptionSection(component, info):
    if custom_descriptions.NeedsCustomDescription(component):
        available_space = LINE_LENGTH - SECTION_INDENTATION
        description = custom_descriptions.GetDescription(component, available_space, LINE_LENGTH)
        summary = custom_descriptions.GetSummary(component, available_space, LINE_LENGTH)
    else:
        description = _GetDescription(info)
        summary = _GetSummary(info)
    text = description or summary or None
    if text:
        return ('DESCRIPTION', text)
    else:
        return None

The "Description" sections of the help string.

Args:
component: The component to produce the description section for.
info: The info dict for the component of interest.

Returns:
Returns the description if available. If not, returns the summary.
If neither are available, returns None.


def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):

        uri = self.__build_volume_snapshot_uri(volume_id_or_uri, snapshot_id_or_uri)
        return self._client.get(uri)

Gets a snapshot of a volume.

Args:
volume_id_or_uri:
Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
but required if it passed a snapshot ID.
snapshot_id_or_uri:
Can be either the snapshot ID or the snapshot URI.

Returns:
dict: The snapshot.


def dataset(self, mode, hparams=None, global_step=None, **kwargs):

    datasets = [p.dataset(mode, **kwargs) for p in self.problems]
    datasets = [
        d.map(lambda x, i=j: self.normalize_example(
            dict(x, problem_id=tf.constant([i])), hparams))
        for j, d in enumerate(datasets)
    ]
    if mode is problem.DatasetSplit.TRAIN:
      if global_step is None:
        global_step = tf.train.get_or_create_global_step()
      pmf = get_schedule_distribution(self.schedule, global_step)
      return get_multi_dataset(datasets, pmf)
    elif self.only_eval_first_problem:
      return datasets[0]
    else:
      datasets = [d.repeat() for d in datasets]
      return tf.data.Dataset.zip(tuple(datasets)).flat_map(
          lambda *x: functools.reduce(
              tf.data.Dataset.concatenate,
              map(tf.data.Dataset.from_tensors, x)))

Returns a dataset containing examples from multiple problems.

Args:
mode: A member of problem.DatasetSplit.
hparams: A tf.HParams object, the model hparams.
global_step: A scalar tensor used to compute the sampling distribution.
If global_step is None, we call tf.train.get_or_create_global_step by
default.
**kwargs: Keywords for problem.Problem.Dataset.

Returns:
A dataset containing examples from multiple problems.


def make_instance(cls, data):
    schema = cls()
    if (not hasattr(schema.Meta, 'model')):
        raise AttributeError('In order to make an instance, a model for the schema must be defined in the Meta class.')
    serialized_data = schema.load(data).data
    return cls.Meta.model(**serialized_data)

Validate the data and create a model instance from the data.

Args:
data (dict): The unserialized data to insert into the new model
instance through it's constructor.

Returns:
peewee.Model|sqlalchemy.Model: The model instance with it's data
inserted into it.

Raises:
AttributeError: This is raised if ``Meta.model`` isn't set on the
schema's definition.


def merge(self, other_rel):
    if ((other_rel.thresholds.size == self.thresholds.size) and np.all((other_rel.thresholds == self.thresholds))):
        self.frequencies += other_rel.frequencies
    else:
        print('Input table thresholds do not match.')

Ingest another DistributedReliability and add its contents to the current object.

Args:
other_rel: a Distributed reliability object.


def fetch_woeid(self, location):
    rss = self._fetch_xml(WOEID_LOOKUP_URL.format(quote(location)))
    try:
        woeid = rss.find('results/Result/woeid').text
    except AttributeError:
        return None
    return woeid

Fetch a location's corresponding WOEID.

Args:
location: (string) a location (e.g. 23454 or Berlin, Germany).

Returns:
a string containing the location's corresponding WOEID or None if
the WOEID could not be found.

Raises:
urllib.error.URLError: urllib.request could not open the URL
(Python 3).
urllib2.URLError: urllib2 could not open the URL (Python 2).
xml.etree.ElementTree.ParseError: xml.etree.ElementTree failed to
parse the XML document.


def dim_reduce_data(data, d):
    (genes, cells) = data.shape
    distances = np.zeros((cells, cells))
    for i in range(cells):
        for j in range(cells):
            distances[(i, j)] = poisson_dist(data[(:, i)], data[(:, j)])
    proximity = (distances ** 2)
    J = (np.eye(cells) - (1.0 / cells))
    B = ((- 0.5) * np.dot(J, np.dot(proximity, J)))
    (e_val, e_vec) = np.linalg.eigh(B)
    lam = np.diag(e_val[(- d):])[::(- 1)]
    E = e_vec[(:, (- d):)][::(- 1)]
    X = np.dot(E, (lam ** 0.5))
    return X

Does a MDS on the data directly, not on the means.

Args:
data (array): genes x cells
d (int): desired dimensionality

Returns:
X, a cells x d matrix


def set_dft_grid(self, radical_points=128, angular_points=302,
                     grid_type="Lebedev"):

        available_lebedev_angular_points = {6, 18, 26, 38, 50, 74, 86, 110, 146,
                                            170, 194, 230, 266, 302, 350, 434,
                                            590, 770, 974, 1202, 1454, 1730,
                                            2030, 2354, 2702, 3074, 3470, 3890,
                                            4334, 4802, 5294}
        if grid_type.lower() == "sg-0":
            self.params["rem"]["xc_grid"] = 0
        elif grid_type.lower() == "sg-1":
            self.params["rem"]["xc_grid"] = 1
        elif grid_type.lower() == "lebedev":
            if angular_points not in available_lebedev_angular_points:
                raise ValueError(str(angular_points) + " is not a valid "
                                 "Lebedev angular points number")
            self.params["rem"]["xc_grid"] = "{rp:06d}{ap:06d}".format(
                rp=radical_points, ap=angular_points)
        elif grid_type.lower() == "gauss-legendre":
            self.params["rem"]["xc_grid"] = "-{rp:06d}{ap:06d}".format(
                rp=radical_points, ap=angular_points)
        else:
            raise ValueError("Grid type " + grid_type + " is not supported "
                                                        "currently")

Set the grid for DFT numerical integrations.

Args:
radical_points: Radical points. (Integer)
angular_points: Angular points. (Integer)
grid_type: The type of of the grid. There are two standard grids:
SG-1 and SG-0. The other two supported grids are "Lebedev" and
"Gauss-Legendre"


def on_epoch_begin(self, epoch, logs=None):

Called at the start of an epoch.

Subclasses should override for any actions to run. This function should
only be called during TRAIN mode.

Args:
epoch: Integer, index of epoch.
logs: Dict. Currently no data is passed to this argument for this
method but that may change in the future.


def dedent(text: str) -> str:
    return textwrap.dedent(text).strip()

Wrapper around `textwrap.dedent` which also `strip()` the content.

Before:

```python
text = textwrap.dedent(
\"\"\"\\
A(
x=1,
)\"\"\"
)
```

After:

```python
text = epy.dedent(
\"\"\"
A(
x=1,
)
\"\"\"
)
```

Args:
text: The text to dedent

Returns:
The dedented text


def get_desired():
    public_members = get_public_members()
    if public_members:
        members = '\n    :members: {}'.format(', '.join(public_members))
    else:
        members = ''
    return DESIRED_TEMPLATE.format(members=members)

Populate ``DESIRED_TEMPLATE`` with public members.

If there are no members, does nothing.

Returns:
str: The "desired" contents of ``bezier.rst``.


def get_evaluations(self, variant_obj):
    query = dict(variant_id=variant_obj['variant_id'])
    res = self.acmg_collection.find(query).sort([('created_at', pymongo.DESCENDING)])
    return res

Return all evaluations for a certain variant.

Args:
variant_obj (dict): variant dict from the database

Returns:
pymongo.cursor: database cursor


def _delete_gridfs_data(self, data):
    if isinstance(data, ObjectId):
        if self._gridfs.exists({'_id': data}):
            self._gridfs.delete(data)
        else:
            raise DataStoreGridfsIdInvalid()
    elif isinstance(data, list):
        for item in data:
            self._delete_gridfs_data(item)
    elif isinstance(data, dict):
        for (key, item) in data.items():
            self._delete_gridfs_data(item)

Delete all GridFS data that is linked by fields in the specified data.

Args:
data: The data that is parsed for MongoDB ObjectIDs. The linked GridFs object
for any ObjectID is deleted.


def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names):

    print('Converting pooling ...')

    if names == 'short':
        tf_name = 'P' + random_string(7)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    if 'kernel_shape' in params:
        height, width, depth = params['kernel_shape']
    else:
        height, width, depth = params['kernel_size']

    if 'strides' in params:
        stride_height, stride_width, stride_depth = params['strides']
    else:
        stride_height, stride_width, stride_depth = params['stride']

    if 'pads' in params:
        padding_h, padding_w, padding_d, _, _ = params['pads']
    else:
        padding_h, padding_w, padding_d = params['padding']

    input_name = inputs[0]
    if padding_h > 0 and padding_w > 0 and padding_d > 0:
        padding_name = tf_name + '_pad'
        padding_layer = keras.layers.ZeroPadding3D(
            padding=(padding_h, padding_w, padding_d),
            name=padding_name
        )
        layers[padding_name] = padding_layer(layers[inputs[0]])
        input_name = padding_name

    pooling = keras.layers.MaxPooling3D(
        pool_size=(height, width, depth),
        strides=(stride_height, stride_width, stride_depth),
        padding='valid',
        name=tf_name
    )

    layers[scope_name] = pooling(layers[input_name])

Convert 3d Max pooling.

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


def _add_arg(self, key, value, mask=False):
    if (self.lang == 'python'):
        self._add_arg_python(key, value, mask)
    elif (self.lang == 'java'):
        self._add_arg_java(key, value, mask)

Add CLI Arg for the correct language.

Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.


def van(first_enc, first_frame, current_enc, gt_image, reuse=False, scope_prefix='', hparams=None):
    with tf.variable_scope((scope_prefix + 'van'), reuse=reuse):
        output_shape = first_frame.get_shape().as_list()
        output_shape[0] = (- 1)
        first_depth = 64
        (f_first_enc, _) = van_enc_2d(first_enc, first_depth)
        (f_first_frame, image_enc_history) = van_image_enc_2d(first_frame, first_depth, hparams=hparams)
        (f_current_enc, van_higher_level) = van_enc_2d(current_enc, first_depth, reuse=True)
        (f_gt_image, _) = van_image_enc_2d(gt_image, first_depth, True, hparams=hparams)
        analogy_t = analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth)
        enc_img = (f_current_enc + analogy_t)
        img = van_dec_2d(enc_img, image_enc_history, output_shape, first_depth, hparams=hparams)
        batch_size = tf.to_float(tf.shape(first_enc)[0])
        r_loss = (tf.nn.l2_loss(((f_gt_image - f_current_enc) - analogy_t)) / batch_size)
        return (img, r_loss, van_higher_level)

Implements a VAN.

Args:
first_enc: The first encoding.
first_frame: The first ground truth frame.
current_enc: The encoding of the frame to generate.
gt_image: The ground truth image, only used for regularization.
reuse: To reuse in variable scope or not.
scope_prefix: The prefix before the scope name.
hparams: The python hparams.

Returns:
The generated image.


def recipe_cm360_report_replicate(config, auth_read, recipe_name, auth_write, account, recipe_slug, report_id, report_name, delete, Aggregate):
    drive(config, {'auth': 'user', 'copy': {'source': 'https:
    dataset(config, {'auth': auth_write, 'dataset': recipe_slug})
    cm_report_replicate(config, {'auth': auth_read, 'report': {'account': account, 'id': report_id, 'name': report_name, 'delete': delete}, 'replicate': {'sheets': {'sheet': recipe_name, 'tab': 'Accounts', 'range': ''}}, 'write': {'bigquery': {'dataset': recipe_slug, 'is_incremental_load': Aggregate}}})

Replicate a report across multiple networks and advertisers.

Args:
auth_read (authentication) - Credentials used for reading data.
recipe_name (string) - Sheet to read ids from.
auth_write (authentication) - Credentials used for writing data.
account (integer) - CM network id.
recipe_slug (string) - NA
report_id (integer) - CM template report id, for template
report_name (string) - CM template report name, empty if using id instead.
delete (boolean) - Use only to reset the reports if setup changes.
Aggregate (boolean) - Append report data to existing table, requires Date column.


def __init__(self, fail_silently=False, aws_access_key_id=None,
                 aws_secret_access_key=None, **kwargs):

        super(EmailBackend, self).__init__(fail_silently=fail_silently)

        access_key_id = getattr(settings, 'AWS_ACCESS_KEY_ID', None)
        secret_access_key = getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)
        region_name = getattr(settings, 'AWS_DEFAULT_REGION', 'us-east-1')

        access_key_id = getattr(settings, 'AWS_SES_ACCESS_KEY_ID',
                                access_key_id)
        secret_access_key = getattr(settings, 'AWS_SES_SECRET_ACCESS_KEY',
                                    secret_access_key)
        region_name = getattr(settings, 'AWS_SES_REGION', region_name)

        if aws_access_key_id is not None and aws_secret_access_key is not None:
            access_key_id = aws_access_key_id
            secret_access_key = aws_secret_access_key

        self.conn = boto3.client(
            'ses',
            aws_access_key_id=access_key_id,
            aws_secret_access_key=secret_access_key,
            region_name=region_name,
        )

Creates a client for the Amazon SES API.

Args:
fail_silently: Flag that determines whether Amazon SES
client errors should throw an exception.


def config_file(self, filename):

        if os.path.isfile(filename):
            with open(filename, 'r') as fh:
                self._config_data = json.load(fh)
        else:
            self.tcex.log.error('Could not load configuration file "{}".'.format(filename))

Load configuration data from provided file and inject values into sys.argv.

Args:
config (str): The configuration file name.


def download(self, folder=None):
    url = self.data.get('url', None)
    if (not url):
        raise HDXError('No URL to download!')
    logger.debug(('Downloading %s' % url))
    filename = self.data['name']
    format = ('.%s' % self.data['format'])
    if (format not in filename):
        filename = ('%s%s' % (filename, format))
    with Download(full_agent=self.configuration.get_user_agent()) as downloader:
        path = downloader.download_file(url, folder, filename)
        return (url, path)

Download resource store to provided folder or temporary folder if no folder supplied

Args:
folder (Optional[str]): Folder to download resource to. Defaults to None.

Returns:
Tuple[str, str]: (URL downloaded, Path to downloaded file)


def get(cls, issue_type):
    if isinstance(issue_type, str):
        obj = getattr(db, cls.__name__).find_one((cls.issue_type == issue_type))
    elif isinstance(issue_type, int):
        obj = getattr(db, cls.__name__).find_one((cls.issue_type_id == issue_type))
    elif isinstance(issue_type, cls):
        return issue_type
    else:
        obj = None
    if (not obj):
        obj = cls()
        obj.issue_type = issue_type
        db.session.add(obj)
        db.session.commit()
        db.session.refresh(obj)
    return obj

Returns the IssueType object for `issue_type`. If no existing object was found, a new type will
be created in the database and returned

Args:
issue_type (str,int,IssueType): Issue type name, id or class

Returns:
:obj:`IssueType`


def acquire(self):
    self._fd = open(self._path, mode='w+')
    os.chmod(self._path, 432)
    fcntl.flock(self._fd, self._op)

Acquire the lock

Raises:
IOError: if the call to flock fails


def get_user(self, user_id=None, user_name=None):

        if user_id:
            endpoint = '/api/user_id/{0}'.format(user_id)
        elif user_name:
            endpoint = '/api/user_name/{0}'.format(user_name)
        else:

            endpoint = '/api/user'

        data = self._make_request(verb="GET", endpoint=endpoint)

        try:
            return User.NewFromJSON(data)
        except:
            return data

Get a user object from the API. If no ``user_id`` or ``user_name``
is specified, it will return the User object for the currently
authenticated user.

Args:
user_id (int): User ID of the user for whom you want to get
information. [Optional]
user_name(str): Username for the user for whom you want to get
information. [Optional]

Returns:
A User object.


def refresh_db(**kwargs):
    salt.utils.pkg.clear_rtag(__opts__)
    retcodes = {100: True, 0: None, 1: False}
    ret = True
    check_update_ = kwargs.pop('check_update', True)
    options = _get_options(**kwargs)
    clean_cmd = ['--quiet', '--assumeyes', 'clean', 'expire-cache']
    clean_cmd.extend(options)
    _call_yum(clean_cmd, ignore_retcode=True)
    if check_update_:
        update_cmd = ['--quiet', '--assumeyes', 'check-update']
        if ((__grains__.get('os_family') == 'RedHat') and (__grains__.get('osmajorrelease') == 7)):
            update_cmd.append('--setopt=autocheck_running_kernel=false')
        update_cmd.extend(options)
        ret = retcodes.get(_call_yum(update_cmd, ignore_retcode=True)['retcode'], False)
    return ret

Check the yum repos for updated packages

Returns:

- ``True``: Updates are available
- ``False``: An error occurred
- ``None``: No updates are available

repo
Refresh just the specified repo

disablerepo
Do not refresh the specified repo

enablerepo
Refresh a disabled repo using this option

branch
Add the specified branch when refreshing

disableexcludes
Disable the excludes defined in your config files. Takes one of three
options:
- ``all`` - disable all excludes
- ``main`` - disable excludes defined in [main] in yum.conf
- ``repoid`` - disable excludes defined for that repo

setopt
A comma-separated or Python list of key=value options. This list will
be expanded and ``--setopt`` prepended to each in the yum/dnf command
that is run.

.. versionadded:: 2019.2.0

CLI Example:

.. code-block:: bash

salt '*' pkg.refresh_db


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

Approves or rejects a pending build. If approved, the returned LRO will be analogous to the LRO returned from a CreateBuild call. If rejected, the returned LRO will be immediately done.

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


def _wrap_any(cls, self, obj: Any):
    if isinstance(obj, expressions.Builder):
        return cls.from_fhir_path_builder(obj)
    if isinstance(obj, list):
        return [cls._wrap_any(self, item) for item in obj]
    if isinstance(obj, tuple):
        return (cls._wrap_any(self, item) for item in obj)
    if isinstance(obj, dict):
        return {cls._wrap_any(self, key): cls._wrap_any(self, value) for key, value in obj.items()}
    if callable(obj):
        return cls._wrap_function(self, obj)
    return obj

Wraps any object with the logic below.

Args:
self: self instance reference.
obj: any object.

Returns:
If the object is:
- an expressions.Builder: returns this class to wrap it;
- a list: returns a new list with each item in the list wrapped;
- a tuple: returns a new tuple with each item in the list wrapped;
- a dictionary: returns a new dictionary with each key/value pair in
the dictionary wrapped.
- a callable function: returns a wrapper function with the return result
of the function wrapped.
- anything else: returns the object itself.


def from_json_value(cls, json_value: Optional[Any], primitive_cls: Type[message.Message], context: Context) -> 'PrimitiveWrapper':
    if isinstance(json_value, (list, tuple)):
        raise ValueError('Error, unable to wrap sequence.')
    if json_value is None or isinstance(json_value, (dict,)):
        return cls(no_value_primitive(primitive_cls), context)
    if not isinstance(json_value, cast(Tuple[Type[Any], ...], cls._PARSABLE_TYPES)):
        raise fhir_errors.InvalidFhirError(f'Unable to parse JSON. {type(json_value)} is invalid FHIR JSON.')
    return cls.from_json_str(str(json_value), primitive_cls, context)

Parses json_value into an instance of primitive_cls and wraps.

Args:
json_value: The optional raw json_value to parse and wrap.
primitive_cls: The type of FHIR primitive message to create and validate.
context: Related primitive information to use for printing/parsing a
wrapped primitive.

Returns:
An instance of PrimitiveWrapper.


def children(self, obj, save_type=base.SaveType.CHECKPOINT, **kwargs):
    children = {}
    for name, ref in self.list_children(obj, **kwargs):
        children[name] = ref
    return children

Returns all child trackables attached to obj.

Args:
obj: A `Trackable` object.
save_type: A string, can be 'savedmodel' or 'checkpoint'.
**kwargs: kwargs to use when retrieving the object's children.

Returns:
Dictionary of all children attached to the object with name to trackable.


def _set_bearer_user_vars(allowed_client_ids, scopes):

  all_scopes, sufficient_scopes = _process_scopes(scopes)
  try:
    authorized_scopes = oauth.get_authorized_scopes(sorted(all_scopes))
  except oauth.Error:
    _logger.debug('Unable to get authorized scopes.', exc_info=True)
    return
  if not _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
    _logger.warning('Authorized scopes did not satisfy scope requirements.')
    return
  client_id = oauth.get_client_id(authorized_scopes)

  if (list(allowed_client_ids) != SKIP_CLIENT_ID_CHECK and
      client_id not in allowed_client_ids):
    _logger.warning('Client ID is not allowed: %s', client_id)
    return

  os.environ[_ENV_USE_OAUTH_SCOPE] = ' '.join(authorized_scopes)
  _logger.debug('get_current_user() will return user from matched oauth_user.')

Validate the oauth bearer token and set endpoints auth user variables.

If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE.  This
provides enough information that our endpoints.get_current_user() function
can get the user.

Args:
allowed_client_ids: List of client IDs that are acceptable.
scopes: List of acceptable scopes.


def create_combination(list_of_sentences):
    num_sentences = (len(list_of_sentences) - 1)
    combinations = []
    for (i, _) in enumerate(list_of_sentences):
        if (i == num_sentences):
            break
        num_pairs = (num_sentences - i)
        populated = (num_pairs * [list_of_sentences[i]])
        zipped = list(zip(populated, list_of_sentences[(i + 1):]))
        combinations += zipped
    return combinations

Generates all possible pair combinations for the input list of sentences.

For example:

input = ["paraphrase1", "paraphrase2", "paraphrase3"]

output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphrase3")]

Args:
list_of_sentences: the list of input sentences.
Returns:
the list of all possible sentence pairs.


def create_index(index_name, index_config, client):

    client.create(index=index_name, body=index_config)

Creates an index with a given configuration

Args:
index_name (str): Name of the index you want to create
index_config (dict) configuration for the index
client (Elasticsearch.IndicesClient) the Elasticsearch client


def rejection_resample(class_func, target_dist, initial_dist=None, seed=None):

    def _apply_fn(dataset):

        return dataset.rejection_resample(class_func=class_func, target_dist=target_dist, initial_dist=initial_dist, seed=seed)
    return _apply_fn

A transformation that resamples a dataset to achieve a target distribution.

**NOTE** Resampling is performed via rejection sampling; some fraction
of the input values will be dropped.

Args:
class_func: A function mapping an element of the input dataset to a scalar
`tf.int32` tensor. Values should be in `[0, num_classes)`.
target_dist: A floating point type tensor, shaped `[num_classes]`.
initial_dist: (Optional.)  A floating point type tensor, shaped
`[num_classes]`.  If not provided, the true class distribution is
estimated live in a streaming fashion.
seed: (Optional.) Python integer seed for the resampler.

Returns:
A `Dataset` transformation function, which can be passed to
`tf.data.Dataset.apply`.


def _dist_to_opt(self):
    dist_to_opt_ops = []
    self._grad_norm = tf.sqrt(self._grad_norm_squared)
    avg_op = self._moving_averager.apply([self._grad_norm])
    dist_to_opt_ops.append(avg_op)
    with tf.control_dependencies([avg_op]):
        self._grad_norm_avg = self._moving_averager.average(self._grad_norm)
        self._d_t = (self._grad_norm_avg / self._grad_norm_squared_avg)
    avg_op = self._moving_averager.apply([self._d_t])
    dist_to_opt_ops.append(avg_op)
    with tf.control_dependencies([avg_op]):
        self._dist_to_opt_avg = tf.identity(self._moving_averager.average(self._d_t))
        if self._sparsity_debias:
            self._dist_to_opt_avg /= tf.sqrt(self._sparsity_avg)
    return dist_to_opt_ops


def explore(config, mutations, resample_probability, custom_explore_fn):
    new_config = copy.deepcopy(config)
    for (key, distribution) in mutations.items():
        if isinstance(distribution, dict):
            new_config.update({key: explore(config[key], mutations[key], resample_probability, None)})
        elif isinstance(distribution, list):
            if ((random.random() < resample_probability) or (config[key] not in distribution)):
                new_config[key] = random.choice(distribution)
            elif (random.random() > 0.5):
                new_config[key] = distribution[max(0, (distribution.index(config[key]) - 1))]
            else:
                new_config[key] = distribution[min((len(distribution) - 1), (distribution.index(config[key]) + 1))]
        else:
            if (random.random() < resample_probability):
                new_config[key] = distribution()
            elif (random.random() > 0.5):
                new_config[key] = (config[key] * 1.2)
            else:
                new_config[key] = (config[key] * 0.8)
            if (type(config[key]) is int):
                new_config[key] = int(new_config[key])
    if custom_explore_fn:
        new_config = custom_explore_fn(new_config)
        assert (new_config is not None), 'Custom explore fn failed to return new config'
    logger.info('[explore] perturbed config from {} -> {}'.format(config, new_config))
    return new_config

Return a config perturbed as specified.

Args:
config (dict): Original hyperparameter configuration.
mutations (dict): Specification of mutations to perform as documented
in the PopulationBasedTraining scheduler.
resample_probability (float): Probability of allowing resampling of a
particular variable.
custom_explore_fn (func): Custom explore fn applied after built-in
config perturbations are.


def fmt_partition(partition):

    if not partition:
        return ''

    parts = [fmt_part(part, partition.node_labels).split('\n')
             for part in partition]

    times = ('   ',
             ' {} '.format(MULTIPLY),
             '   ')
    breaks = ('\n', '\n', '')
    between = [times] * (len(parts) - 1) + [breaks]

    elements = chain.from_iterable(zip(parts, between))

    return ''.join(chain.from_iterable(zip(*elements)))

Format a |Bipartition|.

The returned string looks like::

0,1    ∅
─── ✕ ───
2    0,1

Args:
partition (Bipartition): The partition in question.

Returns:
str: A human-readable string representation of the partition.


def get_cases(variant_source, case_lines=None, case_type='ped', variant_type='snv', variant_mode='vcf'):
    individuals = get_individuals(variant_source=variant_source, case_lines=case_lines, case_type=case_type, variant_mode=variant_mode)
    case_objs = []
    case_ids = set()
    compressed = False
    tabix_index = False
    if variant_source.endswith('.gz'):
        logger.debug('Found compressed variant source')
        compressed = True
        tabix_file = '.'.join([variant_source, 'tbi'])
        if os.path.exists(tabix_file):
            logger.debug('Found index file')
            tabix_index = True
    if (len(individuals) > 0):
        for individual in individuals:
            case_ids.add(individual.case_id)
    else:
        case_ids = [os.path.basename(variant_source)]
    for case_id in case_ids:
        logger.info('Found case {0}'.format(case_id))
        case = Case(case_id=case_id, name=case_id, variant_source=variant_source, variant_type=variant_type, variant_mode=variant_mode, compressed=compressed, tabix_index=tabix_index)
        for individual in individuals:
            if (individual.case_id == case_id):
                logger.info('Adding ind {0} to case {1}'.format(individual.name, individual.case_id))
                case.add_individual(individual)
        case_objs.append(case)
    return case_objs

Create a cases and populate it with individuals

Args:
variant_source (str): Path to vcf files
case_lines (Iterable): Ped like lines
case_type (str): Format of case lines

Returns:
case_objs (list(puzzle.models.Case))


def _batch(self, batch_size) -> TypeSpec:
    raise NotImplementedError(f'{type(self).__name__}._batch')

Returns a TypeSpec representing a batch of objects with this TypeSpec.

Args:
batch_size: An `int` representing the number of elements in a batch, or
`None` if the batch size may vary.

Returns:
A `TypeSpec` representing a batch of objects with this TypeSpec.


def _get_events_list(object_key: str) -> List[str]:

    return DB.get_list(_keys.events_list(object_key))

Get list of event ids for the object with the specified key.

Args:
object_key (str): Key of an object in the database.


def from_dlpack(dlcapsule):
    context.context().ensure_initialized()
    return pywrap_tfe.TFE_FromDlpackCapsule(dlcapsule, context.context()._handle)

Returns the Tensorflow eager tensor.

The returned tensor uses the memory shared by dlpack capsules from other
framework.

```python
a = tf.experimental.dlpack.from_dlpack(dlcapsule)
# `a` uses the memory shared by dlpack
```

Args:
dlcapsule: A PyCapsule named as dltensor

Returns:
A Tensorflow eager tensor


def rand_ascii_str(length):

    letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
    return ''.join(letters)

Generates a random string of specified length, composed of ascii letters
and digits.

Args:
length: The number of characters in the string.

Returns:
The random string generated.


def hash_file(fpath, algorithm='sha256', chunk_size=65535):
    if isinstance(algorithm, str):
        hasher = resolve_hasher(algorithm)
    else:
        hasher = algorithm
    with open(fpath, 'rb') as fpath_file:
        for chunk in iter(lambda: fpath_file.read(chunk_size), b''):
            hasher.update(chunk)
    return hasher.hexdigest()

Calculates a file sha256 or md5 hash.

Example:

>>> hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

Args:
fpath: Path to the file being validated.
algorithm: Hash algorithm, one of `"auto"`, `"sha256"`, or `"md5"`.
The default `"auto"` detects the hash algorithm in use.
chunk_size: Bytes to read at a time, important for large files.

Returns:
The file hash.


def split_leading_dim(tensor, inputs, n_dims=2):
    input_shape_static = inputs.get_shape()
    input_shape_list = input_shape_static.as_list()
    tensor_shape_static = tensor.get_shape()
    tensor_shape_list = tensor_shape_static.as_list()
    if (input_shape_static.is_fully_defined() and tensor_shape_static.is_fully_defined()):
        new_shape = (input_shape_list[:n_dims] + tensor_shape_list[1:])
        return tf.reshape(tensor, new_shape)
    dims_after_first = tf.shape(tensor)[1:]
    split_sizes = tf.shape(inputs)[:n_dims]
    known_split_sizes = input_shape_list[:n_dims]
    known_dims_after_first = tensor_shape_list[1:]
    output_size = tf.concat([split_sizes, dims_after_first], 0)
    result = tf.reshape(tensor, output_size)
    result.set_shape((known_split_sizes + known_dims_after_first))
    return result

Split the first dimension of a tensor.

Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.

Returns:
The input tensor, with its first dimension split.


def easeOutElastic(n, amplitude=1, period=0.3):

    _checkRange(n)

    if amplitude < 1:
        amplitude = 1
        s = period / 4
    else:
        s = period / (2 * math.pi) * math.asin(1 / amplitude)

    return amplitude * 2**(-10*n) * math.sin((n-s)*(2*math.pi / period)) + 1

An elastic tween function that overshoots the destination and then "rubber bands" into the destination.

Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.

Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().


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

Flushes data from the SWO buffer.

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

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

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

Returns:
``None``

Raises:
JLinkException: on error


def confirm_iam_role(self, account):

        try:
            iam = self.session.client('iam')
            rolearn = iam.get_role(RoleName=self.role_name)['Role']['Arn']
            return rolearn

        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchEntity':
                self.create_iam_role(account)
            else:
                raise

        except Exception as e:
            self.log.exception('Failed validating IAM role for VPC Flow Log Auditing for {}'.format(e))

Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3

Args:
account (:obj:`Account`): Account where to locate the role

Returns:
:obj:`IAMRole`


def add_text(self, coords, text, color=(0, 0, 0)):

        source = vtk.vtkVectorText()
        source.SetText(text)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        follower = vtk.vtkFollower()
        follower.SetMapper(mapper)
        follower.GetProperty().SetColor(color)
        follower.SetPosition(coords)
        follower.SetScale(0.5)
        self.ren.AddActor(follower)
        follower.SetCamera(self.ren.GetActiveCamera())

Add text at a coordinate.

Args:
coords: Coordinates to add text at.
text: Text to place.
color: Color for text as RGB. Defaults to black.


def SetActiveBreakpoints(self, breakpoints_data):
    with self._lock:
        ids = set([x['id'] for x in breakpoints_data])
        for breakpoint_id in (six.viewkeys(self._active) - ids):
            self._active.pop(breakpoint_id).Clear()
        self._active.update([(x['id'], python_breakpoint.PythonBreakpoint(x, self._hub_client, self, self.data_visibility_policy)) for x in breakpoints_data if (x['id'] in ((ids - six.viewkeys(self._active)) - self._completed))])
        self._completed &= ids
        if self._active:
            self._next_expiration = datetime.min
        else:
            self._next_expiration = datetime.max

Adds new breakpoints and removes missing ones.

Args:
breakpoints_data: updated list of active breakpoints.


def get_module_class_from_name(module, name):
    modules_children = list(module.children())
    if module.__class__.__name__ == name:
        return module.__class__
    elif len(modules_children) == 0:
        return
    else:
        for child_module in modules_children:
            module_class = get_module_class_from_name(child_module, name)
            if module_class is not None:
                return module_class

Gets a class from a module by its name.

Args:
module (`torch.nn.Module`): The module to get the class from.
name (`str`): The name of the class.


def _AddPropertiesForField(field, cls):

  assert _FieldDescriptor.MAX_CPPTYPE == 10

  constant_name = field.name.upper() + "_FIELD_NUMBER"
  setattr(cls, constant_name, field.number)

  if field.label == _FieldDescriptor.LABEL_REPEATED:
    _AddPropertiesForRepeatedField(field, cls)
  elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    _AddPropertiesForNonRepeatedCompositeField(field, cls)
  else:
    _AddPropertiesForNonRepeatedScalarField(field, cls)

Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.

Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing.


def doc2id(self, doc):

        doc = map(self.process_token, doc)
        return [self.token_to_id(token) for token in doc]

Get the list of token_id given doc.

Args:
doc (list): document.

Returns:
list: int id of doc.


def from_path(cls, path):

        stat_res = os.stat(path)
        return cls.from_int(stat.S_IMODE(stat_res.st_mode))

Make a new :class:`FilePerms` object based on the permissions
assigned to the file or directory at *path*.

Args:
path (str): Filesystem path of the target file.

>>> from os.path import expanduser
>>> 'r' in FilePerms.from_path(expanduser('~')).user  # probably
True


def saveplot(fig, *name_args, close=True, **name_kwargs):

    oname = out_name(*name_args, **name_kwargs)
    fig.savefig('{}.{}'.format(oname, conf.plot.format),
                format=conf.plot.format, bbox_inches='tight')
    if close:
        plt.close(fig)

Save matplotlib figure.

You need to provide :data:`stem` as a positional or keyword argument (see
:func:`out_name`).

Args:
fig (:class:`matplotlib.figure.Figure`): matplotlib figure.
close (bool): whether to close the figure.
name_args: positional arguments passed on to :func:`out_name`.
name_kwargs: keyword arguments passed on to :func:`out_name`.


def _add_tags(self, tags):

        alltagsadded = True
        for tag in tags:
            if not self._add_tag(tag):
                alltagsadded = False
        return alltagsadded

Add a list of tag

Args:
tags (List[str]): list of tags to add

Returns:
bool: True if all tags added or False if any already present.


def numeric_task_id(task_id):
    if (task_id is not None):
        if task_id.startswith('task-'):
            return int(task_id[len('task-'):])
        else:
            return int(task_id)

Converts a task-id to the numeric task-id.

Args:
task_id: task-id in either task-n or n format

Returns:
n


def pack_container(in_container, out_file):
    container_filename = local.path(out_file).basename
    out_container = ((local.cwd / 'container-out') / container_filename)
    out_dir = out_container.dirname
    with local.cwd(in_container):
        tar('cjf', out_container, '.')
    c_hash = download.update_hash(out_container)
    if out_dir.exists():
        mkdir('-p', out_dir)
    mv(out_container, out_file)
    mv((out_container + '.hash'), (out_file + '.hash'))
    new_container = {'path': out_file, 'hash': str(c_hash)}
    CFG['container']['known'] += new_container

Pack a container image into a .tar.bz2 archive.

Args:
in_container (str): Path string to the container image.
out_file (str): Output file name.


def entitlements(self, request, pk=None):

        enterprise_customer_user = self.get_object()
        instance = {"entitlements": enterprise_customer_user.entitlements}
        serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'request': request})
        return Response(serializer.data)

Retrieve the list of entitlements available to this learner.

Only those entitlements are returned that satisfy enterprise customer's data sharing setting.

Arguments:
request (HttpRequest): Reference to in-progress request instance.
pk (Int): Primary key value of the selected enterprise learner.

Returns:
(HttpResponse): Response object containing a list of learner's entitlements.


Computes cos of x element-wise.

Args:
x: Tensor or variable.

Returns:
A tensor.


def main(argv: Optional[Sequence[str]]=None) -> None:
    args = parse_arguments(argv=argv)
    if args.logging:
        logging.basicConfig(level=logging.DEBUG)
    handle_skip()
    action = args.action
    request = parse_request()
    LOGGER.debug('Received action %s with request:\n%s', action, request)
    try:
        mapping = parse_mapping(args.mapping)
    except Exception as error:
        LOGGER.critical('Unable to parse mapping file', exc_info=True)
        print('Unable to parse mapping file: {error}'.format(error=error), file=sys.stderr)
        sys.exit(1)
    if (action == 'get'):
        get_password(request, mapping)
    else:
        LOGGER.info('Action %s is currently not supported', action)
        sys.exit(1)

Start the pass-git-helper script.

Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.


def add_done_callback(self, fn):

        if self._result_set:
            _helpers.safe_invoke_callback(fn, self)
            return

        self._done_callbacks.append(fn)

        if self._polling_thread is None:

            self._polling_thread = _helpers.start_daemon_thread(
                target=self._blocking_poll
            )

Add a callback to be executed when the operation is complete.

If the operation is not already complete, this will start a helper
thread to poll for the status of the operation in the background.

Args:
fn (Callable[Future]): The callback to execute when the operation
is complete.


def decode(self, images, save=None, round=4, names=None, **kwargs):
    if isinstance(images, string_types):
        images = [images]
    if isinstance(images, list):
        imgs_to_decode = imageutils.load_imgs(images, self.masker)
    else:
        imgs_to_decode = images
    methods = {'pearson': self._pearson_correlation, 'dot': self._dot_product, 'roi': self._roi_association}
    result = np.around(methods[self.method](imgs_to_decode, **kwargs), round)
    if (names is None):
        if (type(images).__module__ == np.__name__):
            names = [('image_%d' % i) for i in range(images.shape[1])]
        elif (self.method == 'roi'):
            names = [('cluster_%d' % i) for i in range(result.shape[1])]
        else:
            names = images
    result = pd.DataFrame(result, columns=names, index=self.feature_names)
    if (save is not None):
        result.to_csv(save, index_label='Feature')
    return result

Decodes a set of images.

Args:
images: The images to decode. Can be:
- A single String specifying the filename of the image to decode
- A list of filenames
- A single NumPy array containing the image data
save: Optional filename to save results to. If None (default), returns
all results as an array.
round: Optional integer indicating number of decimals to round result
to. Defaults to 4.
names: Optional list of names corresponding to the images in filenames.
If passed, must be of same length and in same order as filenames.
By default, the columns in the output will be named using the image
filenames.

Returns:
An n_features x n_files numpy array, where each feature is a row and
each image is a column. The meaning of the values depends on the
decoding method used.


def _CalculateDigestHash(self, file_entry, data_stream_name):
    file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
    if (not file_object):
        return None
    try:
        file_object.seek(0, os.SEEK_SET)
        hasher_object = hashers_manager.HashersManager.GetHasher('sha256')
        data = file_object.read(self._READ_BUFFER_SIZE)
        while data:
            hasher_object.Update(data)
            data = file_object.read(self._READ_BUFFER_SIZE)
    finally:
        file_object.close()
    return hasher_object.GetStringDigest()

Calculates a SHA-256 digest of the contents of the file entry.

Args:
file_entry (dfvfs.FileEntry): file entry whose content will be hashed.
data_stream_name (str): name of the data stream whose content is to be
hashed.

Returns:
str: hexadecimal representation of the SHA-256 hash or None if the digest
cannot be determined.


def post_cutout(self, token, channel,
                    x_start,
                    y_start,
                    z_start,
                    data,
                    resolution=0):

        return self.data.post_cutout(token, channel,
                                     x_start,
                                     y_start,
                                     z_start,
                                     data,
                                     resolution)

Post a cutout to the server.

Arguments:
token (str)
channel (str)
x_start (int)
y_start (int)
z_start (int)
data (numpy.ndarray): A numpy array of data. Pass in (x, y, z)
resolution (int : 0): Resolution at which to insert the data

Returns:
bool: True on success

Raises:
RemoteDataUploadError: if there's an issue during upload.


def _get_populate_from_value(instance, field_name: Union[(str, Tuple[str])], language: str):
    if callable(field_name):
        return field_name(instance)

    def get_field_value(name):
        value = resolve_object_property(instance, name)
        with translation.override(language):
            return str(value)
    if (isinstance(field_name, tuple) or isinstance(field_name, list)):
        value = '-'.join([value for value in [get_field_value(name) for name in field_name] if value])
        return value
    return get_field_value(field_name)

Gets the value to create a slug from in the specified language.

Arguments:
instance:
The model that the field resides on.

field_name:
The name of the field to generate a slug for.

language:
The language to generate the slug for.

Returns:
The text to generate a slug for.


def compute_v(self, memory_antecedent):

    if self.shared_kv:
      raise ValueError("compute_v cannot be called with shared_kv")
    ret = mtf.einsum(
        [memory_antecedent, self.wv], reduced_dims=[self.memory_input_dim])
    if self.combine_dims:
      ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.v_dims)
    return ret

Compute value Tensor v.

Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {value_dim} + other_dims


def log_power_spectrum(frames, fft_points=512, normalize=True):
    power_spec = power_spectrum(frames, fft_points)
    power_spec[(power_spec <= 1e-20)] = 1e-20
    log_power_spec = (10 * np.log10(power_spec))
    if normalize:
        return (log_power_spec - np.max(log_power_spec))
    else:
        return log_power_spec

Log power spectrum of each frame in frames.

Args:
frames (array): The frame array in which each row is a frame.
fft_points (int): The length of FFT. If fft_length is greater than
frame_len, the frames will be zero-padded.
normalize (bool): If normalize=True, the log power spectrum
will be normalized.

Returns:
array: The power spectrum - If frames is an
num_frames x sample_per_frame matrix, output will be
num_frames x fft_length.


def read_video_pyav(video_path: str, sample_indices_fn: Callable, **kwargs):
    requires_backends(read_video_pyav, ['av'])
    import av
    container = av.open(video_path)
    total_num_frames = container.streams.video[0].frames
    video_fps = container.streams.video[0].average_rate
    duration = total_num_frames / video_fps if video_fps else 0
    metadata = VideoMetadata(total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend='pyav')
    indices = sample_indices_fn(metadata=metadata, **kwargs)
    frames = []
    container.seek(0)
    end_index = indices[-1]
    for i, frame in enumerate(container.decode(video=0)):
        if i > end_index:
            break
        if i >= 0 and i in indices:
            frames.append(frame)
    video = np.stack([x.to_ndarray(format='rgb24') for x in frames])
    metadata.frames_indices = indices
    return (video, metadata)

Decode the video with PyAV decoder.

Args:
video_path (`str`):
Path to the video file.
sample_indices_fn (`Callable`, *optional*):
A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
If not provided, simple uniform sampling with fps is performed.
Example:
def sample_indices_fn(metadata, **kwargs):
return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

Returns:
Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
- Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
- `VideoMetadata` object.


async def set_notification_level(self, level):
    (await self._client.set_conversation_notification_level(hangouts_pb2.SetConversationNotificationLevelRequest(request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self.id_), level=level)))

Set the notification level of this conversation.

Args:
level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or
``NOTIFICATION_LEVEL_RING`` to enable them.

Raises:
.NetworkError: If the request fails.


def put(self, values, name=None):
    with ops.name_scope(name, '%s_put' % self._name, self._scope_vals(values)) as scope:
        if not isinstance(values, (list, tuple, dict)):
            values = [values]
        indices = list(range(len(values)))
        vals, _ = self._check_put_dtypes(values, indices)
        with ops.colocate_with(self._coloc_op):
            op = gen_data_flow_ops.stage(values=vals, shared_name=self._name, name=scope, capacity=self._capacity, memory_limit=self._memory_limit)
        return op

Create an op that places a value into the staging area.

This operation will block if the `StagingArea` has reached
its capacity.

Args:
values: A single tensor, a list or tuple of tensors, or a dictionary with
tensor values. The number of elements must match the length of the
list provided to the dtypes argument when creating the StagingArea.
name: A name for the operation (optional).

Returns:
The created op.

Raises:
ValueError: If the number or type of inputs don't match the staging area.


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

        if '/' in id_or_url:
            id = urls.SheetUrl.from_string(id_or_url).id
        else:
            id = id_or_url
        try:
            return self[id]
        except KeyError:
            return default

Fetch and return the spreadsheet with the given id or url.

Args:
id_or_url (str): unique alphanumeric id or URL of the spreadsheet
Returns:
New SpreadSheet instance or given default if none is found
Raises:
ValueError: if an URL is given from which no id could be extracted


def encode(self, input_features: jnp.ndarray, attention_mask: Optional[jnp.ndarray]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None, **kwargs):
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    return_dict = return_dict if return_dict is not None else self.config.return_dict
    rngs = {}
    if dropout_rng is not None:
        rngs['dropout'] = dropout_rng

    def _encoder_forward(module, input_features, **kwargs):
        encode_module = module._get_encoder_module()
        return encode_module(input_features, **kwargs)
    return self.module.apply({'params': params or self.params}, input_features=jnp.array(input_features, dtype='f4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, method=_encoder_forward)

Returns:

Example:

```python
>>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", from_pt=True)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="np")
>>> input_features = inputs.input_features
>>> encoder_outputs = model.encode(input_features=input_features)
```


def init(library: typing.Union[(str, types.ModuleType)]) -> None:
    if isinstance(library, types.ModuleType):
        library = library.__name__
    if (library not in manager._handlers):
        raise ValueError('Possible values are <{}>, not <{}>'.format(manager._handlers.keys(), library))
    manager.init(library, asynclib)
    asynclib.lib_name = library
    asynclib._init = True

Must be called at some point after import and before your event loop
is run.

Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.

The supported libraries at the moment are:
- curio
- trio

Args:
library (str or module): Either the module name as a string or the
imported module itself. E.g. ``multio.init(curio)``.


def start(self, on_done):

        genesis_file = os.path.join(self._data_dir, 'genesis.batch')
        try:
            with open(genesis_file, 'rb') as batch_file:
                genesis_data = genesis_pb2.GenesisData()
                genesis_data.ParseFromString(batch_file.read())
            LOGGER.info('Producing genesis block from %s', genesis_file)
        except IOError:
            raise InvalidGenesisStateError(
                "Genesis File {} specified, but unreadable".format(
                    genesis_file))

        initial_state_root = self._context_manager.get_first_root()

        genesis_batches = [batch for batch in genesis_data.batches]
        if genesis_batches:
            scheduler = SerialScheduler(
                self._context_manager.get_squash_handler(),
                initial_state_root,
                always_persist=True)

            LOGGER.debug('Adding %s batches', len(genesis_data.batches))
            for batch in genesis_data.batches:
                scheduler.add_batch(batch)

            self._transaction_executor.execute(scheduler)

            scheduler.finalize()
            scheduler.complete(block=True)

        txn_receipts = []
        state_hash = initial_state_root
        for batch in genesis_batches:
            result = scheduler.get_batch_execution_result(
                batch.header_signature)
            if result is None or not result.is_valid:
                raise InvalidGenesisStateError(
                    'Unable to create genesis block, due to batch {}'
                    .format(batch.header_signature))
            if result.state_hash is not None:
                state_hash = result.state_hash

            txn_results = scheduler.get_transaction_execution_results(
                batch.header_signature)
            txn_receipts += self._make_receipts(txn_results)

        settings_view = SettingsView(
            self._state_view_factory.create_view(state_hash))
        name = settings_view.get_setting('sawtooth.consensus.algorithm.name')
        version = settings_view.get_setting(
            'sawtooth.consensus.algorithm.version')
        if name is None or version is None:
            raise LocalConfigurationError(
                'Unable to start validator; sawtooth.consensus.algorithm.name '
                'and sawtooth.consensus.algorithm.version must be set in the '
                'genesis block.')

        LOGGER.debug('Produced state hash %s for genesis block.', state_hash)

        block_builder = self._generate_genesis_block()
        block_builder.add_batches(genesis_batches)
        block_builder.set_state_hash(state_hash)

        block_publisher = self._get_block_publisher(initial_state_root)
        if not block_publisher.initialize_block(block_builder.block_header):
            LOGGER.error('Consensus refused to initialize consensus block.')
            raise InvalidGenesisConsensusError(
                'Consensus refused to initialize genesis block.')

        if not block_publisher.finalize_block(block_builder.block_header):
            LOGGER.error('Consensus refused to finalize genesis block.')
            raise InvalidGenesisConsensusError(
                'Consensus refused to finalize genesis block.')

        self._sign_block(block_builder)

        block = block_builder.build_block()

        blkw = BlockWrapper(block=block)

        LOGGER.info('Genesis block created: %s', blkw)

        self._block_manager.put([blkw.block])
        self._block_manager.persist(blkw.identifier, "commit_store")

        self._txn_receipt_store.chain_update(block, txn_receipts)
        self._chain_id_manager.save_block_chain_id(block.header_signature)

        LOGGER.debug('Deleting genesis data.')
        os.remove(genesis_file)

        if on_done is not None:
            on_done()

Starts the genesis block creation process.  Will call the given
`on_done` callback on successful completion.

Args:
on_done (function): a function called on completion

Raises:
InvalidGenesisStateError: raises this error if a genesis block is
unable to be produced, or the resulting block-chain-id saved.


def insert_and_get(self, **fields):

        if not self.conflict_target and not self.conflict_action:

            return super().create(**fields)

        compiler = self._build_insert_compiler([fields])
        rows = compiler.execute_sql(return_id=False)

        columns = rows[0]

        model_columns = {}
        for field in self.model._meta.local_concrete_fields:
            model_columns[field.column] = field.attname

        model_init_fields = {}
        for column_name, column_value in columns.items():
            try:
                model_init_fields[model_columns[column_name]] = column_value
            except KeyError:
                pass

        return self.model(**model_init_fields)

Creates a new record in the database and then gets
the entire row.

This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)

Arguments:
fields:
The fields of the row to create.

Returns:
The model instance representing the row that was created.


def append_item(self, item):

        if isinstance(item, SubmenuItem):
            raise TypeError("SubmenuItems cannot be added to a MultiSelectMenu")
        super(MultiSelectMenu, self).append_item(item)

Add an item to the end of the menu before the exit item.

Note that Multi-Select Menus will not allow a SubmenuItem to be added, as multi-select menus
are expected to be used only for executing multiple actions.

Args:
item (:obj:`MenuItem`): The item to be added

Raises:
TypeError: If the specified MenuIem is a SubmenuItem.


def build_from_queue(cls, input_queue, replay_size, batch_size):
    return cls((lambda : input_queue.dequeue_many(batch_size)), replay_size, batch_size=batch_size)

Builds a `ReplayableQueue` that draws from a regular `input_queue`.

Args:
input_queue: The queue to draw from.
replay_size: The size of the replay buffer.
batch_size: The size of each batch.

Returns:
A ReplayableQueue.


def pair_wise_sigmoid_focal_loss(inputs: Tensor, labels: Tensor, alpha: float=0.25, gamma: float=2.0) -> Tensor:
    if alpha < 0:
        raise ValueError('alpha must be positive')
    height_and_width = inputs.shape[1]
    criterion = nn.BCEWithLogitsLoss(reduction='none')
    prob = inputs.sigmoid()
    cross_entropy_loss_pos = criterion(inputs, torch.ones_like(inputs))
    focal_pos = (1 - prob) ** gamma * cross_entropy_loss_pos
    focal_pos *= alpha
    cross_entropy_loss_neg = criterion(inputs, torch.zeros_like(inputs))
    focal_neg = prob ** gamma * cross_entropy_loss_neg
    focal_neg *= 1 - alpha
    loss = torch.matmul(focal_pos, labels.T) + torch.matmul(focal_neg, (1 - labels).T)
    return loss / height_and_width

A pair wise version of the focal loss, see `sigmoid_focal_loss` for usage.

Args:
inputs (`torch.Tensor`):
A tensor representing a mask.
labels (`torch.Tensor`):
A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
(0 for the negative class and 1 for the positive class).
alpha (float, *optional*, defaults to 0.25):
Weighting factor in range (0,1) to balance positive vs negative examples.
gamma (float, *optional*, defaults to 2.0):
Exponent of the modulating factor \\(1 - p_t\\) to balance easy vs hard examples.

Returns:
`torch.Tensor`: The computed loss between each pairs.


def __init__(self, shape, dtype):

    self._dtype = dtype
    self._sum = tf.Variable(lambda: tf.zeros(shape, dtype), False)
    self._count = tf.Variable(lambda: 0, trainable=False)

Specify the shape and dtype of the mean to be estimated.

Note that a float mean to zero submitted elements is NaN, while computing
the integer mean of zero elements raises a division by zero error.

Args:
shape: Shape of the mean to compute.
dtype: Data type of the mean to compute.


def batch_slice(linop, params_overrides, slices):
    if not isinstance(slices, collections.abc.Sequence):
        slices = (slices,)
    if len(slices) == 1 and slices[0] is Ellipsis:
        override_dict = {}
    else:
        batch_shape = linop.batch_shape_tensor()
        override_dict = {}
        for param_name, param_ndims_to_matrix_ndims in linop._experimental_parameter_ndims_to_matrix_ndims.items():
            param = getattr(linop, param_name)
            if param is not None:
                override_dict[param_name] = nest.map_structure_up_to(param, functools.partial(_slice_single_param, slices=slices, batch_shape=batch_shape), param, param_ndims_to_matrix_ndims)
    override_dict.update(params_overrides)
    parameters = dict(linop.parameters, **override_dict)
    return type(linop)(**parameters)

Slices `linop` along its batch dimensions.

Args:
linop: A `LinearOperator` instance.
params_overrides: A `dict` of parameter overrides.
slices: A `slice` or `int` or `int` `Tensor` or `tf.newaxis` or `tuple`
thereof. (e.g. the argument of a `__getitem__` method).

Returns:
new_linop: A batch-sliced `LinearOperator`.


def __gt__(self, other):

    if not isinstance(other, DateTimeValues):
      raise ValueError('Other not an instance of DateTimeValues')

    normalized_timestamp = self._GetNormalizedTimestamp()
    other_normalized_timestamp = other._GetNormalizedTimestamp()

    if normalized_timestamp is None:
      return False

    if other_normalized_timestamp is None:
      return True

    return normalized_timestamp > other_normalized_timestamp

Determines if the date time values are greater than other.

Args:
other (DateTimeValues): date time values to compare against.

Returns:
bool: True if the date time values are greater than other.

Raises:
ValueError: if other is not an instance of DateTimeValues.


def device(self):
    hdevice = self._libinput.libinput_event_get_device(self._hevent)
    return Device(hdevice, self._libinput)

The device associated with this event.

For device added/removed events this is the device added or removed.
For all other device events, this is the device that generated the
event.

Returns:
~libinput.define.Device: Device object.


def __init__(self, default_model=None, id_resolver=None):

    try:
      super(ModelAdapter, self).__init__(id_resolver)
    except:
      pass
    self.default_model = default_model
    self.want_pbs = 0

Constructor.

Args:
default_model: If an implementation for the kind cannot be found, use
this model class.  If none is specified, an exception will be thrown
(default).
id_resolver: A datastore_pbs.IdResolver that can resolve
application ids. This is only necessary when running on the Cloud
Datastore v1 API.


def UploadAccount(self, hash_algorithm, hash_key, accounts):

    param = {
        'hashAlgorithm': hash_algorithm,
        'signerKey': hash_key,
        'users': accounts
    }

    return self._InvokeGitkitApi('uploadAccount', param)

Uploads multiple accounts to Gitkit server.

Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.

Returns:
Response of the API.


def lint(self, targets):

        LinterRunner.targets = targets
        linters = self._config.get_linter_classes()
        with Pool() as pool:
            out_err_none = pool.map(LinterRunner.run, linters)
        out_err = [item for item in out_err_none if item is not None]
        stdout, stderr = zip(*out_err)
        return sorted(chain.from_iterable(stdout)), chain.from_iterable(stderr)

Run linters in parallel and sort all results.

Args:
targets (list): List of files and folders to lint.


def acquire(self):
    if os.path.exists(self.path):
        try:
            pid = None
            with open(self.path, 'r') as f:
                line = f.readline().strip()
                pid = int(line)
            if (not psutil.pid_exists(pid)):
                os.remove(self.path)
        except ValueError as e:
            os.remove(self.path)
        except IOError as e:
            pass
    try:
        self.fd = os.open(self.path, ((os.O_CREAT | os.O_EXCL) | os.O_RDWR))
        to_write = ('%s%s' % (os.getpid(), os.linesep))
        os.write(self.fd, to_write.encode())
    except OSError as e:
        if (not os.path.exists(self.path)):
            raise
        return False
    self.acquired = True
    return True

Attempts to acquire a lock for the J-Link lockfile.

If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.

Args:
self (Jlock): the ``JLock`` instance

Returns:
``True`` if the lock was acquired, otherwise ``False``.

Raises:
OSError: on file errors.


def delete_branch(profile, name):

    ref = "heads/" + name
    data = refs.delete_ref(profile, ref)
    return data

Delete a branch.

Args:

profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.

name
The name of the branch to delete.

Returns:
The response of the DELETE request.


def _continue_search(self, state):

    i = state[_StateKeys.CUR_INDEX]
    alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]
    finished_scores = state[_StateKeys.FINISHED_SCORES]
    finished_flags = state[_StateKeys.FINISHED_FLAGS]

    not_at_max_decode_length = tf.less(i, self.max_decode_length)

    max_length_norm = _length_normalization(self.alpha, self.max_decode_length)

    best_alive_scores = alive_log_probs[:, 0] / max_length_norm

    finished_scores *= tf.to_float(finished_flags)
    lowest_finished_scores = tf.reduce_min(finished_scores, axis=1)

    finished_batches = tf.reduce_any(finished_flags, 1)
    lowest_finished_scores += (1. - tf.to_float(finished_batches)) * -INF

    worst_finished_score_better_than_best_alive_score = tf.reduce_all(
        tf.greater(lowest_finished_scores, best_alive_scores)
    )

    return tf.logical_and(
        not_at_max_decode_length,
        tf.logical_not(worst_finished_score_better_than_best_alive_score)
    )

Return whether to continue the search loop.

The loops should terminate when
1) when decode length has been reached, or
2) when the worst score in the finished sequences is better than the best
score in the alive sequences (i.e. the finished sequences are provably
unchanging)

Args:
state: A dictionary with the current loop state.

Returns:
Bool tensor with value True if loop should continue, False if loop should
terminate.


def _record_op_seen_by_control_dependencies(self, op) -> None:
    for controller in self._control_dependencies_stack:
        controller.add_op(op)

Record that the given op depends on all registered control dependencies.

Args:
op: An Operation.


def user_exists(self, username):
    response = self._get((self.rest_url + '/user'), params={'username': username})
    if (not response.ok):
        return None
    return True

Determines if the user exists.

Args:
username: The user name.

Returns:
bool:
True if the user exists in the Crowd application.


def find_files(directory, pattern, recursively=True):

    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                yield root, basename
        if not recursively:
            break

Yield a list of files with their base directories, recursively or not.

Returns:
A list of (base_directory, filename)

Args:
directory: base directory to start the search.
pattern: fnmatch pattern for filenames.
complete_filename: return complete filename or not?
recursively: do we recurse or not?


def readinto(self, b):

        if not self._readable:
            raise UnsupportedOperation('read')

        size = len(b)
        with self._seek_lock:
            start = self._seek
            end = start + size
            self._seek = end

        with handle_os_exceptions():
            read_data = self._read_range(start, end)

        read_size = len(read_data)
        if read_size:
            memoryview(b)[:read_size] = read_data

        if read_size != size:
            with self._seek_lock:
                self._seek = start + read_size

        return read_size

Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.

Args:
b (bytes-like object): buffer.

Returns:
int: number of bytes read


def fit(self, X):

        training_signal = X

        self.window_design(self.window_length, self.beta)

        if self.method == 'std_dev':
            self.fit_freq_std_dev(training_signal)
        elif self.method == 'min_max':
            self.fit_freq_min_max(training_signal)
        else:
            raise ValueError('Unknown method: {}'.format(self.method))

Defines a spectral mask based on training data

Args:
X: Training data


def list_members(self, name, type='USER', recurse=True, max_results=1000):
    results = self.client.service.getListMembership(name, type, recurse, max_results, self.proxy_id)
    return [item['member'] for item in results]

Look up all the members of a list.

Args:
name (str): The name of the list
type (str): The type of results to return. "USER" to get users,
"LIST" to get lists.
recurse (bool): Presumably, whether to recurse into member lists
when retrieving users.
max_results (int): Maximum number of results to return.

Returns:
list of strings: names of the members of the list


async def is_change_done(self, zone, change_id):

        zone_id = self.get_managed_zone(zone)
        url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'
        resp = await self.get_json(url)
        return resp['status'] == self.DNS_CHANGES_DONE

Check if a DNS change has completed.

Args:
zone (str): DNS zone of the change.
change_id (str): Identifier of the change.
Returns:
Boolean


def unsubscribe(self, peer_jid):

        self.roster.unsubscribe(aioxmpp.JID.fromstr(peer_jid).bare())

Asks for unsubscription

Args:
peer_jid (str): the JID you ask for unsubscriptiion


async def apply(self, sender: str, recipient: str, mailbox: str, append_msg: AppendMessage) -> Tuple[(Optional[str], AppendMessage)]:
    ...

Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually
the same as ``append_msg``.

Args:
sender: The envelope sender of the message.
recipient: The envelope recipient of the message.
mailbox: The intended mailbox to append the message.
append_msg: The message to be appended.

raises:
:exc:`~pymap.exceptions.AppendFailure`


def GetUpdateTimestamp(self):
    if self.update_time is None:
        self.update_time = self._ReadTimestamp(self.update_file)
    return self.update_time

Return the timestamp of the last cache update.

Returns:
An int with the number of seconds since epoch, or None if the timestamp
file doesn't exist or has errors.


def one_step(self, current_state, previous_kernel_results):

    @tfp.mcmc.internal.util.make_innermost_setter
    def set_num_leapfrog_steps(kernel_results, num_leapfrog_steps):
        return kernel_results._replace(accepted_results=kernel_results.accepted_results._replace(num_leapfrog_steps=num_leapfrog_steps))
    step_size = previous_kernel_results.new_step_size
    previous_kernel_results = set_num_leapfrog_steps(previous_kernel_results, self._num_leapfrog_steps(step_size))
    (new_state, kernel_results) = self._kernel.one_step(self._flatten_state(current_state), previous_kernel_results)
    return (self._unflatten_state(new_state), kernel_results)

Runs one iteration of NeuTra.

Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`.
previous_kernel_results: `collections.namedtuple` containing `Tensor`s
representing values from previous calls to this function (or from the
`bootstrap_results` function.)

Returns:
next_state: Tensor or Python list of `Tensor`s representing the state(s)
of the Markov chain(s) after taking exactly one step. Has same type and
shape as `current_state`.
kernel_results: `collections.namedtuple` of internal calculations used to
advance the chain.


def get_worksheet_keys(data_dict, result_info_key):

    keys = set(data_dict.keys())
    keys.remove(result_info_key)
    if 'meta' in keys:
        keys.remove('meta')
    return sorted(keys)

Gets sorted keys from the dict, ignoring result_info_key and 'meta' key
Args:
data_dict: dict to pull keys from

Returns:
list of keys in the dict other than the result_info_key


def config_str2dict(option_value):
    dict = {}
    for key in option_value.split(','):
        if (':' in key):
            (key, value) = pair.split(':')
            value = float(value)
        else:
            value = 0
        dict[key] = value
    return dict

Parse the value of a config option and convert it to a dictionary.

The configuration allows lines formatted like:
foo = Bar:1,Baz,Flub:0.75
This gets converted to a dictionary:
foo = { 'Bar': 1, 'Baz': 0, 'Flub': 0.75 }

Args:
option_value -- The config string to parse.


def __init__(self, name, code, return_type, params=None, language='js', imports=None):

    if not isinstance(return_type, basestring):
      raise TypeError('Argument return_type should be a string. Instead got: ', type(return_type))
    if params and not isinstance(params, list):
      raise TypeError('Argument params should be a list of parameter names and types')
    if imports and not isinstance(imports, list):
      raise TypeError('Argument imports should be a list of GCS string paths')
    if imports and language != 'js':
      raise Exception('Imports are available for Javascript UDFs only')

    self._name = name
    self._code = code
    self._return_type = return_type
    self._params = params or []
    self._language = language
    self._imports = imports or []
    self._sql = None

Initializes a UDF object from its pieces.

Args:
name: the name of the javascript function
code: function body implementing the logic.
return_type: BigQuery data type of the function return. See supported data types in
the BigQuery docs
params: list of parameter tuples: (name, type)
language: see list of supported languages in the BigQuery docs
imports: a list of GCS paths containing further support code.


def merge(metric_kind, prior, latest):

    prior_type, _ = _detect_value(prior)
    latest_type, _ = _detect_value(latest)
    if prior_type != latest_type:
        _logger.warn(u'Metric values are not compatible: %s, %s',
                     prior, latest)
        raise ValueError(u'Incompatible delta metric values')
    if prior_type is None:
        _logger.warn(u'Bad metric values, types not known for : %s, %s',
                     prior, latest)
        raise ValueError(u'Unsupported delta metric types')

    if metric_kind == MetricKind.DELTA:
        return _merge_delta_metric(prior, latest)
    else:
        return _merge_cumulative_or_gauge_metrics(prior, latest)

Merges `prior` and `latest`

Args:
metric_kind (:class:`MetricKind`): indicates the kind of metrics
being merged
prior (:class:`MetricValue`): an prior instance of the metric
latest (:class:`MetricValue`: the latest instance of the metric


def colourise(__text: str, *args, **kwargs) -> str:

    if sys.stdout.isatty():
        __text = style(__text, *args, **kwargs)
    return __text

Colourise text using click’s style function.

Returns text untouched if colour output is not enabled, or ``stdout`` is
not a tty.

See :func:`click.style` for parameters

Args:
__text: Text to colourise
Returns:
Colourised text, when possible


def main():
    windows_libraries = list(pylink.Library.find_library_windows())
    latest_library = None
    for lib in windows_libraries:
        if os.path.dirname(lib).endswith('JLinkARM'):
            latest_library = lib
            break
        elif (latest_library is None):
            latest_library = lib
        elif (os.path.dirname(lib) > os.path.dirname(latest_library)):
            latest_library = lib
    if (latest_library is None):
        raise OSError('No J-Link library found.')
    library = pylink.Library(latest_library)
    jlink = pylink.JLink(lib=library)
    print(('Found version: %s' % jlink.version))
    for emu in jlink.connected_emulators():
        jlink.disable_dialog_boxes()
        jlink.open(serial_no=emu.SerialNumber)
        jlink.sync_firmware()
        print(('Updated emulator with serial number %s' % emu.SerialNumber))
    return None

Upgrades the firmware of the J-Links connected to a Windows device.

Returns:
None.

Raises:
OSError: if there are no J-Link software packages.


def restore_state(self, state):

        config_vars = state.get('config_variables', {})

        for str_name, str_value in config_vars.items():
            name = int(str_name)
            value = base64.b64decode(str_value)

            if name in self._config_variables:
                self._config_variables[name].current_value = value

Restore the current state of this emulated object.

Args:
state (dict): A previously dumped state produced by dump_state.


def economic_qs_linear(G):
    r
    import dask.array as da

    if not isinstance(G, da.Array):
        G = asarray(G, float)

    if G.shape[0] > G.shape[1]:
        (Q, Ssq, _) = svd(G, full_matrices=True)
        S0 = Ssq ** 2
        rank = len(S0)
        Q0, Q1 = Q[:, :rank], Q[:, rank:]
        return ((Q0, Q1), S0)

    return economic_qs(G.dot(G.T))

r"""Economic eigen decomposition for symmetric matrices ``dot(G, G.T)``.

It is theoretically equivalent to ``economic_qs(dot(G, G.T))``.
Refer to :func:`numpy_sugar.economic_qs` for further information.

Args:
G (array_like): Matrix.

Returns:
tuple: ``((Q0, Q1), S0)``.


def _dataset_load_from_hdx(self, id_or_name):

        if not self._load_from_hdx('dataset', id_or_name):
            return False
        self._dataset_create_resources()
        return True

Loads the dataset given by either id or name from HDX

Args:
id_or_name (str): Either id or name of dataset

Returns:
bool: True if loaded, False if not


def thread(self, value: str):
    if ((value is not None) and (not isinstance(value, str))):
        raise TypeError("'thread' MUST be a string")
    self._thread = value

Set thread id of the message

Args:
value (str): the thread id


def add_argument(self, parser, bootstrap=False):
    if self.cli_expose:
        if isinstance(self.child, YapconfBoolItem):
            original_default = self.child.default
            self.child.default = True
            args = self.child._get_argparse_names(parser.prefix_chars)
            kwargs = self._get_argparse_kwargs(bootstrap)
            parser.add_argument(*args, **kwargs)
            self.child.default = False
            args = self.child._get_argparse_names(parser.prefix_chars)
            kwargs = self._get_argparse_kwargs(bootstrap)
            parser.add_argument(*args, **kwargs)
            self.child.default = original_default
        else:
            super(YapconfListItem, self).add_argument(parser, bootstrap)

Add list-style item as an argument to the given parser.

Generally speaking, this works mostly like the normal append
action, but there are special rules for boolean cases. See the
AppendReplace action for more details.

Examples:
A non-nested list value with the name 'values' and a child name of
'value' will result in a command-line argument that will correctly
handle arguments like the following:

['--value', 'VALUE1', '--value', 'VALUE2']

Args:
parser (argparse.ArgumentParser): The parser to add this item to.
bootstrap (bool): Flag to indicate whether you only want to mark
this item as required or not.


def update_object(self, ref, payload, return_fields=None):

        query_params = self._build_query_params(return_fields=return_fields)

        opts = self._get_request_options(data=payload)
        url = self._construct_url(ref, query_params)
        self._log_request('put', url, opts)
        r = self.session.put(url, **opts)

        self._validate_authorized(r)

        if r.status_code != requests.codes.ok:
            self._check_service_availability('update', r, ref)

            raise ib_ex.InfobloxCannotUpdateObject(
                response=jsonutils.loads(r.content),
                ref=ref,
                content=r.content,
                code=r.status_code)

        return self._parse_reply(r)

Update an Infoblox object

Args:
ref      (str): Infoblox object reference
payload (dict): Payload with data to send
Returns:
The object reference of the updated object
Raises:
InfobloxException


Intersects two line segments

Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do


def _path(cls, ndivsm, structure=None, kpath_bounds=None, comment=None):

        if kpath_bounds is None:

            from pymatgen.symmetry.bandstructure import HighSymmKpath
            sp = HighSymmKpath(structure)

            kpath_labels = []
            for labels in sp.kpath["path"]:
                kpath_labels.extend(labels)

            kpath_bounds = []
            for label in kpath_labels:
                red_coord = sp.kpath["kpoints"][label]

                kpath_bounds.append(red_coord)

        return cls(mode=KSamplingModes.path, num_kpts=ndivsm, kpts=kpath_bounds,
                   comment=comment if comment else "K-Path scheme")

Static constructor for path in k-space.

Args:
structure: :class:`Structure` object.
kpath_bounds: List with the reduced coordinates of the k-points defining the path.
ndivsm: Number of division for the smallest segment.
comment: Comment string.

Returns:
:class:`KSampling` object.


def set_trunk_groups(self, intf, value=None, default=False, disable=False):

        if default:
            cmd = 'default switchport trunk group'
            return self.configure_interface(intf, cmd)

        if disable:
            cmd = 'no switchport trunk group'
            return self.configure_interface(intf, cmd)

        current_value = self.get(intf)['trunk_groups']
        failure = False

        value = make_iterable(value)

        for name in set(value).difference(current_value):
            if not self.add_trunk_group(intf, name):
                failure = True

        for name in set(current_value).difference(value):
            if not self.remove_trunk_group(intf, name):
                failure = True

        return not failure

Configures the switchport trunk group value

Args:
intf (str): The interface identifier to configure.
value (str): The set of values to configure the trunk group
default (bool): Configures the trunk group default value
disable (bool): Negates all trunk group settings

Returns:
True if the config operation succeeds otherwise False


def time_stats(self, **kwargs):

        if 'time_stats' in self.attributes:
            return self.attributes['time_stats']

        path = '%s/%s/time_stats' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

Get time stats for the object.

Args:
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done


def __register_class(self, parsed_config):
    methods = parsed_config.get('methods')
    if (not methods):
        return
    service_classes = set()
    for method in methods.itervalues():
        rosy_method = method.get('rosyMethod')
        if (rosy_method and ('.' in rosy_method)):
            method_class = rosy_method.split('.', 1)[0]
            service_classes.add(method_class)
    for service_class in service_classes:
        if (service_class in self.__registered_classes):
            raise api_exceptions.ApiConfigurationError(('API class %s has already been registered.' % service_class))
        self.__registered_classes.add(service_class)

Register the class implementing this config, so we only add it once.

Args:
parsed_config: The JSON object with the API configuration being added.

Raises:
ApiConfigurationError: If the class has already been registered.


def Relay(self, inventory):

        if type(inventory) is MinerTransaction:
            return False

        if inventory.Hash.ToBytes() in self.KnownHashes:
            return False

        self.KnownHashes.append(inventory.Hash.ToBytes())

        if type(inventory) is Block:
            pass

        elif type(inventory) is Transaction or issubclass(type(inventory), Transaction):
            if not self.AddTransaction(inventory):

                try:
                    self.KnownHashes.remove(inventory.Hash.ToBytes())
                except ValueError:

                    pass
                return False
        else:

            pass

        relayed = self.RelayDirectly(inventory)
        return relayed

Relay the inventory to the remote client.

Args:
inventory (neo.Network.Inventory):

Returns:
bool: True if relayed successfully. False otherwise.


def toTFExample(dtypes):

    def _toTFExample(iter):
        float_dtypes = ['float', 'double']
        int64_dtypes = ['boolean', 'tinyint', 'smallint', 'int', 'bigint', 'long']
        bytes_dtypes = ['binary', 'string']
        float_list_dtypes = ['array<float>', 'array<double>']
        int64_list_dtypes = ['array<boolean>', 'array<tinyint>', 'array<smallint>', 'array<int>', 'array<bigint>', 'array<long>']

        def _toTFFeature(name, dtype, row):
            feature = None
            if (dtype in float_dtypes):
                feature = (name, tf.train.Feature(float_list=tf.train.FloatList(value=[row[name]])))
            elif (dtype in int64_dtypes):
                feature = (name, tf.train.Feature(int64_list=tf.train.Int64List(value=[row[name]])))
            elif (dtype in bytes_dtypes):
                if (dtype == 'binary'):
                    feature = (name, tf.train.Feature(bytes_list=tf.train.BytesList(value=[bytes(row[name])])))
                else:
                    feature = (name, tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(row[name]).encode('utf-8')])))
            elif (dtype in float_list_dtypes):
                feature = (name, tf.train.Feature(float_list=tf.train.FloatList(value=row[name])))
            elif (dtype in int64_list_dtypes):
                feature = (name, tf.train.Feature(int64_list=tf.train.Int64List(value=row[name])))
            else:
                raise Exception('Unsupported dtype: {0}'.format(dtype))
            return feature
        results = []
        for row in iter:
            features = dict([_toTFFeature(name, dtype, row) for (name, dtype) in dtypes])
            example = tf.train.Example(features=tf.train.Features(feature=features))
            results.append((bytearray(example.SerializeToString()), None))
        return results
    return _toTFExample

mapPartition function to convert a Spark RDD of Row into an RDD of serialized tf.train.Example bytestring.

Note that tf.train.Example is a fairly flat structure with limited datatypes, e.g. tf.train.FloatList,
tf.train.Int64List, and tf.train.BytesList, so most DataFrame types will be coerced into one of these types.

Args:
:dtypes: the DataFrame.dtypes of the source DataFrame.

Returns:
A mapPartition function which converts the source DataFrame into tf.train.Example bytestrings.


def ProcessAllReadyRequests(self):
    request_dict = data_store.REL_DB.ReadFlowRequestsReadyForProcessing(self.rdf_flow.client_id, self.rdf_flow.flow_id, next_needed_request=self.rdf_flow.next_request_to_process)
    if (not request_dict):
        return 0
    processed = 0
    while (self.rdf_flow.next_request_to_process in request_dict):
        (request, responses) = request_dict[self.rdf_flow.next_request_to_process]
        self.RunStateMethod(request.next_state, request, responses)
        self.rdf_flow.next_request_to_process += 1
        processed += 1
        self.completed_requests.append(request)
    if (processed and self.IsRunning() and (not self.outstanding_requests)):
        self.RunStateMethod('End')
        if ((self.rdf_flow.flow_state == self.rdf_flow.FlowState.RUNNING) and (not self.outstanding_requests)):
            self.MarkDone()
    self.PersistState()
    if (not self.IsRunning()):
        self._ClearAllRequestsAndResponses()
    return processed

Processes all requests that are due to run.

Returns:
The number of processed requests.


def __init__(self, dom, path):

        self._dom = dom
        self._providers = {
            name: self._get_provider(spec)
            for name, spec in self._dom.get('sources', {}).items()
        }
        self._path = path

You would usually use the
:func:`TemplateRepository.from_url` method instead of
directly using this

Args:
dom (dict): Specification of the template repository (not confuse
with xml dom)


def _parse_section(name, source):
    section = textwrap.dedent(_get_section(name, source)[7:])
    commands = []
    for line in section.splitlines():
        if ((not commands) or (line[:1].isalpha() and line[:1].islower())):
            commands.append(line)
        else:
            commands[(- 1)] = '{} {}'.format(commands[(- 1)].strip(), line.strip())
    return commands

Yield each section line.

Note:
Depending on how it is wrapped, a section line can take up more than
one physical line.

Args:
name: The name of the section to extract (e.g. "Usage").
source: The usage string to parse.

Returns:
A list containing each line, de-wrapped by whitespace from the source
code.
If the section is defined multiple times in the source code, all lines
from all sections with that name will be returned.


def sg_min(tensor, opt):
    r
    return tf.reduce_min(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)

r"""Computes the minimum of elements across axis of a tensor.

See `tf.reduce_min()` in tensorflow.

Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with length 1.
name: If provided, replace current tensor's name.

Returns:
A `Tensor`.