code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def read_hdf(cls, path_or_buf, **kwargs):
if cls.read_hdf_remote_task is None:
return super(RayIO, cls).read_hdf(path_or_buf, **kwargs)
format = cls._validate_hdf_format(path_or_buf=path_or_buf)
if format is None:
ErrorMessage.default_to_pandas(
... | Load a h5 file from the file path or buffer, returning a DataFrame.
Args:
path_or_buf: string, buffer or path object
Path to the file to open, or an open :class:`pandas.HDFStore` object.
kwargs: Pass into pandas.read_hdf function.
Returns:
DataFrame constructed from the h5 file. | juraj-google-style |
def single_lf_summary(Y_p, Y=None):
L = sparse.csr_matrix(arraylike_to_numpy(Y_p).reshape(-1, 1))
return lf_summary(L, Y) | Calculates coverage, overlap, conflicts, and accuracy for a single LF
Args:
Y_p: a np.array or torch.Tensor of predicted labels
Y: a np.array or torch.Tensor of true labels (if known) | juraj-google-style |
def make_one_shot_iterator(dataset: DatasetV1) -> Union[iterator_ops.Iterator, iterator_ops.OwnedIterator]:
try:
return dataset._make_one_shot_iterator()
except AttributeError:
return DatasetV1Adapter(dataset)._make_one_shot_iterator() | Creates an iterator for elements of `dataset`.
Note: The returned iterator will be initialized automatically.
A "one-shot" iterator does not support re-initialization.
Args:
dataset: A `tf.data.Dataset`.
Returns:
A `tf.data.Iterator` for elements of `dataset`.
@compatibility(TF2)
This is a legacy API for consuming ... | github-repos |
def variant(self, case_id, variant_id):
case_obj = self.case(case_id=case_id)
vcf_file_path = case_obj.variant_source
self.head = get_header(vcf_file_path)
self.vep_header = self.head.vep_columns
self.snpeff_header = self.head.snpeff_columns
handle = VCF(vcf_fi... | Return a specific variant.
Args:
case_id (str): Path to vcf file
variant_id (str): A variant id
Returns:
variant (Variant): The variant object for the given id | juraj-google-style |
def _import_object(self, path, look_for_cls_method):
last_nth = 2 if look_for_cls_method else 1
path = path.split('.')
module_path = '.'.join(path[:-last_nth])
class_name = path[-last_nth]
module = importlib.import_module(module_path)
if look_for_cls_method and p... | Imports the module that contains the referenced method.
Args:
path: python path of class/function
look_for_cls_method (bool): If True, treat the last part of path as class method.
Returns:
Tuple. (class object, class name, method to be called) | juraj-google-style |
def hour(self, value=None):
if (value is not None):
try:
value = int(value)
except ValueError:
raise ValueError('value {} need to be of type int for field `hour`'.format(value))
if (value < 1):
raise ValueError('value need to be greater or equal 1 for fiel... | Corresponds to IDD Field `hour`
Args:
value (int): value for IDD Field `hour`
value >= 1
value <= 24
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | codesearchnet |
def create(self, msgtype, *args, **kwargs):
if (msgtype not in self._messages):
raise ProtocolError(('Unknown message type %r for protocol version %s' % (msgtype, self._version)))
return self._messages[msgtype].create(*args, **kwargs) | Create a new Message instance for the given type.
Args:
msgtype (str) : | codesearchnet |
def _GetExpectedFractionalAvgPoolResult(self, input_tensor, row_seq, col_seq, overlapping):
input_shape = input_tensor.shape
output_shape = (input_shape[0], len(row_seq) - 1, len(col_seq) - 1, input_shape[3])
output_tensor = np.zeros(shape=output_shape, dtype=input_tensor.dtype)
for batch in range(input... | Get expected fractional average pooling result.
row_seq and col_seq together defines the fractional pooling region.
Args:
input_tensor: Original input tensor, assuming it is a 4-D tensor, with
dimension as [batch, height/row, width/column, channels/depth].
row_seq: Cumulative pooling sequence along row.
col_seq: Cumu... | github-repos |
def has_deprecation_decorator(symbol):
decorators, symbol = tf_decorator.unwrap(symbol)
if contains_deprecation_decorator(decorators):
return True
if tf_inspect.isfunction(symbol):
return False
if not tf_inspect.isclass(symbol):
return False
if not hasattr(symbol, '__init__')... | Checks if given object has a deprecation decorator.
We check if deprecation decorator is in decorators as well as
whether symbol is a class whose __init__ method has a deprecation
decorator.
Args:
symbol: Python object.
Returns:
True if symbol has deprecation decorator. | github-repos |
def __call__(self, hidden_states, cls_index=None, deterministic: bool=True):
output = hidden_states[:, 0]
output = self.first_dropout(output, deterministic=deterministic)
output = self.summary(output)
output = self.activation(output)
output = self.last_dropout(output, deterministic=deterministic)
... | Compute a single vector summary of a sequence hidden states.
Args:
hidden_states (`jnp.ndarray` of shape `[batch_size, seq_len, hidden_size]`):
The hidden states of the last layer.
cls_index (`jnp.ndarray` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *opt... | github-repos |
def freeze_graph(sess, input_tensors, output_tensors):
graph_def = _convert_to_constants.disable_lower_using_switch_merge(sess.graph_def)
config = get_grappler_config(['function'])
graph_def = run_graph_optimizations(graph_def, input_tensors, output_tensors, config, graph=sess.graph)
hinted_outputs_node... | Returns a frozen GraphDef.
Runs a Grappler pass and freezes a graph with Variables in it. Otherwise the
existing GraphDef is returned. The Grappler pass is only run on models that
are frozen in order to inline the functions in the graph.
If OpHints is present, it will try to convert the OpHint graph.
Args:
sess: Tens... | github-repos |
def serial_wire_viewer(jlink_serial, device):
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
jlink.coresight_configure()
... | Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error | juraj-google-style |
def _WriteRow(self, output_writer, values, in_bold=False):
row_strings = []
for (value_index, value_string) in enumerate(values):
padding_size = (self._column_sizes[value_index] - len(value_string))
padding_string = (' ' * padding_size)
row_strings.extend([value_string, padding_string])
... | Writes a row of values aligned with the width to the output writer.
Args:
output_writer (CLIOutputWriter): output writer.
values (list[object]): values.
in_bold (Optional[bool]): True if the row should be written in bold. | codesearchnet |
def add_component(self, component, temporary=False):
tile = IOTile(component)
value = os.path.normpath(os.path.abspath(component))
if (temporary is True):
self._component_overlays[tile.name] = value
else:
self.kvstore.set(tile.name, value) | Register a component with ComponentRegistry.
Component must be a buildable object with a module_settings.json file
that describes its name and the domain that it is part of. By
default, this component is saved in the permanent registry associated
with this environment and will remain registered for future CoreTools
i... | codesearchnet |
def write(self, name, **data):
data["name"] = name
if not ("timestamp" in data):
data["timestamp"] = datetime.utcnow()
try:
self.producer.send(topic=self.topic, value=data)
self.producer.flush()
except (KafkaTimeoutError, NoBrokersAvailable)... | Write the metric to kafka
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric | juraj-google-style |
def _ParseVSSProcessingOptions(self, options):
vss_only = False
vss_stores = None
self._process_vss = not getattr(options, 'no_vss', False)
if self._process_vss:
vss_only = getattr(options, 'vss_only', False)
vss_stores = getattr(options, 'vss_stores', None)
if vss_stores:
t... | Parses the VSS processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | juraj-google-style |
def softplus_and_shift(x, shift=1e-5, name=None):
with tf.compat.v1.name_scope(name, 'softplus_and_shift', [x, shift]):
x = tf.convert_to_tensor(value=x, name='x')
y = tf.nn.softplus(x)
if shift is not None:
y += shift
return y | Converts (batch of) scalars to (batch of) positive valued scalars.
Args:
x: (Batch of) `float`-like `Tensor` representing scalars which will be
transformed into positive elements.
shift: `Tensor` added to `softplus` transformation of elements.
Default value: `1e-5`.
name: A `name_scope` name for operations created by ... | juraj-google-style |
def from_dict(cls, fields, mapping):
iterable = ([None] * len(fields))
for (key, value) in mapping.items():
try:
index = fields.index(key)
except KeyError:
raise ItsdbError(('Invalid field name(s): ' + key))
iterable[index] = value
return cls(fields, iterable) | Create a Record from a dictionary of field mappings.
The *fields* object is used to determine the column indices
of fields in the mapping.
Args:
fields: the Relation schema for the table of this record
mapping: a dictionary or other mapping from field names to
column values
Returns:
a :class:`Record` object | codesearchnet |
def get_tool_filepath(self, tool_alias):
tools_dict = self.get_tools()
if (tool_alias in tools_dict):
if (self.tools_path is None):
return None
else:
return os.path.join(self.tools_path, tool_alias)
else:
return None | Given a visible tool alias, return the full path to the executable.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Filepath of executable, or None if the tool is not in the
suite. May also return None because this suite has not been saved
to disk, so a filepath hasn't yet been established. | codesearchnet |
def loss_masks(self, masks_queries_logits: torch.Tensor, mask_labels: List[torch.Tensor], indices: Tuple[np.array], num_masks: int) -> Dict[str, torch.Tensor]:
src_idx = self._get_predictions_permutation_indices(indices)
tgt_idx = self._get_targets_permutation_indices(indices)
pred_masks = masks_queries_log... | Compute the losses related to the masks using sigmoid_cross_entropy_loss and dice loss.
Args:
masks_queries_logits (`torch.Tensor`):
A tensor of shape `(batch_size, num_queries, height, width)`.
mask_labels (`torch.Tensor`):
List of mask labels of shape `(labels, height, width)`.
indices (`Tuple[np.array])`:
The indic... | github-repos |
def write(self, record):
super(TFRecordWriter, self).write(record) | Write a string record to the file.
Args:
record: str | github-repos |
def __init__(self, output_mediator):
super(XLSXOutputModule, self).__init__(output_mediator)
self._column_widths = {}
self._current_row = 0
self._dynamic_fields_helper = dynamic.DynamicFieldsHelper(output_mediator)
self._fields = self._DEFAULT_FIELDS
self._filename = None
self._sheet = ... | Initializes an Excel Spreadsheet (XLSX) output module.
Args:
output_mediator (OutputMediator): output mediator. | juraj-google-style |
def post_state(self, name, state):
self.post_command(OPERATIONS.CMD_UPDATE_STATE,
{'name': name, 'new_status': state}) | Asynchronously try to update the state for a service.
If the update fails, nothing is reported because we don't wait for a
response from the server. This function will return immmediately and
not block.
Args:
name (string): The name of the service
state (int): The new state of the service | juraj-google-style |
def upsert_project(self, project, id=None, description=None, entity=None):
mutation = gql()
response = self.gql(mutation, variable_values={
'name': self.format_project(project), 'entity': entity or self.settings('entity'),
'description': description, 'repo': self.git.rem... | Create a new project
Args:
project (str): The project to create
description (str, optional): A description of this project
entity (str, optional): The entity to scope this project to. | juraj-google-style |
def createRoles(self, configFiles, dateTimeFormat=None):
if dateTimeFormat is None:
dateTimeFormat = '%Y-%m-%d %H:%M'
scriptStartTime = datetime.datetime.now()
try:
print ("********************Create Roles********************")
print ("Script start... | Parses a JSON configuration file to create roles.
Args:
configFiles (list): A list of JSON files on disk containing
configuration data for creating roles.
dateTimeFormat (str): A valid date formatting directive, as understood
by :py:meth:`datetime.datetime.strftime`. Defaults to ``None``, i.e.,
``'%Y-%m-%d %H:%M'``. | juraj-google-style |
def _get_timestamp_ms(when):
if when is None:
return None
ms_since_epoch = float(time.mktime(when.utctimetuple()) * 1000.0)
ms_since_epoch += when.microsecond / 1000.0
return int(ms_since_epoch) | Converts a datetime.datetime to integer milliseconds since the epoch.
Requires special handling to preserve microseconds.
Args:
when: A datetime.datetime instance.
Returns:
Integer time since the epoch in milliseconds. If the supplied 'when' is
None, the return value will be None. | juraj-google-style |
def register_for_auto_class(cls, auto_class='AutoImageProcessor'):
if not isinstance(auto_class, str):
auto_class = auto_class.__name__
import transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f'{auto_class} is not a valid auto class.')
cls... | Register this class with a given auto class. This should only be used for custom image processors as the ones
in the library are already mapped with `AutoImageProcessor `.
Args:
auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
The auto class to register this new image processor with. | github-repos |
def GenerateBand(self, band, meta_only=False, cast=False):
if (not meta_only):
fname = band.get('file_name')
data = self.ReadTif(('%s/%s' % (os.path.dirname(self.filename), fname)))
def FixBitmap(d):
p = d.get('bitmap_description')
if p:
lis = p.get('bit')
... | Genreate a Band object given band metadata
Args:
band (dict): dictionary containing metadata for a given band
Return:
Band : the loaded Band onject | codesearchnet |
def dump(self):
walkers = {}
walkers.update({str(walker.selector): walker.dump() for walker in self._queue_walkers})
walkers.update({str(walker.selector): walker.dump() for walker in self._virtual_walkers})
return {u'engine': self._engine.dump(), u'rollover_storage': self._rollover_storage, u'rollover_s... | Dump the state of this SensorLog.
The purpose of this method is to be able to restore the same state
later. However there are links in the SensorLog for stream walkers.
So the dump process saves the state of each stream walker and upon
restore, it looks through the current set of stream walkers and
restores each one... | codesearchnet |
def has_thread(prefix, running_threads):
for thread in running_threads:
if thread.startswith(prefix):
return True
return False | Returns whether any 'running_threads' is prefixed with 'prefix'.
Args:
prefix: The prefix of the expected thread name.
running_threads: A collection of the running thread names. | github-repos |
def check_accessible(value_provider_list):
assert isinstance(value_provider_list, list)
def _check_accessible(fnc):
@wraps(fnc)
def _f(self, *args, **kwargs):
for obj in [getattr(self, vp) for vp in value_provider_list]:
if not obj.is_accessible():
... | A decorator that checks accessibility of a list of ValueProvider objects.
Args:
value_provider_list: list of ValueProvider objects
Raises:
``RuntimeValueProviderError``: if any of the provided objects are not
accessible. | github-repos |
def remove(path, force=False):
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
if not os.path.exists(path) and not is_link(path):
raise CommandExecutionError('Path not found: {0}... | Remove the named file or directory
Args:
path (str): The path to the file or directory to remove.
force (bool): Remove even if marked Read-Only. Default is False
Returns:
bool: True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
salt '*' file.remove C:\\Temp | juraj-google-style |
def fetch(self, url):
opener = self._urllib.build_opener()
opener.addheaders = self._requestHeaders.items()
response = opener.open(url)
headers = response.info()
raw = response.read()
raw = raw.decode('utf8')
if not 'Content-Type' in headers:
... | Fetch url and create a response object according to the mime-type.
Args:
url: The url to fetch data from
Returns:
OEmbedResponse object according to data fetched | juraj-google-style |
class XCLIPEncoder(nn.Module):
def __init__(self, config: XCLIPConfig):
super().__init__()
self.config = config
self.layers = nn.ModuleList([XCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, inputs_embeds,... | Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`XCLIPEncoderLayer`].
Args:
config: XCLIPConfig | github-repos |
def blackman(x):
if any_symbolic_tensors((x,)):
return Blackman().symbolic_call(x)
return backend.numpy.blackman(x) | Blackman window function.
The Blackman window is a taper formed by using a weighted cosine.
Args:
x: Scalar or 1D Tensor. Window length.
Returns:
A 1D tensor containing the Blackman window values.
Example:
>>> x = keras.ops.convert_to_tensor(5)
>>> keras.ops.blackman(x)
array([-1.3877788e-17, 3.4000000e-01, 1.0000... | github-repos |
def get_settings(self):
uri = '{}/settings'.format(self.data['uri'])
return self._helper.do_get(uri) | Gets the interconnect settings for a logical interconnect group.
Returns:
dict: Interconnect Settings. | codesearchnet |
def recursive_copy(source, destination):
if os.path.isdir(source):
copy_tree(source, destination) | A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path | codesearchnet |
def __call__(self, name, value):
super(FloatTypeChecker, self).__call__(name, value)
if isinstance(self.minimum, float):
if value < self.minimum:
raise ValueError("%s must be greater or equal %s" % (name, self.minimum))
if isinstance(self.maximum, float):
... | Call method.
Args:
name (str): the value's name.
value (float): the value to check.
Raises:
ValueError: if value is not type float.
ValueError: if value is less than minimum.
ValueError: if value is more than maximum. | juraj-google-style |
def pyrdf(value, class_type=None, datatype=None, **kwargs):
if isinstance(value, BaseRdfDataType):
return value
if isinstance(value, dict):
value = value.copy()
class_type = value.pop('type')
try:
datatype = value.pop('datatype')
except KeyError:
... | Coverts an input to one of the rdfdatatypes classes
Args:
value: any rdfdatatype, json dict or vlaue
class_type: "literal", "uri" or "blanknode"
datatype: "xsd:string", "xsd:int" , etc
kwargs:
lang: language tag | juraj-google-style |
def filter(self, **filters):
for (flt, val) in self._flt.items():
self._flt[flt] = filters.pop(flt, val)
if filters:
raise error.UnknownFiltersError(filters.keys())
return self | Update filters with provided arguments.
Note that filters are only resolved when the view is iterated, and
hence they do not compose. Each call to filter merely updates the
relevant filters. For example, with this code::
view = sdat.steps[500:].filter(rprof=True, fields=['T'])
view.filter(fields=[])
the produced ``v... | codesearchnet |
def get_twitter_id(self, cache=True):
if not (cache and ('twitter' in self.cache)):
response = self.get_attribute('twitter')
self.cache['twitter'] = response['artist'].get('twitter')
return self.cache['twitter'] | Get the twitter id for this artist if it exists
Args:
Kwargs:
Returns:
A twitter ID string
Example:
>>> a = artist.Artist('big boi')
>>> a.get_twitter_id()
u'BigBoi'
>>> | juraj-google-style |
class DonutSwinPatchMerging(nn.Module):
def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module=nn.LayerNorm) -> None:
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
... | Patch Merging Layer.
Args:
input_resolution (`Tuple[int]`):
Resolution of input feature.
dim (`int`):
Number of input channels.
norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
Normalization layer class. | github-repos |
def create_batch(cls, size, **kwargs):
return [cls.create(**kwargs) for _ in range(size)] | Create a batch of instances of the given class, with overriden attrs.
Args:
size (int): the number of instances to create
Returns:
object list: the created instances | juraj-google-style |
def unstage_signature(vcs, signature):
evidence_path = _get_staged_history_path(vcs)
staged = get_staged_signatures(vcs)
if (signature not in staged):
raise NotStagedError
staged.remove(signature)
string = '\n'.join(staged)
with open(evidence_path, 'w') as f:
f.write(string) | Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError | codesearchnet |
def _try_put(self, item):
try:
self._event_queue.put(item)
except QueueClosedError:
self._internal_close()
if self._worker.failure_exc_info:
_, exception, _ = self._worker.failure_exc_info
raise exception from None | Attempts to enqueue an item to the event queue.
If the queue is closed, this will close the EventFileWriter and reraise the
exception that caused the queue closure, if one exists.
Args:
item: the item to enqueue | github-repos |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3):
if (kmip_version < enums.KMIPVersion.KMIP_1_3):
raise exceptions.VersionNotSupported('KMIP {} does not support the RNGParameters object.'.format(kmip_version.value))
super(RNGParameters, self).read(input_buffer, kmip_version=kmip_ver... | Read the data encoding the RNGParameters structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object ... | codesearchnet |
def GetPreviousNonBlankLine(clean_lines, linenum):
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline):
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string ... | juraj-google-style |
def bind(self, isnap, istep):
self._isteps[isnap] = istep
self.sdat.steps[istep].isnap = isnap | Register the isnap / istep correspondence.
Users of :class:`StagyyData` should not use this method.
Args:
isnap (int): snapshot index.
istep (int): time step index. | juraj-google-style |
def __init__(self, credentials=None):
if credentials is None:
credentials = _utils.get_credentials()
self._api = _api.Api(credentials) | Initialize the Projects object.
Args:
credentials: the credentials for the account. | juraj-google-style |
def all_days(boo):
earliest = datetime.strptime(('2015-11-12').replace('-', ' '), '%Y %m %d')
latest = datetime.strptime(datetime.today().date().isoformat().replace('-', ' '), '%Y %m %d')
num_days = (latest - earliest).days + 1
all_days = [latest - timedelta(days=x) for x in range(num_days)]
all_days.rever... | Return a list of all dates from 11/12/2015 to the present.
Args:
boo: if true, list contains Numbers (20151230); if false, list contains Strings ("2015-12-30")
Returns:
list of either Numbers or Strings | juraj-google-style |
def ParseFileObject(self, parser_mediator, file_object):
file_header_map = self._GetDataTypeMap('binarycookies_file_header')
try:
(file_header, file_header_data_size) = self._ReadStructureFromFileObject(file_object, 0, file_header_map)
except (ValueError, errors.ParseError) as exception:
rai... | Parses a Safari binary cookie file-like object.
Args:
parser_mediator (ParserMediator): parser mediator.
file_object (dfvfs.FileIO): file-like object to be parsed.
Raises:
UnableToParseFile: when the file cannot be parsed, this will signal
the event extractor to apply other parsers. | codesearchnet |
def wait_for_file(self, fn: str, max_wait_sec: int = 3600 * 24 * 365,
check_interval: float = 0.02) -> bool:
print("Waiting for file", fn)
start_time = time.time()
while True:
if time.time() - start_time > max_wait_sec:
util.log(f"Timeout exceeded ({max_wait_sec} sec) ... | Waits for file maximum of max_wait_sec. Returns True if file was detected within specified max_wait_sec
Args:
fn: filename on task machine
max_wait_sec: how long to wait in seconds
check_interval: how often to check in seconds
Returns:
False if waiting was was cut short by max_wait_sec limit, True otherwise | juraj-google-style |
def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1... | Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
make use of token type ids, therefore a list of zeros is returned
Args:
token_ids_0 (`List[int]`):
List of ids.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs
Returns:
... | github-repos |
def _set_operation(a, b, set_operation, validate_indices=True):
if isinstance(a, sparse_tensor.SparseTensor):
if isinstance(b, sparse_tensor.SparseTensor):
indices, values, shape = gen_set_ops.sparse_to_sparse_set_operation(a.indices, a.values, a.dense_shape, b.indices, b.values, b.dense_shape, ... | Compute set operation of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if ... | github-repos |
def from_tensor_4x4(t: torch.Tensor) -> Rigid:
if t.shape[-2:] != (4, 4):
raise ValueError('Incorrectly shaped input tensor')
rots = Rotation(rot_mats=t[..., :3, :3], quats=None)
trans = t[..., :3, 3]
return Rigid(rots, trans) | Constructs a transformation from a homogeneous transformation tensor.
Args:
t: [*, 4, 4] homogeneous transformation tensor
Returns:
T object with shape [*] | github-repos |
def GetValueRepresentation(cls, value, version=sorted(_SERVICE_MAP.keys())[(- 1)]):
if (isinstance(value, str) or isinstance(value, unicode)):
return {'value': value, 'xsi_type': 'TextValue'}
elif isinstance(value, bool):
return {'value': value, 'xsi_type': 'BooleanValue'}
elif isinstance(va... | Converts a single python value to its PQL representation.
Args:
value: A python value.
version: A string identifying the Ad Manager version the value object
is compatible with. This defaults to what is currently the latest
version. This will be updated in future releases to point to what is
then the latest version.
R... | codesearchnet |
def bessel_k1(x, name=None):
with ops.name_scope(name, 'bessel_k1', [x]):
return gen_special_math_ops.bessel_k1(x) | Computes the Bessel k1 function of `x` element-wise.
Modified Bessel function of order 1.
It is preferable to use the numerically stabler function `k1e(x)` instead.
>>> tf.math.special.bessel_k1([0.5, 1., 2., 4.]).numpy()
array([1.65644112, 0.60190723, 0.13986588, 0.0124835 ], dtype=float32)
Args:
x: A `Tensor` or ... | github-repos |
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None):
cmse = np.zeros((1, scale))
for i in range(scale):
for j in range(i):
tmp = util_granulate_time_series(time_series[j:], (i + 1))
cmse[i] += (sample_entropy(tmp, sample_length, tolerance) / (i + 1... | Calculate the Composite Multiscale Entropy of the given time series.
Args:
time_series: Time series for analysis
sample_length: Number of sequential points of the time series
scale: Scale factor
tolerance: Tolerance (default = 0.1...0.2 * std(time_series))
Returns:
Vector containing Composite Multiscale Entropy
Refe... | codesearchnet |
def get_userid_from_botid(self, botid):
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if (botinfo['ok'] is True):
return botinfo['bot'].get('user_id')
else:
return botid | Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value | codesearchnet |
def unshare(self, group_id, **kwargs):
path = ('/projects/%s/share/%s' % (self.get_id(), group_id))
self.manager.gitlab.http_delete(path, **kwargs) | Delete a shared project link within a group.
Args:
group_id (int): ID of the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request | codesearchnet |
def lines_from_stream(f, as_interned=False):
if as_interned:
return [sys.intern(line) for line in f.read().splitlines()]
return f.read().splitlines() | Create a list of file lines from a given file stream.
Args:
f (io.TextIOWrapper): File stream
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list | juraj-google-style |
def as_tmpfile(self, tmpdir=None):
import tempfile, shutil
tmpdir = (tempfile.mkdtemp() if (tmpdir is None) else tmpdir)
new_path = os.path.join(tmpdir, self.basename)
shutil.copy(self.filepath, new_path)
(root, ext) = os.path.splitext(self.filepath)
djrepo = (root + '.djrepo')
if os.path.ex... | Copy the pseudopotential to a temporary a file and returns a new pseudopotential object.
Useful for unit tests in which we have to change the content of the file.
Args:
tmpdir: If None, a new temporary directory is created and files are copied here
else tmpdir is used. | codesearchnet |
def seek(self, offset, whence=os.SEEK_SET):
self._check_open()
self._buffer.reset()
self._buffer_future = None
if (whence == os.SEEK_SET):
self._offset = offset
elif (whence == os.SEEK_CUR):
self._offset += offset
elif (whence == os.SEEK_END):
self._offset = (self._file_s... | Set the file's current offset.
Note if the new offset is out of bound, it is adjusted to either 0 or EOF.
Args:
offset: seek offset as number.
whence: seek mode. Supported modes are os.SEEK_SET (absolute seek),
os.SEEK_CUR (seek relative to the current position), and os.SEEK_END
(seek relative to the end, offset shou... | codesearchnet |
def unpack(self, buff, offset=0):
super().unpack(buff, self._pyof_class, offset) | Unpack the elements of the list.
This unpack method considers that all elements have the same size.
To use this class with a pyof_class that accepts elements with
different sizes, you must reimplement the unpack method.
Args:
buff (bytes): The binary data to be unpacked.
offset (int): If we need to shift the beginnin... | juraj-google-style |
def _wrap_usage_section(source, width):
if (not any(((len(line) > width) for line in source.splitlines()))):
return source
section_header = source[:(source.index(':') + 1)].strip()
lines = [section_header]
for (commands, args) in parse_commands(source):
command = ' {} '.format(' '.join(... | Wrap the given usage section string to the current terminal size.
Note:
Commands arguments are wrapped to the column that the arguments began
on the first line of the command.
Args:
source: The section string to wrap.
Returns:
The wrapped section string. | codesearchnet |
def render_secrets(
config_path,
secret_path,
):
with open(secret_path, 'r') as s_fh:
secret_ini = anyconfig.load(s_fh, ac_parser='ini')
with open(config_path, 'r') as c_fh:
raw_cfg = c_fh.read()
rendered_cfg = anytemplate.renders(raw_cfg, secret_ini, at_engine='jinja2... | combine a jinja template with a secret .ini file
Args:
config_path (str): path to .cfg file with jinja templating
secret_path (str): path to .ini-like secrets file
Returns:
ProsperConfig: rendered configuration object | juraj-google-style |
def region(self, bounds):
if not isinstance(bounds, Bounds):
raise TypeError("region param bounds must be isinstance of Bounds")
_d = copy.copy(self)
_d._bounds = bounds
return _d | Set region of the screen area
Args:
bounds: Bounds object
Returns:
A new AndroidDevice object
Raises:
TypeError | juraj-google-style |
def IsLink(self):
if (self._stat_object is None):
self._stat_object = self._GetStat()
if (self._stat_object is not None):
self.entry_type = self._stat_object.type
return (self.entry_type == definitions.FILE_ENTRY_TYPE_LINK) | Determines if the file entry is a link.
Returns:
bool: True if the file entry is a link. | codesearchnet |
def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False):
self.logger.debug('CmdAuthenticate')
if ((len(challenge_param) != 32) or (len(app_param) != 32)):
raise errors.InvalidRequestError()
control = (7 if check_only else 3)
body = bytearray((((challenge_param + app_p... | Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object as a bytes
object.
app_param: SHA-256 hash of the app id as a bytes object.
key_handle: The key handle to use... | codesearchnet |
def set_db_row(db, start, size, _bytearray):
client.db_write(db, start, size, _bytearray) | Here we replace a piece of data in a db block with new data
Args:
db (int): The db to use
start(int): The start within the db
size(int): The size of the data in bytes
_butearray (enumerable): The data to put in the db | codesearchnet |
def strip_html_tags(text, allowed_tags=None):
if (text is None):
return
if (allowed_tags is None):
allowed_tags = ALLOWED_TAGS
return bleach.clean(text, tags=allowed_tags, attributes=['id', 'class', 'style', 'href', 'title'], strip=True) | Strip all tags from a string except those tags provided in `allowed_tags` parameter.
Args:
text (str): string to strip html tags from
allowed_tags (list): allowed list of html tags
Returns: a string without html tags | codesearchnet |
def file_config(filename=None):
logger.debug('On entry into file_config(), filename = {}'.format(filename))
if (filename is None):
filename = CONFIG_DEFAULT_PATH
logger.debug('file_config() will try to open `{}`'.format(filename))
with open(filename) as f:
try:
config = json.... | Returns the config values found in a configuration file.
Args:
filename (str): the JSON file with the configuration values.
If ``None``, CONFIG_DEFAULT_PATH will be used.
Returns:
dict: The config values in the specified config file (or the
file at CONFIG_DEFAULT_PATH, if filename == None) | codesearchnet |
def create(self, friendly_name=None, description=None):
if (not self.exists()):
try:
response = self._api.datasets_insert(self._name_parts, friendly_name=friendly_name, description=description)
except Exception as e:
raise e
if ('selfLink' not in response):
... | Creates the Dataset with the specified friendly name and description.
Args:
friendly_name: (optional) the friendly name for the dataset if it is being created.
description: (optional) a description for the dataset if it is being created.
Returns:
The Dataset.
Raises:
Exception if the Dataset could not be created. | codesearchnet |
def _checkFunctioncode(functioncode, listOfAllowedValues=[]):
FUNCTIONCODE_MIN = 1
FUNCTIONCODE_MAX = 127
_checkInt(functioncode, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode')
if listOfAllowedValues is None:
return
if not isinstance(listOfAllowedValues, list):
... | Check that the given functioncode is in the listOfAllowedValues.
Also verifies that 1 <= function code <= 127.
Args:
* functioncode (int): The function code
* listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking.
Raises:
TypeError, ValueError | juraj-google-style |
async def request(self, method, url, params=None, headers=None, data=None, json=None, token_refresh_attempts=2, **kwargs):
if all([data, json]):
msg = '"data" and "json" request parameters can not be used at the same time'
logging.warn(msg)
raise exceptions.GCPHTTPError(msg)
req_headers ... | Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to be requested.
params (dict): (optional) Query parameters for the request.
Defaults to ``None``.
headers (dict): (optional) HTTP headers to send with the
request. Headers pass through to the request will
include... | codesearchnet |
def auto_convert_cell_no_flags(cell, units=None, parens_as_neg=True):
units = units if units != None else {}
return auto_convert_cell(flagable=Flagable(), cell=cell, position=None, worksheet=0,
flags={}, units=units, parens_as_neg=parens_as_neg) | Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
This version of conversion doesn't flag changes nor store
cell units.
Args:
units: The dictionary holder for cell units.
parens_as_neg: Converts numerics surrounded by parens to
negative values | juraj-google-style |
def _BuildFindSpecsFromFileSourcePath(self, source_path, path_separator, environment_variables, user_accounts):
find_specs = []
for path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(source_path, path_separator):
logger.debug('building find spec from path glob: {0:s}'.format(path_glob))
fo... | Builds find specifications from a file source type.
Args:
source_path (str): file system path defined by the source.
path_separator (str): file system path segment separator.
environment_variables (list[str]): environment variable attributes used to
dynamically populate environment variables in key.
user_accounts (lis... | codesearchnet |
def create_sonos_playlist_from_queue(self, title):
response = self.avTransport.SaveQueue([('InstanceID', 0), ('Title', title), ('ObjectID', '')])
item_id = response['AssignedObjectID']
obj_id = item_id.split(':', 2)[1]
uri = 'file:
res = [DidlResource(uri=uri, protocol_info='x-rincon-playlist:*:*:*'... | Create a new Sonos playlist from the current queue.
Args:
title: Name of the playlist
:rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` | codesearchnet |
def add_metric(self, labels, buckets, sum_value, timestamp=None):
for b in buckets:
bucket, value = b[:2]
exemplar = None
if len(b) == 3:
exemplar = b[2]
self.samples.append(Sample(
self.name + '_bucket',
di... | Add a metric to the metric family.
Args:
labels: A list of label values
buckets: A list of lists.
Each inner list can be a pair of bucket name and value,
or a triple of bucket name, value, and exemplar.
The buckets must be sorted, and +Inf present.
sum_value: The sum value of the metric. | juraj-google-style |
def _SimpleEncoder(wire_type, encode_value, compute_value_size):
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
... | Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize(). | juraj-google-style |
def get_vcf_header(source):
head = HeaderParser()
for line in source:
line = line.rstrip()
if line.startswith('
if line.startswith('
logger.debug("Found metadata line {0}".format(line))
head.parse_meta_data(line)
else:
... | Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object | juraj-google-style |
async def get_random_popular_person(self, limit=500):
index = random.randrange(limit)
data = (await self._get_popular_people_page())
if (data is None):
return
if (index >= len(data['results'])):
(page, index) = self._calculate_page_index(index, data)
data = (await self._get_popul... | Randomly select a popular person.
Notes:
Requires at least two API calls. May require three API calls
if the randomly-selected index isn't within the first page of
required data.
Arguments:
limit (:py:class:`int`, optional): How many of the most
popular people to make random choice from (defaults to top
``500``).
Re... | codesearchnet |
def __init__(self, field_instance, sequence):
if not field_instance.repeated:
raise FieldDefinitionError(
'FieldList may only accept repeated fields')
self.__field = field_instance
self.__field.validate(sequence)
list.__init__(self, sequence) | Constructor.
Args:
field_instance: Instance of field that validates the list.
sequence: List or tuple to construct list from. | juraj-google-style |
def parse_brome_config_from_browser_config(browser_config):
config = {}
brome_keys = [key for key in browser_config if key.find(':') != -1]
for brome_key in brome_keys:
section, option = brome_key.split(':')
value = browser_config[brome_key]
if section not in config:
... | Parse the browser config and look for brome specific config
Args:
browser_config (dict) | juraj-google-style |
def forward(ctx, forward_fn, *args, **kwargs):
ctx.forward_fn = forward_fn
ctx.save_for_backward(*args)
try:
output, ctx.grad_fn = forward_fn(*args, **kwargs)
except:
output = forward_fn(*args, **kwargs)
ctx.grad_fn = lambda *args, **kwargs: torch.full((), float('nan'))
retur... | Forward pass computation specification.
Args:
ctx: Context object.
forward_fn: Function to compute forward pass.
*args: Arguments for the forward pass.
**kwargs: Keyword arguments for the forward pass. | github-repos |
def Lease(self, request, global_params=None):
config = self.GetMethodConfig('Lease')
return self._RunMethod(config, request, global_params=global_params) | Leases a dataflow WorkItem to run.
Args:
request: (DataflowProjectsJobsWorkItemsLeaseRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(LeaseWorkItemResponse) The response message. | github-repos |
def get_md5sum(fname, chunk_size=1024):
def iter_chunks(f):
while True:
chunk = f.read(chunk_size)
if (not chunk):
break
(yield chunk)
sig = hashlib.md5()
with open(fname, 'rb') as f:
for chunk in iter_chunks(f):
sig.update(chu... | Returns the MD5 checksum of a file.
Args:
fname (str): Filename
chunk_size (Optional[int]): Size (in Bytes) of the chunks that should be
read in at once. Increasing chunk size reduces the number of reads
required, but increases the memory usage. Defaults to 1024.
Returns:
The MD5 checksum of the file, which is a stri... | codesearchnet |
def nack(self, channel_id=None, **kwargs):
path = '/event-service/v1/channels/{}/nack'.format(channel_id)
r = self._httpclient.request(method='POST', url=self.url, path=path, **kwargs)
return r | Send a negative read-acknowledgement to the service.
Causes the channel's read point to move to its previous position
prior to the last poll.
Args:
channel_id (str): The channel ID.
**kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters.
Returns:
requests.Response: Requests Response() object.... | codesearchnet |
def deserialize(name, custom_objects=None):
return serialization_lib.deserialize_keras_object(name, module_objects=ALL_OBJECTS_DICT, custom_objects=custom_objects) | Deserializes a serialized loss class/function instance.
Args:
name: Loss configuration.
custom_objects: Optional dictionary mapping names (strings) to custom
objects (classes and functions) to be considered during
deserialization.
Returns:
A Keras `Loss` instance or a loss function. | github-repos |
def get_albums_for_artist(self, artist, full_album_art_uri=False):
subcategories = [artist]
result = self.get_album_artists(
full_album_art_uri=full_album_art_uri,
subcategories=subcategories,
complete_result=True)
reduced = [item for item in result ... | Get an artist's albums.
Args:
artist (str): an artist's name.
full_album_art_uri: whether the album art URI should be
absolute (i.e. including the IP address). Default `False`.
Returns:
A `SearchResult` instance. | juraj-google-style |
def regroup_if_changed(group, op_list, name=None):
has_deltas = isinstance(op_list, sequence_with_deltas.SequenceWithDeltas)
if ((group is None) or (len(group.control_inputs) != len(op_list)) or (has_deltas and op_list.has_changed())):
if has_deltas:
op_list.mark()
if op_list:
... | Creates a new group for op_list if it has changed.
Args:
group: The current group. It is returned if op_list is unchanged.
op_list: The list of operations to check.
name: The name to use if a new group is created.
Returns:
Either group or a new group (or if op_list is empty then no_op). | codesearchnet |
def accept_alert(self, text=None, wait=None):
wait = wait or capybara.default_max_wait_time
with self.driver.accept_modal("alert", text=text, wait=wait):
yield | Execute the wrapped code, accepting an alert.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found. | juraj-google-style |
def build_authorization_endpoint(self, request, disable_sso=None):
self.load_config()
redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None)
if not redirect_to:
redirect_to = django_settings.LOGIN_REDIRECT_URL
redirect_to = base64.urlsafe_b64encode(redirect_to.enco... | This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI | juraj-google-style |
def remove_server(self, name):
cmd = self.command_builder('no ntp server', value=name)
return self.configure(cmd) | Remove an NTP server entry from the node config
Args:
name (string): The IP address or FQDN of the NTP server.
Returns:
True if the operation succeeds, otherwise False. | codesearchnet |
def add_time_dimension(padded_inputs, seq_lens):
padded_batch_size = tf.shape(padded_inputs)[0]
max_seq_len = (padded_batch_size
new_batch_size = (padded_batch_size
new_shape = ([new_batch_size, max_seq_len] + padded_inputs.get_shape().as_list()[1:])
return tf.reshape(padded_inputs, new_shape) | Adds a time dimension to padded inputs.
Arguments:
padded_inputs (Tensor): a padded batch of sequences. That is,
for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
A, B, C are sequence elements and * denotes padding.
seq_lens (Tensor): the sequence lengths within the input batch,
suitable for passing to tf.... | codesearchnet |
def dict_of_lists_add(dictionary, key, value):
list_objs = dictionary.get(key, list())
list_objs.append(value)
dictionary[key] = list_objs | Add value to a list in a dictionary by key
Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to list in dictionary
Returns:
None | codesearchnet |
def get_ut_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
if hparams.recurrence_type == "basic":
ut_initializer = (x, x, x)
ut_function = functools.partial(
universal_transformer_basic,
hparams=hparams,
... | Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
ut_function and the ut_initializer
Raises:
ValueError... | juraj-google-style |
class TFConvNextStage(keras.layers.Layer):
def __init__(self, config: ConvNextConfig, in_channels: int, out_channels: int, kernel_size: int=2, stride: int=2, depth: int=2, drop_path_rates: Optional[List[float]]=None, **kwargs):
super().__init__(**kwargs)
if in_channels != out_channels or stride > 1... | ConvNext stage, consisting of an optional downsampling layer + multiple residual blocks.
Args:
config (`ConvNextV2Config`):
Model configuration class.
in_channels (`int`):
Number of input channels.
out_channels (`int`):
Number of output channels.
depth (`int`):
Number of residual blocks.
drop_path_rates(`List[float]`)... | github-repos |
def _send_data(self, data, start_offset, file_len):
headers = {}
end_offset = start_offset + len(data) - 1
if data:
headers['content-range'] = ('bytes %d-%d/%s' %
(start_offset, end_offset, file_len))
else:
headers['content-range'] = ('bytes */%s' % fi... | Send the block to the storage service.
This is a utility method that does not modify self.
Args:
data: data to send in str.
start_offset: start offset of the data in relation to the file.
file_len: an int if this is the last data to append to the file.
Otherwise '*'. | juraj-google-style |
def _stream_data(self, chunk=None):
self._stream_sm_running = True
if chunk is None:
chunk = self._next_streaming_chunk(20)
if chunk is None or len(chunk) == 0:
self._stream_sm_running = False
return
try:
self._send_no... | Stream reports to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.