def stop_site(name):

    ps_cmd = ['Stop-WebSite', r"'{0}'".format(name)]

    cmd_ret = _srvmgr(ps_cmd)

    return cmd_ret['retcode'] == 0

Stop a Web Site in IIS.

.. versionadded:: 2017.7.0

Args:
name (str): The name of the website to stop.

Returns:
bool: True if successful, otherwise False

CLI Example:

.. code-block:: bash

salt '*' win_iis.stop_site name='My Test Site'


def logsumexp(x, axis=None, keepdims=False):
    return math_ops.reduce_logsumexp(x, axis, keepdims)

Computes log(sum(exp(elements across dimensions of a tensor))).

This function is more numerically stable than log(sum(exp(x))).
It avoids overflows caused by taking the exp of large inputs and
underflows caused by taking the log of small inputs.

Args:
x: A tensor or variable.
axis: An integer, the axis to reduce over.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`, the reduced dimension is
retained with length 1.

Returns:
The reduced tensor.


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

Corresponds to IDD Field `ws025`
Wind speed corresponding to 2.5% annual cumulative frequency of occurrence

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

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


def state_invariant_scope(self, state: Sequence[tf.Tensor]):
    scope = {}
    scope.update(self.non_fluents_scope())
    scope.update(self.state_scope(state))
    return scope

Returns the state invariant fluent scope for the current `state`.

Args:
state (Sequence[tf.Tensor]): The current state fluents.

Returns:
A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`.


def _CreateRoutePatternsFolder(self, parent, route, style_id=None, visible=True):
    pattern_id_to_trips = route.GetPatternIdTripDict()
    if (not pattern_id_to_trips):
        return None
    pattern_trips = pattern_id_to_trips.values()
    pattern_trips.sort((lambda a, b: cmp(len(b), len(a))))
    folder = self._CreateFolder(parent, 'Patterns', visible)
    for (n, trips) in enumerate(pattern_trips):
        trip_ids = [trip.trip_id for trip in trips]
        name = ('Pattern %d (trips: %d)' % ((n + 1), len(trips)))
        description = ('Trips using this pattern (%d in total): %s' % (len(trips), ', '.join(trip_ids)))
        placemark = self._CreatePlacemark(folder, name, style_id, visible, description)
        coordinates = [(stop.stop_lon, stop.stop_lat) for stop in trips[0].GetPattern()]
        self._CreateLineString(placemark, coordinates)
    return folder

Create a KML Folder containing placemarks for each pattern in the route.

A pattern is a sequence of stops used by one of the trips in the route.

If there are not patterns for the route then no folder is created and None
is returned.

Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the folder is initially visible or not.

Returns:
The Folder ElementTree.Element instance or None if there are no patterns.


def init_from_acceptor(self, acceptor):

        self.states = copy.deepcopy(acceptor.states)
        self.alphabet = copy.deepcopy(acceptor.alphabet)
        self.osyms = copy.deepcopy(acceptor.osyms)
        self.isyms = copy.deepcopy(acceptor.isyms)

Adds a sink state
Args:
alphabet (list): The input alphabet
Returns:
None


def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None:
    color_p = ffi.new('TCOD_color_t*')
    (color_p.r, color_p.g, color_p.b) = (c.r, c.g, c.b)
    lib.TCOD_color_scale_HSV(color_p, scoef, vcoef)
    c[:] = (color_p.r, color_p.g, color_p.b)

Scale a color's saturation and value.

Does not return a new Color.  ``c`` is modified inplace.

Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.
Use 1 to keep current saturation.
vcoef (float): Value multiplier, from 0 to 1.
Use 1 to keep current value.


def sigmoid_cross_entropy_with_logits(logits, targets):

  if logits.shape != targets.shape:
    raise ValueError(
        "logits shape must equal targets shape"
        "logits=%s targets=%s" % (logits.to_string, targets.to_string))
  x = logits
  z = targets
  return mtf.relu(x) - x * z + mtf.log(1 + mtf.exp(-mtf.abs(x)))

Sigmoid cross-entropy loss.

Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits

Returns:
a mtf.Tensor whose shape is equal to logits.shape

Raises:
ValueError: if the shapes do not match.


def ParseRecord(self, parser_mediator, key, structure):

    if key not in ('header', 'logline'):
      raise errors.ParseError(
          'Unable to parse record, unknown structure: {0:s}'.format(key))

    if key == 'logline':
      self._ParseLine(parser_mediator, structure)

    elif key == 'header':
      self._ParseHeader(parser_mediator, structure)

Parse each record structure and return an EventObject if applicable.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): identifier of the structure of tokens.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.

Raises:
ParseError: when the structure type is unknown.


def binfiles_set(self, isnap):
    possible_files = set((self.filename(fstem, isnap, force_legacy=True) for fstem in phyvars.FIELD_FILES))
    return (possible_files & self.files)

Set of existing binary files at a given snap.

Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number.


def vibrational_internal_energy(self, temperature, volume):

        y = self.debye_temperature(volume) / temperature
        return self.kb * self.natoms * temperature * (9./8. * y +
                                                      3*self.debye_integral(y))

Vibrational internal energy, U_vib(V, T).
Eq(4) in doi.org/10.1016/j.comphy.2003.12.001

Args:
temperature (float): temperature in K
volume (float): in Ang^3

Returns:
float: vibrational internal energy in eV


def default_get_arg_names_from_class_name(class_name):
    parts = []
    rest = class_name
    if rest.startswith('_'):
        rest = rest[1:]
    while True:
        m = re.match('([A-Z][a-z]+)(.*)', rest)
        if (m is None):
            break
        parts.append(m.group(1))
        rest = m.group(2)
    if (not parts):
        return []
    return ['_'.join((part.lower() for part in parts))]

Converts normal class names into normal arg names.

Normal class names are assumed to be CamelCase with an optional leading
underscore.  Normal arg names are assumed to be lower_with_underscores.

Args:
class_name: a class name, e.g., "FooBar" or "_FooBar"
Returns:
all likely corresponding arg names, e.g., ["foo_bar"]


def _extract_match(self, candidate, offset):

        if (_SLASH_SEPARATED_DATES.search(candidate)):
            return None

        if _TIME_STAMPS.search(candidate):
            following_text = self.text[offset + len(candidate):]
            if _TIME_STAMPS_SUFFIX.match(following_text):
                return None

        match = self._parse_and_verify(candidate, offset)
        if match is not None:
            return match

        return self._extract_inner_match(candidate, offset)

Attempts to extract a match from a candidate string.

Arguments:
candidate -- The candidate text that might contain a phone number.
offset -- The offset of candidate within self.text
Returns the match found, None if none can be found


def create_border(self, border_style_type):
    if (border_style_type == MenuBorderStyleType.ASCII_BORDER):
        return self.create_ascii_border()
    elif (border_style_type == MenuBorderStyleType.LIGHT_BORDER):
        return self.create_light_border()
    elif (border_style_type == MenuBorderStyleType.HEAVY_BORDER):
        return self.create_heavy_border()
    elif (border_style_type == MenuBorderStyleType.DOUBLE_LINE_BORDER):
        return self.create_doubleline_border()
    elif (border_style_type == MenuBorderStyleType.HEAVY_OUTER_LIGHT_INNER_BORDER):
        return self.create_heavy_outer_light_inner_border()
    elif (border_style_type == MenuBorderStyleType.DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER):
        return self.create_doubleline_outer_light_inner_border()
    else:
        self.logger.info('Unrecognized border style type: {}. Defaulting to ASCII.'.format(border_style_type))
        return self.create_ascii_border()

Create a new MenuBorderStyle instance based on the given border style type.

Args:
border_style_type (int):  an integer value from :obj:`MenuBorderStyleType`.

Returns:
:obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style.


def from_tuplelist(tuple_list):

        out = Layout()
        for physical, virtual in enumerate(tuple_list):
            if virtual is None:
                continue
            elif Layout.is_virtual(virtual):
                if virtual in out._v2p:
                    raise LayoutError('Duplicate values not permitted; Layout is bijective.')
                out[virtual] = physical
            else:
                raise LayoutError("The list should contain elements of the form"
                                  " (Register, integer) or None")
        return out

Populates a Layout from a list containing virtual
qubits---(QuantumRegister, int) tuples---, or None.

Args:
tuple_list (list):
e.g.: [qr[0], None, qr[2], qr[3]]
Returns:
Layout: the corresponding Layout object
Raises:
LayoutError: If the elements are not (Register, integer) or None


def sym_hash(x: Any) -> int:
    if isinstance(x, Symbolic):
        return x.sym_hash()
    if inspect.isfunction(x):
        return hash(x.__code__.co_code)
    if inspect.ismethod(x):
        return hash((sym_hash(x.__self__), x.__code__.co_code))
    return hash(x)

Returns hash of value. Use symbolic hashing function if possible.

Example::

@pg.symbolize
class A:
def __init__(self, x):
self.x = x

assert hash(A(1)) != hash(A(1))
assert pg.hash(A(1)) == pg.hash(A(1))
assert pg.hash(pg.Dict(x=[A(1)])) == pg.hash(pg.Dict(x=[A(1)]))

Args:
x: Value for computing hash.

Returns:
The hash value for `x`.


def JoinTypes(types):
    queue = collections.deque(types)
    seen = set()
    new_types = []
    while queue:
        t = queue.popleft()
        if isinstance(t, pytd.UnionType):
            queue.extendleft(reversed(t.type_list))
        elif isinstance(t, pytd.NothingType):
            pass
        elif t not in seen:
            new_types.append(t)
            seen.add(t)
    if len(new_types) == 1:
        return new_types.pop()
    elif any((isinstance(t, pytd.AnythingType) for t in new_types)):
        nonetype = pytd.NamedType('builtins.NoneType')
        unresolved_nonetype = pytd.NamedType('NoneType')
        if any((t in (nonetype, unresolved_nonetype) for t in new_types)):
            return pytd.UnionType((pytd.AnythingType(), nonetype))
        return pytd.AnythingType()
    elif new_types:
        return pytd.UnionType(tuple(new_types))
    else:
        return pytd.NothingType()

Combine a list of types into a union type, if needed.

Leaves singular return values alone, or wraps a UnionType around them if there
are multiple ones, or if there are no elements in the list (or only
NothingType) return NothingType.

Arguments:
types: A list of types. This list might contain other UnionTypes. If so,
they are flattened.

Returns:
A type that represents the union of the types passed in. Order is preserved.


def unparse_headers(hdrs):
    return (''.join([unparse_header(n, v) for (n, v) in hdrs.items()]) + '\r\n')

Parse a dictionary of headers to a string.

Args:
hdrs: A dictionary of headers.

Returns:
The headers as a string that can be used in an NNTP POST.


class BayesianWatermarkDetectorModelOutput(ModelOutput):
    loss: Optional[torch.FloatTensor] = None
    posterior_probabilities: Optional[torch.FloatTensor] = None

