code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def get_gap(self, tol=0.001, abs_tol=False, spin=None):
(cbm, vbm) = self.get_cbm_vbm(tol, abs_tol, spin)
return max((cbm - vbm), 0.0) | Expects a DOS object and finds the gap.
Args:
tol: tolerance in occupations for determining the gap
abs_tol: An absolute tolerance (True) and a relative one (False)
spin: Possible values are None - finds the gap in the summed
densities, Up - finds the gap in the up spin channel,
Down - finds the gap in the down spin c... | codesearchnet |
def get_uri(self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None):
if is_list:
return self._get_typed_list_value(key=key, target_type=UriSpec, type_convert=self.parse_uri_spec, is_optional=is_optional, is_secret=is_secret, is_local=is_local, default=defaul... | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_opt... | codesearchnet |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
devices = match.get('Devices', {})
for (device_identifier, device_information) in iter(devices.items()):
datetime_value = device_information.get('Connected', None)
if (not datetime_value):
continue
event_data... | Extract device information from the iPod plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | codesearchnet |
def batch_frexp(inputs, max_bit=31):
shape_of_input = inputs.size()
inputs = inputs.view(-1)
output_m, output_e = np.frexp(inputs.cpu().numpy())
tmp_m = []
for m in output_m:
int_m_shifted = int(decimal.Decimal(m * 2 ** max_bit).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))... | Decompose the scaling factor into mantissa and twos exponent.
Args:
scaling_factor (`torch.Tensor`):
Target scaling factor to decompose.
Returns:
``Tuple(torch.Tensor, torch.Tensor)`: mantisa and exponent | github-repos |
def transformer_moe_2k():
hparams = transformer_moe_8k()
hparams.batch_size = 2048
hparams.default_ff = 'sep'
encoder_archi = 'a/a/a/a/a'
decoder_archi = 'a-sepm/a-sepm/a-moe/a-sepm/a-sepm'
hparams.layer_types = '{}
return hparams | Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention... | codesearchnet |
def load_stopwords(self, path):
if path:
with open(path) as f:
self.stopwords = set(f.read().splitlines())
else:
self.stopwords = set(pkgutil.get_data('textplot', 'data/stopwords.txt').decode('utf8').splitlines()) | Load a set of stopwords.
Args:
path (str): The stopwords file path. | codesearchnet |
def For(start, limit, delta, inputs, body, name=None, hostmem=None, rewrite_with_while=None):
if rewrite_with_while:
return _ForUsingWhile(start, limit, delta, inputs, body, name, hostmem)
if body.captured_inputs:
ret = gen_functional_ops._for(start, limit, delta, inputs + body.captured_inputs, ... | out = input; for i in range(start, limit, delta) out = body(i, out).
Args:
start: A `Tensor` of type `int32`.
limit: A `Tensor` of type `int32`.
delta: A `Tensor` of type `int32`.
inputs: A list of `Tensor` objects. A list of input tensors whose types are
T.
body: A function takes a list of tensors and returns another... | github-repos |
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
y_pred_rank = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred).shape.ndims
y_true_rank = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_true).shape.ndims
if y_true_rank is not None and y_pred_rank is not None:
if y_pred_... | Computes how often integer targets are in the top `K` predictions.
Standalone usage:
>>> y_true = [2, 1]
>>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
>>> m = tf.keras.metrics.sparse_top_k_categorical_accuracy(
... y_true, y_pred, k=3)
>>> assert m.shape == (2,)
>>> m.numpy()
array([1., 1.], dtype=float32)
Args... | github-repos |
def __init__(
self, name, description='', creator='', raw={}):
BossResource.__init__(self, name, description, creator, raw) | Constructor.
Args:
name (string): Collection name.
description (optional[string]): Collection description. Defaults to empty.
creator (optional[string]): Resource creator.
raw (optional[dictionary]): Holds JSON data returned by the Boss API on a POST (create) or GET operation. | juraj-google-style |
def _wrap_method(name):
method = getattr(datetime.datetime, name)
@functools.wraps(method, ("__name__", "__doc__"), ())
def wrapper(self, *args, **kw):
r = method(self, *args, **kw)
if isinstance(r, datetime.datetime) and not isinstance(r, type(self)):
r = type(self)(r)
return r
setat... | Wrap a method.
Patch a method which might return a datetime.datetime to return a
datetime_tz.datetime_tz instead.
Args:
name: The name of the method to patch | juraj-google-style |
def compute_video_metrics_from_predictions(predictions, decode_hparams):
all_results = {}
(ssim_all_decodes, psnr_all_decodes) = ([], [])
for single_decode in predictions:
args = get_zipped_dataset_from_predictions(single_decode)
(psnr_single, ssim_single) = compute_one_decoding_video_metric... | Computes metrics from predictions.
Args:
predictions: list of list of dicts.
outer length: num_decodes, inner_length: num_samples
decode_hparams: Decode hparams. instance of HParams.
Returns:
statistics: dict of Tensors, key being the metric with each Tensor
having the shape (num_samples, num_frames). | codesearchnet |
def bytes(self) -> bytes | None:
if self.part.text:
return self.text.encode()
if isinstance(self.part.inline_data, genai_types.Blob):
return self.part.inline_data.data
return None | Returns part contents as bytes.
Returns:
Text encoded into bytes or bytes from inline data if the underlying part
is a Blob. | github-repos |
def apply(self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction:
result_dict: dict[str, Any] = {}
_AggModelIdMixin.add_model_id(self, result_dict)
_SourcePredictionMixin.add_source_predictions(self, result_dict, predictions)
scores = [prediction.score for prediction in predictions if pred... | Applies the score aggregation function to a list of predictions.
Args:
predictions (Iterable[AnomalyPrediction]): A collection of
`AnomalyPrediction` objects to be aggregated.
Returns:
AnomalyPrediction: A single `AnomalyPrediction` object with the
aggregated score. The aggregated score is determined as follows:
- I... | github-repos |
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM':
assert self.status in ['connected', 'done']
prog = quil_to_program(str(binary))
self._prog = prog
self.program = binary
self.status = 'loaded'
return self | Load a pyQuil program, and initialize QVM into a fresh state.
Args:
binary: A pyQuil program | juraj-google-style |
def new_message_from_header(header):
message_type = header.message_type
if (not isinstance(message_type, Type)):
try:
if isinstance(message_type, str):
message_type = Type[message_type]
elif isinstance(message_type, int):
message_type = Type(messag... | Given an OF Header, return an empty message of header's message_type.
Args:
header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header.
Returns:
Empty OpenFlow message of the same type of message_type attribute from
the given header.
The header attribute of the message will be populated.
Raises:
KytosUndefi... | codesearchnet |
def publish(self, message):
if (not isinstance(message, types.PubsubMessage)):
message = types.PubsubMessage(**message)
future = None
with self._state_lock:
if (not self.will_accept(message)):
return future
new_size = (self._size + message.ByteSize())
new_count = ... | Publish a single message.
Add the given message to this object; this will cause it to be
published once the batch either has enough messages or a sufficient
period of time has elapsed.
This method is called by :meth:`~.PublisherClient.publish`.
Args:
message (~.pubsub_v1.types.PubsubMessage): The Pub/Sub message.
R... | codesearchnet |
def __call__(self, stream, content_type):
try:
return json.load(codecs.getreader('utf-8')(stream))
finally:
stream.close() | Decode a JSON object into the corresponding Python object.
Args:
stream (stream): The response stream to be deserialized.
content_type (str): The content type of the response.
Returns:
object: Body of the response deserialized into a JSON object. | juraj-google-style |
def _implicit_credentials_from_files():
credentials_filename = _get_environment_variable_file()
if (not credentials_filename):
credentials_filename = _get_well_known_file()
if os.path.isfile(credentials_filename):
extra_help = ' (produced automatically when running "gcloud auth login... | Attempts to get implicit credentials from local credential files.
First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS
is set with a filename and then falls back to a configuration file (the
"well known" file) associated with the 'gcloud' command line tool.
Returns:
Credentials object associated wi... | codesearchnet |
def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS):
batch_job_service = client.GetService('BatchJobService', 'v201809')
batch_job['status'] = 'CANCELING'
operation = {'operator': 'SET', 'operand': batch_job}
batch_job_service.mutate([operation])
poll_attempt = 0
while ((p... | Cancels the given BatchJob.
Args:
client: an instantiated AdWordsClient used to cancel the BatchJob.
batch_job: a BatchJob to be canceled.
max_poll_attempts: an int defining the number of times the BatchJob will be
checked to determine whether it has been canceled. | codesearchnet |
def assert_same_structure(nest1, nest2, check_types=True):
nest_util.assert_same_structure(nest_util.Modality.DATA, nest1, nest2, check_types) | Asserts that two structures are nested in the same way.
Args:
nest1: an arbitrarily nested structure.
nest2: an arbitrarily nested structure.
check_types: if `True` (default) types of sequences should be same as
well. For dictionary, "type" of dictionary is considered to include its
keys. In other words, two dictionar... | github-repos |
def __init__(self, date_time, date_time_description):
super(OLECFSummaryInformationEvent, self).__init__(
date_time, date_time_description)
self.name = 'Summary Information' | Initializes an event.
Args:
date_time (dfdatetime.DateTimeValues): date and time values.
date_time_description (str): description of the meaning of the date
and time values. | juraj-google-style |
def preprocess_image(image_buffer, output_height, output_width, num_channels, is_training=False):
if is_training:
image = _decode_crop_and_flip(image_buffer, num_channels)
mlperf_log.resnet_print(key=mlperf_log.INPUT_RESIZE, value=[output_height, output_width])
image = _resize_image(image, o... | Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion of the image to improve accuracy.
Args:
image_buffer: scalar string Tensor representing the raw JPEG image buffer.
output_height: ... | codesearchnet |
def find_importer_frame():
byte = (lambda ch: (ord(ch) if PY2 else ch))
frame = inspect.currentframe()
try:
while frame:
code = frame.f_code
lasti = frame.f_lasti
if (byte(code.co_code[lasti]) == dis.opmap['IMPORT_NAME']):
arg = (byte(code.co_code[... | Returns the outer frame importing this "end" module.
If this module is being imported by other means than import statement,
None is returned.
Returns:
A frame object or None. | codesearchnet |
def _create_environment(config):
if isinstance(config.env, str):
env = gym.make(config.env)
else:
env = config.env()
if config.max_length:
env = tools.wrappers.LimitDuration(env, config.max_length)
if isinstance(env.action_space, gym.spaces.Box):
if config.normalize_ranges:
env = tools.... | Constructor for an instance of the environment.
Args:
config: Object providing configurations via attributes.
Raises:
NotImplementedError: For action spaces other than Box and Discrete.
Returns:
Wrapped OpenAI Gym environment. | juraj-google-style |
def replace_batch_norm(model):
for name, module in model.named_children():
if isinstance(module, nn.BatchNorm2d):
new_module = GroundingDinoFrozenBatchNorm2d(module.num_features)
if not module.weight.device == torch.device('meta'):
new_module.weight.data.copy_(module.... | Recursively replace all `torch.nn.BatchNorm2d` with `GroundingDinoFrozenBatchNorm2d`.
Args:
model (torch.nn.Module):
input model | github-repos |
class PatchTSMixerForTimeSeriesClassification(PatchTSMixerPreTrainedModel):
def __init__(self, config: PatchTSMixerConfig):
super().__init__(config)
self.model = PatchTSMixerModel(config)
self.head = PatchTSMixerLinearHead(config=config)
self.use_return_dict = config.use_return_dict... | `PatchTSMixer` for classification application.
Args:
config (`PatchTSMixerConfig`):
Configuration.
Returns:
`None`. | github-repos |
def connected_emulators(self, host=enums.JLinkHost.USB):
res = self._dll.JLINKARM_EMU_GetList(host, 0, 0)
if res < 0:
raise errors.JLinkException(res)
num_devices = res
info = (structs.JLinkConnectInfo * num_devices)()
num_found = self._dll.JLINKARM_EMU_GetL... | Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.
Raises:
JLinkException: if fails to enumerate devices. | juraj-google-style |
def ragged_cumsum(x: ragged_tensor.Ragged, axis: int=0, exclusive: bool=False, reverse: bool=False, name: typing.Optional[str]=None):
with ops.name_scope(name, 'RaggedCumSum', [x, axis, exclusive, reverse]):
axis = array_ops.get_positive_axis(axis, x.shape.rank, ndims_name='rank')
if axis == x.ragge... | Calculate math_ops.cumsum for a RaggedTensor.
Given a ragged tensor `x`, the `result` is a ragged tensor with the same
shape. One can calculate the value of `result[i_1...i_k]` as follows:
```
dense_result=tf.math.cumsum(rt.to_tensor(), axis=axis, exclusive=exclusive,
reverse=reverse)
result[i_1...i_k]=dense_result[i_... | github-repos |
def CreateSession(cls, artifact_filter_names=None, command_line_arguments=None, debug_mode=False, filter_file_path=None, preferred_encoding='utf-8', preferred_time_zone=None, preferred_year=None):
session = sessions.Session()
session.artifact_filters = artifact_filter_names
session.command_line_arguments = ... | Creates a session attribute container.
Args:
artifact_filter_names (Optional[list[str]]): names of artifact definitions
that are used for filtering file system and Windows Registry
key paths.
command_line_arguments (Optional[str]): the command line arguments.
debug_mode (bool): True if debug mode was enabled.
filter_f... | codesearchnet |
def set_status(self, on, switch=1):
if isinstance(switch, int):
switch = str(switch)
payload = self.generate_payload(SET, {switch:on})
data = self._send_receive(payload)
log.debug('set_status received data=%r', data)
return data | Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set | juraj-google-style |
def draw_lines(self, *points):
point_array = ffi.new('SDL_Point[]', len(points))
for i, p in enumerate(points):
point_array[i] = p._ptr[0]
check_int_err(lib.SDL_RenderDrawLines(self._ptr, point_array, len(points))) | Draw a series of connected lines on the current rendering target.
Args:
*points (Point): The points along the lines.
Raises:
SDLError: If an error is encountered. | juraj-google-style |
def handle_event(self, event_handler, event_name, user_args, event_timeout=None, cond=None, cond_timeout=None):
worker = self.executor.submit(self._handle, event_handler, event_name, user_args, event_timeout, cond, cond_timeout)
return worker | Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
one argument - the event json object.
event_na... | codesearchnet |
def get_header(message, name):
header = message.get(name)
log.debug("Getting header {!r}: {!r}".format(name, header))
if header:
return decode_header_part(header)
return six.text_type() | Gets an email.message.Message and a header name and returns
the mail header decoded with the correct charset.
Args:
message (email.message.Message): email message object
name (string): header to get
Returns:
decoded header | juraj-google-style |
def suggestions(self, word):
suggestions = set(self._misspelling_dict.get(word, [])).union(
set(self._misspelling_dict.get(word.lower(), [])))
return sorted([same_case(source=word, destination=w)
for w in suggestions]) | Returns a list of suggestions for a misspelled word.
Args:
word: The word to check.
Returns:
List of zero or more suggested replacements for word. | juraj-google-style |
def dumps(o, encoder=None):
retval = ""
if encoder is None:
encoder = TomlEncoder(o.__class__)
addtoretval, sections = encoder.dump_sections(o, "")
retval += addtoretval
while sections:
newsections = encoder.get_empty_table()
for section in sections:
addtore... | Stringifies input dict as toml
Args:
o: Object to dump into toml
preserve: Boolean parameter. If true, preserve inline tables.
Returns:
String containing the toml corresponding to dict | juraj-google-style |
def __init__(self, section):
self.section = section
super().__init__('invalid section name: {}'.format(section)) | Initialization of instances:
Args:
section (str): invalid section name.
Attributes:
section (str): invalid section name. | juraj-google-style |
def color_string(self, x):
diff_str = ""
color = "black"
if len(x) == 2 and self.compare_file is not None:
difference = x[0] - x[1]
if difference:
color, sign = ('green', '-') if difference < 0 else ('red', '+')
diff_str = '{}{}'.... | Return a string formatted delta for the values in x.
Args:
x: 2-item list of integers (representing number of calls) or
2-item list of floats (representing seconds of runtime).
Returns:
A list with [formatted x[0], [color, formatted delta]], where
color reflects whether x[1] is lower, greater, or the same as
x[0]. | juraj-google-style |
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
if (((class_info.last_line - class_info.starting_linenum) <= 24) or (linenum <= class_info.starting_linenum)):
return
matched = Match('\\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
prev_li... | Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check... | codesearchnet |
def create_module_file(txt, directory):
name = nonpresent_module_filename()
path = os.path.join(directory, name)
with open(path, 'w') as fh:
fh.write(txt)
return path | Create a file in the given directory with
a valid module name populated with the given txt.
Returns:
A path to the file | codesearchnet |
def generate_encodeable_characters(characters: Iterable[str],
encodings: Iterable[str]) -> Iterable[str]:
for c in characters:
for encoding in encodings:
try:
c.encode(encoding)
yield c
except UnicodeEncodeError:... | Generates the subset of 'characters' that can be encoded by 'encodings'.
Args:
characters: The characters to check for encodeability e.g. 'abcd'.
encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5'].
Returns:
The subset of 'characters' that can be encoded using one of the provided
encodings. | juraj-google-style |
def __init__(self,
make_distribution_fn,
convert_to_tensor_fn=tfd.Distribution.sample,
**kwargs):
if isinstance(make_distribution_fn, six.string_types):
make_distribution_fn = _deserialize_function(make_distribut... | Create a `DistributionLambda` Keras layer.
Args:
make_distribution_fn: Python `callable` that takes previous layer outputs
and returns a `tfd.Distribution` instance.
convert_to_tensor_fn: Python `callable` that takes a `tfd.Distribution`
instance and returns a `tf.Tensor`-like object. For examples, see
`class` docstri... | juraj-google-style |
def padFrameRange(frange, zfill):
def _do_pad(match):
'\n Substitutes padded for unpadded frames.\n '
result = list(match.groups())
result[1] = pad(result[1], zfill)
if result[4]:
result[4] = pad(result[4], zfill)
return ''.join((i for i in ... | Return the zero-padded version of the frame range string.
Args:
frange (str): a frame range to test
zfill (int):
Returns:
str: | codesearchnet |
def project(self, **kwargs: Dict[str, Any]) -> Union[Hist, Dict[str, Hist]]:
if self.single_observable_projection:
return self._project_single_observable(**kwargs)
else:
return self._project_dict(**kwargs) | Perform the requested projection(s).
Note:
All cuts on the original histograms will be reset when this function is completed.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram(s). The projected histograms are also stored in ``outp... | juraj-google-style |
def UpdateNumberOfEvents(
self, number_of_consumed_events, number_of_produced_events):
consumed_events_delta = 0
if number_of_consumed_events is not None:
if number_of_consumed_events < self.number_of_consumed_events:
raise ValueError(
'Number of consumed events smaller than... | Updates the number of events.
Args:
number_of_consumed_events (int): total number of events consumed by
the process.
number_of_produced_events (int): total number of events produced by
the process.
Returns:
bool: True if either number of events has increased.
Raises:
ValueError: if the consumed or produced number of... | juraj-google-style |
def get_list(self, id, name=None):
return self.create_list(dict(id=id, name=name)) | Get a list
Returns:
List: The list with the given `id` | codesearchnet |
def set_pattern_actual_step(self, patternnumber, value):
_checkPatternNumber(patternnumber)
_checkStepNumber(value)
address = _calculateRegisterAddress('actualstep', patternnumber)
self.write_register(address, value, 0) | Set the 'actual step' parameter for a given pattern.
Args:
* patternnumber (integer): 0-7
* value (integer): 0-7 | codesearchnet |
def dump(voevent, file, pretty_print=True, xml_declaration=True):
file.write(dumps(voevent, pretty_print, xml_declaration)) | Writes the voevent to the file object.
e.g.::
with open('/tmp/myvoevent.xml','wb') as f:
voeventparse.dump(v, f)
Args:
voevent(:class:`Voevent`): Root node of the VOevent etree.
file (io.IOBase): An open (binary mode) file object for writing.
pretty_print
pretty_print(bool): See :func:`dumps`
xml_declaration(bool): ... | codesearchnet |
def from_ops(*operations: ops.OP_TREE,
strategy: InsertStrategy = InsertStrategy.EARLIEST,
device: devices.Device = devices.UnconstrainedDevice
) -> 'Circuit':
result = Circuit(device=device)
result.append(operations, strategy)
return r... | Creates an empty circuit and appends the given operations.
Args:
operations: The operations to append to the new circuit.
strategy: How to append the operations.
device: Hardware that the circuit should be able to run on.
Returns:
The constructed circuit containing the operations. | juraj-google-style |
def concat(values, axis, name: str='concat'):
if name is None:
name = 'concat'
_assert_concat_compatible_structured_tensors(values)
def leaf_op(values):
return array_ops.concat(values, axis)
axis = array_ops.get_positive_axis(axis, values[0].rank)
with ops.name_scope(name, 'Structur... | tf.concat for structured tensors.
Does not support (yet) checks on illegal axis values, et cetera.
Args:
values: a sequence of StructuredTensors.
axis: an axis to concatenate upon.
name: the name of the op(s).
Returns:
the params reorganized according to indices. | github-repos |
def get_variation_for_experiment(self, experiment_id):
return self.experiment_bucket_map.get(experiment_id, {self.VARIATION_ID_KEY: None}).get(self.VARIATION_ID_KEY) | Helper method to retrieve variation ID for given experiment.
Args:
experiment_id: ID for experiment for which variation needs to be looked up for.
Returns:
Variation ID corresponding to the experiment. None if no decision available. | juraj-google-style |
def delete_direct(self, addresses):
with self._lock:
for address in addresses:
self._validate_write(address)
if address in self._state:
self._state[address].set_deleted()
else:
fut = _ContextFuture(addr... | Called in the context manager's delete method to either
mark an entry for deletion , or create a new future and immediately
set it for deletion in the future.
Args:
address_list (list of str): The unique full addresses.
Raises:
AuthorizationException | juraj-google-style |
def process_alias_export_namespace(namespace):
namespace.export_path = os.path.abspath(namespace.export_path)
if os.path.isfile(namespace.export_path):
raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))
export_path_dir = os.path.dirname(namespace.export_path)
if not os... | Validate input arguments when the user invokes 'az alias export'.
Args:
namespace: argparse namespace object. | juraj-google-style |
def of(cls, key: SearchKey, params: SearchParams) -> 'SearchCriteria':
key_name = key.value
if key_name in params.disabled:
raise SearchNotAllowed(key_name)
elif key.inverse:
return InverseSearchCriteria(key.not_inverse, params)
elif key_name == b'SEQSET'... | Factory method for producing a search criteria sub-class from a
search key.
Args:
key: The search key defining the criteria.
params: The parameters that may be used by some searches. | juraj-google-style |
def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):
try:
results = query_phenomizer.query(username, password, *hpo_ids)
diseases = [result for result in results if (result['p_value'] <= p_value_treshold)]
return diseases
except SystemExit:
return None | Return the list of HGNC symbols that match annotated HPO terms.
Args:
username (str): username to use for phenomizer connection
password (str): password to use for phenomizer connection
Returns:
query_result: a generator of dictionaries on the form
{
'p_value': float,
'disease_source': str,
'disease_nr': int,
'gene_s... | codesearchnet |
def ucast_ip(ip_addr, return_tuple=True):
regex_ucast_ip = __re.compile("^((22[0-3])|(2[0-1][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))$")
if return_t... | Function to check if a address is unicast
Args:
ip_addr: Unicast IP address in the following format 192.168.1.1
return_tuple: Set to True it returns a IP, set to False returns True or False
Returns: see return_tuple for return options | juraj-google-style |
def _rpc(self, method, *args):
with self._lock:
apiid = next(self._counter)
data = {'id': apiid, 'method': method, 'params': args}
request = json.dumps(data)
self._client_send(request)
response = self._client_receive()
if not response:... | Sends an rpc to the app.
Args:
method: str, The name of the method to execute.
args: any, The args of the method.
Returns:
The result of the rpc.
Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors. | juraj-google-style |
def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):
done = False
records = {}
page = 1
while (not done):
kwargs['page'] = page
response = self.__cloudflare_request(account=account, path='/zones/{}/dns_records'.format(zoneID), args=kwargs)
info = response['resu... | Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and
their information.
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
zoneID (`int`): Internal CloudFlare ID of the DNS zone
**kwargs (`dict`): Additional arguments to be consumed by the API end... | codesearchnet |
def run(func, options, args=(), kwargs={}, host='localhost', port=8000):
run_stats = run_profilers((func, args, kwargs), options)
result = None
for prof in run_stats:
if (not result):
result = run_stats[prof]['result']
del run_stats[prof]['result']
post_data = gzip.compress(j... | Runs profilers on a function.
Args:
func: A Python function.
options: A string with profilers configuration (i.e. 'cmh').
args: func non-keyword arguments.
kwargs: func keyword arguments.
host: Host name to send collected data.
port: Port number to send collected data.
Returns:
A result of func execution. | codesearchnet |
def _pool(inputs, initial_value, reduce_fn, pool_size, strides=None, padding='valid'):
if padding not in ('same', 'valid'):
raise ValueError(f"Invalid padding '{padding}', must be 'same' or 'valid'.")
padding = padding.upper()
return lax.reduce_window(inputs, initial_value, reduce_fn, pool_size, str... | Helper function to define pooling functions.
Args:
inputs: input data of shape `N+2`.
initial_value: the initial value for the reduction.
reduce_fn: a reduce function of the form `(T, T) -> T`.
pool_size: a sequence of `N` integers, representing the window size to
reduce over.
strides: a sequence of `N` integers, repr... | github-repos |
def offTagAdd(self, name, func):
if ('*' in name):
self.ontagaddglobs.rem(name, func)
return
cblist = self.ontagadds.get(name)
if (cblist is None):
return
try:
cblist.remove(func)
except ValueError:
pass | Unregister a callback for tag addition.
Args:
name (str): The name of the tag or tag glob.
func (function): The callback func(node, tagname, tagval). | codesearchnet |
def _cast_value(self, value):
if (self.convert_datetimes):
try:
date_time = datetime.datetime.fromtimestamp(float(value))
if datetime.datetime(1970, 1, 1) > date_time:
raise ValueError
else:
ret... | Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
value : The value to be casted
Returns:
A casted Value. | juraj-google-style |
def distribute_tensor(tensor, layout):
if isinstance(tensor, KerasTensor):
return tensor
return distribution_lib.distribute_tensor(tensor, layout) | Change the layout of a Tensor value in the jit function execution.
Args:
tensor: a Tensor to change the layout.
layout: `TensorLayout` to be applied on the value.
Returns:
a new value with the specified tensor layout. | github-repos |
def delete(self, id, **kwargs):
if (id is None):
path = self.path
else:
if (not isinstance(id, int)):
id = id.replace('/', '%2F')
path = ('%s/%s' % (self.path, id))
self.gitlab.http_delete(path, **kwargs) | Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | codesearchnet |
def quadratic_2d(data):
arg_data_max = np.argmax(data)
i, j = np.unravel_index(arg_data_max, data.shape)
z_ = data[i-1:i+2, j-1:j+2]
try:
a = (-z_[0,0] + 2*z_[0,1] - z_[0,2] + 2*z_[1,0] + 5*z_[1,1] + 2*z_[1,2] -
z_[2,0] + 2*z_[2,1] - z_[2,2]) / 9
... | Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively | juraj-google-style |
def get(self, ID, index='vector-web-s'):
url = self.get_url % index
r = self.gbdx_connection.get(url + ID)
r.raise_for_status()
return r.json() | Retrieves a vector. Not usually necessary because searching is the best way to find & get stuff.
Args:
ID (str): ID of the vector object
index (str): Optional. Index the object lives in. defaults to 'vector-web-s'
Returns:
record (dict): A dict object identical to the json representation of the catalog record | juraj-google-style |
def forward(self, inputs_embeddings=None, output_attentions=None, output_hidden_states=None, return_dict=None):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.conf... | Args:
inputs_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Flattened feature map (output of the backbone + projection layers) that is passed to the encoder.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `att... | github-repos |
def __init__(self, timestep, natoms, box, data):
self.timestep = timestep
self.natoms = natoms
self.box = box
self.data = data | Base constructor.
Args:
timestep (int): Current timestep.
natoms (int): Total number of atoms in the box.
box (LammpsBox): Simulation box.
data (pd.DataFrame): Dumped atomic data. | juraj-google-style |
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. | juraj-google-style |
def _get_fullname(obj):
if not hasattr(obj, "__name__"):
obj = obj.__class__
if obj.__module__ in ("builtins", "__builtin__"):
return obj.__name__
return "{}.{}".format(obj.__module__, obj.__name__) | Get the full name of an object including the module.
Args:
obj: An object.
Returns:
The full class name of the object. | juraj-google-style |
def set_scf_algorithm_and_iterations(self, algorithm="diis",
iterations=50):
available_algorithms = {"diis", "dm", "diis_dm", "diis_gdm", "gdm",
"rca", "rca_diis", "roothaan"}
if algorithm.lower() not in available_algorith... | Set algorithm used for converging SCF and max number of SCF iterations.
Args:
algorithm: The algorithm used for converging SCF. (str)
iterations: The max number of SCF iterations. (Integer) | juraj-google-style |
def _finalize_outputs(cls, mapreduce_spec, mapreduce_state):
if (mapreduce_spec.mapper.output_writer_class() and
mapreduce_state.result_status == model.MapreduceState.RESULT_SUCCESS):
mapreduce_spec.mapper.output_writer_class().finalize_job(mapreduce_state) | Finalize outputs.
Args:
mapreduce_spec: an instance of MapreduceSpec.
mapreduce_state: an instance of MapreduceState. | juraj-google-style |
def create_game(self, map_name):
map_inst = maps.get(map_name)
map_data = map_inst.data(self._run_config)
if map_name not in self._saved_maps:
for controller in self._controllers:
controller.save_map(map_inst.path, map_data)
self._saved_maps.add(map_name)
create = sc_pb.Re... | Create a game for the agents to join.
Args:
map_name: The map to use. | juraj-google-style |
def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
out = []
for i, hidden_state in enumerate(hidden_states):
if i not in self.neck_ignore_stages:
cls_token, hidden_state = (hidden_state[:, 0], hidden_state[:, 1:])
batc... | Args:
hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
List of hidden states from the backbone. | github-repos |
def connect_engine(self):
try:
self.connection = self.engine.connect()
return True
except sa.exc.OperationalError as opex:
LOG.fatal("Could not connect to the database. The error was: '%s'", str(opex))
return False | Establish a connection to the database.
Provides simple error handling for fatal errors.
Returns:
True, if we could establish a connection, else False. | codesearchnet |
def _ReadStreamDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
if is_member:
supported_definition_values = self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_MEMBER_DATA_TYPE
else:
supported_definition_values = self._SUPPORTED_DEFINITION_VALUES_ELEMEN... | Reads a stream data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type definition is a member
data type defi... | codesearchnet |
def write_to_path(self,path,suffix='',format='png',overwrite=False):
if os.path.exists(path) and overwrite is False: raise ValueError("Error: use ovewrite=True to overwrite images")
if not os.path.exists(path): os.makedirs(path)
for i,r in self.iterrows():
spath = os.path.jo... | Output the data the dataframe's 'image' column to a directory structured by project->sample and named by frame
Args:
path (str): Where to write the directory of images
suffix (str): for labeling the imaages you write
format (str): default 'png' format to write the file
overwrite (bool): default False. if true can over... | juraj-google-style |
def get_extrema(self, normalize_rxn_coordinate=True):
x = np.arange(0, np.max(self.r), 0.01)
y = (self.spline(x) * 1000)
scale = (1 if (not normalize_rxn_coordinate) else (1 / self.r[(- 1)]))
min_extrema = []
max_extrema = []
for i in range(1, (len(x) - 1)):
if ((y[i] < y[(i - 1)]) and (... | Returns the positions of the extrema along the MEP. Both local
minimums and maximums are returned.
Args:
normalize_rxn_coordinate (bool): Whether to normalize the
reaction coordinate to between 0 and 1. Defaults to True.
Returns:
(min_extrema, max_extrema), where the extrema are given as
[(x1, y1), (x2, y2), ...]. | codesearchnet |
def install(self, ref, table_name=None, index_columns=None,logger=None):
try:
obj_number = ObjectNumber.parse(ref)
if isinstance(obj_number, TableNumber):
table = self._library.table(ref)
connection = self._backend._get_connection()
... | Finds partition by reference and installs it to warehouse db.
Args:
ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. | juraj-google-style |
def _fill_from_default(self, default_job_config):
if (self._job_type != default_job_config._job_type):
raise TypeError(((('attempted to merge two incompatible job types: ' + repr(self._job_type)) + ', ') + repr(default_job_config._job_type)))
new_job_config = self.__class__()
default_job_properties ... | Merge this job config with a default job config.
The keys in this object take precedence over the keys in the default
config. The merge is done at the top-level as well as for keys one
level below the job type.
Arguments:
default_job_config (google.cloud.bigquery.job._JobConfig):
The default job config that will be u... | codesearchnet |
def set_bool(self, location, value):
element = self._handle_location(location)
if isinstance(value, basestring):
value = True if value.upper() == "TRUE" else False
elif not isinstance(value, bool):
raise ValueError
if value is True:
element.te... | Set a boolean value.
Casper booleans in XML are string literals of "true" or "false".
This method sets the text value of "location" to the correct
string representation of a boolean.
Args:
location: Element or a string path argument to find()
value: Boolean or string value to set. (Accepts
"true"/"True"/"TRUE"; all o... | juraj-google-style |
def update_detector(self, detector_id, detector):
resp = self._put(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id), data=detector)
resp.raise_for_status()
return resp.json() | Update an existing detector.
Args:
detector_id (string): the ID of the detector.
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (updated detector model). | codesearchnet |
def commit(self):
commit_response = self._client._firestore_api.commit(self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata)
self._write_pbs = []
self.write_results = results = list(commit_response.write_results)
self.commit_time = commit_response.commit_... | Commit the changes accumulated in this batch.
Returns:
List[google.cloud.proto.firestore.v1beta1.\
write_pb2.WriteResult, ...]: The write results corresponding
to the changes committed, returned in the same order as the
changes were applied to this batch. A write result contains an
``update_time`` field. | codesearchnet |
def _create_mirrored_tpu_replicated_variables(**kwargs):
initial_value = kwargs['initial_value']
with maybe_init_scope():
initial_value = initial_value() if callable(initial_value) else initial_value
mirrored_replicated_var_list = []
for replica_id in range(num_replicas):
replicated_var_... | Returns a list of `TPUReplicatedVariable`s.
The list consists of `num_replicas` `TPUReplicatedVariable`s and can be
used to initialize a `TPUMirroredVariable`. Each `TPUReplicatedVariable`
contains a list of `tf.Variable`s which are replicated to
`num_cores_per_replica` logical cores to enable XLA SPMD compilation.
A... | github-repos |
def start_entry(self, target, var_id):
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_i... | Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the... | juraj-google-style |
def _construct_location_to_filter_list(match_query):
location_to_filters = {}
for match_traversal in match_query.match_traversals:
for match_step in match_traversal:
current_filter = match_step.where_block
if current_filter is not None:
current... | Return a dict mapping location -> list of filters applied at that location.
Args:
match_query: MatchQuery object from which to extract location -> filters dict
Returns:
dict mapping each location in match_query to a list of
Filter objects applied at that location | juraj-google-style |
def local_conv1d(inputs, kernel, kernel_size, strides, data_format=None):
output_shape = (kernel.shape[0],)
return local_conv(inputs, kernel, kernel_size, strides, output_shape, data_format) | Apply 1D conv with un-shared weights.
Args:
inputs: 3D tensor with shape:
(batch_size, steps, input_dim)
if data_format is "channels_last" or
(batch_size, input_dim, steps)
if data_format is "channels_first".
kernel: the unshared weight for convolution,
with shape (output_length, feature_dim, filters).
kernel_size: a ... | github-repos |
def sort_elements_by_child_values(obj_pyxb, child_name_list):
obj_pyxb.sort(key=(lambda x: [get_auto(getattr(x, n)) for n in child_name_list])) | In-place sort simple or complex elements in a PyXB object by values they contain
in child elements.
Args:
obj_pyxb: PyXB object
child_name_list: list of str
List of element names that are direct children of the PyXB object. | codesearchnet |
def Lock(fd, path, blocking):
operation = (fcntl.LOCK_EX if blocking else (fcntl.LOCK_EX | fcntl.LOCK_NB))
try:
fcntl.flock(fd, operation)
except IOError as e:
if (e.errno == errno.EWOULDBLOCK):
raise IOError(('Exception locking %s. File already locked.' % path))
else:
... | Lock the provided file descriptor.
Args:
fd: int, the file descriptor of the file to lock.
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Raises:
IOError, raised from flock while attempting to lock a file. | codesearchnet |
def get_excel_workbook(api_data, result_info_key, identifier_keys):
cleaned_data = []
for item_data in api_data:
result_info = item_data.pop(result_info_key, {})
cleaned_item_data = {}
if 'meta' in item_data:
meta = item_data.pop('meta')
cleaned_item_data... | Generates an Excel workbook object given api_data returned by the Analytics API
Args:
api_data: Analytics API data as a list of dicts (one per identifier)
result_info_key: the key in api_data dicts that contains the data results
identifier_keys: the list of keys used as requested identifiers
(address, zipcode, block_i... | juraj-google-style |
def key_periods(ciphertext, max_key_period):
if (max_key_period <= 0):
raise ValueError('max_key_period must be a positive integer')
key_scores = []
for period in range(1, (min(max_key_period, len(ciphertext)) + 1)):
score = abs((ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, p... | Rank all key periods for ``ciphertext`` up to and including ``max_key_period``
Example:
>>> key_periods(ciphertext, 30)
[2, 4, 8, 3, ...]
Args:
ciphertext (str): The text to analyze
max_key_period (int): The maximum period the key could be
Returns:
Sorted list of keys
Raises:
ValueError: If max_key_period is less t... | codesearchnet |
def pull(self, platform=None):
(repository, _) = parse_repository_tag(self.image_name)
return self.collection.pull(repository, tag=self.id, platform=platform) | Pull the image digest.
Args:
platform (str): The platform to pull the image for.
Default: ``None``
Returns:
(:py:class:`Image`): A reference to the pulled image. | codesearchnet |
def read(self, filename, encoding=None):
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
self._filename = os.path.abspath(filename) | Read and parse a filename.
Args:
filename (str): path to file
encoding (str): encoding of file, default None | codesearchnet |
def mean(x, axis=None, keepdims=False):
if any_symbolic_tensors((x,)):
return Mean(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.mean(x, axis=axis, keepdims=keepdims) | Compute the arithmetic mean along the specified axes.
Args:
x: Input tensor.
axis: Axis or axes along which the means are computed. The default
is to compute the mean of the flattened tensor.
keepdims: If this is set to `True`, the axes which are reduced are left
in the result as dimensions with size one.
Returns:
Ou... | github-repos |
def scheduled_sample_count(ground_truth_x, generated_x, batch_size, scheduled_sample_var):
num_ground_truth = scheduled_sample_var
idx = tf.random_shuffle(tf.range(batch_size))
ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))
generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_s... | Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
scheduled_sample_var: number of ground-truth examples to include in batch.
Returns:
New batch with num_ground_truth sa... | codesearchnet |
def penalty_satisfaction(response, bqm):
record = response.record
label_dict = response.variables.index
if (len(bqm.info['reduction']) == 0):
return np.array(([1] * len(record.sample)))
penalty_vector = np.prod([((record.sample[(:, label_dict[qi])] * record.sample[(:, label_dict[qj])]) == record... | Creates a penalty satisfaction list
Given a sampleSet and a bqm object, will create a binary list informing
whether the penalties introduced during degree reduction are satisfied for
each sample in sampleSet
Args:
response (:obj:`.SampleSet`): Samples corresponding to provided bqm
bqm (:obj:`.BinaryQuadraticModel`):... | codesearchnet |
def _FormatDescription(self, event):
date_time_string = timelib.Timestamp.CopyToIsoFormat(
event.timestamp, timezone=self._output_mediator.timezone)
timestamp_description = event.timestamp_desc or 'UNKNOWN'
message, _ = self._output_mediator.GetFormattedMessages(event)
if message is None:
... | Formats the description.
Args:
event (EventObject): event.
Returns:
str: formatted description field. | juraj-google-style |
def add_layer(self, label, change_layer=True):
self.layer_stack.insert((self.last_layer() + 1), label)
if change_layer:
self.set_current_layer(self.last_layer())
return None | Add new mesh layer to the end of the stack
Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer | codesearchnet |
def plugins(self):
if (not self.loaded):
self.load_modules()
return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True, type_filter=self.type_filter) | Newest version of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary key with index-notation,
a :py:exc:... | codesearchnet |
def export_vms(self, vms_names=None, standalone=False, export_dir='.', compress=False, init_file_name='LagoInitFile', out_format=YAMLOutFormatPlugin(), collect_only=False, with_threads=True):
return self.virt_env.export_vms(vms_names, standalone, export_dir, compress, init_file_name, out_format, collect_only, with_... | Export vm images disks and init file.
The exported images and init file can be used to recreate
the environment.
Args:
vms_names(list of str): Names of the vms to export, if None
export all the vms in the env (default=None)
standalone(bool): If false, export a layered image
(default=False)
export_dir(str): Dir to plac... | codesearchnet |
def get_version(here_path, default_version=DEFAULT_VERSION):
if ('site-packages' in here_path):
return _version_from_file(here_path)
if os.environ.get('TRAVIS_TAG'):
if (not TEST_MODE):
return os.environ.get('TRAVIS_TAG').replace('v', '')
else:
warnings.warn('Trav... | tries to resolve version number
Args:
here_path (str): path to project local dir
default_version (str): what version to return if all else fails
Returns:
str: semantic_version information for library | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.