def _checkpoint_dependencies(self):
    return self._self_unconditional_checkpoint_dependencies

All dependencies of this object.

May be overridden to include conditional dependencies.

Returns:
A list of `TrackableReference` objects indicating named
`Trackable` dependencies which should be saved along with this
object.


def __init__(self, encoding='utf-8'):

    super(CLIInputReader, self).__init__()
    self._encoding = encoding

Initializes an input reader.

Args:
encoding (Optional[str]): input encoding.


def argflag(key, argv=None):
    if (argv is None):
        argv = sys.argv
    keys = ([key] if isinstance(key, six.string_types) else key)
    flag = any(((k in argv) for k in keys))
    return flag

Determines if a key is specified on the command line

Args:
key (str or tuple): string or tuple of strings. Each key should be
prefixed with two hyphens (i.e. `--`)
argv (Optional[list]): overrides `sys.argv` if specified

Returns:
bool: flag : True if the key (or any of the keys) was specified

Example:
>>> import ubelt as ub
>>> argv = ['--spam', '--eggs', 'foo']
>>> assert ub.argflag('--eggs', argv=argv) is True
>>> assert ub.argflag('--ans', argv=argv) is False
>>> assert ub.argflag('foo', argv=argv) is True
>>> assert ub.argflag(('bar', '--spam'), argv=argv) is True


def non_argument_modifiers(role='ARG1', only_connecting=True):

    def func(xmrs, deps):
        edges = []
        for src in deps:
            for (_, tgt) in deps[src]:
                edges.append((src, tgt))
        components = _connected_components(xmrs.nodeids(), edges)
        ccmap = {}
        for (i, component) in enumerate(components):
            for n in component:
                ccmap[n] = i
        addl = {}
        if ((not only_connecting) or (len(components) > 1)):
            lsh = xmrs.labelset_heads
            lblheads = {v: lsh(v) for (v, vd) in xmrs._vars.items() if ('LBL' in vd['refs'])}
            for heads in lblheads.values():
                if (len(heads) > 1):
                    first = heads[0]
                    joined = set([ccmap[first]])
                    for other in heads[1:]:
                        occ = ccmap[other]
                        srt = var_sort(xmrs.args(other).get(role, 'u0'))
                        needs_edge = ((not only_connecting) or (occ not in joined))
                        edge_available = (srt == 'u')
                        if (needs_edge and edge_available):
                            addl.setdefault(other, []).append((role, first))
                            joined.add(occ)
        return addl
    return func

Return a function that finds non-argument modifier dependencies.

Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate components in the basic dependencies;
if `False`, all non-argument modifier dependencies are
included

Returns:
a function with signature `func(xmrs, deps)` that returns a
mapping of non-argument modifier dependencies

Examples:
The default function behaves like the LKB:

>>> func = non_argument_modifiers()

A variation is similar to DMRS's MOD/EQ links:

>>> func = non_argument_modifiers(role="MOD", only_connecting=False)


def rhombohedral(a: float, alpha: float):
    return Lattice.from_parameters(a, a, a, alpha, alpha, alpha)

Convenience constructor for a rhombohedral lattice.

Args:
a (float): *a* lattice parameter of the rhombohedral cell.
alpha (float): Angle for the rhombohedral lattice in degrees.

Returns:
Rhombohedral lattice of dimensions a x a x a.


def get_program_by_uuid(self, program_uuid):

        return self._load_data(
            self.PROGRAMS_ENDPOINT,
            resource_id=program_uuid,
            default=None
        )

Return single program by UUID, or None if not found.

Arguments:
program_uuid(string): Program UUID in string form

Returns:
dict: Program data provided by Course Catalog API


def is_likely_benign(bs_terms, bp_terms):
    if bs_terms:
        if bp_terms:
            return True
    if (len(bp_terms) >= 2):
        return True
    return False

Check if criterias for Likely Benign are fullfilled

The following are descriptions of Likely Benign clasification from ACMG paper:

Likely Benign
(i) 1 Strong (BS1–BS4) and 1 supporting (BP1– BP7) OR
(ii) ≥2 Supporting (BP1–BP7)

Args:
bs_terms(list(str)): Terms that indicate strong evidence for benign variant
bp_terms(list(str)): Terms that indicate supporting evidence for benign variant

Returns:
bool: if classification indicates Benign level


def Group(params, name=None, type=None):

    atts = {}
    if name:
        atts['name'] = name
    if type:
        atts['type'] = type
    g = objectify.Element('Group', attrib=atts)
    for p in params:
        g.append(p)
    return g

Groups together Params for adding under the 'What' section.

Args:
params(list of :func:`Param`): Parameter elements to go in this group.
name(str): Group name. NB ``None`` is valid, since the group may be
best identified by its type.
type(str): Type of group, e.g. 'complex' (for real and imaginary).


def console_get_alignment(con: tcod.console.Console) -> int:

    return int(lib.TCOD_console_get_alignment(_console(con)))

Return this consoles current alignment mode.

Args:
con (Console): Any Console instance.

.. deprecated:: 8.5
Check :any:`Console.default_alignment` instead.


def mutual_info(rho: Density,
                qubits0: Qubits,
                qubits1: Qubits = None,
                base: float = None) -> float:

    if qubits1 is None:
        qubits1 = tuple(set(rho.qubits) - set(qubits0))

    rho0 = rho.partial_trace(qubits1)
    rho1 = rho.partial_trace(qubits0)

    ent = entropy(rho, base)
    ent0 = entropy(rho0, base)
    ent1 = entropy(rho1, base)

    return ent0 + ent1 - ent

Compute the bipartite von-Neumann mutual information of a mixed
quantum state.

Args:
rho:    A density matrix of the complete system
qubits0: Qubits of system 0
qubits1: Qubits of system 1. If none, taken to be all remaining qubits
base:   Optional logarithm base. Default is base e

Returns:
The bipartite von-Neumann mutual information.


def compile_file(source, globals_=None):
    if isinstance(source, gast.AST):
        source = quoting.to_source(source)
    tempdir = tempfile.mkdtemp()
    uuid = str(uuid4().hex[:4])
    tmpname = os.path.join(tempdir, ('tangent_%s.py' % uuid))
    with open(tmpname, 'w') as f:
        f.write(source)
    module_name = ('tangent_%s' % uuid)
    if six.PY3:
        spec = util.spec_from_file_location(module_name, tmpname)
        m = util.module_from_spec(spec)
        spec.loader.exec_module(m)
    else:
        m = imp.load_source(module_name, tmpname)
    if globals_:
        m.__dict__.update(globals_)
    return m

Compile by saving to file and importing that.

Compiling the AST/source code this way ensures that the source code is
readable by e.g. `pdb` or `inspect`.

Args:
source: The code to compile, either as a string or as an AST.
globals_: A dictionary of variables that should be available as globals in
the compiled module. They will be monkey patched after importing the
module.

Returns:
A module object containing the compiled source code.


def clone(self, name=None):
    if (name is None):
        name = (self.module_name + '_clone')
    return Linear(output_size=self.output_size, use_bias=self._use_bias, initializers=self._initializers, partitioners=self._partitioners, regularizers=self._regularizers, name=name)

Returns a cloned `Linear` module.

Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.

Returns:
Cloned `Linear` module.


def full_game_name(short_name):
    camel_game_name = misc_utils.snakecase_to_camelcase(short_name)
    full_name = (camel_game_name + ATARI_GAME_MODE)
    return full_name

CamelCase game name with mode suffix.

Args:
short_name: snake_case name without mode e.g "crazy_climber"

Returns:
full game name e.g. "CrazyClimberNoFrameskip-v4"


def element_or_none(self, using, value):
    try:
        return self._execute(Command.FIND_CHILD_ELEMENT, {'using': using, 'value': value})
    except:
        return None

Check if an element in the current element.

Support:
Android iOS Web(WebView)

Args:
using(str): The element location strategy.
value(str): The value of the location strategy.

Returns:
Return Element if the element does exists and return None otherwise.

Raises:
WebDriverException.


def generate_zip_state_data(means, weights, z):
    x_true = np.dot(means, weights)
    sample = np.random.poisson(x_true)
    random = np.random.random(x_true.shape)
    x_true[(random < z)] = 0
    return sample.astype(float)

Generates data according to the Zero-inflated Poisson Convex Mixture Model.

Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
z (float): zero-inflation parameter

Returns:
data matrix - genes x cells


def write_contents_to_file(path, contents=None, link_to=None, content_mode='text', root=None, conflicts='fail'):
    if ((root is None) and (not isabs(path))):
        root = os.getcwd()
    if root:
        path = join(root, path)
    if (exists(path) or islink(path)):
        if (conflicts == 'fail'):
            msg = 'A file at path {} already exists.'
            raise ValueError(msg.format(path))
        elif (conflicts == 'skip'):
            msg = 'A file at path {} already exists, skipping writing file.'
            logging.warn(msg.format(path))
            return
        elif (conflicts == 'overwrite'):
            if isdir(path):
                logging.warn('New path is a directory, not going to overwrite it, skipping instead.')
                return
            os.remove(path)
        elif (conflicts == 'append'):
            i = 1
            while (i < sys.maxsize):
                path_splits = splitext(path)
                path_splits[0] = (path_splits[0] + ('_%d' % i))
                appended_filename = os.extsep.join(path_splits)
                if ((not exists(appended_filename)) and (not islink(appended_filename))):
                    path = appended_filename
                    break
                i += 1
        else:
            raise ValueError('Did not provide a valid conflicts parameter')
    if (not exists(dirname(path))):
        os.makedirs(dirname(path))
    if link_to:
        os.symlink(link_to, path)
    elif contents:
        mode = ('wb' if (content_mode == 'binary') else 'w')
        with open(path, mode) as f:
            f.write(contents)
    else:
        raise ValueError('One of contents or link_to must be provided.')

Uses provided filename patterns to write contents to a new path, given
a corresponding entity map.

Args:
path (str): Destination path of the desired contents.
contents (str): Raw text or binary encoded string of contents to write
to the new path.
link_to (str): Optional path with which to create a symbolic link to.
Used as an alternative to and takes priority over the contents
argument.
content_mode (str): Either 'text' or 'binary' to indicate the writing
mode for the new file. Only relevant if contents is provided.
root (str): Optional root directory that all patterns are relative
to. Defaults to current working directory.
conflicts (str): One of 'fail', 'skip', 'overwrite', or 'append'
that defines the desired action when the output path already
exists. 'fail' raises an exception; 'skip' does nothing;
'overwrite' overwrites the existing file; 'append' adds  a suffix
to each file copy, starting with 1. Default is 'fail'.