Base class for outputs of models predicting if the text is watermarked.

Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
Multiple choice classification loss.


def draw_rects(self, *rects):
    rect_array = ffi.new('SDL_Rect[]', len(rects))
    for (i, r) in enumerate(rects):
        rect_array[i] = r._ptr[0]
    check_int_err(lib.SDL_RenderDrawRects(self._ptr, rect_array, len(rects)))

Draw some number of rectangles on the current rendering target.

Args:
*rects (Rect): The destination rectangles.

Raises:
SDLError: If an error is encountered.


def load_structure_path(self, structure_path, file_type):

        if not file_type:
            raise ValueError('File type must be specified')

        self.file_type = file_type
        self.structure_dir = op.dirname(structure_path)
        self.structure_file = op.basename(structure_path)

Load a structure file and provide pointers to its location

Args:
structure_path (str): Path to structure file
file_type (str): Type of structure file


def managed(name, table, data, record=None):
    ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
    if (record is None):
        record = name
    current_data = {column: __salt__['openvswitch.db_get'](table, record, column) for column in data}
    comment_changes = 'Columns have been updated.'
    comment_no_changes = 'All columns are already up to date.'
    comment_error = 'Error while updating column {0}: {1}'
    if __opts__['test']:
        for column in data:
            if (data[column] != current_data[column]):
                ret['changes'][column] = {'old': current_data[column], 'new': data[column]}
        if ret['changes']:
            ret['result'] = None
            ret['comment'] = comment_changes
        else:
            ret['result'] = True
            ret['comment'] = comment_no_changes
        return ret
    for column in data:
        if (data[column] != current_data[column]):
            result = __salt__['openvswitch.db_set'](table, record, column, data[column])
            if (result is not None):
                ret['comment'] = comment_error.format(column, result)
                ret['result'] = False
                return ret
            ret['changes'][column] = {'old': current_data[column], 'new': data[column]}
    ret['result'] = True
    ret['comment'] = comment_no_changes
    return ret

Ensures that the specified columns of the named record have the specified
values.

Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from column names to the desired
values. Columns that exist, but are not specified in this
dictionary are not touched.
record: The name of the record (optional). Replaces name if specified.


def __init__(self, token=None, auth_test=False, verify=True, lazy=False):

        try:
            self.token = token if token else os.environ['SLACK_TOKEN']
        except KeyError:
            raise ValueError('If not providing a token, must set SLACK_TOKEN envvar')
        if auth_test:
            response = self.auth_test()
            if not response['ok']:
                raise ValueError('Authentication Failed with response: {}'.format(response))
        self.verify = verify

        self._channels = []
        self._users = []

        if not lazy:
            _ = self.channels
            _ = self.users

Instantiation an instance of the Slack API

Args:
token: {str} (required) API token, read from SLACK_TOKEN env var
auth_test: {bool} verify this token
verify: {bool} verify all API calls return with a True 'ok'
lazy: {bool} Don't populate properties until called


def _read_mode_tsopt(self, size, kind):
    temp = struct.unpack('>II', self._read_fileng(size))
    data = dict(kind=kind, length=size, val=temp[0], ecr=temp[1])
    return data

Read Timestamps option.

Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)

Returns:
* dict -- extracted Timestamps (TS) option

Structure of TCP TSopt [RFC 7323]:
+-------+-------+---------------------+---------------------+
|Kind=8 |  10   |   TS Value (TSval)  |TS Echo Reply (TSecr)|
+-------+-------+---------------------+---------------------+
1       1              4                     4

Octets      Bits        Name                    Description
0           0     tcp.ts.kind             Kind (8)
1           8     tcp.ts.length           Length (10)
2          16     tcp.ts.val              Timestamp Value
6          48     tcp.ts.ecr              Timestamps Echo Reply


def with_row_splits_dtype(self, dtype):
    dtype = dtypes.as_dtype(dtype)
    if dtype not in (dtypes.int32, dtypes.int64):
        raise ValueError(f'Argument `row_splits` dtype must be int32 or int64. Received {dtype}.')
    if self._row_partition.dtype == dtype:
        return self
    current_values = self._values
    if isinstance(current_values, RaggedTensor):
        return RaggedTensor(values=current_values.with_row_splits_dtype(dtype), row_partition=self._row_partition.with_dtype(dtype), internal=True)
    else:
        return RaggedTensor(values=current_values, row_partition=self._row_partition.with_dtype(dtype), internal=True)

Returns a copy of this RaggedTensor with the given `row_splits` dtype.

For RaggedTensors with multiple ragged dimensions, the `row_splits` for all
nested `RaggedTensor` objects are cast to the given dtype.

Args:
dtype: The dtype for `row_splits`.  One of `tf.int32` or `tf.int64`.

Returns:
A copy of this RaggedTensor, with the `row_splits` cast to the given
type.


async def getTempCoreCmdr(mods=None, outp=None):
    acm = genTempCoreProxy(mods)
    prox = (await acm.__aenter__())
    cmdrcore = (await CmdrCore.anit(prox, outp=outp))
    cmdrcore.acm = acm
    return cmdrcore

Get a CmdrCore instance which is backed by a temporary Cortex.

Args:
mods (list): A list of additional CoreModules to load in the Cortex.
outp: A output helper.  Will be used for the Cmdr instance.

Notes:
The CmdrCore returned by this should be fini()'d to tear down the temporary Cortex.

Returns:
CmdrCore: A CmdrCore instance.


def GetLinkedFileEntry(self):
    link = self._GetLink()
    if (not link):
        return None
    path_spec = os_path_spec.OSPathSpec(location=link)
    return OSFileEntry(self._resolver_context, self._file_system, path_spec)

Retrieves the linked file entry, for example for a symbolic link.

Returns:
OSFileEntry: linked file entry or None if not available.


def get_channel(self, channel_name, project_name, dataset_name):

        return self.resources.get_channel(channel_name, project_name,
                                          dataset_name)

Gets info about a channel given its name, name of its project
, and name of its dataset.

Arguments:
channel_name (str): Channel name
project_name (str): Project name
dataset_name (str): Dataset name

Returns:
dict: Channel info


def coldestmonth(self, value=None):

        if value is not None:
            try:
                value = int(value)
            except ValueError:
                raise ValueError('value {} need to be of type int '
                                 'for field `coldestmonth`'.format(value))
            if value < 1:
                raise ValueError('value need to be greater or equal 1 '
                                 'for field `coldestmonth`')
            if value > 12:
                raise ValueError('value need to be smaller 12 '
                                 'for field `coldestmonth`')

        self._coldestmonth = value

Corresponds to IDD Field `coldestmonth`

Args:
value (int): value for IDD Field `coldestmonth`
value >= 1
value <= 12
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

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


def savefits(cube, fitsname, **kwargs):
    dropdeg = kwargs.pop('dropdeg', False)
    ndim = len(cube.dims)
    FITSINFO = get_data('decode', 'data/fitsinfo.yaml')
    hdrdata = yaml.load(FITSINFO, dc.utils.OrderedLoader)
    if (ndim == 2):
        header = fits.Header(hdrdata['dcube_2d'])
        data = cube.values.T
    elif (ndim == 3):
        if dropdeg:
            header = fits.Header(hdrdata['dcube_2d'])
            data = cube.values[(:, :, 0)].T
        else:
            header = fits.Header(hdrdata['dcube_3d'])
            kidfq = cube.kidfq.values
            freqrange = (~ np.isnan(kidfq))
            orderedfq = np.argsort(kidfq[freqrange])
            newcube = cube[(:, :, orderedfq)]
            data = newcube.values.T
    else:
        raise TypeError(ndim)
    if (cube.coordsys == 'AZEL'):
        header.update({'CTYPE1': 'dAZ', 'CTYPE2': 'dEL'})
    elif (cube.coordsys == 'RADEC'):
        header.update({'OBSRA': float(cube.xref), 'OBSDEC': float(cube.yref)})
    else:
        pass
    header.update({'CRVAL1': float(cube.x[0]), 'CDELT1': float((cube.x[1] - cube.x[0])), 'CRVAL2': float(cube.y[0]), 'CDELT2': float((cube.y[1] - cube.y[0])), 'DATE': datetime.now(timezone('UTC')).isoformat()})
    if ((ndim == 3) and (not dropdeg)):
        header.update({'CRVAL3': float(newcube.kidfq[0]), 'CDELT3': float((newcube.kidfq[1] - newcube.kidfq[0]))})
    fitsname = str(Path(fitsname).expanduser())
    fits.writeto(fitsname, data, header, **kwargs)
    logger.info('{} has been created.'.format(fitsname))

Save a cube to a 3D-cube FITS file.

Args:
cube (xarray.DataArray): Cube to be saved.
fitsname (str): Name of output FITS file.
kwargs (optional): Other arguments common with astropy.io.fits.writeto().


def log_mel_spectrogram(data, audio_sample_rate=8000, log_offset=0.0, window_length_secs=0.025, hop_length_secs=0.01, **kwargs):
    window_length_samples = int(round((audio_sample_rate * window_length_secs)))
    hop_length_samples = int(round((audio_sample_rate * hop_length_secs)))
    fft_length = (2 ** int(np.ceil((np.log(window_length_samples) / np.log(2.0)))))
    spectrogram = stft_magnitude(data, fft_length=fft_length, hop_length=hop_length_samples, window_length=window_length_samples)
    mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix(num_spectrogram_bins=spectrogram.shape[1], audio_sample_rate=audio_sample_rate, **kwargs))
    return np.log((mel_spectrogram + log_offset))

Convert waveform to a log magnitude mel-frequency spectrogram.

Args:
data: 1D np.array of waveform data.
audio_sample_rate: The sampling rate of data.
log_offset: Add this to values when taking log to avoid -Infs.
window_length_secs: Duration of each window to analyze.
hop_length_secs: Advance between successive analysis windows.
**kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.

Returns:
2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank
magnitudes for successive frames.


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

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

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


