code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def get_content_field(self, name):
fields = self._content.findall(name)
if (not fields):
return None
elif (len(fields) == 1):
return etree_to_dict(fields[0])[name]
else:
return [etree_to_dict(field)[name] for field in fields] | Get the contents of a specific subtag from Clusterpoint Storage's response's content tag.
Args:
name -- A name string of the content's subtag to be returned.
Returns:
A dict representing the contents of the specified field or a list of dicts
if there are multiple fields with that tag name. Returns None if no field fo... | codesearchnet |
def filter_parts(cls, part_info):
filtered = OrderedDict()
for part_name, info_list in part_info.items():
if info_list is None or isinstance(info_list, Exception):
continue
info_list = [i for i in info_list if isinstance(i, cls)]
if i... | Filter the part_info dict looking for instances of our class
Args:
part_info (dict): {part_name: [Info] or None} as returned from
Controller.run_hook()
Returns:
dict: {part_name: [info]} where info is a subclass of cls | juraj-google-style |
def _MakeGroupFromRootSection(root_section, undefined_str):
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.string_types):
continue
func, args = statement
if func is _DoDef and isinstance(args, _Section):
section =... | Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree | juraj-google-style |
def remove_pad(x, pad_remover, mode):
x = expert_utils.flatten_all_but_last(x)
if (mode != ModeKeys.PREDICT):
x = pad_remover.remove(x)
x = tf.expand_dims(x, axis=0)
return x | Remove padding by concatenating all dimension into one.
Args:
x (tf.Tensor): input of shape [batch_size, length, depth]
pad_remover (obj): a PadRemover object
mode (ModeKeys): infer, train or eval. If inference, the padding remover is
not applied
Returns:
tf.Tensor of shape [1,length_nonpad,depth] where
length_nonpad... | codesearchnet |
def pad_trajectories(trajectories, boundary=20):
t_max = max((r.shape[0] for (_, _, r) in trajectories))
boundary = int(boundary)
bucket_length = (boundary * int(np.ceil((float(t_max) / boundary))))
padded_observations = []
padded_actions = []
padded_rewards = []
padded_lengths = []
rewa... | Pad trajectories to a bucket length that is a multiple of boundary.
Args:
trajectories: list[(observation, actions, rewards)], where each observation
is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the
length of the list being B (batch size).
boundary: int, bucket length, the actions and rewards are... | codesearchnet |
def preprocess_input_examples_arg_string(input_examples_str):
input_dict = preprocess_input_exprs_arg_string(input_examples_str)
for input_key, example_list in input_dict.items():
if not isinstance(example_list, list):
raise ValueError('tf.Example input must be a list of dictionaries, but "%... | Parses input into dict that maps input keys to lists of tf.Example.
Parses input string in the format of 'input_key1=[{feature_name:
feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary
that maps each input_key to its list of serialized tf.Example.
Args:
input_examples_str: A string that specif... | github-repos |
def _run_graph(self, device, input_shape, axes, num_layers, mode, scale, train, num_iters):
graph = ops.Graph()
with graph.as_default():
outputs = build_graph(device, input_shape, axes, num_layers, mode, scale, train)
with session_lib.Session(graph=graph) as session:
variables.global_variabl... | Run the graph and print its execution time.
Args:
device: string, the device to run on.
input_shape: shape of the input tensor.
axes: axes that are to be normalized across.
num_layers: number of batch normalization layers in the graph.
mode: "op", "py" or "slow" depending on the implementation.
scale: scale after norm... | github-repos |
def _parse_trunk_native_vlan(self, config):
match = re.search(r'switchport trunk native vlan (\d+)', config)
return dict(trunk_native_vlan=match.group(1)) | Scans the specified config and parse the trunk native vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport trunk
native vlan value. The dict returned is intended to be
merged into the resource dict | juraj-google-style |
def get_yaml_parser_roundtrip():
yaml_writer = yamler.YAML(typ='rt', pure=True)
yaml_writer.indent(mapping=2, sequence=4, offset=2)
return yaml_writer | Create the yaml parser object with this factory method.
The round-trip parser preserves:
- comments
- block style and key ordering are kept, so you can diff the round-tripped
source
- flow style sequences ( ‘a: b, c, d’) (based on request and test by
Anthony Sottile)
- anchor names that are hand-crafted (i.e. not of t... | codesearchnet |
def _post_process(self, feed_item, item):
if item['assetIdentifier']['name']:
feed_item[FieldMap.CREATIVE_ASSET_NAME] = item['assetIdentifier']['name'] | Maps ids and names of related entities so they can be updated in the Bulkdozer feed.
When Bulkdozer is done processing an item, it writes back the updated names
and ids of related objects, this method makes sure those are updated in the
creative asset feed.
Args:
feed_item: Feed item representing the creative asset f... | github-repos |
def _assign_method(self, resource_class, method_type):
"\n If we assigned the same method to each method, it's the same\n method in memory, so we need one for each acceptable HTTP method.\n "
method_name = resource_class.get_method_name(resource_class, method_type)
valid_status_codes = ... | Using reflection, assigns a new method to this class.
Args:
resource_class: A resource class
method_type: The HTTP method type | codesearchnet |
def item(self, key):
return _item.Item(self._name, key, context=self._context) | Retrieves an Item object for the specified key in this bucket.
The item need not exist.
Args:
key: the key of the item within the bucket.
Returns:
An Item instance representing the specified key. | juraj-google-style |
def update_handler(Model, name=None, **kwds):
async def action_handler(service, action_type, payload, props, notify=True, **kwds):
if action_type == get_crud_action('update', name or Model):
try:
message_props = {}
i... | This factory returns an action handler that updates a new instance of
the specified model when a update action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to update when the action
received.
Returns:
function(type, payload): The action handler for this mod... | juraj-google-style |
def _find_furious_yaml(start, checked):
directory = start
while directory not in checked:
checked.add(directory)
for fs_yaml_name in FURIOUS_YAML_NAMES:
yaml_path = os.path.join(directory, fs_yaml_name)
if os.path.exists(yaml_path):
return yaml_path
... | Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of furious.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward... | juraj-google-style |
def getexcfo(e):
tb = sys.exc_info()[2]
tbinfo = traceback.extract_tb(tb)
(path, line, name, src) = ('', '', '', None)
if tbinfo:
(path, line, name, sorc) = tbinfo[(- 1)]
retd = {'msg': str(e), 'file': path, 'line': line, 'name': name, 'src': src}
if isinstance(e, s_exc.SynErr):
... | Get an err tufo from an exception.
Args:
e (Exception): An Exception (or Exception subclass).
Notes:
This can be called outside of the context of an exception handler,
however details such as file, line, function name and source may be
missing.
Returns:
((str, dict)): | codesearchnet |
def GetFileObject(self, data_stream_name=''):
data_stream_names = [
data_stream.name for data_stream in self._GetDataStreams()]
if data_stream_name and data_stream_name not in data_stream_names:
return None
path_spec = copy.deepcopy(self.path_spec)
if data_stream_name:
... | Retrieves the file-like object.
Args:
data_stream_name (Optional[str]): data stream name, where an empty
string represents the default data stream.
Returns:
TSKFileIO: file-like object or None. | juraj-google-style |
def convert_config_value(self, value, label):
if isinstance(value, six.string_types):
value = value.lower()
if (value in self.TRUTHY_VALUES):
return True
elif (value in self.FALSY_VALUES):
return False
else:
raise YapconfValueError('Cowardly refusing to interpret config v... | Converts all 'Truthy' values to True and 'Falsy' values to False.
Args:
value: Value to convert
label: Label of the config which this item was found.
Returns: | codesearchnet |
def argpartition(x, kth, axis=-1):
if any_symbolic_tensors((x,)):
return Argpartition(kth, axis).symbolic_call(x)
return backend.numpy.argpartition(x, kth, axis) | Performs an indirect partition along the given axis.
It returns an array
of indices of the same shape as `x` that index data along the given axis
in partitioned order.
Args:
a: Array to sort.
kth: Element index to partition by.
The k-th element will be in its final sorted position and all
smaller elements will be mov... | github-repos |
def get_input_mask_at(self, node_index):
inputs = self.get_input_at(node_index)
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None) | Retrieves the input mask tensor(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A mask tensor
(or list of tensors if the layer has multiple inputs). | github-repos |
def get_data_xls(file_name, file_contents=None, on_demand=False):
def tuple_to_iso_date(tuple_date):
(y,m,d, hh,mm,ss) = tuple_date
non_zero = lambda n: n!=0
date = "%04d-%02d-%02d" % (y,m,d) if list(filter(non_zero, (y,m,d))) else ''
time = "T%02d:%02... | Loads the old excel format files. New 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 quickhull(sample):
link = lambda a, b: np.concatenate((a, b[1:]))
edge = lambda a, b: np.concatenate(([a], [b]))
def dome(sample, base):
h, t = base
dists = np.dot(sample - h, np.dot(((0, -1), (1, 0)), (t - h)))
outer = np.repeat(sample, dists > 0, axis=0)
if len(... | Find data points on the convex hull of a supplied data set
Args:
sample: data points as column vectors n x d
n - number samples
d - data dimension (should be two)
Returns:
a k x d matrix containint the convex hull data points | juraj-google-style |
def _queue_dag(self, name, *, data=None):
if self._stop_workflow:
return None
if (name not in self._dags_blueprint):
raise DagNameUnknown()
new_dag = copy.deepcopy(self._dags_blueprint[name])
new_dag.workflow_name = self.name
self._dags_running[new_dag.name] = self._celery_app.send_t... | Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
Raises:
DagNameUnknown: If the specified dag name does not exist
Returns:
str: The name of the ... | codesearchnet |
def load_config(self, filepath=None):
def load_settings(filepath):
instruments_loaded = {}
probes_loaded = {}
scripts_loaded = {}
if filepath and os.path.isfile(filepath):
in_data = load_b26_file(filepath)
... | checks if the file is a valid config file
Args:
filepath: | juraj-google-style |
def slice_arrays(arrays, indices, contiguous=True):
converted_to_list = False
if not isinstance(arrays, list):
converted_to_list = True
arrays = [arrays]
if any((tensor_util.is_tf_type(x) for x in arrays)):
if not contiguous:
entries = [[x[i:i + 1] for i in indices] for x... | Slices batches out of provided arrays (workaround for eager tensors).
Unfortunately eager tensors don't have the same slicing behavior as
Numpy arrays (they follow the same slicing behavior as symbolic TF tensors),
hence we cannot use `generic_utils.slice_arrays` directly
and we have to implement this workaround based... | github-repos |
def __init__(self,corpus_dir,datastore_type='file',db_name='corpus.db'):
self.g = Goose({'browser_user_agent': 'Mozilla','parser_class':'soup'})
self.corpus_dir = corpus_dir
self.datastore_type = datastore_type
self.db_name = db_name
self.stats = defaultdict(in... | Read links and associated categories for specified articles
in text file seperated by a space
Args:
corpus_dir (str): The directory to save the generated corpus
datastore_type (Optional[str]): Format to save generated corpus.
Specify either 'file' or 'sqlite'.
db_name (Optional[str]): Name of database if 'sqlite' is s... | juraj-google-style |
def parse(self, args: List[str]) -> Optional[argparse.Namespace]:
try:
return self._parser.parse_args(args)
except KeyboardInterrupt:
raise
except:
return None | Parses a list of string inputs.
The parsed namespace contains these attributes:
output_name: Optional[str], the output variable name.
verbose: bool, whether to display more details of the magic execution.
query: Optional[List[str]], the beam SQL query to execute.
Returns:
The parsed args or None if fail to parse. | github-repos |
def get_by(self, field, value):
if not field:
logger.exception(RESOURCE_CLIENT_INVALID_FIELD)
raise ValueError(RESOURCE_CLIENT_INVALID_FIELD)
filter = "\"{0}='{1}'\"".format(field, value)
results = self.get_all(filter=filter)
if "." not in fiel... | Get the resource by passing a field and its value.
Note:
This function uses get_all passing a filter.The search is case-insensitive.
Args:
field: Field name to filter.
value: Value to filter.
Returns:
dict | juraj-google-style |
def _parse_networks(self, config):
networks = list()
regexp = 'network (.+)/(\\d+) area (\\d+\\.\\d+\\.\\d+\\.\\d+)'
matches = re.findall(regexp, config)
for (network, netmask, area) in matches:
networks.append(dict(network=network, netmask=netmask, area=area))
return dict(networks=networks) | Parses config file for the networks advertised
by the OSPF process
Args:
config(str): Running configuration
Returns:
list: dict:
keys: network (str)
netmask (str)
area (str) | codesearchnet |
def _vmap_for_bhqkv(mask_function: Callable, bh_indices: bool=True) -> Callable:
dimensions = [(None, None, None, 0), (None, None, 0, None)]
if bh_indices:
dimensions.extend([(None, 0, None, None), (0, None, None, None)])
for dims in dimensions:
mask_function = torch.vmap(mask_function, in_d... | Used to vmap our mask_functions over the q_idx and kv_idx dimensions of the inputs. Optionally, vmap over
the batch and head indices as well if `bh_indices=True`.
Using vmap here allows us to keep the performance of vectorized ops, while having a single set of primitive
functions between attention interfaces (i.e. betw... | github-repos |
def encode_function_call(self, function_name, args):
if (function_name not in self.function_data):
raise ValueError('Unkown function {}'.format(function_name))
description = self.function_data[function_name]
function_selector = zpad(encode_int(description['prefix']), 4)
arguments = encode_abi(de... | Return the encoded function call.
Args:
function_name (str): One of the existing functions described in the
contract interface.
args (List[object]): The function arguments that wll be encoded and
used in the contract execution in the vm.
Return:
bin: The encoded function name and arguments so that it can be used
with... | codesearchnet |
def __init__(self, features: List[np.ndarray], timestamps: np.ndarray, schema: Optional[Schema]=None) -> None:
self.features = features
self.timestamps = timestamps
if schema is not None:
self.check_schema(schema) | Initializes the IndexData object by checking and setting the features
and timestamps.
Raises:
ValueError: If features are not one-dimensional arrays.
ValueError: If the number of elements in features and timestamps
do not match. | github-repos |
def insert_arguments_into_match_query(compilation_result, arguments):
if compilation_result.language != MATCH_LANGUAGE:
raise AssertionError(u'Unexpected query output language: {}'.format(compilation_result))
base_query = compilation_result.query
argument_types = compilation_result.input_metad... | Insert the arguments into the compiled MATCH query to form a complete query.
Args:
compilation_result: a CompilationResult object derived from the GraphQL compiler
arguments: dict, mapping argument name to its value, for every parameter the query expects.
Returns:
string, a MATCH query with inserted argument data | juraj-google-style |
def get_updates_for(self, inputs):
warnings.warn('`layer.get_updates_for` is deprecated and will be removed in a future version. Please use `layer.updates` method instead.')
return self.updates | Deprecated, do NOT use!
Retrieves updates relevant to a specific set of inputs.
Args:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of update ops of the layer that depend on `inputs`. | github-repos |
def load_method(path,method,class_name = None,instance_creator = None):
module = load_module(path)
if class_name :
class_type = getattr(module, class_name)
if instance_creator:
ic_rest = instance_creator
nxt = module
while ('.'... | Returns an instance of the method specified.
Args :
path : The path to the module contianing the method or function.
method : The name of the function.
class_name : The name of the class if the funtion is a method.
instance_creator: The name of the method to return the class instance. | juraj-google-style |
def compute_invariants(self, graph_file, input_format, invariants=Invariants.ALL, email=None, use_threads=False, callback=None):
if (email is None):
email = self.email
if (input_format not in GraphFormats._any):
raise ValueError('Invalid input format, {}.'.format(input_format))
if (not (set(... | Compute invariants from an existing GraphML file using the remote
grute graph services.
Arguments:
graph_file (str): The filename of the graphml file
input_format (str): One of grute.GraphFormats
invariants (str[]: Invariants.ALL)*: An array of grute.Invariants
to compute on the graph
email (str: self.email)*: The ema... | codesearchnet |
def _GetTableNames(self, database):
table_names = []
for esedb_table in database.tables:
table_names.append(esedb_table.name)
return table_names | Retrieves the table names in a database.
Args:
database (pyesedb.file): ESE database.
Returns:
list[str]: table names. | juraj-google-style |
def plot_axis(self, ax, legend, ladder=False, default_width=1, match_only=None, colour=None, colour_function=None, cmap=None, default=None, width_field=None, **kwargs):
default_c = None
patches = []
for iv in self.__list:
origin = (0, iv.top.z)
d = legend.get_decor(iv.primary, match_only=mat... | Plotting, but only the Rectangles. You have to set up the figure.
Returns a matplotlib axis object.
Args:
ax (axis): The matplotlib axis to plot into.
legend (Legend): The Legend to use for colours, etc.
ladder (bool): Whether to use widths or not. Default False.
default_width (int): A width for the plot if not using ... | codesearchnet |
def localize_file(path_or_buffer):
path_or_buffer = _stringify_path(path_or_buffer)
if _is_url(path_or_buffer):
req = urlopen(path_or_buffer)
filename = os.path.basename(req.geturl())
if os.path.splitext(filename)[-1] is not ".pdf":
pid = os.getpid()
filena... | Ensure localize target file.
If the target file is remote, this function fetches into local storage.
Args:
path (str):
File path or file like object or URL of target file.
Returns:
filename (str): file name in local storage
temporary_file_flag (bool): temporary file flag | juraj-google-style |
def stop_gradient(input_layer):
if input_layer.is_sequence():
result = [tf.stop_gradient(t) for t in input_layer.sequence]
return input_layer.with_sequence(result)
else:
return tf.stop_gradient(input_layer) | Cuts off the gradient at this point.
This works on both sequence and regular Pretty Tensors.
Args:
input_layer: The input.
Returns:
A new Pretty Tensor of the same type with stop_gradient applied. | codesearchnet |
def clone(self, *args, **overrides):
clone = super(Layout, self).clone(*args, **overrides)
clone._max_cols = self._max_cols
return clone | Clones the Layout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
**overrides: New keyword arguments to pass to constructor
Return... | juraj-google-style |
def get_peers(self, id=None, endpoint=None):
return self._call_endpoint(GET_PEERS, id=id, endpoint=endpoint) | Get the current peers of a remote node
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call | juraj-google-style |
def _write_install_json(self, filename, install_json):
if os.path.isfile(filename):
with open(filename, 'w') as fh:
json.dump(install_json, fh, indent=4, sort_keys=True)
else:
err = 'Could not write file: {}.'.format(filename)
... | Write install.json file.
Some projects have bundles App with multiple install.json files. Typically these files are
prefixed with the App name (e.g., MyApp.install.json).
Args:
filename (str): The install.json file name.
install_json (dict): The contents of the install.json file. | juraj-google-style |
def find_rootfs(conn, disk_root):
rootfs = conn.inspect_os()
if ((not rootfs) or (len(rootfs) > 1)):
filesystems = conn.list_filesystems()
if (disk_root in filesystems):
rootfs = [disk_root]
else:
rootfs = [fs for fs in filesystems.keys() if (disk_root in fs)]
... | Find the image's device root filesystem, and return its path.
1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than
one root filesystem or None, try:
2. Find an exact match of `disk_root` from
:func:`guestfs.GuestFS.list_filesystems`, if none is found, try:
3. Return the device that has the substri... | codesearchnet |
def add_vectors(self, vectors):
if isinstance(vectors[0], (list, np.ndarray)):
for vec in vectors:
self.vectors.append(vec)
else:
self.vectors.append(vectors) | Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller. | codesearchnet |
def inspect_task(self, task):
url = self._url('/tasks/{0}', task)
return self._result(self._get(url), True) | Retrieve information about a task.
Args:
task (str): Task ID
Returns:
(dict): Information about the task.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. | juraj-google-style |
def check_candidate_exists(self, basepath, candidates):
checked = []
for item in candidates:
abspath = os.path.join(basepath, item)
if os.path.exists(abspath):
checked.append(abspath)
return checked | Check that at least one candidate exist into a directory.
Args:
basepath (str): Directory path where to search for candidate.
candidates (list): List of candidate file paths.
Returns:
list: List of existing candidates. | juraj-google-style |
def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
if reverse:
dimensions = dimensions[::(- 1)]
trace_systems = ((len(dimensions) - 1) - np.array(trace_systems))
rho = vec.reshape(dimensions)
rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems))
d =... | Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
dimensions (list(int)): a list of the dimensions of the subsystems.
If this is not set it will assume all
subsystems are qubits.
reverse (boo... | codesearchnet |
def Pack(cls, obj, version):
if isinstance(obj, ServiceQuery):
return str(obj)
return obj | Pack the given object using AdWords-specific logic.
Args:
obj: an object to be packed for SOAP using AdWords-specific logic, if
applicable.
version: the version of the current API, e.g. 'v201809'
Returns:
The given object packed with AdWords-specific logic for SOAP, if
applicable. Otherwise, returns the given object ... | codesearchnet |
def get_normalized_variable_map(scope_or_module, collection=tf.GraphKeys.GLOBAL_VARIABLES, context=None, group_sliced_variables=True):
scope_name = get_variable_scope_name(scope_or_module)
if (context is None):
context = scope_or_module
prefix = get_variable_scope_name(context)
prefix_length = (... | Builds map of `tf.Variable`s in scope or module with normalized names.
The names of the variables are normalized to remove the scope prefix.
Args:
scope_or_module: Scope or module to build map from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.GLOBAL_VARIABLES`, which includes non-tra... | codesearchnet |
def submit_batch_prediction(job_request, job_id=None):
if (job_id is None):
job_id = ('prediction_' + datetime.datetime.now().strftime('%y%m%d_%H%M%S'))
job = {'job_id': job_id, 'prediction_input': job_request}
context = datalab.Context.default()
cloudml = discovery.build('ml', 'v1', credentials... | Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
'input_paths': ['gs://my_bucket/my_file.csv'],
'output_path': 'gs://my_bucket/predict_output',
'region': 'us-ce... | codesearchnet |
def get_capacity_grav(self, min_voltage=None, max_voltage=None, use_overall_normalization=True):
pairs_in_range = self._select_in_voltage_range(min_voltage, max_voltage)
normalization_mass = (self.normalization_mass if (use_overall_normalization or (len(pairs_in_range) == 0)) else pairs_in_range[(- 1)].mass_dis... | Get the gravimetric capacity of the electrode.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.
use_overall_normalization (booL): If False, normalize by the
discharged state of only the voltage pairs matching the v... | codesearchnet |
def publish_metric(self, metric_name, metric_value, epoch_seconds=None):
if (epoch_seconds is None):
epoch_seconds = self._reactor.seconds()
self._client_factory.publish_metric(metric_name, metric_value, int(epoch_seconds)) | Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the time for the metric hit.
Returns:
None | codesearchnet |
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth):
side = random.randrange(2)
left_depth = random.randrange((min_depth if side else 0), (max_depth + 1))
right_depth = random.randrange((min_depth if (not side) else 0), (max_depth + 1))
var_index = random.randrange(len(vlist... | Randomly generate an algebra inverse dataset sample.
Given an input equation and variable, produce the expression equal to the
variable.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
solve_ops: See `solve_ops` doc... | codesearchnet |
def layer_preprocess(layer_input, hparams, layer_collection=None):
assert "a" not in hparams.layer_preprocess_sequence, (
"No residual connections allowed in hparams.layer_preprocess_sequence")
assert "z" not in hparams.layer_preprocess_sequence, (
"No residual connections allowed in hparams.layer_pr... | Apply layer preprocessing.
See layer_prepostprocess() for details.
A hyperparameters object is passed for convenience. The hyperparameters
that may be used are:
layer_preprocess_sequence
layer_prepostprocess_dropout
norm_type
hidden_size
norm_epsilon
Args:
layer_input: a Tensor
hparams: a hyperparameters object.
l... | juraj-google-style |
def select_executor(elem, doc):
executor = EXECUTORS['default']
if ('cmd' in elem.attributes.keys()):
executor = elem.attributes['cmd']
elif ('runas' in elem.attributes.keys()):
executor = EXECUTORS[elem.attributes['runas']]
elif (elem.classes[0] != 'exec'):
executor = EXECUTORS[... | Determines the executor for the code in `elem.text`.
The elem attributes and classes select the executor in this order (highest
to lowest):
- custom commands (cmd=...)
- runas (runas=...) takes a key for the executors
- first element class (.class) determines language and thus executor
Args:
elem The AST element.
doc... | codesearchnet |
def build_single_handler_applications(paths, argvs=None):
applications = {}
argvs = ({} or argvs)
for path in paths:
application = build_single_handler_application(path, argvs.get(path, []))
route = application.handlers[0].url_path()
if (not route):
if ('/' in application... | Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
path (seq[str]) : paths to files o... | codesearchnet |
def price(self, market: pmd.ProcessedMarketData, name: Optional[str]=None):
model = self._config.model or models.InterestRateModelType.HULL_WHITE_ONE_FACTOR
name = name or self._name + '_price'
with tf.name_scope(name):
valuation_date = dateslib.convert_to_date_tensor(market.date)
strike = s... | Returns the present value of the swaption on the valuation date.
Args:
market: A instance of type `ProcessedMarketData` which contains the
necessary information for pricing the swaption.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.
Returns:
A Ran... | github-repos |
def _randomFloats(self, shape, low=0.0, high=1.0, dtype=dtypes.float32):
val = np.random.random_sample(shape)
diff = high - low
val *= diff
val += low
return constant_op.constant(val, dtype=dtype) | Generate a tensor of random floating-point values.
Values will be continuously distributed in the range [low, high).
Note that we use numpy to generate random numbers and then feed the result
through a constant op to avoid the re-rolling of TensorFlow random ops on
each run in graph mode.
Args:
shape: The output sha... | github-repos |
def accumulate_from_superclasses(cls, propname):
cachename = "__cached_all" + propname
if cachename not in cls.__dict__:
s = set()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
... | Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__`` | juraj-google-style |
def _PrintEventLabelsCounter(
self, event_labels_counter, session_identifier=None):
if not event_labels_counter:
return
title = 'Event tags generated per label'
if session_identifier:
title = '{0:s}: {1:s}'.format(title, session_identifier)
table_view = views.ViewsFactory.GetTab... | Prints the event labels counter.
Args:
event_labels_counter (collections.Counter): number of event tags per
label.
session_identifier (Optional[str]): session identifier. | juraj-google-style |
def __Build(leaves):
if len(leaves) < 1:
raise Exception('Leaves must have length')
if len(leaves) == 1:
return leaves[0]
num_parents = int((len(leaves) + 1) / 2)
parents = [MerkleTreeNode() for i in range(0, num_parents)]
for i in range(0, num_... | Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node. | juraj-google-style |
def get_contour_pd_plot(self):
from scipy import interpolate
from matplotlib import cm
pd = self._pd
entries = pd.qhull_entries
data = np.array(pd.qhull_data)
plt = self._get_2d_plot()
data[(:, 0:2)] = triangular_coord(data[(:, 0:2)]).transpose()
for (i, e) in enumerate(entries):
... | Plot a contour phase diagram plot, where phase triangles are colored
according to degree of instability by interpolation. Currently only
works for 3-component phase diagrams.
Returns:
A matplotlib plot object. | codesearchnet |
def get_exe_info(dir_, flag_protected=False):
ret = []
ff = glob.glob(os.path.join(dir_, "*.py"))
ff = [f for f in ff if flag_protected or not os.path.basename(f).startswith("_")]
ff.sort()
for f in ff:
_, filename = os.path.split(f)
flag_error = False
flag_g... | Returns a list of ExeInfo objects, which represent Python scripts within dir_
Args:
dir_: string, path to directory
flag_protected: whether or not to include files starting with a '_'
Returns:
list of ExeInfo objects
The ExeInfo objects represent the ".py" files in directory dir_, | juraj-google-style |
def __init__(self, value=None):
super(ApplicationData, self).__init__(value, Tags.APPLICATION_DATA) | Construct an ApplicationData object.
Args:
value (str): A string representing data for a particular namespace.
Optional, defaults to None. | juraj-google-style |
def get_country_by_id(self, country_id) -> 'Country':
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in self._countries_by_id.keys():
for country in self.countries:
if country.country_id == country_id:
... | Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country | juraj-google-style |
def bind_to_storage_buffer(self, binding=0, *, offset=0, size=(- 1)) -> None:
self.mglo.bind_to_storage_buffer(binding, offset, size) | Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all. | codesearchnet |
def swo_disable(self, port_mask):
res = self._dll.JLINKARM_SWO_DisableTarget(port_mask)
if res != 0:
raise errors.JLinkException(res)
return None | Disables ITM & Stimulus ports.
Args:
self (JLink): the ``JLink`` instance
port_mask (int): mask specifying which ports to disable
Returns:
``None``
Raises:
JLinkException: on error | juraj-google-style |
def download_and_prep_data() -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
mnist_dataset = tf.keras.datasets.mnist
(tr_x, tr_y), (te_x, te_y) = mnist_dataset.load_data()
tr_x = tr_x / 255.0
te_x = te_x / 255.0
return (tr_x, tr_y, te_x, te_y) | Download dataset and scale to [0, 1].
Returns:
tr_x: Training data.
tr_y: Training labels.
te_x: Testing data.
te_y: Testing labels. | github-repos |
def replace_dots_to_underscores_at_last(path):
if path == '':
return path
bits = path.split('/')
bits[-1] = bits[-1].replace('.', '_')
return '/'.join(bits) | Remove dot ('.') while a dot is treated as a special character in backends
Args:
path (str): A target path string
Returns:
str | juraj-google-style |
def refresh_role(self, role, file_hierarchy):
if role not in self.cache:
self.cache[role] = {}
was_change = self._refresh_hierarchy_recursive(self.cache[role], file_hierarchy)
if was_change:
cf = open(self.cache_file, 'w')
yaml.dump(self.cache, cf, Du... | Checks and refreshes (if needed) all assistants with given role.
Args:
role: role of assistants to refresh
file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\
YamlAssistantLoader.get_assistants_file_hierarchy | juraj-google-style |
def init_on_device(device: 'torch.device', include_buffers: bool=False):
if include_buffers:
with device:
yield
return
old_register_parameter = nn.Module.register_parameter
if include_buffers:
old_register_buffer = nn.Module.register_buffer
def register_empty_paramet... | A context manager under which models are initialized with all parameters on the specified device.
Args:
device (`torch.device`):
Device to initialize all parameters on.
include_buffers (`bool`, *optional*):
Whether or not to also put all buffers on the meta device while initializing.
Example:
```python
import torch.... | github-repos |
def add_child(self, child):
if (not isinstance(child, Node)):
raise TypeError('child must be a Node')
self.children.append(child)
child.parent = self | Add child to ``Node`` object
Args:
``child`` (``Node``): The child ``Node`` to be added | codesearchnet |
def m_seg(p1, p2, rad, dist):
v = vector(p1, p2)
m = unit(rotate(v, rad), dist)
return translate(p1, m), translate(p2, m) | move segment by distance
Args:
p1, p2: point(x, y)
rad: relative direction angle(radian)
dist: distance
Return:
translated segment(p1, p2) | juraj-google-style |
def _prefix_from_prefix_string(self, prefixlen_str):
try:
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
raise ValueError
prefixlen = int(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
raise ValueError
... | Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range. | juraj-google-style |
def add_permissions(self, grp_name, resource, permissions):
self.project_service.set_auth(self._token_project)
self.project_service.add_permissions(grp_name, resource, permissions) | Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure. | juraj-google-style |
def _GetImportTimestamps(self, pefile_object):
import_timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_IMPORT'):
return import_timestamps
for importdata in pefile_object.DIRECTORY_ENTRY_IMPORT:
dll_name = getattr(importdata, 'dll', '')
try:
dll_name = dll_name.de... | Retrieves timestamps from the import directory, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: import timestamps. | juraj-google-style |
def __call__(self, *args, **kwargs) -> Any: | Calls the functor.
Args:
*args: Any positional arguments.
**kwargs: Any keyword arguments.
Returns:
Any value. | github-repos |
def group_alleles_by_start_end_Xbp(arr, bp=28):
starts = arr[:,0:bp]
ends = arr[:,-bp:]
starts_ends_idxs = defaultdict(list)
l, seq_len = arr.shape
for i in range(l):
start_i = starts[i]
end_i = ends[i]
start_i_str = ''.join([str(x) for x in start_i])
end_i_str =... | Group alleles by matching ends
Args:
arr (numpy.array): 2D int matrix of alleles
bp (int): length of ends to group by
Returns:
dict of lists: key of start + end strings to list of indices of alleles with matching ends | juraj-google-style |
def _update_in_hdx(self, object_type, id_field_name, file_to_upload=None, **kwargs):
self._check_load_existing_object(object_type, id_field_name)
self._merge_hdx_update(object_type, id_field_name, file_to_upload, **kwargs) | Helper method to check if HDX object exists in HDX and if so, update it
Args:
object_type (str): Description of HDX object type (for messages)
id_field_name (str): Name of field containing HDX object identifier
file_to_upload (Optional[str]): File to upload to HDX
**kwargs: See below
operation (string): Operation to p... | juraj-google-style |
def update_variant_rank(self, case_obj, variant_type='clinical', category='snv'):
variants = self.variant_collection.find({'case_id': case_obj['_id'], 'category': category, 'variant_type': variant_type}).sort('rank_score', pymongo.DESCENDING)
LOG.info('Updating variant_rank for all variants')
requests = []
... | Updates the manual rank for all variants in a case
Add a variant rank based on the rank score
Whenever variants are added or removed from a case we need to update the variant rank
Args:
case_obj(Case)
variant_type(str) | codesearchnet |
def remove_repeated_comments(node):
last_comment = {'text': None}
for _node in gast.walk(node):
if anno.hasanno(_node, 'comment'):
comment = anno.getanno(_node, 'comment')
if (comment['text'] == last_comment['text']):
anno.delanno(_node, 'comment')
las... | Remove comments that repeat themselves.
Multiple statements might be annotated with the same comment. This way if one
of the statements is deleted during optimization passes, the comment won't be
lost. This pass removes sequences of identical comments, leaving only the
first one.
Args:
node: An AST
Returns:
An AST w... | codesearchnet |
def get_attr(self, name):
fields = ('s', 'i', 'f', 'b', 'type', 'shape', 'tensor', 'func')
try:
with c_api_util.tf_buffer() as buf:
pywrap_tf_session.TF_OperationGetAttrValueProto(self._c_op, name, buf)
data = pywrap_tf_session.TF_GetBuffer(buf)
except errors.InvalidArgumentE... | Returns the value of the attr of this op with the given `name`.
Args:
name: The name of the attr to fetch.
Returns:
The value of the attr, as a Python object.
Raises:
ValueError: If this op does not have an attr with the given `name`. | github-repos |
def path_new_using_function(w: int, h: int, func: Callable[([int, int, int, int, Any], float)], userData: Any=0, dcost: float=1.41) -> tcod.path.AStar:
return tcod.path.AStar(tcod.path._EdgeCostFunc((func, userData), (w, h)), dcost) | Return a new AStar using the given callable function.
Args:
w (int): Clipping width.
h (int): Clipping height.
func (Callable[[int, int, int, int, Any], float]):
userData (Any):
dcost (float): A multiplier for the cost of diagonal movement.
Can be set to 0 to disable diagonal movement.
Returns:
AStar: A new AStar inst... | codesearchnet |
def commandline_parser(parser=None, arguments=None):
if parser is None:
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(' Command line to execute all tasks in a recipe once. ( Common Entry Point )\n\n This script dispatches all... | Used in StarThinker scripts as entry point for command line calls.
Defines standard parameters used by almost every entry point.
Usage example:
```
import argparse
from starthinker.util.configuration import commandline_parser
if __name__ == "__main__":
# custom parameters
parser = argparse.ArgumentParser()
parser.... | github-repos |
def view_quick_save_page(name=None):
response.set_header('Cache-control', 'no-cache')
response.set_header('Pragma', 'no-cache')
if (request.method == 'PUT'):
if (name is None):
if (len(request.forms.filename) > 0):
name = request.forms.filename
if (name is not Non... | Quick save a page.
.. note:: this is a bottle view
* this view must be called with the PUT method
write the new page content to the file, and not not commit or redirect
Keyword Arguments:
:name: (str) -- name of the rest file (without the .rst extension)
Returns:
bottle response object (200 OK) | codesearchnet |
def load_module_functions(module):
module_functions = {}
for name, item in vars(module).items():
if validator.is_function(item):
module_functions[name] = item
return module_functions | load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
} | juraj-google-style |
def _load_from_file_object(self, f):
subtoken_strings = []
for line in f:
s = line.strip()
if ((s.startswith("'") and s.endswith("'")) or
(s.startswith("\"") and s.endswith("\""))):
s = s[1:-1]
subtoken_strings.append(native_to_unicode(s))
self._init_subtokens... | Load from a file object.
Args:
f: File object to load vocabulary from | juraj-google-style |
def scheduled_sample_count(ground_truth_x,
generated_x,
batch_size,
scheduled_sample_var):
num_ground_truth = scheduled_sample_var
idx = tf.random_shuffle(tf.range(batch_size))
ground_truth_idx = tf.gather(idx, tf.range(num_ground... | Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
scheduled_sample_var: number of ground-truth examples to include in batch.
Returns:
New batch with num_ground_truth sa... | juraj-google-style |
class ViltFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
do_pad: Optional[bool]
size_divisor: Optional[int]
rescale_factor: Optional[float] | Args:
do_pad (`bool`, *optional*, defaults to `True`):
Whether to pad the image. If `True`, will pad the images in the batch to the largest height and width
in the batch. Padding will be applied to the bottom and right with zeros.
size_divisor (`int`, *optional*, defaults to 32):
The size to make the height and width d... | github-repos |
def fetch_all_messages(self, conn, directory, readonly):
conn.select(directory, readonly)
message_data = []
typ, data = conn.search(None, 'All')
for num in data[0].split():
typ, data = conn.fetch(num, '(RFC822)')
for response_part in data:
... | Fetches all messages at @conn from @directory.
Params:
conn IMAP4_SSL connection
directory The IMAP directory to look for
readonly readonly mode, true or false
Returns:
List of subject-body tuples | juraj-google-style |
def _compute_intersection(boxes1, boxes2):
y_min1, x_min1, y_max1, x_max1 = ops.split(boxes1[..., :4], 4, axis=-1)
y_min2, x_min2, y_max2, x_max2 = ops.split(boxes2[..., :4], 4, axis=-1)
boxes2_rank = len(boxes2.shape)
perm = [1, 0] if boxes2_rank == 2 else [0, 2, 1]
intersect_ymax = ops.minimum(y_m... | Computes intersection area between two sets of boxes.
Args:
boxes1: [N, 4] or [batch_size, N, 4] float Tensor boxes.
boxes2: [M, 4] or [batch_size, M, 4] float Tensor boxes.
Returns:
a [N, M] or [batch_size, N, M] float Tensor. | github-repos |
def _iter_errors_custom(instance, checks, options):
for v_function in checks:
try:
result = v_function(instance)
except TypeError:
result = v_function(instance, options)
if isinstance(result, Iterable):
for x in result:
(yield x)
el... | Perform additional validation not possible merely with JSON schemas.
Args:
instance: The STIX object to be validated.
checks: A sequence of callables which do the checks. Each callable
may be written to accept 1 arg, which is the object to check,
or 2 args, which are the object and a ValidationOptions instance.
optio... | codesearchnet |
def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op):
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if (ckpt and ckpt.model_checkpoint_path):
print('ckpt.model_checkpoint_path: {0}'.format(ckpt.model_checkpoint_path))
s... | Runs Eval once.
Args:
saver: Saver.
summary_writer: Summary writer.
top_1_op: Top 1 op.
top_5_op: Top 5 op.
summary_op: Summary op. | codesearchnet |
def next(self):
try:
entry = {}
row = self._csv_reader.next()
for i in range(0, len(row)):
entry[self._headers[i]] = row[i]
return entry
except Exception as e:
self._file.close()
raise e | Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
{key1: value1, key2: value2, ...} | codesearchnet |
def add_to_tensor(self, mat, name='add_to_tensor'):
return self._possibly_broadcast_batch_shape(mat) | Add matrix represented by this operator to `mat`. Equiv to `I + mat`.
Args:
mat: `Tensor` with same `dtype` and shape broadcastable to `self`.
name: A name to give this `Op`.
Returns:
A `Tensor` with broadcast shape and same `dtype` as `self`. | github-repos |
def __init__(self, plugin_callback, plugin_dir = 'workers'):
self.plugin_callback = plugin_callback
self.plugin_dir = plugin_dir
self.load_all_plugins()
self.watcher = dir_watcher.DirWatcher(self.plugin_path)
self.watcher.register_callbacks(self.on_cr... | Initialize the Plugin Manager for Workbench.
Args:
plugin_callback: The callback for plugin. This is called when plugin is added.
plugin_dir: The dir where plugin resides. | juraj-google-style |
def get_configuration(head, update, head_source=None):
head_source = (head_source or get_head_source(head))
update_source = get_acquisition_source(update)
if not is_arxiv_and_publisher(head_source, update_source) and is_manual_merge(head, update):
return ManualMergeOperations
if head_sour... | This function return the right configuration for the inspire_merge
function in according to the given sources. Both parameters can not be None.
Params:
head(dict): the HEAD record
update(dict): the UPDATE record
head_source(string): the source of the HEAD record
Returns:
MergerConfigurationOperations: an object conta... | juraj-google-style |
def to_string(self):
def filt(x):
return '+'+x[0] in PROJ4_PARAMS.keys() and x[1] is not False
items = []
for k, v in sorted(filter(filt, self.items())):
items.append(
"+" + "=".join(
map(str, filter(
l... | Turn a CRS dict into a PROJ.4 string. Mapping keys are tested against
``all_proj_keys`` list. Values of ``True`` are omitted, leaving the key
bare: {'no_defs': True} -> "+no_defs" and items where the value is
otherwise not a str, int, or float are omitted.
Args:
crs: A CRS dict as used in Location.
Returns:
str. The ... | juraj-google-style |
def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None:
... | Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use as
``WHERE`` filters
include_ddl: if ``... | juraj-google-style |
def recipe_trends_places_to_bigquery_via_query(config, auth_write, secret, key, places_dataset, places_query, places_legacy, destination_dataset, destination_table):
twitter(config, {'auth': auth_write, 'secret': secret, 'key': key, 'trends': {'places': {'single_cell': True, 'bigquery': {'dataset': places_dataset, ... | Move using a WOEID query.
Args:
auth_write (authentication) - Credentials used for writing data.
secret (string) - NA
key (string) - NA
places_dataset (string) - NA
places_query (string) - NA
places_legacy (boolean) - NA
destination_dataset (string) - NA
destination_table (string) - NA | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.