def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False):
    if (not only_attributes):
        keys = list(self.__dict__.keys())
    else:
        keys = ssbio.utils.force_list(only_attributes)
    if exclude_attributes:
        exclude_attributes = ssbio.utils.force_list(exclude_attributes)
        for x in exclude_attributes:
            if (x in keys):
                keys.remove(x)
    df_dict = {}
    for (k, orig_v) in self.__dict__.items():
        if (k in keys):
            v = deepcopy(orig_v)
            if df_format:
                if (v and (not isinstance(v, str)) and (not isinstance(v, int)) and (not isinstance(v, float)) and (not isinstance(v, bool))):
                    try:
                        df_dict[k] = ssbio.utils.force_string(deepcopy(v))
                    except TypeError:
                        log.warning('{}: excluding attribute from dict, cannot transform into string'.format(k))
                elif ((not v) and (not isinstance(v, int)) and (not isinstance(v, float))):
                    df_dict[k] = None
                else:
                    df_dict[k] = deepcopy(v)
            else:
                df_dict[k] = deepcopy(v)
    return df_dict

Get a dictionary of this object's attributes. Optional format for storage in a Pandas DataFrame.

Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all are returned.
exclude_attributes (str, list): Attributes that should be excluded.
df_format (bool): If dictionary values should be formatted for a dataframe
(everything possible is transformed into strings, int, or float -
if something can't be transformed it is excluded)

Returns:
dict: Dictionary of attributes


def __call__(self, *args, **kwargs):

        kwarg_hash = kwargs.pop('_memoization_hash_', ())
        (self.args, self.kwargs) = (args, kwargs)
        if not args and not kwargs and not any(kwarg_hash): return self.callable()
        inputs = [i for i in self.inputs if isinstance(i, DynamicMap)]
        streams = []
        for stream in [s for i in inputs for s in get_nested_streams(i)]:
            if stream not in streams: streams.append(stream)

        memoize = self._stream_memoization and not any(s.transient and s._triggering for s in streams)
        values = tuple(tuple(sorted(s.hashkey.items())) for s in streams)
        key = args + kwarg_hash + values

        hashed_key = util.deephash(key) if self.memoize else None
        if hashed_key is not None and memoize and hashed_key in self._memoized:
            return self._memoized[hashed_key]

        if self.argspec.varargs is not None:

            pass
        elif len(args) != 0:
            pos_kwargs = {k:v for k,v in zip(self.argspec.args, args)}
            ignored = range(len(self.argspec.args),len(args))
            if len(ignored):
                self.param.warning('Ignoring extra positional argument %s'
                                   % ', '.join('%s' % i for i in ignored))
            clashes = set(pos_kwargs.keys()) & set(kwargs.keys())
            if clashes:
                self.param.warning(
                    'Positional arguments %r overriden by keywords'
                    % list(clashes))
            args, kwargs = (), dict(pos_kwargs, **kwargs)

        try:
            ret = self.callable(*args, **kwargs)
        except KeyError:

            raise
        except Exception as e:
            posstr = ', '.join(['%r' % el for el in self.args]) if self.args else ''
            kwstr = ', '.join('%s=%r' % (k,v) for k,v in self.kwargs.items())
            argstr = ', '.join([el for el in [posstr, kwstr] if el])
            message = ("Callable raised \"{e}\".\n"
                       "Invoked as {name}({argstr})")
            self.param.warning(message.format(name=self.name, argstr=argstr, e=repr(e)))
            raise

        if hashed_key is not None:
            self._memoized = {hashed_key : ret}
        return ret

Calls the callable function with supplied args and kwargs.

If enabled uses memoization to avoid calling function
unneccessarily.

Args:
*args: Arguments passed to the callable function
**kwargs: Keyword arguments passed to the callable function

Returns:
Return value of the wrapped callable function


def key_rule(self, regex, verifier):
    if (regex is not None):
        regex = re.compile(regex)
    self._additional_key_rules.append((regex, verifier))

Add a rule with a pattern that should apply to all keys.

Any key not explicitly listed in an add_required or add_optional rule
must match ONE OF the rules given in a call to key_rule().
So these rules are all OR'ed together.

In this case you should pass a raw string specifying a regex that is
used to determine if the rule is used to check a given key.

Args:
regex (str): The regular expression used to match the rule or None
if this should apply to all
verifier (Verifier): The verification rule


def _ircounts2radiance(counts, scale, offset):

        rad = (counts - offset) / scale
        return rad.clip(min=0)

Convert IR counts to radiance

Reference: [IR].

Args:
counts: Raw detector counts
scale: Scale [mW-1 m2 cm sr]
offset: Offset [1]

Returns:
Radiance [mW m-2 cm-1 sr-1]


def GetFsType(self):
    if (self._tsk_fs_type is None):
        self._tsk_fs_type = pytsk3.TSK_FS_TYPE_UNSUPP
        if ((not self._tsk_file_system) or (not hasattr(self._tsk_file_system, 'info'))):
            return self._tsk_fs_type
        self._tsk_fs_type = getattr(self._tsk_file_system.info, 'ftype', pytsk3.TSK_FS_TYPE_UNSUPP)
    return self._tsk_fs_type

Retrieves the file system type.

Returns:
pytsk3.TSK_FS_TYPE_ENUM: file system type.


def FilterItems(self, filterFn):
    with self._mutex:
        size_before = len(self.items)
        self.items = list(filter(filterFn, self.items))
        size_diff = (size_before - len(self.items))
        prop_remaining = ((len(self.items) / float(size_before)) if (size_before > 0) else 0)
        self._num_items_seen = int(round((self._num_items_seen * prop_remaining)))
        return size_diff

Filter items in a ReservoirBucket, using a filtering function.

Filtering items from the reservoir bucket must update the
internal state variable self._num_items_seen, which is used for determining
the rate of replacement in reservoir sampling. Ideally, self._num_items_seen
would contain the exact number of items that have ever seen by the
ReservoirBucket and satisfy filterFn. However, the ReservoirBucket does not
have access to all items seen -- it only has access to the subset of items
that have survived sampling (self.items). Therefore, we estimate
self._num_items_seen by scaling it by the same ratio as the ratio of items
not removed from self.items.

Args:
filterFn: A function that returns True for items to be kept.

Returns:
The number of items removed from the bucket.


def _get_color(self, age):

        if age == self.tree.age:
            return self.leaf_color
        color = self.stem_color
        tree = self.tree

        if len(color) == 3:
            return color

        diff = [color[i+3]-color[i] for i in range(3)]
        per_age = [diff[i]/(tree.age-1) for i in range(3)]

        return tuple([int(color[i]+per_age[i]*age) for i in range(3)])

Get the fill color depending on age.

Args:
age (int): The age of the branch/es

Returns:
tuple: (r, g, b)


def get_precursor_mz(exact_mass, precursor_type):
    d = {'[M-H]-': (- 1.007276), '[M+H]+': 1.007276, '[M+H-H2O]+': (1.007276 - ((1.007276 * 2) + 15.9949))}
    try:
        return (exact_mass + d[precursor_type])
    except KeyError as e:
        print(e)
        return False

Calculate precursor mz based on exact mass and precursor type

Args:
exact_mass (float): exact mass of compound of interest
precursor_type (str): Precursor type (currently only works with '[M-H]-', '[M+H]+' and '[M+H-H2O]+'

Return:
neutral mass of compound


def export_as_code(self, cv_source):

        rand_value = ''.join(random.choice(string.ascii_uppercase + string.digits)
                             for _ in range(25))

        base_learner_code = ''
        base_learner_code += 'base_learner_list_{} = []\n'.format(rand_value)
        base_learner_code += 'meta_feature_generators_list_{} = []\n\n'.format(rand_value)
        for idx, base_learner in enumerate(self.base_learners):
            base_learner_code += '
            base_learner_code += '
            base_learner_code += '
            base_learner_code += base_learner.base_learner_origin.source
            base_learner_code += '\n\n'
            base_learner_code += 'base_learner' \
                                 '.set_params(**{})\n'.format(base_learner.hyperparameters)
            base_learner_code += 'base_learner_list_{}.append(base_learner)\n'.format(rand_value)
            base_learner_code += 'meta_feature_generators_list_{}.append("{}")\n'.format(
                rand_value,
                base_learner.base_learner_origin.meta_feature_generator
            )
            base_learner_code += '\n\n'

        base_learner_code += '
        base_learner_code += '
        base_learner_code += '
        base_learner_code += self.base_learner_origin.source
        base_learner_code += '\n\n'
        base_learner_code += 'base_learner' \
                             '.set_params(**{})\n'.format(self.secondary_learner_hyperparameters)
        base_learner_code += 'secondary_learner_{} = base_learner\n'.format(rand_value)
        base_learner_code += '\n\n'

        base_learner_code += '
        base_learner_code += '
        base_learner_code += '
        base_learner_code += cv_source
        base_learner_code += '\n\n'

        base_learner_code += '
        base_learner_code += '
        base_learner_code += '
        stacker_file_loc = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'stacker.py')
        with open(stacker_file_loc) as f2:
            base_learner_code += f2.read()

        base_learner_code += '\n\n' \
                             '    def {}(self, X):\n' \
                             '        return self._process_using_' \
                             'meta_feature_generator(X, "{}")\n\n'\
            .format(self.base_learner_origin.meta_feature_generator,
                    self.base_learner_origin.meta_feature_generator)

        base_learner_code += '\n\n'

        base_learner_code += 'base_learner = XcessivStackedEnsemble' \
                             '(base_learners=base_learner_list_{},' \
                             ' meta_feature_generators=meta_feature_generators_list_{},' \
                             ' secondary_learner=secondary_learner_{},' \
                             ' cv_function=return_splits_iterable)\n'.format(
            rand_value,
            rand_value,
            rand_value
        )

        return base_learner_code

Returns a string value that contains the Python code for the ensemble

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

Returns:
base_learner_code (str, unicode): String that can be used as Python code


def validate(self):
    if ((self.status_code == 200) and self.data.get('ok', False)):
        self._logger.debug('Received the following response: %s', self.data)
        return self
    msg = 'The request to the Slack API failed.'
    raise e.SlackApiError(message=msg, response=self.data)

Check if the response from Slack was successful.

Returns:
(SlackResponse)
This method returns it's own object. e.g. 'self'

Raises:
SlackApiError: The request to the Slack API failed.


def slice_naive(self, key):
    kwargs = {'name': self.name, 'description': self.description, 'meta': self.meta}
    for (name, data) in self._data().items():
        k = (name[1:] if name.startswith('_') else name)
        kwargs[k] = data.slice_naive(key)
    return self.__class__(**kwargs)

Naively slice each data object in the container by the object's index.

Args:
key: Int, slice, or list by which to extra "sub"-container

Returns:
sub: Sub container of the same format with a view of the data

Warning:
To ensure that a new container is created, use the copy method.

.. code-block:: Python

mycontainer[slice].copy()


def upsample_like(pixel_values: Tensor, like: Tensor, mode: str='bilinear') -> Tensor:
    _, _, height, width = like.shape
    upsampled = nn.functional.interpolate(pixel_values, size=(height, width), mode=mode, align_corners=False)
    return upsampled

An utility function that upsamples `pixel_values` to match the dimension of `like`.

Args:
pixel_values (`torch.Tensor`):
The tensor we wish to upsample.
like (`torch.Tensor`):
The tensor we wish to use as size target.
mode (str, *optional*, defaults to `"bilinear"`):
The interpolation mode.

Returns:
`torch.Tensor`: The upsampled tensor


def ParseOptions(cls, options, configuration_object):

    if not isinstance(configuration_object, tools.CLITool):
      raise errors.BadConfigObject(
          'Configuration object is not an instance of CLITool')

    data_location = cls._ParseStringOption(options, 'data_location')
    if not data_location:

      data_location = os.path.dirname(cls._PATH)
      data_location = os.path.dirname(data_location)
      data_location = os.path.dirname(data_location)
      data_location = os.path.dirname(data_location)

      data_location_egg = os.path.join(data_location, 'share', 'plaso')
      data_location_source = os.path.join(data_location, 'data')

      data_location = None
      if os.path.exists(data_location_egg) and os.path.isfile(os.path.join(
          data_location_egg, 'plaso-data.README')):
        data_location = data_location_egg
      elif os.path.exists(data_location_source) and os.path.isfile(os.path.join(
          data_location_source, 'plaso-data.README')):
        data_location = data_location_source

      if not data_location or not os.path.exists(data_location):
        data_location = os.path.join(sys.prefix, 'share', 'plaso')
      if not os.path.exists(data_location):
        data_location = os.path.join(sys.prefix, 'local', 'share', 'plaso')

      if sys.prefix != '/usr':
        if not os.path.exists(data_location):
          data_location = os.path.join('/usr', 'share', 'plaso')
        if not os.path.exists(data_location):
          data_location = os.path.join('/usr', 'local', 'share', 'plaso')

      if not os.path.exists(data_location) or not os.path.isfile(os.path.join(
          data_location, 'plaso-data.README')):
        data_location = None

    if not data_location:
      raise errors.BadConfigOption(
          'Unable to determine location of data files.')

    logger.info('Determined data location: {0:s}'.format(data_location))

    setattr(configuration_object, '_data_location', data_location)

Parses and validates options.

Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.

Raises:
BadConfigObject: when the configuration object is of the wrong type.


def hash_stream(self, url):

        md5hash = hashlib.md5()
        try:
            for chunk in self.response.iter_content(chunk_size=10240):
                if chunk:
                    md5hash.update(chunk)
            return md5hash.hexdigest()
        except Exception as e:
            raisefrom(DownloadError, 'Download of %s failed in retrieval of stream!' % url, e)

Stream file from url and hash it using MD5. Must call setup method first.

Args:
url (str): URL to download

Returns:
str: MD5 hash of file


def UploadImage(client, filepath):

  media_service = client.GetService('MediaService', 'v201809')

  with open(filepath, 'rb') as image_handle:
    image_data = image_handle.read().decode('utf-8')

  image = [{
      'xsi_type': 'Image',
      'data': image_data,
      'type': 'IMAGE'
  }]

  image = media_service.upload(image)[0]

  return image

Uploads a .jpg image with the given filepath via the AdWords MediaService.

Args:
client: an AdWordsClient instance.
filepath: a str filepath to the .jpg file to be uploaded.

Returns:
The created Image as a sudsobject.


def CopyToStatTimeTuple(self):
    if (self.fraction_of_second is None):
        return (self._timestamp, None)
    return super(TSKTime, self).CopyToStatTimeTuple()

Copies the SleuthKit timestamp to a stat timestamp tuple.

Returns:
tuple[int, int]: a POSIX timestamp in seconds and the remainder in
100 nano seconds or (None, None) on error.


def output_slot(self):
    return self._output_slot

Output slot index from which the tensor value was dumped.

Returns:
(`int`) output slot index watched by the debug op.


def __init__(self, model: typing.Dict[str, typing.Dict[str, int]]):
    self.model = model

Initializes the parser.

Args:
model (Dict[str, Dict[str, int]]): A dict mapping a feature and its score.


def compute_ld(cur_geno, other_genotypes, r2=False):
    norm_cur = normalize_genotypes(cur_geno)
    norm_others = np.stack(tuple((normalize_genotypes(g) for g in other_genotypes)), axis=1)
    assert (norm_cur.shape[0] == norm_others.shape[0])
    n = ((~ np.isnan(norm_cur.reshape(norm_cur.shape[0], 1))) * (~ np.isnan(norm_others))).sum(axis=0)
    r = pd.Series(np.dot(np.nan_to_num(norm_cur), (np.nan_to_num(norm_others) / n)), index=[g.variant.name for g in other_genotypes], name=('r2' if r2 else 'r'))
    r.loc[(r > 1)] = 1
    r.loc[(r < (- 1))] = (- 1)
    if r2:
        return (r ** 2)
    else:
        return r

Compute LD between a marker and a list of markers.

Args:
cur_geno (Genotypes): The genotypes of the marker.
other_genotypes (list): A list of genotypes.

Returns:
numpy.array: An array containing the r or r**2 values between cur_geno
and other_genotypes.

Note:
The genotypes will automatically be normalized using (x - mean) / std.


def verify_cert(signature_chain_url: str) -> Optional[crypto.X509]:
    try:
        certs_chain_get = requests.get(signature_chain_url)
    except requests.exceptions.ConnectionError as e:
        log.error(f'Amazon signature chain get error: {e}')
        return None
    certs_chain_txt = certs_chain_get.text
    certs_chain = extract_certs(certs_chain_txt)
    amazon_cert: crypto.X509 = certs_chain.pop(0)
    sc_url_verification = verify_sc_url(signature_chain_url)
    if (not sc_url_verification):
        log.error(f'Amazon signature url {signature_chain_url} was not verified')
    expired_verification = (not amazon_cert.has_expired())
    if (not expired_verification):
        log.error(f'Amazon certificate ({signature_chain_url}) expired')
    sans_verification = verify_sans(amazon_cert)
    if (not sans_verification):
        log.error(f'Subject alternative names verification for ({signature_chain_url}) certificate failed')
    chain_verification = verify_certs_chain(certs_chain, amazon_cert)
    if (not chain_verification):
        log.error(f'Certificates chain verification for ({signature_chain_url}) certificate failed')
    result = (sc_url_verification and expired_verification and sans_verification and chain_verification)
    return (amazon_cert if result else None)

Conducts series of Alexa SSL certificate verifications against Amazon Alexa requirements.

Args:
signature_chain_url: Signature certificate URL from SignatureCertChainUrl HTTP header.
Returns:
result: Amazon certificate if verification was successful, None if not.


def start_at(self, document_fields):
    return self._cursor_helper(document_fields, before=True, start=True)

Start query results at a particular document value.

The result set will **include** the document specified by
``document_fields``.

If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_after` -- this will
overwrite it.

When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.

Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.

Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.


def _convert_as_saved_model(self):
    temp_dir = tempfile.mkdtemp()
    try:
        graph_def, input_tensors, _ = self._convert_concrete_functions_to_saved_model(temp_dir)
        if self.saved_model_dir:
            self._validate_inputs(graph_def, input_tensors)
            return self._convert_from_saved_model(graph_def)
    finally:
        shutil.rmtree(temp_dir, True)
    return None

Converts the given concrete functions as a saved model format.

Returns:
The converted data in serialized format.


def get_resource(self, uri: str) -> Optional[message.Message]:
    for package in self.packages:
        resource = package.get_resource(uri)
        if resource is not None:
            return resource
    return None

Retrieves a protocol buffer representation of the given resource.

Searches the packages added to the package manger for the resource with the
given URI. If multiple packages contain the same resource, the package
consulted will be non-deterministic.

Args:
uri: The URI of the resource to retrieve.

Returns:
Protocol buffer for the resource or `None` if the `uri` can not be found.


def _IncrementalUpdateFromMap(self, cache, new_map):
    error_count = 0
    if len(new_map) == 0:
        self.log.info('Empty map on incremental update, skipping')
        return 0
    self.log.debug('loading cache map, may be slow for large maps.')
    cache_map = cache.GetMap()
    if len(cache_map) == 0:
        raise error.EmptyMap
    if cache_map.Merge(new_map):
        error_count += cache.WriteMap(map_data=cache_map)
        if error_count == 0:
            self.WriteModifyTimestamp(new_map.GetModifyTimestamp())
    else:
        self.WriteModifyTimestamp(new_map.GetModifyTimestamp())
        self.log.info('Nothing new merged, returning')
    if error_count == 0:
        self.WriteUpdateTimestamp()
    return error_count

Merge a given map into the provided cache.

Args:
cache: A nss_cache.caches.Cache object.
new_map: A nss_cache.maps.Map object.

Returns:
An int indicating the success of an update (0 == good, fail otherwise).

Raises:
EmptyMap: We're trying to merge into cache with an emtpy map.


def divide_no_nan(x1, x2):
    if any_symbolic_tensors((x1, x2)):
        return DivideNoNan().symbolic_call(x1, x2)
    return backend.numpy.divide_no_nan(x1, x2)

Safe element-wise division which returns 0 where the denominator is 0.

Args:
x1: First input tensor.
x2: Second input tensor.

Returns:
The quotient `x1/x2`, element-wise, with zero where x2 is zero.


def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'):

    h, w = dst_img.shape[:2]
    return imresize(img, (w, h), return_scale, interpolation)

Resize image to the same size of a given image.

Args:
img (ndarray): The input image.
dst_img (ndarray): The target image.
return_scale (bool): Whether to return `w_scale` and `h_scale`.
interpolation (str): Same as :func:`resize`.

Returns:
tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or
`resized_img`.


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):

        super(ApplicationSpecificInformation, self).read(
            istream,
            kmip_version=kmip_version
        )
        tstream = BytearrayStream(istream.read(self.length))

        self.application_namespace.read(tstream, kmip_version=kmip_version)
        self.application_data.read(tstream, kmip_version=kmip_version)

        self.is_oversized(tstream)
        self.validate()

Read the data encoding the ApplicationSpecificInformation object and
decode it into its constituent parts.

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


def serialize_to_list(self, name, datas):

        items = datas.get('items', None)
        splitter = datas.get('splitter', self._DEFAULT_SPLITTER)

        if items is None:
            msg = ("List reference '{}' lacks of required 'items' variable "
                   "or is empty")
            raise SerializerError(msg.format(name))
        else:
            items = self.value_splitter(name, 'items', items, mode=splitter)

        return items

Serialize given datas to a list structure.

List structure is very simple and only require a variable ``--items``
which is a string of values separated with an empty space. Every other
properties are ignored.

Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.

Returns:
list: List of serialized reference datas.


def streaming_callback(self, body_part):
    b64_body_string = base64.b64encode(body_part).decode('utf-8')
    response = {'message_id': self._message_id, 'data': b64_body_string}
    if (self._last_response is None):
        response.update(self._generate_metadata_body())
    else:
        self._last_response['done'] = False
        self._write_message_func(self._last_response)
    self._last_response = response

Handles a streaming chunk of the response.

The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chunk is emitted. The
done() method is expected to be called after the response completes to
ensure that the last piece of data is sent.

Args:
body_part: A chunk of the streaming response.


def read_config_(self, cfile):
    if (not cfile.exists()):
        return {}
    try:
        conf_dict = toml.load(str(cfile))
    except toml.TomlDecodeError:
        return None
    self.update_(conf_dict)
    return conf_dict

Read a config file and set config values accordingly.

Returns:
dict: content of config file.


def log_uuid(self, uuid):

        if uuid not in self.uuids and uuid in uuids:
            self.uuids[uuid] = uuids[uuid].describe()

Logs the object with the specified `uuid` to `self.uuids` if
possible.

Args:
uuid (str): string value of :meth:`uuid.uuid4` value for the
object.


def _AddVolume(self, volume):
    if (volume.identifier in self._volumes):
        raise KeyError('Volume object already set for volume identifier: {0:s}'.format(volume.identifier))
    self._volumes[volume.identifier] = volume
    self._volume_identifiers.append(volume.identifier)

Adds a volume.

Args:
volume (Volume): a volume.

Raises:
KeyError: if volume is already set for the corresponding volume
identifier.


def pybel_to_json(molecule, name=None):

    atoms = [{'element': table.GetSymbol(atom.atomicnum),
              'location': list(atom.coords)}
             for atom in molecule.atoms]

    for json_atom, pybel_atom in zip(atoms, molecule.atoms):
        if pybel_atom.partialcharge != 0:
            json_atom['charge'] = pybel_atom.partialcharge
        if pybel_atom.OBAtom.HasData('_atom_site_label'):
            obatom = pybel_atom.OBAtom
            json_atom['label'] = obatom.GetData('_atom_site_label').GetValue()
        if pybel_atom.OBAtom.HasData('color'):
            obatom = pybel_atom.OBAtom
            json_atom['color'] = obatom.GetData('color').GetValue()

    bonds = [{'atoms': [b.GetBeginAtom().GetIndex(),
                        b.GetEndAtom().GetIndex()],
              'order': b.GetBondOrder()}
             for b in ob.OBMolBondIter(molecule.OBMol)]
    output = {'atoms': atoms, 'bonds': bonds, 'units': {}}

    if hasattr(molecule, 'unitcell'):
        uc = molecule.unitcell
        output['unitcell'] = [[v.GetX(), v.GetY(), v.GetZ()]
                              for v in uc.GetCellVectors()]
        density = (sum(atom.atomicmass for atom in molecule.atoms) /
                   (uc.GetCellVolume() * 0.6022))
        output['density'] = density
        output['units']['density'] = 'kg / L'

    element_count = Counter(table.GetSymbol(a.atomicnum) for a in molecule)
    hill_count = []
    for element in ['C', 'H']:
        if element in element_count:
            hill_count += [(element, element_count[element])]
            del element_count[element]
    hill_count += sorted(element_count.items())

    div = (reduce(gcd, (c[1] for c in hill_count))
           if hasattr(molecule, 'unitcell') else 1)

    output['formula'] = ''.join(n if c / div == 1 else '%s%d' % (n, c / div)
                                for n, c in hill_count)
    output['molecular_weight'] = molecule.molwt / div
    output['units']['molecular_weight'] = 'g / mol'

    if name:
        output['name'] = name

    return output

Converts a pybel molecule to json.

Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data


def copy_rec(source, dest):
    if os.path.isdir(source):
        for child in os.listdir(source):
            new_dest = os.path.join(dest, child)
            os.makedirs(new_dest, exist_ok=True)
            copy_rec(os.path.join(source, child), new_dest)
    elif os.path.isfile(source):
        logging.info(' Copy "{}" to "{}"'.format(source, dest))
        shutil.copy(source, dest)
    else:
        logging.info(' Ignoring "{}"'.format(source))

Copy files between diferent directories.

Copy one or more files to an existing directory. This function is
recursive, if the source is a directory, all its subdirectories are created
in the destination. Existing files in destination are overwrited without
any warning.

Args:
source (str): File or directory name.
dest (str): Directory name.

Raises:
FileNotFoundError: Destination directory doesn't exist.


def dump(destination, xs, model=None, properties=False, indent=True, **kwargs):

    text = dumps(
        xs, model=model, properties=properties, indent=indent, **kwargs
    )
    if hasattr(destination, 'write'):
        print(text, file=destination)
    else:
        with open(destination, 'w') as fh:
            print(text, file=fh)

Serialize Xmrs (or subclass) objects to PENMAN and write to a file.

Args:
destination: filename or file object
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` or `None`,
don't indent; if a non-negative integer N, indent N spaces
per level


def create_graph_debug_info_def(func_named_operations):
    builder = tf_stack.GraphDebugInfoBuilder()
    for func_name, op in func_named_operations:
        if op.traceback is None:
            continue
        builder.AccumulateStackTrace(func_name, op.name, _compute_useful_frames(op.traceback, 10))
    return builder.Build()

Construct and returns a `GraphDebugInfo` protocol buffer.

Args:
func_named_operations: An iterable of (func_name, op.Operation) tuples
where the Operation instances have a _traceback members. The func_name
should be the empty string for operations in the top-level Graph.

Returns:
GraphDebugInfo protocol buffer.

Raises:
TypeError: If the arguments are not of the correct proto buffer type.


def heightmap_lerp_hm(hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float) -> None:
    lib.TCOD_heightmap_lerp_hm(_heightmap_cdata(hm1), _heightmap_cdata(hm2), _heightmap_cdata(hm3), coef)

Perform linear interpolation between two heightmaps storing the result
in ``hm3``.

This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef``

Args:
hm1 (numpy.ndarray): The first heightmap.
hm2 (numpy.ndarray): The second heightmap to add to the first.
hm3 (numpy.ndarray): A destination heightmap to store the result.
coef (float): The linear interpolation coefficient.


def get_pending_users_queryset(self, search_keyword, customer_uuid):
    queryset = PendingEnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid)
    if (search_keyword is not None):
        queryset = queryset.filter(user_email__icontains=search_keyword)
    return queryset

