code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def port(self, value):
self._port = value
if (value is None):
try:
del self._connectionXML.attrib['port']
except KeyError:
pass
else:
self._connectionXML.set('port', value) | Set the connection's port property.
Args:
value: New port value. String.
Returns:
Nothing. | codesearchnet |
def rotoreflection(axis, angle, origin=(0, 0, 0)):
rot = SymmOp.from_origin_axis_angle(origin, axis, angle)
refl = SymmOp.reflection(axis, origin)
m = np.dot(rot.affine_matrix, refl.affine_matrix)
return SymmOp(m) | Returns a roto-reflection symmetry operation
Args:
axis (3x1 array): Axis of rotation / mirror normal
angle (float): Angle in degrees
origin (3x1 array): Point left invariant by roto-reflection.
Defaults to (0, 0, 0).
Return:
Roto-reflection operation | juraj-google-style |
def get_controller(self, path):
path_info = path.lstrip('/').split('/', 2)
try:
return self._routes.get(path_info[0] + '/' + path_info[1])
except (IndexError, KeyError):
return self._routes.get(path_info[0] or 'index') | Return controller that handle given path.
Args:
- path: requested path, like: /blog/post_view/15 | juraj-google-style |
def get_session(self, username, password, remote='127.0.0.1', proxy=None):
params = {'username': username, 'password': password, 'validation-factors': {'validationFactors': [{'name': 'remote_address', 'value': remote}]}}
if proxy:
params['validation-factors']['validationFactors'].append({'name': 'X-Forw... | Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be config... | codesearchnet |
def to_dict(self) -> Dict[str, Any]:
output = copy.deepcopy(self.__dict__)
if '_commit_hash' in output:
del output['_commit_hash']
if '_original_object_hash' in output:
del output['_original_object_hash']
if 'compile_config' in output:
del output['compile_config']
output['tra... | Serializes this instance to a Python dictionary.
Returns:
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. | github-repos |
def _initial_guess(self):
(a, b, c) = np.polyfit(self.volumes, self.energies, 2)
self.eos_params = [a, b, c]
v0 = ((- b) / (2 * a))
e0 = (((a * (v0 ** 2)) + (b * v0)) + c)
b0 = ((2 * a) * v0)
b1 = 4
(vmin, vmax) = (min(self.volumes), max(self.volumes))
if ((not (vmin < v0)) and (v0 < vma... | Quadratic fit to get an initial guess for the parameters.
Returns:
tuple: (e0, b0, b1, v0) | codesearchnet |
def _timesfm_masked_mean_std(inputs: torch.Tensor, padding: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
def _get_patch_index(arr: torch.Tensor):
indices = torch.argmax((arr >= 3).to(torch.int32), dim=1)
row_sum = (arr >= 3).to(torch.int32).sum(dim=1)
return torch.where(row_sum == 0,... | Calculates mean and standard deviation of `inputs` across axis 1.
It excludes values where `padding` is 1.
Args:
inputs: A PyTorch tensor of shape [b, n, p].
padding: A PyTorch tensor of shape [b, n, p] with values 0 or 1.
Returns:
A tuple containing the mean and standard deviation.
We return the statistics of the f... | github-repos |
def summary(self, line_length=None, positions=None, print_fn=None):
if not self.built:
raise ValueError('This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.')
laye... | Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided,
defaults to `[.33, .55, .67, 1.]`.
print_fn: Print function to use. ... | github-repos |
def BasenamePath(self, path):
if path.endswith(self.PATH_SEPARATOR):
path = path[:-1]
_, _, basename = path.rpartition(self.PATH_SEPARATOR)
return basename | Determines the basename of the path.
Args:
path (str): path.
Returns:
str: basename of the path. | juraj-google-style |
def __init__(
self, name, data_type_definition, aliases=None, data_type=None,
description=None, urls=None):
super(ElementSequenceDataTypeDefinition, self).__init__(
name, aliases=aliases, description=description, urls=urls)
self.byte_order = getattr(
data_type_definition, 'byte_... | Initializes a sequence data type definition.
Args:
name (str): name.
data_type_definition (DataTypeDefinition): sequence element data type
definition.
aliases (Optional[list[str]]): aliases.
data_type (Optional[str]): name of the sequence element data type.
description (Optional[str]): description.
urls (Optional[list... | juraj-google-style |
def cancel(self, workflow_id):
self.logger.debug('Canceling workflow: ' + workflow_id)
url = '%(wf_url)s/%(wf_id)s/cancel' % {
'wf_url': self.workflows_url, 'wf_id': workflow_id
}
r = self.gbdx_connection.post(url, data='')
r.raise_for_status() | Cancels a running workflow.
Args:
workflow_id (str): Workflow id.
Returns:
Nothing | juraj-google-style |
def register_thread(self, thread):
with self._lock:
self._registered_threads.add(thread) | Register a thread to join.
Args:
thread: A Python thread to join. | github-repos |
def list_changes(self):
if (not self.is_attached()):
raise ItsdbError('changes are not tracked for detached tables.')
return [(i, self[i]) for (i, row) in enumerate(self._records) if (row is not None)] | Return a list of modified records.
This is only applicable for attached tables.
Returns:
A list of `(row_index, record)` tuples of modified records
Raises:
:class:`delphin.exceptions.ItsdbError`: when called on a
detached table | codesearchnet |
def lsfiles(root='.', **kwargs):
paths = ls(root=root, **kwargs)
if isfile(root):
return paths
return [_path for _path in paths if isfile(path(root, _path))] | Return only files from a directory listing.
Arguments:
root (str): Path to directory. Can be relative or absolute.
**kwargs: Any additional arguments to be passed to ls().
Returns:
list of str: A list of file paths.
Raises:
OSError: If root directory does not exist. | codesearchnet |
def from_json_stat(datasets, naming='label', value='value'):
warnings.warn("Shouldn't use this function anymore! Now use read() methods ofDataset, Collection or Dimension.", DeprecationWarning)
check_input(naming)
results = []
if (type(datasets) is list):
for (idx, element) in enumerate(datasets... | Decode JSON-stat formatted data into pandas.DataFrame object.
Args:
datasets(OrderedDict, list): data in JSON-stat format, previously \
deserialized to a python object by \
json.load() or json.loads(), for example.\
Both List and OrderedDict are accepted \
as inputs.
naming(string, optional): dimension naming. Possibl... | codesearchnet |
def text_set_fields(text, variables):
text = RE_TEXT_FIELD.sub('{\\1}', text)
try:
return text.format_map(defaultdict(str, variables))
except ValueError:
return text | Replaces fields in text with values from recipe.
Fields in text are just are {field}, where field is a name of the variable.
Missing fields default to blanks.
Args:
text (string) A paragraph possible containing {field} entries
variables: (dict) The keys mapping to field, and values to replace
Returns:
A string with ... | github-repos |
def _get_kind_name(param_type, is_list):
if issubclass(param_type, bool):
typename = 'bool'
elif issubclass(param_type, six.integer_types):
typename = 'int64'
elif issubclass(param_type, (six.string_types, six.binary_type)):
typename = 'bytes'... | Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not recognized. | juraj-google-style |
def is_traceback_filtering_enabled():
return global_state.get_global_attribute('traceback_filtering', True) | Check if traceback filtering is enabled.
Raw Keras tracebacks (also known as stack traces)
involve many internal frames, which can be
challenging to read through, while not being actionable for end users.
By default, Keras filters internal frames in most exceptions that it
raises, to keep traceback short, readable, an... | github-repos |
def record_data(self, content):
if 'timestamp' not in content:
content = content.copy()
content['timestamp'] = utils.get_current_epoch_time()
self.summary_writer.dump(content, records.TestSummaryEntryType.USER_DATA) | Record an entry in test summary file.
Sometimes additional data need to be recorded in summary file for
debugging or post-test analysis.
Each call adds a new entry to the summary file, with no guarantee of
its position among the summary file entries.
The content should be a dict. If absent, timestamp field is added ... | github-repos |
def get_assistants(cls, superassistants):
_assistants = cls.load_all_assistants(superassistants)
result = []
for supa in superassistants:
result.extend(_assistants[supa.name])
return result | Returns list of assistants that are subassistants of given superassistants
(I love this docstring).
Args:
roles: list of names of roles, defaults to all roles
Returns:
list of YamlAssistant instances with specified roles | juraj-google-style |
def _bns_task_id(job: str) -> Union[int, str]:
maybe_task_id = job.rsplit('/')[-1].rsplit(':')[0]
try:
return int(maybe_task_id)
except ValueError:
return job | Tries to extract an integer task ID from a job name.
For example, for `job` = '/.../tpu_worker/0:port_name', return 0.
Args:
job: A job name to extract task ID from.
Returns:
The task ID on success, or the original job name on failure. | github-repos |
def fn(x: str, y: Optional[list[Union[str, int]]], z: tuple[Union[str, int], str]=(42, 'hello')) -> tuple[int, str]:
pass | Test function with multiple args, and docstring args that we have to strip out.
Args:
x: The first input. It's got a big multiline
description and also contains
(choices: ["a", "b", "c"])
y: The second input. It's a big list with a single-line description.
z: The third input. It's some kind of tuple with a default a... | github-repos |
def return_resource_name(self, record, resource_type):
try:
if resource_type == 's3':
regex = re.compile('.*(\.(?:s3-|s3){1}(?:.*)?\.amazonaws\.com)')
bucket_name = record.replace(regex.match(record).group(1), '')
return bucket_name
e... | Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..) | juraj-google-style |
def constant(interval=1):
try:
itr = iter(interval)
except TypeError:
itr = itertools.repeat(interval)
for val in itr:
(yield val) | Generator for constant intervals.
Args:
interval: A constant value to yield or an iterable of such values. | codesearchnet |
def validate(self, message, schema_name):
err = None
try:
jsonschema.validate(message, self.schemas[schema_name])
except KeyError:
msg = f
err = {'msg': msg}
except jsonschema.ValidationError as e:
msg = f'Given message was not valid against the schema "{schema_name}": {e... | Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used to look up
schema from :py:attr:`.MessageValidator.schemas` dict
Raises:
InvalidMessageError: if message is invalid ... | codesearchnet |
def _save_env(env):
env_path = os.path.join(env["resultdir"], "env")
if os.path.isdir(env["resultdir"]):
with open(env_path, "w") as f:
yaml.dump(env, f) | Saves one environment.
Args:
env (dict): the env dict to save. | juraj-google-style |
def __init__(self, data_type_definition):
if (data_type_definition.false_value is None and
data_type_definition.true_value is None):
raise errors.FormatError(
'Boolean data type has no True or False values.')
super(BooleanMap, self).__init__(data_type_definition) | Initializes a boolean data type map.
Args:
data_type_definition (DataTypeDefinition): data type definition.
Raises:
FormatError: if the data type map cannot be determined from the data
type definition. | juraj-google-style |
def rename(self, source_file_names, destination_file_names):
if not len(source_file_names) == len(destination_file_names):
message = 'Unable to rename unequal number of sources and destinations'
raise BeamIOError(message)
src_dest_pairs = list(zip(source_file_names, destination_file_names))
... | Rename the files at the source list to the destination list.
Source and destination lists should be of the same size.
Args:
source_file_names: List of file paths that need to be moved
destination_file_names: List of destination_file_names for the files
Raises:
``BeamIOError``: if any of the rename operations fail | github-repos |
def get_plot(self, structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16):
if (ax is None):
from pymatgen.util.plotting import pretty_plot
plt = pretty_plot(16, 10)
ax = plt.gca()
else:
import matplotlib.pyplot as plt
xrd = self.get_p... | Returns the diffraction plot as a matplotlib.pyplot.
Args:
structure: Input structure
two_theta_range ([float of length 2]): Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you want all diffracted beams within the limiting
sphere of radius 2 / wavelength.
annotate_peaks: Whet... | codesearchnet |
class LlavaFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
do_pad: Optional[bool] | Args:
do_pad (`bool`, *optional*):
Whether to pad the image to a square based on the longest edge. | github-repos |
def infer_module(filename, pythonpath):
for path in filter(bool, pythonpath):
if not path.endswith(path_utils.sep):
path += path_utils.sep
if filename.startswith(path):
filename = filename[len(path):]
break
else:
path = ''
return Module(path, filen... | Convert a filename to a module relative to pythonpath.
This method tries to deduce the module name from the pythonpath and the
filename. This will not always be possible. (It depends on the filename
starting with an entry in the pythonpath.)
Args:
filename: The filename of a Python file. E.g. "foo/bar/baz.py".
python... | github-repos |
def checkpoint_exists(checkpoint_prefix):
return checkpoint_exists_internal(checkpoint_prefix) | Checks whether a V1 or V2 checkpoint exists with the specified prefix.
This is the recommended way to check if a checkpoint exists, since it takes
into account the naming difference between V1 and V2 formats.
Args:
checkpoint_prefix: the prefix of a V1 or V2 checkpoint, with V2 taking
priority. Typically the result ... | github-repos |
def _get_version(self, root):
version = self.get_version(root)
if version:
return StrictVersion(version)
raise UnknownVersionError(
"Unable to determine the version of the input document. No "
"version information found on ... | Return the version of the root element passed in.
Args:
root (etree.Element)
Returns:
distutils.StrictVersion
Raises:
UnknownVersionError | juraj-google-style |
def __init__(self, request, response):
self.status = QueueItem.STATUS_QUEUED
self.decomposed = False
self.__response_soup = None
self.__index_hash = None
self.request = request
self.response = response | Constructs a QueueItem instance.
Args:
request (:class:`nyawc.http.Request`): The Request object.
response (:class:`nyawc.http.Response`): The Response object (empty object when initialized). | juraj-google-style |
def validate(self, corpus):
invalid_utterances = {}
for utterance in corpus.utterances.values():
if self.label_list_idx in utterance.label_lists.keys():
ll = utterance.label_lists[self.label_list_idx]
if len(ll) < self.min_number_of_labels:
... | Perform the validation on the given corpus.
Args:
corpus (Corpus): The corpus to test/validate.
Returns:
InvalidUtterancesResult: Validation result. | juraj-google-style |
def show_app(app, state, notebook_url, port=0, **kw):
logging.basicConfig()
from tornado.ioloop import IOLoop
from ..server.server import Server
loop = IOLoop.current()
if callable(notebook_url):
origin = notebook_url(None)
else:
origin = _origin_url(notebook_url)
server = Se... | Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a... | codesearchnet |
def serialize_sparse(sp_input, name=None, out_type=dtypes.string):
return serialize_sparse_v2(sp_input, out_type, name) | Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object.
Args:
sp_input: The input `SparseTensor`.
name: A name prefix for the returned tensors (optional).
out_type: The `dtype` to use for serialization.
Returns:
A 3-vector (1-D `Tensor`), with each column representing the serialized
`SparseTensor`'s indices... | github-repos |
def load(self, cfgstr=None):
from six.moves import cPickle as pickle
cfgstr = self._rectify_cfgstr(cfgstr)
dpath = self.dpath
fname = self.fname
verbose = self.verbose
if (not self.enabled):
if (verbose > 1):
self.log('[cacher] ... cache disabled: fname={}'.format(self.fname)... | Loads the data
Raises:
IOError - if the data is unable to be loaded. This could be due to
a cache miss or because the cache is disabled.
Example:
>>> from ubelt.util_cache import * # NOQA
>>> # Setting the cacher as enabled=False turns it off
>>> cacher = Cacher('test_disabled_load', '', enabled=True)
>>> cacher.sav... | codesearchnet |
def to_subquery(self) -> StandardSqlExpression:
return SubQuery(Select(select_part=self, from_part=None)) | Renders the expression as a subquery.
Builds a SELECT statement for the expression and returns it as a subquery.
Expressions which already render a SELECT (such as the Select and
UnionExpression classes) should overide this to remove the extra SELECT.
Returns:
A SubQuery expression for this expression. | github-repos |
def remove_observer(self, callback):
if (callback not in self._observers):
raise ValueError('{} is not an observer of {}'.format(callback, self))
self._observers.remove(callback) | Remove an observer from this event.
Args:
callback: A function or coroutine callback to remove from this
event.
Raises:
ValueError: If the callback is not an observer of this event. | codesearchnet |
def find_structure(self, filename_or_structure):
try:
if isinstance(filename_or_structure, str):
s = Structure.from_file(filename_or_structure)
elif isinstance(filename_or_structure, Structure):
s = filename_or_structure
else:
raise MPRestError('Provide fi... | Finds matching structures on the Materials Project site.
Args:
filename_or_structure: filename or Structure object
Returns:
A list of matching structures.
Raises:
MPRestError | codesearchnet |
def _try_run_local_init_op(self, sess: session.Session) -> Tuple[bool, Optional[str]]:
if self._local_init_op is not None:
is_ready_for_local_init, msg = self._model_ready_for_local_init(sess)
if is_ready_for_local_init:
logging.info('Running local_init_op.')
sess.run(self._l... | Tries to run _local_init_op, if not None, and is ready for local init.
Args:
sess: A `Session`.
Returns:
A tuple (is_successful, msg), where is_successful is True if
_local_init_op is None, or we ran _local_init_op, and False otherwise;
and msg is a `String` with the reason why the model was not ready to run
local in... | github-repos |
def load_data(path):
if not os.path.exists(path):
print(path)
raise AttributeError('Path given does not exist!')
data = {}
if 'raw_data' in os.listdir(path): ... | loads the data that has been save with Script.save.
Args:
path: path to folder saved by Script.save or raw_data folder within
Returns:
a dictionary with the data of form
data = {param_1_name: param_1_data, ...} | juraj-google-style |
def from_text_vision_configs(cls, text_config: SiglipTextConfig, vision_config: SiglipVisionConfig, **kwargs):
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs) | Instantiate a [`SiglipConfig`] (or a derived class) from siglip text model configuration and siglip vision
model configuration.
Returns:
[`SiglipConfig`]: An instance of a configuration object | github-repos |
def oauth_access(self, *, client_id: str, client_secret: str, code: str, **kwargs) -> SlackResponse:
kwargs.update({'client_id': client_id, 'client_secret': client_secret, 'code': code})
return self.api_call('oauth.access', data=kwargs) | Exchanges a temporary OAuth verifier code for an access token.
Args:
client_id (str): Issued when you created your application. e.g. '4b39e9-752c4'
client_secret (str): Issued when you created your application. e.g. '33fea0113f5b1'
code (str): The code param returned via the OAuth callback. e.g. 'ccdaa72ad' | codesearchnet |
def duplicate_verts(script):
if script.ml_version == '1.3.4BETA':
filter_xml = ' <filter name="Remove Duplicated Vertex"/>\n'
else:
filter_xml = ' <filter name="Remove Duplicate Vertices"/>\n'
util.write_filter(script, filter_xml)
return None | "Check for every vertex on the mesh: if there are two vertices with
the same coordinates they are merged into a single one.
Args:
script: the FilterScript object or script filename to write
the filter to.
Layer stack:
No impacts
MeshLab versions:
2016.12
1.3.4BETA | juraj-google-style |
def ParseLocalEntryRow(
self, parser_mediator, query, row, cache=None, database=None,
**unused_kwargs):
query_hash = hash(query)
inode_number = self._GetRowValue(query_hash, row, 'inode_number')
local_path = self.GetLocalPath(inode_number, cache, database)
event_data = GoogleDriveSnap... | Parses a local entry row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
cache (Optional[SQLiteCache]): cache.
database (Optional[SQLiteDatabase]): database. | juraj-google-style |
def _num_slices_in_dimension(self, axis):
if not isinstance(axis, int):
raise TypeError('axis must be an integer')
if axis < 0:
rank = self.rank
if rank is None:
raise ValueError("You can't use negative values if the rank is undefined")
axis = axis + rank
if axis ... | The total size of a dimension (like nvals).
Effectively, this is self[:axis+1]._num_elements()
Example:
shape = DynamicRaggedShape._from_inner_shape([2, 3, 4])
shape._num_slices_in_dimension(0) = 2
shape._num_slices_in_dimension(1) = 6
shape._num_slices_in_dimension(2) = 24
shape._num_slices_in_dimension(-1) = 24
sha... | github-repos |
def command_runner(shell_command, force_rerun_flag, outfile_checker, cwd=None, silent=False):
program_and_args = shlex.split(shell_command)
if (not program_exists(program_and_args[0])):
raise OSError('{}: program not installed'.format(program_and_args[0]))
if cwd:
outfile_checker = op.join(c... | Run a shell command with subprocess, with additional options to check if output file exists and printing stdout.
Args:
shell_command (str): Command as it would be formatted in the command-line (ie. "program -i test.in -o test.out").
force_rerun_flag: If the program should be rerun even if the output file exists.
outfi... | codesearchnet |
def is_published(self):
citeable = (('publication_info' in self.record) and is_citeable(self.record['publication_info']))
submitted = (('dois' in self.record) and any((('journal_title' in el) for el in force_list(self.record.get('publication_info')))))
return (citeable or submitted) | Return True if a record is published.
We say that a record is published if it is citeable, which means that
it has enough information in a ``publication_info``, or if we know its
DOI and a ``journal_title``, which means it is in press.
Returns:
bool: whether the record is published.
Examples:
>>> record = {
... ... | codesearchnet |
def restore_state(self, state):
super(EmulatedPeripheralTile, self).restore_state(state)
self.debug_mode = state.get('debug_mode', False)
self.run_level = state.get('run_level', None)
if state.get('app_started', False):
self._hosted_app_running.set() | Restore the current state of this emulated object.
Args:
state (dict): A previously dumped state produced by dump_state. | juraj-google-style |
def _init_project_service(self, version):
project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)
self._token_project = project_cfg[CONFIG_TOKEN]
proto = project_cfg[CONFIG_PROTOCOL]
host = project_cfg[CONFIG_HOST]
self._project = ProjectService(host, version)
self._project.base_protocol... | Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | codesearchnet |
def get_course_video_ids_with_youtube_profile(course_ids=None, offset=None, limit=None):
course_videos = CourseVideo.objects.select_related('video').prefetch_related('video__encoded_videos', 'video__encoded_videos__profile').filter(video__encoded_videos__profile__profile_name='youtube').order_by('id').distinct()
... | Returns a list that contains all the course ids and video ids with the youtube profile
Args:
course_ids (list): valid course ids
limit (int): batch records limit
offset (int): an offset for selecting a batch
Returns:
(list): Tuples of course_id, edx_video_id and youtube video url | codesearchnet |
def train(total_loss, global_step):
num_batches_per_epoch = (NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size)
decay_steps = int((num_batches_per_epoch * NUM_EPOCHS_PER_DECAY))
lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE, global_step, decay_steps, LEARNING_RATE_DECAY_FACTOR, staircase=True)
... | Train CIFAR-10 model.
Create an optimizer and apply to all trainable variables. Add moving
average for all trainable variables.
Args:
total_loss: Total loss from loss().
global_step: Integer Variable counting the number of training steps
processed.
Returns:
train_op: op for training. | codesearchnet |
def signatures(self, transaction):
if (not self.multi_wallet):
raise DecryptionError('This wallet must be unlocked with wallet.unlock(passphrase)')
return self.multi_wallet.signatures(transaction) | Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ] | codesearchnet |
def __setitem__(self, key, value):
with self._condition:
if key not in self._processors:
proc_iterator = self._proc_iter_class()
proc_iterator.add_processor(value)
self._processors[key] = proc_iterator
else:
self._p... | Either create a new ProcessorIterator, if none exists for a
ProcessorType, or add the Processor to the ProcessorIterator.
Args:
key (ProcessorType): The type of transactions this transaction
processor can handle.
value (Processor): Information about the transaction processor. | juraj-google-style |
def CreateSourceType(cls, type_indicator, attributes):
if type_indicator not in cls._source_type_classes:
raise errors.FormatError(
'Unsupported type indicator: {0:s}.'.format(type_indicator))
return cls._source_type_classes[type_indicator](**attributes) | Creates a source type.
Args:
type_indicator (str): source type indicator.
attributes (dict[str, object]): source type attributes.
Returns:
SourceType: a source type.
Raises:
FormatError: if the type indicator is not set or unsupported,
or if required attributes are missing. | juraj-google-style |
def get_compute_usage(access_token, subscription_id, location):
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/providers/Microsoft.compute/locations/', location,
'/usages?api-version=', COMP_API])
return d... | List compute usage and limits for a location.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data center location. E.g. westus.
Returns:
HTTP response. JSON body of Compute usage and limits data. | juraj-google-style |
def get_data_xlsx(file_name, file_contents=None, on_demand=False):
return get_data_xls(file_name, file_contents=file_contents, on_demand=on_demand) | Loads the new excel format files. Old format files will automatically get loaded as well.
Args:
file_name: The name of the local file, or the holder for the
extension type when the file_contents are supplied.
file_contents: The file-like object holding contents of file_name.
If left as None, then file_name is directly... | juraj-google-style |
def count(self, files=False):
return (len(self.files) if files else len(self.unique())) | Returns a count of unique values or files.
Args:
files (bool): When True, counts all files mapped to the Entity.
When False, counts all unique values.
Returns: an int. | codesearchnet |
def list_vdirs(site, app=_DEFAULT_APP):
ret = dict()
ps_cmd = ['Get-WebVirtualDirectory', '-Site', "'{0}'".format(site), '-Application', "'{0}'".format(app), '|', "Select-Object PhysicalPath, @{ Name = 'name';", "Expression = { $_.path.Split('/')[-1] } }"]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
... | Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_... | codesearchnet |
def by_name(name):
devices = discover(all_households=True)
for device in (devices or []):
if (device.player_name == name):
return device
return None | Return a device by name.
Args:
name (str): The name of the device to return.
Returns:
:class:`~.SoCo`: The first device encountered among all zone with the
given player name. If none are found `None` is returned. | codesearchnet |
def match_shortname(self, name, filled_args=None):
filled_count = 0
if filled_args is not None:
filled_count = len(filled_args)
possible = [x for x in self.arg_names[filled_count:] if x.startswith(name)]
if len(possible) == 0:
raise ArgumentError("Could... | Try to convert a prefix into a parameter name.
If the result could be ambiguous or there is no matching
parameter, throw an ArgumentError
Args:
name (str): A prefix for a parameter name
filled_args (list): A list of filled positional arguments that will be
removed from consideration.
Returns:
str: The full matching ... | juraj-google-style |
def record_ttft_metric(self, created_time: float, request_id: str) -> None:
if not _has_opentelemetry:
return
ttft_ms = (time.time() - created_time) * 1000.0
try:
self.ttft_histogram.record(ttft_ms)
logger.debug(f'Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms')
except E... | Record Time to First Token (TTFT).
Args:
created_time: The time the request was created
request_id: The ID of the request | github-repos |
def write(self, string):
x, y = self._normalizeCursor(*self._cursor)
width, height = self.get_size()
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
writeLines = []
for line in string.split('\n'):
if line:
... | This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :an... | juraj-google-style |
def meas_gate(self, circuit, qreg, op):
if (self.meas_fun is None):
pass
else:
self.meas_fun(circuit, qreg, op) | Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement. | codesearchnet |
def auth_user_id(self, value):
if value == self._defaults['ai.user.authUserId'] and 'ai.user.authUserId' in self._values:
del self._values['ai.user.authUserId']
else:
self._values['ai.user.authUserId'] = value | The auth_user_id property.
Args:
value (string). the property value. | juraj-google-style |
def github_belspec_files(spec_dir, force: bool = False):
if not force:
dtnow = datetime.datetime.utcnow()
delta = datetime.timedelta(1)
yesterday = dtnow - delta
for fn in glob.glob(f"{spec_dir}/bel*yaml"):
if datetime.datetime.fromtimestamp(os.path.getmtime(fn)) >... | Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old | juraj-google-style |
def DNN(input_shape,
dense_layers,
output_layer=[1, 'sigmoid'],
optimizer='adam',
loss='binary_crossentropy'):
inputs = Input(shape=input_shape)
dense = inputs
for i, d in enumerate(dense_layers):
dense = Dense(d, activation='relu')(dense)
... | Summary
Args:
input_shape (list): The shape of the input layer
targets (int): Number of targets
dense_layers (list): Dense layer descriptor [fully_connected]
optimizer (str or object optional): Keras optimizer as string or keras optimizer
Returns:
TYPE: model, build_arguments | juraj-google-style |
def _PromptUserForAPFSVolumeIdentifiers(
self, volume_system, volume_identifiers):
print_header = True
while True:
if print_header:
self._PrintAPFSVolumeIdentifiersOverview(
volume_system, volume_identifiers)
print_header = False
lines = self._textwrapper.wra... | Prompts the user to provide APFS volume identifiers.
Args:
volume_system (dfvfs.APFSVolumeSystem): volume system.
volume_identifiers (list[str]): volume identifiers including prefix.
Returns:
list[str]: selected volume identifiers including prefix or None. | juraj-google-style |
def combine_slices(self, slices, tensor_shape, device=None):
if (tensor_shape.ndims == 0):
return slices[0]
ret = slices[:]
tensor_layout = self.tensor_layout(tensor_shape)
for (mesh_dim, tensor_axis) in zip(self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
slice_size = (l... | Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor. | codesearchnet |
def chimera_anticluster(m, n=None, t=4, multiplier=3.0, cls=BinaryQuadraticModel, subgraph=None, seed=None):
if (seed is None):
seed = numpy.random.randint((2 ** 32), dtype=np.uint32)
r = numpy.random.RandomState(seed)
m = int(m)
if (n is None):
n = m
else:
n = int(n)
t =... | Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
m (int):
Number of rows in the Chimera lattice.
n (int, optional, default=m):
Number of columns in the Chimera lattice.
t (int, optional, default=t):
Size of ... | codesearchnet |
def from_coffeescript(cls, code, args={}):
compiled = nodejs_compile(code, lang='coffeescript', file='???')
if ('error' in compiled):
raise CompilationError(compiled.error)
return cls(code=compiled.code, args=args) | Create a CustomJSHover instance from a CoffeeScript snippet. The
function bodies are translated to JavaScript functions using node and
therefore require return statements.
The ``code`` snippet namespace will contain the variable ``value`` (the
untransformed value) at render time as well as ``special_vars`` and
``forma... | codesearchnet |
def _infer_device_name(self, device_name, node_name):
if device_name is None:
if node_name in self._node_devices:
if len(self._node_devices[node_name]) == 1:
return list(self._node_devices[node_name])[0]
else:
raise ValueError("There are multiple (%d) ... | Infer the device name given node name.
If device_name is provided (i.e., not None), it'll be simply returned right
away.
Args:
device_name: (str or None) name of the device. If None, will try to infer
the device name by looking at the available nodes.
node_name: (str) name of the node.
Returns:
(str) Inferred name o... | github-repos |
def find_mip(self, direction, mechanism, purview):
if not purview:
return _null_ria(direction, mechanism, purview)
repertoire = self.repertoire(direction, mechanism, purview)
def _mip(phi, partition, partitioned_repertoire):
... | Return the minimum information partition for a mechanism over a
purview.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The nodes in the mechanism.
purview (tuple[int]): The nodes in the purview.
Returns:
RepertoireIrreducibilityAnalysis: The irreducibility analysis for
the mininum-informat... | juraj-google-style |
def _lookup_key_parse(table_keys):
regex_matcher = '\\[([^\\]]+)]'
valid_dynamodb_datatypes = ['M', 'S', 'N', 'L']
clean_table_keys = []
new_keys = []
for key in table_keys:
match = re.search(regex_matcher, key)
if match:
if (match.group(1) in valid_dynamodb_datatypes):
... | Return the order in which the stacks should be executed.
Args:
dependencies (dict): a dictionary where each key should be the
fully qualified name of a stack whose value is an array of
fully qualified stack names that the stack depends on. This is
used to generate the order in which the stacks should be
executed.
Ret... | codesearchnet |
class EmbeddingTypeAdapter(Generic[EmbeddingTypeAdapterInputT, EmbeddingTypeAdapterOutputT]):
input_fn: Callable[[Sequence[EmbeddingTypeAdapterInputT]], List[str]]
output_fn: Callable[[Sequence[EmbeddingTypeAdapterInputT], Sequence[Any]], List[EmbeddingTypeAdapterOutputT]]
def __reduce__(self):
... | Adapts input types to text for embedding and converts output embeddings.
Args:
input_fn: Function to extract text for embedding from input type
output_fn: Function to create output type from input and embeddings | github-repos |
def _get_pprof_proto(self, profile_datum_generator):
pprof_profile = profile_pb2.Profile()
samples = Samples(self._string_table)
for datum in profile_datum_generator:
if not datum.traceback:
continue
stack_frame = datum.traceback[-1]
after_apply_op = False
locatio... | Returns profile data in pprof proto format.
Args:
profile_datum_generator: Generator outputting `ProfileDatum` objects.
Returns:
A proto in pprof format. | github-repos |
def _op_expand(n_bits, func=None, broadcastable=None):
if func is None:
return functools.partial(_op_expand, n_bits, broadcastable=broadcastable)
@functools.wraps(func)
def wrapper(self, *args):
params = args[0:-n_bits] if len(args) > n_bits else tuple()
rargs = args[-n_bits:]
... | Decorator for expanding an operation across a whole register or register subset.
Args:
n_bits (int): the number of register bit arguments the decorated function takes
func (function): used for decorators with keyword args
broadcastable (list(bool)): list of bool for which register args can be
broadcast from 1 bit to th... | juraj-google-style |
def render_head_repr(expr: Any, sub_render=None, key_sub_render=None) -> str:
head_repr_fmt = '{head}({args}{kwargs})'
if (sub_render is None):
sub_render = render_head_repr
if (key_sub_render is None):
key_sub_render = sub_render
if isinstance(expr.__class__, Singleton):
return ... | Render a textual representation of `expr` using
Positional and keyword arguments are recursively
rendered using `sub_render`, which defaults to `render_head_repr` by
default. If desired, a different renderer may be used for keyword
arguments by giving `key_sub_renderer`
Raises:
AttributeError: if `expr` is not an ins... | codesearchnet |
def getmtime(self, path=None, client_kwargs=None, header=None):
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | juraj-google-style |
def clean_email_or_username(self):
email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()
if (not email_or_username):
return email_or_username
email = email_or_username__to__email(email_or_username)
bulk_entry = (len(split_usernames_and_emails(email)) > 1)
if bulk_entry... | Clean email form field
Returns:
str: the cleaned value, converted to an email address (or an empty string) | codesearchnet |
def run( self, for_time=None ):
self.for_time = for_time
try:
self.is_initialised()
except AttributeError:
raise
if self.number_of_equilibration_jumps > 0:
for step in range( self.number_of_equilibration_jumps ):
self.lattice.j... | Run the simulation.
Args:
for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None.
Returns:
None | juraj-google-style |
def call(self, input_ids: Optional[tf.Tensor]=None, token_type_ids: Optional[tf.Tensor]=None, inputs_embeds: Optional[tf.Tensor]=None, training: bool=False) -> tf.Tensor:
assert not (input_ids is None and inputs_embeds is None)
if input_ids is not None:
check_embeddings_within_bounds(input_ids, self.con... | Applies embedding based on inputs tensor.
Returns:
final_embeddings (`tf.Tensor`): output embedding tensor. | github-repos |
def claim(self, unclaimed_file_readers):
claimed_vcf_readers = []
for caller in self._callers:
(unclaimed_file_readers,
translated_vcf_readers) = caller.claim(unclaimed_file_readers)
claimed_vcf_readers.extend(translated_vcf_readers)
return unclaime... | Allows each caller to claim incoming files as they are recognized.
Args:
unclaimed_file_readers: Usually, all files in the input dir.
Returns:
A tuple of unclaimed file readers and claimed VcfReaders. The
presence of any unclaimed file readers could indicate stray files
in the input dir. | juraj-google-style |
def en(item):
if pakr is None:
return msgpack.packb(item, use_bin_type=True, unicode_errors='surrogatepass')
try:
return pakr.pack(item)
except Exception:
pakr.reset()
raise | Use msgpack to serialize a compatible python object.
Args:
item (obj): The object to serialize
Notes:
String objects are encoded using utf8 encoding. In order to handle
potentially malformed input, ``unicode_errors='surrogatepass'`` is set
to allow encoding bad input strings.
Returns:
bytes: The serialized bytes in... | juraj-google-style |
def GetSoapXMLForComplexType(self, type_name, value):
element = self.schema.get_element(
'{%s}%s' % (self._namespace_override, type_name))
result_element = self._element_maker(element.qname.localname)
element_value = element(**value)
element.type.render(result_element, element_value)
da... | Return an XML string representing a SOAP complex type.
Args:
type_name: The name of the type with namespace prefix if necessary.
value: A python dictionary to hydrate the type instance with.
Returns:
A string containing the SOAP XML for the type. | juraj-google-style |
def screenshot(self):
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff) | Take screenshot with session check
Returns:
PIL.Image | codesearchnet |
def do_post(self, uri, resource, timeout, custom_headers):
self.validate_resource_uri(uri)
(task, entity) = self._connection.post(uri, resource, custom_headers=custom_headers)
if (not task):
return entity
return self._task_monitor.wait_for_task(task, timeout) | Helps to make post requests.
Args:
uri: URI of the resource.
resource: Resource data to post.
timeout: Time out for the request in seconds.
cutom_headers: Allows to add custom http headers.
Returns:
Retunrs Task object. | codesearchnet |
def get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None):
if (hparams.recurrence_type == 'basic'):
ut_initializer = (x, x, x)
ut_function = functools.partial(universal_transformer_basic, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit)
elif (hparams.recurrence_t... | Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
ut_function and the ut_initializer
Raises:
ValueError... | codesearchnet |
def patch_on_member(src: symbolic.Symbolic, cls: Union[Type[Any], Tuple[Type[Any], ...]], name: str, value: Any=None, value_fn: Optional[Callable[[Any], Any]]=None, skip_notification: Optional[bool]=None) -> Any:
return _conditional_patch(src, lambda k, v, p: isinstance(p, cls) and k.key == name, value, value_fn, s... | Recursively patch values that are the requested member of classes.
Example::
d = pg.Dict(a=A(x=1), b=2)
print(pg.patching.patch_on_member(d, A, 'x', 2)
# {a=A(x=2), b=4}
Args:
src: symbolic value to patch.
cls: In which class the member belongs to.
name: Member name.
value: New value for field that satisfy `conditio... | github-repos |
def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT):
try:
dim = self._read_dimensions(dimname, path=path)[0]
return len(dim)
except self.Error:
if default is NO_DEFAULT: raise
return default | Returns the value of a dimension.
Args:
dimname: Name of the variable
path: path to the group.
default: return `default` if `dimname` is not present and
`default` is not `NO_DEFAULT` else raise self.Error. | juraj-google-style |
def get_num_filters(layer):
if K.ndim(layer.output) == 2:
return K.int_shape(layer.output)[-1]
channel_idx = 1 if K.image_data_format() == 'channels_first' else -1
return K.int_shape(layer.output)[channel_idx] | Determines the number of filters within the given `layer`.
Args:
layer: The keras layer to use.
Returns:
Total number of filters within `layer`.
For `keras.layers.Dense` layer, this is the total number of outputs. | juraj-google-style |
def get_element_dt(self, el_name, tz=None, el_idx=0):
return iso8601.parse_date(self.get_element_by_name(el_name, el_idx).text, tz) | Return the text of the selected element as a ``datetime.datetime`` object.
The element text must be a ISO8601 formatted datetime
Args:
el_name : str
Name of element to use.
tz : datetime.tzinfo
Timezone in which to return the datetime.
- Without a timezone, other contextual information is required in order to
deter... | codesearchnet |
def read_nanopubs(fn: str) -> Iterable[Mapping[(str, Any)]]:
(jsonl_flag, json_flag, yaml_flag) = (False, False, False)
if ((fn == '-') or ('jsonl' in fn)):
jsonl_flag = True
elif ('json' in fn):
json_flag = True
elif re.search('ya?ml', fn):
yaml_flag = True
else:
log... | Read file and generate nanopubs
If filename has *.gz, will read as a gzip file
If filename has *.jsonl*, will parsed as a JSONLines file
IF filename has *.json*, will be parsed as a JSON file
If filename has *.yaml* or *.yml*, will be parsed as a YAML file
Args:
filename (str): filename to read nanopubs from
Return... | codesearchnet |
def updateGroup(self, group, vendorSpecific=None):
response = self.updateGroupResponse(group, vendorSpecific)
return self._read_boolean_response(response) | See Also: updateGroupResponse()
Args:
group:
vendorSpecific:
Returns: | juraj-google-style |
def get_showcases(self):
(assoc_result, showcases_dicts) = self._read_from_hdx('showcase', self.data['id'], fieldname='package_id', action=hdx.data.showcase.Showcase.actions()['list_showcases'])
showcases = list()
if assoc_result:
for showcase_dict in showcases_dicts:
showcase = hdx.data... | Get any showcases the dataset is in
Returns:
List[Showcase]: list of showcases | codesearchnet |
def has_file_with_suffix(self, suffixes):
if not isinstance(suffixes, list):
suffixes = [suffixes]
if self.handle:
for member in self.handle.getmembers():
if os.path.splitext(member.name)[1] in suffixes:
return True
el... | Finds out if there is a file with one of suffixes in the archive.
Args:
suffixes: list of suffixes or single suffix to look for
Returns:
True if there is at least one file with at least one given suffix
in the archive, False otherwise (or archive can't be opened) | juraj-google-style |
def all(self, data={}, **kwargs):
return super(Plan, self).all(data, **kwargs) | Fetch all plan entities
Returns:
Dictionary of plan data | codesearchnet |
def _ParseProcessingOptions(self, options):
self._single_process_mode = getattr(options, 'single_process', False)
argument_helper_names = [
'process_resources', 'temporary_directory', 'workers', 'zeromq']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument... | Parses the processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.