def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'):
    with tf.variable_scope(scope):
        if (stride > 1):
            avg_pool = CONFIG[dim]['avg_pool']
            x = avg_pool(x, pool_size=(stride, stride), strides=(stride, stride), padding='VALID')
        input_channels = tf.shape(x)[3]
        diff = (output_channels - input_channels)
        x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [(diff
        return x

Downsamples 'x' by `stride` using average pooling.

Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to use. Usually 1 or 2.
scope: Optional variable scope.

Returns:
A downsampled tensor of size [N, H/2, W/2, output_channels] if stride
is 2, else returns a tensor of size [N, H, W, output_channels] if
stride is 1.


def writegroup(self, auth, entries, defer=False):

        return self._call('writegroup', auth, [entries], defer)

Writes the given values for the respective resources in the list, all writes have same
timestamp.

Args:
auth: cik for authentication.
entries: List of key, value lists. eg. [[key, value], [k,v],,,]


def dump_property(self, name):

        if not hasattr(self, name):
            raise ArgumentError("Unknown property %s" % name)

        value = getattr(self, name)
        if name in self._complex_properties:
            value = self._complex_properties[name][0](value)

        return value

Serialize a property of this class by name.

Args:
name (str): The name of the property to dump.

Returns:
object: The serialized value of the property.


def _tf_extension_type_fields(cls):
    if '_tf_extension_type_cached_fields' in cls.__dict__:
        return cls._tf_extension_type_cached_fields
    try:
        type_hints = typing_extensions.get_type_hints(cls, include_extras=False)
        ok_to_cache = True
    except (NameError, AttributeError):
        type_hints = {}
        for base in reversed(cls.__mro__):
            type_hints.update(base.__dict__.get('__annotations__', {}))
        ok_to_cache = False
    fields = []
    for name, value_type in type_hints.items():
        default = getattr(cls, name, extension_type_field.ExtensionTypeField.NO_DEFAULT)
        fields.append(extension_type_field.ExtensionTypeField(name, value_type, default))
    fields = tuple(fields)
    if ok_to_cache:
        cls._tf_extension_type_cached_fields = fields
    return fields

An ordered list describing the fields of this ExtensionType.

Returns:
A list of `ExtensionTypeField` objects.  Forward references are resolved
if possible, or left unresolved otherwise.


def trainable(self, value):
    value = bool(value)
    self._trainable = value
    for v in self._trainable_variables:
        v.trainable = value
    for layer in self._layers:
        layer.trainable = value

Sets trainable attribute for the layer and its sublayers.

When this value is changed during training (e.g. with a
`Callback`) you need to call the parent
`Model.make_train_function` with `force=True` in order to
recompile the training graph.

Args:
value: Boolean with the desired state for the layer's trainable
attribute.


def GetCacheValueByObject(self, vfs_object):

    for identifier, cache_value in iter(self._values.items()):
      if not cache_value:
        raise RuntimeError('Missing cache value.')

      if cache_value.vfs_object == vfs_object:
        return identifier, cache_value

    return None, None

Retrieves the cache value for the cached object.

Args:
vfs_object (object): VFS object that was cached.

Returns:
tuple[str, ObjectsCacheValue]: identifier and cache value object or
(None, None) if not cached.

Raises:
RuntimeError: if the cache value is missing.


def setProvisioningUrl(self, strURL='grl.com'):

        print '%s call setProvisioningUrl' % self.port
        self.provisioningUrl = strURL
        if self.deviceRole == Thread_Device_Role.Commissioner:
            cmd = WPANCTL_CMD + 'setprop Commissioner:ProvisioningUrl %s' %(strURL)
            print cmd
            return self.__sendCommand(cmd)[0] != "Fail"
        return True

set provisioning Url

Args:
strURL: Provisioning Url string

Returns:
True: successful to set provisioning Url
False: fail to set provisioning Url


def _results_tc_args(self):
    results = []
    if os.access(self.default_args.tc_out_path, os.W_OK):
        result_file = '{}/results.tc'.format(self.default_args.tc_out_path)
    else:
        result_file = 'results.tc'
    if os.path.isfile(result_file):
        with open(result_file, 'r') as rh:
            results = rh.read().strip().split('\n')
        os.remove(result_file)
    for line in results:
        if ((not line) or (' = ' not in line)):
            continue
        (key, value) = line.split(' = ')
        if (value == 'true'):
            value = True
        elif (value == 'false'):
            value = False
        elif (not value):
            value = None
        setattr(self._default_args, key, value)

Read data from results_tc file from previous run of app.

This method is only required when not running from the with the
TcEX platform and is only intended for testing apps locally.

Returns:
(dictionary): A dictionary of values written to results_tc.


def find_many(self, url, type, resource):
    return [type(item) for item in RestClient.get(url)[resource]]

Get a list of resources

Args:
url (string): URL to invoke
type (class): Class type
resource (string): The REST Resource
Returns:
list of object: List of resource instances


def scoped_format(txt, **objects):
    pretty = objects.pop('pretty', RecursiveAttribute.format_pretty)
    expand = objects.pop('expand', RecursiveAttribute.format_expand)
    attr = RecursiveAttribute(objects, read_only=True)
    formatter = scoped_formatter(**objects)
    return formatter.format(txt, pretty=pretty, expand=expand)

Format a string with respect to a set of objects' attributes.

Example:

>>> Class Foo(object):
>>>     def __init__(self):
>>>         self.name = "Dave"
>>> print scoped_format("hello {foo.name}", foo=Foo())
hello Dave

Args:
objects (dict): Dict of objects to format with. If a value is a dict,
its values, and any further neted dicts, will also format with dot
notation.
pretty (bool): See `ObjectStringFormatter`.
expand (bool): See `ObjectStringFormatter`.


def get_graphql_schema_from_schema_graph(schema_graph, class_to_field_type_overrides, hidden_classes):
    _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides, schema_graph)
    inherited_field_type_overrides = _get_inherited_field_types(class_to_field_type_overrides, schema_graph)
    if (not schema_graph.get_element_by_class_name(ORIENTDB_BASE_VERTEX_CLASS_NAME).properties):
        hidden_classes.add(ORIENTDB_BASE_VERTEX_CLASS_NAME)
    graphql_types = OrderedDict()
    type_equivalence_hints = OrderedDict()
    for vertex_cls_name in sorted(schema_graph.vertex_class_names):
        vertex_cls = schema_graph.get_element_by_class_name(vertex_cls_name)
        if (vertex_cls_name in hidden_classes):
            continue
        inherited_field_type_overrides.setdefault(vertex_cls_name, dict())
        field_type_overrides = inherited_field_type_overrides[vertex_cls_name]
        field_specification_lambda = _create_field_specification(schema_graph, graphql_types, field_type_overrides, hidden_classes, vertex_cls_name)
        current_graphql_type = None
        if vertex_cls.abstract:
            current_graphql_type = GraphQLInterfaceType(vertex_cls_name, fields=field_specification_lambda)
        else:
            interface_specification_lambda = _create_interface_specification(schema_graph, graphql_types, hidden_classes, vertex_cls_name)
            current_graphql_type = GraphQLObjectType(vertex_cls_name, field_specification_lambda, interfaces=interface_specification_lambda, is_type_of=(lambda : None))
        graphql_types[vertex_cls_name] = current_graphql_type
    for vertex_cls_name in sorted(schema_graph.vertex_class_names):
        vertex_cls = schema_graph.get_element_by_class_name(vertex_cls_name)
        if (vertex_cls_name in hidden_classes):
            continue
        vertex_cls_subclasses = schema_graph.get_subclass_set(vertex_cls_name)
        if ((not vertex_cls.abstract) and (len(vertex_cls_subclasses) > 1)):
            union_type_name = _get_union_type_name(vertex_cls_subclasses)
            type_specification_lambda = _create_union_types_specification(schema_graph, graphql_types, hidden_classes, vertex_cls_name)
            union_type = GraphQLUnionType(union_type_name, types=type_specification_lambda)
            graphql_types[union_type_name] = union_type
            type_equivalence_hints[graphql_types[vertex_cls_name]] = union_type
    for non_graph_cls_name in sorted(schema_graph.non_graph_class_names):
        if (non_graph_cls_name in hidden_classes):
            continue
        if (not schema_graph.get_element_by_class_name(non_graph_cls_name).abstract):
            continue
        cls_subclasses = schema_graph.get_subclass_set(non_graph_cls_name)
        if (len(cls_subclasses) > 1):
            all_non_abstract_subclasses_are_vertices = True
            for subclass_name in cls_subclasses:
                subclass = schema_graph.get_element_by_class_name(subclass_name)
                if (subclass_name != non_graph_cls_name):
                    if ((not subclass.abstract) and (not subclass.is_vertex)):
                        all_non_abstract_subclasses_are_vertices = False
                        break
            if all_non_abstract_subclasses_are_vertices:
                inherited_field_type_overrides.setdefault(non_graph_cls_name, dict())
                field_type_overrides = inherited_field_type_overrides[non_graph_cls_name]
                field_specification_lambda = _create_field_specification(schema_graph, graphql_types, field_type_overrides, hidden_classes, non_graph_cls_name)
                graphql_type = GraphQLInterfaceType(non_graph_cls_name, fields=field_specification_lambda)
                graphql_types[non_graph_cls_name] = graphql_type
    if (not graphql_types):
        raise EmptySchemaError(u'After evaluating all subclasses of V, we were not able to find visible schema data to import into the GraphQL schema object')
    RootSchemaQuery = GraphQLObjectType('RootSchemaQuery', OrderedDict([(name, GraphQLField(value)) for (name, value) in sorted(six.iteritems(graphql_types), key=(lambda x: x[0])) if (not isinstance(value, GraphQLUnionType))]))
    schema = GraphQLSchema(RootSchemaQuery, directives=DIRECTIVES)
    return (schema, _get_referenced_type_equivalences(graphql_types, type_equivalence_hints))

Return a GraphQL schema object corresponding to the schema of the given schema graph.

Args:
schema_graph: SchemaGraph
class_to_field_type_overrides: dict, class name -> {field name -> field type},
(string -> {string -> GraphQLType}). Used to override the
type of a field in the class where it's first defined and all
the class's subclasses.
hidden_classes: set of strings, classes to not include in the GraphQL schema.

Returns:
tuple of (GraphQL schema object, GraphQL type equivalence hints dict).
The tuple is of type (GraphQLSchema, {GraphQLObjectType -> GraphQLUnionType}).


def maybe_saved_model_directory(export_dir):
    txt_path = file_io.join(export_dir, constants.SAVED_MODEL_FILENAME_PBTXT)
    pb_path = file_io.join(export_dir, constants.SAVED_MODEL_FILENAME_PB)
    cpb_path = file_io.join(export_dir, constants.SAVED_MODEL_FILENAME_CPB)
    return file_io.file_exists(txt_path) or file_io.file_exists(pb_path) or file_io.file_exists(cpb_path)

Checks whether the provided export directory could contain a SavedModel.

Note that the method does not load any data by itself. If the method returns
`false`, the export directory definitely does not contain a SavedModel. If the
method returns `true`, the export directory may contain a SavedModel but
provides no guarantee that it can be loaded.

Args:
export_dir: Absolute string path to possible export location. For example,
'/my/foo/model'.

Returns:
True if the export directory contains SavedModel files, False otherwise.


def get_stable_entries(self, charge_to_discharge=True):

        list_copy = list(self._stable_entries)
        return list_copy if charge_to_discharge else list_copy.reverse()

Get the stable entries.

Args:
charge_to_discharge: order from most charge to most discharged
state? Default to True.

Returns:
A list of stable entries in the electrode, ordered by amount of the
working ion.


def _process_inputs(self, input_reader, shard_state, tstate, ctx):
    processing_limit = self._processing_limit(tstate.mapreduce_spec)
    if (processing_limit == 0):
        return
    finished_shard = True
    iterator = iter(input_reader)
    while True:
        try:
            entity = iterator.next()
        except StopIteration:
            break
        if isinstance(entity, db.Model):
            shard_state.last_work_item = repr(entity.key())
        elif isinstance(entity, ndb.Model):
            shard_state.last_work_item = repr(entity.key)
        else:
            shard_state.last_work_item = repr(entity)[:100]
        processing_limit -= 1
        if (not self._process_datum(entity, input_reader, ctx, tstate)):
            finished_shard = False
            break
        elif (processing_limit == 0):
            finished_shard = False
            break
    self.slice_context.incr(context.COUNTER_MAPPER_WALLTIME_MS, int(((self._time() - self._start_time) * 1000)))
    return finished_shard

Read inputs, process them, and write out outputs.

This is the core logic of MapReduce. It reads inputs from input reader,
invokes user specified mapper function, and writes output with
output writer. It also updates shard_state accordingly.
e.g. if shard processing is done, set shard_state.active to False.

If errors.FailJobError is caught, it will fail this MR job.
All other exceptions will be logged and raised to taskqueue for retry
until the number of retries exceeds a limit.

Args:
input_reader: input reader.
shard_state: shard state.
tstate: transient shard state.
ctx: mapreduce context.

Returns:
Whether this shard has finished processing all its input split.


def detailed_log_handler(self, handler):
    if (not self.opened()):
        handler = (handler or util.noop)
        self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
        self._dll.JLINKARM_EnableLogCom(self._detailed_log_handler)

Setter for the detailed log handler function.

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

Returns:
``None``


def price(self, valuation_date, market, model=None, pricing_context=None, name=None):
    name = name or self._name + '_price'
    with tf.name_scope(name):
        valuation_date = dates.convert_to_date_tensor(valuation_date)
        pay_cf = self._pay_leg.price(valuation_date, market, model, pricing_context)
        receive_cf = self._receive_leg.price(valuation_date, market, model, pricing_context)
        return receive_cf - pay_cf

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

Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the interest rate swap.
model: Reserved for future use.
pricing_context: Additional context relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.

Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each IRS
contract based on the input market data.


def load_dataset(data_path: str, findex: typing.Dict[str, int]) -> Dataset:
    Y = array.array('i')
    X_rows = array.array('I')
    X_cols = array.array('I')
    with open(data_path) as f:
        i = 0
        for row in f:
            cols = row.strip().split('\t')
            if len(cols) < 2:
                continue
            Y.append(int(cols[0]))
            hit_indices = [findex[feat] for feat in cols[1:] if feat in findex]
            X_rows.extend((i for _ in range(len(hit_indices))))
            X_cols.extend(hit_indices)
            i += 1
    return Dataset(jnp.asarray(X_rows), jnp.asarray(X_cols), jnp.asarray(Y))

Loads a dataset from the given encoded data file.

Args:
data_path (str): A file path for the encoded data file.
findex (Dict[str, int]): A dictionary that maps a feature to its index.

Returns:
A dataset


def to_dict(mapreduce_yaml):
    all_configs = []
    for config in mapreduce_yaml.mapreduce:
        out = {'name': config.name, 'mapper_input_reader': config.mapper.input_reader, 'mapper_handler': config.mapper.handler}
        if config.mapper.params_validator:
            out['mapper_params_validator'] = config.mapper.params_validator
        if config.mapper.params:
            param_defaults = {}
            for param in config.mapper.params:
                param_defaults[param.name] = (param.default or param.value)
            out['mapper_params'] = param_defaults
        if config.params:
            param_defaults = {}
            for param in config.params:
                param_defaults[param.name] = (param.default or param.value)
            out['params'] = param_defaults
        if config.mapper.output_writer:
            out['mapper_output_writer'] = config.mapper.output_writer
        all_configs.append(out)
    return all_configs

Converts a MapReduceYaml file into a JSON-encodable dictionary.

For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list

Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.

Returns:
A list of configuration dictionaries.


def _get_entry_energy(pd, composition):

        candidate = [i.energy_per_atom for i in pd.qhull_entries if
                     i.composition.fractional_composition ==
                     composition.fractional_composition]

        if not candidate:
            warnings.warn("The reactant " + composition.reduced_formula +
                          " has no matching entry with negative formation"
                          " energy, instead convex hull energy for this"
                          " composition will be used for reaction energy "
                          "calculation. ")
            return pd.get_hull_energy(composition)
        else:
            min_entry_energy = min(candidate)
            return min_entry_energy * composition.num_atoms

Finds the lowest entry energy for entries matching the composition.
Entries with non-negative formation energies are excluded. If no
entry is found, use the convex hull energy for the composition.

Args:
pd (PhaseDiagram): PhaseDiagram object.
composition (Composition): Composition object that the target
entry should match.

Returns:
The lowest entry energy among entries matching the composition.


def json(self, branch='master', filename=''):

        file_contents = self.get(branch=branch, filename=filename)

        try:
            json_dict = json.loads(file_contents)

        except ValueError as error:
            msg = ('"{filename}" appears to be invalid json. '
                   'Please validate it with http:
                   'JSON decoder error:\n'
                   '{error}').format(
                       filename=filename, error=error)
            raise SystemExit(msg)

        LOG.debug('JSON object:\n%s', json_dict)
        return json_dict

Retrieve _filename_ from GitLab.

Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve.

Returns:
dict: Decoded JSON.

Raises:
SystemExit: Invalid JSON provided.


def validate_metadata(train_config):
    if (len(train_config['csv_header']) != len(train_config['csv_defaults'])):
        raise ValueError('Unequal number of columns in input features file and schema file.')
    sorted_columns = sorted((train_config['csv_header'] + [train_config['target_column']]))
    sorted_columns2 = sorted((((train_config['categorical_columns'] + train_config['numerical_columns']) + [train_config['key_column']]) + [train_config['target_column']]))
    if (sorted_columns2 != sorted_columns):
        raise ValueError('Each csv header must be a numerical/categorical type, a  key, or a target.')

Perform some checks that the trainig config is correct.

Args:
train_config: train config as produced by merge_metadata()

Raises:
ValueError: if columns look wrong.


def delete_object(self, ref, delete_arguments=None):
    opts = self._get_request_options()
    if (not isinstance(delete_arguments, dict)):
        delete_arguments = {}
    url = self._construct_url(ref, query_params=delete_arguments)
    self._log_request('delete', url, opts)
    r = self.session.delete(url, **opts)
    self._validate_authorized(r)
    if (r.status_code != requests.codes.ok):
        self._check_service_availability('delete', r, ref)
        raise ib_ex.InfobloxCannotDeleteObject(response=jsonutils.loads(r.content), ref=ref, content=r.content, code=r.status_code)
    return self._parse_reply(r)

Remove an Infoblox object

Args:
ref               (str): Object reference
delete_arguments (dict): Extra delete arguments
Returns:
The object reference of the removed object
Raises:
InfobloxException


def enforce_periodic_boundary_conditions( self ):

        for s in self.sites:
            for i in range(3):
                if s.r[i] < 0.0:
                    s.r[i] += self.cell_lengths[i]
                if s.r[i] > self.cell_lengths[i]:
                    s.r[i] -= self.cell_lengths[i]

Ensure that all lattice sites are within the central periodic image of the simulation cell.
Sites that are outside the central simulation cell are mapped back into this cell.

Args:
None

Returns:
None


def _GetNumericProjectId(self):
    project_id = 'project/numeric-project-id'
    return self.watcher.GetMetadata(metadata_key=project_id, recursive=False)

Get the numeric project ID for this VM.

Returns:
string, the numeric project ID if one is found.


def generate_token(key, user_id, action_id='', when=None):

    digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8'))
    digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8'))
    digester.update(DELIMITER)
    digester.update(_helpers._to_bytes(action_id, encoding='utf-8'))
    digester.update(DELIMITER)
    when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8')
    digester.update(when)
    digest = digester.digest()

    token = base64.urlsafe_b64encode(digest + DELIMITER + when)
    return token

Generates a URL-safe token for the given user, action, time tuple.

Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
when: the time in seconds since the epoch at which the user was
authorized for this action. If not set the current time is used.

Returns:
A string XSRF protection token.


def is_multiline_string(self):
    return self.is_string and self.value.endswith(('"""', "'''"))

Test if this string is a multiline string.

Returns:
A multiline string always ends with triple quotes, so if it is a string
token, inspect the last 3 characters and return True if it is a triple
double or triple single quote mark.


def log_images(self, name, images, step=None):
    if isinstance(images, six.string_types):
        raise TypeError('"images" should be a list of ndarrays, got {}'.format(type(images)))
    self._check_step(step)
    tf_name = self._ensure_tf_name(name)
    summary = self._image_summary(tf_name, images, step=step)
    self._log_summary(tf_name, summary, images, step=step)

Log new images for given name on given step.

Args:
name (str): name of the variable (it will be converted to a valid
tensorflow summary name).
images (list): list of images to visualize
step (int): non-negative integer used for visualization


def graphviz_imshow(self, ax=None, figsize=None, dpi=300, fmt='png', **kwargs):
    graph = self.get_graphviz(**kwargs)
    graph.format = fmt
    graph.attr(dpi=str(dpi))
    (_, tmpname) = tempfile.mkstemp()
    path = graph.render(tmpname, view=False, cleanup=True)
    (ax, fig, _) = get_ax_fig_plt(ax=ax, figsize=figsize, dpi=dpi)
    import matplotlib.image as mpimg
    ax.imshow(mpimg.imread(path, format='png'))
    ax.axis('off')
    return fig

Generate flow graph in the DOT language and plot it with matplotlib.

Args:
ax: matplotlib :class:`Axes` or None if a new figure should be created.
figsize: matplotlib figure size (None to use default)
dpi: DPI value.
fmt: Select format for output image

Return: matplotlib Figure


def _encode_fhir_path_constraint(self, struct_def: _fhir_path_data_types.StructureDataType, fhir_path_expression: str, node_context: expressions.Builder) -> Optional[_BuilderSql]:
    if node_context.get_root_builder().fhir_path == node_context.fhir_path:
        node_context = None
    try:
        new_builder = expressions.from_fhir_path_expression(fhir_path_expression, self._context, struct_def, self._primitive_handler, node_context)
    except Exception as e:
        self._error_reporter.report_fhir_path_error(self._abs_path_invocation(node_context), f'{node_context}.{fhir_path_expression}', self._error_message_for_exception(e))
        return None
    return self._encode_fhir_path_builder_constraint(new_builder, node_context)

Returns a Standard SQL translation of the constraint `fhir_path_expression`.

If an error is encountered during encoding, the associated error reporter
will be notified, and this method will return `None`.

Args:
struct_def: The Structure definition that the fhir_path_expression
originates from.
fhir_path_expression: The fluent-style dot-delimited ('.') FHIRPath
expression that encodes to Standard SQL.
node_context: The root builder of the fhir_path_expression. May be another
FHIRPath expression.

Returns:
A Standard SQL encoding of the constraint `fhir_path_expression` upon
successful completion. The SQL will evaluate to a single boolean
indicating whether the constraint is satisfied and the builder that
created it. May be different from the input builder(s).


def MakeSuiteFromCdf(cdf, name=None):

    if name is None:
        name = cdf.name

    suite = Suite(name=name)

    prev = 0.0
    for val, prob in cdf.Items():
        suite.Incr(val, prob - prev)
        prev = prob

    return suite

Makes a normalized Suite from a Cdf object.

Args:
cdf: Cdf object
name: string name for the new Suite

Returns:
Suite object


def remove_liers(points):

    result = [points[0]]
    for i in range(1, len(points) - 2):
        prv = points[i-1]
        crr = points[i]
        nxt = points[i+1]
        if prv.time <= crr.time and crr.time <= nxt.time:
            result.append(crr)
    result.append(points[-1])

    return result

Removes obvious noise points

Checks time consistency, removing points that appear out of order

Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`list` of :obj:`Point`


def __init__(self, num_layers: int=1, in_channels: int=3, out_channels: int=64, use_batchnorm: bool=True):
    super().__init__()
    self.conv = Conv2dSamePadding(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=2, bias=False)
    self.batchnorm = nn.BatchNorm2d(num_features=out_channels) if use_batchnorm else nn.Identity()
    self.relu = nn.ReLU()
    self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2)