Get the list of PendingEnterpriseCustomerUsers we want to render.

Args:
search_keyword (str): The keyword to search for in pending users' email addresses.
customer_uuid (str): A unique identifier to filter down to only pending users
linked to a particular EnterpriseCustomer.


def get_show_name(self):
    div = self.soup.find('div', attrs={'data-hover': True})
    data = json.loads(div['data-hover'])
    show_name = data.get('title')
    return show_name

Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.

Returns:
str: Video show name.


def length_from_embedding(emb):

  return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32)

Compute the length of each sequence in the batch.

Args:
emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth].
Returns:
a Tensor with shape [batch].


def create_host_call(model_dir):

  graph = tf.get_default_graph()
  summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
  gs_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1])
  summary_kwargs = collections.OrderedDict()
  for t in summaries:

    if t.op.type not in ["ScalarSummary"]:
      tf.logging.warn("Ignoring unsupported tf.Summary type %s" % t.op.type)
      continue

    name = t.op.name
    tensor = t.op.inputs[1]
    if t.op.type == "ScalarSummary":
      assert tensor.shape.is_compatible_with([])
      if tensor.dtype == tf.int64:
        tensor = tf.to_int32(tensor)
      summary_kwargs["ScalarSummary" + name] = tf.reshape(tensor, [1])
    elif t.op.type == "ImageSummary":

      if tensor.dtype != tf.float32:
        tf.logging.warn(
            "Currently T2T on TPU only supports ImageSummary of "
            "tf.float32-type Tensors. Skipping Tensor "
            "%s with dtype %s..." % (tensor.name, tensor.dtype))
        continue

      summary_kwargs["ImageSummary" + name] = tensor

  if not summary_kwargs:
    return None
  summary_kwargs["global_step"] = gs_t
  log_info("summary_kwargs %s" % str(summary_kwargs))

  def host_call_fn(**kwargs):

    gs = tf.to_int64(kwargs.pop("global_step")[0])
    with tf.contrib.summary.create_file_writer(model_dir).as_default():
      with tf.contrib.summary.always_record_summaries():

        for name, value in sorted(six.iteritems(kwargs)):
          if name.startswith("ScalarSummary"):
            name = name[len("ScalarSummary"):]
            tf.contrib.summary.scalar(
                name, tf.reduce_mean(tf.to_float(value)), step=gs)
          elif name.startswith("ImageSummary"):
            name = name[len("ImageSummary"):]
            tf.contrib.summary.image(name, value, step=gs)

        return tf.contrib.summary.all_summary_ops()

  return (host_call_fn, summary_kwargs)

