code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def update_container(self, container, blkio_weight=None, cpu_period=None, cpu_quota=None, cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, mem_limit=None, mem_reservation=None, memswap_limit=None, kernel_memory=None, restart_policy=None):
url = self._url('/containers/{0}/update', container)
data = {}
if... | Update resource configs of one or more containers.
Args:
container (str): The container to inspect
blkio_weight (int): Block IO (relative weight), between 10 and 1000
cpu_period (int): Limit CPU CFS (Completely Fair Scheduler) period
cpu_quota (int): Limit CPU CFS (Completely Fair Scheduler) quota
cpu_shares (int): CP... | codesearchnet |
def __get_scope(cls, expr: Union[('Expression', Tuple)]) -> Set[str]:
scope = set()
for (i, atom) in enumerate(expr):
if isinstance(atom, Expression):
scope.update(cls.__get_scope(atom._expr))
elif (type(atom) in [tuple, list]):
scope.update(cls.__get_scope(atom))
... | Returns the set of fluents in the expression's scope.
Args:
expr: Expression object or nested tuple of Expressions.
Returns:
The set of fluents in the expression's scope. | codesearchnet |
def _lease_owned(self, lease, current_uuid_path):
prev_uuid_path, prev_uuid = lease.metadata
with open(current_uuid_path) as f:
current_uuid = f.read()
return \
current_uuid_path == prev_uuid_path and \
prev_uuid == current_uuid | Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the lease
current_uuid_path (str): Path to the uuid to check ownership of
Returns:
bool: ``True`` if the given lease in owned by the ... | juraj-google-style |
def links(res: requests.models.Response,
search: str = None,
pattern: str = None) -> list:
hrefs = [link.to_text() for link in find_all_links(res.text)]
if search:
hrefs = [href for href in hrefs if search in href]
if pattern:
hrefs = [href for href in hrefs if re.fi... | Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the page. | juraj-google-style |
def _pycurl_post(self, url, json=None, data=None, username='', password='', headers={}, timeout=30):
response_headers = {}
curl = pycurl.Curl()
curl.setopt(curl.URL, url)
if (sys.version_info[0] >= 3):
stringbuffer = BytesIO()
else:
stringbuffer = StringIO()
curl.setopt(curl.WRIT... | This function will POST to the url endpoint using pycurl. returning
an AdyenResult object on 200 HTTP responce. Either json or data has to
be provided. If username and password are provided, basic auth will be
used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, opti... | codesearchnet |
def load_pickle(file, encoding=None):
if encoding:
with open(file, 'rb') as f:
return pickle.load(f, encoding=encoding)
with open(file, 'rb') as f:
return pickle.load(f) | Load a pickle file.
Args:
file (str): Path to pickle file
Returns:
object: Loaded object from pickle file | juraj-google-style |
def delete_contexts(self, context_id_list):
for c_id in context_id_list:
if c_id in self._contexts:
del self._contexts[c_id] | Delete contexts from the ContextManager.
Args:
context_id_list (list): a list of context ids
Returns:
None | juraj-google-style |
def _save_function_alias(saved_model_dir: str, tags: Collection[str], function_aliases: Mapping[str, str]) -> None:
loader = saved_model_loader.SavedModelLoader(saved_model_dir)
meta_graph_def = loader.get_meta_graph_def_from_tags(tags)
for function_name, function_alias in function_aliases.items():
... | Saves the function alias to the SavedModel.
SavedModelBuilder (TF1 saved model saver) does not support saving function
aliases, so this function loads the SavedModel proto and adds the
`function_aliases` field.
Args:
saved_model_dir: Path to the saved model directory.
tags: A collection of tags to specify the meta gr... | github-repos |
def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
if en... | Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | juraj-google-style |
def is_clockwise(vertices):
it = iterator.consecutive(cycle(vertices), 3)
clockwise = 0
counter = 0
for _ in range(len(vertices)):
p0, p1, p2 = next(it)
cross = cross_product(p1, p2, p0)
int_angle = interior_angle(p0, p2, p1)
if cross < 0:
clockwise += ... | Evaluate whether vertices are in clockwise order.
Args:
vertices: list of vertices (x, y) in polygon.
Returns:
True: clockwise, False: counter-clockwise
Raises:
ValueError: the polygon is complex or overlapped. | juraj-google-style |
def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):
with tf.variable_scope(name, default_name='edge_vectors'):
att_adj_vectors_shape = [num_edge_types, depth]
adjacency_matrix_shape = common_layers.shape_list(adjacency_matrix)
adj_vectors = (tf.get_variable('adj_vector... | Gets edge vectors for the edge types in the adjacency matrix.
Args:
adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.
num_edge_types: Number of different edge types
depth: Number of channels
name: a string
Returns:
A [batch, num_nodes, num_nodes, depth] vector of tensors | codesearchnet |
def ms_bot_framework(self) -> dict:
card_action = {}
card_action['type'] = 'postBack'
card_action['title'] = self.name
card_action['value'] = self.callback = self.callback
return card_action | Returns MS Bot Framework compatible state of the Button instance.
Creates MS Bot Framework CardAction (button) with postBack value return.
Returns:
control_json: MS Bot Framework representation of Button state. | codesearchnet |
def _combine_named_parameters(**kwargs) -> list[OrderedDict[str, Any]]:
sort_by_key = lambda k: k[0]
combinations: list[list[tuple[str, Any]]] = []
for key, values in sorted(kwargs.items(), key=sort_by_key):
if not isinstance(values, list):
values = [values]
combinations.append([... | Generate combinations based on its keyword arguments.
Two sets of returned combinations can be concatenated using +. Their product
can be computed using `times()`.
Args:
**kwargs: keyword arguments of form `option=[possibilities, ...]` or
`option=the_only_possibility`.
Returns:
a list of dictionaries for each combi... | github-repos |
def copy_foreign_keys(self, event):
event_keys = set(event._meta.fields.keys())
obj_keys = self._meta.fields.keys()
matching_keys = event_keys.intersection(obj_keys)
for key in matching_keys:
if key == 'created_by':
continue... | Copies possible foreign key values from the object into the Event,
skipping common keys like modified and created.
Args:
event (Event): The Event instance to copy the FKs into
obj (fleaker.db.Model): The object to pull the values from | juraj-google-style |
def _draw_breakpoint_icon(self, top, painter, icon_name):
rect = QRect(0, top, self.sizeHint().width(),
self.sizeHint().height())
try:
icon = self.icons[icon_name]
except KeyError as e:
debug_print("Breakpoint icon doen't exist, {}".format(e)... | Draw the given breakpoint pixmap.
Args:
top (int): top of the line to draw the breakpoint icon.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons) | juraj-google-style |
def MakePmfFromHist(hist, name=None):
if (name is None):
name = hist.name
d = dict(hist.GetDict())
pmf = Pmf(d, name)
pmf.Normalize()
return pmf | Makes a normalized PMF from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Pmf object | codesearchnet |
def most_specific_common_supertype(self, others):
if not all((isinstance(other, TensorArraySpec) for other in others)):
return False
common_shape = self._element_shape.most_specific_common_supertype((other._element_shape for other in others))
if common_shape is None:
return None
if not a... | Returns the most specific supertype of `self` and `others`.
Args:
others: A Sequence of `TypeSpec`.
Returns `None` if a supertype does not exist. | github-repos |
def imag(self):
def im(val):
if hasattr(val, 'imag'):
return val.imag
elif hasattr(val, 'as_real_imag'):
return val.as_real_imag()[1]
elif hasattr(val, 'conjugate'):
return ((val.conjugate() - val) / (2 * I))
else:
raise NoConjugateMat... | Element-wise imaginary part
Raises:
NoConjugateMatrix: if entries have no `conjugate` method and no
other way to determine the imaginary part
Note:
A mathematically equivalent way to obtain an imaginary matrix from
a complex matrix ``M`` is::
(M.conjugate() - M) / (I * 2)
with same same caveats as :attr:`real`. | codesearchnet |
def get(self):
return self._diff_median_tracker.get() | Retrieves the current MAD value.
Returns:
float: The MAD of the values within the defined window. Returns `NaN` if
the window is empty. | github-repos |
def convert_dict_to_compatible_tensor(values, targets):
result = {}
for key, value in sorted(values.items()):
result[key] = _convert_to_compatible_tensor(
value, targets[key], error_prefix="Can't convert %r" % key)
return result | Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` but values converted into
Tensor/SparseTensors that can be fed into `protomap... | juraj-google-style |
def pad_image(self, image: 'torch.Tensor', size: SizeDict, random_padding: bool=False) -> 'torch.Tensor':
output_height, output_width = (size.height, size.width)
input_height, input_width = image.shape[-2:]
delta_width = output_width - input_width
delta_height = output_height - input_height
if rando... | Pad the image to the specified size.
Args:
image (`torch.Tensor`):
The image to be padded.
size (`Dict[str, int]`):
The size `{"height": h, "width": w}` to pad the image to.
random_padding (`bool`, *optional*, defaults to `False`):
Whether to use random padding or not.
data_format (`str` or `ChannelDimension`, *option... | github-repos |
def resolve_variables(self, provided_variables):
self.resolved_variables = {}
variable_dict = dict((var.name, var) for var in provided_variables)
for var_name, _var_def in variable_dict.items():
value = resolve_variable(
variable_dict.get(var_name),
... | Resolve the values of the blueprint variables.
This will resolve the values of the template parameters with values
from the env file, the config, and any lookups resolved. The
resolution is run twice, in case the blueprint is jinja2 templated
and requires provided variables to render.
Args:
provided_variables (list o... | juraj-google-style |
def _Extract(
self, source_path_specs, destination_path, output_writer,
skip_duplicates=True):
output_writer.Write('Extracting file entries.\n')
path_spec_generator = self._path_spec_extractor.ExtractPathSpecs(
source_path_specs, resolver_context=self._resolver_context)
for path_sp... | Extracts files.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications to extract.
destination_path (str): path where the extracted files should be stored.
output_writer (CLIOutputWriter): output writer.
skip_duplicates (Optional[bool]): True if files with duplicate content
should be skipped. | juraj-google-style |
def reset(self, indices, observations):
assert isinstance(indices, np.ndarray)
assert (len(indices.shape) == 1)
assert isinstance(observations, np.ndarray)
assert (indices.shape[0] == observations.shape[0])
for (index, observation) in zip(indices, observations):
trajectory = self._trajectori... | Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self._completed_trajectories.
Args:
indices: 1-D np.ndarray statin... | codesearchnet |
def find_yang_file(profile, filename, path):
module_dir = os.path.dirname(__file__)
full_path = os.path.join(module_dir, 'mappings', profile, path, filename)
if os.path.exists(full_path):
return full_path
else:
msg = "Couldn't find parsing file: {}".format(full_path)
logger.error... | Find the necessary file for the given test case.
Args:
device(napalm device connection): for which device
filename(str): file to find
path(str): where to find it relative to where the module is installed | codesearchnet |
def _ConvertFieldValuePair(js, message):
names = []
message_descriptor = message.DESCRIPTOR
for name in js:
try:
field = message_descriptor.fields_by_camelcase_name.get(name, None)
if not field:
raise ParseError(
'Message type "{0}" has no field named "{1}".'.format(
... | Convert field value pairs into regular message.
Args:
js: A JSON object to convert the field value pairs.
message: A regular protocol message to record the data.
Raises:
ParseError: In case of problems converting. | juraj-google-style |
def resolve_workdir_path(cls, start_path=os.curdir):
if start_path == 'auto':
start_path = os.curdir
cur_path = start_path
LOGGER.debug(
'Checking if %s is a workdir',
os.path.abspath(cur_path),
)
if cls.is_workdir(cur_path):
... | Look for an existing workdir in the given path, in a path/.lago dir,
or in a .lago dir under any of it's parent directories
Args:
start_path (str): path to start the search from, if None passed, it
will use the current dir
Returns:
str: path to the found prefix
Raises:
LagoUserException: if no prefix was found | juraj-google-style |
def save_image(byteio, imgfmt):
from os import path, mkdir
ptdir = '{}.{}'.format(project, task)
uuid = str(uuid4())
idir = path.join(dbdir, ptdir)
if (not path.isdir(idir)):
mkdir(idir)
ipath = path.join(idir, '{}.{}'.format(uuid, imgfmt))
with open(ipath, 'wb') as f:
f.writ... | Saves the specified image to disk.
Args:
byteio (bytes): image bytes to save to disk.
imgfmt (str): used as the extension of the saved file.
Returns:
str: a uuid for the saved image that can be added to the database entry. | codesearchnet |
def get_service_credentials(pipeline_options):
return _Credentials.get_service_credentials(pipeline_options) | For internal use only; no backwards-compatibility guarantees.
Get credentials to access Azure services.
Args:
pipeline_options: Pipeline options, used in creating credentials
like managed identity credentials.
Returns:
A ``azure.identity.*Credential`` object or None if credentials
not found. Returned object is thread... | github-repos |
def filepath(self):
if hasattr(self, 'local_path'):
return self.local_path
if (self.scheme in ['ftp', 'http', 'https', 'globus']):
return self.filename
elif (self.scheme in ['file']):
return self.path
else:
raise Exception('Cannot return filepath for unknown scheme {}'.fo... | Return the resolved filepath on the side where it is called from.
The appropriate filepath will be returned when called from within
an app running remotely as well as regular python on the client side.
Args:
- self
Returns:
- filepath (string) | codesearchnet |
def rules(self):
list_of_rules = []
for main_row in self.dict_rules:
if ('rules' in main_row):
for rule_row in main_row['rules']:
if ('grants' in rule_row):
for grant_row in rule_row['grants']:
if ('group_id' in grant_row):
... | Returns a sorted list of firewall rules.
Returns:
list | codesearchnet |
def metadata(self, path):
try:
file_metadata = self._gcsIO()._status(path)
return FileMetadata(path, file_metadata['size'], file_metadata['updated'])
except Exception as e:
raise BeamIOError('Metadata operation failed', {path: e}) | Fetch metadata fields of a file on the FileSystem.
Args:
path: string path of a file.
Returns:
:class:`~apache_beam.io.filesystem.FileMetadata`.
Raises:
``BeamIOError``: if path isn't a file or doesn't exist. | github-repos |
def get_existing_test_names(self):
test_names = []
for name, _ in inspect.getmembers(type(self), callable):
if name.startswith('test_'):
test_names.append(name)
return test_names + list(self._generated_test_table.keys()) | Gets the names of existing tests in the class.
A method in the class is considered a test if its name starts with
'test_*'.
Note this only gets the names of tests that already exist. If
`generate_tests` has not happened when this was called, the
generated tests won't be listed.
Returns:
A list of strings, each is a ... | github-repos |
def save_lines(lines, filename):
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines)) | Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file. | codesearchnet |
def _ParseValueData(self, knowledge_base, value_data):
if not isinstance(value_data, py2to3.UNICODE_TYPE):
raise errors.PreProcessFail(
'Unsupported Windows Registry value type: {0:s} for '
'artifact: {1:s}.'.format(
type(value_data), self.ARTIFACT_DEFINITION_NAME))
... | Parses Windows Registry value data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
value_data (object): Windows Registry value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | juraj-google-style |
def sequential_spherical(xyz):
d_xyz = np.diff(xyz,axis=0)
r = np.linalg.norm(d_xyz,axis=1)
theta = np.arctan2(d_xyz[:,1], d_xyz[:,0])
hyp = d_xyz[:,0]**2 + d_xyz[:,1]**2
phi = np.arctan2(np.sqrt(hyp), d_xyz[:,2])
return (r,theta,phi) | Converts sequence of cartesian coordinates into a sequence of
line segments defined by spherical coordinates.
Args:
xyz = 2d numpy array, each row specifies a point in
cartesian coordinates (x,y,z) tracing out a
path in 3D space.
Returns:
r = lengths of each line segment (1D array)
theta = angles of line segments in ... | juraj-google-style |
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
if topology_only:
self.points = drp(self.points, eps)
else:
self.points = spt(self.points, max_dist_error, max_speed_error)
return self | In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
max_speed_error (float): Max speed error, in km/h
topology_only (bool, optional): True to only keep topology, not considering
times whe... | juraj-google-style |
def simple_lmdb_settings(path, map_size=1000000000.0, user_supplied_id=False):
def decorator(cls):
provider = (ff.UserSpecifiedIdProvider(key='_id') if user_supplied_id else ff.UuidProvider())
class Settings(ff.PersistenceSettings):
id_provider = provider
key_builder = ff.S... | Creates a decorator that can be used to configure sane default LMDB
persistence settings for a model
Args:
path (str): The path where the LMDB database files will be created
map_size (int): The amount of space to allot for the database | codesearchnet |
def jwt_is_expired(self, access_token=None, leeway=0):
if access_token is not None:
exp = self._decode_exp(access_token)
else:
exp = self.jwt_exp
now = time()
if exp < (now - leeway):
return True
return False | Validate JWT access token expiration.
Args:
access_token (str): Access token to validate. Defaults to ``None``.
leeway (float): Time in seconds to adjust for local clock skew. Defaults to 0.
Returns:
bool: ``True`` if expired, otherwise ``False``. | juraj-google-style |
def convert(cls, content, input_format, output_format):
assert (input_format in ('srt', 'sjson'))
assert (output_format in ('srt', 'sjson'))
content = content.decode('utf-8-sig')
if (input_format == output_format):
return content
if (input_format == 'srt'):
if (output_format == 'sjso... | Convert transcript `content` from `input_format` to `output_format`.
Arguments:
content: Transcript content byte-stream.
input_format: Input transcript format.
output_format: Output transcript format.
Accepted input formats: sjson, srt.
Accepted output format: srt, sjson.
Raises:
TranscriptsGenerationException: On p... | codesearchnet |
def optimize(node):
node = dead_code_elimination(node)
node = constant_folding(node)
node = assignment_propagation(node)
return node | Perform a series of optimization passes.
This function performs a series of optimizations (dead code elimination,
constant folding, variable folding) on the given AST.
It optimizes the code repeatedly until reaching a fixed point. The fixed
point is determine roughly by checking whether the number of lines of
generate... | juraj-google-style |
def _add_genotype_calls(self, variant_obj, variant_line, case_obj):
variant_line = variant_line.split('\t')
if (len(variant_line) > 8):
gt_format = variant_line[8].split(':')
for individual in case_obj.individuals:
sample_id = individual.ind_id
index = individual.ind_inde... | Add the genotype calls for the variant
Args:
variant_obj (puzzle.models.Variant)
variant_dict (dict): A variant dictionary
case_obj (puzzle.models.Case) | codesearchnet |
def reset_state(self, reset_state):
if isinstance(reset_state, int):
self._pool.map(_reset_state, self._shard_num_args({'reset_state': reset_state}))
elif isinstance(reset_state, np.ndarray):
sim.validate_normalized_state(reset_state, self._num_qubits)
args = []
for kwargs in sel... | Reset the state to the given initial state.
Args:
reset_state: If this is an int, then this is the state to reset
the stepper to, expressed as an integer of the computational
basis. Integer to bitwise indices is little endian. Otherwise
if this is a np.ndarray this must be the correct size, be
normalized (L2 norm of 1... | codesearchnet |
def assertAllCloseAccordingToType(self, a, b, rtol=1e-06, atol=1e-06, float_rtol=1e-06, float_atol=1e-06, half_rtol=0.001, half_atol=0.001, bfloat16_rtol=0.01, bfloat16_atol=0.01, msg=None):
a, b = self.evaluate_if_both_tensors(a, b)
a = self._GetNdArray(a)
b = self._GetNdArray(b)
if a.dtype == np.float... | Like assertAllClose, but also suitable for comparing fp16 arrays.
In particular, the tolerance is reduced to 1e-3 if at least
one of the arguments is of type float16.
Args:
a: the expected numpy ndarray or anything can be converted to one.
b: the actual numpy ndarray or anything can be converted to one.
rtol: relativ... | github-repos |
def _cancel_http(api_request, operation_name):
path = "operations/{}:cancel".format(operation_name)
api_request(method="POST", path=path) | Cancel an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation. | juraj-google-style |
def embedding_lookup(params, ids: ragged_tensor.Ragged, partition_strategy='mod', name=None, validate_indices=True, max_norm=None):
if params is None:
raise ValueError('params must be specified.')
if isinstance(params, (list, tuple)) and (not params):
raise ValueError('params should not be empty... | Look up the ragged ids in a list of embedding tensors.
Args:
params: A tensor representing the complete embedding tensor having the shape
[e1, ...eM]
ragged_ids: A 'RaggedTensor' with type 'int32' or 'int64' containing the ids
to be looked up in 'params' of shape [r0, ..rN]. Values must be in the
range '[0, params.sha... | github-repos |
def _flatten_subsection(subsection, _type, offset, parent):
for row in subsection:
if row in ('Low', 'Generated', 'High', ):
continue
elif isinstance(row[0], StringType):
if len(row) in (4, 5, ):
if len(row) == 5:
assert row[4... | Flatten a subsection from its nested version
Args:
subsection: Nested subsection as produced by _parse_section, except one level in
_type: type of section, ie: AXON, etc
parent: first element has this as it's parent
offset: position in the final array of the first element
Returns:
Generator of values corresponding to... | juraj-google-style |
def tv_credits(self, **kwargs):
path = self._get_id_path('tv_credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the TV credits for a specific person id.
Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any person method.
Returns:
A dict respresentation of the JSON returned from the API. | codesearchnet |
def _method_url(self, method_name):
return "{base_url}/api/{api}/{method}".format(
base_url=self._base_url(),
api=self.api_version,
method=method_name
) | Generate the URL for the requested method
Args:
method_name (str): Name of the method
Returns:
A string containing the URL of the method | juraj-google-style |
def add_to_queue(self, queueable_item, position=0, as_next=False):
metadata = to_didl_string(queueable_item)
response = self.avTransport.AddURIToQueue([('InstanceID', 0), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), ('DesiredFirstTrackNumberEnqueued', position), ('Enqueue... | Add a queueable item to the queue.
Args:
queueable_item (DidlObject or MusicServiceItem): The item to be
added to the queue
position (int): The index (1-based) at which the URI should be
added. Default is 0 (add URI at the end of the queue).
as_next (bool): Whether this URI should be played as the next
track in shuffl... | codesearchnet |
def tokenize(self, vector_list):
if self.computable_distance is None:
self.computable_distance = EuclidDistance()
vector_arr = np.array(vector_list)
distance_arr = np.empty_like(vector_arr)
feature_arr = self.__dbm.get_feature_point(layer_number=0)
key_arr = ... | Tokenize vector.
Args:
vector_list: The list of vector of one token.
Returns:
token | juraj-google-style |
def _get_authorization_headers(self, context):
headers = {}
self._credentials.before_request(self._request, context.method_name, context.service_url, headers)
return list(six.iteritems(headers)) | Gets the authorization headers for a request.
Returns:
Sequence[Tuple[str, str]]: A list of request headers (key, value)
to add to the request. | codesearchnet |
def _extract_response_chunks(self, all_responses, response_chunks, api_name):
for response_chunk in response_chunks:
if not isinstance(response_chunk, list):
response_chunk = [response_chunk]
for response in response_chunk:
if not response:
... | Extracts and caches the responses from the response chunks in case
of the responses for the requests containing multiple concatenated
resources. Extracted responses are added to the already cached
responses passed in the all_responses parameter.
Args:
all_responses: a list containing already cached responses.
response... | juraj-google-style |
def write(self, name, **data):
data['name'] = name
if (not ('timestamp' in data)):
data['timestamp'] = datetime.utcnow()
try:
self.client.index(index=self.get_index(), doc_type=self.doc_type, id=None, body=data)
except TransportError as exc:
logger.warning('writing metric %r fail... | Write the metric to elasticsearch
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric | codesearchnet |
def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''):
log.info('Get latest data for sensors. Stop with Ctrl+C.')
log.info('MACs: %s', macs)
for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device):
callback(new_data) | Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. Function executes while run_flag.running
bt_device (string): Bluetooth device id | juraj-google-style |
def identifiers(config):
ids = []
if (config.klass_name == 'gen'):
for generator in os.listdir(config.generator_dir):
if (generator == '__init__.py'):
continue
(gid, ext) = os.path.splitext(generator)
if (ext == '.py' and
os.pa... | Show list of identifiers for this prefix.
Handles both the case of local file based identifiers and
also image generators.
Arguments:
config - configuration object in which:
config.klass_name - 'gen' if a generator function
config.generator_dir - directory for generator code
config.image_dir - directory for images
R... | juraj-google-style |
def send_async(self, transaction, headers=None):
return self.transport.forward_request(method='POST', path=self.path, json=transaction, params={'mode': 'async'}, headers=headers) | Submit a transaction to the Federation with the mode `async`.
Args:
transaction (dict): the transaction to be sent
to the Federation node(s).
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction sent to the Federation node(s). | codesearchnet |
def migrate(self, id_or_uri, timeout=-1):
migrationInformation = {
'migrationState': 'Migrated',
'type': 'migratable-vc-domains',
'category': 'migratable-vc-domains'
}
complete_uri = self._client.build_uri(id_or_uri)
... | Initiates a migration of an enclosure specified by the ID or URI of a migration report.
Args:
id_or_uri: ID or URI of the migration report.
timeout: Timeout in seconds. Waits for task completion by default. The timeout does not abort the task in
OneView; just stops waiting for its completion.
Returns: dict: a migra... | juraj-google-style |
def __check_no_missing_attributes(self, node: yaml.Node,
mapping: CommentedMap) -> None:
logger.debug('Checking presence of required attributes')
for name, type_, required in class_subobjects(self.class_):
if required and name not in mapping:
... | Checks that all required attributes are present.
Also checks that they're of the correct type.
Args:
mapping: The mapping with subobjects of this object.
Raises:
RecognitionError: if an attribute is missing or the type \
is incorrect. | juraj-google-style |
def tomography_data(results, name, tomoset):
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for (j, _) in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]), tomoset['qubits'])
shots = sum(counts.values())
... | Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts ... | codesearchnet |
def __init__(
self, name, aliases=None, description=None, maximum_value=None,
minimum_value=None, urls=None):
super(IntegerDefinition, self).__init__(
name, aliases=aliases, description=description, urls=urls)
self.format = definitions.FORMAT_SIGNED
self.maximum_value = maximum_valu... | Initializes an integer data type definition.
Args:
name (str): name.
aliases (Optional[list[str]]): aliases.
description (Optional[str]): description.
maximum_value (Optional[int]): maximum allowed value of the integer
data type.
minimum_value (Optional[int]): minimum allowed value of the integer
data type.
urls (Opti... | juraj-google-style |
def get_what_follows_raw(s: str,
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True) -> Tuple[bool, str]:
prefixstart = s.find(prefix)
if ((prefixstart == 0 and onlyatstart) or
(prefixstart != -1 and not... | Find the part of ``s`` that is after ``prefix``.
Args:
s: string to analyse
prefix: prefix to find
onlyatstart: only accept the prefix if it is right at the start of
``s``
stripwhitespace: remove whitespace from the result
Returns:
tuple: ``(found, result)`` | juraj-google-style |
def FilterItem(self, launchditem):
for regex in self.blacklist_regex:
if regex.match(launchditem.get('Label', '')):
return True
return False | Should this job be filtered.
Args:
launchditem: job NSCFDictionary
Returns:
True if the item should be filtered (dropped) | codesearchnet |
def __init__(self, fsntfs_data_stream):
super(NTFSDataStream, self).__init__()
self._fsntfs_data_stream = fsntfs_data_stream | Initializes the data stream object.
Args:
fsntfs_data_stream (pyfsntfs.data_stream): NTFS data stream. | juraj-google-style |
def create_course_completion(self, user_id, payload):
return self._post(
urljoin(
self.enterprise_configuration.degreed_base_url,
self.global_degreed_config.completion_status_api_path
),
payload,
self.COMPLETION_PROVIDER_... | Send a completion status payload to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing completion status fields per Degreed documentation.
Returns:
A tuple containing the status code and the body of the response.
... | juraj-google-style |
def fill_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_RenderFillRects(self._ptr, rect_array, len(rects))) | Fill some number of rectangles on the current rendering target with the drawing color.
Args:
*rects (Rect): The destination rectangles.
Raises:
SDLError: If an error is encountered. | codesearchnet |
def compose(self, r: Rigid) -> Rigid:
new_rot = self._rots.compose_r(r._rots)
new_trans = self._rots.apply(r._trans) + self._trans
return Rigid(new_rot, new_trans) | Composes the current rigid object with another.
Args:
r:
Another Rigid object
Returns:
The composition of the two transformations | github-repos |
def encode_request(request_line, **headers):
lines = [request_line]
lines.extend(['%s: %s' % kv for kv in headers.items()])
return ('\r\n'.join(lines) + '\r\n\r\n').encode('utf-8') | Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
value pairs to present in the request.
Returns:
bytes: The encoded request. | juraj-google-style |
def __init__(self, cell, device, **kwargs):
super(DeviceWrapperBase, self).__init__(cell, **kwargs)
self._device = device | Construct a `DeviceWrapper` for `cell` with device `device`.
Ensures the wrapped `cell` is called with `tf.device(device)`.
Args:
cell: An instance of `RNNCell`.
device: A device string or function, for passing to `tf.device`.
**kwargs: dict of keyword arguments for base layer. | github-repos |
def checksum1(data, stringlength):
value_buffer = 0
for count in range(0, stringlength):
value_buffer = (value_buffer ^ data[count])
return (value_buffer & 254) | Calculate Checksum 1
Calculate the ckecksum 1 required for the herkulex data packet
Args:
data (list): the data of which checksum is to be calculated
stringlength (int): the length of the data
Returns:
int: The calculated checksum 1 | codesearchnet |
def get_error_name(error):
error_type = type(error)
if (error_type.__module__ in ['__main__', 'builtins']):
return error_type.__name__
else:
return f'{error_type.__module__}.{error_type.__name__}' | Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Exception object.
Returns:
str. Canonical error name. | codesearchnet |
def mark_typed_list(self, name, type_object):
if (not hasattr(type_object, 'dump')):
raise ArgumentError(('The passed type object %s is missing required method: dump()' % type_object))
if (not hasattr(type_object, 'Restore')):
raise ArgumentError(('The passed type object %s is missing required m... | Mark a property as containing serializable objects of a given type.
This convenience method allows you to avoid having to call
``mark_complex()`` whenever you need to serialize a list of objects.
This method requires that all members of the given list be of a single
class that contains a dump() method and a Restore() ... | codesearchnet |
def dq_argument(self) -> str:
def escape():
self._escape = True
return 1
self._escape = False
self.offset += 1
start = self.offset
self.dfa([{'': (lambda : 0), '"': (lambda : (- 1)), '\\': escape}, {'': (lambda : 0)}])
self._arg += (self.unescape(self.input[start:self.offset]) i... | Parse double-quoted argument.
Raises:
EndOfInput: If past the end of input. | codesearchnet |
def __call__(self, fn):
def exception(app, *args, **kwargs):
try:
return fn(app, *args, **kwargs)
except Exception as e:
app.tcex.log.error('method failure ({})'.format(e))
app.tcex.exit(1, self.msg)
return ... | Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | juraj-google-style |
def get_feature(w1: str, w2: str, w3: str, w4: str, w5: str, w6: str) -> typing.List[str]:
raw_feature = {'UW1': w1, 'UW2': w2, 'UW3': w3, 'UW4': w4, 'UW5': w5, 'UW6': w6, 'BW1': w2 + w3, 'BW2': w3 + w4, 'BW3': w4 + w5, 'TW1': w1 + w2 + w3, 'TW2': w2 + w3 + w4, 'TW3': w3 + w4 + w5, 'TW4': w4 + w5 + w6}
for key,... | Generates a feature from characters around (w1-6).
Args:
w1 (str): The character 3 characters before the break point.
w2 (str): The character 2 characters before the break point.
w3 (str): The character right before the break point.
w4 (str): The character right after the break point.
w5 (str): The character 2 charact... | github-repos |
def plugin_method(*plugin_names):
def wrapper(callable_obj):
for plugin_name in plugin_names:
if not hasattr(callable_obj, plugin_name):
setattr(callable_obj, plugin_name, True)
return callable_obj
return wrapper | Plugin Method decorator.
Signs a web handler function with the plugins to be applied as attributes.
Args:
plugin_names (list): A list of plugin callable names
Returns:
A wrapped handler callable.
Examples:
>>> @plugin_method('json', 'bill')
... def method():
... return "Hello!"
...
>>> print method.json
True
>>>... | juraj-google-style |
def longestNumber(self, inp):
split = inp.split(' ')
numStart = None
numEnd = None
for i, w in enumerate(split):
if self.isValid(w):
if numStart is None:
numStart = i
numEnd = i
else:
... | Extracts the longest valid numerical description from a string.
Not guaranteed to return a result even if some valid numerical
description exists (i.e., method is not particularly advanced).
Args:
inp (str): An arbitrary string, hopefully containing a number.
Returns:
The number with the longest string description in... | juraj-google-style |
def _ParseCachedEntryXP(self, value_data, cached_entry_offset):
try:
cached_entry = self._ReadStructureFromByteStream(
value_data[cached_entry_offset:], cached_entry_offset,
self._cached_entry_data_type_map)
except (ValueError, errors.ParseError) as exception:
raise errors.P... | Parses a Windows XP cached entry.
Args:
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.
Returns:
AppCompatCacheCachedEntry: cached entry.
Raises:
ParseError: if the value data could not be parsed. | juraj-google-style |
def get_signatures_from_saved_model(saved_model_path: str, signature_keys: Optional[Sequence[str]]=None, tags: Optional[Collection[str]]=None) -> Dict[str, meta_graph_pb2.SignatureDef]:
if tags is None:
tags = {tag_constants.SERVING}
loader = saved_model_loader.SavedModelLoader(saved_model_path)
met... | Gets a map from signature keys to their SignatureDef.
Args:
saved_model_path: Path to the saved model.
signature_keys: List of keys identifying SignatureDef to retrieve. If None,
retrieve all except the init signature.
tags: Set of tags identifying the MetaGraphDef within the SavedModel.
Returns:
A map from signature... | github-repos |
def select_embedding_from_tag(cur, embedding_tag, target_nodelist, target_edgelist):
encoded_data = {'num_nodes': len(target_nodelist), 'num_edges': len(target_edgelist), 'edges': json.dumps(target_edgelist, separators=(',', ':')), 'tag': embedding_tag}
select = '\n SELECT\n source_node,\n ... | Select an embedding from the given tag and target graph.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.
source_nodelist (list):
The nodes in the source graph. Should be integer valued.
source_edgelist (list):
The edges in the source graph.
ta... | codesearchnet |
def mkzip(archive, items, mode="w", save_full_paths=False):
close = False
try:
if not isinstance(archive, zipfile.ZipFile):
archive = zipfile.ZipFile(archive, mode, allowZip64=True)
close = True
logger.info("mkdzip: Creating %s, from: %s", archive.filename, items)
... | Recursively zip a directory.
Args:
archive (zipfile.ZipFile or str): ZipFile object add to or path to the
output zip archive.
items (str or list of str): Single item or list of items (files and
directories) to be added to zipfile.
mode (str): w for create new and write a for append to.
save_full_paths (bool): Preserve... | juraj-google-style |
def list(self,params=None, headers=None):
path = '/creditor_bank_accounts'
response = self._perform_request('GET', path, params, headers,
retry_failures=True)
return self._resource_for(response) | List creditor bank accounts.
Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your
creditor bank accounts.
Args:
params (dict, optional): Query string parameters.
Returns:
CreditorBankAccount | juraj-google-style |
def get(path, objectType, user=None):
ret = {'Path': path,
'ACLs': []}
sidRet = _getUserSid(user)
if path and objectType:
dc = daclConstants()
objectTypeBit = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectTypeBit)
tdacl = _get_dacl(path, ... | Get the ACL of an object. Will filter by user if one is provided.
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: A user name to filter by
Returns (dict): A dictionary containing the ACL
CLI Example:
.. code-block:: bash
salt 'minion-id' win_dacl.get c:\temp dire... | juraj-google-style |
def attribute(self, name):
return super(Map, self).attribute(self._inputs[0], name) | Expression for an input attribute.
An input attribute is an attribute on the input
port of the operator invocation.
Args:
name(str): Name of the attribute.
Returns:
Expression: Expression representing the input attribute. | juraj-google-style |
def ParseGshadowEntry(self, line):
fields = ("name", "passwd", "administrators", "members")
if line:
rslt = dict(zip(fields, line.split(":")))
name = rslt["name"]
pw_entry = self.shadow.setdefault(name, rdf_client.PwEntry())
pw_entry.store = self.shadow_store
pw_entry.h... | Extract the members of each group from /etc/gshadow.
Identifies the groups in /etc/gshadow and several attributes of the group,
including how the password is crypted (if set).
gshadow files have the format group_name:passwd:admins:members
admins are both group members and can manage passwords and memberships.
Args:
... | juraj-google-style |
def decode(self):
if (self.encoding >= self.public_key.n):
raise ValueError('Attempted to decode corrupted number')
elif (self.encoding <= self.public_key.max_int):
mantissa = self.encoding
elif (self.encoding >= (self.public_key.n - self.public_key.max_int)):
mantissa = (self.encodi... | Decode plaintext and return the result.
Returns:
an int or float: the decoded number. N.B. if the number
returned is an integer, it will not be of type float.
Raises:
OverflowError: if overflow is detected in the decrypted number. | codesearchnet |
def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise errors.BadReaderParamsError("Input reader class mismatch")
params = _get_params(mapper_spec, allowed_keys=cls._PARAMS)
if (cls.VERSION_IDS_PARAM not in params and
cls.MODULE_VERSIONS_PARAM not in params):
... | Validates the mapper's specification and all necessary parameters.
Args:
mapper_spec: The MapperSpec to be used with this InputReader.
Raises:
BadReaderParamsError: If the user fails to specify both a starting time
and an ending time, or if the starting time is later than the ending
time. | juraj-google-style |
def get_servo_angle(self):
servoposition = self.get_servo_position()
if ((self.servomodel == 6) or (self.servomodel == 4)):
return scale(servoposition, 10627, 22129, (- 159.9), 159.6)
else:
return scale(servoposition, 21, 1002, (- 150), 150) | Gets the current angle of the servo in degrees
Args:
none
Returns:
int : the current servo angle | codesearchnet |
def neighborhood_probability(self, threshold, radius):
weights = disk(radius, dtype=np.uint8)
thresh_data = np.zeros(self.data.shape[1:], dtype=np.uint8)
neighbor_prob = np.zeros(self.data.shape, dtype=np.float32)
for t in np.arange(self.data.shape[0]):
thresh_data[s... | Calculate a probability based on the number of grid points in an area that exceed a threshold.
Args:
threshold:
radius:
Returns: | juraj-google-style |
def _FormatIPCPermToken(self, token_data):
return {
'user_id': token_data.user_identifier,
'group_id': token_data.group_identifier,
'creator_user_id': token_data.creator_user_identifier,
'creator_group_id': token_data.creator_group_identifier,
'access': token_data.access... | Formats an IPC permissions token as a dictionary of values.
Args:
token_data (bsm_token_data_ipc_perm): AUT_IPC_PERM token data.
Returns:
dict[str, str]: token values. | juraj-google-style |
def abort_all(reason, extras=None):
raise signals.TestAbortAll(reason, extras) | Abort all subsequent tests, including the ones not in this test class or
iteration.
Args:
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortAll: Abort all subsequent tests. | github-repos |
def extend(self, elts):
elts = elts[:]
self._in_deque.append(elts)
event = self._event_for(elts)
self._event_deque.append(event)
return event | Adds elts to the tasks.
Args:
elts (Sequence): a iterable of elements that can be appended to the
task's bundle_field.
Returns:
Event: an event that can be used to wait on the response. | codesearchnet |
def read(self, size=None):
if not self._is_open:
raise IOError('Not opened.')
if self._fsntfs_data_stream:
return self._fsntfs_data_stream.read(size=size)
return self._fsntfs_file_entry.read(size=size) | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
bytes: data read.
Raises:
IOError: if... | juraj-google-style |
def _process_update(self, item, feed_item):
lp = self.landing_page_dao.get(feed_item, required=True)
feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_ID] = lp['id']
feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_NAME] = lp['name']
item['startDate'] = StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap... | Updates a campaign based on the values from the feed.
Args:
item: Object representing the campaign to be updated, this object is
updated directly.
feed_item: Feed item representing campaign values from the Bulkdozer feed. | github-repos |
def ParseOptions(cls, options, analysis_plugin):
if not isinstance(analysis_plugin, nsrlsvr.NsrlsvrAnalysisPlugin):
raise errors.BadConfigObject(
'Analysis plugin is not an instance of NsrlsvrAnalysisPlugin')
label = cls._ParseStringOption(
options, 'nsrlsvr_label', default_value=c... | Parses and validates options.
Args:
options (argparse.Namespace): parser options object.
analysis_plugin (NsrlsvrAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the analysis plugin is the wrong type.
BadConfigOption: when unable to connect to nsrlsvr instance. | juraj-google-style |
def CreateSubdivision(self, parent=None, value=None):
division = {'xsi_type': 'ProductPartition', 'partitionType': 'SUBDIVISION', 'id': str(self.next_id)}
if (parent is not None):
division['parentCriterionId'] = parent['id']
division['caseValue'] = value
adgroup_criterion = {'xsi_type': 'Bid... | Creates a subdivision node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
Returns:
A new subdivision node. | codesearchnet |
def _send_offset_fetch_request(self, partitions):
assert self.config['api_version'] >= (0, 8, 1), 'Unsupported Broker API'
assert all(map(lambda k: isinstance(k, TopicPartition), partitions))
if not partitions:
return Future().success({})
node_id = self.coordinator(... | Fetch the committed offsets for a set of partitions.
This is a non-blocking call. The returned future can be polled to get
the actual offsets returned from the broker.
Arguments:
partitions (list of TopicPartition): the partitions to fetch
Returns:
Future: resolves to dict of offsets: {TopicPartition: int} | juraj-google-style |
def word_error_rate(raw_predictions,
labels,
lookup=None,
weights_fn=common_layers.weights_nonzero):
def from_tokens(raw, lookup_):
gathered = tf.gather(lookup_, tf.cast(raw, tf.int32))
joined = tf.regex_replace(tf.reduce_join(gathered, axis=1), ... | Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to output tokens.
weights_fn: Weighting function.
Returns:
The word error rate. | juraj-google-style |
def ends_with(self, suffix):
suffix = suffix.lower()
found_words = []
res = cgaddag.gdg_ends_with(self.gdg, suffix.encode(encoding='ascii'))
tmp = res
while tmp:
word = tmp.contents.str.decode('ascii')
found_words.append(word)
tmp = tmp.contents.next
cgaddag.gdg_destroy_r... | Find all words ending with a suffix.
Args:
suffix: A suffix to be searched for.
Returns:
A list of all words found. | codesearchnet |
def load_metadata_for_topics(self, *topics, **kwargs):
if ('ignore_leadernotavailable' in kwargs):
ignore_leadernotavailable = kwargs['ignore_leadernotavailable']
else:
ignore_leadernotavailable = False
if topics:
self.reset_topic_metadata(*topics)
else:
self.reset_all_me... | Fetch broker and topic-partition metadata from the server.
Updates internal data: broker list, topic/partition list, and
topic/partition -> broker map. This method should be called after
receiving any error.
Note: Exceptions *will not* be raised in a full refresh (i.e. no topic
list). In this case, error codes will b... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.