Constructs a Conv2DDownsample model.

Args:
in_channels (`int`, *optional*, defaults to 3):
The number of input channels.
out_channels (`int`, *optional*, defaults to 64):
The number of conv output channels.
use_batchnorm (`bool`, *optional*, defaults to `True`):
Whether to use batchnorm.


def _expect(self, expected, times=50):

        logger.debug('[%s] Expecting [%s]', self.port, expected)
        retry_times = 10
        while times:
            if not retry_times:
                break

            line = self._readline()

            if line == expected:
                return

            if not line:
                retry_times -= 1
                time.sleep(0.1)

            times -= 1

        raise Exception('failed to find expected string[%s]' % expected)

Find the `expected` line within `times` trials.

Args:
expected    str: the expected string
times       int: number of trials


def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor):
    image_tokens_list = self.vqmodel.encode(pixel_values, image_sizes)
    bpe_tokens_list = [self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in image_tokens_list]
    bpe_tokens = torch.cat(bpe_tokens_list)
    return bpe_tokens

Tokenizes images into discrete tokens with VQGAN module. Converts
obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
special tokens.

Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
The tensors corresponding to the input images.
image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
The sizes of the images in the batch, being (height, width) for each image.


def simple_vertex_array(self, program, buffer, *attributes,
                            index_buffer=None, index_element_size=4) -> 'VertexArray':

        if type(buffer) is list:
            raise SyntaxError('Change simple_vertex_array to vertex_array')

        content = [(buffer, detect_format(program, attributes)) + attributes]
        return self.vertex_array(program, content, index_buffer, index_element_size)