Construct a host_call writing scalar summaries.

Args:
model_dir: String containing path to train

Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.


def renderJsonReadsSince(self, timestamp, meter):
    result = ''
    try:
        connection = sqlite3.connect(self.m_connection_string)
        connection.row_factory = self.dict_factory
        select_cursor = connection.cursor()
        select_cursor.execute((((((((('select * from Meter_Reads where ' + Field.Time_Stamp) + ' > ') + str(timestamp)) + ' and ') + Field.Meter_Address) + "= '") + meter) + "';"))
        reads = select_cursor.fetchall()
        result = json.dumps(reads, indent=4)
    except:
        ekm_log(traceback.format_exc(sys.exc_info()))
    return result

Simple since Time_Stamp query returned as JSON records.

Args:
timestamp (int): Epoch time in seconds.
meter (str): 12 character meter address to query

Returns:
str: JSON rendered read records.


def text(message: Text, default: Text='', validate: Union[(Type[Validator], Callable[([Text], bool)], None)]=None, qmark: Text=DEFAULT_QUESTION_PREFIX, style: Optional[Style]=None, **kwargs: Any) -> Question:
    merged_style = merge_styles([DEFAULT_STYLE, style])
    validator = build_validator(validate)

    def get_prompt_tokens():
        return [('class:qmark', qmark), ('class:question', ' {} '.format(message))]
    p = PromptSession(get_prompt_tokens, style=merged_style, validator=validator, **kwargs)
    p.default_buffer.reset(Document(default))
    return Question(p.app)

Prompt the user to enter a free text message.

This question type can be used to prompt the user for some text input.

Args:
message: Question text

default: Default value will be returned if the user just hits
enter.

validate: Require the entered value to pass a validation. The
value can not be submited until the validator accepts
it (e.g. to check minimum password length).

This can either be a function accepting the input and
returning a boolean, or an class reference to a
subclass of the prompt toolkit Validator class.

qmark: Question prefix displayed in front of the question.
By default this is a `?`

style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.

Returns:
Question: Question instance, ready to be prompted (using `.ask()`).


