code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def plot(self, ax=None, legend=None, return_fig=False, **kwargs):
if (ax is None):
fig = plt.figure(figsize=(2, 10))
ax = fig.add_subplot(111)
return_ax = False
else:
return_ax = True
d = None
if (legend is not None):
try:
d = legend.get_decor(self)
... | Plot a curve.
Args:
ax (ax): A matplotlib axis.
legend (striplog.legend): A legend. Optional.
return_fig (bool): whether to return the matplotlib figure.
Default False.
kwargs: Arguments for ``ax.set()``
Returns:
ax. If you passed in an ax, otherwise None. | codesearchnet |
def close(self, reason=None):
with self._closing:
if self._closed:
return
if self.is_active:
_LOGGER.debug("Stopping consumer.")
self._consumer.stop()
self._consumer = None
_LOGGE... | Stop consuming messages and shutdown all helper threads.
This method is idempotent. Additional calls will have no effect.
Args:
reason (Any): The reason to close this. If None, this is considered
an "intentional" shutdown. This is passed to the callbacks
specified via :meth:`add_close_callback`. | juraj-google-style |
def set_custom_predict_fn(self, predict_fn):
self.delete('estimator_and_spec')
self.store('custom_predict_fn', predict_fn)
self.set_inference_address('custom_predict_fn')
if (not self.has_model_name()):
self.set_model_name('1')
return self | Sets a custom function for inference.
Instead of using TF Serving to host a model for WIT to query, WIT can
directly use a custom function as the model to query. In this case, the
provided function should accept example protos and return:
- For classification: A 2D list of numbers. The first dimension is for
each exam... | codesearchnet |
def get_flat_size(self):
return sum((np.prod(v.get_shape().as_list()) for v in self.variables.values())) | Returns the total length of all of the flattened variables.
Returns:
The length of all flattened variables concatenated. | codesearchnet |
def delay(self, n, start_time):
if ((n > self.max_retries) or ((n > self.min_retries) and ((time.time() - start_time) > self.max_retry_period))):
return (- 1)
return min((math.pow(self.backoff_factor, (n - 1)) * self.initial_delay), self.max_delay) | Calculate delay before the next retry.
Args:
n: the number of current attempt. The first attempt should be 1.
start_time: the time when retry started in unix time.
Returns:
Number of seconds to wait before next retry. -1 if retry should give up. | codesearchnet |
def build_input_fns(data_dir, batch_size):
with open(download(data_dir, 'vocab.pkl'), 'r') as f:
words_to_idx = pickle.load(f)
num_words = len(words_to_idx)
vocabulary = ([None] * num_words)
for (word, idx) in words_to_idx.items():
vocabulary[idx] = word
def train_input_fn():
... | Builds iterators for train and evaluation data.
Each object is represented as a bag-of-words vector.
Arguments:
data_dir: Folder in which to store the data.
batch_size: Batch size for both train and evaluation.
Returns:
train_input_fn: A function that returns an iterator over the training data.
eval_input_fn: A func... | codesearchnet |
def _GetByteStreamOperation(self):
byte_order_string = self.GetStructByteOrderString()
format_string = self.GetStructFormatString()
if (not format_string):
return None
format_string = ''.join([byte_order_string, format_string])
return byte_operations.StructOperation(format_string) | Retrieves the byte stream operation.
Returns:
ByteStreamOperation: byte stream operation or None if unable to determine. | codesearchnet |
def cosmic_link(variant_obj):
cosmic_ids = variant_obj.get('cosmic_ids')
if not cosmic_ids:
return None
else:
cosmic_id = cosmic_ids[0]
url_template = ("https:
return url_template.format(cosmic_id) | Compose link to COSMIC Database.
Args:
variant_obj(scout.models.Variant)
Returns:
url_template(str): Link to COSMIIC database if cosmic id is present | juraj-google-style |
def rgb_to_yuv(images):
images = ops.convert_to_tensor(images, name='images')
kernel = ops.convert_to_tensor(_rgb_to_yuv_kernel, dtype=images.dtype, name='kernel')
ndims = images.get_shape().ndims
return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]]) | Converts one or more images from RGB to YUV.
Outputs a tensor of the same shape as the `images` tensor, containing the YUV
value of the pixels.
The output is only well defined if the value in images are in [0, 1].
There are two ways of representing an image: [0, 255] pixel values range or
[0, 1] (as float) pixel value... | github-repos |
def predict_raw(self, X):
b = np.ones((X.shape[0], 1))
w2 = self.w[-(self.h + 1):].reshape(self.h + 1, 1)
w1 = self.w[:-(self.h + 1)].reshape(self.i + 1, self.h)
if X.shape[1] > self.i:
X = X[:, :self.i]
elif ... | Predict targets for a feature matrix.
Args:
X (np.array of float): feature matrix for prediction | juraj-google-style |
def _parse_options(self, options):
for key in ('username', 'client_name', 'client_id', 'client_secret', 'trusted', 'logout_uri'):
value = options.get(key)
if (value is not None):
self.fields[key] = value
username = self.fields.pop('username', None)
if (username is not None):
... | Parse the command's options.
Arguments:
options (dict): Options with which the command was called.
Raises:
CommandError, if a user matching the provided username does not exist. | codesearchnet |
def parse_non_selinux(parts):
(links, owner, group, last) = parts
result = {'links': int(links), 'owner': owner, 'group': group}
if (',' in last[:4]):
(major, minor, rest) = last.split(None, 2)
result['major'] = int(major.rstrip(','))
result['minor'] = int(minor)
else:
(s... | Parse part of an ls output line that isn't selinux.
Args:
parts (list): A four element list of strings representing the initial
parts of an ls line after the permission bits. The parts are link
count, owner, group, and everything else.
Returns:
A dict containing links, owner, group, date, and name. If the line
repres... | codesearchnet |
def expand_dims(self, image):
self._ensure_format_supported(image)
if isinstance(image, PIL.Image.Image):
return image
if is_torch_tensor(image):
image = image.unsqueeze(0)
else:
image = np.expand_dims(image, axis=0)
return image | Expands 2-dimensional `image` to 3 dimensions.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to expand. | github-repos |
def dbmax_stddev(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 `dbmax_stddev`'.format(value))
self._... | Corresponds to IDD Field `dbmax_stddev`
Standard deviation of extreme annual maximum dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax_stddev`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a val... | juraj-google-style |
def rename_next_state_fluent(name: str) -> str:
i = name.index('/')
functor = name[:i-1]
arity = name[i+1:]
return "{}/{}".format(functor, arity) | Returns next state fluent canonical name.
Args:
name (str): The current state fluent name.
Returns:
str: The next state fluent name. | juraj-google-style |
def __init__(self, context):
self._logdir = context.logdir
self._db_uri = context.db_uri
self._window_title = context.window_title
self._multiplexer = context.multiplexer
self._db_connection_provider = context.db_connection_provider
self._assets_zip_provider = context.assets_zip_provider | Instantiates CorePlugin.
Args:
context: A base_plugin.TBContext instance. | juraj-google-style |
def __init__(self, xid=None, flags=ConfigFlag.OFPC_FRAG_NORMAL,
miss_send_len=ControllerMaxLen.OFPCML_NO_BUFFER):
super().__init__(xid, flags, miss_send_len)
self.header.message_type = Type.OFPT_SET_CONFIG | Create a SetConfig with the optional parameters below.
Args:
xid (int): xid to be used on the message header.
flags (:class:`~pyof.v0x01.controller2switch.common.ConfigFlag`):
OFPC_* flags.
miss_send_len (int): UBInt16 max bytes of new flow that the
datapath should send to the controller. | juraj-google-style |
def query(self, terms=None, negated_terms=None):
if terms is None:
terms = []
matches_all = 'owl:Thing' in terms
if negated_terms is None:
negated_terms = []
termset = set(terms)
negated_termset = set(negated_terms)
matches = []
n... | Basic boolean query, using inference.
Arguments:
- terms: list
list of class ids. Returns the set of subjects that have at least one inferred annotation to each of the specified classes.
- negated_terms: list
list of class ids. Filters the set of subjects so that there are no inferred annotations to any of the spe... | juraj-google-style |
def check_schema_equal(left: Union['bigquery.TableSchema', 'bigquery.TableFieldSchema'], right: Union['bigquery.TableSchema', 'bigquery.TableFieldSchema'], *, ignore_descriptions: bool=False, ignore_field_order: bool=False) -> bool:
if type(left) != type(right) or not isinstance(left, (bigquery.TableSchema, bigquer... | Check whether schemas are equivalent.
This comparison function differs from using == to compare TableSchema
because it ignores categories, policy tags, descriptions (optionally), and
field ordering (optionally).
Args:
left (~apache_beam.io.gcp.internal.clients.bigquery.bigquery_v2_messages.TableSchema, ~apache_beam.i... | github-repos |
def extrapolate_points(points, n_points):
points = points[:n_points]
lat = []
lon = []
last = None
for point in points:
if last is not None:
lat.append(last.lat-point.lat)
lon.append(last.lon-point.lon)
last = point
dts = np.mean([p.dt for p in point... | Extrapolate a number of points, based on the first ones
Args:
points (:obj:`list` of :obj:`Point`)
n_points (int): number of points to extrapolate
Returns:
:obj:`list` of :obj:`Point` | juraj-google-style |
def __lt__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (
self._tp__get_typed_properties()
< other._tp__get_typed_properties()
) | Test if self is less than an object of the same class.
Args:
other: The object to compare against.
Returns:
True if self is less than other; else False.
Raises:
TypeError: Raised if the objects are not of the same class. | juraj-google-style |
def get_feature_variable_double(self, feature_key, variable_key, user_id, attributes=None):
variable_type = entities.Variable.Type.DOUBLE
return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes) | Returns value for a certain double variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Double value of the var... | codesearchnet |
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
return SymbolWildcard(name)
return SymbolWildcard(symbol_type, variable_name=name) | Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
Returns:
A `SymbolWildcard` that matches the *symbol_type*. | juraj-google-style |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
self._ParseLogonApplications(parser_mediator, registry_key)
self._ParseRegisteredDLLs(parser_mediator, registry_key) | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | juraj-google-style |
def HandleMessage(self, message):
self._is_active = True
try:
action_cls = actions.ActionPlugin.classes.get(message.name)
if action_cls is None:
raise RuntimeError("Client action %r not known" % message.name)
action = action_cls(grr_worker=self)
self.transaction_log... | Entry point for processing jobs.
Args:
message: The GrrMessage that was delivered from the server.
Raises:
RuntimeError: The client action requested was not found. | juraj-google-style |
def licenses(self):
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
res = self._dll.JLINK_GetAvailableLicense(buf, buf_size)
if (res < 0):
raise errors.JLinkException(res)
return ctypes.string_at(buf).decode() | Returns a string of the built-in licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the built-in licenses the J-Link has. | codesearchnet |
def dump_next(self):
if (self.dump_walker is None):
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED)
try:
return self.dump_walker.pop()
except StreamEmptyError:
return None | Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one | codesearchnet |
def encrypt_block(self, plainText):
if not self.initialized:
raise TypeError("CamCrypt object has not been initialized")
if len(plainText) != BLOCK_SIZE:
raise ValueError("plainText must be %d bytes long (received %d bytes)" %
(BLOCK_SIZE, len(plainText)))
cipher = ct... | Encrypt a 16-byte block of data.
NOTE: This function was formerly called `encrypt`, but was changed when
support for encrypting arbitrary-length strings was added.
Args:
plainText (str): 16-byte data.
Returns:
16-byte str.
Raises:
TypeError if CamCrypt object has not been initialized.
ValueError if `plainText` is n... | juraj-google-style |
def _new(self, name, **kwargs):
if self._name_path:
parent = self
for path_element in self._name_path.split('/'):
self._set_xml_from_keys(parent, (path_element, None))
parent = parent.find(path_element)
parent.text = name
else:
ElementTree.SubElement(self,... | Create a new JSSObject with name and "keys".
Generate a default XML template for this object, based on
the class attribute "keys".
Args:
name: String name of the object to use as the
object's name property.
kwargs:
Accepted keyword args can be viewed by checking the
"data_keys" class attribute. Typically, they includ... | codesearchnet |
def __init__(self, channel):
self.ListSessionEntityTypes = channel.unary_unary(
'/google.cloud.dialogflow.v2beta1.SessionEntityTypes/ListSessionEntityTypes',
request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_session__entity__type__pb2.ListSessionEntityTypesRequest.Serial... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def upgrade(**kwargs):
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
return {} | Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash... | codesearchnet |
def __init__(self, parser, codegen, writer):
self._parser = parser
self._codegen = codegen
self._symbolgen = SymtableCodeGen()
self._writer = writer
self._sources = []
self._searchers = []
self._borrowers = [] | Creates an instance of *MibCompiler* class.
Args:
parser: ASN.1 MIB parser object
codegen: MIB transformation object
writer: transformed MIB storing object | juraj-google-style |
def from_signature(message, signature):
if (signature.recovery_id is None):
raise ValueError('The signature must have a recovery_id.')
msg = get_bytes(message)
pub_keys = bitcoin_curve.recover_public_key(msg, signature, signature.recovery_id)
for (k, recid) in pub_keys:
if ((signature.re... | Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
A PublicKey object derived from the
signature, it it exists. None otherwise. | codesearchnet |
def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims):
if isinstance(tensor_or_shape, Tensor):
return reshape(tensor_or_shape, replace_dimensions(
tensor_or_shape.shape, old_dim_or_dims, new_dim_or_dims))
if not isinstance(tensor_or_shape, Shape):
raise ValueError(
"te... | Replace dimensions in a Tensor or Shape.
old_dim_or_dims consists of a single dimension or a list of dimensions
that must occur consecutively in the input shape. They are replaced
by the dimensions in new_dim_or_dims.
Args:
tensor_or_shape: a Tensor or a Shape
old_dim_or_dims: a Dimension or a list of Dimensions
new... | juraj-google-style |
def _process_single_batch(model, inputs, targets, output_loss_metrics=None, sample_weights=None, training=False):
with backend.eager_learning_phase_scope(1 if training else 0), training_utils.RespectCompiledTrainableState(model):
with GradientTape() as tape:
outs, total_loss, output_losses, mask... | Calculate the loss and gradient for one input batch.
The model weights are updated if training is set to True.
Args:
model: Model whose loss has to be calculated.
inputs: List of input arrays.
targets: List of target arrays.
output_loss_metrics: List of metrics that are used to aggregated output
loss values.
sample_w... | github-repos |
def __init__(self, value=None, tag=enums.Tags.DEFAULT):
if value is None:
value = int(time.time())
super(DateTime, self).__init__(value, tag)
self.type = enums.Types.DATE_TIME | Create a DateTime.
Args:
value (int): The value of the DateTime in number of seconds since
the Epoch. See the time package for additional information.
Optional, defaults to the current time.
tag (Tags): An enumeration defining the tag of the LongInteger.
Optional, defaults to Tags.DEFAULT. | juraj-google-style |
def UploadFile(self, fd, offset=0, amount=None):
return self._UploadChunkStream(
self._streamer.StreamFile(fd, offset=offset, amount=amount)) | Uploads chunks of a given file descriptor to the transfer store flow.
Args:
fd: A file descriptor to upload.
offset: An integer offset at which the file upload should start on.
amount: An upper bound on number of bytes to stream. If it is `None` then
the whole file is uploaded.
Returns:
A `BlobImageDescriptor` object... | juraj-google-style |
def __one_equals_true(value):
if (isinstance(value, six.integer_types) and (value == 1)):
return True
elif (isinstance(value, six.string_types) and (re.match('\\d+', value, flags=(re.IGNORECASE + re.UNICODE)) is not None) and (six.text_type(value) == '1')):
return True
return False | Test for ``1`` as a number or a string and return ``True`` if it is.
Args:
value: string or number or None.
Returns:
bool: ``True`` if 1 otherwise ``False``. | codesearchnet |
def get_module(dir_path: str, relative_to_dir: str) -> str:
dir_path = dir_path[len(relative_to_dir):]
dir_path = dir_path.replace(os.sep, '/')
return dir_path.replace('/', '.').strip('.') | Get module that corresponds to path relative to relative_to_dir.
Args:
dir_path: Path to directory.
relative_to_dir: Get module relative to this directory.
Returns:
Name of module that corresponds to the given directory. | github-repos |
def export_model(model, model_type, export_dir, model_column_fn):
(wide_columns, deep_columns) = model_column_fn()
if (model_type == 'wide'):
columns = wide_columns
elif (model_type == 'deep'):
columns = deep_columns
else:
columns = (wide_columns + deep_columns)
feature_spec ... | Export to SavedModel format.
Args:
model: Estimator object
model_type: string indicating model type. "wide", "deep" or "wide_deep"
export_dir: directory to export the model.
model_column_fn: Function to generate model feature columns. | codesearchnet |
def latents_to_observations(self, latent_means, latent_covs):
with tf.name_scope('latents_to_observations'):
pushforward_latents_step = build_pushforward_latents_step(self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep)
latent_means = distribution_util.move_dimension(la... | Push latent means and covariances forward through the observation model.
Args:
latent_means: float `Tensor` of shape `[..., num_timesteps, latent_size]`
latent_covs: float `Tensor` of shape
`[..., num_timesteps, latent_size, latent_size]`.
Returns:
observation_means: float `Tensor` of shape
`[..., num_timesteps, obse... | codesearchnet |
def _CreateWindowsPathResolver(self, file_system, mount_point, environment_variables):
if (environment_variables is None):
environment_variables = []
path_resolver = windows_path_resolver.WindowsPathResolver(file_system, mount_point)
for environment_variable in environment_variables:
name = ... | Create a Windows path resolver and sets the environment variables.
Args:
file_system (dfvfs.FileSystem): file system.
mount_point (dfvfs.PathSpec): mount point path specification.
environment_variables (list[EnvironmentVariableArtifact]): environment
variables.
Returns:
dfvfs.WindowsPathResolver: Windows path resolve... | codesearchnet |
def flatten(vari):
if isinstance(vari, Poly):
shape = int(numpy.prod(vari.shape))
return reshape(vari, (shape,))
return numpy.array(vari).flatten() | Flatten a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari`` with `len(Q.shape)==1`.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaosp... | juraj-google-style |
def subnet_range(ip_net, cidr):
subnets_dict = dict()
subnet = whole_subnet_maker(ip_net, cidr)
subnets_dict['IP'] = ip_net
subnets_dict['NET'] = subnet
subnets_dict['CIDR'] = '%s/%s' % (whole_subnet_maker(ip_net, cidr), cidr)
if int(cidr) >= 24:
subnet_split = subnet.split('.')
... | Function to return a subnet range value from a IP address and CIDR pair
Args:
ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1
cidr: CIDR value of 1 to 32
Returns: returns a dictionary of info | juraj-google-style |
def wait_for(port_num, timeout):
logger.debug("wait for {port_num}".format(**locals()))
t_start = time.time()
sleeps = 0.1
while time.time() - t_start < timeout:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((_host(), port_... | waits while process starts.
Args:
port_num - port number
timeout - specify how long, in seconds, a command can take before times out.
return True if process started, return False if not | juraj-google-style |
def str_to_inet(address):
try:
return socket.inet_pton(socket.AF_INET, address)
except socket.error:
return socket.inet_pton(socket.AF_INET6, address) | Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address | codesearchnet |
def add(x1, x2, output_shape=None, name=None):
output_shape = convert_to_shape(output_shape)
if (not isinstance(x2, Tensor)):
return ScalarAddOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name='add'):
(x1, x2) = binary_arguments_to_tensors(x1, x2)
return AddOperation(... | Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | codesearchnet |
def resize(self, image: 'torch.Tensor', size: SizeDict, size_divisor: int=32, interpolation: 'F.InterpolationMode'=None, antialias: bool=True, **kwargs) -> 'torch.Tensor':
interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
if not size.shortest_edge:
raise ValueE... | Resize an image.
Resizes the shorter side of the image to `size["shortest_edge"]` while preserving the aspect ratio. If the
longer side is larger than the max size `(int(`size["shortest_edge"]` * 1333 / 800))`, the longer side is then
resized to the max size while preserving the aspect ratio.
Args:
image (`torch.Tens... | github-repos |
def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None):
LOG.info('Create custom IAM Policy for %s.', app)
services = pipeline_settings.get('services', {})
LOG.debug('Found requested services: %s', services)
services = auto_service(pipeline_setting... | Assemble IAM Policy for _app_.
Args:
app (str): Name of Spinnaker Application.
env (str): Environment/Account in AWS
group (str):A Application group/namespace
region (str): AWS region
pipeline_settings (dict): Settings from *pipeline.json*.
Returns:
json: Custom IAM Policy for _app_.
None: When no *services* have bee... | codesearchnet |
def is_packet_trace(path):
path = os.path.abspath(path)
if (not os.path.isfile(path)):
return False
try:
f = open(path, 'rb')
except:
return False
magic = f.read(4)
f.close()
return (magic in FILE_TYPE_HANDLER) | Determine if a file is a packet trace that is supported by this module.
Args:
path (str): path to the trace file.
Returns:
bool: True if the file is a valid packet trace. | codesearchnet |
def blit(self, source, x=0, y=0, width=None, height=None, srcX=0, srcY=0, fg_alpha=1.0, bg_alpha=1.0):
assert isinstance(source, (Console, Window)), 'source muse be a Window or Console instance'
(x, y, width, height) = self._normalizeRect(x, y, width, height)
(srcX, srcY, width, height) = source._normalizeR... | Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this c... | codesearchnet |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_stream = BytearrayStream()
if self._credential_type:
self._credential_type.write(local_stream, kmip_version=kmip_version)
else:
raise ValueError('Credential struct missing the credential type.')
if self._crede... | Write the data encoding the Credential struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defau... | codesearchnet |
def _get_string_match(self, key):
expression = '(?:\\s*)'.join(['^', 'define', '\\(', "'{}'".format(key), ',', "\\'(.*)\\'", '\\)', ';'])
pattern = re.compile(expression, re.MULTILINE)
return pattern.search(self._content) | Gets a MatchObject for the given key, assuming a string value.
Args:
key (str): Key of the property to look-up.
Return:
MatchObject: The discovered match. | codesearchnet |
def plan_scripts(self):
if (not self.__plan_scripts):
self.__plan_scripts = PlanScripts(self.__connection)
return self.__plan_scripts | Gets the Plan Scripts API client.
Returns:
PlanScripts: | codesearchnet |
def on_test_batch_begin(self, batch, logs=None): | Called at the beginning of a batch in `evaluate` methods.
Also called at the beginning of a validation batch in the `fit`
methods, if validation data is provided.
Subclasses should override for any actions to run.
Note that if the `steps_per_execution` argument to `compile` in
`Model` is set to `N`, this method will... | github-repos |
def _find(self, index):
match = _PATTERN.search(self.text, index)
while self._max_tries > 0 and match is not None:
start = match.start()
candidate = self.text[start:match.end()]
candidate = self._trim_after... | Attempts to find the next subsequence in the searched sequence on or after index
that represents a phone number. Returns the next match, None if none was found.
Arguments:
index -- The search index to start searching at.
Returns the phone number match found, None if none can be found. | juraj-google-style |
def get_tabular_stream(self, url, **kwargs):
self.close_response()
file_type = kwargs.get('file_type')
if file_type is not None:
kwargs['format'] = file_type
del kwargs['file_type']
try:
self.response = tabulator.Stream(url, **kwargs)... | Get Tabulator stream.
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers
file_type (Optional[str]): Type of file. Defaults to inferring.
delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring.
R... | juraj-google-style |
def _GetTitleFromChromeWebStore(self, extension_identifier):
if extension_identifier in self._extensions:
return self._extensions.get(extension_identifier)
page_content = self._GetChromeWebStorePage(extension_identifier)
if not page_content:
logger.warning(
'[{0:s}] no data ... | Retrieves the name of the extension from the Chrome store website.
Args:
extension_identifier (str): Chrome extension identifier.
Returns:
str: name of the extension or None. | juraj-google-style |
def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):
return self.tokenizer.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs) | Post-process the output of a vlm to decode the text.
Args:
generated_outputs (`torch.Tensor` or `np.ndarray`):
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
or `(sequence_length,)`.
skip_special_tokens (`bool`, *optional*, defaults to `True`... | github-repos |
def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None):
countriesdata = cls.countriesdata(use_live=use_live)
iso3 = cls.get_iso3_country_code(country, use_live=use_live)
if (iso3 is not None):
return (iso3, True)
def remove_matching_from_list(wordlist, word_or_part):
... | Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second
showing if the match is exact or not.
Args:
country (str): Country for which to get ISO3 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[Except... | codesearchnet |
def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:
try:
from pycocotools import mask as coco_mask
except ImportError:
raise ImportError('Pycocotools is not installed in your environment.')
masks = []
for polygons in segmentations:... | Convert a COCO polygon annotation to a mask.
Args:
segmentations (`List[List[float]]`):
List of polygons, each polygon represented by a list of x-y coordinates.
height (`int`):
Height of the mask.
width (`int`):
Width of the mask. | github-repos |
def concat(input_layer, concat_dim, other_tensors=None):
if input_layer.is_sequence():
all_tensors = input_layer.sequence
all_tensors.extend((other_tensors or []))
else:
all_tensors = [input_layer]
if (other_tensors is None):
raise ValueError('Other Tensors must be su... | Concatenates input PrettyTensor with other_tensors along the specified dim.
This adds the Pretty Tensor passed via input_layer to the front of the list of
tensors to concat.
Args:
input_layer: The input layer.
concat_dim: The dimension along which to concat.
other_tensors: The tensors to concatenate with as an iterab... | codesearchnet |
def add_oxidation_state_by_guess(self, **kwargs):
oxid_guess = self.composition.oxi_state_guesses(**kwargs)
oxid_guess = oxid_guess or \
[dict([(e.symbol, 0) for e in self.composition])]
self.add_oxidation_state_by_element(oxid_guess[0]) | Decorates the structure with oxidation state, guessing
using Composition.oxi_state_guesses()
Args:
**kwargs: parameters to pass into oxi_state_guesses() | juraj-google-style |
def _acquire_given_subnet(self, uuid_path, subnet):
lease = self.create_lease_object_from_subnet(subnet)
self._take_lease(lease, uuid_path)
return lease.to_ip_network() | Try to create a lease for subnet
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): dotted ipv4 subnet
(for example ```192.168.200.0```)
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the requested subnet is not in the
range of ... | codesearchnet |
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(config, request, global_params=global_params) | Lists snapshots.
Args:
request: (DataflowProjectsLocationsSnapshotsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListSnapshotsResponse) The response message. | github-repos |
def _convert_dict_inputs(inputs, tensor_info_map):
dict_inputs = _prepare_dict_inputs(inputs, tensor_info_map)
return tensor_info.convert_dict_to_compatible_tensor(dict_inputs, tensor_info_map) | Converts from inputs into dict of input tensors.
This handles:
- putting inputs into a dict, per _prepare_dict_inputs(),
- converting all input values into tensors compatible with the
expected input tensor (dtype, shape).
- check sparse/non-sparse tensor types.
Args:
inputs: inputs fed to Module.__call__().
tensor_in... | codesearchnet |
def __init__(self, seed, salt):
self._seed = seed.original_seed if isinstance(seed, SeedStream) else seed
self._salt = salt
self._counter = 0 | Initializes a `SeedStream`.
Args:
seed: Any Python object convertible to string, supplying the
initial entropy. If `None`, operations seeded with seeds
drawn from this `SeedStream` will follow TensorFlow semantics
for not being seeded.
salt: Any Python object convertible to string, supplying
auxiliary entropy. Must ... | juraj-google-style |
def CreateAdGroup(client, campaign_id):
ad_group_service = client.GetService('AdGroupService', 'v201809')
ad_group = {'name': 'Dynamic remarketing ad group', 'campaignId': campaign_id, 'status': 'ENABLED'}
operations = [{'operator': 'ADD', 'operand': ad_group}]
return ad_group_service.mutate(operations)... | Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created. | codesearchnet |
def get_rbounds(step):
if (step.geom is not None):
rcmb = step.geom.rcmb
else:
rcmb = step.sdat.par['geometry']['r_cmb']
if (step.sdat.par['geometry']['shape'].lower() == 'cartesian'):
rcmb = 0
rcmb = max(rcmb, 0)
return (rcmb, (rcmb + 1)) | Radial or vertical position of boundaries.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of floats: radial or vertical positions of boundaries of the
domain. | codesearchnet |
def create_reader_of_type(type_name):
readers = available_readers()
if type_name not in readers.keys():
raise UnknownReaderException('Unknown reader: %s' % (type_name,))
return readers[type_name]() | Create an instance of the reader with the given name.
Args:
type_name: The name of a reader.
Returns:
An instance of the reader with the given type. | juraj-google-style |
def uninstalled(name):
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['wusa.is_installed'](name):
ret['result'] = True
ret['comment'] = '{0} already uninstalled'.format(name)
return ret
if __opts__... | Ensure an update is uninstalled from the minion
Args:
name(str):
Name of the Windows KB ("KB123456")
Example:
.. code-block:: yaml
KB123456:
wusa.uninstalled | juraj-google-style |
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
batch_size = shape_list(mu)[0]
prior_distribution = tfp.distributions.Normal(
mu_p, tf.exp(tf.multiply(0.5, log_var_p)))
posterior_distribution = tfp.distributions.Normal(
mu, tf.exp(tf.multiply(0.5, log_var)))
kld = tfp.distributions.kl_d... | KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var) from a learned prior distribution
Returns:
the KL loss. | juraj-google-style |
def __parameter_enum(self, param):
if isinstance(param, messages.EnumField):
return [enum_entry[0] for enum_entry in sorted(
param.type.to_dict().items(), key=lambda v: v[1])] | Returns enum descriptor of a parameter if it is an enum.
An enum descriptor is a list of keys.
Args:
param: A simple field.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None. | juraj-google-style |
def _get_qubit_index(self, qubit):
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise exceptions.VisualizationError("unable to find bit for operation")
return qindex | Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found | juraj-google-style |
def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100):
url = nurls['setProperty']
data = {'userid': self.user_id,
'useridx': self.useridx,
'tagtype': tagtype,
'startnum': startnum,
'pagingrow': pagingrow,
... | GetMusicAlbumList
Args:
tagtype = ???
startnum
pagingrow
Returns:
???
False: Failed to get property | juraj-google-style |
def edit_distance_filter(source_target_input, max_equal_to_diff_ratio=0):
thrown_out_count = 0
source_target_output = []
if not max_equal_to_diff_ratio:
return source_target_input, thrown_out_count
for src_tgt in source_target_input:
opcodes = fast_match_sequences(*src_tgt)
diff_char_count = 0
... | Filter out examples that exceed max_edit_ratio between source and target.
Args:
source_target_input: a list of [source, target] pairs
max_equal_to_diff_ratio: cutoff for ratio of equal chars / diff chars
between source and target
Returns:
source_target_output: filtered subset of [source, target] input pairs
th... | juraj-google-style |
def open(self, filename):
if filename:
self.binary = BinaryFile(filename)
self.text_section = self.binary.text_section
self._load(arch_mode=self.binary.architecture_mode) | Open a file for analysis.
Args:
filename (str): Name of an executable file. | codesearchnet |
def _init_vocab_from_file(self, filename):
with tf.gfile.Open(filename) as f:
tokens = [token.strip() for token in f.readlines()]
def token_gen():
for token in tokens:
yield token
self._init_vocab(token_gen(), add_reserved_tokens=False) | Load vocab from a file.
Args:
filename: The file to load vocabulary from. | juraj-google-style |
def from_file_obj(cls, fp):
log.debug("Parsing email from file object")
try:
fp.seek(0)
except IOError:
pass
finally:
s = fp.read()
return cls.from_string(s) | Init a new object from a file-like object.
Not for Outlook msg.
Args:
fp (file-like object): file-like object of raw email
Returns:
Instance of MailParser | juraj-google-style |
def check_tweet(tweet, validation_checking=False):
if ('id' not in tweet):
raise NotATweetError("This text has no 'id' key")
original_format = is_original_format(tweet)
if original_format:
_check_original_format_tweet(tweet, validation_checking=validation_checking)
else:
_check_a... | Ensures a tweet is valid and determines the type of format for the tweet.
Args:
tweet (dict/Tweet): the tweet payload
validation_checking (bool): check for valid key structure in a tweet. | codesearchnet |
def not_modified(cls, errors=None):
if cls.expose_status:
cls.response.content_type = 'application/json'
cls.response._status_line = '304 Not Modified'
return cls(304, None, errors).to_json | Shortcut API for HTTP 304 `Not Modified` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. | juraj-google-style |
def add_candidate_peer_endpoints(self, peer_endpoints):
with self._lock:
for endpoint in peer_endpoints:
if endpoint not in self._candidate_peer_endpoints:
self._candidate_peer_endpoints.append(endpoint) | Adds candidate endpoints to the list of endpoints to
attempt to peer with.
Args:
peer_endpoints ([str]): A list of public uri's which the
validator can attempt to peer with. | juraj-google-style |
def capture(self, payment_id, amount, data={}, **kwargs):
url = "{}/{}/capture".format(self.base_url, payment_id)
data['amount'] = amount
return self.post_url(url, data, **kwargs) | Capture Payment for given Id
Args:
payment_id : Id for which payment object has to be retrieved
Amount : Amount for which the payment has to be retrieved
Returns:
Payment dict after getting captured | juraj-google-style |
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],,,] | codesearchnet |
def mesh_element(script, sample_num=1000, element='VERT'):
if (element.lower() == 'vert'):
element_num = 0
elif (element.lower() == 'edge'):
element_num = 1
elif (element.lower() == 'face'):
element_num = 2
filter_xml = ''.join([' <filter name="Mesh Element Subsampling">\n', ' ... | Create a new layer populated with a point sampling of the current mesh,
at most one sample for each element of the mesh is created.
Samples are taking in a uniform way, one for each element
(vertex/edge/face); all the elements have the same probabilty of being
choosen.
Args:
script: the FilterScript object or script ... | codesearchnet |
def get_updates_for(self, inputs):
if inputs is None:
return [u for u in self.updates if u._unconditional_update]
updates = [u for u in self.updates if not u._unconditional_update]
inputs = nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, updates)
return [u for u i... | Retrieves updates relevant to a specific set of inputs.
Args:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of update ops of the layer that depend on `inputs`. | github-repos |
def all_tokens(self, delimiter=' '):
tokens = set()
for label in self:
tokens = tokens.union(set(label.tokenized(delimiter=delimiter)))
return tokens | Return a list of all tokens occurring in the label-list.
Args:
delimiter (str): The delimiter used to split labels into tokens
(see :meth:`audiomate.annotations.Label.tokenized`).
Returns:
:class:`set`: A set of distinct tokens. | juraj-google-style |
def remove_attribute(self, attribute: str) -> None:
attr_index = self.__attr_index(attribute)
if (attr_index is not None):
self.yaml_node.value.pop(attr_index) | Remove an attribute from the node.
Use only if is_mapping() returns True.
Args:
attribute: The name of the attribute to remove. | codesearchnet |
def get_distance(self, i, j, jimage=None):
return self[i].distance(self[j], jimage) | Get distance between site i and j assuming periodic boundary
conditions. If the index jimage of two sites atom j is not specified it
selects the jimage nearest to the i atom and returns the distance and
jimage indices in terms of lattice vector translations if the index
jimage of atom j is specified it returns the dist... | codesearchnet |
def _RegisterProcess(self, process):
if process is None:
raise ValueError('Missing process.')
if process.pid in self._processes_per_pid:
raise KeyError(
'Already managing process: {0!s} (PID: {1:d})'.format(
process.name, process.pid))
self._processes_per_pid[proce... | Registers a process with the engine.
Args:
process (MultiProcessBaseProcess): process.
Raises:
KeyError: if the process is already registered with the engine.
ValueError: if the process is missing. | juraj-google-style |
def _initialize_tensor_name_to_ids(self):
tensor_name_to_ids = {}
for (i, operation) in enumerate(self._operations):
for (j, tensor) in enumerate(operation.outputs):
tensor_name_to_ids[tensor.name] = (i, j)
return tensor_name_to_ids | Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs. | codesearchnet |
def Verify(self):
if (not (self.Hash.ToBytes() == GetGenesis().Hash.ToBytes())):
return False
bc = GetBlockchain()
if (not bc.ContainsBlock(self.Index)):
return False
if (self.Index > 0):
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToBytes())
if (prev_header is ... | Verify block using the verification script.
Returns:
bool: True if valid. False otherwise. | codesearchnet |
def usufyToTextExport(d, fPath=None):
if (d == []):
return '+------------------+\n| No data found... |\n+------------------+'
import pyexcel as pe
import pyexcel.ext.text as text
if (fPath == None):
isTerminal = True
else:
isTerminal = False
try:
oldData = get_dat... | Workaround to export to a .txt file or to show the information.
Args:
-----
d: Data to export.
fPath: File path for the output file. If None was provided, it will
assume that it has to print it.
Returns:
--------
unicode: It sometimes returns a unicode representation of the Sheet
received. | codesearchnet |
def _populate_from_repo(self, example: Example):
path = Path(example.filepath)
example_folder = path.parent
log_file_path = example_folder / self.LOGS_FILENAME
if log_file_path.exists():
example.logs = log_file_path.read_text()
graph_file_path = example_folder / self.GRAPH_FILENAME
if gr... | Populate fields of the example reading them from the repository.
Args:
example: beam example that should be verified | github-repos |
def ParseFileDownloadedRow(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = ChromeHistoryFileDownloadedEventData()
event_data.full_path = self._GetRowValue(query_hash, row, 'target_path')
event_data.offset = self._GetRowValue(query_hash, row, 'id')
... | Parses a file downloaded row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | juraj-google-style |
def _torch_extract_fbank_features(self, waveform: 'torch.FloatTensor', audio_lengths: 'torch.Tensor', device: str='cpu') -> 'torch.FloatTensor':
fft_window = torch.hamming_window(self.win_length, periodic=False, device=device, dtype=torch.float64)
batch_size = waveform.shape[0]
frames = waveform.unfold(-1, ... | Compute the log mel-scaled spectrogram of batched waveforms using PyTorch's FFT implementation.
Args:
waveform (torch.FloatTensor` of shape `(batch_size, max_audio_length)`):
The batched waveforms.
audio_lengths (`torch.Tensor` of shape `(batch_size,)`):
The lengths of the waveforms along the max_audio_length dimensio... | github-repos |
def detect_alias_config_change(self):
if self.parse_error():
return False
alias_config_sha1 = hashlib.sha1(self.alias_config_str.encode('utf-8')).hexdigest()
if (alias_config_sha1 != self.alias_config_hash):
self.alias_config_hash = alias_config_sha1
return True
return False | Change if the alias configuration has changed since the last run.
Returns:
False if the alias configuration file has not been changed since the last run.
Otherwise, return True. | codesearchnet |
def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None, has_accumulators=False, **kwargs):
if (num_loop_vars is None):
return WhileLoopOperation(cond_fn, body_fn, inputs, tf_kwargs=kwargs, has_accumulators=has_accumulators).outputs
assert (num_loop_vars > 0)
extra_inputs = inputs[num_loop_vars:... | While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By setting
num_loop_vars=k, then all of the loop variables except for the first k
are handled as mtf Variables instead of loop va... | codesearchnet |
def is_distributed(partition_column, lower_bound, upper_bound):
if (
(partition_column is not None)
and (lower_bound is not None)
and (upper_bound is not None)
):
if upper_bound > lower_bound:
return True
else:
raise InvalidArguments("upper_bo... | Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the maximum value to be requested from the partition_column
Returns:
True for distributed or False if ... | juraj-google-style |
def experimental_write_bytecode(filename, mlir_txt):
pywrap_mlir.experimental_write_bytecode(filename, mlir_txt) | Writes an MLIR module out as bytecode.
Args:
filename: The filename to write to.
mlir_txt: The MLIR module in textual format. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.