code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _calculate_expected_result(dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config):
if config.use_gumbel_for_cells:
gumbel_dist = tfp.distributions.RelaxedBernoulli(config.temperature, logits=dist_per_cell.logits_parameter() * config.temperature)
scaled... | Calculates the expected result given cell and aggregation probabilities.
Args:
dist_per_cell (`tfp.distributions.Bernoulli`):
Cell selection distribution for each cell.
numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
Numeric values of every token. Nan for tokens which are not numeric values.
numeric_... | github-repos |
def load_resource(resource_url: str, forceupdate: bool=False):
log.info(f'Loading resource {resource_url}')
try:
fo = bel.utils.download_file(resource_url)
if (not fo):
log.error(f'Could not download and open file {resource_url}')
return 'Failed to download resource_url'
... | Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL API
forceupdate: force full update - e.g. don't leave Elasticsearch indexes alone if the... | codesearchnet |
def repository_contributors(self, **kwargs):
path = ('/projects/%s/repository/contributors' % self.get_id())
return self.manager.gitlab.http_list(path, **kwargs) | Return a list of contributors for the project.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False and no pagination option is
defined, return a generator in... | codesearchnet |
def parse(cls, data: bytes) -> 'MessageContent':
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | Parse the bytestring into message content.
Args:
data: The bytestring to parse. | codesearchnet |
def convert_bytes_to_c_source(data, array_name, max_line_width=80, include_guard=None, include_path=None, use_tensorflow_license=False):
starting_pad = ' '
array_lines = []
array_line = starting_pad
for value in bytearray(data):
if len(array_line) + 4 > max_line_width:
array_lines.... | Returns strings representing a C constant array containing `data`.
Args:
data: Byte array that will be converted into a C constant.
array_name: String to use as the variable name for the constant array.
max_line_width: The longest line length, for formatting purposes.
include_guard: Name to use for the include guard m... | github-repos |
def _MergeTaskStorage(self, storage_writer):
if self._processing_profiler:
self._processing_profiler.StartTiming('merge_check')
for task_identifier in storage_writer.GetProcessedTaskIdentifiers():
try:
task = self._task_manager.GetProcessedTaskByIdentifier(task_identifier)
... | Merges a task storage with the session storage.
This function checks all task stores that are ready to merge and updates
the scheduled tasks. Note that to prevent this function holding up
the task scheduling loop only the first available task storage is merged.
Args:
storage_writer (StorageWriter): storage writer for... | codesearchnet |
def _create_formatters(self, instrumentation_block, new_state):
formatters = []
if self._previous_block_never_completed(current_block=instrumentation_block, previous_block=instrumentation_block.previous_instrumentation_block, new_state=new_state):
instrumentation_block.previous_instrumentation_block.set... | Creates the _InstrumentationBlockFormatters for outputting the
instrumentation method block that have finished parsing.
Args:
instrumentation_block: _InstrumentationBlock, the current
instrumentation method block to create formatters based upon.
new_state: _InstrumentationBlockState, the next state that the
parser wil... | github-repos |
def delta_E( self ):
site_delta_E = self.final_site.energy - self.initial_site.energy
if self.nearest_neighbour_energy:
site_delta_E += self.nearest_neighbour_delta_E()
if self.coordination_number_energy:
site_delta_E += self.coordination_number_delta_E()
... | The change in system energy if this jump were accepted.
Args:
None
Returns:
(Float): delta E | juraj-google-style |
def create_bulk(self, resource, timeout=(- 1)):
uri = (self.URI + '/bulk')
default_values = self._get_default_values(self.BULK_DEFAULT_VALUES)
updated_data = self._helper.update_resource_fields(resource, default_values)
self._helper.create(updated_data, uri=uri, timeout=timeout)
return self.get_rang... | Creates bulk Ethernet networks.
Args:
resource (dict): Specifications to create in bulk.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
list: List of created Ethernet Networks. | codesearchnet |
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name):
self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name)
return | Set the grid values for y.
Create information for the grid of y values.
Args:
num_y (int): Number of points on axis.
y_low/y_high (float): Lowest/highest value for the axis.
yscale (str): Scale of the axis. Choices are 'log' or 'lin'.
yval_name (str): Name representing the axis. See GenerateContainer documentation
fo... | codesearchnet |
def Wget(src_url, tgt_name, tgt_root=None):
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import wget
tgt_file = local.path(tgt_root) / tgt_name
if not source_required(tgt_file):
Copy(tgt_file, ".")
return
wget(src_url, "-O", tgt_file)
... | Download url, if required.
Args:
src_url (str): Our SOURCE url.
tgt_name (str): The filename we want to have on disk.
tgt_root (str): The TARGET directory for the download.
Defaults to ``CFG["tmpdir"]``. | juraj-google-style |
def length(self, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
return tf.gather(self._length, rows) | Tensor holding the current length of episodes.
Args:
rows: Episodes to select length from, defaults to all.
Returns:
Batch tensor of sequence lengths. | juraj-google-style |
def make_scheduler(self, **kwargs):
from .launcher import PyFlowScheduler
if not kwargs:
sched = PyFlowScheduler.from_user_config()
else:
filepath = kwargs.pop("filepath", None)
if filepath is not None:
assert... | Build a return a :class:`PyFlowScheduler` to run the flow.
Args:
kwargs: if empty we use the user configuration file.
if `filepath` in kwargs we init the scheduler from filepath.
else pass **kwargs to :class:`PyFlowScheduler` __init__ method. | juraj-google-style |
def run_conditional_decorators(self, context):
logger.debug("starting")
run_me = context.get_formatted_as_type(self.run_me, out_type=bool)
skip_me = context.get_formatted_as_type(self.skip_me, out_type=bool)
swallow_me = context.get_formatted_as_type(... | Evaluate the step decorators to decide whether to run step or not.
Use pypyr.dsl.Step.run_step if you intend on executing the step the
same way pypyr does.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. | juraj-google-style |
def num_mode_groups(self):
num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups(self._handle)
if (num < 0):
raise AttributeError('This device is not a tablet pad device')
return num | Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.define.Table... | codesearchnet |
def validate_config_value(value, possible_values):
if value not in possible_values:
raise Exception('Invalid config value "%s". Possible values are '
'%s' % (value, ', '.join(e for e in possible_values))) | Validate a config value to make sure it is one of the possible values.
Args:
value: the config value to validate.
possible_values: the possible values the value can be
Raises:
Exception if the value is not one of possible values. | juraj-google-style |
def __init__(self, key_path):
super(WindowsRegistryKeyPathFilter, self).__init__()
key_path.rstrip('\\')
self._key_path = key_path
key_path = key_path.upper()
self._key_path_upper = key_path
self._wow64_key_path = None
self._wow64_key_path_upper = None
if key_path.startswith(sel... | Initializes a Windows Registry key filter.
Args:
key_path (str): key path. | juraj-google-style |
def replace_composites_with_components(structure):
if isinstance(structure, CompositeTensor):
return replace_composites_with_components(structure._type_spec._to_components(structure))
elif not nest.is_nested(structure):
return structure
else:
return nest.map_structure(replace_composi... | Recursively replaces CompositeTensors with their components.
Args:
structure: A `nest`-compatible structure, possibly containing composite
tensors.
Returns:
A copy of `structure`, where each composite tensor has been replaced by
its components. The result will contain no composite tensors.
Note that `nest.flatten(re... | github-repos |
def _get_localized_fn(path, root_dir):
local_fn = path
if path.startswith(root_dir):
local_fn = path.replace(root_dir, '', 1)
if (not local_fn.startswith('/')):
return ('/' + local_fn)
return local_fn | Return absolute `path` relative to `root_dir`.
When `path` == ``/home/xex/somefile.txt`` and `root_dir` == ``/home``,
returned path will be ``/xex/somefile.txt``.
Args:
path (str): Absolute path beginning in `root_dir`.
root_dir (str): Absolute path containing `path` argument.
Returns:
str: Local `path` when `root_d... | codesearchnet |
def _PrintProcessingTime(self, processing_status):
if not processing_status:
processing_time = '00:00:00'
else:
processing_time = time.time() - processing_status.start_time
time_struct = time.gmtime(processing_time)
processing_time = time.strftime('%H:%M:%S', time_struct)
self.... | Prints the processing time.
Args:
processing_status (ProcessingStatus): processing status. | juraj-google-style |
def get_graphs(self, run_key, debug=False):
graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs)
graph_wrappers = graph_dict.get(run_key, {})
graph_defs = dict()
for (device_name, wrapper) in graph_wrappers.items():
graph_defs[device_name] = wrapper.graph_d... | Get the runtime GraphDef protos associated with a run key.
Args:
run_key: A Session.run kay.
debug: Whether the debugger-decoratedgraph is to be retrieved.
Returns:
A `dict` mapping device name to `GraphDef` protos. | codesearchnet |
def get_all_existing(self, server_group):
self.log.info('Checking for existing scaling policy')
url = '{0}/applications/{1}/clusters/{2}/{1}/serverGroups'.format(API_URL, self.app, self.env)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok, 'Error looking for... | Finds all existing scaling policies for an application
Returns:
scalingpolicies (list): List of all existing scaling policies for the application | codesearchnet |
def create_variable(self, feature_column, name, shape, dtype=None, trainable=True, use_resource=True, initializer=None):
del feature_column, name, shape, dtype, trainable, use_resource, initializer
raise NotImplementedError('StateManager.create_variable') | Creates a new variable.
Args:
feature_column: A `FeatureColumn` object this variable corresponds to.
name: variable name.
shape: variable shape.
dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
trainable: Whether this variable is trainable or not.
use_resource: If true, we use resource variables... | github-repos |
def _update_dict(self, to_dict, from_dict):
for (key, value) in from_dict.items():
if ((key in to_dict) and isinstance(to_dict[key], dict) and isinstance(from_dict[key], dict)):
self._update_dict(to_dict[key], from_dict[key])
else:
to_dict[key] = from_dict[key] | Recursively merges the fields for two dictionaries.
Args:
to_dict (dict): The dictionary onto which the merge is executed.
from_dict (dict): The dictionary merged into to_dict | codesearchnet |
def __init__(self, num_agents, observation_spec, action_spec):
self._num_agents = num_agents
self._observation_spec = observation_spec
self._action_spec = action_spec
self._episode_steps = 0
self.next_timestep = [
environment.TimeStep(
step_type=environment.StepType.MID,
... | Initializes the TestEnvironment.
The `next_observation` is initialized to be reward = 0., discount = 1.,
and an appropriately sized observation of all zeros. `episode_length` is set
to `float('inf')`.
Args:
num_agents: The number of agents.
observation_spec: The observation specs for each player.
action_spec: The act... | juraj-google-style |
def write_uint64(self, value, little_endian=True):
if little_endian:
endian = '<'
else:
endian = '>'
return self.pack(('%sQ' % endian), value) | Pack the value as an unsigned integer and write 8 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | codesearchnet |
def end_of_chunk(prev_tag, tag, prev_type, type_):
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_e... | Checks if a chunk ended between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_end: boolean. | juraj-google-style |
def ParseFileEntry(self, parser_mediator, file_entry):
index_file_parser = ChromeCacheIndexFileParser()
file_object = file_entry.GetFileObject()
try:
index_file_parser.ParseFileObject(parser_mediator, file_object)
except (IOError, errors.ParseError) as exception:
file_object.close()
... | Parses Chrome Cache files.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): file entry.
Raises:
UnableToParseFile: when the file cannot be parsed. | codesearchnet |
def python_value(self, value):
value = super(ArrowDateTimeField, self).python_value(value)
if isinstance(value, (datetime.datetime, datetime.date, string_types)):
return arrow.get(value)
return value | Return the value in the data base as an arrow object.
Returns:
arrow.Arrow: An instance of arrow with the field filled in. | codesearchnet |
def recipe_sheets_clear(config, auth_read, sheets_sheet, sheets_tab, sheets_range):
sheets(config, {'auth': auth_read, 'sheet': sheets_sheet, 'tab': sheets_tab, 'range': sheets_range, 'clear': True}) | Clear data from a sheet.
Args:
auth_read (authentication) - Credentials used for reading data.
sheets_sheet (string) - NA
sheets_tab (string) - NA
sheets_range (string) - NA | github-repos |
def size(self, path):
try:
return os.path.getsize(path)
except Exception as e:
raise BeamIOError('Size operation failed', {path: e}) | Get size of path on the FileSystem.
Args:
path: string path in question.
Returns: int size of path according to the FileSystem.
Raises:
``BeamIOError``: if path doesn't exist. | github-repos |
async def _on_trace_notification(self, trace_event):
conn_string = trace_event.get('connection_string')
payload = trace_event.get('payload')
await self.notify_event(conn_string, 'trace', payload) | Callback function called when a trace chunk is received.
Args:
trace_chunk (dict): The received trace chunk information | juraj-google-style |
def _expand_terms(self, terms):
ret = {
'keywords': list(),
'doc': list()}
if not isinstance(terms, dict):
stp = SearchTermParser()
terms = stp.parse(terms, term_join=self.backend._and_join)
if 'about' in terms:
ret['doc'].a... | Expands terms of the dataset to the appropriate fields. It will parse the search phrase
and return only the search term components that are applicable to a Dataset query.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings | juraj-google-style |
def tf_baseline_loss(self, states, internals, reward, update, reference=None):
if self.baseline_mode == 'states':
loss = self.baseline.loss(
states=states,
internals=internals,
reward=reward,
update=update,
refe... | Creates the TensorFlow operations for calculating the baseline loss of a batch.
Args:
states: Dict of state tensors.
internals: List of prior internal state tensors.
reward: Reward tensor.
update: Boolean tensor indicating whether this call happens during an update.
reference: Optional reference tensor(s), in case of ... | juraj-google-style |
def setModelData(self, spinBox, model, index):
spinBox.interpretText()
value = spinBox.value()
model.setData(index, value, QtCore.Qt.EditRole) | Gets data from the editor widget and stores it in the specified model at the item index.
Args:
spinBox (QDoubleSpinBox): editor widget.
model (QAbstractItemModel): parent model.
index (QModelIndex): model data index. | juraj-google-style |
def _CheckIsDirectory(self, file_entry):
if definitions.FILE_ENTRY_TYPE_DIRECTORY not in self._file_entry_types:
return False
return file_entry.IsDirectory() | Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | juraj-google-style |
def sin(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.sin, tf.float32) | Returns a TensorFluent for the sin function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the sin function. | codesearchnet |
def grid_deploy(site, nodes, options):
gk = get_api_client()
environment = options.pop("env_name")
options.update(environment=environment)
options.update(nodes=nodes)
key_path = DEFAULT_SSH_KEYFILE
options.update(key=key_path.read_text())
logger.info("Deploying %s with options %s" % (no... | Deploy and wait for the deployment to be finished.
Args:
site(str): the site
nodes(list): list of nodes (str) to depoy
options(dict): option of the deployment (refer to the Grid'5000 API
Specifications)
Returns:
tuple of deployed(list), undeployed(list) nodes. | juraj-google-style |
def testBroadcastDimension(self, axis, row_length, original_dim_sizes, broadcast_dim_sizes):
original_shape = RaggedTensorDynamicShape.from_dim_sizes(original_dim_sizes)
bcast_shape = RaggedTensorDynamicShape.from_dim_sizes(broadcast_dim_sizes)
self.assertEqual(original_shape.rank, bcast_shape.rank)
bca... | Tests for the broadcast_dimension method.
Verifies that:
* `original.broadcast_dimension(axis, row_length) == broadcast`
* `broadcast.broadcast_dimension(axis, row_length) == broadcast`
* `broadcast.broadcast_dimension(axis, 1) == broadcast`
Args:
axis: The axis to broadcast
row_length: The slice lengths to broadcas... | github-repos |
def __init__(self, granularity: Granularity) -> None:
super().__init__()
self.chunks = ['']
self.row = 0
self.col = 0
self.current_word = ''
self.on_split_row = False
self.granularity = granularity | Initializes the HTML parser for the KNBC corpus.
Args:
granularity: Granularity of the output chunks. | github-repos |
def get_tensor_by_name(self, name) -> tensor_lib.Tensor:
if not isinstance(name, str):
raise TypeError('Tensor names are strings (or similar), not %s.' % type(name).__name__)
tensor = cast(tensor_lib.Tensor, self.as_graph_element(name, allow_tensor=True, allow_operation=False))
return tensor | Returns the `Tensor` with the given `name`.
This method may be called concurrently from multiple threads.
Args:
name: The name of the `Tensor` to return.
Returns:
The `Tensor` with the given `name`.
Raises:
TypeError: If `name` is not a string.
KeyError: If `name` does not correspond to a tensor in this graph. | github-repos |
def columns(self, dimensions=None):
if dimensions is None:
dimensions = self.dimensions()
else:
dimensions = [self.get_dimension(d, strict=True) for d in dimensions]
return OrderedDict([(d.name, self.dimension_values(d)) for d in dimensions]) | Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimension | juraj-google-style |
def encode(self, s):
try:
import matplotlib.image as im
except ImportError as e:
tf.logging.warning(
"Reading an image requires matplotlib to be installed: %s", e)
raise NotImplementedError("Image reading not implemented.")
return im.imread(s) | Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers | juraj-google-style |
def acos(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.acos, tf.float32) | Returns a TensorFluent for the arccos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the arccos function. | codesearchnet |
def __fa_process_sequence(self, sequence, avoid, initial_state, execution_state, trace_current, next_addr):
ip = sequence.address
next_ip = None
while ip:
try:
instr = sequence.fetch(ip)
except ReilSequenceInvalidAddressErr... | Process a REIL sequence.
Args:
sequence (ReilSequence): A REIL sequence to process.
avoid (list): List of address to avoid.
initial_state: Initial state.
execution_state: Execution state queue.
trace_current (list): Current trace.
next_addr: Address of the next instruction following the current one.
Returns:
Returns ... | juraj-google-style |
def ParseTable(table):
precondition.AssertIterableType(table, dict)
result = rdf_osquery.OsqueryTable()
result.header = ParseHeader(table)
for row in table:
result.rows.append(ParseRow(result.header, row))
return result | Parses table of osquery output.
Args:
table: A table in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryTable` instance. | juraj-google-style |
def parse_statement(self, statement, orig_contents):
children = []
is_block = False
name = statement.getName()
if name == 'block':
children_statements = statement[1]
for child in children_statements:... | Parse a statement, possibly called recursively.
Args:
statement (int, ParseResult): The pyparsing parse result that
contains one statement prepended with the match location
orig_contents (str): The original contents of the file that we're
parsing in case we need to convert an index into a line, column
pair.
Returns:
... | juraj-google-style |
def from_dict(cls, config_dict: dict[str, Any], **kwargs) -> 'PretrainedConfig':
return_unused_kwargs = kwargs.pop('return_unused_kwargs', False)
kwargs.pop('_from_auto', None)
kwargs.pop('_from_pipeline', None)
if '_commit_hash' in kwargs and '_commit_hash' in config_dict:
kwargs['_commit_hash'... | Instantiates a [`PretrainedConfig`] from a Python dictionary of parameters.
Args:
config_dict (`Dict[str, Any]`):
Dictionary that will be used to instantiate the configuration object. Such a dictionary can be
retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.
kwargs ... | github-repos |
def numeric_task_id(task_id):
if task_id is not None:
if task_id.startswith('task-'):
return int(task_id[len('task-'):])
else:
return int(task_id) | Converts a task-id to the numeric task-id.
Args:
task_id: task-id in either task-n or n format
Returns:
n | juraj-google-style |
def _get_fans(shape):
r
if len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
elif len(shape) == 4 or len(shape) == 5:
kernel_size = np.prod(shape[:2])
fan_in = shape[-2] * kernel_size
fan_out = shape[-1] * kernel_size
else:
fan_in = n... | r"""Returns the size of input dimension and output dimension, given `shape`.
Args:
shape: A list of integers.
Returns:
fan_in: An int. The value of input dimension.
fan_out: An int. The value of output dimension. | juraj-google-style |
def upsert_run(self, id=None, name=None, project=None, host=None, group=None, tags=None, config=None, description=None, entity=None, state=None, repo=None, job_type=None, program_path=None, commit=None, sweep_name=None, summary_metrics=None, num_retries=None):
mutation = gql('\n mutation UpsertBucket(\n ... | Update a run
Args:
id (str, optional): The existing run to update
name (str, optional): The name of the run to create
group (str, optional): Name of the group this run is a part of
project (str, optional): The name of the project
config (dict, optional): The latest config params
description (str, optional): A descript... | codesearchnet |
def last(series, order_by=None):
if (order_by is not None):
series = order_series_by(series, order_by)
last_s = series.iloc[(series.size - 1)]
return last_s | Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | codesearchnet |
def get_image_features(self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.LongTensor, qformer_attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: Optional[bool]=False, return_dict: Optional[bool]=False):
vision_outputs = self.vision_model(pixel_values=pixel_values, interpolate_po... | Encodes images into continuous embeddings that can be forwarded to the language model.
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
The tensors corresponding to the input images. | github-repos |
def distance_between(self, u, v):
if not isinstance(u, Node):
raise TypeError("u must be a Node")
if not isinstance(v, Node):
raise TypeError("v must be a Node")
if u == v:
return 0.
u_dists = {u:0.}; v_dists = {v:0.}
c = u; p = u.pare... | Return the distance between nodes ``u`` and ``v`` in this ``Tree``
Args:
``u`` (``Node``): Node ``u``
``v`` (``Node``): Node ``v``
Returns:
``float``: The distance between nodes ``u`` and ``v`` | juraj-google-style |
def construct(parent=None, defaults=None, **kwargs):
for key in kwargs:
assert (key in LEGAL_ATTRS), '{} is not legal input'.format(key)
if (parent is not None):
for (key, value) in LEGAL_ATTRS.items():
if ((key not in kwargs) and hasattr(parent, value)):
kwargs[key] ... | Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution used as basis for new distribution. Any other argument
that is omitted will instead take is function from ``parent``.
doc (str]):... | codesearchnet |
def postings(self, quarter, stats_counter=None):
logging.info('Finding postings for %s', quarter)
for posting in self._iter_postings(quarter):
transformed = self._transform(posting)
transformed['id'] = '{}_{}'.format(
self.partner_id,
self... | Yield job postings in common schema format
Args:
quarter (str) The quarter, in format '2015Q1'
stats_counter (object, optional) A counter that can track both
input and output documents using a 'track' method. | juraj-google-style |
def mounts(prefix, __mounts):
i = 0
mntpoints = []
for mount in __mounts:
if not isinstance(mount, dict):
mntpoint = "{0}/{1}".format(prefix, str(i))
mntpoints.append(mntpoint)
i = i + 1
return mntpoints | Compute the mountpoints of the current user.
Args:
prefix: Define where the job was running if it ran on a cluster.
mounts: All mounts the user currently uses in his file system.
Return:
mntpoints | juraj-google-style |
def FormatCode(unformatted_source, filename='<unknown>', style_config=None, lines=None, print_diff=False):
try:
tree = pytree_utils.ParseCodeToTree(unformatted_source)
except Exception as e:
e.filename = filename
raise errors.YapfError(errors.FormatErrorMsg(e))
reformatted_source = F... | Format a string of Python code.
This provides an alternative entry point to YAPF.
Arguments:
unformatted_source: (unicode) The code to format.
filename: (unicode) The name of the file being reformatted.
style_config: (string) Either a style name or a path to a file that contains
formatting style settings. If None is ... | github-repos |
def __init__(self, map_task, counter_factory, state_sampler, test_shuffle_source=None, test_shuffle_sink=None):
self._map_task = map_task
self._counter_factory = counter_factory
self._ops = []
self._state_sampler = state_sampler
self._test_shuffle_source = test_shuffle_source
self._test_shuffle_... | Initializes SimpleMapTaskExecutor.
Args:
map_task: The map task we are to run. The maptask contains a list of
operations, and aligned lists for step_names, original_names,
system_names of pipeline steps.
counter_factory: The CounterFactory instance for the work item.
state_sampler: The StateSampler tracking the execut... | github-repos |
def get_credentials_for_url(url, opts, force_user=None):
creds = None
verbose = int(opts.get('verbose'))
force_prompt = opts.get('prompt', False)
allow_prompt = (not opts.get('no_prompt', True))
allow_keyring = ((not opts.get('no_keyring', False)) and (not force_user))
allow_netrc = ((not opts.g... | Lookup credentials for a given target in keyring and .netrc.
Optionally prompts for credentials if not found.
Returns:
2-tuple (username, password) or None | codesearchnet |
def inferred_steps(self):
return self._inferred_steps | The inferred steps per epoch of the created `Dataset`.
This will be `None` in the case where:
(1) A `Dataset` of unknown cardinality was passed to the `DataHandler`, and
(2) `steps_per_epoch` was not provided, and
(3) The first epoch of iteration has not yet completed.
Returns:
The inferred steps per epoch of the cr... | github-repos |
def forward(self, input_ids: torch.Tensor, cache_position: torch.Tensor) -> torch.Tensor:
return self.model.forward(input_ids, cache_position) | Forward pass of the module, which is compatible with the ExecuTorch llm runner.
Args:
input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
Returns:
torch.Tensor: Logits output from the model. | github-repos |
def get_node(self, index: int) -> Optional[Node]:
return self._nodes.get(index) | Returns the node with the given index if such a node currently exists in the node list.
Arguments:
index (int): The index of the queried node.
Returns:
The node with the given index if such a node currently exists in the node list,
`None` otherwise. | juraj-google-style |
def list_container_instance_groups_sub(access_token, subscription_id):
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/providers/Microsoft.ContainerInstance/ContainerGroups',
'?api-version=', CONTAINER_API])
... | List the container groups in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON list of container groups and their properties. | juraj-google-style |
def _AlignDecryptedDataOffset(self, decrypted_data_offset):
self._file_object.seek(0, os.SEEK_SET)
self._decrypter = self._GetDecrypter()
self._decrypted_data = b''
encrypted_data_offset = 0
encrypted_data_size = self._file_object.get_size()
while (encrypted_data_offset < encrypted_data_size):
... | Aligns the encrypted file with the decrypted data offset.
Args:
decrypted_data_offset (int): decrypted data offset. | codesearchnet |
def satellites_used(feed):
total_satellites = 0
used_satellites = 0
if not isinstance(feed, list):
return 0, 0
for satellites in feed:
total_satellites += 1
if satellites['used'] is True:
used_satellites += 1
return total_satellites, used_satellites | Counts number of satellites used in calculation from total visible satellites
Arguments:
feed feed=data_stream.TPV['satellites']
Returns:
total_satellites(int):
used_satellites (int): | juraj-google-style |
def check_symmetry(A):
A = asanyarray(A)
if (A.ndim != 2):
raise ValueError('Checks symmetry only for bi-dimensional arrays.')
if (A.shape[0] != A.shape[1]):
return False
return (abs((A - A.T)).max() < sqrt(finfo(float).eps)) | Check if ``A`` is a symmetric matrix.
Args:
A (array_like): Matrix.
Returns:
bool: ``True`` if ``A`` is symmetric; ``False`` otherwise. | codesearchnet |
def linear(x):
return x | Linear activation function (pass-through).
For example:
>>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
>>> b = tf.keras.activations.linear(a)
>>> b.numpy()
array([-3., -1., 0., 1., 3.], dtype=float32)
Args:
x: Input tensor.
Returns:
The input, unmodified. | github-repos |
def parse_lxml(self, file, encoding=None, target_class=HTMLParserTarget, parser_type='html'):
if encoding:
lxml_encoding = (to_lxml_encoding(encoding) or 'latin1')
else:
lxml_encoding = encoding
elements = []
callback_func = elements.append
target = target_class(callback_func)
if... | Return an iterator of elements found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
target_class: A class to be used for target parsing.
parser_type (str): The type of parser to use. Accepted values:
``html``, ``xhtml``, ``xml``.
Returns:
iterator: Ea... | codesearchnet |
def get_mutations(aln_df):
mutation_df = aln_df[aln_df['type'] == 'mutation']
tuples = []
if not mutation_df.empty:
subset = mutation_df[['id_a_aa', 'id_a_pos', 'id_b_aa']]
subset['id_a_pos'] = subset['id_a_pos'].astype(int)
tuples = [tuple(x) for x in subset.values]
return ... | Get a list of residue numbers (in the original sequence's numbering) that are mutated
Args:
aln_df (DataFrame): Alignment DataFrame
just_resnums: If only the residue numbers should be returned, instead of a list of tuples of
(original_residue, resnum, mutated_residue)
Returns:
list: Residue mutations | juraj-google-style |
def verifymessage(self, address, signature, message):
verified = self.rpc.call("verifymessage", address, signature, message)
self.logger.debug("Signature verified: %s" % str(verified))
return verified | Verifies that a message has been signed by an address.
Args:
address (str): address claiming to have signed the message
signature (str): ECDSA signature
message (str): plaintext message which was signed
Returns:
bool: True if the address signed the message, False otherwise | juraj-google-style |
def estimate_cpdag(skel_graph, sep_set):
dag = skel_graph.to_directed()
node_ids = skel_graph.nodes()
for (i, j) in combinations(node_ids, 2):
adj_i = set(dag.successors(i))
if j in adj_i:
continue
adj_j = set(dag.successors(j))
if i in adj_j:
con... | Estimate a CPDAG from the skeleton graph and separation sets
returned by the estimate_skeleton() function.
Args:
skel_graph: A skeleton graph (an undirected networkx.Graph).
sep_set: An 2D-array of separation set.
The contents look like something like below.
sep_set[i][j] = set([k, l, m])
Returns:
An estimated DAG. | juraj-google-style |
def ParseFileObject(self, parser_mediator, file_object):
page_header_map = self._GetDataTypeMap('dls_page_header')
try:
(page_header, file_offset) = self._ReadStructureFromFileObject(file_object, 0, page_header_map)
except (ValueError, errors.ParseError) as exception:
raise errors.UnableToPa... | Parses an fseventsd file.
Args:
parser_mediator (ParserMediator): parser mediator.
file_object (dfvfs.FileIO): a file-like object.
Raises:
UnableToParseFile: when the header cannot be parsed. | codesearchnet |
def GetDefaultContract(self):
try:
return self.GetContracts()[0]
except Exception as e:
logger.error(('Could not find default contract: %s' % str(e)))
raise | Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints a warning to the console if the default contract could not be found. | codesearchnet |
def port_add(br, port, may_exist=False, internal=False):
param_may_exist = _param_may_exist(may_exist)
cmd = 'ovs-vsctl {2}add-port {0} {1}'.format(br, port, param_may_exist)
if internal:
cmd += ' -- set interface {0} type=internal'.format(port)
result = __salt__['cmd.run_all'](cmd)
ret... | Creates on bridge a new port named port.
Returns:
True on success, else False.
Args:
br: A string - bridge name
port: A string - port name
may_exist: Bool, if False - attempting to create a port that exists returns False.
internal: A boolean to create an internal interface if one does not exist.
.. versionadded:: 20... | juraj-google-style |
def __init__(self, keys=None):
if not keys:
raise errors.FormatError('Missing keys value.')
if not isinstance(keys, list):
raise errors.FormatError('keys must be a list')
for key in keys:
self.ValidateKey(key)
super(WindowsRegistryKeySourceType, self).__init__()
self.keys =... | Initializes a source type.
Args:
keys (Optional[list[str]]): key paths relative to the root of
the Windows Registry.
Raises:
FormatError: when keys is not set. | juraj-google-style |
def send_message(self, message):
try:
if _message_test_port is not None:
_message_test_port.sent.append(message)
yield message.send(self)
except (WebSocketClosedError, StreamClosedError):
log.warning("Failed sending message as co... | Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send | juraj-google-style |
def build_graph(self):
import tensorflow as tf
input_jpeg = tf.placeholder(tf.string, shape=None)
image = tf.image.decode_jpeg(input_jpeg, channels=self.CHANNELS)
image = tf.expand_dims(image, 0)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = tf.image.resize_bilinear(image... | Forms the core by building a wrapper around the inception graph.
Here we add the necessary input & output tensors, to decode jpegs,
serialize embeddings, restore from checkpoint etc.
To use other Inception models modify this file. Note that to use other
models beside Inception, you should make sure input_shape matche... | codesearchnet |
def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'):
msg = self.current.task_data['msg']
self.current.output['msgbox'] = {'type': box_type, "title": title, "msg": msg}
del self.current.task_data['msg'] | It shows incorrect operations or successful operation messages.
Args:
title (string): title of message box
box_type (string): type of message box (warning, info) | juraj-google-style |
def start_site(name):
ps_cmd = ['Start-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site' | juraj-google-style |
def get_metalpdb_info(metalpdb_lig_file):
pdb_metals = ['CU', 'ZN', 'MN', 'FE', 'MG', 'CO', 'SE', 'YB', 'SF4', 'FES', 'F3S', 'NI', 'FE2']
coordination_number = 0
endogenous_ligands = []
exogenous_ligands = []
ss = StructProp(ident='metalpdb', structure_path=metalpdb_lig_file, file_type='pdb')
ch... | Parse a MetalPDB .lig file and return a tuple of the chain ID it represents, along with metal binding information.
Args:
metalpdb_lig_file (str): Path to .lig file
Returns:
tuple: (str, dict) of the chain ID and the parsed metal binding site information | codesearchnet |
def single_offset(self, shape):
single_slice_dim = self.single_slice_dim(shape)
if single_slice_dim is None:
return 0
return self.var_offset[single_slice_dim] | Returns the offset when the variable is partitioned in at most one dim.
Args:
shape: Tuple or list of `int` indicating the shape of one specific
variable partition.
Returns:
`int` representing the offset in the dimension along which the variable is
partitioned. Returns 0 if the variable is not being partitioned.
Rai... | github-repos |
def get_filelikeobject(filename: str=None, blob: bytes=None) -> BinaryIO:
if ((not filename) and (not blob)):
raise ValueError('no filename and no blob')
if (filename and blob):
raise ValueError('specify either filename or blob')
if filename:
return open(filename, 'rb')
else:
... | Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object | codesearchnet |
def process_buffer(buffer, n_channels):
samples = np.concatenate(buffer)
if n_channels > 1:
samples = samples.reshape((-1, n_channels)).T
samples = librosa.to_mono(samples)
return samples | Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples | juraj-google-style |
async def get_person(self, id_):
data = (await self._get_person_json(id_, OrderedDict(append_to_response='movie_credits')))
return Person.from_json(data, self.config['data'].get('images')) | Retrieve person data by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
Returns:
:py:class:`~.Person`: The requested person. | codesearchnet |
def CompleteTask(self, task):
with self._lock:
if (task.identifier not in self._tasks_merging):
raise KeyError('Task {0:s} was not merging.'.format(task.identifier))
self.SampleTaskStatus(task, 'completed')
del self._tasks_merging[task.identifier]
logger.debug('Completed ... | Completes a task.
The task is complete and can be removed from the task manager.
Args:
task (Task): task.
Raises:
KeyError: if the task was not merging. | codesearchnet |
def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting softmax ...')
if names == 'short':
tf_name = 'SMAX' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
def target_lay... | Convert softmax layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def __init__(self, structure, element):
self.structure = structure
self.element = element
sga = SpacegroupAnalyzer(self.structure)
self.symm_structure = sga.get_symmetrized_structure()
self.equiv_sub = []
for equiv_site_set in list(self.symm_structure.... | Initializes a Substitution Generator
note: an Antisite is considered a type of substitution
Args:
structure(Structure): pymatgen structure object
element (str or Element or Specie): element for the substitution | juraj-google-style |
def _ufunc_dispatch(ufunc, method, i, inputs, **kwargs):
if 'out' in kwargs and kwargs['out'] is not None:
raise Error('for distributed ufuncs `out=` is not yet implemented')
nin = 2 if ufunc is np.dot else ufunc.nin
if nin is 1 and method == '__call__':
return vectorize(ufunc.__ca... | Route ufunc execution intelligently to local host or remote engine(s)
depending on where the inputs are, to minimize the need to move data.
Args:
see numpy documentation for __numpy_ufunc__ | juraj-google-style |
def _is_injective(self):
return True | Returns true iff the forward map `g` is injective (one-to-one function).
**WARNING** This hidden property and its behavior are subject to change.
Note: Non-injective maps `g` are supported, provided their domain `D` can
be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measu... | github-repos |
def accumulate_dict_from_superclasses(cls, propname):
cachename = "__cached_all" + propname
if cachename not in cls.__dict__:
d = dict()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
... | Traverse the class hierarchy and accumulate the special dicts
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__dataspecs__``,
``__overridden_defaults__`` | juraj-google-style |
def match_objects(self, set_a, set_b, time_a, time_b):
costs = (self.cost_matrix(set_a, set_b, time_a, time_b) * 100)
min_row_costs = costs.min(axis=1)
min_col_costs = costs.min(axis=0)
good_rows = np.where((min_row_costs < 100))[0]
good_cols = np.where((min_col_costs < 100))[0]
assignments = []... | Match two sets of objects at particular times.
Args:
set_a: list of STObjects
set_b: list of STObjects
time_a: time at which set_a is being evaluated for matching
time_b: time at which set_b is being evaluated for matching
Returns:
List of tuples containing (set_a index, set_b index) for each match | codesearchnet |
def process_arguments(self, func, args):
pos_args = []
kw_args = {}
while (len(args) > 0):
if (func.metadata.spec_filled(pos_args, kw_args) and (not self._is_flag(args[0]))):
break
arg = args.pop(0)
if (arg == '--'):
break
elif self._is_flag(arg):
... | Process arguments from the command line into positional and kw args.
Arguments are consumed until the argument spec for the function is filled
or a -- is found or there are no more arguments. Keyword arguments can be
specified using --field=value, -f value or --field value. Positional
arguments are specified just on... | codesearchnet |
def long_click(self, pos, duration=2.0):
try:
duration = float(duration)
except ValueError:
raise ValueError('Argument `duration` should be <float>. Got {}'.format(repr(duration)))
if not (0 <= pos[0] <= 1) or not (0 <= pos[1] <= 1):
raise InvalidOp... | Similar to click but press the screen for the given time interval and then release
Args:
pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1
duration: duration of press the screen | juraj-google-style |
def _build(self, inputs):
shape_inputs = inputs.get_shape().as_list()
rank = len(shape_inputs)
full_multiples = [1] * rank
for dim, multiple in zip(self._dims, self._multiples):
full_multiples[dim] = multiple
return tf.tile(inputs, multiples=full_multiples) | Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor. | juraj-google-style |
def load(self,cache_genotype=False,cache_phenotype=True):
self.f = h5py.File(self.file_name,'r')
self.pheno = self.f['phenotype']
self.geno = self.f['genotype']
self.genoM = self.geno['matrix']
self.phenoM = self.pheno['matrix']
self.sample_I... | load data file
Args:
cache_genotype: load genotypes fully into memory (default: False)
cache_phenotype: load phentopyes fully intro memry (default: True) | juraj-google-style |
def _receive_signal(self, progress_subscript):
self.progress = self._estimate_progress()
self.updateProgress.emit(int(self.progress)) | this function takes care of signals emitted by the subscripts
Args:
progress_subscript: progress of subscript | juraj-google-style |
def from_json(cls, json):
params = dict((str(k), v) for k, v in json.iteritems()
if k in cls._PARAMS)
if cls._OFFSET_PARAM in params:
params[cls._OFFSET_PARAM] = base64.b64decode(params[cls._OFFSET_PARAM])
return cls(**params) | Creates an instance of the InputReader for the given input shard's state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters. | juraj-google-style |
def ignore():
def parse_line(line):
if (not isinstance(line, string_types)):
line = line.decode('utf-8')
line = line.split('
return line
ignore_files = [conf.proj_path('.gitignore'), conf.proj_path('.git/info/exclude'), config().get('core.excludesfile')]
result = []
... | Return a list of patterns in the project .gitignore
Returns:
list[str]: List of patterns set to be ignored by git. | codesearchnet |
def register_gpt_plugin(self, fs_guid, plugin):
key = uuid.UUID(fs_guid.lower())
self.logger.debug('GPT: {}, GUID: {}'
.format(self.__get_plugin_name(plugin), fs_guid))
self.__gpt_plugins[key].append(plugin) | Used in plugin's registration routine,
to associate it's detection method with given filesystem guid
Args:
fs_guid: filesystem guid that is read from GPT partition entry
plugin: plugin that supports this filesystem | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.