def _on_disconnected(self, device):

        self._logger.debug("Device disconnected event: {}".format(device))

        if self.streaming:
            self.device.close_streaming_interface()
            self.streaming = False

        if self.tracing:
            self.device.close_tracing_interface()
            self.tracing = False

        self.device.connected = False
        self.connected = False
        self._connection_handle = 0
        self.header_notif = False
        self.payload = False

        self._clear_reports()
        self._clear_traces()

        self._defer(self.set_advertising, [True])
        self._audit('ClientDisconnected')

Callback function called when a disconnected event has been received.
This resets any open interfaces on the virtual device and clears any
in progress traces and streams.
It is executed in the baBLE working thread: should not be blocking.

Args:
device (dict): Information about the newly connected device


def islink(self, path=None, header=None):
    if (header is None):
        header = self._head(self.get_client_kwargs(path))
    for key in ('x-oss-object-type', 'type'):
        try:
            return (header.pop(key) == 'Symlink')
        except KeyError:
            continue
    return False

Returns True if object is a symbolic link.

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

Returns:
bool: True if object is Symlink.


def register_resource(handle, create_op, is_initialized_op, is_shared=True):
    resource = _Resource(handle, create_op, is_initialized_op)
    if is_shared:
        ops.add_to_collection(ops.GraphKeys.RESOURCES, resource)
    else:
        ops.add_to_collection(ops.GraphKeys.LOCAL_RESOURCES, resource)

Registers a resource into the appropriate collections.

This makes the resource findable in either the shared or local resources
collection.

Args:
handle: op which returns a handle for the resource.
create_op: op which initializes the resource.
is_initialized_op: op which returns a scalar boolean tensor of whether
the resource has been initialized.
is_shared: if True, the resource gets added to the shared resource
collection; otherwise it gets added to the local resource collection.


def calcPF(pf):

        pf_y = pf[:1]
        pf_x = pf[1:]
        result = 100
        if pf_y == CosTheta.CapacitiveLead:
            result = 200 - int(pf_x)
        elif pf_y == CosTheta.InductiveLag:
            result = int(pf_x)

        return result

Simple wrap to calc legacy PF value

Args:
pf: meter power factor reading

Returns:
int: legacy push pf


def AddConnectedPeer(self, peer):
    self.RemoveFromQueue(peer.address)
    self.AddKnownAddress(peer.address)
    if (len(self.Peers) > settings.CONNECTED_PEER_MAX):
        peer.Disconnect('Max connected peers reached', isDead=False)
    if (peer not in self.Peers):
        self.Peers.append(peer)
    else:
        self.RemoveKnownAddress(peer.address)
        peer.Disconnect()

Add a new connect peer to the known peers list.

Args:
peer (NeoNode): instance.


def destroy(self, prefix_names=None):
    if (prefix_names is None):
        self.destroy(prefix_names=self.prefixes.keys())
        return
    for prefix_name in prefix_names:
        if ((prefix_name == 'current') and (self.current in prefix_names)):
            continue
        elif (prefix_name == 'current'):
            prefix_name = self.current
        self.get_prefix(prefix_name).destroy()
        self.prefixes.pop(prefix_name)
        if self.prefixes:
            self._update_current()
    if (not self.prefixes):
        shutil.rmtree(self.path)

Destroy all the given prefixes and remove any left files if no more
prefixes are left

Args:
prefix_names(list of str): list of prefix names to destroy, if None
passed (default) will destroy all of them


def list_media_endpoint_keys(access_token, subscription_id, rgname, msname):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', rgname,
                        '/providers/microsoft.media/',
                        '/mediaservices/', msname,
                        '/listKeys?api-version=', MEDIA_API])
    return do_get(endpoint, access_token)

list the media endpoint keys in a media service

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
msname (str): Media service name.

Returns:
HTTP response. JSON body.


def GetTestConfigs():
    test_configs = [('NHWC', False), ('NHWC', True)]
    if test.is_gpu_available(cuda_only=True):
        test_configs += [('NCHW', True)]
    return test_configs

Get all the valid tests configs to run.

Returns:
all the valid test configs as tuples of data_format and use_gpu.


def max_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None):
    with tf.name_scope(scope, 'MaxPool', [inputs]):
        (kernel_h, kernel_w) = _two_element_tuple(kernel_size)
        (stride_h, stride_w) = _two_element_tuple(stride)
        return tf.nn.max_pool(inputs, ksize=[1, kernel_h, kernel_w, 1], strides=[1, stride_h, stride_w, 1], padding=padding)

Adds a Max Pooling layer.

It is assumed by the wrapper that the pooling is only done per image and not
in depth or batch.

Args:
inputs: a tensor of size [batch_size, height, width, depth].
kernel_size: a list of length 2: [kernel_height, kernel_width] of the
pooling kernel over which the op is computed. Can be an int if both
values are the same.
stride: a list of length 2: [stride_height, stride_width].
Can be an int if both strides are the same.  Note that presently
both strides must have the same value.
padding: the padding method, either 'VALID' or 'SAME'.
scope: Optional scope for name_scope.

Returns:
a tensor representing the results of the pooling operation.
Raises:
ValueError: if 'kernel_size' is not a 2-D list


def dot(self, attribute: str, sql_data_type: StandardSqlDataType, sql_alias: Optional[str]=None) -> Identifier:
    return Identifier((*self.dotted_path, attribute), sql_data_type, _sql_alias=sql_alias)

Builds an identifier for the attribute of this identifier.

For example, Identifier('a').dot('b') renders SQL like 'SELECT a.b'.

Args:
attribute: The attribute on this identifier to select.
sql_data_type: The type of the attribute being selected.
sql_alias: The alias of the identifier.

Returns:
A new identifier representing the given path.


def initial_sync(self, limit=1):

        warnings.warn("initial_sync is deprecated. Use sync instead.", DeprecationWarning)
        return self._send("GET", "/initialSync", query_params={"limit": limit})

.. warning::

Deprecated. Use sync instead.

Perform /initialSync.

Args:
limit (int): The limit= param to provide.


def _init_params(self, amplitude, length_scale, validate_args):
    dtype = util.maybe_get_common_dtype([amplitude, length_scale])
    if (amplitude is not None):
        amplitude = tf.convert_to_tensor(value=amplitude, name='amplitude', dtype=dtype)
    self._amplitude = _validate_arg_if_not_none(amplitude, tf.compat.v1.assert_positive, validate_args)
    if (length_scale is not None):
        length_scale = tf.convert_to_tensor(value=length_scale, name='length_scale', dtype=dtype)
    self._length_scale = _validate_arg_if_not_none(length_scale, tf.compat.v1.assert_positive, validate_args)
    return dtype

Shared init logic for `amplitude` and `length_scale` params.

Args:
amplitude: `Tensor` (or convertible) or `None` to convert, validate.
length_scale: `Tensor` (or convertible) or `None` to convert, validate.
validate_args: If `True`, parameters are checked for validity despite
possibly degrading runtime performance

Returns:
dtype: The common `DType` of the parameters.


def _parse_error_message(self, message):
    error_code_mapping = {'Failed to functionalize Control Flow V1 ops. Consider using Control Flow V2 ops instead. See https:
    for pattern, error_code in error_code_mapping.items():
        if pattern in message:
            error_data = converter_error_data_pb2.ConverterErrorData()
            error_data.error_message = message
            error_data.error_code = error_code
            self.append_error(error_data)
            return

If the message matches a pattern, assigns the associated error code.

It is difficult to assign an error code to some errrors in MLIR side, Ex:
errors thrown by other components than TFLite or not using mlir::emitError.
This function try to detect them by the error message and assign the
corresponding error code.

Args:
message: The error message of this exception.


def __init__(self, strategy):
    if not getattr(self, '_has_initialized', False):
        if not hasattr(strategy, '_is_parameter_server_strategy_v2'):
            raise ValueError('Only `tf.distribute.experimental.ParameterServerStrategy` is supported to work with `tf.distribute.experimental.coordinator.ClusterCoordinator` currently.')
        self._strategy = strategy
        self.strategy.extended._used_with_coordinator = True
        self._cluster = Cluster(strategy)
        self._has_initialized = True

Initialization of a `ClusterCoordinator` instance.

Args:
strategy: a supported `tf.distribute.Strategy` object. Currently, only
`tf.distribute.experimental.ParameterServerStrategy` is supported.

Raises:
ValueError: if the strategy being used is not supported.


def get_program(self, label: str) -> moderngl.Program:

        return self._project.get_program(label)

Get a program by its label

Args:
label (str): The label for the program

Returns: py:class:`moderngl.Program` instance


def temp_copy_extracted_submission(self):
    tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy')
    shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir), tmp_copy_dir])
    return tmp_copy_dir

Creates a temporary copy of extracted submission.

When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary copy
of submission is deleted.

Returns:
directory where temporary copy is located


def diff_cleanupMerge(self, diffs):

    diffs.append((self.DIFF_EQUAL, ''))
    pointer = 0
    count_delete = 0
    count_insert = 0
    text_delete = ''
    text_insert = ''
    while pointer < len(diffs):
      if diffs[pointer][0] == self.DIFF_INSERT:
        count_insert += 1
        text_insert += diffs[pointer][1]
        pointer += 1
      elif diffs[pointer][0] == self.DIFF_DELETE:
        count_delete += 1
        text_delete += diffs[pointer][1]
        pointer += 1
      elif diffs[pointer][0] == self.DIFF_EQUAL:

        if count_delete + count_insert > 1:
          if count_delete != 0 and count_insert != 0:

            commonlength = self.diff_commonPrefix(text_insert, text_delete)
            if commonlength != 0:
              x = pointer - count_delete - count_insert - 1
              if x >= 0 and diffs[x][0] == self.DIFF_EQUAL:
                diffs[x] = (diffs[x][0], diffs[x][1] +
                            text_insert[:commonlength])
              else:
                diffs.insert(0, (self.DIFF_EQUAL, text_insert[:commonlength]))
                pointer += 1
              text_insert = text_insert[commonlength:]
              text_delete = text_delete[commonlength:]

            commonlength = self.diff_commonSuffix(text_insert, text_delete)
            if commonlength != 0:
              diffs[pointer] = (diffs[pointer][0], text_insert[-commonlength:] +
                  diffs[pointer][1])
              text_insert = text_insert[:-commonlength]
              text_delete = text_delete[:-commonlength]

          new_ops = []
          if len(text_delete) != 0:
            new_ops.append((self.DIFF_DELETE, text_delete))
          if len(text_insert) != 0:
            new_ops.append((self.DIFF_INSERT, text_insert))
          pointer -= count_delete + count_insert
          diffs[pointer : pointer + count_delete + count_insert] = new_ops
          pointer += len(new_ops) + 1
        elif pointer != 0 and diffs[pointer - 1][0] == self.DIFF_EQUAL:

          diffs[pointer - 1] = (diffs[pointer - 1][0],
                                diffs[pointer - 1][1] + diffs[pointer][1])
          del diffs[pointer]
        else:
          pointer += 1

        count_insert = 0
        count_delete = 0
        text_delete = ''
        text_insert = ''

    if diffs[-1][1] == '':
      diffs.pop()

    changes = False
    pointer = 1

    while pointer < len(diffs) - 1:
      if (diffs[pointer - 1][0] == self.DIFF_EQUAL and
          diffs[pointer + 1][0] == self.DIFF_EQUAL):

        if diffs[pointer][1].endswith(diffs[pointer - 1][1]):

          if diffs[pointer - 1][1] != "":
            diffs[pointer] = (diffs[pointer][0],
                diffs[pointer - 1][1] +
                diffs[pointer][1][:-len(diffs[pointer - 1][1])])
            diffs[pointer + 1] = (diffs[pointer + 1][0],
                                  diffs[pointer - 1][1] + diffs[pointer + 1][1])
          del diffs[pointer - 1]
          changes = True
        elif diffs[pointer][1].startswith(diffs[pointer + 1][1]):

          diffs[pointer - 1] = (diffs[pointer - 1][0],
                                diffs[pointer - 1][1] + diffs[pointer + 1][1])
          diffs[pointer] = (diffs[pointer][0],
              diffs[pointer][1][len(diffs[pointer + 1][1]):] +
              diffs[pointer + 1][1])
          del diffs[pointer + 1]
          changes = True
      pointer += 1

    if changes:
      self.diff_cleanupMerge(diffs)

