code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def getNext(self, dataset, requires_initialization=False, shared_name=None): def ta_wrapper(gn): def _wrapper(): r = gn() if isinstance(r, tensor_array_ops.TensorArray): return r.stack() else: return r return _wrapper if conte...
Returns a callable that returns the next element of the dataset. Example use: ```python # In both graph and eager modes dataset = ... get_next = self.getNext(dataset) result = self.evaluate(get_next()) ``` Args: dataset: A dataset whose elements will be returned. requires_initialization: Indicates that when the test ...
github-repos
def gray2bgr(img): img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image.
juraj-google-style
def monitoring(line, cell=None): parser = datalab.utils.commands.CommandParser(prog='monitoring', description=( 'Execute various Monitoring-related operations. Use "%monitoring ' '<command> -h" for help on a specific command.')) list_parser = parser.subcommand( 'list', 'List the metrics or res...
Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
juraj-google-style
def _build_request_factory(cls, session: AppSession): def request_factory(*args, **kwargs): request = session.factory.class_map['Request'](*args, **kwargs) user_agent = (session.args.user_agent or session.default_user_agent) request.fields['User-Agent'] = user_agent if session.args....
Create the request factory. A request factory is any callable object that returns a :class:`.http.Request`. The callable must accept the same arguments to Request. Returns: A callable object
codesearchnet
def get(self): if len(self._queue) == 0: return float('nan') with warnings.catch_warnings(record=False): warnings.simplefilter('ignore') return np.nanmean(self._queue)
Calculates and returns the mean of the current sliding window. Returns: float: The mean of the values in the current sliding window. Returns NaN if the window is empty.
github-repos
def save_graph(graph_str, dest_file, fmt=None, image_ratio=None): g = pydot.graph_from_dot_data(graph_str) if (fmt is None): fmt = (os.path.splitext(dest_file)[1].lower().strip('.') or 'png') if hasattr(g, ('write_' + fmt)): write_fn = getattr(g, ('write_' + fmt)) else: raise Exc...
Render a graph to an image file. Args: graph_str (str): Dot-language graph string. dest_file (str): Filepath to save the graph to. fmt (str): Format, eg "png", "jpg". image_ratio (float): Image ratio. Returns: String representing format that was written, such as 'png'.
codesearchnet
def scale(reader, writer, column, start, stop, multiple): for i, row in enumerate(reader): if i >= start and i <= stop: row[column] = type(multiple)(row[column]) * multiple writer.appendRecord(row)
Multiplies a value over a range of rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. column: The column of data to modify. start: The first row in the range to modify. end: The last row in the range to modify. multiple: The value to scale/multipl...
juraj-google-style
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id] if token_ids_1 is not None: output += token_ids_1 + [self.sep_token_id] return output
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A Funnel sequence has the following format: - single sequence: `[CLS] X [SEP]` - pair of sequences: `[CLS] A [SEP] B [SEP]` Args: token_ids_0 (`List[int]`): List of IDs to which the s...
github-repos
def StartProfiling(self, configuration, identifier, process_information): if not configuration: return if configuration.HaveProfileParsers(): identifier = '{0:s}-parsers'.format(identifier) self._cpu_time_profiler = profilers.CPUTimeProfiler( identifier, configuration) s...
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration. identifier (str): identifier of the profiling session used to create the sample filename. process_information (ProcessInfo): process information.
juraj-google-style
def _patch_expand_paths(self, settings, name, value): return [self._patch_expand_path(settings, name, item) for item in value]
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Returns: list: Patched path list to an absolute path.
juraj-google-style
def dbmin_mean(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 `dbmin_mean`'.format(value)) self._dbmi...
Corresponds to IDD Field `dbmin_mean` Mean of extreme annual minimum dry-bulb temperature Args: value (float): value for IDD Field `dbmin_mean` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
juraj-google-style
def __init__(self, receive_port, logdir, always_flush=False): debugger_directory = os.path.join( os.path.expanduser(logdir), constants.DEBUGGER_DATA_DIRECTORY_NAME) if not tf.io.gfile.exists(debugger_directory): try: ...
Receives health pills from a debugger and writes them to disk. Args: receive_port: The port at which to receive health pills from the TensorFlow debugger. logdir: The directory in which to write events files that TensorBoard will read. always_flush: A boolean indicating whether the EventsWriter will be flushed after e...
juraj-google-style
def add_graph(self, graph, global_step=None, graph_def=None): if graph is not None and graph_def is not None: raise ValueError('Please pass only graph, or graph_def (deprecated), but not both.') if isinstance(graph, ops.Graph) or isinstance(graph_def, ops.Graph): if not isinstance(graph, ops.Gra...
Adds a `Graph` to the event file. The graph described by the protocol buffer will be displayed by TensorBoard. Most users pass a graph in the constructor instead. Args: graph: A `Graph` object, such as `sess.graph`. global_step: Number. Optional global step counter to record with the graph. graph_def: DEPRECATED. Use...
github-repos
def _AddDependencyEdges(self, rdf_artifact): artifact_dependencies = artifact_registry.GetArtifactPathDependencies(rdf_artifact) if artifact_dependencies: for attribute in artifact_dependencies: self._AddEdge(attribute, rdf_artifact.name) else: self.reachable_nodes.add(rdf_artifa...
Add an edge for every dependency of the given artifact. This method gets the attribute names for a given artifact and for every attribute it adds a directed edge from the attribute node to the artifact node. If an artifact does not have any dependencies it is added to the set of reachable nodes. Args: rdf_artifact: T...
codesearchnet
def _serialize_linear_biases(linear, nodelist): linear_bytes = struct.pack(('<' + ('d' * len(linear))), *[linear[i] for i in nodelist]) return base64.b64encode(linear_bytes).decode('utf-8')
Serializes the linear biases. Args: linear: a interable object where linear[v] is the bias associated with v. nodelist (list): an ordered iterable containing the nodes. Returns: str: base 64 encoded string of little endian 8 byte floats, one for each of the biases in linear. Ordered according to nodelist. Examples: ...
codesearchnet
def setMeterPassword(self, new_pwd, pwd='00000000'): result = False self.setContext('setMeterPassword') try: if ((len(new_pwd) != 8) or (len(pwd) != 8)): self.writeCmdMsg('Passwords must be exactly eight characters.') self.setContext('') return result if (...
Serial Call to set meter password. USE WITH CAUTION. Args: new_pwd (str): 8 digit numeric password to set pwd (str): Old 8 digit numeric password. Returns: bool: True on completion with ACK.
codesearchnet
def write_filter(script, filter_xml): if isinstance(script, mlx.FilterScript): script.filters.append(filter_xml) elif isinstance(script, str): script_file = open(script, 'a') script_file.write(filter_xml) script_file.close() else: print(filter_xml) return None
Write filter to FilterScript object or filename Args: script (FilterScript object or filename str): the FilterScript object or script filename to write the filter to. filter_xml (str): the xml filter string
codesearchnet
def escalatee(self, main_type, sub_type, unique_id, escalatee_id, action='GET', params=None): params = params or {} url = '/v2/{}/{}/{}/escalatees/{}'.format(main_type, sub_type, unique_id, escalatee_id) if action == 'GET': return self.tcex.session.get(url, params=params) ...
Args: main_type: sub_type: unique_id: escalatee_id: action: params: Return:
juraj-google-style
def CacheFileSystem(self, path_spec, file_system): identifier = self._GetFileSystemCacheIdentifier(path_spec) self._file_system_cache.CacheObject(identifier, file_system)
Caches a file system object based on a path specification. Args: path_spec (PathSpec): path specification. file_system (FileSystem): file system object.
juraj-google-style
def concatenate(inputs, axis=-1, **kwargs): return Concatenate(axis=axis, **kwargs)(inputs)
Functional interface to the `Concatenate` layer. Args: inputs: A list of input tensors. axis: Concatenation axis. **kwargs: Standard layer keyword arguments. Returns: A tensor, the concatenation of the inputs alongside axis `axis`.
github-repos
def _build_watermark_updates(runner_execution_context: execution.FnApiRunnerExecutionContext, stage_inputs: Iterable[str], expected_timers: Iterable[translations.TimerFamilyId], pcolls_with_da: Set[str], transforms_w_splits: Set[str], watermarks_by_transform_and_timer_family: Dict[translations.TimerFamilyId, timestamp....
Builds a dictionary of PCollection (or TimerFamilyId) to timestamp. Args: stage_inputs: represent the set of expected input PCollections for a stage. These do not include timers. expected_timers: represent the set of TimerFamilyIds that the stage can expect to receive as inputs. pcolls_with_da: represent the set of st...
github-repos
def start_router(router_class, router_name): handle = router_class.remote(router_name) ray.experimental.register_actor(router_name, handle) handle.start.remote() return handle
Wrapper for starting a router and register it. Args: router_class: The router class to instantiate. router_name: The name to give to the router. Returns: A handle to newly started router actor.
codesearchnet
def authenticate_credentials(self, token): try: user_info = self.get_user_info(token) except UserInfoRetrievalFailed: msg = 'Failed to retrieve user info. Unable to authenticate.' logger.error(msg) raise exceptions.AuthenticationFailed(msg) ...
Validate the bearer token against the OAuth provider. Arguments: token (str): Access token to validate Returns: (tuple): tuple containing: user (User): User associated with the access token access_token (str): Access token Raises: AuthenticationFailed: The user is inactive, or retrieval of user info failed.
juraj-google-style
def get_angle_degrees(self, indices): coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[(indices.index, coords)].values b_pos = self.loc[(indices.loc[(:, 'b')], coords)].values a_pos = self.loc[(indices.loc[(:, 'a')], coords)].values else: indice...
Return the angles between given atoms. Calculates the angle in degrees between the atoms with indices ``i, b, a``. The indices can be given in three ways: * As simple list ``[i, b, a]`` * As list of lists: ``[[i1, b1, a1], [i2, b2, a2]...]`` * As :class:`pd.DataFrame` where ``i`` is taken from the index and ``b`` and...
codesearchnet
def forward(self, hidden_states: torch.Tensor, original_hidden_states: Optional[torch.Tensor]=None, layer_idx: Optional[int]=None, attention_mask: Optional[torch.Tensor]=None, causal_mask: Optional[torch.Tensor]=None, past_key_value: Optional[ZambaHybridDynamicCache]=None, output_attentions: Optional[bool]=False, use_c...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, sequence_length)` where padding elements are indicated by 0. past_key_value (`ZambaHybridDynamicCache`, *optional*): cached past key and ...
github-repos
def _in_place_subclassed_model_reset(model): assert not model._is_graph_network version_utils.swap_class(model.__class__, training.Model, training_v1.Model, ops.executing_eagerly_outside_functions()) attributes_cache = {} for name in dir(model): if name == 'submodules' or name == '_self_tracked_...
Substitute for model cloning that works for subclassed models. Subclassed models cannot be cloned because their topology is not serializable. To "instantiate" an identical model in a new TF graph, we reuse the original model object, but we clear its state. After calling this function on a model instance, you can use ...
github-repos
def position(self, partition): if not isinstance(partition, TopicPartition): raise TypeError('partition must be a TopicPartition namedtuple') assert self._subscription.is_assigned(partition), 'Partition is not assigned' offset = self._subscription.assignment[partition].posit...
Get the offset of the next record that will be fetched Arguments: partition (TopicPartition): Partition to check Returns: int: Offset
juraj-google-style
def notify( self, method_name: str, *args: Any, trim_log_values: Optional[bool] = None, validate_against_schema: Optional[bool] = None, **kwargs: Any ) -> Response: return self.send( Notification(method_name, *args, **kwargs), ...
Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_sche...
juraj-google-style
def tomography_data(results, name, tomoset): labels = tomography_circuit_names(tomoset, name) circuits = tomoset['circuits'] data = [] prep = None for j, _ in enumerate(labels): counts = marginal_counts(results.get_counts(labels[j]), tomoset['qubits']) ...
Return a results dict for a state or process tomography experiment. Args: results (Result): Results from execution of a process tomography circuits on a backend. name (string): The name of the circuit being reconstructed. tomoset (tomography_set): the dict of tomography configurations. Returns: list: A list of dicts ...
juraj-google-style
def as_matrix(self, depth=0): if (depth in self._matrix_cache): return self._matrix_cache[depth] self._matrix_cache[depth] = matrix = Matrix(self, depth=depth) return matrix
Create a matrix with self as node, cache it, return it. Args: depth (int): depth of the matrix. Returns: Matrix: an instance of Matrix.
codesearchnet
def DeregisterDefinition(self, data_type_definition): name = data_type_definition.name.lower() if (name not in self._definitions): raise KeyError('Definition not set for name: {0:s}.'.format(data_type_definition.name)) del self._definitions[name]
Deregisters a data type definition. The data type definitions are identified based on their lower case name. Args: data_type_definition (DataTypeDefinition): data type definition. Raises: KeyError: if a data type definition is not set for the corresponding name.
codesearchnet
def vibrational_free_energy(self, temperature, volume): y = self.debye_temperature(volume) / temperature return self.kb * self.natoms * temperature * ( 9./8. * y + 3 * np.log(1 - np.exp(-y)) - self.debye_integral(y))
Vibrational Helmholtz free energy, A_vib(V, T). Eq(4) in doi.org/10.1016/j.comphy.2003.12.001 Args: temperature (float): temperature in K volume (float) Returns: float: vibrational free energy in eV
juraj-google-style
def _inter_df_op_handler(self, func, other, **kwargs): axis = kwargs.get('axis', 0) axis = (pandas.DataFrame()._get_axis_number(axis) if (axis is not None) else 0) if isinstance(other, type(self)): return self._inter_manager_operations(other, 'outer', (lambda x, y: func(x, y, **kwargs))) else: ...
Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/scalar. other: The other Manager/scalar. Returns: New DataManager with new data and index.
codesearchnet
def __init__( self, name: str, dtype: type, unique: bool, validators: t.List[VALIDATOR_FUNCTION], recoders: t.List[RECODER_FUNCTION],) -> None: if validators is None: validators = [] if recoders is None: ...
Construct a new `Column` object. Args: name (str): The exact name of the column in a ``pd.DataFrame``. dtype (type): The type that each member of the recoded column must belong to. unique (bool): Whether values are allowed to recur in this column. validators (list): A list of validator functions. recoders (list): A li...
juraj-google-style
def select_top_predictions(self, predictions): scores = predictions.get_field('scores') keep = torch.nonzero((scores > self.confidence_threshold)).squeeze(1) predictions = predictions[keep] scores = predictions.get_field('scores') (_, idx) = scores.sort(0, descending=True) return predictions[idx...
Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. It should contain the field `scores`. Returns: prediction (BoxList): the detected objects. Additional informa...
codesearchnet
def stop(pid): if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
Shut down a specific process. Args: pid: the pid of the process to shutdown.
codesearchnet
def add_stream(self, stream, path, compress, flags): self.data_fileobj.seek(self.last_offset) if compress == 'bz2': stream = bz2_compress_stream(stream) elif compress == 'xz': stream = xz_compress_stream(stream) elif compress is None: pass ...
Add the contents of an iterable to the MAR file. Args: stream (iterable): yields blocks of data path (str): name of this file in the MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None. flags (int): permission of this file in the MAR file
juraj-google-style
def visualize_conv_activations(activation, name): import math with tf.name_scope(('visualize_act_' + name)): (_, h, w, c) = activation.get_shape().as_list() rows = [] c_per_row = int(math.sqrt(c)) for y in range(0, (c - c_per_row), c_per_row): row = activation[(:, :, ...
Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations
codesearchnet
def get_data(self, columns, type='ndarray', with_index=False): res = self.select_columns(columns) if type == 'ndarray': if with_index: return res.reset_index().values else: return res.values elif type == 'list': if wit...
获取不同格式的数据 Arguments: columns {[type]} -- [description] Keyword Arguments: type {str} -- [description] (default: {'ndarray'}) with_index {bool} -- [description] (default: {False}) Returns: [type] -- [description]
juraj-google-style
def _parse(json_str: str, primitive_cls: Type[Time]) -> Time: try: time = datetime.datetime.strptime(json_str, '%H:%M:%S').time() return _primitive_time_utils.build_time(time, _primitive_time_utils.TimePrecision.MICROSECOND.SECOND, primitive_cls) except ValueError: pass try: ...
Parses the json_str into a Time FHIR primitive. Args: json_str: The raw JSON string to parse. primitive_cls: The FHIR primitive to parse into. Returns: A FHIR primitive Time instance. Raises: fhir_errors.InvalidFhirError: In the event that no FHIR primitive Time format was able to properly parse the json_str.
github-repos
def _gauss(mean: int, sigma: int) -> int: return int(random.gauss(mean, sigma))
Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value
juraj-google-style
def _validate_required(self, settings, name, value): if not value: raise SettingsInvalidError(("Required value from setting '{name}' " "must not be " "empty.").format(name=name)) return value
Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exceptions.SettingsInvalidError: If value is empty. Returns: str: Validated value.
juraj-google-style
def add_error(self, position, e): if self.result != TestResultEnums.TEST_RESULT_FAIL: self.result = TestResultEnums.TEST_RESULT_ERROR if position in self.extra_errors: raise Error('An exception is already recorded with position "%s", cannot reuse.' % position) if isinstance(e, ExceptionRecor...
Add extra error happened during a test. If the test has passed or skipped, this will mark the test result as ERROR. If an error is added the test record, the record's result is equivalent to the case where an uncaught exception happened. If the test record has not recorded any error, the newly added error would be t...
github-repos
def process_function_type_comment(node, op, func, ctx): if not op.annotation: return comment, line = op.annotation if func.signature.annotations: ctx.errorlog.redundant_function_type_comment(op.code.filename, line) return fake_stack = ctx.vm.simple_stack(op.at_line(line)) m =...
Modifies annotations from a function type comment. Checks if a type comment is present for the function. If so, the type comment is used to populate annotations. It is an error to have a type comment when annotations is not empty. Args: node: The current node. op: An opcode (used to determine filename and line numb...
github-repos
def is_collection_aligned(self, data_collection): if self._collection_type != data_collection._collection_type: return False elif len(self.values) != len(data_collection.values): return False elif self.datetimes != data_collection.datetimes: return Fa...
Check if this Data Collection is aligned with another. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: data_collection: The Data Collection which you want to test if this collection is aligned with. Return: True if collections are alig...
juraj-google-style
def get_metadata(self, resource, keys): self.metadata_service.set_auth(self._token_metadata) return self.metadata_service.get(resource, keys)
Gets the values for given keys associated with the given resource. Args: resource (intern.resource.boss.BossResource) keys (list) Returns: (dictionary) Raises: HTTPErrorList on failure.
juraj-google-style
def from_dict(cls, data): try: fulfillment = _fulfillment_from_details(data['condition']['details']) except KeyError: fulfillment = data['condition']['uri'] try: amount = int(data['amount']) except ValueError: raise Am...
Transforms a Python dictionary to an Output object. Note: To pass a serialization cycle multiple times, a Cryptoconditions Fulfillment needs to be present in the passed-in dictionary, as Condition URIs are not serializable anymore. Args: data (dict): The dict to be transformed. Returns: :class:`~bigchaindb.common.tr...
juraj-google-style
def GetFileEntryByPathSpec(self, path_spec): volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec) if volume_index is None: location = getattr(path_spec, 'location', None) if location is None or location != self.LOCATION_ROOT: return None return apf...
Retrieves a file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: APFSContainerFileEntry: a file entry or None if not exists.
juraj-google-style
def GetName(self, number): value = self._data_type_definition.values_per_number.get(number, None) if not value: return None return value.name
Retrieves the name of an enumeration value by number. Args: number (int): number. Returns: str: name of the enumeration value or None if no corresponding enumeration value was found.
juraj-google-style
def _get_sync(self, url): response = self.session.get(url) if (response.status_code == requests.codes.ok): return response.json() else: raise HTTPError
Internal method used for GET requests Args: url (str): URL to fetch Returns: Individual URL request's response Raises: HTTPError: If HTTP request failed.
codesearchnet
def get_modname_from_modpath(module_fpath): modsubdir_list = get_module_subdir_list(module_fpath) modname = '.'.join(modsubdir_list) modname = modname.replace('.__init__', '').strip() modname = modname.replace('.__main__', '').strip() return modname
returns importable name from file path get_modname_from_modpath Args: module_fpath (str): module filepath Returns: str: modname Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> module_fpath = ut.util_path.__file__ >>> modname = ut.get_modname_from_modpath(module_fpa...
codesearchnet
def post_request(profile, resource, payload): url = get_url(profile, resource) headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response.json()
Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:...
codesearchnet
def create_identity_with_nan_gradients_fn(have_nan_gradients): @custom_gradient.custom_gradient def _identity_with_nan_gradients(x): x = array_ops.identity(x) def grad(dx): return cond.cond(have_nan_gradients, lambda: dx * float('NaN'), lambda: dx) return (x, grad)...
Returns a function that optionally has NaN gradients. This serves as a hook to introduce NaN gradients to a model. This returns an identity function. The identity's gradient function will check if the boolean tensor `have_nan_gradients` is True. If so, the gradient will be NaN. Otherwise, the gradient will also be the...
github-repos
def update_config_pwd(msg, cfg): msg_type = msg.__class__.__name__.lower() key_fmt = msg.profile + "_" + msg_type if isinstance(msg._auth, (MutableSequence, tuple)): cfg.pwd[key_fmt] = " :: ".join(msg._auth) else: cfg.pwd[key_fmt] = msg._auth
Updates the profile's auth entry with values set by the user. This will overwrite existing values. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance.
juraj-google-style
def pylint_check(files): files = fs.wrap_paths(files) cfg_path = conf.get_path('lint.pylint_cfg', 'ops/tools/pylint.ini') pylint_cmd = 'pylint --rcfile {} {}'.format(cfg_path, files) return shell.run(pylint_cmd, exit_on_error=False).return_code
Run code checks using pylint. Args: files (list[str]): A list of files to check Returns: bool: **True** if all files passed the checks, **False** otherwise.
juraj-google-style
def read_undone_from_datastore(self, shard_id=None, num_shards=None): if (shard_id is not None): shards_list = [((i + shard_id) % num_shards) for i in range(num_shards)] else: shards_list = [] shards_list.append(None) for shard in shards_list: self._read_undone_shard_from_datasto...
Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read. Args: shard_i...
codesearchnet
def zopen(filename, *args, **kwargs): if ((Path is not None) and isinstance(filename, Path)): filename = str(filename) (name, ext) = os.path.splitext(filename) ext = ext.upper() if (ext == '.BZ2'): if (PY_VERSION[0] >= 3): return bz2.open(filename, *args, **kwargs) el...
This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for write. \*\*kwargs: Standard kwargs for python open...
codesearchnet
def update_note(self, note): if ('key' in note): noteid = note.pop('key', None) else: noteid = uuid.uuid4().hex if ('version' in note): version = note.pop('version', None) url = ('%s/i/%s/v/%s?response=1' % (DATA_URL, noteid, version)) else: url = ('%s/i/%s?respon...
Method to update a specific note object, if the note object does not have a "key" field, a new note is created Arguments - note (dict): note object to update Returns: A tuple `(note, status)` - note (dict): note object - status (int): 0 on success and -1 otherwise
codesearchnet
def find_all(self, collection): obj = getattr(self.db, collection) result = obj.find() return result
Search a collection for all available items. Args: collection: The db collection. See main class documentation. Returns: List of all items in the collection.
juraj-google-style
def active_futures(ticker: str, dt) -> str: t_info = ticker.split() (prefix, asset) = (' '.join(t_info[:(- 1)]), t_info[(- 1)]) info = const.market_info(f'{prefix[:(- 1)]}1 {asset}') (f1, f2) = (f'{prefix[:(- 1)]}1 {asset}', f'{prefix[:(- 1)]}2 {asset}') fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq...
Active futures contract Args: ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc. dt: date Returns: str: ticker name
codesearchnet
def _list(self, request, start_response): configs = [] generator = directory_list_generator.DirectoryListGenerator(request) for config in self._config_manager.configs.itervalues(): if (config != self.API_CONFIG): configs.append(config) directory = generator.pretty_print_config_to_jso...
Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
codesearchnet
def wrap_callable(cls, uri, methods, callable_obj): if isinstance(callable_obj, HandlerMeta): callable_obj.base_endpoint = uri callable_obj.is_valid = True return callable_obj if isinstance(callable_obj, types.FunctionType): return cls(uri=uri, methods=methods, callable_obj=calla...
Wraps function-based callable_obj into a `Route` instance, else proxies a `bottle_neck.handlers.BaseHandler` subclass instance. Args: uri (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (instance): The callable object. Returns: A route instance. Raises: RouteError for in...
codesearchnet
def get_data_layout(self, data_shape): raise NotImplementedError()
Retrieve the `TensorLayout` for the input data. Args: data_shape: shape for the input data in list or tuple format. Returns: The `TensorLayout` for the data, which can be used by `backend.distribute_value()` to redistribute a input data.
github-repos
def __init__(self, event_count=0, first_timestamp=-1, last_timestamp=-1): self.event_count = event_count self.first_timestamp = first_timestamp self.last_timestamp = last_timestamp
Tracks events for a single category of values. Args: event_count: The initial event count to use. first_timestamp: The timestamp of the first event with this value. last_timestamp: The timestamp of the last event with this category of values.
juraj-google-style
def get_content_metadata(self, enterprise_customer): content_metadata = OrderedDict() if enterprise_customer.catalog: response = self._load_data( self.ENTERPRISE_CUSTOMER_ENDPOINT, detail_resource='courses', resource_id=str(e...
Return all content metadata contained in the catalogs associated with the EnterpriseCustomer. Arguments: enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for. Returns: list: List of dicts containing content metadata.
juraj-google-style
def _get_populate_values(self, instance) -> Tuple[str, str]: return [ ( lang_code, self._get_populate_from_value( instance, self.populate_from, lang_code ), ) ...
Gets all values (for each language) from the specified's instance's `populate_from` field. Arguments: instance: The instance to get the values from. Returns: A list of (lang_code, value) tuples.
juraj-google-style
def filter_sequences(self, seq_type): return DictList((x for x in self.sequences if isinstance(x, seq_type)))
Return a DictList of only specified types in the sequences attribute. Args: seq_type (SeqProp): Object type Returns: DictList: A filtered DictList of specified object type only
codesearchnet
def softplus_inverse(x, name=None): with tf.name_scope(name or "softplus_inverse"): x = tf.convert_to_tensor(value=x, name="x") threshold = np.log(np.finfo(dtype_util.as_numpy_dtype(x.dtype)).eps) ...
Computes the inverse softplus, i.e., x = softplus_inverse(softplus(x)). Mathematically this op is equivalent to: ```none softplus_inverse = log(exp(x) - 1.) ``` Args: x: `Tensor`. Non-negative (not enforced), floating-point. name: A name for the operation (optional). Returns: `Tensor`. Has the same type/shape as in...
juraj-google-style
def __call__(self, *args, **kwargs): for loop, m in self.iter_methods(): coro = m(*args, **kwargs) self.submit_coroutine(coro, loop)
Triggers all stored callbacks (coroutines) Args: *args: Positional arguments to pass to callbacks **kwargs: Keyword arguments to pass to callbacks
juraj-google-style
def map_resources(self): assert not context.executing_eagerly() object_map = object_identity.ObjectIdentityDictionary() tensor_map = object_identity.ObjectIdentityDictionary() asset_info = _AssetInfo(asset_defs=[], asset_initializers_by_resource=object_identity.ObjectIdentityDictionary(), asset_filename...
Makes new resource handle ops corresponding to existing resource tensors. Creates resource handle ops in the current default graph, whereas `accessible_objects` will be from an eager context. Resource mapping adds resource handle ops to the main GraphDef of a SavedModel, which allows the C++ loader API to interact wit...
github-repos
def filter(self, predicates): tys = [] for col_name, raw_column in self.raw_columns.items(): dtype = str(raw_column.dtype) if dtype == 'object' or dtype == '|S64': weld_type = WeldVec(WeldChar()) else: weld_type = grizzly_impl....
Summary Args: grouping_column_name (TYPE): Description Returns: TYPE: Description
juraj-google-style
def sampler_to_iterator(dataset, sampler): for sample in sampler: if isinstance(sample, (list, tuple)): (yield [dataset[i] for i in sample]) else: (yield dataset[sample])
Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over dataset examples
codesearchnet
def get_device_name(self, cached=True): if (cached and (self.name is not None)): return self.name device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME) if (device_name is None): logger.warn('Failed to find handle for device name') return None self.name = self.d...
Returns the SK8 device BLE name. Args: cached (bool): if True, returns the locally cached copy of the name. If this is set to False, or the name is not cached, it will read from the device instead. Returns: str. The current device name. May be `None` if an error occurs.
codesearchnet
def save_collection(png_filename_base, numpy_data, start_layers_at=1): file_ext = png_filename_base.split('.')[-1] if file_ext in ['png']: file_base = '.'.join(png_filename_base.split('.')[:-1]) else: file_base = png_filename_base file_ext = ".png" ...
Export a numpy array to a set of png files, with each Z-index 2D array as its own 2D file. Arguments: png_filename_base: A filename template, such as "my-image-*.png" which will lead to a collection of files named "my-image-0.png", "my-image-1.png", etc. numpy_data: The numpy array data to save to png....
juraj-google-style
def get_program(self, program_resource_name: str) -> Dict: return self.service.projects().programs().get(name=program_resource_name).execute()
Returns the previously created quantum program. Params: program_resource_name: A string of the form `projects/project_id/programs/program_id`. Returns: A dictionary containing the metadata and the program.
codesearchnet
def auth_middleware(policy): assert isinstance(policy, AbstractAuthentication) async def _auth_middleware_factory(app, handler): async def _middleware_handler(request): request[POLICY_KEY] = policy response = (await handler(request)) (await policy.process_response(r...
Returns a aiohttp_auth middleware factory for use by the aiohttp application object. Args: policy: A authentication policy with a base class of AbstractAuthentication.
codesearchnet
def insert_json(table=None, bulk_size=1000, concurrency=25, hosts=None, output_fmt=None): if (not hosts): return print_only(table) queries = (to_insert(table, d) for d in dicts_from_stdin()) bulk_queries = as_bulk_queries(queries, bulk_size) print('Executing inserts: bulk_size={} concurrency={}'...
Insert JSON lines fed into stdin into a Crate cluster. If no hosts are specified the statements will be printed. Args: table: Target table name. bulk_size: Bulk size of the insert statements. concurrency: Number of operations to run concurrently. hosts: hostname:port pairs of the Crate nodes
codesearchnet
def ensure_app_cache_dir(appname, *args): from ubelt import util_path dpath = get_app_cache_dir(appname, *args) util_path.ensuredir(dpath) return dpath
Calls `get_app_cache_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_cache_dir Example: >>> import ubelt as ub >>> dpath = ub.ensure_app_cache_dir('ubelt') >>> assert exists(dpath)
codesearchnet
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'): with tf.variable_scope(scope): if stride > 1: avg_pool = CONFIG[dim]['avg_pool'] x = avg_pool(x, pool_size=(stride, stride), strides=(stride, stride), padding='VALID'...
Downsamples 'x' by `stride` using average pooling. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: A downsampled tensor of size [N, H/2...
juraj-google-style
def make_agent() -> EcommerceAgent: config_path = find_config('tfidf_retrieve') skill = build_model(config_path) agent = EcommerceAgent(skills=[skill]) return agent
Make an agent Returns: agent: created Ecommerce agent
codesearchnet
def appliance_device_read_community(self): if (not self.__appliance_device_read_community): self.__appliance_device_read_community = ApplianceDeviceReadCommunity(self.__connection) return self.__appliance_device_read_community
Gets the ApplianceDeviceReadCommunity API client. Returns: ApplianceDeviceReadCommunity:
codesearchnet
def __random_density_hs(N, rank=None, seed=None): G = __ginibre_matrix(N, rank, seed) G = G.dot(G.conj().T) return (G / np.trace(G))
Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To set a random seed. Returns: ndarray: rho (N,N a density matrix.
codesearchnet
def Write(self, map_data): self._Begin() written_keys = set() write_offset = 0 try: while 1: entry = map_data.PopItem() for index in self._indices: self._indices[index][str(getattr(entry, index))] = str(write_offset) write_offset += self._Write...
Write the map to the cache. Warning -- this destroys map_data as it is written. This is done to save memory and keep our peak footprint smaller. We consume memory again on Verify() as we read a new copy of the entries back in. Args: map_data: A Map subclass containing the entire map to be written. Returns: a set o...
github-repos
def __call__(self, fn): def debug(app, *args, **kwargs): data = fn(app, *args, **kwargs) app.tcex.log.debug( 'function: "{}", args: "{}", kwargs: "{}"'.format( self.__class__.__name__, vars(args), kwargs ) ...
Implement __call__ function for decorator. Args: fn (function): The decorated function. Returns: function: The custom decorator function.
juraj-google-style
def random_strings(self, string_length=1): str_list = [] for path in self.uniform_generate(string_length): str_list.append(self._path_to_str(path)) return str_list
Generate string_length random strings that belong to the automaton. Args: string_length (integer): The size of the random string Returns: str: The generated string
juraj-google-style
def __getitem__(self, index: Any) -> Rotation: if type(index) is not tuple: index = (index,) if self._rot_mats is not None: rot_mats = self._rot_mats[index + (slice(None), slice(None))] return Rotation(rot_mats=rot_mats) elif self._quats is not None: quats = self._quats[index...
Allows torch-style indexing over the virtual shape of the rotation object. See documentation for the shape property. Args: index: A torch index. E.g. (1, 3, 2), or (slice(None,)) Returns: The indexed rotation
github-repos
def stack_residual_blocks_v1(x, filters, blocks, stride1=2, name=None): x = residual_block_v1(x, filters, stride=stride1, name=name + '_block1') for i in range(2, blocks + 1): x = residual_block_v1(x, filters, conv_shortcut=False, name=name + '_block' + str(i)) return x
A set of stacked residual blocks. Args: x: Input tensor. filters: Number of filters in the bottleneck layer in a block. blocks: Number of blocks in the stacked blocks. stride1: Stride of the first layer in the first block. Defaults to `2`. name: Stack label. Returns: Output tensor for the stacked blocks.
github-repos
def _get_ngrams_with_counter(segment, max_order): ngram_counts = collections.Counter() for order in xrange(1, max_order + 1): for i in xrange(0, len(segment) - order + 1): ngram = tuple(segment[i:i + order]) ngram_counts[ngram] += 1 return ngram_counts
Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams upto max_order in segment with a count of how many times ea...
juraj-google-style
def schedule(cls, mapreduce_spec): task_name = mapreduce_spec.mapreduce_id + "-finalize" finalize_task = taskqueue.Task( name=task_name, url=(mapreduce_spec.params["base_path"] + "/finalizejob_callback/" + mapreduce_spec.mapreduce_id), params={"mapreduce_id": mapreduce_...
Schedule finalize task. Args: mapreduce_spec: mapreduce specification as MapreduceSpec.
juraj-google-style
def write(self, save_path, options=None): return self._write(save_path, options)
Save the checkpointed variables. Args: save_path: The file prefix of the checkpoint file. options: Optional CheckpointOption instance. Returns: The full path of the checkpoint file.
github-repos
def match(self, f, *args): try: match = f(self.tokenizer, *args) except StopIteration: return if match is None: return if not isinstance(match, grammar.TokenMatch): raise TypeError("Invalid ...
Match grammar function 'f' against next token and set 'self.matched'. Arguments: f: A grammar function - see efilter.parsers.common.grammar. Must return TokenMatch or None. args: Passed to 'f', if any. Returns: Instance of efilter.parsers.common.grammar.TokenMatch or None. Comment: If a match is returned, it will al...
juraj-google-style
def __init__(self, max_size=10, max_age=600): super(TimeBasedCache, self).__init__(max_size) self.max_age = max_age def HouseKeeper(): if not time: return now = time.time() for cache in TimeBasedCache.active_caches: with cache.lock: ...
Constructor. This cache will refresh the age of the cached object as long as they are accessed within the allowed age. The age refers to the time since it was last touched. Args: max_size: The maximum number of objects held in cache. max_age: The maximum length of time an object is considered alive.
juraj-google-style
def register_entry(self, navbar_kwargs): path = navbar_kwargs.pop('path') if ((not hasattr(path, '__iter__')) or isinstance(path, basestring)): path = [path] entry_group = self.navbar_entries for (name, is_last) in iter_islast(path): kwargs = deepcopy(navbar_kwargs) kwargs['name'...
Register a navbar entry with the copilot. Args: navbar_kwargs (dict): Arguments passed to the :class:`NavbarEntry` instance.
codesearchnet
def _model_source_dir(self): return (self.source_dir if self.sagemaker_session.local_mode else self.uploaded_code.s3_prefix)
Get the appropriate value to pass as source_dir to model constructor on deploying Returns: str: Either a local or an S3 path pointing to the source_dir to be used for code by the model to be deployed
codesearchnet
def __init__(self, array): self.array = array
Specify a NumPy array to wrap. Args: array: The NumPy array to save and restore (may be overwritten).
github-repos
def GetMetadata( self, metadata_key='', recursive=True, timeout=None, retry=True): return self._HandleMetadataUpdate( metadata_key=metadata_key, recursive=recursive, wait=False, timeout=timeout, retry=retry)
Retrieve the contents of metadata server for a metadata key. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. timeout: int, timeout in seconds for returning metadata output. retry: bool, True if we should retry on failure. Re...
juraj-google-style
def _GenClientLibCallback(args, client_func=_GenClientLib): client_path = client_func(args.discovery_doc[0], args.language, args.output, args.build_system) print 'API client library written to %s' % client_path
Generate a client library to file. Args: args: An argparse.Namespace object to extract parameters from client_func: A function that generates client libraries and stores them to files, accepting a path to a discovery doc, a client library language, an output directory, and a build system for the client library languag...
juraj-google-style
def exists(self, vars_list: List[str]) -> 'TensorFluent': return self._aggregation_op(tf.reduce_any, self, vars_list)
Returns the TensorFluent for the exists aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the exists aggregation function.
juraj-google-style
def __send_smtp_email(self, recipients, subject, html_body, text_body): smtp = smtplib.SMTP(dbconfig.get('smtp_server', NS_EMAIL, 'localhost'), dbconfig.get('smtp_port', NS_EMAIL, 25)) source_arn = dbconfig.get('source_arn', NS_EMAIL) return_arn = dbconfig.get('return_path_arn', NS_EMAIL) from_arn = dbc...
Send an email using SMTP Args: recipients (`list` of `str`): List of recipient email addresses subject (str): Subject of the email html_body (str): HTML body of the email text_body (str): Text body of the email Returns: `None`
codesearchnet
def convert_to_qutip(expr, full_space=None, mapping=None): if (full_space is None): full_space = expr.space if (not expr.space.is_tensor_factor_of(full_space)): raise ValueError(("expr '%s' must be in full_space %s" % (expr, full_space))) if (full_space == TrivialSpace): raise Algebr...
Convert a QNET expression to a qutip object Args: expr: a QNET expression full_space (HilbertSpace): The Hilbert space in which `expr` is defined. If not given, ``expr.space`` is used. The Hilbert space must have a well-defined basis. mapping (dict): A mapping of any (sub-)expression to either a `quip.Qobj` directly, ...
codesearchnet