Create a :py:class:`VertexArray` object.

Args:
program (Program): The program used when rendering.
buffer (Buffer): The buffer.
attributes (list): A list of attribute names.

Keyword Args:
index_element_size (int): byte size of each index element, 1, 2 or 4.
index_buffer (Buffer): An index buffer.

Returns:
:py:class:`VertexArray` object


def _ReverseHostname(self, hostname):

    if not hostname:
      return ''

    if len(hostname) <= 1:
      return hostname

    if hostname[-1] == '.':
      return hostname[::-1][1:]

    return hostname[::-1][0:]

Reverses the hostname and strips the leading dot.

The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com

Args:
hostname (str): reversed hostname.

Returns:
str: hostname without a leading dot.


def get_meta_references(self, datas):
    rule = datas.get(RULE_META_REFERENCES, {})
    if (not rule):
        msg = "Manifest lacks of '.{}' or is empty"
        raise SerializerError(msg.format(RULE_META_REFERENCES))
    elif rule.get('names', None):
        names = rule.get('names').split(' ')
    elif rule.get('auto', None):
        names = self.get_available_references(datas)
    else:
        msg = "'.{}' either require '--names' or '--auto' variable to be defined"
        raise SerializerError(msg.format(RULE_META_REFERENCES))
    for item in names:
        self.validate_rule_name(item)
    return names

Get manifest enabled references declaration

This required declaration is readed from
``styleguide-metas-references`` rule that require either a ``--names``
or ``--auto`` variable, each one define the mode to enable reference:

Manually
Using ``--names`` which define a list of names to enable, every
other non enabled rule will be ignored.

Section name (and so Reference name also) must not contains special
character nor ``-`` so they still be valid variable name for almost
any languages. For word separator inside name, use ``_``.
Automatic
Using ``--auto`` variable every reference rules will be enabled.
The value of this variable is not important since it is not empty.

If both of these variables are defined, the manual enable mode is used.

Arguments:
datas (dict): Data where to search for meta references declaration.
This is commonly the fully parsed manifest.

Returns:
list: A list of reference names.


def search(self, queryType, query=None, vendorSpecific=None, **kwargs):

        response = self.searchResponse(queryType, query, vendorSpecific, **kwargs)
        return self._read_dataone_type_response(response, 'ObjectList')

See Also: searchResponse()

Args:
queryType:
query:
vendorSpecific:
**kwargs:

Returns:


def get(cls, sha1=''):

        with conf.within_proj_dir():
            cmd = 'git show -s --format="%H||%an||%ae||%s||%b||%P" {}'.format(
                sha1
            )
            result = shell.run(cmd, capture=True, never_pretend=True).stdout

        sha1, name, email, title, desc, parents = result.split('||')

        return CommitDetails(
            sha1=sha1,
            author=Author(name, email),
            title=title,
            desc=desc,
            parents_sha1=parents.split(),
        )

Return details about a given commit.

Args:
sha1 (str):
The sha1 of the commit to query. If not given, it will return
the details for the latest commit.

Returns:
CommitDetails: Commit details. You can use the instance of the
class to query git tree further.


def options(self, options=None):

		if options is None:
			return self._options

		if not isinstance(options, (list, tuple)):
			raise ValueError('__options__')

		if self._type not in ['base64', 'date', 'datetime', 'decimal', 'float', \
								'int', 'ip', 'md5', 'price', 'string', 'time', \
								'timestamp', 'uint', 'uuid']:
			raise TypeError('can not set __options__ for ' + self._type)

		lOpts = []

		for i in range(len(options)):

			if self._type in ['base64', 'date', 'datetime', 'ip', 'md5', 'time', 'uuid']:

				if not isinstance(options[i], basestring) \
					or not _typeToRegex[self._type].match(options[i]):
					raise ValueError('__options__[%d]' % i)

			elif self._type == 'decimal':

				if isinstance(options[i], Decimal):
					pass

				else:
					try: options[i] = Decimal(options[i])
					except ValueError:
						raise ValueError('__options__[%d]' % i)

			elif self._type == 'float':

				try:
					options[i] = float(options[i])
				except ValueError:
					raise ValueError('__options__[%d]' % i)

			elif self._type in ['int', 'timestamp', 'uint']:

				if not isinstance(options[i], (int, long)):

					if not isinstance(options[i], basestring):
						raise ValueError('__options__[%d]' % i)

					try:
						options[i] = int(options[i], 0)
					except ValueError:
						raise ValueError('__options__[%d]' % i)

				if self._type in ['timestamp', 'uint'] and options[i] < 0:
					raise ValueError('__options__[' + str(i) + ']')

			elif self._type == 'price':

				if isinstance(options[i], Decimal):
					pass

				elif not isinstance(options[i], basestring) or not _typeToRegex['price'].match(options[i]):
					raise ValueError('__options__[%d]' % i)

				options[i] = Decimal(options[i])

			elif self._type == 'string':

				if not isinstance(options[i], basestring):

					try:
						options[i] = str(options[i])
					except ValueError:
						raise ValueError('__options__[%d]' % i)

			else:
				raise TypeError('can not set __options__ for ' + self._type)

			if options[i] in lOpts:
				sys.stderr.write('__options__[' + str(i) + '] is a duplicate')

			else:
				lOpts.append(options[i])

		self._options = lOpts

Options

Sets or gets the list of acceptable values for the Node

Arguments:
options {list} -- A list of valid values

Raises:
TypeError, ValueError

Returns:
None | list


def logged(level=logging.DEBUG):

    def wrap(f):
        _logger = logging.getLogger("{}.{}".format(f.__module__, f.__name__))

        def wrapped_f(*args, **kwargs):
            _logger.log(level, "Called at {} with args = {} and kwargs = {}"
                        .format(datetime.datetime.now(), args, kwargs))
            data = f(*args, **kwargs)
            _logger.log(level, "Done at {} with args = {} and kwargs = {}"
                        .format(datetime.datetime.now(), args, kwargs))
            return data

        return wrapped_f
    return wrap

Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.

Args:
level: Level to log method at. Defaults to DEBUG.


def get_table_map() -> t.Dict:
    fs = GCSFileSystem()
    table_map = {}
    with fs.open(METADATA_URI) as f:
        table_map = json.load(f)
    return table_map

Load and return the table map from dataset-meta.json file.

Returns:
dict: Dictionary containing table names as keys and their metadata as values.


def transfer(self, data):

        settings = self.transfer_settings
        settings.spi_tx_size = len(data)
        self.transfer_settings = settings

        response = ''
        for i in range(0, len(data), 60):
            response += self.sendCommand(commands.SPITransferCommand(data[i:i + 60])).data
            time.sleep(0.01)

        while len(response) < len(data):
            response += self.sendCommand(commands.SPITransferCommand('')).data

        return ''.join(response)

Transfers data over SPI.

Arguments:
data: The data to transfer.

Returns:
The data returned by the SPI device.


def write(name, value):

    def wrapped(func):

        @functools.wraps(func)
        def _decorator(*args, **kwargs):
            existing_env = core.read(name, allow_none=True)
            core.write(name, value)
            func_val = func(*args, **kwargs)
            core.write(name, existing_env)
            return func_val
        return _decorator
    return wrapped

Temporarily change or set the environment variable during the execution of a function.

Args:
name: The name of the environment variable
value: A value to set for the environment variable

Returns:
The function return value.


def _upsample_filters(filters, rate):
    if rate == 1:
        return filters
    filters_up = np.transpose(filters, [2, 3, 0, 1])
    ker = np.zeros([rate, rate], dtype=np.float32)
    ker[0, 0] = 1
    filters_up = np.kron(filters_up, ker)[:, :, :-(rate - 1), :-(rate - 1)]
    filters_up = np.transpose(filters_up, [2, 3, 0, 1])
    return filters_up

Upsamples the filters by a factor of rate along the spatial dimensions.