Reorder and merge like edit sections.  Merge equalities.
Any edit section can move as long as it doesn't cross an equality.

Args:
diffs: Array of diff tuples.


def forward(self, feature_representation):
    self.extend_pos_enc(feature_representation)
    hidden_states = feature_representation * self.input_scale
    center_idx = self.pos_enc.size(1)
    pos_emb = self.pos_enc[:, center_idx - hidden_states.size(1) + 1:center_idx + hidden_states.size(1)]
    return (self.dropout(hidden_states), self.dropout(pos_emb))

Args:
feature_representation (`torch.Tensor` of shape (batch_size, time, `*`)):
Input tensor.

Returns:
`torch.Tensor`: Encoded tensor (batch_size, time, `*`).


def _add_validator(fv, validator_instance):

  for flag_name in validator_instance.get_flags_names():
    fv[flag_name].validators.append(validator_instance)

Register new flags validator to be checked.

Args:
fv: flags.FlagValues, the FlagValues instance to add the validator.
validator_instance: validators.Validator, the validator to add.
Raises:
KeyError: Raised when validators work with a non-existing flag.


def get_entries(self, criteria, inc_structure=False, optional_data=None):
    all_entries = list()
    optional_data = ([] if (not optional_data) else list(optional_data))
    optional_data.append('oxide_type')
    fields = [k for k in optional_data]
    fields.extend(['task_id', 'unit_cell_formula', 'energy', 'is_hubbard', 'hubbards', 'pseudo_potential.labels', 'pseudo_potential.functional', 'run_type', 'input.is_lasph', 'input.xc_override', 'input.potcar_spec'])
    if inc_structure:
        fields.append('output.crystal')
    for c in self.query(fields, criteria):
        func = c['pseudo_potential.functional']
        labels = c['pseudo_potential.labels']
        symbols = ['{} {}'.format(func, label) for label in labels]
        parameters = {'run_type': c['run_type'], 'is_hubbard': c['is_hubbard'], 'hubbards': c['hubbards'], 'potcar_symbols': symbols, 'is_lasph': (c.get('input.is_lasph') or False), 'potcar_spec': c.get('input.potcar_spec'), 'xc_override': c.get('input.xc_override')}
        optional_data = {k: c[k] for k in optional_data}
        if inc_structure:
            struct = Structure.from_dict(c['output.crystal'])
            entry = ComputedStructureEntry(struct, c['energy'], 0.0, parameters=parameters, data=optional_data, entry_id=c['task_id'])
        else:
            entry = ComputedEntry(Composition(c['unit_cell_formula']), c['energy'], 0.0, parameters=parameters, data=optional_data, entry_id=c['task_id'])
        all_entries.append(entry)
    return all_entries

Get ComputedEntries satisfying a particular criteria.

.. note::

The get_entries_in_system and get_entries  methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
are returned.  The dataset is very heterogeneous and not
directly comparable.  It is highly recommended that you perform
post-processing using pymatgen.entries.compatibility.

Args:
criteria:
Criteria obeying the same syntax as query.
inc_structure:
Optional parameter as to whether to include a structure with
the ComputedEntry. Defaults to False. Use with care - including
structures with a large number of entries can potentially slow
down your code to a crawl.
optional_data:
Optional data to include with the entry. This allows the data
to be access via entry.data[key].

Returns:
List of pymatgen.entries.ComputedEntries satisfying criteria.


def parse(self, request):

        assert isinstance(request, HttpRequest), "Invalid request type: %s" % type(request)

        try:

            from_email = self._get_addresses([_decode_POST_value(request, 'from')])[0]

            to_email = self._get_addresses([_decode_POST_value(request, 'to')])
            cc = self._get_addresses([_decode_POST_value(request, 'cc', default='')])
            bcc = self._get_addresses([_decode_POST_value(request, 'bcc', default='')])

            subject = _decode_POST_value(request, 'subject')
            text = _decode_POST_value(request, 'text', default='')
            html = _decode_POST_value(request, 'html', default='')

        except IndexError as ex:
            raise RequestParseError(
                "Inbound request lacks a valid from address: %s." % request.get('from')
            )

        except MultiValueDictKeyError as ex:
            raise RequestParseError("Inbound request is missing required value: %s." % ex)

        if "@" not in from_email:

            raise RequestParseError("Could not get a valid from address out of: %s." % request)

        email = EmailMultiAlternatives(
            subject=subject,
            body=text,
            from_email=from_email,
            to=to_email,
            cc=cc,
            bcc=bcc,
        )
        if html is not None and len(html) > 0:
            email.attach_alternative(html, "text/html")

        for n, f in list(request.FILES.items()):
            if f.size > self.max_file_size:
                logger.debug(
                    "File attachment %s is too large to process (%sB)",
                    f.name,
                    f.size
                )
                raise AttachmentTooLargeError(
                    email=email,
                    filename=f.name,
                    size=f.size
                )
            else:
                email.attach(f.name, f.read(), f.content_type)
        return email

Parse incoming request and return an email instance.

Args:
request: an HttpRequest object, containing the forwarded email, as
per the SendGrid specification for inbound emails.

Returns:
an EmailMultiAlternatives instance, containing the parsed contents
of the inbound email.

TODO: non-UTF8 charset handling.
TODO: handler headers.


def remove_event_handler(self, handler, event_name):
    if (event_name not in self._event_handlers):
        raise ValueError("Input event name '{}' does not exist".format(event_name))
    new_event_handlers = [(h, args, kwargs) for (h, args, kwargs) in self._event_handlers[event_name] if (h != handler)]
    if (len(new_event_handlers) == len(self._event_handlers[event_name])):
        raise ValueError("Input handler '{}' is not found among registered event handlers".format(handler))
    self._event_handlers[event_name] = new_event_handlers

Remove event handler `handler` from registered handlers of the engine

Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to.


def check_refresh(opts, refresh=None):
    return bool((salt.utils.data.is_true(refresh) or (os.path.isfile(rtag(opts)) and (refresh is not False))))

Check whether or not a refresh is necessary

Returns:

- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists


def export(self, out_file: str, layer: str = None, format: str = "tab") -> None:

		if format != "tab":
			raise NotImplementedError("Only 'tab' is supported")

		with open(out_file, "w") as f:

			for ca in self.col_attrs.keys():
				for ra in self.row_attrs.keys():
					f.write("\t")
				f.write(ca + "\t")
				for v in self.col_attrs[ca]:
					f.write(str(v) + "\t")
				f.write("\n")

			for ra in self.row_attrs.keys():
				f.write(ra + "\t")
			f.write("\t")
			for v in range(self.shape[1]):
				f.write("\t")
			f.write("\n")

			for row in range(self.shape[0]):
				for ra in self.row_attrs.keys():
					f.write(str(self.row_attrs[ra][row]) + "\t")
				f.write("\t")

				if layer is None:
					for v in self[row, :]:
						f.write(str(v) + "\t")
				else:
					for v in self.layers[layer][row, :]:
						f.write(str(v) + "\t")
				f.write("\n")

Export the specified layer and row/col attributes as tab-delimited file.

Args:
out_file:	Path to the output file
layer:	Name of the layer to export, or None to export the main matrix
format: Desired file format (only 'tab' is supported)


def abivalidate_inputs(self):
    if (not self.allocated):
        self.allocate()
    (isok, tuples) = (True, [])
    for task in self.iflat_tasks():
        t = task.input.abivalidate()
        if (t.retcode != 0):
            isok = False
        tuples.append(t)
    return (isok, tuples)

Run ABINIT in dry mode to validate all the inputs of the flow.

Return:
(isok, tuples)

isok is True if all inputs are ok.
tuples is List of `namedtuple` objects, one for each task in the flow.
Each namedtuple has the following attributes:

retcode: Return code. 0 if OK.
log_file:  log file of the Abinit run, use log_file.read() to access its content.
stderr_file: stderr file of the Abinit run. use stderr_file.read() to access its content.

Raises:
`RuntimeError` if executable is not in $PATH.


def get_coordinate_offset(self, other_reading):
    (my_x, my_y) = self.reference_source_point
    (other_x, other_y) = other_reading.reference_source_point
    return ((my_x - other_x), (my_y - other_y))

Calculates the offsets between readings' coordinate systems.

Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.

Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
coordinate systems.


async def _get(self, term: str = None, random: bool = False) -> dict:

        params = None
        if random:
            url = self.RANDOM_URL
        else:
            params = {'term': term}
            url = self.API_URL

        async with self.session.get(url, params=params) as response:
            if response.status == 200:
                response = await response.json()
            else:
                raise UrbanConnectionError(response.status)

        if not response['list']:
            raise WordNotFoundError(term)

        return response

Helper method to reduce some boilerplate with :module:`aiohttp`.

Args:
term: The term to search for. Optional if doing a random search.
random: Whether the search should return a random word.

Returns:
The JSON response from the API.

Raises:
UrbanConnectionError: If the response status isn't ``200``.
WordNotFoundError: If the response doesn't contain data (i.e. no word found).


def Reference(uri, meaning=None):
    attrib = {'uri': uri}
    if (meaning is not None):
        attrib['meaning'] = meaning
    return objectify.Element('Reference', attrib)

Represents external information, typically original obs data and metadata.

Args:
uri(str): Uniform resource identifier for external data, e.g. FITS file.
meaning(str): The nature of the document referenced, e.g. what
instrument and filter was used to create the data?


