code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def create_resource(self, parent_id=''):
resource_name = self.trigger_settings.get('resource', '')
resource_name = resource_name.replace('/', '')
if (not self.resource_id):
created_resource = self.client.create_resource(restApiId=self.api_id, parentId=parent_id, pathPart=resource_name)
self.... | Create the specified resource.
Args:
parent_id (str): The resource ID of the parent resource in API Gateway | codesearchnet |
def delete(filepath):
remove_acl(filepath)
remove_immutable_attribute(filepath)
if (os.path.isfile(filepath) or os.path.islink(filepath)):
os.remove(filepath)
elif os.path.isdir(filepath):
shutil.rmtree(filepath) | Delete the given file, directory or link.
It Should support undelete later on.
Args:
filepath (str): Absolute full path to a file. e.g. /path/to/file | codesearchnet |
def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch, mode):
if self._training_state is not None:
return self._training_state.maybe_load_initial_epoch_from_ckpt(initial_epoch, mode)
return initial_epoch | Maybe load initial epoch from ckpt considering possible worker recovery.
Refer to tensorflow/python/keras/distribute/worker_training_state.py
for more information.
Args:
initial_epoch: The original initial_epoch user passes in in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recoveri... | github-repos |
def parse_application_name(setup_filename):
with open(setup_filename, 'rt') as setup_file:
fst = RedBaron(setup_file.read())
for node in fst:
if ((node.type == 'atomtrailers') and (str(node.name) == 'setup')):
for call in node.call:
if (str(call.name) ... | Parse a setup.py file for the name.
Returns:
name, or None | codesearchnet |
def get_metadata(changeset):
url = 'https:
return ET.fromstring(requests.get(url).content).getchildren()[0] | Get the metadata of a changeset using the OSM API and return it as a XML
ElementTree.
Args:
changeset: the id of the changeset. | codesearchnet |
def minimal_selector(self, complete_selector):
if complete_selector not in self._selector_map:
raise KeyError("No value with selector '{}'.".format(complete_selector))
selector_components = complete_selector.split('.')
node = self._selector_tree
start = None
for i, component in enumerat... | Returns the minimal selector that uniquely matches `complete_selector`.
Args:
complete_selector: A complete selector stored in the map.
Returns:
A partial selector that unambiguously matches `complete_selector`.
Raises:
KeyError: If `complete_selector` is not in the map. | juraj-google-style |
def _string_to_components(spec=None):
cached_result = _STRING_TO_COMPONENTS_CACHE.get(spec)
if cached_result is not None:
return cached_result
raw_spec = spec
job, replica, task, device_type, device_index = (None, None, None, None, None)
spec = spec or ''
splits = [x.split(':') for x in ... | Stateless portion of device spec string parsing.
Args:
spec: An optional string specifying a device specification.
Returns:
The parsed components of `spec`. Note that the result of this function
must go through attribute setters of DeviceSpec, and should therefore NOT
be used directly. | github-repos |
def Print(self, x, data, message, **kwargs):
del data, message, kwargs
tf.logging.warning("Warning - mtf.Print not implemented for this mesh type")
return x | Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor. | juraj-google-style |
def reindex(self, kdims=[], force=False):
if (not isinstance(kdims, list)):
kdims = [kdims]
kdims = [self.get_dimension(kd, strict=True) for kd in kdims]
dropped = [kd for kd in self.kdims if (kd not in kdims)]
if dropped:
raise ValueError('DynamicMap does not allow dropping dimensions, ... | Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions.
Dropping dimensions is not allowed on a DynamicMap.
Args:
kdims: List of dimensions to reindex the mapping with
force: Not applicable to a DynamicMap
Returns:
Reindexed DynamicMap | codesearchnet |
def submit(self, command='', blocksize=1, job_name='parsl.auto'):
(instance, name) = self.create_instance(command=command)
self.provisioned_blocks += 1
self.resources[name] = {'job_id': name, 'status': translate_table[instance['status']]}
return name | The submit method takes the command string to be executed upon
instantiation of a resource most often to start a pilot.
Args :
- command (str) : The bash command string to be executed.
- blocksize (int) : Blocksize to be requested
KWargs:
- job_name (str) : Human friendly name to be assigned to the job request
Retur... | codesearchnet |
def get(self, key):
match = self._get_match(key=key)
if not match:
return None
return self._get_value_from_match(key=key, match=match) | Gets the value of the property of the given key.
Args:
key (str): Key of the property to look-up. | juraj-google-style |
def get_token(self, text, start=0):
best_class = best_match = None
for (token_class, match) in self.matching_tokens(text):
if (best_match and (best_match.end() >= match.end())):
continue
best_match = match
best_class = token_class
return (best_class, best_match) | Retrieve the next token from some text.
Args:
text (str): the text from which tokens should be extracted
Returns:
(token_kind, token_text): the token kind and its content. | codesearchnet |
async def reopen(self):
res = (await self.connection('POST', 'tournaments/{}/matches/{}/reopen'.format(self._tournament_id, self._id)))
self._refresh_from_json(res) | Reopens a match that was marked completed, automatically resetting matches that follow it
|methcoro|
Raises:
APIException | codesearchnet |
def get_stored_hash(self, temp_ver):
with open(self._prefixed('%s.hash' % temp_ver.name)) as f:
return f.read().strip() | Retrieves the hash for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the hash
for
Returns:
str: hash of the given template version | juraj-google-style |
def compute_kv(self, memory_antecedent):
if not self.shared_kv:
raise ValueError("compute_kv can only be called with shared_kv")
ret = mtf.einsum(
[memory_antecedent, self.wkv], reduced_dims=[self.memory_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.d... | Compute key/value Tensor kv.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {key_dim} + other_dims | juraj-google-style |
def RetrievePluginAsset(self, run, plugin_name, asset_name):
accumulator = self.GetAccumulator(run)
return accumulator.RetrievePluginAsset(plugin_name, asset_name) | Return the contents for a specific plugin asset from a run.
Args:
run: The string name of the run.
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is not available. | juraj-google-style |
def _wrap_method(name):
method = getattr(datetime.datetime, name)
@functools.wraps(method, ('__name__', '__doc__'), ())
def wrapper(self, *args, **kw):
r = method(self, *args, **kw)
if (isinstance(r, datetime.datetime) and (not isinstance(r, type(self)))):
r = type(self)(r)
... | Wrap a method.
Patch a method which might return a datetime.datetime to return a
datetime_tz.datetime_tz instead.
Args:
name: The name of the method to patch | codesearchnet |
def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent':
header_lines = cls._find_lines(header)
body_lines = cls._find_lines(body)
header_view = memoryview(header)
body_view = memoryview(body)
return cls._parse_split([header_view, body_view], header, body,
... | Parse the header and body bytestrings into message content.
Args:
header: The header bytestring to parse.
body: The body bytestring to parse. | juraj-google-style |
def unregister(self, alias):
if (alias not in self._service_objects):
raise Error(self._device, ('No service is registered with alias "%s".' % alias))
service_obj = self._service_objects.pop(alias)
if service_obj.is_alive:
with expects.expect_no_raises(('Failed to stop service instance "%s".... | Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister. | codesearchnet |
def _parse_plugin_data_as(content, data_oneof_field):
plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content)
if (plugin_data.version != PLUGIN_DATA_VERSION):
raise error.HParamsError(('Only supports plugin_data version: %s; found: %s in: %s' % (PLUGIN_DATA_VERSION, plugin_data.version, plug... | Returns a data oneof's field from plugin_data.content.
Raises HParamsError if the content doesn't have 'data_oneof_field' set or
this file is incompatible with the version of the metadata stored.
Args:
content: The SummaryMetadata.plugin_data.content to use.
data_oneof_field: string. The name of the data oneof field ... | codesearchnet |
def add_result(self, test, passed, error=None):
self.result[unicode(test.__class__.__name__)] = {
'started': self.started,
'stopped': time.strftime('%Y-%m-%dT%H:%M:%S'),
'passed': passed,
'error': error,
'executions': SimpleTestResult.executio... | Record test result into json file
Args:
test (TestCase): The test just run
passed (bool): Whether the case is passed | juraj-google-style |
def ClientCertFromCSR(cls, csr):
builder = x509.CertificateBuilder()
common_name = csr.GetCN()
serial = int(common_name.split('.')[1], 16)
builder = builder.serial_number(serial)
builder = builder.subject_name(x509.Name([x509.NameAttribute(oid.NameOID.COMMON_NAME, str(common_name))]))
now = rdfv... | Creates a new cert for the given common name.
Args:
csr: A CertificateSigningRequest.
Returns:
The signed cert. | codesearchnet |
def get_json_type(obj):
if hasattr(obj, 'get_config'):
return {'class_name': obj.__class__.__name__, 'config': obj.get_config()}
if type(obj).__module__ == np.__name__:
if isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj.item()
if callable(obj... | Serializes any object to a JSON-serializable structure.
Args:
obj: the object to serialize
Returns:
JSON-serializable structure representing `obj`.
Raises:
TypeError: if `obj` cannot be serialized. | github-repos |
def etm_register_write(self, register_index, value, delay=False):
self._dll.JLINKARM_ETM_WriteReg(int(register_index), int(value), int(delay))
return None | Writes a value to an ETM register.
Args:
self (JLink): the ``JLink`` instance.
register_index (int): the register to write to.
value (int): the value to write to the register.
delay (bool): boolean specifying if the write should be buffered.
Returns:
``None`` | codesearchnet |
def unitary(input_circuit: circuit.QuantumCircuit):
return tfq.layers.Unitary()(input_circuit.pqc, symbol_names=input_circuit.symbol_names, symbol_values=tf.expand_dims(input_circuit.symbol_values, 0)).to_tensor()[0] | Returns the unitary matrix corresponding to the given circuit.
Args:
input_circuit: Quantum circuit whose unitary matrix is to be calculated. | github-repos |
def sparse_subtract(x1, x2):
if isinstance(x2, tf.SparseTensor):
return tf.sparse.add(x1, tf.sparse.map_values(tf.negative, x2))
else:
return tf.sparse.add(x1, tf.negative(x2)) | Subtraction for `tf.SparseTensor`s.
Either `x1` or `x2` or both can be `tf.SparseTensor`s.
Args:
x1: fist tensor to add.
x2: second tensor to add.
Returns:
The sum of `x1` and `x2`, which is a `tf.SparseTensor` if and only if
both `x1` or `x2` are `tf.SparseTensor`s. | github-repos |
def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool=False) -> torch.Tensor:
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states, attn_weights, _ = self.self_attn(hidden_states=hidden_states, attention_mask=attention... | Args:
hidden_states (`torch.FloatTensor`):
input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`):
attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very
large negative values. | github-repos |
def remove_file_from_tree(tree, file_path):
match = None
for item in tree:
if item.get("path") == file_path:
match = item
break
if match:
tree.remove(match)
return tree | Remove a file from a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of a file to remove from a tree.
Returns:
The provided tree, but with the item matching the specified
file_path removed. | juraj-google-style |
def __init__(self, idx):
self.idx = idx
self.source = -1
self.target = -1
self.data = {} | Initialize the Edge.
Args:
idx: The index of the Edge. | juraj-google-style |
def GetHandlers(self):
handlers = []
if self.ssl_context:
handlers.append(urllib2.HTTPSHandler(context=self.ssl_context))
if self.proxies:
handlers.append(urllib2.ProxyHandler(self.proxies))
return handlers | Retrieve the appropriate urllib2 handlers for the given configuration.
Returns:
A list of urllib2.BaseHandler subclasses to be used when making calls
with proxy. | codesearchnet |
def get_settings(section='gocd', settings_paths=('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')):
if isinstance(settings_paths, basestring):
settings_paths = (settings_paths,)
config_file = next((path for path in settings_paths if is_file_readable(path)), None)
if config_file:
config_file =... | Returns a `gocd_cli.settings.Settings` configured for settings file
The settings will be read from environment variables first, then
it'll be read from the first config file found (if any).
Environment variables are expected to be in UPPERCASE and to be prefixed
with `GOCD_`.
Args:
section: The prefix to use for rea... | codesearchnet |
def is_user_profile_valid(user_profile):
if (not user_profile):
return False
if (not (type(user_profile) is dict)):
return False
if (UserProfile.USER_ID_KEY not in user_profile):
return False
if (UserProfile.EXPERIMENT_BUCKET_MAP_KEY not in user_profile):
return False
... | Determine if provided user profile is valid or not.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not. | codesearchnet |
def listTemplates(data={}):
conn = Qubole.agent()
url_path = Template.rest_entity_path
page_attr = []
if "page" in data and data["page"] is not None:
page_attr.append("page=%s" % data["page"])
if "per_page" in data and data["per_page"] is not None:
... | Fetch existing Templates details.
Args:
`data`: dictionary containing the value of page number and per-page value
Returns:
Dictionary containing paging_info and command_templates details | juraj-google-style |
def get_strip_metadata(self, catID):
self.logger.debug('Retrieving strip catalog metadata')
url = '%(base_url)s/record/%(catID)s?includeRelationships=false' % {
'base_url': self.base_url, 'catID': catID
}
r = self.gbdx_connection.get(url)
if r.status_code ==... | Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with interesting information exposed. | juraj-google-style |
def Save(obj: _Serializable, filename: Path, compress: bool=False, open_function=open) -> None:
with open_function(filename, 'wb') as fi:
if compress:
with gzip.GzipFile(filename='', mode='wb', fileobj=fi, mtime=1.0) as zfi:
zfi.write(Encode(obj))
else:
fi.wri... | Saves a serializable object to a file.
Args:
obj: The object to serialize.
filename: filename to write to.
compress: if True, the data will be compressed using gzip. The given
filename will be used, unaltered.
open_function: The function to use to open files. Defaults to the builtin
open() function. | github-repos |
def _write_init_fetchers(self, filenames):
destination = ('%s%s' % (self.output_directory, self.fetchers_path))
self.write(destination=destination, filename='__init__.py', template_name='__init_fetcher__.py.tpl', filenames=self._prepare_filenames(filenames, suffix='Fetcher'), class_prefix=self._class_prefix, pr... | Write fetcher init file
Args:
filenames (dict): dict of filename and classes | codesearchnet |
def filter_by_analysis_period(self, analysis_period):
_filtered_data = self.filter_by_months_per_hour(
analysis_period.months_per_hour)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | juraj-google-style |
def annotations_from_file(filename):
import edflib
e = edflib.EdfReader(filename, annotations_mode='all')
return e.read_annotations() | Get a list of event annotations from an EDF (European Data Format file
or EDF+ file, using edflib.
Args:
filename: EDF+ file
Returns:
list: annotation events, each in the form [start_time, duration, text] | juraj-google-style |
def __init__(self, rdfclass=None, **kwargs):
super(RDFStructDictType, self).__init__(**kwargs)
self._type = self.rdfclass = rdfclass | An arg which must be an RDFStruct.
Args:
rdfclass: The RDFStruct subclass that this arg must be.
**kwargs: Passthrough to base class. | juraj-google-style |
def asym(scatterer, h_pol=True):
if (scatterer.psd_integrator is not None):
return scatterer.psd_integrator.get_angular_integrated(scatterer.psd, scatterer.get_geometry(), 'asym')
old_geom = scatterer.get_geometry()
cos_t0 = np.cos((scatterer.thet0 * deg_to_rad))
sin_t0 = np.sin((scatterer.thet0... | Asymmetry parameter for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The asymmetry parameter. | codesearchnet |
def __init__(self, resolver_context):
super(NTFSFileSystem, self).__init__(resolver_context)
self._file_object = None
self._fsntfs_volume = None | Initializes a file system object.
Args:
resolver_context (Context): resolver context. | juraj-google-style |
def update_port(self, port_information, id_or_uri, timeout=(- 1)):
uri = (self._client.build_uri(id_or_uri) + '/ports')
return self._client.update(port_information, uri, timeout) | Updates an interconnect port.
Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
port_information (dict): object to update
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:
... | codesearchnet |
def variables(self, name):
if isinstance(name, tuple):
name = name[0]
if name.startswith('@{'):
name = '@' + name[2:-1]
i = len(self)
while i >= 0:
i -= 1
if name in self[i]['__variables__']:
return self[i]['__varia... | Search for variable by name. Searches scope top down
Args:
name (string): Search term
Returns:
Variable object OR False | juraj-google-style |
def _load_sentence_list(self, path):
result = {}
for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3):
if self.include_languages is None or entry[1] in self.include_languages:
result[entry[0]] = entry[1:]
return result | Load and filter the sentence list.
Args:
path (str): Path to the sentence list.
Returns:
dict: Dictionary of sentences (id : language, transcription) | juraj-google-style |
def __str__(self):
d = enums.JLinkHaltReasons.__dict__
s = next(k for k, v in d.items() if v == self.HaltReason)
if self.dbgrq():
return s
return s.replace('_', ' ').title() | Returns a string representation of the instance.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
A string representation of the instance. | juraj-google-style |
def get_template_files(self, template_id, filename):
url = self.TEMPLATE_GET_FILES_URL + template_id
request = self._get_request()
return request.get_file(url, filename) | Download a PDF copy of a template's original files
Args:
template_id (str): The id of the template to retrieve.
filename (str): Filename to save the PDF file to. This should be a full path.
Returns:
Returns a PDF file | juraj-google-style |
def _build(self, inputs_list):
outputs = []
for (idx, tensor) in enumerate(inputs_list):
outputs.append(Linear(self._output_size, initializers=self._initializers, partitioners=self._partitioners, regularizers=self._regularizers, use_bias=((idx == 0) and self._use_bias))(tensor))
return tf.add_n(outp... | Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for the multiplication. The batch size may differ for eac... | codesearchnet |
def count_up_to(self, limit):
return gen_state_ops.resource_count_up_to(self.handle, limit=limit, T=self.dtype) | Increments this variable until it reaches `limit`.
When that Op is run it tries to increment the variable by `1`. If
incrementing the variable would bring it above `limit` then the Op raises
the exception `OutOfRangeError`.
If no error is raised, the Op outputs the value of the variable before
the increment.
This is... | github-repos |
def transform(self, value):
with tf.name_scope((self._name + '/transform')):
no_batch_dim = (value.shape.ndims == self._mean.shape.ndims)
if no_batch_dim:
value = value[(None, ...)]
if self._center:
value -= self._mean[(None, ...)]
if self._scale:
... | Normalize a single or batch tensor.
Applies the activated transformations in the constructor using current
estimates of mean and variance.
Args:
value: Batch or single value tensor.
Returns:
Normalized batch or single value tensor. | codesearchnet |
def line_starts_subpgm(line: str) -> Tuple[(bool, Optional[str])]:
match = RE_SUB_START.match(line)
if (match != None):
f_name = match.group(1)
return (True, f_name)
match = RE_FN_START.match(line)
if (match != None):
f_name = match.group(1)
return (True, f_name)
retu... | Indicates whether a line in the program is the first line of a subprogram
definition.
Args:
line
Returns:
(True, f_name) if line begins a definition for subprogram f_name;
(False, None) if line does not begin a subprogram definition. | codesearchnet |
def clean(self, value):
if value is None and self._optional:
return None
for i in range(len(self._nodes)):
if self._nodes[i].valid(value):
return self._nodes[i].clean(value)
raise ValueError('value', value) | Clean
Uses the valid method to check which type the value is, and then calls
the correct version of clean on that node
Arguments:
value {mixed} -- The value to clean
Returns:
mixed | juraj-google-style |
def full_name_node(name, ctx=ast.Load()):
names = name.split('.')
names.reverse()
node = ast.Name(id=names.pop(), ctx=ast.Load())
while names:
node = ast.Attribute(value=node, attr=names.pop(), ctx=ast.Load())
node.ctx = ctx
return node | Make an Attribute or Name node for name.
Translate a qualified name into nested Attribute nodes (and a Name node).
Args:
name: The name to translate to a node.
ctx: What context this name is used in. Defaults to Load()
Returns:
A Name or Attribute node. | github-repos |
def sequence_path(self, fasta_path):
if (not fasta_path):
self.sequence_dir = None
self.sequence_file = None
else:
if (not op.exists(fasta_path)):
raise OSError('{}: file does not exist'.format(fasta_path))
if (not op.dirname(fasta_path)):
self.sequence_di... | Provide pointers to the paths of the FASTA file
Args:
fasta_path: Path to FASTA file | codesearchnet |
def get_source_var_declaration(self, var):
return next((x.source_mapping for x in self.variables if (x.name == var))) | Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping | codesearchnet |
def __init__(self, device, configs=None):
self._device = device
self._configs = configs | Constructor of the class.
The constructor is the only place to pass in a config. If you need to
change the config later, you should unregister the service instance
from `ServiceManager` and register again with the new config.
Args:
device: the device object this service is associated with.
config: optional configurat... | github-repos |
def join_dags(self, names=None):
return self._client.send(
Request(
action='join_dags',
payload={'names': names}
)
).success | Wait for the specified dags to terminate.
This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.
Args:
names (list): The names of the dags that have to terminate.
Returns:
bool: True if all the... | juraj-google-style |
def to_string(cls, error_code):
if error_code == cls.ERROR_UNKNOWN:
return 'Unknown error.'
elif error_code == cls.ERROR_NO_MORE_EVENTS:
return 'There are no more available watchpoint units.'
elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return 'No ... | Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | juraj-google-style |
def create_attention_mask_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]:
return [1] * (1 + len(query_ids) + 1 + len(table_values)) | Creates the attention mask according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs corresponding to the ID.
table_values (`List[TableValue]`): lift of table values, which are named tuples containing the
token value, the column ID and the row ID of said token.
Retu... | github-repos |
def _task_table(self, task_id):
assert isinstance(task_id, ray.TaskID)
message = self._execute_command(task_id, 'RAY.TABLE_LOOKUP', ray.gcs_utils.TablePrefix.RAYLET_TASK, '', task_id.binary())
if (message is None):
return {}
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(messag... | Fetch and parse the task table information for a single task ID.
Args:
task_id: A task ID to get information about.
Returns:
A dictionary with information about the task ID in question. | codesearchnet |
def uniprot_reviewed_checker_batch(uniprot_ids):
uniprot_ids = ssbio.utils.force_list(uniprot_ids)
invalid_ids = [i for i in uniprot_ids if (not is_valid_uniprot_id(i))]
uniprot_ids = [i for i in uniprot_ids if is_valid_uniprot_id(i)]
if invalid_ids:
warnings.warn('Invalid UniProt IDs {} will be... | Batch check if uniprot IDs are reviewed or not
Args:
uniprot_ids: UniProt ID or list of UniProt IDs
Returns:
A dictionary of {UniProtID: Boolean} | codesearchnet |
def netflix(es, ps, e0, l=.0001):
m = len(es)
n = len(ps[0])
X = np.stack(ps).T
pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2)
w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy)
return X.dot(w), w | Combine predictions with the optimal weights to minimize RMSE.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the ridge regression
Returns:
Ensemble prediction (np.array) and weights (np.array) for input predictions | juraj-google-style |
def convert_compartment_entry(self, compartment, adjacencies):
d = OrderedDict()
d['id'] = compartment.id
if adjacencies is not None:
d['adjacent_to'] = adjacencies
order = {key: i for i, key in enumerate(['name'])}
prop_keys = set(compartment.properties)
... | Convert compartment entry to YAML dict.
Args:
compartment: :class:`psamm.datasource.entry.CompartmentEntry`.
adjacencies: Sequence of IDs or a single ID of adjacent
compartments (or None). | juraj-google-style |
def node_from_map(node_map: Mapping[str, node_def_pb2.NodeDef], name: str) -> node_def_pb2.NodeDef:
stripped_name = node_name_from_input(name)
if stripped_name not in node_map:
raise ValueError("No node named '%s' found in map." % name)
return node_map[stripped_name] | Pulls a node def from a dictionary for a given name.
Args:
node_map: Dictionary containing an entry indexed by name for every node.
name: Identifies the node we want to find.
Returns:
NodeDef of the node with the given name.
Raises:
ValueError: If the node isn't present in the dictionary. | github-repos |
def _bdtr(k, n, p):
ones = tf.ones_like((n - k))
k_eq_n = tf.equal(k, n)
safe_dn = tf.where(k_eq_n, ones, (n - k))
dk = tf.math.betainc(a=safe_dn, b=(k + 1), x=(1 - p))
return tf.where(k_eq_n, ones, dk) | The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`. | codesearchnet |
def get_next_of_type(self, processor_type):
with self._condition:
if processor_type not in self:
self.wait_for_registration(processor_type)
try:
processor = self[processor_type].next_processor()
except NoProcessorVacancyError:
... | Get the next available processor of a particular type and increment
its occupancy counter.
Args:
processor_type (ProcessorType): The processor type associated with
a zmq identity.
Returns:
(Processor): Information about the transaction processor | juraj-google-style |
def getMAC(self, bType=MacType.RandomMac):
print '%s call getMAC' % self.port
print bType
if self.isPowerDown:
macAddr64 = self.mac
else:
if bType == MacType.FactoryMac:
macAddr64 = self.__sendCommand('eui64')[0]
elif ... | get one specific type of MAC address
currently OpenThread only supports Random MAC address
Args:
bType: indicate which kind of MAC address is required
Returns:
specific type of MAC address | juraj-google-style |
def has_ncols(state, incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}."):
has_result(state)
n_stu = len(state.student_result)
n_sol = len(state.solution_result)
if (n_stu != n_sol... | Test whether the student and solution query results have equal numbers of columns.
Args:
incorrect_msg: If specified, this overrides the automatically generated feedback message
in case the number of columns in the student and solution query don't match.
:Example:
Consider the following solution and SCT: ::
# solut... | codesearchnet |
def _ReadStructureFromFileObject(self, file_object, file_offset, data_type_map):
context = None
data = b''
last_data_size = 0
data_size = data_type_map.GetByteSize()
if (not data_size):
data_size = data_type_map.GetSizeHint()
while (data_size != last_data_size):
read_offset = (fi... | Reads a structure from a file-like object.
If the data type map has a fixed size this method will read the predefined
number of bytes from the file-like object. If the data type map has a
variable size, depending on values in the byte stream, this method will
continue to read from the file-like object until the data t... | codesearchnet |
def CsvToTable(self, buf, header=True, separator=","):
self.Reset()
header_row = self.row_class()
if header:
line = buf.readline()
header_str = ""
while not header_str:
header_str = line.split("
if not... | Parses buffer into tabular format.
Strips off comments (preceded by '#').
Optionally parses and indexes by first line (header).
Args:
buf: String file buffer containing CSV data.
header: Is the first line of buffer a header.
separator: String that CSV is separated by.
Returns:
int, the size of the table created.
Ra... | juraj-google-style |
def get_converter_to_specific(self, dataset=None, mass=None, to_unit=None, from_unit=None):
if (not dataset):
dataset_number = self._validate_dataset_number(None)
if (dataset_number is None):
self._report_empty_dataset()
return
dataset = self.datasets[dataset_number]
... | get the convertion values
Args:
dataset: DataSet object
mass: mass of electrode (for example active material in mg)
to_unit: (float) unit of input, f.ex. if unit of charge
is mAh and unit of mass is g, then to_unit for charge/mass
will be 0.001 / 1.0 = 0.001
from_unit: float) unit of output, f.ex. if unit of charge
is... | codesearchnet |
def GetMetadataAttribute(self, attribute_name):
table_name = 'metadata'
has_table = self._database_file.HasTable(table_name)
if not has_table:
return None
column_names = ['value']
condition = 'name == "{0:s}"'.format(attribute_name)
values = list(self._database_file.GetValues(
... | Retrieves the metadata attribute.
Args:
attribute_name (str): name of the metadata attribute.
Returns:
str: the metadata attribute or None.
Raises:
RuntimeError: if more than one value is found in the database. | juraj-google-style |
def __eq__(self, other: 'TensorFluent') -> 'TensorFluent':
return self._binary_op(self, other, tf.equal, tf.float32) | Returns a TensorFluent for the equal relational operator.
Args:
self: The first operand.
other: The second operand. | juraj-google-style |
def describe_file(module):
descriptor = FileDescriptor()
descriptor.package = util.get_package_for_module(module)
if not descriptor.package:
descriptor.package = None
message_descriptors = []
enum_descriptors = []
for name in sorted(dir(module)):
value = getattr... | Build a file from a specified Python module.
Args:
module: Python module to describe.
Returns:
Initialized FileDescriptor instance describing the module. | juraj-google-style |
def categorical_partition_data(data):
series = pd.Series(data)
value_counts = series.value_counts(dropna=True)
null_indexes = series.isnull()
nonnull_count = (null_indexes == False).sum()
weights = value_counts.values / nonnull_count
return {
"values": value_counts.inde... | Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list) The weights of the values in the partition.
} | juraj-google-style |
def mix(self, ca, cb, xb):
r = (((1 - xb) * ca.red) + (xb * cb.red))
g = (((1 - xb) * ca.green) + (xb * cb.green))
b = (((1 - xb) * ca.blue) + (xb * cb.blue))
a = (((1 - xb) * ca.alpha) + (xb * cb.alpha))
return gdk.RGBA(red=r, green=g, blue=b, alpha=a) | Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS. | codesearchnet |
def has_no_flat_neurites(neuron, tol=0.1, method='ratio'):
return CheckResult(len(get_flat_neurites(neuron, tol, method)) == 0) | Check that a neuron has no flat neurites
Arguments:
neuron(Neuron): The neuron object to test
tol(float): tolerance
method(string): way of determining flatness, 'tolerance', 'ratio' \
as described in :meth:`neurom.check.morphtree.get_flat_neurites`
Returns:
CheckResult with result | juraj-google-style |
def construct(cls, name, range=None):
other = Requirement(None)
other.name_ = name
other.range_ = (VersionRange() if (range is None) else range)
return other | Create a requirement directly from an object name and VersionRange.
Args:
name: Object name string.
range: VersionRange object. If None, an unversioned requirement is
created. | codesearchnet |
def _TestCase(self, shape, indices, scatter_op=state_ops.scatter_add):
super(ScatterAddSubTest, self).setUp()
with self.cached_session(use_gpu=False):
p_init = np.random.rand(*shape).astype('f')
vals_shape = [len(indices)] + shape[1:]
vals_init = np.random.rand(*vals_shape).astype('f')
... | Run a random test case with the given shape and indices.
Args:
shape: Shape of the parameters array.
indices: One-dimensional array of ints, the indices of the last dimension
of the parameters to update.
scatter_op: ScatterAdd or ScatterSub. | github-repos |
def _generic_fit(fqdn, result, scorer, yP=None, *argl, **argd):
out = None
if (len(argl) > 0):
machine = argl[0]
out = {}
if hasattr(machine, 'best_score_'):
out['score'] = machine.best_score_
yL = _do_auto_predict(*argl[0:2])
yscore = scorer(fqdn, yL, yP, *ar... | Performs the generic fit tests that are common to both classifier and
regressor; uses `scorer` to score the predicted values given by the machine
when tested against its training set.
Args:
scorer (function): called on the result of `machine.predict(Xtrain,
ytrain)`. | codesearchnet |
def GetTransactionResults(self):
if (self.References is None):
return None
results = []
realresults = []
for ref_output in self.References.values():
results.append(TransactionResult(ref_output.AssetId, ref_output.Value))
for output in self.outputs:
results.append(TransactionR... | Get the execution results of the transaction.
Returns:
None: if the transaction has no references.
list: of TransactionResult objects. | codesearchnet |
def predict(self, data, alpha=0.01, max_iter=2000, **kwargs):
edge_model = GraphLasso(alpha=alpha, max_iter=max_iter)
edge_model.fit(data.values)
return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()), {idx: i for (idx, i) in enumerate(data.columns)}) | Predict the graph skeleton.
Args:
data (pandas.DataFrame): observational data
alpha (float): regularization parameter
max_iter (int): maximum number of iterations
Returns:
networkx.Graph: Graph skeleton | codesearchnet |
def list_insights_components(access_token, subscription_id, resource_group):
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', resource_group,
'/providers/microsoft.insights/',
... | List the Microsoft Insights components in a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
Returns:
HTTP response. JSON body of components. | juraj-google-style |
def add_middleware(middleware: EFBMiddleware):
global middlewares
if isinstance(middleware, EFBMiddleware):
middlewares.append(middleware)
else:
raise TypeError("Middleware instance is expected") | Register a middleware with the coordinator.
Args:
middleware (EFBMiddleware): Middleware to register | juraj-google-style |
def add_attribute(self, attribute_type, attribute_value):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
return self.tc_requests.add_attribute(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_type,
... | Adds a attribute to a Group/Indicator or Victim
Args:
attribute_type:
attribute_value:
Returns: attribute json | juraj-google-style |
def write_byte(self, value):
if isinstance(value, bytes):
self.stream.write(value)
elif isinstance(value, str):
self.stream.write(value.encode('utf-8'))
elif isinstance(value, int):
self.stream.write(bytes([value])) | Write a single byte to the stream.
Args:
value (bytes, str or int): value to write to the stream. | juraj-google-style |
def CopyTextToLabel(cls, text, prefix=''):
text = '{0:s}{1:s}'.format(prefix, text)
return cls._INVALID_LABEL_CHARACTERS_REGEX.sub('_', text) | Copies a string to a label.
A label only supports a limited set of characters therefore
unsupported characters are replaced with an underscore.
Args:
text (str): label text.
prefix (Optional[str]): label prefix.
Returns:
str: label. | juraj-google-style |
def new(self, val):
if (len(self.things) >= self.max_things):
raise LimitationError('too many things')
self.things.add(val)
return val | Add a new value to me.
Args:
val (LispVal): The value to be added.
Returns:
LispVal: The added value.
Raises:
~parthial.errs.LimitationError: If I already contain the maximum
number of elements. | codesearchnet |
def create_api_call(func, settings):
def base_caller(api_call, _, *args):
'Simply call api_call and ignore settings.'
return api_call(*args)
def inner(request, options=None):
'Invoke with the actual settings.'
this_options = _merge_options_metadata(options, settings)
th... | Converts an rpc call into an API call governed by the settings.
In typical usage, ``func`` will be a callable used to make an rpc request.
This will mostly likely be a bound method from a request stub used to make
an rpc call.
The result is created by applying a series of function decorators defined
in this module to... | codesearchnet |
def _BuildOobLink(self, param, mode):
code = self.rpc_helper.GetOobCode(param)
if code:
parsed = list(parse.urlparse(self.widget_url))
query = dict(parse.parse_qsl(parsed[4]))
query.update({'mode': mode, 'oobCode': code})
try:
parsed[4] = parse.urlencode(query)
... | Builds out-of-band URL.
Gitkit API GetOobCode() is called and the returning code is combined
with Gitkit widget URL to building the out-of-band url.
Args:
param: dict of request.
mode: string, Gitkit widget mode to handle the oob action after user
clicks the oob url in the email.
Raises:
GitkitClientError: if oob co... | codesearchnet |
def set_parameter(self, key, value):
for x in self.transformed_structures:
x.other_parameters[key] = value | Add parameters to the transmuter. Additional parameters are stored in
the as_dict() output.
Args:
key: The key for the parameter.
value: The value for the parameter. | juraj-google-style |
def compile_initial_state(self, batch_size: Optional[int]=None) -> Sequence[tf.Tensor]:
with self.graph.as_default():
with tf.name_scope('initial_state'):
self._initialize_initial_state_fluents()
if (batch_size is None):
return self.initial_state_fluents
r... | Returns a tuple of tensors representing the initial state fluents.
Args:
batch_size (Optional[int]): The batch size.
Returns:
Sequence[tf.Tensor]: A tuple of tensors. | codesearchnet |
def __init__(
self, resolver_context, file_system, path_spec, is_root=False,
is_virtual=False):
super(SQLiteBlobFileEntry, self).__init__(
resolver_context, file_system, path_spec, is_root=is_root,
is_virtual=is_virtual)
self._number_of_entries = None
if is_virtual:
s... | Initializes a file entry.
Args:
resolver_context (Context): resolver context.
file_system (FileSystem): file system.
path_spec (PathSpec): path specification.
is_root (Optional[bool]): True if the file entry is the root file entry
of the corresponding file system.
is_virtual (Optional[bool]): True if the file entry is... | juraj-google-style |
def replace_with_json(self, json):
replacement = self.from_json(json)
replacement._destructively_move(self) | Overwrite everything in this document with the JSON-encoded
document.
json (JSON-data) :
A JSON-encoded document to overwrite this one.
Returns:
None | codesearchnet |
def with_redis_cache(self, host: str, port: int, time_to_live: Union[int, timedelta]=DEFAULT_CACHE_ENTRY_TTL_SEC, *, request_coder: Optional[coders.Coder]=None, response_coder: Optional[coders.Coder]=None, **kwargs):
if has_valid_redis_address(host, port):
self._cache = RedisCache(host=host, port=port, time... | Configure the Redis cache to use with enrichment transform.
Args:
host (str): The hostname or IP address of the Redis server.
port (int): The port number of the Redis server.
time_to_live: `(Union[int, timedelta])` The time-to-live (TTL) for
records stored in Redis. Provide an integer (in seconds) or a
`datetime.timed... | github-repos |
def serve(name: str='', port: int=5000) -> None:
logging.info(' * Listening on port %s', port)
httpd = HTTPServer((name, port), RequestHandler)
httpd.serve_forever() | A basic way to serve the methods.
Args:
name: Server address.
port: Server port. | codesearchnet |
def get_players(self, team):
team_id = self.__get_team_id(team)
self.logger.debug(f'Getting players of team {team_id}.')
return self._request('teams', team_id, 'players') | Loads the players of a team.
Args:
* team (:obj: json): a team in json format obtained from the service.
Returns:
* :obj: json: the players of the team | codesearchnet |
def derivative(self, rate):
rate = self._validate_number_sequence(rate, 3)
return 0.5 * self * Quaternion(vector=rate) | Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit quaternion describing the rotation rate | juraj-google-style |
def _profile_table(self, batch_id):
message = self._execute_command(batch_id, "RAY.TABLE_LOOKUP",
ray.gcs_utils.TablePrefix.PROFILE, "",
batch_id.binary())
if message is None:
return [... | Get the profile events for a given batch of profile events.
Args:
batch_id: An identifier for a batch of profile events.
Returns:
A list of the profile events for the specified batch. | juraj-google-style |
def build(self, var_list):
if self.built:
return
super().build(var_list)
self._momentums = self.add_optimizer_variables(var_list, 'momentum') | Initialize optimizer variables.
Lion optimizer has one variable `momentums`.
Args:
var_list: list of model variables to build Lion variables on. | github-repos |
def _RegisterDebuggee(self, service):
try:
request = {'debuggee': self._GetDebuggee()}
try:
response = service.debuggees().register(body=request).execute()
project_number = response['debuggee'].get('project')
self._project_number = (project_number or self._project... | Single attempt to register the debuggee.
If the registration succeeds, sets self._debuggee_id to the registered
debuggee ID.
Args:
service: client to use for API calls
Returns:
(registration_required, delay) tuple | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.