code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def split(cls, n, contiguous, can_query=itertools.chain(itertools.repeat(True, 50), itertools.repeat(False)).next, _app=None): if (n < 1): raise ValueError('n must be >= 1') ranges = None if can_query(): if (not contiguous): ns_keys = get_namespace_keys(_app, (n + 1)) ...
Splits the complete NamespaceRange into n equally-sized NamespaceRanges. Args: n: The maximum number of NamespaceRanges to return. Fewer than n namespaces may be returned. contiguous: If True then the returned NamespaceRanges will cover the entire space of possible namespaces (i.e. from MIN_NAMESPACE to MAX_NAMESPACE)...
codesearchnet
def get_raw_entry(self, variant_line=None, variant_dict=None, vcf_header=None, individual_id=None, dict_key=None): if variant_line: variant_line = variant_line.rstrip().split() entry = None if self.field == 'CHROM': if variant_line: ...
Return the raw entry from the vcf field If no entry was found return None Args: variant_line (str): A vcf formated variant line vcf_header (list): A list with the vcf header line individual_id (str): The individual id to get gt call Returns: The raw entry found in variant line
juraj-google-style
def tf_initialize(self, x_init, base_value, target_value, estimated_improvement): self.base_value = base_value if (estimated_improvement is None): estimated_improvement = tf.abs(x=base_value) first_step = super(LineSearch, self).tf_initialize(x_init) improvement = tf.divide(x=(target_value - sel...
Initialization step preparing the arguments for the first iteration of the loop body. Args: x_init: Initial solution guess $x_0$. base_value: Value $f(x')$ at $x = x'$. target_value: Value $f(x_0)$ at $x = x_0$. estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None. Returns: Initial arguments for tf_st...
codesearchnet
def split(self): ranges = [] for bound in self.bounds: range = VersionRange(None) range.bounds = [bound] ranges.append(range) return ranges
Split into separate contiguous ranges. Returns: A list of VersionRange objects. For example, the range "3|5+" will be split into ["3", "5+"].
codesearchnet
def MakeZip(self, input_dir, output_file): logging.info("Generating zip template file at %s", output_file) basename, _ = os.path.splitext(output_file) shutil.make_archive( basename, "zip", base_dir=".", root_dir=input_dir, verbose=True)
Creates a ZIP archive of the files in the input directory. Args: input_dir: the name of the input directory. output_file: the name of the output ZIP archive without extension.
juraj-google-style
def sheets_tab_id(config, auth, sheet_url_or_name, sheet_tab): sheet_id = None tab_id = None spreadsheet = sheets_get(config, auth, sheet_url_or_name) if spreadsheet: sheet_id = spreadsheet['spreadsheetId'] for tab in spreadsheet.get('sheets', []): if tab['properties']['title...
Pull sheet tab id from URL, name, or id itself. Args: config - see starthinker/util/configuration.py auth - user or service url_or_name - one of: URL, document title, or id sheet_tab - name of tab to get id for Returns: Pair of sheet id and tab id.
github-repos
def locked_get(self): credentials = None if self._cache: json = self._cache.get(self._key_name) if json: credentials = client.Credentials.new_from_json(json) if (credentials is None): entity = self._get_entity() if (entity is not None): credentials = g...
Retrieve Credential from datastore. Returns: oauth2client.Credentials
codesearchnet
def _count_nonzero(input_tensor, dtype=dtypes.int64): with ops.name_scope('count_nonzero', values=[input_tensor]): zero = array_ops.zeros([], dtype=input_tensor.dtype) nonzero_count = math_ops.reduce_sum(math_ops.cast(math_ops.not_equal(input_tensor, zero), dtype=dtype), name='nonzero_count') ...
Same as math_ops.count_nonzero. The reduction is done in dtype, which can be faster for 32-bit dtypes. Args: input_tensor: numeric tensor dtype: reduction dtype Returns: number of nonzero values with type dtype
github-repos
def one_hot_encoding(labels, num_classes, scope=None): with tf.name_scope(scope, 'OneHotEncoding', [labels]): batch_size = labels.get_shape()[0] indices = tf.expand_dims(tf.range(0, batch_size), 1) labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype) concated = tf.concat(axis=1...
Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels.
codesearchnet
def db_en010(self, value=None): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `db_en010`'.format(value)) self._db_en010 = value
Corresponds to IDD Field `db_en010` mean coincident dry-bulb temperature to Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `db_en010` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Rais...
codesearchnet
def fold_point(p, lattice, coords_are_cartesian=False): if coords_are_cartesian: p = lattice.get_fractional_coords(p) else: p = np.array(p) p = ((np.mod(((p + 0.5) - 1e-10), 1) - 0.5) + 1e-10) p = lattice.get_cartesian_coords(p) closest_lattice_point = None smallest_distance = 10...
Folds a point with coordinates p inside the first Brillouin zone of the lattice. Args: p: coordinates of one point lattice: Lattice object used to convert from reciprocal to cartesian coordinates coords_are_cartesian: Set to True if you are providing coordinates in cartesian coordinates. Defaults to False. Returns: T...
codesearchnet
def __init__(self, resolver_context): super(VShadowFileSystem, self).__init__(resolver_context) self._file_object = None self._vshadow_volume = None
Initializes a file system. Args: resolver_context (Context): resolver context.
juraj-google-style
def GetEntries(self, parser_mediator, match=None, **unused_kwargs): stores = match.get('Stores', {}) for volume_name, volume in iter(stores.items()): datetime_value = volume.get('CreationDate', None) if not datetime_value: continue partial_path = volume['PartialPath'] even...
Extracts relevant Volume Configuration Spotlight entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
juraj-google-style
async def update_server_data(server): data = datatools.get_data() send_welcome_message = False if server.id not in data["discord"]["servers"]: logger.debug("Adding new server to serverdata") data["discord"]["servers"][server.id] = {"prefix": "!"} if "mute_intro" not in dat...
Updates the server info for the given server Args: server: The Discord server to update info for
juraj-google-style
def release(self): if not self.acquired: return False os.close(self.fd) if os.path.exists(self.path): os.remove(self.path) self.acquired = False return True
Cleans up the lockfile if it was acquired. Args: self (JLock): the ``JLock`` instance Returns: ``False`` if the lock was not released or the lock is not acquired, otherwise ``True``.
juraj-google-style
def scan_message(self, message, regex): for line in message.split('\n'): if bool(re.search(regex, line, flags=(re.IGNORECASE | re.MULTILINE))): return line return ''
Scans regex from msg and returns the line that matches Keyword arguments: message -- A (long) string, e.g. email body that will be scanned. regex -- A regular expression string that the message will be scanned against. Returns: Matching line or empty string
codesearchnet
def join(self, *args, **kwargs): super(ThreadReturn, self).join(*args, **kwargs) return self._return
Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread.
codesearchnet
def get_type(name, env, non_generic): if name in env: if isinstance(env[name], MultiType): return clone(env[name]) return fresh(env[name], non_generic) else: print("W: Undefined symbol {0}".format(name)) return TypeVariable()
Get the type of identifier name from the type environment env. Args: name: The identifier name env: The type environment mapping from identifier names to types non_generic: A set of non-generic TypeVariables Raises: ParseError: Raised if name is an undefined symbol in the type environment.
juraj-google-style
def generate(passphrase, trees=['primary']): (seeds, multi_wallet) = MultiWallet.generate(trees, entropy=True) result = {} for tree in trees: result[tree] = dict(private_seed=seeds[tree], public_seed=multi_wallet.public_wif(tree), encrypted_seed=PassphraseBox.encrypt(passphrase, seeds[tree])) re...
Generate a seed for the primary tree of a Gem wallet. You may choose to store the passphrase for a user so the user doesn't have to type it in every time. This is okay (although the security risks should be obvious) but Gem strongly discourages storing even the encrypted private seed, and storing both the passphrase a...
codesearchnet
def binary_n(total_N, min_n=50): max_exp = np.log2(((1.0 * total_N) / min_n)) max_exp = int(np.floor(max_exp)) return [int(np.floor(((1.0 * total_N) / (2 ** i)))) for i in range(1, (max_exp + 1))]
Creates a list of values by successively halving the total length total_N until the resulting value is less than min_n. Non-integer results are rounded down. Args: total_N (int): total length Kwargs: min_n (int): minimal length after division Returns: list of integers: total_N/2, total_N/4, total_N/8, ... until tota...
codesearchnet
def merge_all_summaries(key=ops.GraphKeys.SUMMARIES): summary_ops = ops.get_collection(key) if not summary_ops: return None else: return merge_summary(summary_ops)
Merges all summaries collected in the default graph. This op is deprecated. Please switch to tf.compat.v1.summary.merge_all, which has identical behavior. Args: key: `GraphKey` used to collect the summaries. Defaults to `GraphKeys.SUMMARIES`. Returns: If no summaries were collected, returns None. Otherwise returns...
github-repos
def _maybe_download_corpora(tmp_dir, dataset_split): cnn_filename = 'cnn_stories.tgz' cnn_finalpath = os.path.join(tmp_dir, 'cnn/stories/') dailymail_filename = 'dailymail_stories.tgz' dailymail_finalpath = os.path.join(tmp_dir, 'dailymail/stories/') if (not tf.gfile.Exists(cnn_finalpath)): ...
Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. dataset_split: whether we're in train/dev/test mode. Returns: List of all files generated and path to file containing train/dev/test split info.
codesearchnet
def validate(self): if (not isinstance(self.value, bytes)): raise TypeError('opaque value must be bytes') elif (not isinstance(self.opaque_type, enums.OpaqueDataType)): raise TypeError('opaque data type must be an OpaqueDataType enumeration') name_count = len(self.names) for i in range(n...
Verify that the contents of the OpaqueObject are valid. Raises: TypeError: if the types of any OpaqueObject attributes are invalid.
codesearchnet
def _upload_artifacts_to_path(self, mirror=False): if ((not os.listdir(self.artifact_path)) or (not self.artifact_path)): raise S3ArtifactNotFound uploaded = False if self.s3props.get('content_metadata'): LOG.info('Uploading in multiple parts to set metadata') uploaded = self.content...
Recursively upload directory contents to S3. Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version.
codesearchnet
def from_file(cls, path, directory=None, modules=None, active=None): name = basename(path) if name.endswith('.rpp'): name = name[:(- 4)] lines = _repp_lines(path) directory = (dirname(path) if (directory is None) else directory) r = cls(name=name, modules=modules, active=active) _parse_r...
Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name...
codesearchnet
def delete(script, layer_num=None): filter_xml = ' <filter name="Delete Current Mesh"/>\n' if isinstance(script, mlx.FilterScript): if (layer_num is None) or (layer_num == script.current_layer()): util.write_filter(script, filter_xml) script.del_layer(script.current_layer()...
Delete layer Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to delete. Default is the current layer. Not supported on the file base API. Layer stack: Deletes a layer will change current layer if deleted layer is lower in the stack MeshLab...
juraj-google-style
def post_command(self, command, args): self._loop.log_coroutine(self.send_command(command, args, Verifier()))
Post a command asynchronously and don't wait for a response. There is no notification of any error that could happen during command execution. A log message will be generated if an error occurred. The command's response is discarded. This method is thread-safe and may be called from inside or ouside of the backgrou...
codesearchnet
def change(script, layer_num=None): if layer_num is None: if isinstance(script, mlx.FilterScript): layer_num = script.last_layer() else: layer_num = 0 filter_xml = ''.join([ ' <filter name="Change the current layer">\n', ' <Param name="mesh" ', ...
Change the current layer by specifying the new layer number. Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to change to. Default is the last layer if script is a mlx.FilterScript object; if script is a filename the default is the first lay...
juraj-google-style
def push(self, x): self._queue.append(x)
Adds a new value to the data window. Args: x: The value to be added to the window.
github-repos
def _shuffle_single(fname, extra_fn=None): records = read_records(fname) random.shuffle(records) if (extra_fn is not None): records = extra_fn(records) out_fname = fname.replace(UNSHUFFLED_SUFFIX, '') write_records(records, out_fname) tf.gfile.Remove(fname)
Shuffle a single file of records. Args: fname: a string extra_fn: an optional function from list of TFRecords to list of TFRecords to be called after shuffling.
codesearchnet
def poll(self, timeout=None): p = select.poll() p.register(self._fd, select.POLLIN | select.POLLPRI) events = p.poll(int(timeout * 1000)) if len(events) > 0: return True return False
Poll for data available for reading from the serial port. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Default is a blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if data is available for...
juraj-google-style
def update_variant_compounds(self, variant, variant_objs = None): compound_objs = [] for compound in variant.get('compounds', []): not_loaded = True gene_objs = [] if variant_objs: variant_obj = variant_objs.get(compound['variant'...
Update compounds for a variant. This will add all the necessary information of a variant on a compound object. Args: variant(scout.models.Variant) variant_objs(dict): A dictionary with _ids as keys and variant objs as values. Returns: compound_objs(list(dict)): A dictionary with updated compound objects.
juraj-google-style
def einsum_vecmul_index(gate_indices, number_of_qubits): (mat_l, mat_r, tens_lin, tens_lout) = _einsum_matmul_index_helper(gate_indices, number_of_qubits) return ('{mat_l}{mat_r}, '.format(mat_l=mat_l, mat_r=mat_r) + '{tens_lin}->{tens_lout}'.format(tens_lin=tens_lin, tens_lout=tens_lout))
Return the index string for Numpy.eignsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indice...
codesearchnet
def is_dsub_operation(op): if not is_pipeline(op): return False for name in ['dsub-version', 'job-id', 'job-name', 'user-id']: if not get_label(op, name): return False return True
Determine if a pipelines operation is a dsub request. We don't have a rigorous way to identify an operation as being submitted by dsub. Our best option is to check for certain fields that have always been part of dsub operations. - labels: job-id, job-name, and user-id have always existed. The dsub-version label has ...
juraj-google-style
def get_export_outputs(export_outputs, predictions): if export_outputs is None: default_output = export_output_lib.PredictOutput(predictions) export_outputs = {signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: default_output} if not isinstance(export_outputs, dict): raise TypeError(...
Validate export_outputs or create default export_outputs. Args: export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict or None. predictions: Predictions `Tensor` or dict of `Tensor`. Returns: Valid export_outputs dict Raises: TypeError: if export_out...
github-repos
def set_timer(self, num_secs): status = self.status() devices = status['dps'] devices_numbers = list(devices.keys()) devices_numbers.sort() dps_id = devices_numbers[-1] payload = self.generate_payload(SET, {dps_id:num_secs}) data = se...
Set a timer. Args: num_secs(int): Number of seconds
juraj-google-style
def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO: sx, sz = size rx, rz = resolution dx, dz = sx / rx, sz / rz ox, oz = -sx / 2, -sz / 2 def gen_pos(): for z in range(rz): for x in range(rx): yield ox + x * dx yield 0 ...
Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO` instance
juraj-google-style
def log2(x): if any_symbolic_tensors((x,)): return Log2().symbolic_call(x) return backend.numpy.log2(x)
Base-2 logarithm of `x`, element-wise. Args: x: Input tensor. Returns: Output tensor, element-wise base-2 logarithm of `x`.
github-repos
def _ProcessEvent(self, mediator, event): try: self._analysis_plugin.ExamineEvent(mediator, event) except Exception as exception: self.SignalAbort() if self._debug_output: logger.warning('Unhandled exception while processing event object.') logger.exception(except...
Processes an event. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event.
codesearchnet
def get_default_padding(self): high = ((1024 * 10) + (self.size low = (1024 + (self.size if (self.padding >= 0): if (self.padding > high): return low return self.padding else: return low
The default implementation which tries to select a reasonable amount of padding and which might change in future versions. Returns: int: Amount of padding after saving
codesearchnet
def get_definition_directive(self, node, directive, arg, default): defs = anno.getanno(node, anno.Static.ORIG_DEFINITIONS, ()) if not defs: return default arg_values_found = [] for def_ in defs: if directive in def_.directives and arg in def_.directives[directive]: arg_values...
Returns the unique directive argument for a symbol. See lang/directives.py for details on directives. Example: # Given a directive in the code: ag.foo_directive(bar, baz=1) # One can write for an AST node Name(id='bar'): get_definition_directive(node, ag.foo_directive, 'baz') Args: node: ast.AST, the node represent...
github-repos
def integers(start, count): if count < 0: raise ValueError("integers() count cannot be negative") return query(irange(start, start + count))
Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the specified range of integers. Raises: ValueError: If count is negative.
juraj-google-style
def find(self, id): url = "{}/{}/{}".format(__endpoint__, self.type.RESOURCE, id) response = RestClient.get(url)[self.type.RESOURCE[:-1]] return self.type(response)
Get a resource by its id Args: id (string): Resource id Returns: object: Instance of the resource type
juraj-google-style
def call(self, inputs, **kwargs): return inputs
This is where the layer's logic lives. Args: inputs: Input tensor, or list/tuple of input tensors. **kwargs: Additional keyword arguments. Returns: A tensor or list/tuple of tensors.
github-repos
def status(self, job_ids): if job_ids: self._status() return [self.resources[jid]['status'] for jid in job_ids]
Get the status of a list of jobs identified by the job identifiers returned from the submit request. Args: - job_ids (list) : A list of job identifiers Returns: - A list of status from ['PENDING', 'RUNNING', 'CANCELLED', 'COMPLETED', 'FAILED', 'TIMEOUT'] corresponding to each job_id in the job_ids list. Raises: - Ex...
juraj-google-style
def verify_abort(func, *args, **kwargs): expected_exception = kwargs.pop("expected_exception", runez.system.AbortException) with CaptureOutput() as logged: try: value = func(*args, **kwargs) assert False, "%s did not raise, but returned %s" % (func, value) except ex...
Convenient wrapper around functions that should exit or raise an exception Example: assert "Can't create folder" in verify_abort(ensure_folder, "/dev/null/not-there") Args: func (callable): Function to execute *args: Args to pass to 'func' **kwargs: Named args to pass to 'func' Returns: (str): Chatter from call to '...
juraj-google-style
def prepare_background_data(self): self.background_data = [] background_dir = os.path.join(self.data_dir, BACKGROUND_NOISE_DIR_NAME) if not gfile.Exists(background_dir): return self.background_data with tf.compat.v1.Session(graph=tf.Graph()) as sess: wav_filename_placeholder = tf.compat....
Searches a folder for background noise audio, and loads it into memory. It's expected that the background audio samples will be in a subdirectory named '_background_noise_' inside the 'data_dir' folder, as .wavs that match the sample rate of the training data, but can be much longer in duration. If the '_background_n...
github-repos
def load_file_to_str(path): with open(path, 'rt') as f: string = f.read().replace(linesep, '') if (not string): raise LoadError(('%s file is empty!' % path)) return string
Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file
codesearchnet
def sort_dependencies(self, image, dependencies=None): if (dependencies is None): dependencies = OrderedDict() if (image in dependencies): return requires = self.ymldefs[image].get('requires', []) for dep in requires: self.sort_dependencies(dep, dependencies) dependencies[ima...
Topologically sort the docker commands by their requirements Note: Circular "requires" dependencies are assumed to have already been checked in get_external_base_image, they are not checked here Args: image (str): process this docker image's dependencies dependencies (OrderedDict): running cache of sorted dependencie...
codesearchnet
def histogram(self, tag, values, bins, step=None): if (step is None): step = self._step else: self._step = step values = onp.array(values) bins = onp.array(bins) values = onp.reshape(values, (- 1)) (counts, limits) = onp.histogram(values, bins=bins) cum_counts = onp.cumsum(on...
Saves histogram of values. Args: tag: str: label for this data values: ndarray: will be flattened by this routine bins: number of bins in histogram, or array of bins for onp.histogram step: int: training step
codesearchnet
def __replaceSpecialValues(self, decisions): error = [] for (row, line) in enumerate(decisions): if ('.' in line): for (i, element) in enumerate(line): if (row == 0): error.append("Row: {}colume: {}==> don't have parent value".format(str(row).ljust(4), str...
Will replace special values in decisions array. Args: decisions (array of array of str): Standard decision array format. Raises: ValueError: Row element don't have parent value. Returns: New decision array with updated values.
codesearchnet
def iter_archive(self, resource): if isinstance(resource, six.string_types): resource = resource_lib.Resource(path=resource) return extractor.iter_archive(resource.path, resource.extract_method)
Returns iterator over files within archive. **Important Note**: caller should read files as they are yielded. Reading out of order is slow. Args: resource: path to archive or `tfds.download.Resource`. Returns: Generator yielding tuple (path_within_archive, file_obj).
juraj-google-style
def _flatten_tensors(tensors): if not tensors: raise ValueError('tensors cannot be empty') shape = tensors[0].shape for tensor in tensors: shape = shape.merge_with(tensor.shape) if not shape.is_fully_defined(): raise ValueError('Tensors must have statically known shape.') if ...
Check tensors for isomorphism and flatten. Args: tensors: list of `tf.Tensor` which must all have the same shape. Returns: tensors: a list of `tf.Tensor` which are flattened (1D) views of tensors shape: the original shape of each element of input tensors Raises: ValueError: tensors are empty or non-isomorphic or hav...
github-repos
def get_kerberos_ticket(username, password): cache = ('/tmp/ion-%s' % uuid.uuid4()) logger.debug("Setting KRB5CCNAME to 'FILE:{}'".format(cache)) os.environ['KRB5CCNAME'] = ('FILE:' + cache) try: realm = settings.CSL_REALM kinit = pexpect.spawnu('/usr/bin/kinit {}@{}'.format(username, re...
Attempts to create a Kerberos ticket for a user. Args: username The username. password The password. Returns: Boolean indicating success or failure of ticket creation
codesearchnet
def post_process(self, dir_name, d): logger.info('Post-processing dir:{}'.format(dir_name)) fullpath = os.path.abspath(dir_name) transformations = {} filenames = glob.glob(os.path.join(fullpath, 'transformations.json*')) if (len(filenames) >= 1): with zopen(filenames[0], 'rt') as f: ...
Simple post-processing for various files other than the vasprun.xml. Called by generate_task_doc. Modify this if your runs have other kinds of processing requirements. Args: dir_name: The dir_name. d: Current doc generated.
codesearchnet
def argsort(*args, **kwargs): if ((len(args) == 1) and isinstance(args[0], dict)): dict_ = args[0] index_list = list(dict_.keys()) value_list = list(dict_.values()) return sortedby2(index_list, value_list) else: index_list = list(range(len(args[0]))) return sorted...
like np.argsort but for lists Args: *args: multiple lists to sort by **kwargs: reverse (bool): sort order is descending if True else acscending CommandLine: python -m utool.util_list argsort Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100}) >...
codesearchnet
def items(self, prefix=None, delimiter=None): return _item.Items(self._name, prefix, delimiter, context=self._context)
Get an iterator for the items within this bucket. Args: prefix: an optional prefix to match items. delimiter: an optional string to simulate directory-like semantics. The returned items will be those whose names do not contain the delimiter after the prefix. For the remaining items, the names will be returned truncate...
codesearchnet
def add_primitives_path(path): if (path not in _PRIMITIVES_PATHS): if (not os.path.isdir(path)): raise ValueError('Invalid path: {}'.format(path)) LOGGER.debug('Adding new primitives path %s', path) _PRIMITIVES_PATHS.insert(0, os.path.abspath(path))
Add a new path to look for primitives. The new path will be inserted in the first place of the list, so any primitive found in this new folder will take precedence over any other primitive with the same name that existed in the system before. Args: path (str): path to add Raises: ValueError: A `ValueError` will be r...
codesearchnet
def zero_state(self, batch_size, dtype): state_size = self.state_size is_eager = context.executing_eagerly() if is_eager and _hasattr(self, '_last_zero_state'): last_state_size, last_batch_size, last_dtype, last_output = getattr(self, '_last_zero_state') if last_batch_size == batch_size and ...
Return zero-filled state tensor(s). Args: batch_size: int, float, or unit Tensor representing the batch size. dtype: the data type to use for the state. Returns: If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is...
github-repos
def clean_headers(headers): clean = {} try: for (k, v) in six.iteritems(headers): if (not isinstance(k, six.binary_type)): k = str(k) if (not isinstance(v, six.binary_type)): v = str(v) clean[_helpers._to_bytes(k)] = _helpers._to_bytes(...
Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary o...
codesearchnet
def _get_linear_trajectory(x0, velocity, t): x0 = tf.convert_to_tensor(x0) velocity = tf.convert_to_tensor(velocity) t = tf.convert_to_tensor(t) if (x0.shape.ndims != 1): raise ValueError('x0 must be a rank 1 tensor') if (velocity.shape.ndims != 1): raise ValueError('velocity must be...
Construct a linear trajectory from x0. Args: x0: N-D float tensor. velocity: N-D float tensor t: [sequence_length]-length float tensor Returns: x: [sequence_length, ndims] float tensor.
codesearchnet
def get_item(self, *key): item = self._get_item_or_section(key) if not item.is_item: raise RuntimeError('{} is a section, not an item'.format(key)) return item
The recommended way of retrieving an item by key when extending configmanager's behaviour. Attribute and dictionary key access is configurable and may not always return items (see PlainConfig for example), whereas this method will always return the corresponding Item as long as NOT_FOUND hook callbacks don't break this...
juraj-google-style
def export_msdt(self, filename): fmt = ('csv' if filename.lower().endswith('.csv') else 'dat') delimiter = (', ' if (fmt == 'csv') else ' ') with open(filename, 'wt') as f: if (fmt == 'dat'): f.write(' f.write(delimiter.join(['t', 'MSD', 'MSD_a', 'MSD_b', 'MSD_c', 'MSCD'])) ...
Writes MSD data to a csv file that can be easily plotted in other software. Args: filename (str): Filename. Supported formats are csv and dat. If the extension is csv, a csv file is written. Otherwise, a dat format is assumed.
codesearchnet
def convert_to_shape(x): if (x is None): return None if isinstance(x, Shape): return x if isinstance(x, str): x = _parse_string_to_list_of_pairs(x, seconds_to_int=True) return Shape(x)
Converts input to a Shape. Args: x: Shape, str, or None. Returns: Shape or None. Raises: ValueError: If x cannot be converted to a Shape.
codesearchnet
def _ReduceParserFilters(cls, includes, excludes): if ((not includes) or (not excludes)): return for parser_name in set(includes).intersection(excludes): if (includes[parser_name] == excludes[parser_name]): logger.warning('Parser {0:s} was in both the inclusion and exclusion lists. I...
Reduces the parsers and plugins to include and exclude. If an intersection is found, the parser or plugin is removed from the inclusion set. If a parser is not in inclusion set there is no need to have it in the exclusion set. Args: includes (dict[str, BaseParser]): included parsers and plugins by name. excludes (dic...
codesearchnet
def playback_trajectory(env, ep_dir): xml_path = os.path.join(ep_dir, "model.xml") with open(xml_path, "r") as f: env.reset_from_xml_string(f.read()) state_paths = os.path.join(ep_dir, "state_*.npz") t = 0 for state_file in sorted(glob(state_paths)): print(state_fil...
Playback data from an episode. Args: ep_dir: The path to the directory containing data for an episode.
juraj-google-style
def remove_node(self, node_id, force=False): url = self._url('/nodes/{0}', node_id) params = {'force': force} res = self._delete(url, params=params) self._raise_for_status(res) return True
Remove a node from the swarm. Args: node_id (string): ID of the node to be removed. force (bool): Force remove an active node. Default: `False` Raises: :py:class:`docker.errors.NotFound` If the node referenced doesn't exist in the swarm. :py:class:`docker.errors.APIError` If the server returns an error. Returns: `Tr...
codesearchnet
def from_dict(d): i = Tags() for k, v in d.items(): if k not in ("@module", "@class"): i[k] = v return i
Creates Tags object from a dictionary. Args: d: Dict of feff parameters and values. Returns: Tags object
juraj-google-style
def _get_ngram_counter(ids, n): ids = [token_id for token_id in ids if (token_id != 0)] ngram_list = [tuple(ids[i:(i + n)]) for i in range(((len(ids) + 1) - n))] ngrams = set(ngram_list) counts = collections.Counter() for ngram in ngrams: counts[ngram] = 1 return counts
Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values.
codesearchnet
def first(self): def _transform(xs): try: return [six.next(iter(xs))] except StopIteration: return [] return self.transform(_transform, 'first')
Return a Query that selects only the first element of this Query. If no elements are available, returns a query with no results. Example usage: .. code:: python >> q = Query(lambda: list(range(5))) >> q.first.results [0] Returns: Query
codesearchnet
def _define_loop(graph, eval_steps): loop = tools.Loop( None, graph.step, graph.should_log, graph.do_report, graph.force_reset) loop.add_phase( 'eval', graph.done, graph.score, graph.summary, eval_steps, report_every=eval_steps, log_every=None, checkpoint_every=None, feed={gra...
Create and configure an evaluation loop. Args: graph: Object providing graph elements via attributes. eval_steps: Number of evaluation steps per epoch. Returns: Loop object.
juraj-google-style
def option(self, key, value=None, **kwargs): if (not isinstance(self._container, Section)): raise ValueError('Options can only be added inside a section!') option = Option(key, value, container=self._container, **kwargs) option.value = value self._container.structure.insert(self._idx, option) ...
Creates a new option inside a section Args: key (str): key of the option value (str or None): value of the option **kwargs: are passed to the constructor of :class:`Option` Returns: self for chaining
codesearchnet
def _reraise_with_traceback(f): def wrap(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: traceback_str = traceback.format_exc() e.traceback = traceback_str raise e return wrap
Call the function normally. But if the function raises an error, attach the str(traceback) into the function.traceback attribute, then reraise the error. Args: f: The function to run. Returns: A function that wraps f, attaching the traceback if an error occurred.
juraj-google-style
def diff_commonPrefix(self, text1, text2): if not text1 or not text2 or text1[0] != text2[0]: return 0 pointermin = 0 pointermax = min(len(text1), len(text2)) pointermid = pointermax pointerstart = 0 while pointermin < pointermid: if text1[pointerstart:pointermid]...
Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string.
juraj-google-style
def postprocess_image(x, rows, cols, hparams): batch = common_layers.shape_list(x)[0] x = tf.reshape(x, [batch, rows, cols, hparams.hidden_size]) likelihood = getattr(hparams, 'likelihood', DistributionType.CAT) if (likelihood == DistributionType.DMOL): depth = (hparams.num_mixtures * 10) ...
Postprocessing after decoding. Args: x: Tensor of shape [batch, ...], where ... can be any rank such that the number of elements in x is batch * rows * cols * hparams.hidden_size. rows: Integer representing number of rows in a 2-D data point. cols: Integer representing number of columns in a 2-D data point. hparams: H...
codesearchnet
def enable(self, information, id_or_uri, timeout=(- 1)): uri = self._client.build_uri(id_or_uri) return self._client.update(information, uri, timeout=timeout)
Enables or disables a range. Args: information (dict): Information to update. id_or_uri: ID or URI of range. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated resource.
codesearchnet
def cosine_similarity(y_true, y_pred, axis=-1): y_pred = ops.convert_to_tensor(y_pred) y_true = ops.convert_to_tensor(y_true, dtype=y_pred.dtype) y_true, y_pred = squeeze_or_expand_to_same_rank(y_true, y_pred) y_pred = normalize(y_pred, axis=axis) y_true = normalize(y_true, axis=axis) return ops...
Computes the cosine similarity between labels and predictions. Formula: ```python loss = sum(l2_norm(y_true) * l2_norm(y_pred)) ``` Args: y_true: Tensor of true targets. y_pred: Tensor of predicted targets. axis: Axis along which to determine similarity. Defaults to `-1`. Returns: Cosine similarity tensor. Example...
github-repos
def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes: return self.mglo.read(viewport, components, attachment, alignment, dtype)
Read the content of the framebuffer. Args: viewport (tuple): The viewport. components (int): The number of components to read. Keyword Args: attachment (int): The color attachment. alignment (int): The byte alignment of the pixels. dtype (str): Data type. Returns: bytes
codesearchnet
def get_outputs_filtered(self, owner, spent=None): outputs = self.fastquery.get_outputs_by_public_key(owner) if spent is None: return outputs elif spent is True: return self.fastquery.filter_unspent_outputs(outputs) elif spent is False: return...
Get a list of output links filtered on some criteria Args: owner (str): base58 encoded public_key. spent (bool): If ``True`` return only the spent outputs. If ``False`` return only unspent outputs. If spent is not specified (``None``) return all outputs. Returns: :obj:`list` of TransactionLink: list of ``txid`` s and...
juraj-google-style
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]]=None): if tensor_type is None: return self is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type) for key, value in self.items(): try: if not is_tensor(value): tensor = as_tensor(va...
Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If `None`, no modification is done.
github-repos
def joinpaths(self, *paths): if sys.version_info >= (3, 6): paths = [os.fspath(path) for path in paths] if len(paths) == 1: return paths[0] if self.is_windows_fs: return self._join_paths_with_drive_support(*paths) joined_path_segments = [] ...
Mimic os.path.join using the specified path_separator. Args: *paths: (str) Zero or more paths to join. Returns: (str) The paths joined by the path separator, starting with the last absolute path in paths.
juraj-google-style
def requires(self, require=None): if require is None: return self._requires if not isinstance(require, dict): raise ValueError('__require__') for k,v in iteritems(require): if k not in self._nodes: raise ValueError('__require__[%s]' % str(k)) if isinstance(v, basestring): ...
Requires Sets the require rules used to validate the Parent Arguments: require {dict} -- A dictionary expressing requirements of fields Raises: ValueError Returns: None
juraj-google-style
def ip_mask(ip_addr_and_mask, return_tuple=True): regex_ip_and_mask = __re.compile("^((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))/((3[0-2...
Function to check if a address and CIDR mask is good Args: ip_addr_and_mask: IP address and mask in the following format 192.168.1.1/24 return_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False Returns: see return_tuple for return options
juraj-google-style
def set_weights(self, weights): params = self.weights if len(params) != len(weights): raise ValueError('Length of the specified weight list (' + str(len(weights)) + ') does not match the number of weights of the optimizer (' + str(len(params)) + ')') weight_value_tuples = [] param_values = backe...
Sets the weights of the optimizer, from Numpy arrays. Should only be called after computing the gradients (otherwise the optimizer has no weights). Args: weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the optimizer (i.e. it should match the ...
github-repos
def get_inst_info(qry_string): qry_prefix = "EC2C.describe_instances(" qry_real = qry_prefix + qry_string + ")" qry_results = eval(qry_real) return qry_results
Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict): raw information returned from AWS.
juraj-google-style
def is_scalar(value): return (np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0)))
Test if the given value is a scalar. This function also works with memory mapped array values, in contrast to the numpy is_scalar method. Args: value: the value to test for being a scalar value Returns: boolean: if the given value is a scalar or not
codesearchnet
def _obj_to_path(obj): if obj is None: return obj if inspect.isclass(obj) or inspect.isfunction(obj): fetched = getattr(sys.modules[obj.__module__], obj.__name__, None) if fetched is None: raise ValueError( "Object %r must be defined on the top level of a module." % obj) return "...
Returns the fully qualified path to the object. Args: obj: obj must be a new style top level class, or a top level function. No inner function or static method. Returns: Fully qualified path to the object. Raises: TypeError: when argument obj has unsupported type. ValueError: when obj can't be discovered on the top ...
juraj-google-style
def get_sequence_length_feature_key_name_from_feature_key_name(feature_name): return feature_name + _SEQUENCE_FEATURE_LENGTH_POSTFIX
Gets the name of the sequence length feature from that of the base feature. Args: feature_name: The feature key of a sequence column. Returns: A string which is the feature key for the associated feature length column.
github-repos
def _output_dir( self, ext, is_instance=False, interpolatable=False, autohinted=False, is_variable=False, ): assert not (is_variable and any([is_instance, interpolatable])) if is_variable: dir_prefix = "variable_" ...
Generate an output directory. Args: ext: extension string. is_instance: The output is instance font or not. interpolatable: The output is interpolatable or not. autohinted: The output is autohinted or not. is_variable: The output is variable font or not. Return: output directory string.
juraj-google-style
def convert_elementwise_sub( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting elementwise_sub ...') model0 = layers[inputs[0]] model1 = layers[inputs[1]] if names == 'short': tf_name = 'S' + random_string(7) elif names == 'keep': tf_name = w_n...
Convert elementwise subtraction. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def _flag_value_as_list(self, wanted_flag_name): string_value_list = [] found, flag_value = self.get_flag_value(wanted_flag_name) if found: assert flag_value is not None string_value_list = flag_value.split(',') return string_value_list
Returns the string list of a TensorTracer flag. Args: wanted_flag_name: the name of the flag we are looking for. Returns: The list value of the flag.
github-repos
def map_shape_structure(func, structure): return tree_impl.map_shape_structure(func, structure)
Variant of keras.tree.map_structure that operates on shape tuples. Tuples containing ints and Nones are considered shapes and passed to `func`. Args: structure: Arbitrarily nested structure. Returns: The same structure with `func` applied.
github-repos
def detect_response_encoding(response, is_html=False, peek=131072): encoding = get_heading_encoding(response) encoding = wpull.string.detect_encoding( wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html ) _logger.debug(__('Got encoding: {0}', encoding)) retu...
Return the likely encoding of the response document. Args: response (Response): An instance of :class:`.http.Response`. is_html (bool): See :func:`.util.detect_encoding`. peek (int): The maximum number of bytes of the document to be analyzed. Returns: ``str``, ``None``: The codec name.
juraj-google-style
def _build_case(branch_index, branch_graphs, branch_inputs, name=None, lower_using_switch_merge=None): _make_indexed_slices_indices_types_match(_CASE, branch_graphs) _check_same_outputs(_CASE, branch_graphs) case_inputs = _make_inputs_match(branch_graphs, branch_inputs) stateful_ops = [] for bg in b...
Creates an `Case` op from `branch_index`, branch graphs and inputs. Note that this modifies `branch_graphs` to make the inputs match, and to output all intermediates values so they're available for the gradient computation. `branch_graphs` need not have the same input types, but they must have the same output types. ...
github-repos
def Delete(self, request, global_params=None): config = self.GetMethodConfig('Delete') return self._RunMethod(config, request, global_params=global_params)
Delete an association between a GCP project and a GitHub Enterprise server. Args: request: (CloudbuildProjectsLocationsGithubEnterpriseConfigsDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Operation) The response message.
github-repos
def Process(self, parser_mediator, plist_name, top_level, **kwargs): if not plist_name.startswith(self.PLIST_PATH): raise errors.WrongPlistPlugin(self.NAME, plist_name) super(AppleAccountPlugin, self).Process( parser_mediator, plist_name=self.PLIST_PATH, top_level=top_level)
Check if it is a valid Apple account plist file name. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. plist_name (str): name of the plist. top_level (dict[str, object]): plist top-level key.
juraj-google-style
def _parse_ospf_process_id(self, config): match = re.search('^router ospf (\\d+)', config) return dict(ospf_process_id=int(match.group(1)))
Parses config file for the OSPF proc ID Args: config(str): Running configuration Returns: dict: key: ospf_process_id (int)
codesearchnet
def __init__(self, action, *, payload=None): self.action = action self.payload = payload if payload is not None else {} self.uid = uuid.uuid4()
Initialise the request object. Args: action (str): A string representing the requested action that should be executed by the server. payload (dict): A dictionary with data that is available to the action.
juraj-google-style
def replace_symbols(text, form='NFKD', excluded=None, replacement=''): if (excluded is None): excluded = set() categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So']) return ''.join(((c if ((unicodedata.category(c) not in categories) or (c in excluded)) else replacement) for c in unicodedata.normalize(form...
Replace symbols in text. Removes symbols from input text or replaces them with a string if specified. Args: text: The text to be processed. form: Unicode form. excluded: Set of unicode characters to exclude. replacement: New text that will replace symbols. Returns: The text without symbols.
codesearchnet
def pop(self, name, defval=None): valu = self.info.pop(name, defval) lkey = (self.pref + name.encode('utf8')) self.slab.pop(lkey, db=self.db) return valu
Pop a name from the SlabDict. Args: name (str): The name to remove. defval (obj): The default value to return if the name is not present. Returns: object: The object stored in the SlabDict, or defval if the object was not present.
codesearchnet