def _Execute(self, funcname, *args, **kwargs):

    wait_for_completion = kwargs.get('wait_for_completion', False)
    rpc_dict = {'func': funcname, 'args': args}
    self._Send(json.dumps(rpc_dict))
    timeout = TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT

    result_string = self._Recv(timeout)

    try:
      result = json.loads(result_string, object_hook=self._JsonDecodeDict)
      if isinstance(result, unicode):
        result = self._TryStr(result)
      elif isinstance(result, list):
        result = self._JsonDecodeList(result)
    except ValueError:
      raise ValueError('Response JSON invalid: ' + str(result_string))
    except TypeError:
      raise ValueError('Response JSON invalid: ' + str(result_string))

    return result

Send an RPC request to the gdb-internal python.

Blocks for 3 seconds by default and returns any results.
Args:
funcname: the name of the function to call.
*args: the function's arguments.
**kwargs: Only the key 'wait_for_completion' is inspected, which decides
whether to wait forever for completion or just 3 seconds.
Returns:
The result of the function call.


def __init__(self, learning_rate, num_samples=1, unroll_loop=False, scope='evolutionary', summary_labels=()):

        assert isinstance(learning_rate, float) and learning_rate > 0.0
        self.learning_rate = learning_rate

        assert isinstance(num_samples, int) and num_samples > 0
        self.num_samples = num_samples

        assert isinstance(unroll_loop, bool)
        self.unroll_loop = unroll_loop

        super(Evolutionary, self).__init__(scope=scope, summary_labels=summary_labels)

Creates a new evolutionary optimizer instance.

Args:
learning_rate: Learning rate.
num_samples: Number of sampled perturbations.


def search(self, query):

        results = self.skype.conn("GET", SkypeConnection.API_DIRECTORY,
                                  auth=SkypeConnection.Auth.SkypeToken,
                                  params={"searchstring": query, "requestId": "0"}).json().get("results", [])
        return [SkypeUser.fromRaw(self.skype, json.get("nodeProfileData", {})) for json in results]

Search the Skype Directory for a user.

Args:
query (str): name to search for

Returns:
SkypeUser list: collection of possible results


def list_function_names(self):
    self.ensure_initialized()
    return set(pywrap_tfe.TFE_ContextListFunctionNames(self._handle))

Get a list of names of registered functions.

Returns:
A set of names of all registered functions for the context.


def log_partition_function(beta, h_num):
    h_eigs, _ = np.linalg.eigh(tf.cast(h_num, tf.complex128))
    return tf.reduce_logsumexp(-tf.cast(beta, tf.float64) * tf.cast(h_eigs, tf.float64))

Computes the logarithm of the partition function.
The log partition function is ln(Tr[expm(-beta * h_num)])
Args:
beta: Scalar `tf.Tensor` of dtype `float64` which is the inverse
temperature at which to calculate the thermal state.
h_num: Square, Hermitian `tf.Tensor` of dtype `complex128` which is the
Hamiltonian appearing in the partition function.
Returns:
Scalar `tf.Tensor` of dtype `float64` which is the logarithm of the
partition function.


def _should_shutdown(self) -> bool:
    if self._is_executing():
        return False
    watermark_manager = self._executor.evaluation_context._watermark_manager
    _, any_unfired_realtime_timers = watermark_manager.extract_all_timers()
    if any_unfired_realtime_timers:
        return False
    else:
        if self._executor.evaluation_context.is_done():
            self._executor.visible_updates.offer(_ExecutorServiceParallelExecutor._VisibleExecutorUpdate())
        else:
            self._executor.visible_updates.offer(_ExecutorServiceParallelExecutor._VisibleExecutorUpdate((Exception('Monitor task detected a pipeline stall.'), None, None)))
        self._executor.executor_service.shutdown()
        return True

Checks whether the pipeline is completed and should be shut down.

If there is anything in the queue of tasks to do or
if there are any realtime timers set, do not shut down.

Otherwise, check if all the transforms' watermarks are complete.
If they are not, the pipeline is not progressing (stall detected).
Whether the pipeline has stalled or not, the executor should shut
down the pipeline.

Returns:
True only if the pipeline has reached a terminal state and should
be shut down.


def PopItem(self):
    try:
        index_key = self._index.pop(0)
    except IndexError:
        raise KeyError
    return self._data.pop(index_key)

Return a MapEntry object, throw KeyError if none exist.

Returns:
A maps.MapEntry from within maps.Map internal dict.

Raises:
KeyError if there is nothing to return


def update_mapping(self, mapping: Dict[ops.Qid, LogicalIndex],
                       keys: Sequence[ops.Qid]
                       ) -> None:

        permutation = self.permutation()
        indices = tuple(permutation.keys())
        new_keys = [keys[permutation[i]] for i in indices]
        old_elements = [mapping[keys[i]] for i in indices]
        mapping.update(zip(new_keys, old_elements))

Updates a mapping (in place) from qubits to logical indices.

Args:
mapping: The mapping to update.
keys: The qubits acted on by the gate.


def outer_horizontal_border_bottom(self):
    return u'{lm}{lv}{hz}{rv}'.format(lm=(' ' * self.margins.left), lv=self.border_style.bottom_left_corner, rv=self.border_style.bottom_right_corner, hz=self.outer_horizontals())

The complete outer bottom horizontal border section, including left and right margins.

Returns:
str: The bottom menu border.


def _list(self, dir_or_prefix):
    raise NotImplementedError

List files in a location.

Listing is non-recursive (for filesystems that support directories).