Args:
filters: [h, w, in_depth, out_depth]. Original filters.
rate: An int, specifying the upsampling rate.

Returns:
filters_up: [h_up, w_up, in_depth, out_depth]. Upsampled filters with
h_up = h + (h - 1) * (rate - 1)
w_up = w + (w - 1) * (rate - 1)
containing (rate - 1) zeros between consecutive filter values along
the filters' spatial dimensions.


def __init__(self,
            density_matrix: np.ndarray,
            measurements: Dict[str, np.ndarray],
            qubit_map: Dict[ops.Qid, int],
            dtype: Type[np.number] = np.complex64):

        super().__init__(measurements)
        self._density_matrix = density_matrix
        self._qubit_map = qubit_map
        self._dtype = dtype

DensityMatrixStepResult.

Args:
density_matrix: The density matrix at this step. Can be mutated.
measurements: The measurements for this step of the simulation.
qubit_map: A map from qid to index used to define the
ordering of the basis in density_matrix.
dtype: The numpy dtype for the density matrix.


def GetKeyByScriptHash(self, script_hash):
    contract = self.GetContract(script_hash)
    if contract:
        return self.GetKey(contract.PublicKeyHash)
    return None

Get the KeyPair belonging to the script hash.

Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.

Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None


def ConvertValueForCsv(pql_value):

  if 'value' in pql_value:
    field = pql_value['value']
  elif 'values' in pql_value:
    field = pql_value['values']
  else:
    field = None

  if field:
    if isinstance(field, list):
      return ','.join(['"%s"' % str(ConvertValueForCsv(single_field))
                       for single_field in field])
    else:
      class_type = ad_manager.AdManagerClassType(pql_value)

      if class_type == 'TextValue':
        return field.replace('"', '""').encode('UTF8')
      elif class_type == 'NumberValue':
        return float(field) if '.' in field else int(field)
      elif class_type == 'DateTimeValue':
        return ConvertDateTimeToOffset(field)
      elif class_type == 'DateValue':
        return date(int(field['date']['year']),
                    int(field['date']['month']),
                    int(field['date']['day'])).isoformat()
      else:
        return field
  else:
    return '-'

Sanitizes a field value from a Value object to a CSV suitable format.

Args:
pql_value: dict a dictionary containing the data for a single field of an
entity.

Returns:
str a CSV writer friendly value formatted by Value.Type.


def __init__(self, prevHash=None, timestamp=None, index=None,
                 consensusData=None, nextConsensus=None,
                 script=None, transactions=None, build_root=False):

        super(Block, self).__init__()
        self.Version = 0
        self.PrevHash = prevHash
        self.Timestamp = timestamp
        self.Index = index
        self.ConsensusData = consensusData
        self.NextConsensus = nextConsensus
        self.Script = script

        if transactions:
            self.Transactions = transactions
        else:
            self.Transactions = []

        if build_root:
            self.RebuildMerkleRoot()

Create an instance.

Args:
prevHash (UInt160):
timestamp (int): seconds since Unix epoch.
index (int): block height.
consensusData (int): uint64.
nextConsensus (UInt160):
script (neo.Core.Witness): script used to verify the block.
transactions (list): of neo.Core.TX.Transaction.Transaction objects.
build_root (bool): flag indicating whether to rebuild the merkle root.


def ReadFrom(self, byte_stream):

    try:
      return self._struct.unpack_from(byte_stream)
    except (TypeError, struct.error) as exception:
      raise IOError('Unable to read byte stream with error: {0!s}'.format(
          exception))

Read values from a byte stream.

Args:
byte_stream (bytes): byte stream.

Returns:
tuple[object, ...]: values copies from the byte stream.

Raises:
IOError: if byte stream cannot be read.
OSError: if byte stream cannot be read.


def loads(s, single=False):

    corpus = etree.fromstring(s)
    if single:
        ds = _deserialize_mrs(next(corpus))
    else:
        ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus)
    return ds

Deserialize MRX string representations

Args:
s (str): a MRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)


def get_from(input_file, property_names):

    with open(input_file) as f:
        feature_collection = geojson.load(f)

    features = feature_collection['features']
    values = [tuple([feat['properties'].get(x)
                     for x in property_names]) for feat in features]

    return values

Reads a geojson and returns a list of value tuples, each value corresponding to a
property in property_names.

Args:
input_file (str): File name.
property_names: List of strings; each string is a property name.

Returns:
List of value tuples.


def _deferred_dependencies(self):
    return self._self_unconditional_deferred_dependencies

A dictionary with deferred dependencies.

Stores restorations for other Trackable objects on which this object
may eventually depend. May be overridden by sub-classes (e.g. Optimizers use
conditional dependencies based the current graph, and so need separate
management of deferred dependencies too).

Returns:
A dictionary mapping from local name to a list of CheckpointPosition
objects.


def predict_features(self, df_features, df_target, idx=0, **kwargs):

        X = df_features.values
        y = df_target.values
        regressor = DecisionTreeRegressor()
        regressor.fit(X, y)

        return regressor.feature_importances_

For one variable, predict its neighbouring nodes.

Args:
df_features (pandas.DataFrame):
df_target (pandas.Series):
idx (int): (optional) for printing purposes
kwargs (dict): additional options for algorithms

Returns:
list: scores of each feature relatively to the target


def report_conversion_error(self, element_path: str, msg: str) -> None:

Reports the given error during FHIR conversion.

This indicates that the resource does not fully comply with the FHIR
specification or profile, and the field could not be converted to the target
structure. Data may have been lost during the conversion.

Args:
element_path: The path to the field where the issue occurred.
msg: The error message produced.


def package_in_memory(cls, workflow_name, workflow_files):

        s = StringIO()
        p = cls(s, workflow_name, meta_data=[])
        p.add_bpmn_files_by_glob(workflow_files)
        p.create_package()
        return s.getvalue()

Generates wf packages from workflow diagrams.

Args:
workflow_name: Name of wf
workflow_files:  Diagram  file.

Returns:
Workflow package (file like) object


def verify_mfa(self, mfa_token):
    response = self.resource.verify_mfa({'mfa_token': mfa_token})
    return ((response['valid'] == True) or (response['valid'] == 'true'))

Verify an SMS or TOTP MFA token for this user.

Args:
mfa_token (str): An alphanumeric code from either a User's TOTP
application or sent to them via SMS.

Returns:
True if the mfa_token is valid, False otherwise.


def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern):
    submissions = self._storage_client.list_blobs(prefix=os.path.join(self._round_name, dir_suffix))
    return {id_pattern.format(idx): SubmissionDescriptor(path=s, participant_id=participant_from_submission_path(s)) for (idx, s) in enumerate(submissions)}

Loads list of submissions from the directory.

Args:
dir_suffix: suffix of the directory where submissions are stored,
one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR
or DEFENSE_SUBDIR.
id_pattern: pattern which is used to generate (internal) IDs
for submissins. One of the following constants: ATTACK_ID_PATTERN,
TARGETED_ATTACK_ID_PATTERN or DEFENSE_ID_PATTERN.

Returns:
dictionary with all found submissions


def split(x, split_dim, num_or_size_splits, name=None):
    return SplitOperation(x, split_dim, num_or_size_splits, name=name).outputs

Like tf.split.

Args:
x: a Tensor
split_dim: a Dimension in x.shape.dims
num_or_size_splits: either an integer dividing split_dim.size
or a list of integers adding up to split_dim.size
name: an optional string
Returns:
a list of Tensors.


def find_code_and_splits(object_name: str, base_path: str, buffer: Optional[dict]=None):
    if buffer is None:
        buffer = {}
    if (object_name, base_path) in buffer:
        lines, code, code_splits = buffer[object_name, base_path]
    else:
        code, (lines, target_start_index, target_end_index) = find_code_in_transformers(object_name, base_path=base_path, return_indices=True)
        indent = get_indent(code)
        code_splits = split_code_into_blocks(lines, target_start_index, target_end_index, len(indent) + 4, backtrace=True)
        buffer[object_name, base_path] = (lines, code, code_splits)
    return (lines, code, code_splits)

Find the code of an object (specified by `object_name`) and split it into blocks.

Args:
object_name (`str`):
The name of the object, e.g. `transformers.models.bert.modeling_bert.BertAttention` or
`tests.models.llama.test_modeling_llama.LlamaModelTest.test_config`.
base_path (`str`):
The path to the base directory within which the search will be performed. It could be either
`TRANSFORMERS_PATH` or `MODEL_TEST_PATH`.
buffer (`dict`, *optional*):
The buffer used to store the previous results in order to speed up the process.

Returns:
lines (`List[str]`):
The lines of the whole file where the object is defined.
code (`str`):
The object's code.
code_splits (`List[Tuple[str, int, int]]`):
`code` splitted into blocks. See `split_code_into_blocks`.


def compute_mup_vector(config):
    intermediate_size = config.mamba_d_ssm if config.mamba_d_ssm is not None else int(config.mamba_expand * config.hidden_size)
    groups_time_state_size = config.mamba_n_groups * config.mamba_d_state
    num_heads = config.mamba_n_heads
    zxbcdt_multipliers = config.ssm_multipliers
    vector_shape = 2 * intermediate_size + 2 * groups_time_state_size + num_heads
    mup_vector = torch.ones(1, 1, vector_shape)
    mup_vector[:, :, :intermediate_size] *= zxbcdt_multipliers[0]
    mup_vector[:, :, intermediate_size:2 * intermediate_size] *= zxbcdt_multipliers[1]
    mup_vector[:, :, 2 * intermediate_size:2 * intermediate_size + groups_time_state_size] *= zxbcdt_multipliers[2]
    mup_vector[:, :, 2 * intermediate_size + groups_time_state_size:2 * intermediate_size + 2 * groups_time_state_size] *= zxbcdt_multipliers[3]
    mup_vector[:, :, 2 * intermediate_size + 2 * groups_time_state_size:] *= zxbcdt_multipliers[4]
    return mup_vector

Computes the MuP vector based on model configuration.

FalconH1 applies different MuP multiplier for each dimension of the hidden states.
The MuP vector is partitioned into chunks, and each chunk is multiplied with its
corresponding projected dimension.

Args:
config: FalconH1Config object

Returns:
torch.Tensor: The computed MuP vector


def build_vocab(self, texts, verbose=1, **kwargs):
    if self.has_vocab:
        logger.warn('Tokenizer already has existing vocabulary. Overriding and building new vocabulary.')
    progbar = Progbar(len(texts), verbose=verbose, interval=0.25)
    count_tracker = utils._CountTracker()
    self._token_counts.clear()
    self._num_texts = len(texts)
    for token_data in self.token_generator(texts, **kwargs):
        (indices, token) = (token_data[:(- 1)], token_data[(- 1)])
        count_tracker.update(indices)
        self._token_counts[token] += 1
        progbar.update(indices[0])
    self.create_token_indices(self._token_counts.keys())
    count_tracker.finalize()
    self._counts = count_tracker.counts
    progbar.update(len(texts))

