code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def write_json(self, fh, pretty=True):
sjson = json.JSONEncoder().encode(self.json())
if pretty:
json.dump(json.loads(sjson), fh, sort_keys=True, indent=4)
else:
json.dump(json.loads(sjson), fh)
return | Write composite object to file handle in JSON format.
Args:
fh (file): File handle to write to.
pretty (bool): Sort keys and indent in output. | codesearchnet |
def summary_writer_function(name, tensor, function, family=None):
name_scope = ops.get_name_scope()
if name_scope:
name_scope += '/'
def record():
with ops.name_scope(name_scope), summary_op_util.summary_scope(name, family, values=[tensor]) as (tag, scope):
with ops.control_depe... | Helper function to write summaries.
Args:
name: name of the summary
tensor: main tensor to form the summary
function: function taking a tag and a scope which writes the summary
family: optional, the summary's family
Returns:
The result of writing the summary. | github-repos |
def transform_rest_response(self, response_body):
body_json = json.loads(response_body)
return json.dumps(body_json, indent=1, sort_keys=True) | Translates an apiserving REST response so it's ready to return.
Currently, the only thing that needs to be fixed here is indentation,
so it's consistent with what the live app will return.
Args:
response_body: A string containing the backend response.
Returns:
A reformatted version of the response JSON. | codesearchnet |
def check_constraint(type_constraint, object_instance):
if type_constraint is None and object_instance is None:
return
elif isinstance(type_constraint, TypeConstraint):
type_constraint.type_check(object_instance)
elif type_constraint is None:
pass
elif not isinstance(type_constra... | Determine if the passed type instance satisfies the TypeConstraint.
When examining a candidate type for constraint satisfaction in
'type_check', all CompositeTypeHint's eventually call this function. This
function may end up being called recursively if the hinted type of a
CompositeTypeHint is another CompositeTypeHin... | github-repos |
def _deconstruct_single_qubit_matrix_into_gate_turns(
mat: np.ndarray) -> Tuple[float, float, float]:
pre_phase, rotation, post_phase = (
linalg.deconstruct_single_qubit_matrix_into_angles(mat))
tau = 2 * np.pi
xy_turn = rotation / tau
xy_phase_turn = 0.25 - pre_phase / tau
... | Breaks down a 2x2 unitary into gate parameters.
Args:
mat: The 2x2 unitary matrix to break down.
Returns:
A tuple containing the amount to rotate around an XY axis, the phase of
that axis, and the amount to phase around Z. All results will be in
fractions of a whole turn, with values canonicalized into the range
[-0.... | juraj-google-style |
def parse_filepath(self, filepath=None):
filepath = (filepath or self._default_filename)
(path, filename) = os.path.split(filepath)
if (not path):
path = self.basedir
elif (not os.path.isabs(path)):
path = os.path.join(self.basedir, path)
return (os.path.normpath(path), filename) | Parse given filepath to split possible path directory from filename.
* If path directory is empty, will use ``basedir`` attribute as base
filepath;
* If path directory is absolute, ignore ``basedir`` attribute;
* If path directory is relative, join it to ``basedir`` attribute;
Keyword Arguments:
filepath (str): Filep... | codesearchnet |
def get_conflicting_tools(self, request_only=False):
from collections import defaultdict
tool_sets = defaultdict(set)
tools_dict = self.get_tools(request_only=request_only)
for variant, tools in tools_dict.itervalues():
for tool in tools:
tool_sets[t... | Returns tools of the same name provided by more than one package.
Args:
request_only: If True, only return the key from resolved packages
that were also present in the request.
Returns:
Dict of {tool-name: set([Variant])}. | juraj-google-style |
def _list_samples(self, predicate=None):
cursor = self.database[self.sample_collection].find(predicate, {'_id': 0, 'md5': 1})
return [item['md5'] for item in cursor] | List all samples that meet the predicate or all if predicate is not specified.
Args:
predicate: Match samples against this predicate (or all if not specified)
Returns:
List of the md5s for the matching samples | codesearchnet |
def InitFromAff4Object(self, file_obj, stat_entry=None, hash_entry=None, with_details=False):
self.name = file_obj.urn.Basename()
self.path = '/'.join(file_obj.urn.Path().split('/')[2:])
self.is_directory = ('Container' in file_obj.behaviours)
self.stat = (stat_entry or file_obj.Get(file_obj.Schema.STAT... | Initializes the current instance from an Aff4Stream.
Args:
file_obj: An Aff4Stream representing a file.
stat_entry: An optional stat entry object to be used. If none is provided,
the one stored in the AFF4 data store is used.
hash_entry: An optional hash entry object to be used. If none is provided,
the one stored in ... | codesearchnet |
def __init__( self, label, r ):
self.label = label
self.r = r | Initialise an Atom instance
Args:
label (Str): a label for this atom
r (numpy.array): the atom coordinates
Returns:
None | juraj-google-style |
def __init__(self, optimizer, scope=None, summary_labels=(), **kwargs):
self.tf_optimizer_type = optimizer
self.tf_optimizer = TFOptimizer.tf_optimizers[optimizer](**kwargs)
super(TFOptimizer, self).__init__(scope=(scope or optimizer), summary_labels=summary_labels) | Creates a new optimizer instance of a TensorFlow optimizer.
Args:
optimizer: The name of the optimizer. Must be one of the keys of the tf_optimizers dict.
**kwargs: Arguments passed on to the TensorFlow optimizer constructor as **kwargs. | juraj-google-style |
def choose(self, locator=None, allow_label_click=None, **kwargs):
self._check_with_label(
"radio_button", True, locator=locator, allow_label_click=allow_label_click, **kwargs) | Find a radio button and mark it as checked. The radio button can be found via name, id, or
label text. ::
page.choose("Male")
Args:
locator (str, optional): Which radio button to choose.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capyba... | juraj-google-style |
def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)
... | Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_spe... | github-repos |
def forward(self, hidden_features):
hidden_features = self.flatten(hidden_features)
hidden_features = self.dropout_layer(hidden_features)
forecast = self.base_forecast_block(hidden_features)
if isinstance(forecast, tuple):
forecast = tuple((z.transpose(-1, -2) for z in forecast))
else:
... | Args:
hidden_features (`torch.Tensor` of shape `(batch_size, num_patch, d_model)` in `flatten` mode
or `(batch_size, n_vars, num_patch, d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
features.
Returns:
`torch.Tensor` of shape `(batch_size, prediction_length, nvars)`. | github-repos |
def parse(ifp, pb_cls, **kwargs):
mode = 'rb'
if isinstance(ifp, str):
istream = open(ifp, mode=mode, **kwargs)
else:
istream = open(fileobj=ifp, mode=mode, **kwargs)
with istream:
for data in istream:
pb_obj = pb_cls()
pb_obj.ParseFromString(data)
... | Parse a stream.
Args:
ifp (string or file-like object): input stream.
pb_cls (protobuf.message.Message.__class__): The class object of
the protobuf message type encoded in the stream. | codesearchnet |
def _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t):
(s_val, t_val) = _intersection_helpers.newton_refine(s_val, nodes1, t_val, nodes2)
(s_val, success_s) = _helpers.wiggle_interval(s_val)
(t_val, success_t) = _helpers.wiggle_interval(t_val)
if (not (success_s and success_t)):
r... | Resolve a computed intersection and add to lists.
We perform one Newton step to deal with any residual issues of
high-degree polynomial solves (one of which depends on the already
approximate ``x_val, y_val``).
Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
s_val (float): The approximate intersection par... | codesearchnet |
def _create_3d_attention_mask_from_input_mask(self, from_tensor, to_mask):
batch_size, from_seq_length = (from_tensor.shape[0], from_tensor.shape[1])
to_seq_length = to_mask.shape[1]
to_mask = torch.reshape(to_mask, (batch_size, 1, to_seq_length)).float()
broadcast_ones = torch.ones(size=(batch_size, fr... | Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_length, to_seq_length]. | github-repos |
def register_from_fields(self, *args):
names = []
for field in args:
widget = self.resolve_widget(field)
self.register(widget.config_name)
if (widget.config_name not in names):
names.append(widget.config_name)
return names | Register config name from field widgets
Arguments:
*args: Fields that contains widget
:class:`djangocodemirror.widget.CodeMirrorWidget`.
Returns:
list: List of registered config names from fields. | codesearchnet |
def AppendPathEntries(cls, path, path_separator, number_of_wildcards, skip_first):
if (path[(- 1)] == path_separator):
path = path[:(- 1)]
if skip_first:
path = ''.join([path, path_separator, '*'])
number_of_wildcards -= 1
paths = []
for _ in range(0, number_of_wildcards):
... | Appends glob wildcards to a path.
This function will append glob wildcards "*" to a path, returning paths
with an additional glob wildcard up to the specified number. E.g. given
the path "/tmp" and a number of 2 wildcards, this function will return
"tmp/*", "tmp/*/*". When skip_first is true the path with the first
wi... | codesearchnet |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(local_stream, kmip_version=kmip_version)
if self._lease_time:
self._lease_time.write(local_stream, kmip_version=kmip_versi... | Write the data encoding the ObtainLease response payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Opti... | codesearchnet |
def _fill_meta_graph_def(meta_graph_def: meta_graph_pb2.MetaGraphDef, saveable_view: _SaveableView, signature_functions: Dict[str, Callable[..., Any]], namespace_whitelist: List[str], save_custom_gradients: bool, create_saver: bool, enable_debug_stripper: bool, defaults=None) -> Tuple[_AssetInfo, ops.Graph]:
resour... | Generates a MetaGraph which calls `signature_functions`.
Args:
meta_graph_def: The MetaGraphDef proto to fill.
saveable_view: The _SaveableView being exported.
signature_functions: A dictionary mapping signature keys to concrete
functions containing signatures to add to the MetaGraph.
namespace_whitelist: List of stri... | github-repos |
def get_run_short_description(run_call_count, fetches, feed_dict, is_callable_runner=False):
if is_callable_runner:
return 'runner from make_callable()'
description = 'run
if isinstance(fetches, (tensor_lib.Tensor, ops.Operation, variables.Variable)):
description += '1 fetch (%s); ' % commo... | Get a short description of the run() call.
Args:
run_call_count: (int) Run call counter.
fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
for more details.
feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
for more details.
is_callable_runner: (bool) whether a runner retu... | github-repos |
def assert_equal_graph_def_v2(expected: graph_pb2.GraphDef, actual: graph_pb2.GraphDef) -> None:
assert_equal_graph_def(actual, expected, checkpoint_v2=True, hash_table_shared_name=True) | Asserts that two `GraphDef`s are (mostly) the same.
Compares two `GraphDef` protos for equality, ignoring versions and ordering of
nodes, attrs, and control inputs. Node names are used to match up nodes
between the graphs, so the naming of nodes must be consistent. This function
ignores randomized attribute values th... | github-repos |
def from_directory(input_dir, optional_files=None):
sub_d = {}
for fname, ftype in [("INCAR", Incar), ("KPOINTS", Kpoints),
("POSCAR", Poscar), ("POTCAR", Potcar)]:
fullzpath = zpath(os.path.join(input_dir, fname))
sub_d[fname.lower()] = ftyp... | Read in a set of VASP input from a directory. Note that only the
standard INCAR, POSCAR, POTCAR and KPOINTS files are read unless
optional_filenames is specified.
Args:
input_dir (str): Directory to read VASP input from.
optional_files (dict): Optional files to read in as well as a
dict of {filename: Object type}. Obj... | juraj-google-style |
def is_user_enrolled(cls, user, course_id, course_mode):
enrollment_client = EnrollmentApiClient()
try:
enrollments = enrollment_client.get_course_enrollment(user.username, course_id)
if enrollments and course_mode == enrollments.get('mode'):
return True
... | Query the enrollment API and determine if a learner is enrolled in a given course run track.
Args:
user: The user whose enrollment needs to be checked
course_mode: The mode with which the enrollment should be checked
course_id: course id of the course where enrollment should be checked.
Returns:
Boolean: Whether or n... | juraj-google-style |
def _error_messages(self, driver_id):
assert isinstance(driver_id, ray.DriverID)
message = self.redis_client.execute_command('RAY.TABLE_LOOKUP', ray.gcs_utils.TablePrefix.ERROR_INFO, '', driver_id.binary())
if (message is None):
return []
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTab... | Get the error messages for a specific driver.
Args:
driver_id: The ID of the driver to get the errors for.
Returns:
A list of the error messages for this driver. | codesearchnet |
def _ReadN(self, n):
ret = ''
while True:
chunk = self._read_file.read((n - len(ret)))
ret += chunk
if ((len(ret) == n) or (not chunk)):
return ret | Reads n characters from the input stream, or until EOF.
This is equivalent to the current CPython implementation of read(n), but
not guaranteed by the docs.
Args:
n: int
Returns:
string | codesearchnet |
def recompose(src: Path, target_file: Path):
mission_folder, assets_folder = NewMiz._get_subfolders(src)
base_info = ujson.loads(Path(mission_folder, 'base_info.json').read_text(encoding=ENCODING))
version = base_info['__version__']
with Miz(target_file) as miz:
... | Recompose a Miz from json object
Args:
src: folder containing the json structure
target_file: target Miz file | juraj-google-style |
def get_value_spec(self, name: str) -> Optional[class_schema.ValueSpec]:
for arg in self.named_args:
if arg.name == name:
return arg.value_spec
if self.varkw is not None:
return self.varkw.value_spec.schema.dynamic_field.value
return None | Returns Value spec for an argument name.
Args:
name: Argument name.
Returns:
ValueSpec for the requested argument. If name is not found, value spec of
wildcard keyword argument will be used. None will be returned if name
does not exist in signature and wildcard keyword is not accepted. | github-repos |
def subtract_business_days(self, date_tensor, num_days, roll_convention=constants.BusinessDayConvention.NONE):
return self.add_business_days(date_tensor, -num_days, roll_convention) | Adds given number of business days to given dates.
Note that this is different from calling `subtract_period_and_roll` with
PeriodType.DAY. For example, subtracting 5 business days from Friday gives
the previous Friday (unless there are holidays on this week or previous
Friday). Subtracting 5 days and rolling means la... | github-repos |
def add_citations(voevent, event_ivorns):
if (not voevent.xpath('Citations')):
etree.SubElement(voevent, 'Citations')
voevent.Citations.extend(_listify(event_ivorns)) | Add citations to other voevents.
The schema mandates that the 'Citations' section must either be entirely
absent, or non-empty - hence we require this wrapper function for its
creation prior to listing the first citation.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
event_ivorns (:class:`voeventpars... | codesearchnet |
def _CopyDateFromString(self, date_string):
date_string_length = len(date_string)
if date_string_length < 10:
raise ValueError('Date string too short.')
if date_string[4] != '-' or date_string[7] != '-':
raise ValueError('Invalid date string.')
try:
year = int(date_string[... | Copies a date from a string.
Args:
date_string (str): date value formatted as: YYYY-MM-DD
Returns:
tuple[int, int, int]: year, month, day of month.
Raises:
ValueError: if the date string is invalid or not supported. | juraj-google-style |
def equal_distribution_folds(y, folds=2):
(n, classes) = y.shape
dist = y.sum(axis=0).astype('float')
dist /= dist.sum()
index_list = []
fold_dist = np.zeros((folds, classes), dtype='float')
for _ in range(folds):
index_list.append([])
for i in range(n):
if (i < folds):
... | Creates `folds` number of indices that has roughly balanced multi-label distribution.
Args:
y: The multi-label outputs.
folds: The number of folds to create.
Returns:
`folds` number of indices that have roughly equal multi-label distributions. | codesearchnet |
def to_json(self, **kwargs):
config = self.get_config()
timeseries_generator_config = {'class_name': self.__class__.__name__, 'config': config}
return json.dumps(timeseries_generator_config, **kwargs) | Returns a JSON string containing the generator's configuration.
Args:
**kwargs: Additional keyword arguments to be passed
to `json.dumps()`.
Returns:
A JSON string containing the tokenizer configuration. | github-repos |
def _process_sum_prod(self, func, **kwargs):
axis = kwargs.get('axis', 0)
min_count = kwargs.get('min_count', 0)
def sum_prod_builder(df, **kwargs):
return func(df, **kwargs)
if (min_count <= 1):
return self._full_reduce(axis, sum_prod_builder)
else:
return self._full_axis_r... | Calculates the sum or product of the DataFrame.
Args:
func: Pandas func to apply to DataFrame.
ignore_axis: Whether to ignore axis when raising TypeError
Return:
A new QueryCompiler object with sum or prod of the object. | codesearchnet |
def start(logdir):
if logdir.startswith('gs:
datalab.storage._api.Api.verify_permitted_to_read(logdir)
port = datalab.utils.pick_unused_port()
args = ['tensorboard', ('--logdir=' + logdir), ('--port=' + str(port))]
p = subprocess.Popen(args)
retry = 10
while (retry > 0):
if datal... | Start a TensorBoard instance.
Args:
logdir: the logdir to run TensorBoard on.
Raises:
Exception if the instance cannot be started. | codesearchnet |
def _compile_function_expression(self, expr: Expression, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[List[tf.Tensor]]=None) -> TensorFluent:
etype = expr.etype
args = expr.args
if (len(args) == 1):
etype2func = {'abs': TensorFluent.abs, 'exp': TensorFluent.exp, ... | Compile a function expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL function expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.fl... | codesearchnet |
def fixminimized(self, alphabet):
endstate = len(list(self.states))
for state in self.states:
for char in alphabet:
found = 0
for arc in state.arcs:
if self.isyms.find(arc.ilabel) == char:
found = 1
... | After pyfst minimization,
all unused arcs are removed,
and all sink states are removed.
However this may break compatibility.
Args:
alphabet (list): The input alphabet
Returns:
None | juraj-google-style |
def users_lookupByEmail(self, *, email: str, **kwargs) -> SlackResponse:
kwargs.update({"email": email})
return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs) | Find a user with an email address.
Args:
email (str): An email address belonging to a user in the workspace.
e.g. 'spengler@ghostbusters.example.com' | juraj-google-style |
def sg_mean(tensor, opt):
r
return tf.reduce_mean(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | r"""Computes the mean of elements across axis of a tensor.
See `tf.reduce_mean()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with length 1.
name: If provided, replace cur... | juraj-google-style |
def safe_sum(x, alt_value=(- np.inf), name=None):
with tf.compat.v1.name_scope(name, 'safe_sum', [x, alt_value]):
if (not is_list_like(x)):
raise TypeError('Expected list input.')
if (not x):
raise ValueError('Input should not be empty.')
in_shape = x[0].shape
... | Elementwise adds list members, replacing non-finite results with alt_value.
Typically the `alt_value` is chosen so the `MetropolisHastings`
`TransitionKernel` always rejects the proposal.
Args:
x: Python `list` of `Tensors` to elementwise add.
alt_value: Python scalar used to replace any elementwise sums which would
... | codesearchnet |
def _GetTaskStorageFilePath(self, task):
filename = '{0:s}.plaso'.format(task.identifier)
return os.path.join(self._task_storage_path, filename) | Retrieves the path of a task storage file in the temporary directory.
Args:
task (Task): task.
Returns:
str: path of a task storage file in the temporary directory. | juraj-google-style |
def get_column_names(self, X):
if isinstance(X, pd.DataFrame):
return X.columns
return range(X.shape[1]) | Return iterable containing columns for the given array X.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
iterable: columns for the given matrix. | codesearchnet |
def garbage_collect_exports(export_dir_base, exports_to_keep):
if (exports_to_keep is None):
return
version_paths = []
for filename in tf_v1.gfile.ListDirectory(export_dir_base):
path = os.path.join(tf.compat.as_bytes(export_dir_base), tf.compat.as_bytes(filename))
if ((len(filename)... | Deletes older exports, retaining only a given number of the most recent.
Export subdirectories are assumed to be named with monotonically increasing
integers; the most recent are taken to be those with the largest values.
Args:
export_dir_base: the base directory under which each export is in a
versioned subdirectory... | codesearchnet |
def exists(path):
filesystem = FileSystems.get_filesystem(path)
return filesystem.exists(path) | Check if the provided path exists on the FileSystem.
Args:
path: string path that needs to be checked.
Returns: boolean flag indicating if path exists | github-repos |
def limit(self, accountID, **kwargs):
return self.create(accountID, order=LimitOrderRequest(**kwargs)) | Shortcut to create a Limit Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a LimitOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | codesearchnet |
def Parse(text):
precondition.AssertType(text, Text)
if compatibility.PY2:
text = text.encode("utf-8")
return yaml.safe_load(text) | Parses a YAML source into a Python object.
Args:
text: A YAML source to parse.
Returns:
A Python data structure corresponding to the YAML source. | juraj-google-style |
def verify(self, obj):
if self.encoding == 'none' and not isinstance(obj, (bytes, bytearray)):
raise ValidationError('Byte object was not either bytes or a bytearray', type=obj.__class__.__name__)
elif self.encoding == 'base64':
try:
data = base64.b64dec... | Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Returns:
bytes or byterray: The decoded byte buffer
Raises:
ValidationError: If there is a problem verifying the object, a
ValidationError is thrown with at least the reason key set indicating
the reason for the l... | juraj-google-style |
def extract_class(jar, name):
with jar.open(name) as entry:
return LinkableClass(javatools.unpack_class(entry)) | Extracts a LinkableClass from a jar.
Args:
jar: An open ZipFile instance.
name: A string containing the binary name of a class.
Raises:
KeyError: The class does not exist in the jar. | juraj-google-style |
def save(self, path=None, complevel=1, complib='zlib'):
if (path is None):
path = (self.hexuid + '.hdf5')
elif os.path.isdir(path):
path += ((os.sep + self.hexuid) + '.hdf5')
elif (not (path.endswith('.hdf5') or path.endswith('.hdf'))):
raise ValueError('File path must have a ".hdf5"... | Save the container as an HDF5 archive.
Args:
path (str): Path where to save the container | codesearchnet |
def write_jsonl_file(fname, data):
if (not isinstance(data, list)):
print('warning: malformed json data for file', fname)
return
with open(fname, 'w') as of:
for row in data:
if row.strip():
of.write(('%s\n' % row.strip())) | Writes a jsonl file.
Args:
data: list of json encoded data | codesearchnet |
def get_pointgroup(self, tolerance=0.3):
PA = self._get_point_group_analyzer(tolerance=tolerance)
return PointGroupOperations(PA.sch_symbol, PA.symmops) | Returns a PointGroup object for the molecule.
Args:
tolerance (float): Tolerance to generate the full set of symmetry
operations.
Returns:
:class:`~PointGroupOperations` | codesearchnet |
def __init__(self, idx):
self.idx = idx
self.in_edges = []
self.out_edges = [] | Initialize the Vertex.
Args:
idx: The index of the vertex. | juraj-google-style |
def bounding_box_from(points, i, i1, thr):
pi = points[i]
pi1 = points[i1]
min_lat = min(pi.lat, pi1.lat)
min_lon = min(pi.lon, pi1.lon)
max_lat = max(pi.lat, pi1.lat)
max_lon = max(pi.lon, pi1.lon)
return min_lat-thr, min_lon-thr, max_lat+thr, max_lon+thr | Creates bounding box for a line segment
Args:
points (:obj:`list` of :obj:`Point`)
i (int): Line segment start, index in points array
i1 (int): Line segment end, index in points array
Returns:
(float, float, float, float): with bounding box min x, min y, max x and max y | juraj-google-style |
def start_worker(node_ip_address, object_store_name, raylet_name, redis_address, worker_path, temp_dir, stdout_file=None, stderr_file=None):
command = [sys.executable, '-u', worker_path, ('--node-ip-address=' + node_ip_address), ('--object-store-name=' + object_store_name), ('--raylet-name=' + raylet_name), ('--red... | This method starts a worker process.
Args:
node_ip_address (str): The IP address of the node that this worker is
running on.
object_store_name (str): The socket name of the object store.
raylet_name (str): The socket name of the raylet server.
redis_address (str): The address that the Redis server is listening on.
wor... | codesearchnet |
def run(command, num_retries=1, timeout=(- 1), **kwargs):
last_error = None
for _ in range(num_retries):
try:
process = Subprocess(command, **kwargs)
return process.run(timeout)
except Exception as err:
last_error = err
raise last_error | Run a command with optional timeout and retries.
Provides a convenience method for executing a subprocess with
additional error handling.
Arguments:
command (list of str): The command to execute.
num_retries (int, optional): If the subprocess fails, the number of
attempts to execute it before failing.
timeout (float,... | codesearchnet |
def monitoring(line, cell=None):
parser = datalab.utils.commands.CommandParser(prog='monitoring', description='Execute various Monitoring-related operations. Use "%monitoring <command> -h" for help on a specific command.')
list_parser = parser.subcommand('list', 'List the metrics or resource types in a monitore... | Implements the monitoring cell magic for ipython notebooks.
Args:
line: the contents of the storage line.
Returns:
The results of executing the cell. | codesearchnet |
def int64_gauge(urn, metric, ptransform=None) -> metrics_pb2.MonitoringInfo:
labels = create_labels(ptransform=ptransform)
if isinstance(metric, int):
value = metric
time_ms = int(time.time()) * 1000
else:
raise TypeError('Expected int metric type but received %s with value %s' % (ty... | Return the gauge monitoring info for the URN, metric and labels.
Args:
urn: The URN of the monitoring info/metric.
metric: An int representing the value. The current time will be used for
the timestamp.
ptransform: The ptransform id used as a label. | github-repos |
def _call_concrete_function(function, inputs):
expected_structure = function.graph.structured_input_signature
flatten_inputs = nest.flatten_up_to(expected_structure, inputs, expand_composites=True)
flatten_expected = nest.flatten(expected_structure, expand_composites=True)
tensor_inputs = []
for arg... | Calls a restored Function with structured inputs.
This differs from `function.__call__` in that inputs and outputs are
structured and that it casts inputs to tensors if needed.
Note: this does not checks that non-tensor inputs match. That should be
done before via `_concrete_function_callable_with`.
Args:
function: ... | github-repos |
def method_not_allowed(cls, errors=None):
if cls.expose_status:
cls.response.content_type = 'application/json'
cls.response._status_line = '405 Method Not Allowed'
return cls(405, None, errors).to_json | Shortcut API for HTTP 405 `Method not allowed` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. | juraj-google-style |
def most_frequent(self, k):
word_count = {w:self.word_count[w] for w in self.words[:k]}
return CountedVocabulary(word_count=word_count) | Returns a vocabulary with the most frequent `k` words.
Args:
k (integer): specifies the top k most frequent words to be returned. | juraj-google-style |
def get_cached_filename(self, filename, extention, settings_list=None):
cached_name = "_".join([filename, self.get_hash()])
return ".".join([cached_name, extention]) | Creates a filename with md5 cache string based on settings list
Args:
filename (str): the filename without extention
extention (str): the file extention without dot. (i.e. 'pkl')
settings_list (dict|list): the settings list as list (optional)
NB! The dictionaries have to be sorted or hash id will change
arbitrarely. | juraj-google-style |
def _log_band_gap_information(bs):
bg_data = bs.get_band_gap()
if (not bg_data['direct']):
logging.info('Indirect band gap: {:.3f} eV'.format(bg_data['energy']))
direct_data = bs.get_direct_band_gap_dict()
if bs.is_spin_polarized:
direct_bg = min((spin_data['value'] for spin_data in dire... | Log data about the direct and indirect band gaps.
Args:
bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): | codesearchnet |
def install(self, connection, partition, table_name=None, columns=None, materialize=False, logger=None):
partition.localize()
self._add_partition(connection, partition)
fdw_table = partition.vid
view_table = '{}_v'.format(fdw_table)
if materialize:
with connection.cursor() as cursor:
... | Creates FDW or materialize view for given partition.
Args:
connection: connection to postgresql
partition (orm.Partition):
materialize (boolean): if True, create read-only table. If False create virtual table.
Returns:
str: name of the created table. | codesearchnet |
def linear_interpolate(tensor1, tensor2, coeffs):
interp_tensors = []
for coeff in coeffs:
interp_tensor = tensor1 + coeff * (tensor2 - tensor1)
interp_tensors.append(interp_tensor)
return tf.concat(interp_tensors, axis=0) | Linearly interpolate between two tensors at coeff.
Args:
tensor1: 4-D Tensor, shape=(NHWC)
tensor2: 4-D Tensor, shape=(NHWC)
coeffs: list of floats.
Returns:
interp_latents: 5-D Tensor, with interp_latents[i] representing
interpolations at coeffs[i].
shape=(len(coeffs), NHWC) | juraj-google-style |
def CheckAltTokens(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if Match('^\\s*
return
if ((line.find('') >= 0)):
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2, ('Use operator ... | Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | codesearchnet |
def remove(path):
if os.path.isdir(path):
return __rmtree(path)
else:
return __rmfile(path) | Delete a file or directory.
Args:
path (str): Path to the file or directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | juraj-google-style |
def parse(self, **global_args):
if (self.build_file not in ParseContext._parsed):
butcher_context = {}
for str_to_exec in self._strs_to_exec:
ast = compile(str_to_exec, '<string>', 'exec')
exec_function(ast, butcher_context)
with ParseContext.activate(self):
... | Entry point to parsing a BUILD file.
Args:
**global_args: Variables to include in the parsing environment. | codesearchnet |
def variable_type(self, variable):
var_type = 'String'
if (variable is not None):
variable = variable.strip()
if re.match(self._variable_match, variable):
var_type = re.search(self._variable_parse, variable).group(4)
return var_type | Get the Type from the variable string or default to String type.
The default type is "String" for those cases when the input variable is
contains not "DB variable" and is just a String.
**Example Variable**::
#App:1234:output!StringArray returns **StringArray**
**Example String**::
"My Data" returns **String**
Ar... | codesearchnet |
def FillDepressions(dem, epsilon=False, in_place=False, topology='D8'):
if (type(dem) is not rdarray):
raise Exception('A richdem.rdarray or numpy.ndarray is required!')
if (topology not in ['D8', 'D4']):
raise Exception('Unknown topology!')
if (not in_place):
dem = dem.copy()
_A... | Fills all depressions in a DEM.
Args:
dem (rdarray): An elevation model
epsilon (float): If True, an epsilon gradient is imposed to all flat regions.
This ensures that there is always a local gradient.
in_place (bool): If True, the DEM is modified in place and there is
no return; otherwise, a new, altered DEM ... | codesearchnet |
def getHeaders(self):
headers = self._impl.getHeaders()
return tuple((headers.getIndex(i) for i in range(self._impl.getNumCols()))) | Get the headers of this DataFrame.
Returns:
The headers of this DataFrame. | codesearchnet |
def PyParseRangeCheck(lower_bound, upper_bound):
def CheckRange(string, location, tokens):
try:
check_number = tokens[0]
except IndexError:
check_number = -1
if check_number < lower_bound:
raise pyparsing.ParseException(
'Value: {0:d} precedes lower bound: {1:d}'.fo... | Verify that a number is within a defined range.
This is a callback method for pyparsing setParseAction
that verifies that a read number is within a certain range.
To use this method it needs to be defined as a callback method
in setParseAction with the upper and lower bound set as parameters.
Args:
lower_bound (int)... | juraj-google-style |
def _rolling_window(self, window_length, func1d, step=1, return_rolled=False):
if window_length % 2 == 0:
window_length += 1
shape = self.shape[:-1] + (self.shape[-1], window_length)
strides = self.strides + (step*self.strides[-1],)
data = np.nan_to_num(sel... | Private function. Smoother for other smoothing/conditioning functions.
Args:
window_length (int): the window length.
func1d (function): a function that takes a 1D array and returns a
scalar.
step (int): if you want to skip samples in the shifted versions.
Don't use this for smoothing, you will get strange results.
Re... | juraj-google-style |
def project_group_token(self, group_tokens: tf.Tensor) -> tf.Tensor:
projected_group_tokens = self.mlp_inter(group_tokens)
projected_group_tokens = self.norm_post_tokens(projected_group_tokens)
return projected_group_tokens | Args:
group_tokens (tf.Tensor): group tokens, [batch_size, num_group_tokens, channels]
Returns:
projected_group_tokens (tf.Tensor): [batch_size, num_output_groups, channels] | github-repos |
def parseSemver(text):
txt = text.strip().lstrip('vV')
ret = {}
m = semver_re.match(txt)
if (not m):
return None
d = m.groupdict()
ret['major'] = int(d.get('maj'))
ret['minor'] = int(d.get('min'))
ret['patch'] = int(d.get('pat'))
pre = d.get('pre')
bld = d.get('bld')
... | Parse a Semantic Version string into is component parts.
Args:
text (str): A text string to parse into semver components. This string has whitespace and leading 'v'
characters stripped off of it.
Examples:
Parse a string into it semvar parts::
parts = parseSemver('v1.2.3')
Returns:
dict: The dictionary will contain... | codesearchnet |
def get_execution_role(sagemaker_session=None):
if not sagemaker_session:
sagemaker_session = Session()
arn = sagemaker_session.get_caller_identity_arn()
if ':role/' in arn:
return arn
message = 'The current AWS identity is not a role: {}, therefore it cannot be used as a SageMaker... | Return the role ARN whose credentials are used to call the API.
Throws an exception if
Args:
sagemaker_session(Session): Current sagemaker session
Returns:
(str): The role ARN | juraj-google-style |
def createEditor(self, parent, option, index):
editor = QtGui.QLineEdit(parent)
return editor | Returns the widget used to edit the item specified by index for editing. The parent widget and style option are used to control how the editor widget appears.
Args:
parent (QWidget): parent widget.
option (QStyleOptionViewItem): controls how editor widget appears.
index (QModelIndex): model data index. | juraj-google-style |
def validator(sample: rd.RepresentativeSample) -> rd.RepresentativeSample:
if not isinstance(sample, Mapping):
raise ValueError(f'Invalid representative sample type. Provide a mapping (usually a dict) of {{input_key: input_value}}. Got type: {type(sample)} instead.')
if set(sample.keys()) != expected_in... | Validates a single instance of representative sample.
This provides a simple check for `sample` that this is a mapping of
{input_key: input_value}.
Args:
sample: A `RepresentativeSample` to validate.
Returns:
`sample` iff it is valid.
Raises:
ValueError: iff the sample isn't an instance of `Mapping`.
KeyError: iff ... | github-repos |
def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)
... | Args:
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_spec... | github-repos |
def threshold(x, threshold, default_value):
return ops.threshold(x, threshold, default_value) | Threshold activation function.
It is defined as:
`threshold(x) = x` if `x > threshold`,
`threshold(x) = default_value` otherwise.
Args:
x: Input tensor.
threshold: The value that decides when to retain or replace x.
default_value: Value to assign when `x <= threshold`. | github-repos |
def get_repo(task, source_env_prefix):
repo = _extract_from_env_in_payload(task, source_env_prefix + '_HEAD_REPOSITORY')
if repo is not None:
repo = repo.rstrip('/')
return repo | Get the repo for a task.
Args:
task (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
str: the source url.
None: if not defined for this task. | juraj-google-style |
def preprocessing_fn(inputs):
outputs = {}
for key in taxi.DENSE_FLOAT_FEATURE_KEYS:
outputs[taxi.transformed_name(key)] = transform.scale_to_z_score(_fill_in_missing(inputs[key]))
for key in taxi.VOCAB_FEATURE_KEYS:
outputs[taxi.transformed_name(key)] = transform.compute_and_apply_vocabular... | tf.transform's callback function for preprocessing inputs.
Args:
inputs: map from feature keys to raw not-yet-transformed features.
Returns:
Map from string feature key to transformed feature operations. | github-repos |
def __init__(self, resolver_context, file_object=None):
super(DataRange, self).__init__(resolver_context)
self._current_offset = 0
self._file_object = file_object
if file_object:
self._file_object_set_in_init = True
self._range_offset = 0
self._range_size = file_object.get_size()... | Initializes a file-like object.
If the file-like object is chained do not separately use the parent
file-like object.
Args:
resolver_context (Context): resolver context.
file_object (Optional[file]): parent file-like object. | juraj-google-style |
def fetch(self, addon_id, data={}, **kwargs):
return super(Addon, self).fetch(addon_id, data, **kwargs) | Fetch addon for given Id
Args:
addon_id : Id for which addon object has to be retrieved
Returns:
addon dict for given subscription Id | juraj-google-style |
def get_context(self, max_frames=None, missing_entities=[]):
if ((not max_frames) or (max_frames > len(self.frame_stack))):
max_frames = len(self.frame_stack)
missing_entities = list(missing_entities)
context = []
for i in xrange(max_frames):
frame_entities = [entity.copy() for entity in... | Constructs a list of entities from the context.
Args:
max_frames(int): maximum number of frames to look back
missing_entities(list of str): a list or set of tag names, as strings
Returns:
list: a list of entities | codesearchnet |
def mean_pooling(self, model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-09) | The function calculates the mean of token embeddings
Args:
model_output: The output of the model.
attention_mask: This is a tensor that contains 1s for all input tokens and
0s for all padding tokens.
Returns:
The mean of the token embeddings. | github-repos |
def by_location(self, location, cc=None):
header, content = self._http_request(self.BASE_URL, location=location, cc=cc)
return json.loads(content) | Perform a Yelp Neighborhood API Search based on a location specifier.
Args:
location - textual location specifier of form: "address, city, state or zip, optional country"
cc - ISO 3166-1 alpha-2 country code. (Optional) | juraj-google-style |
def show_backref(target, max_depth=3):
if objgraph is None:
raise NotImplementedError('objgraph is not installed.')
string_io = io.StringIO()
objgraph.show_backrefs(target, max_depth=max_depth, output=string_io)
graph = string_io.getvalue()
string_io.close()
return graph | Returns a dot graph of all the objects that are referencing the target.
A object referencing graph is useful to debug memory leak like circular
reference. objgraph provides a good visualization of the memory graph than
most python built-in utilities like gc.get_referrers(), which are not
human-readable sometimes.
The... | github-repos |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
mru_values_dict = {}
for subkey in registry_key.GetSubkeys():
username_value = subkey.GetValueByName('UsernameHint')
if (username_value and username_value.data and
username_value.DataIsString()):
username = use... | Extracts events from a Terminal Server Client Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | juraj-google-style |
def get_victim_web_asset(self, main_type, sub_type, unique_id, asset_id, params=None):
params = params or {}
return self.victim_web_asset(main_type, sub_type, unique_id, asset_id, params=params) | Args:
main_type:
sub_type:
unique_id:
asset_id:
params:
Return: | juraj-google-style |
def forward(self, g_values: torch.Tensor) -> torch.Tensor:
p_one_unique_token, p_two_unique_tokens = self._compute_latents(g_values)
return 0.5 * ((g_values + 0.5) * p_two_unique_tokens + p_one_unique_token) | Computes the likelihoods P(g_values|watermarked).
Args:
g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
g-values (values 0 or 1)
Returns:
p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth]. | github-repos |
def _bitResponseToValue(bytestring):
_checkString(bytestring, description='bytestring', minlength=1, maxlength=1)
RESPONSE_ON = '\x01'
RESPONSE_OFF = '\x00'
if (bytestring == RESPONSE_ON):
return 1
elif (bytestring == RESPONSE_OFF):
return 0
else:
raise ValueError('Could ... | Convert a response string to a numerical value.
Args:
bytestring (str): A string of length 1. Can be for example ``\\x01``.
Returns:
The converted value (int).
Raises:
TypeError, ValueError | codesearchnet |
def tseries_between(self, tstart=None, tend=None):
if self.tseries is None:
return None
ndat = self.tseries.shape[0]
if tstart is None:
istart = 0
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
ista... | Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class:`pandas.DataFrame`: slice of :attr:`tseries`. | juraj-google-style |
def count(cls, cur, table:str, where_keys: list=None):
if where_keys:
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._count_query_where.format(table, where_clause)
q, t = query, values
else:
query = cls._count_qu... | gives the number of records in the table
Args:
table: a string indicating the name of the table
Returns:
an integer indicating the number of records in the table | juraj-google-style |
def _postprocess_flat_outputs(outputs: Any, need_spmd_partitioning: bool) -> Tuple[List[Optional[core_types.Tensor]], List[ops.Operation], List[Any]]:
if outputs is None:
outputs = tuple()
pack_template = nest.flatten(outputs, expand_composites=False)
outputs = nest.flatten(outputs, expand_composite... | Validates non-flat outputs, add backs device assignments and other attrs.
Args:
outputs: Output from `computation` inside `tpu.rewrite`.
need_spmd_partitioning: Whether XLA SPMD partitioning is needed.
Returns:
- Tensors extracted from outputs.
- Operations extracted from outputs.
- A pack template for use with nest.... | github-repos |
def HandleMessageBundles(self, request_comms, response_comms):
(messages, source, timestamp) = self._communicator.DecodeMessages(request_comms)
now = time.time()
if messages:
self.ReceiveMessages(source, messages)
required_count = max(0, (self.max_queue_size - request_comms.queue_size))
task... | Processes a queue of messages as passed from the client.
We basically dispatch all the GrrMessages in the queue to the task scheduler
for backend processing. We then retrieve from the TS the messages destined
for this client.
Args:
request_comms: A ClientCommunication rdfvalue with messages sent by the
client. source... | codesearchnet |
def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):
if downsample_frac:
df = df.sample(frac=downsample_frac)
plt.figure(figsize=figsize)
sns.pairplot(df[features], hue='target')
plt.show() | Plot a scatterplot matrix for a list of features, colored by target value.
Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
downsample_frac: Dataframe ... | juraj-google-style |
def get_module(module_abs_import):
logger.debug("starting")
logger.debug(f"loading module {module_abs_import}")
try:
imported_module = importlib.import_module(module_abs_import)
logger.debug("done")
return imported_module
except ModuleNotFoundError as err:
msg = ("Th... | Use importlib to get the module dynamically.
Get instance of the module specified by the module_abs_import.
This means that module_abs_import must be resolvable from this package.
Args:
module_abs_import: string. Absolute name of module to import.
Raises:
PyModuleNotFoundError: if module not found. | juraj-google-style |
def get_qos_aggregated_configuration(self):
uri = '{}{}'.format(self.data['uri'], self.QOS_AGGREGATED_CONFIGURATION)
return self._helper.do_get(uri) | Gets the QoS aggregated configuration for the logical interconnect.
Returns:
dict: QoS Configuration. | codesearchnet |
def _length(self):
self._build_chunk_headers()
length = 0
if self._data:
for field in self._data:
length += len(self._chunk_headers[field])
length += len(self._data[field])
length += 2
if self._files:
for field in self._files:
length += len... | Returns total length for this request.
Returns:
int. Length | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.