Args:
dir_or_prefix: (string) A directory or location prefix (for filesystems
that don't have directories).

Returns:
Generator of ``FileMetadata`` objects.

Raises:
``BeamIOError``: if listing fails, but not if no files were found.


def _setup_selection_range(self, f_start=None, f_stop=None, t_start=None, t_stop=None, init=False):

        if init is True:
            if t_start is None:
                t_start = self.t_begin
            if t_stop is None:
                t_stop = self.t_end
            if f_start is None:
                f_start = self.f_begin
            if f_stop is None:
                f_stop = self.f_end
        else:
            if f_start is None:
                f_start = self.f_start
            if f_stop is None:
                f_stop = self.f_stop
            if t_start is None:
                t_start = self.t_start
            if t_stop is None:
                t_stop = self.t_stop

        if t_stop >= 0 and t_start >= 0 and t_stop < t_start:
            t_stop, t_start = t_start,t_stop
            logger.warning('Given t_stop < t_start, assuming reversed values.')
        if f_stop and f_start and f_stop < f_start:
            f_stop, f_start = f_start,f_stop
            logger.warning('Given f_stop < f_start, assuming reversed values.')

        if t_start >= self.t_begin and t_start < self.t_end:
            self.t_start = int(t_start)
        else:
            if init is False or t_start != None:
                logger.warning('Setting t_start = %f, since t_start not given or not valid.'%self.t_begin)
            self.t_start = self.t_begin

        if t_stop <= self.t_end  and t_stop > self.t_begin:
            self.t_stop = int(t_stop)
        else:
            if init is False or t_stop:
                logger.warning('Setting t_stop = %f, since t_stop not given or not valid.'%self.t_end)
            self.t_stop = self.t_end

        if f_start >= self.f_begin and f_start < self.f_end:
            self.f_start = f_start
        else:
            if init is False or f_start:
                logger.warning('Setting f_start = %f, since f_start not given or not valid.'%self.f_begin)
            self.f_start = self.f_begin

        if f_stop <= self.f_end and f_stop > self.f_begin:
            self.f_stop = f_stop
        else:
            if init is False or f_stop:
                logger.warning('Setting f_stop = %f, since f_stop not given or not valid.'%self.f_end)
            self.f_stop = self.f_end

        self.selection_shape = self._calc_selection_shape()

Making sure the selection if time and frequency are within the file limits.

Args:
init (bool): If call during __init__


def batch_id(self, batch_id):

        self._request_uri = '{}/{}'.format(self._api_uri, batch_id)
        self._request_entity = 'batchStatus'

The ID of the batch job used to push data and/or retrieve status.

Args:
batch_id (integer): The id of the batch job.


async def remember_ticket(self, request, ticket):

        session = await get_session(request)
        session[self.cookie_name] = ticket

Called to store the ticket data for a request.

Ticket data is stored in the aiohttp_session object

Args:
request: aiohttp Request object.
ticket: String like object representing the ticket to be stored.


def generate_combinations_with_testcase_name(**kwargs):
    sort_by_key = lambda k: k[0]
    combinations = []
    for key, values in sorted(kwargs.items(), key=sort_by_key):
        if not isinstance(values, list):
            values = [values]
        combinations.append([(key, value) for value in values])
    combinations = [collections.OrderedDict(result) for result in itertools.product(*combinations)]
    named_combinations = []
    for combination in combinations:
        assert isinstance(combination, collections.OrderedDict)
        name = ''.join(['_{}_{}'.format(''.join(filter(str.isalnum, key)), ''.join(filter(str.isalnum, str(value)))) for key, value in combination.items()])
        named_combinations.append(collections.OrderedDict(list(combination.items()) + [('testcase_name', '_test{}'.format(name))]))
    return named_combinations

Generate combinations based on its keyword arguments using combine().

This function calls combine() and appends a testcase name to the list of
dictionaries returned. The 'testcase_name' key is a required for named
parameterized tests.

Args:
**kwargs: keyword arguments of form `option=[possibilities, ...]` or
`option=the_only_possibility`.

Returns:
a list of dictionaries for each combination. Keys in the dictionaries are
the keyword argument names.  Each key has one value - one of the
corresponding keyword argument values.


def predict_task(self, X, t=0, break_ties="random", **kwargs):

        Y_tp = self.predict_task_proba(X, t=t, **kwargs)
        Y_tph = self._break_ties(Y_tp, break_ties)
        return Y_tph

Predicts int labels for an input X on task t

Args:
X: The input for the predict_task_proba method
t: The task index to predict
Returns:
An n-dim tensor of int predictions for the specified task


def _get_parameter_signatures(self):
    declarations = []
    for p in self.get_parameters():
        new_p = p.get_renamed(p.name.replace('.', '_'))
        declarations.append(new_p.get_declaration())
    return declarations

Get the signature of the parameters for the CL function declaration.

This should return the list of signatures of the parameters for use inside the function signature.

Returns:
list: the signatures of the parameters for the use in the CL code.


def _ConvertMessage(value, message):

  message_descriptor = message.DESCRIPTOR
  full_name = message_descriptor.full_name
  if _IsWrapperMessage(message_descriptor):
    _ConvertWrapperMessage(value, message)
  elif full_name in _WKTJSONMETHODS:
    _WKTJSONMETHODS[full_name][1](value, message)
  else:
    _ConvertFieldValuePair(value, message)

Convert a JSON object into a message.

Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.

Raises:
ParseError: In case of convert problems.


def plot(self, figure_list):
    if (self._current_subscript_stage is not None):
        if (self._current_subscript_stage['current_subscript'] is not None):
            self._current_subscript_stage['current_subscript'].plot(figure_list)
    if ((self.is_running is False) and (not ((self.data == {}) or (self.data is None)))):
        script_names = list(self.settings['script_order'].keys())
        script_indices = [self.settings['script_order'][name] for name in script_names]
        (_, sorted_script_names) = list(zip(*sorted(zip(script_indices, script_names))))
        last_script = self.scripts[sorted_script_names[(- 1)]]
        last_script.force_update()
        axes_list = last_script.get_axes_layout(figure_list)
        try:
            last_script._plot(axes_list, self.data)
        except TypeError as err:
            print(warnings.warn("can't plot average script data because script.plot function doens't take data as optional argument. Plotting last data set instead"))
            print(err.message)
            last_script.plot(figure_list)

When each subscript is called, uses its standard plotting

Args:
figure_list: list of figures passed from the guit


def inspect_task(self, task):
    url = self._url('/tasks/{0}', task)
    return self._result(self._get(url), True)

Retrieve information about a task.

Args:
task (str): Task ID

Returns:
(dict): Information about the task.

Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.


def _FillEventSourceHeap(self, storage_writer, event_source_heap, start_with_first=False):
    if self._processing_profiler:
        self._processing_profiler.StartTiming('fill_event_source_heap')
    if self._processing_profiler:
        self._processing_profiler.StartTiming('get_event_source')
    if start_with_first:
        event_source = storage_writer.GetFirstWrittenEventSource()
    else:
        event_source = storage_writer.GetNextWrittenEventSource()
    if self._processing_profiler:
        self._processing_profiler.StopTiming('get_event_source')
    while event_source:
        event_source_heap.PushEventSource(event_source)
        if event_source_heap.IsFull():
            break
        if self._processing_profiler:
            self._processing_profiler.StartTiming('get_event_source')
        event_source = storage_writer.GetNextWrittenEventSource()
        if self._processing_profiler:
            self._processing_profiler.StopTiming('get_event_source')
    if self._processing_profiler:
        self._processing_profiler.StopTiming('fill_event_source_heap')

Fills the event source heap with the available written event sources.

Args:
storage_writer (StorageWriter): storage writer for a session storage.
event_source_heap (_EventSourceHeap): event source heap.
start_with_first (Optional[bool]): True if the function should start
with the first written event source.


def save(self, out_path):
    out = {'selectors': [str(x) for x in self.selectors], 'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]}
    with open(out_path, 'wb') as outfile:
        json.dump(out, outfile, indent=4)

Save an ascii representation of this simulation trace.

Args:
out_path (str): The output path to save this simulation trace.


def _remove_tree(self, tree, parent=None):
    for sub_tree in tree.sub_trees:
        self._remove_tree(sub_tree, parent=tree)
    for index in tree.indexes:
        if (not getattr(tree, index)):
            continue
        self._remove_from(getattr(self, (index + '_db')), getattr(tree, index), tree)
    if parent:
        self._remove_from(self.parent_db, tree.path, parent)
    self.zeo.pack()

Really remove the tree identified by `tree` instance from all indexes
from database.

Args:
tree (obj): :class:`.Tree` instance.
parent (obj, default None): Reference to parent.


def calc_track_errors(model_tracks, obs_tracks, track_pairings):

        columns = ['obs_track_id',
                   'translation_error_x',
                   'translation_error_y',
                   'start_time_difference',
                   'end_time_difference',
                   ]
        track_errors = pd.DataFrame(index=list(range(len(model_tracks))),
                                    columns=columns)
        for p, pair in enumerate(track_pairings):
            model_track = model_tracks[pair[0]]
            if type(pair[1]) in [int, np.int64]:
                obs_track = obs_tracks[pair[1]]
            else:
                obs_track = obs_tracks[pair[1][0]]
            model_com = model_track.center_of_mass(model_track.start_time)
            obs_com = obs_track.center_of_mass(obs_track.start_time)
            track_errors.loc[pair[0], 'obs_track_id'] = pair[1] if type(pair[1]) in [int, np.int64] else pair[1][0]
            track_errors.loc[pair[0], 'translation_error_x'] = model_com[0] - obs_com[0]
            track_errors.loc[pair[0], 'translation_error_y'] = model_com[1] - obs_com[1]
            track_errors.loc[pair[0], 'start_time_difference'] = model_track.start_time - obs_track.start_time
            track_errors.loc[pair[0], 'end_time_difference'] = model_track.end_time - obs_track.end_time
        return track_errors

Calculates spatial and temporal translation errors between matched
forecast and observed tracks.

Args:
model_tracks: List of model track STObjects
obs_tracks: List of observed track STObjects
track_pairings: List of tuples pairing forecast and observed tracks.

Returns:
pandas DataFrame containing different track errors


def _check_module(folder):

        if not folder.exists():
            folder.mkdir(parents=True, exist_ok=True, mode=0o755)
            (folder / '__init__.py').touch()

Create module folder with empty __init__.py if it doesn't exist.

Args:
folder (pathlib.Path): Module path.


def uniform(key, shape, dtype=tf_np.random.DEFAULT_RANDN_DTYPE, minval=0.0, maxval=1.0):
    minval = math_ops.cast(minval, dtype)
    maxval = math_ops.cast(maxval, dtype)
    key = tf_np.asarray(key, dtype=_RNG_KEY_DTYPE)
    return tf_np.asarray(stateless_random_ops.stateless_random_uniform(shape, seed=_key2seed(key), dtype=dtype, minval=minval, maxval=maxval))

Sample uniform random values in range [`minval`, `maxval`).

Args:
key: the RNG key.
shape: the shape of the result.
dtype: the dtype of the result.
minval: the minimal value (inclusive).
maxval: the maximal value (exclusive).

Returns:
An ndarray with shape `shape` and dtype `dtype`. Each value in the ndarray
is sampled uniformly randomly in range [`minval`, `maxval`).


def move_temp_file(src, dest):
    try:
        move_file(src, dest)
    except Exception:
        try:
            os.remove(src)
        except Exception as ex_clean:
            logger.error(f'error removing temp file {src}. {ex_clean}')
        raise

Move src to dest. Delete src if something goes wrong.

Overwrites dest.

Args:
src: str or path-like. source file
dest: str or path-like. destination file

Returns:
None.

Raises:
FileNotFoundError: out path parent doesn't exist.
OSError: if any IO operations go wrong. Does its best to clean up after
itself and remove temp files.


def create_repository(cls, repository_data):

        location = "memory{%s}" % hex(id(repository_data))
        resource_pool = ResourcePool(cache_size=None)
        repo = MemoryPackageRepository(location, resource_pool)
        repo.data = repository_data
        return repo

Create a standalone, in-memory repository.

Using this function bypasses the `package_repository_manager` singleton.
This is usually desired however, since in-memory repositories are for
temporarily storing programmatically created packages, which we do not
want to cache and that do not persist.

Args:
repository_data (dict): Repository data, see class docstring.

Returns:
`MemoryPackageRepository` object.


def draw_wires(wires, vertically_compressed=True):

        lines = []
        bot_line = None
        for wire in wires:

            top_line = ''
            for instruction in wire:
                top_line += instruction.top

            if bot_line is None:
                lines.append(top_line)
            else:
                if vertically_compressed:
                    lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
                else:
                    lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot"))

            mid_line = ''
            for instruction in wire:
                mid_line += instruction.mid
            lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))

            bot_line = ''
            for instruction in wire:
                bot_line += instruction.bot
            lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))

        return lines

Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
so the drawing will take less vertical room.
Returns:
list: A list of lines with the text drawing.


def setEditable(self, editable):
    if (not isinstance(editable, bool)):
        raise TypeError('Argument is not of type bool')
    self._editable = editable

setter to _editable. apply changes while changing dtype.

Raises:
TypeError: if editable is not of type bool.

Args:
editable (bool): apply changes while changing dtype.


def validate(cls, mapper_spec):
    if (mapper_spec.output_writer_class() != cls):
        raise errors.BadWriterParamsError('Output writer class mismatch')
    params = output_writers._get_params(mapper_spec)
    if (cls.BUCKET_NAME_PARAM not in params):
        raise errors.BadWriterParamsError(('%s is required for the _HashingGCSOutputWriter' % cls.BUCKET_NAME_PARAM))

Validates mapper specification.

Args:
mapper_spec: an instance of model.MapperSpec to validate.
Raises:
BadWriterParamsError: when Output writer class mismatch.


def run_display_app_output(self, out):

        if not self.profile.get('quiet') and not self.args.quiet:
            print('App Output:')
            for o in out.decode('utf-8').split('\n'):
                print('  {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, o))
                self.log.debug('[tcrun] App output: {}'.format(o))

Print any App output.

Args:
out (str): One or more lines of output messages.


def shuffle(x, axis=0, seed=None):
    return backend.random.shuffle(x, axis=axis, seed=seed)

Shuffle the elements of a tensor uniformly at random along an axis.

Args:
x: The tensor to be shuffled.
axis: An integer specifying the axis along which to shuffle. Defaults to
`0`.
seed: Optional Python integer or instance of
`keras.random.SeedGenerator`.
By default, the `seed` argument is `None`, and an internal global
`keras.random.SeedGenerator` is used. The `seed` argument can be
used to ensure deterministic (repeatable) random number generation.
Note that passing an integer as the `seed` value will produce the
same random values for each call. To generate different random
values for repeated calls, an instance of
`keras.random.SeedGenerator` must be provided as the `seed` value.
Remark concerning the JAX backend: When tracing functions with the
JAX backend the global `keras.random.SeedGenerator` is not
supported. Therefore, during tracing the default value seed=None
will produce an error, and a `seed` argument must be provided.


def retrieve(self, txid, headers=None):
    path = (self.path + txid)
    return self.transport.forward_request(method='GET', path=path, headers=None)

Retrieves the transaction with the given id.

Args:
txid (str): Id of the transaction to retrieve.
headers (dict): Optional headers to pass to the request.

Returns:
dict: The transaction with the given id.


def recursion_error(self, repeated_parser: str):

        if self.finished:
            return 'Infinite recursion detected in {}; empty string was matched and will be matched forever at ' \
                   'end of source'.format(repeated_parser)
        else:
            return 'Infinite recursion detected in {}; empty string was matched and will be matched forever at ' \
                   'index {} before {}'.format(repeated_parser, self.position, self.next_token())

Generate an error to indicate that infinite recursion was encountered.

A parser can supply a representation of itself to this method and the
reader will supply the context, including the location where the
parser stalled.

Args:
repeated_parser: A representation of the repeated parser

Returns:
A full error message


def shot_noise(x, severity=1):
    c = [60, 25, 12, 5, 3][(severity - 1)]
    x = (np.array(x) / 255.0)
    x_clip = (np.clip((np.random.poisson((x * c)) / float(c)), 0, 1) * 255)
    return around_and_astype(x_clip)

Shot noise corruption to images.

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

Returns:
numpy array, image with uint8 pixels in [0,255]. Added shot noise.


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 get_state_variable_from_name(self, variable_name):

        return next((v for v in self.state_variables if v.name == variable_name), None)

Return a state variable from a name
Args:
varible_name (str): name of the variable
Returns:
StateVariable