Builds the internal vocabulary and computes various statistics.

Args:
texts: The list of text items to encode.
verbose: The verbosity level for progress. Can be 0, 1, 2. (Default value = 1)
**kwargs: The kwargs for `token_generator`.


def collect_human_trajectory(env, device):

    obs = env.reset()

    env.set_robot_joint_positions([0, -1.18, 0.00, 2.18, 0.00, 0.57, 1.5708])

    env.viewer.set_camera(camera_id=2)
    env.render()

    is_first = True

    reset = False
    task_completion_hold_count = -1
    device.start_control()
    while not reset:
        state = device.get_controller_state()
        dpos, rotation, grasp, reset = (
            state["dpos"],
            state["rotation"],
            state["grasp"],
            state["reset"],
        )

        current = env._right_hand_orn
        drotation = current.T.dot(rotation)
        dquat = T.mat2quat(drotation)
        grasp = grasp - 1.
        action = np.concatenate([dpos, dquat, [grasp]])

        obs, reward, done, info = env.step(action)

        if is_first:
            is_first = False

            initial_mjstate = env.sim.get_state().flatten()
            xml_str = env.model.get_xml()
            env.reset_from_xml_string(xml_str)
            env.sim.reset()
            env.sim.set_state_from_flattened(initial_mjstate)
            env.sim.forward()
            env.viewer.set_camera(camera_id=2)

        env.render()

        if task_completion_hold_count == 0:
            break

        if env._check_success():
            if task_completion_hold_count > 0:
                task_completion_hold_count -= 1
            else:
                task_completion_hold_count = 10
        else:
            task_completion_hold_count = -1

    env.close()

Use the device (keyboard or SpaceNav 3D mouse) to collect a demonstration.
The rollout trajectory is saved to files in npz format.
Modify the DataCollectionWrapper wrapper to add new fields or change data formats.

Args:
env: environment to control
device (instance of Device class): to receive controls from the device


def annotate_op(self, op):

        if isinstance(op, Label):
            return op
        else:
            return AnnotatedOp(self, op.name, op.arg)

Takes a bytecode operation (:class:`Op`) and annotates it using the
data contained in this code object.

Arguments:
op(Op): An :class:`Op` instance.

Returns:
AnnotatedOp: An annotated bytecode operation.


def configure(self, cfg, handler, path=""):

        for name, attr in handler.attributes():
            if cfg.get(name) is not None:
                continue
            if attr.expected_type not in [list, dict]:
                cfg[name] = self.set(handler, attr, name, path, cfg)
            elif attr.default is None and not hasattr(handler, "configure_%s" % name):
                self.action_required.append(("%s.%s: %s" % (path, name, attr.help_text)).strip("."))

        for name, attr in handler.attributes():
            if cfg.get(name) is not None:
                continue
            if hasattr(handler, "configure_%s" % name):
                fn = getattr(handler, "configure_%s" % name)
                fn(self, cfg, "%s.%s"% (path, name))
                if attr.expected_type in [list, dict] and not cfg.get(name):
                    try:
                        del cfg[name]
                    except KeyError:
                        pass

Start configuration process for the provided handler

Args:
cfg (dict): config container
handler (config.Handler class): config handler to use
path (str): current path in the configuration progress


def ValidateDict(self, dict_value, outer_messages):
    valid_dict = {}
    for f in self.fields:
        if f.name in dict_value:
            valid_dict[f.name] = self._ValidateField(f, dict_value[f.name], outer_messages)
        elif not f.optional:
            raise NameError("Mandatoray field missing in message '%s': %s" % (self.name, f.name))
    return valid_dict

Validate a dictionary value.

It checks whether all individual fields of |dict_value| are valid, i.e.
all required fields exist and the values of fields correspond to their
types.

Args:
dict_value: Dictionary value to validate.
outer_messages: Messages visible from the scope of |dict_value|.
Returns:
Dictionary value validated.
Raises:
NameError: If any required fields are missed.


def non_slot_devices(self, var_list):
    raise NotImplementedError('must be implemented in descendants')

Device(s) for non-slot variables.

DEPRECATED: TF 1.x ONLY.

This method returns non-slot devices where non-slot variables are placed.
Users can create non-slot variables on these devices by using a block:

```python
with tf.distribute.StrategyExtended.colocate_vars_with(tf.distribute.StrategyExtended.non_slot_devices(...)):
...
```

Args:
var_list: The list of variables being optimized, needed with the
default `tf.distribute.Strategy`.
Returns:
A sequence of devices for non-slot variables.


def n_choose_k(n, k):
    if (n == 0):
        return 0
    return reduce((lambda x, y: ((x * y[0]) / y[1])), zip(range(((n - k) + 1), (n + 1)), range(1, (k + 1))), 1)

Return the number of combinations for n choose k.

Args:
n (int): the total number of options .
k (int): The number of elements.

Returns:
int: returns the binomial coefficient


def __init__(self, config, n_bins=16, mlp_dim=256, min_depth=0.001, max_depth=10):
    super().__init__()
    self.in_features = config.bottleneck_features
    self.bin_centers_type = config.bin_centers_type
    self.min_depth = min_depth
    self.max_depth = max_depth
    self.conv1 = nn.Conv2d(self.in_features, mlp_dim, 1, 1, 0)
    self.act1 = nn.ReLU(inplace=True)
    self.conv2 = nn.Conv2d(mlp_dim, n_bins, 1, 1, 0)
    self.act2 = nn.ReLU(inplace=True) if self.bin_centers_type == 'normed' else nn.Softplus()

Bin center regressor network.

Can be "normed" or "unnormed". If "normed", bin centers are bounded on the (min_depth, max_depth) interval.

Args:
config (`int`):
Model configuration.
n_bins (`int`, *optional*, defaults to 16):
Number of bin centers.
mlp_dim (`int`, *optional*, defaults to 256):
Hidden dimension.
min_depth (`float`, *optional*, defaults to 1e-3):
Min depth value.
max_depth (`float`, *optional*, defaults to 10):
Max depth value.


def _valuelistToBytestring(valuelist, numberOfRegisters):

    MINVALUE = 0
    MAXVALUE = 65535

    _checkInt(numberOfRegisters, minvalue=1, description='number of registers')

    if not isinstance(valuelist, list):
        raise TypeError('The valuelist parameter must be a list. Given {0!r}.'.format(valuelist))

    for value in valuelist:
        _checkInt(value, minvalue=MINVALUE, maxvalue=MAXVALUE, description='elements in the input value list')

    _checkInt(len(valuelist), minvalue=numberOfRegisters, maxvalue=numberOfRegisters, \
        description='length of the list')

    numberOfBytes = _NUMBER_OF_BYTES_PER_REGISTER * numberOfRegisters

    bytestring = ''
    for value in valuelist:
        bytestring += _numToTwoByteString(value, signed=False)

    assert len(bytestring) == numberOfBytes
    return bytestring

Convert a list of numerical values to a bytestring.

Each element is 'unsigned INT16'.

Args:
* valuelist (list of int): The input list. The elements should be in the range 0 to 65535.
* numberOfRegisters (int): The number of registers. For error checking.

Returns:
A bytestring (str). Length = 2*numberOfRegisters

Raises:
TypeError, ValueError


def __init__(self, channel):

        self.ListInstances = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/ListInstances",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.ListInstancesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.ListInstancesResponse.FromString,
        )
        self.GetInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/GetInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.GetInstanceRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.Instance.FromString,
        )
        self.CreateInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/CreateInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.CreateInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )
        self.UpdateInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/UpdateInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.UpdateInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )
        self.DeleteInstance = channel.unary_unary(
            "/google.cloud.redis.v1beta1.CloudRedis/DeleteInstance",
            request_serializer=google_dot_cloud_dot_redis__v1beta1_dot_proto_dot_cloud__redis__pb2.DeleteInstanceRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )

Constructor.

Args:
channel: A grpc.Channel.


def start(self, channel):

        super(TileBasedVirtualDevice, self).start(channel)

        for tile in self._tiles.values():
            tile.start(channel=channel)

Start running this virtual device including any necessary worker threads.

Args:
channel (IOTilePushChannel): the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface


def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):

    if get_dirs is None and get_files is None:
        get_dirs = True
        get_files = True

    source_dir = os.path.join(settings.BASE_DIR, 'app', dir_name)

    dirs = []

    for dir_or_file_name in os.listdir(source_dir):
        path = os.path.join(source_dir, dir_or_file_name)
        if hide_ignored and dir_or_file_name.startswith('_'):
            continue
        is_dir = os.path.isdir(path)
        if get_dirs and is_dir or get_files and not is_dir:
            dirs.append(dir_or_file_name)

    return dirs

Return list of all dirs and files inside given dir.

Also can filter contents to return only dirs or files.

Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Return files list
- hide_ignored: Exclude files and dirs with initial underscore


def delete(self, **options):

    fut = delete_async(self.key(), **options)
    fut.get_result()

Permanently delete this blob from Blobstore.

Args:
**options: Options for create_rpc().


def __init__(self, particle_kind="bead"):

        super(Bead, self).__init__()

        self.add(mb.Particle(name=particle_kind), particle_kind)

        self.add(mb.Port(anchor=self.labels[particle_kind]), 'up')
        self['up'].translate(np.array([0, 0.7, 0]))

        self.add(mb.Port(anchor=self.labels[particle_kind]), 'down')
        self['down'].translate(np.array([0, -0.7, 0]))

Initialize a Bead object.

Args:
particle_kind (str): Descriptive name for the Bead.


def has_member(self, device_object):

        if device_object.tag == "computer":
            container_search = "computers/computer"
        elif device_object.tag == "mobile_device":
            container_search = "mobile_devices/mobile_device"
        else:
            raise ValueError

        return len([device for device in self.findall(container_search) if
                    device.findtext("id") == device_object.id]) is not 0

Return bool whether group has a device as a member.

Args:
device_object (Computer or MobileDevice). Membership is
determined by ID, as names can be shared amongst devices.


def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
    if (bai_field_variation not in (FieldVariations.search, FieldVariations.raw)):
        raise ValueError('Non supported field variation "{}".'.format(bai_field_variation))
    normalized_author_name = normalize_name(node_value).strip('.')
    if (ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ElasticSearchVisitor.BAI_REGEX.match(node_value)):
        return [((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)]
    elif ((not whitespace.search(normalized_author_name)) and query_bai_field_if_dots_in_name and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ('.' in normalized_author_name)):
        return ([((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)] + force_list(ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']))
    else:
        return None

Generates new fieldnames in case of BAI query.

Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)
if dots exist in the name and name contains no whitespace.

Returns:
list: Fieldnames to query on, in case of BAI query or None, otherwise.

Raises:
ValueError, if ``field_variation`` is not one of ('search', 'raw').


def assert_type(__x, __t) -> None:
    del __x, __t

Prevent runtime errors from assert_type statements.

assert_type is handled internally by pytype at type-checking time; it should
do nothing at runtime.

Usage example:

```
import pytype_extensions
assert_type = pytype_extensions.assert_type

x = 3
assert_type(x, int)
```

Args:
__x: The object to make the type assertion about.
__t: The type we want to assert.


def _tensor_product(t1, t2):
    return tf.matmul(tf.expand_dims(t1, axis=(- 1)), tf.expand_dims(t2, axis=(- 2)))

Computes the outer product of two possibly batched vectors.

Args:
t1: A `tf.Tensor` of shape `[..., n]`.
t2: A `tf.Tensor` of shape `[..., m]`.

Returns:
A tensor of shape `[..., n, m]` with matching batch dimensions, let's call
it `r`, whose components are:

```None
r[..., i, j] = t1[..., i] * t2[..., j]
```


def find_matching(self) -> Dict[(TLeft, TRight)]:
    directed_graph = {}
    for (left, right) in self._edges:
        tail = (LEFT, left)
        head = (RIGHT, right)
        if (tail not in directed_graph):
            directed_graph[tail] = {head}
        else:
            directed_graph[tail].add(head)
    matching = HopcroftKarp(directed_graph).maximum_matching()
    return dict(((tail[1], head[1]) for (tail, head) in matching.items() if (tail[0] == LEFT)))

Finds a matching in the bipartite graph.

This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.

Returns:
A dictionary where each edge of the matching is represented by a key-value pair
with the key being from the left part of the graph and the value from te right part.


def _GetMember(component, args):
    members = dir(component)
    arg = args[0]
    arg_names = [arg, arg.replace('-', '_')]
    for arg_name in arg_names:
        if arg_name in members:
            return (getattr(component, arg_name), [arg], args[1:])
    raise FireError('Could not consume arg:', arg)

Returns a subcomponent of component by consuming an arg from args.

Given a starting component and args, this function gets a member from that
component, consuming one arg in the process.

Args:
component: The component from which to get a member.
args: Args from which to consume in the search for the next component.
Returns:
component: The component that was found by consuming an arg.
consumed_args: The args that were consumed by getting this member.
remaining_args: The remaining args that haven't been consumed yet.
Raises:
FireError: If we cannot consume an argument to get a member.


def load_variants(adapter, vcf_obj, case_obj, skip_case_id=False, gq_treshold=None,
                  max_window=3000, variant_type='snv'):

    if variant_type == 'snv':
        nr_variants = case_obj['nr_variants']
    else:
        nr_variants = case_obj['nr_sv_variants']

    nr_inserted = 0
    case_id = case_obj['case_id']
    if skip_case_id:
        case_id = None

    with click.progressbar(vcf_obj, label="Inserting variants",length=nr_variants) as bar:

        variants = (build_variant(variant,case_obj,case_id, gq_treshold) for variant in bar)

    if variant_type == 'sv':
        for sv_variant in variants:
            if not sv_variant:
                continue
            adapter.add_structural_variant(variant=sv_variant, max_window=max_window)
            nr_inserted += 1

    if variant_type == 'snv':
        nr_inserted = adapter.add_variants(variants)

    LOG.info("Inserted %s variants of type %s", nr_inserted, variant_type)

    return nr_inserted

Load variants for a family into the database.

Args:
adapter (loqusdb.plugins.Adapter): initialized plugin
case_obj(Case): dict with case information
nr_variants(int)
skip_case_id (bool): whether to include the case id on variant level
or not
gq_treshold(int)
max_window(int): Specify the max size for sv windows
variant_type(str): 'sv' or 'snv'

Returns:
nr_inserted(int)


def _process_arguments(arguments):

    if arguments is None: return ""
    result = ""
    for key, value in arguments.items():
        if not key.startswith("bokeh-"):
            result += "&{}={}".format(quote_plus(str(key)), quote_plus(str(value)))
    return result

Return user-supplied HTML arguments to add to a Bokeh server URL.

Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL

Returns:
str


def getFingerprintForExpression(self, body, sparsity=1.0):

        return self._expressions.resolveExpression(self._retina, body, sparsity)

Resolve an expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
sparsity, float: Sparsify the resulting expression to this percentage (optional)
Returns:
Fingerprint
Raises:
CorticalioException: if the request was not successful


def ExpandGlobs(path, opts=None):
    precondition.AssertType(path, Text)
    if (not path):
        raise ValueError('Path is empty')
    if (not _IsAbsolutePath(path, opts)):
        raise ValueError(("Path '%s' is not absolute" % path))
    if ((opts is not None) and (opts.pathtype == rdf_paths.PathSpec.PathType.REGISTRY)):
        (root_dir, tail) = path.replace('\\', '/').lstrip('/').split('/', 1)
        components = list(ParsePath(tail, opts=opts))
    else:
        (drive, tail) = os.path.splitdrive(path)
        root_dir = os.path.join(drive, os.path.sep).upper()
        components = list(ParsePath(tail[1:], opts=opts))
    return _ExpandComponents(root_dir, components)

Performs glob expansion on a given path.

Path can contain regular glob elements (such as `**`, `*`, `?`, `[a-z]`). For
example, having files `foo`, `bar`, `baz` glob expansion of `ba?` will yield
`bar` and `baz`.

Args:
path: A path to expand.
opts: A `PathOpts` object.

Returns:
Generator over all possible glob expansions of a given path.

Raises:
ValueError: If given path is empty or relative.


def subdivide_with(self, branches, join_function, name='mixed'):
    return _subdivide_context(self, branches, join_function, name)

Branches this pretty tensor and uses an explicit join function.

This should be used in a with statement, for example to fork and join with
a sum:

with pt.subdivide_with(2, tf.add_n) as [a, b]:
a...
b...

Args:
branches: The number of branches.
join_function: A function to use when rejoining.
name: A base name for this branch.
Returns:
A python context manager to use in a with statement that supplies a
sequence of tensors with one per branch.
Raises:
ValueError: if join_function is None.


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

    if not self.async:
      raise UnexpectedPipelineError(
          'May only call get_callback_task() method for asynchronous pipelines.')

    params = kwargs.get('params', {})
    kwargs['params'] = params
    params['pipeline_id'] = self._pipeline_key.name()
    kwargs['url'] = self.base_path + '/callback'
    kwargs['method'] = 'POST'
    return taskqueue.Task(*args, **kwargs)

Returns a task for calling back this Pipeline.

Args:
params: Keyword argument containing a dictionary of key/value pairs
that will be passed to the callback when it is executed.
args, kwargs: Passed to the taskqueue.Task constructor. Use these
arguments to set the task name (for idempotence), etc.

Returns:
A taskqueue.Task instance that must be enqueued by the caller.


def do_dock6_flexible(self, ligand_path, force_rerun=False):

        log.debug('{}: running DOCK6...'.format(self.id))

        ligand_name = os.path.basename(ligand_path).split('.')[0]
        in_name = op.join(self.dock_dir, "{}_{}_flexdock.in".format(self.id, ligand_name))
        out_name = op.join(self.dock_dir, "{}_{}_flexdock.out".format(self.id, ligand_name))

        conformers_out = op.join(self.dock_dir, '{}_{}_flexdock_conformers.mol2'.format(self.id, ligand_name))
        scored_out = op.join(self.dock_dir, '{}_{}_flexdock_scored.mol2'.format(self.id, ligand_name))
        ranked_out = op.join(self.dock_dir, '{}_{}_flexdock_ranked.mol2'.format(self.id, ligand_name))

        if ssbio.utils.force_rerun(flag=force_rerun, outfile=ranked_out):
            with open(in_name, "w") as f:
                dock_text = .format(ligand_path, op.basename(self.sphsel_path), op.splitext(op.basename(self.grid_path))[0],
                   op.splitext(op.basename(self.grid_path))[0], self.amb_file, self.flex1_file, self.flex2_file,
                   self.id, ligand_name)

                f.write(dock_text)

            os.chdir(self.dock_dir)
            cmd = "dock6 -i {} -o {} -v".format(in_name, out_name)
            os.system(cmd)

        if ssbio.utils.is_non_zero_file(ranked_out):
            self.dock_flexible_outfile = out_name
            self.dock_flexible_conformers_result = conformers_out
            self.dock_flexible_scored_result = scored_out
            log.debug('{}: successful docking!'.format(self.dock_flexible_outfile))
        else:
            log.error('{}+{}: empty DOCK6 ranked file, execution error (or ligand failed to dock)'.format(self.id,
                                                                                op.basename(ligand_path)))

Dock a ligand to the protein.

Args:
ligand_path (str): Path to ligand (mol2 format) to dock to protein
force_rerun (bool): If method should be rerun even if output file exists


def modify_object(self, modification, obj):

        d = obj.as_dict()
        self.modify(modification, d)
        return obj.from_dict(d)

Modify an object that supports pymatgen's as_dict() and from_dict API.

Args:
modification (dict): Modification must be {action_keyword :
settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}}
obj (object): Object to modify


def series_expand(self, param: Symbol, about, order: int):

        s = self.shape
        emats = zip(*[o.series_expand(param, about, order)
                      for o in self.matrix.ravel()])
        return tuple((Matrix(np_array(em).reshape(s)) for em in emats))

Expand the matrix expression as a truncated power series in a scalar
parameter.

Args:
param: Expansion parameter.
about (.Scalar): Point about which to expand.
order: Maximum order of expansion >= 0

Returns:
tuple of length (order+1), where the entries are the expansion
coefficients.


def load(tiff_filename):

    tiff_filename = os.path.expanduser(tiff_filename)

    try:
        img = tiff.imread(tiff_filename)
    except Exception as e:
        raise ValueError("Could not load file {0} for conversion."
                         .format(tiff_filename))
        raise

    return numpy.array(img)

Import a TIFF file into a numpy array.

Arguments:
tiff_filename:  A string filename of a TIFF datafile

Returns:
A numpy array with data from the TIFF file


def Dump(obj):

  text = yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True)

  if compatibility.PY2:
    text = text.decode("utf-8")

  return text

Stringifies a Python object into its YAML representation.

Args:
obj: A Python object to convert to YAML.

Returns:
A YAML representation of the given object.


def Verify(self, public_key):
    if (self.digest_type != self.HashType.SHA256):
        raise rdfvalue.DecodeError('Unsupported digest.')
    if (self.signature_type not in [self.SignatureType.RSA_PKCS1v15, self.SignatureType.RSA_PSS]):
        raise rdfvalue.DecodeError('Unsupported signature type.')
    try:
        public_key.Verify(self.data, self.signature)
    except InvalidSignature as e:
        raise rdfvalue.DecodeError(('Could not verify blob. Error: %s' % e))
    return True

Verify the data in this blob.

Args:
public_key: The public key to use for verification.

Returns:
True when verification succeeds.

Raises:
rdfvalue.DecodeError if the data is not suitable verified.