code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def remove_handler(self, handler: Handler, group: int=0): if isinstance(handler, DisconnectHandler): self.disconnect_handler = None else: self.dispatcher.remove_handler(handler, group)
Removes a previously-added update handler. Make sure to provide the right group that the handler was added in. You can use the return value of the :meth:`add_handler` method, a tuple of (handler, group), and pass it directly. Args: handler (``Handler``): The handler to be removed. group (``int``, *optional*): The gr...
codesearchnet
def getWindow(title, exact=False): titles = getWindows() hwnd = titles.get(title, None) if not hwnd and not exact: for k, v in titles.items(): if title in k: hwnd = v break if hwnd: return Window(hwnd) else: return None
Return Window object if 'title' or its part found in visible windows titles, else return None Return only 1 window found first Args: title: unicode string exact (bool): True if search only exact match
juraj-google-style
def concat(self, second_iterable): if self.closed(): raise ValueError("Attempt to call concat() on a closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute concat() with second_iterable of " "non-iterable {0}".format(s...
Concatenates two sequences. Note: This method uses deferred execution. Args: second_iterable: The sequence to concatenate on to the sequence. Returns: A Queryable over the concatenated sequences. Raises: ValueError: If the Queryable is closed(). TypeError: If second_iterable is not in fact iterable.
juraj-google-style
def ReadFile(self, definitions_registry, path): with open(path, 'r') as file_object: self.ReadFileObject(definitions_registry, file_object)
Reads data type definitions from a file into the registry. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. path (str): path of the file to read from.
codesearchnet
def _DrawHours(self): tmpstrs = [] for i in range(0, self._gwidth, self._min_grid): if ((i % self._hour_grid) == 0): tmpstrs.append(('<polyline class="FullHour" points="%d,%d, %d,%d" />' % (((i + 0.5) + 20), 20, ((i + 0.5) + 20), self._gheight))) tmpstrs.append(('<text class="Lab...
Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..."
codesearchnet
def uninstalled(name): ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_installed'](name) if not old: ret['comment'] = 'Package {0} is not installed'.format(name) ret['result'] = True return ret e...
Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp
juraj-google-style
def deprecated(msg): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): logging.getLogger(__name__).warning(msg) return func(*args, **kwargs) return wrapper return decorator
Marks a function / method as deprecated. Takes one argument, a message to be logged with information on future usage of the function or alternative methods to call. Args: msg (str): Deprecation message to be logged Returns: `callable`
juraj-google-style
def witness_tx(tx_ins, tx_outs, tx_witnesses, **kwargs): deser = [script_ser.deserialize(tx_in.redeem_script) for tx_in in tx_ins if tx_in is not None] for w in tx_witnesses: try: deser.append(script_ser.deserialize(w.stack[-1].item)) except (NotImplementedErr...
Construct a fully-signed segwit transaction Args: tx_ins list(TxIn instances): list of transaction inputs tx_outs list(TxOut instances): list of transaction outputs tx_witnesses list(TxWitness instances): list of transaction witnsses **kwargs: version (int): transaction version number locktime (hex): ...
juraj-google-style
def defer(self, func: typing.Callable[([], typing.Any)], until: typing.Union[(int, float)]=(- 1)) -> typing.Any: raise NotImplementedError()
Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that ar...
codesearchnet
def process_fixed_issues(self, volumes, existing_issues): fixed_issues = [] for issue_id, issue in list(existing_issues.items()): if issue_id not in volumes: fixed_issues.append(issue) return fixed_issues
Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict`): A dictionary keyed on the issue id, with the :obj:`EBSVolumeAuditIssue` object as the value Retu...
juraj-google-style
def inspect_last(self, stream, only_allocated=False): if only_allocated: found = False for walker in self._virtual_walkers: if walker.matches(stream): found = True break if (not found): raise UnresolvedIdentifierError('inspect_last coul...
Return the last value pushed into a stream. This function works even if the stream is virtual and no virtual walker has been created for it. It is primarily useful to aid in debugging sensor graphs. Args: stream (DataStream): The stream to inspect. only_allocated (bool): Optional parameter to only allow inspection o...
codesearchnet
def with_division(self, division): if (division is None): division = '' division = slugify(division) self._validate_division(division) self.division = division return self
Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError
codesearchnet
def limit_epochs(tensor, num_epochs=None, name=None): if num_epochs is None: return tensor if num_epochs <= 0: raise ValueError('num_epochs must be > 0 not %d.' % num_epochs) with ops.name_scope(name, 'limit_epochs', [tensor]) as name: zero64 = constant_op.constant(0, dtype=dtypes.in...
Returns tensor `num_epochs` times and then raises an `OutOfRange` error. Note: creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables. Args: tensor: Any `Tensor`. num_epochs: A positive integer (optional). If specified, limits the number of steps the output tensor may be ev...
github-repos
def iter_predict(self, X, include_init=False): utils.validation.check_is_fitted(self, 'init_estimator_') X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False) y_pred = self.init_estimator_.predict(X) if include_init: (yield y_pred) for (estimators, line_s...
Returns the predictions for ``X`` at every stage of the boosting procedure. Args: X (array-like or sparse matrix of shape (n_samples, n_features): The input samples. Sparse matrices are accepted only if they are supported by the weak model. include_init (bool, default=False): If ``True`` then the prediction from ``ini...
codesearchnet
def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse: self._validate_xoxp_token() kwargs.update({'channel': channel, 'user': user}) return self.api_call('groups.invite', json=kwargs)
Invites a user to a private channel. Args: channel (str): The group id. e.g. 'G1234567890' user (str): The user id. e.g. 'U1234567890'
codesearchnet
def add_timing_signal_1d_given_position(x, position, min_timescale=1.0, max_timescale=1.0e4): channels = common_layers.shape_list(x)[2] num_timescales = channels log_timescale_increment = ( ...
Adds sinusoids of diff frequencies to a Tensor, with timing position given. Args: x: a Tensor with shape [batch, length, channels] position: a Tensor with shape [batch, length] min_timescale: a float max_timescale: a float Returns: a Tensor the same shape as x.
juraj-google-style
def _get_saver_def_or_none(exported_model: exported_model_pb2.ExportedModel) -> Optional[saver_pb2.SaverDef]: if exported_model.HasField('saver_def'): return exported_model.saver_def return None
Returns the SaverDef from ExportedModel, None otherwise. Args: exported_model: ExportedModel to take the SaverDef from. Returns: SaverDef instance if the field `saver_def` is set. None otherwise.
github-repos
def range(self, x_data=None): if x_data is None: try: x_data = evaluation.evaluate_inverse( self, numpy.array([[0.5]]*len(self))) except StochasticallyDependentError: x_data = approximation.find_interior_point(self) ...
Generate the upper and lower bounds of a distribution. Args: x_data (numpy.ndarray) : The bounds might vary over the sample space. By providing x_data you can specify where in the space the bound should be taken. If omitted, a (pseudo-)random sample is used. Returns: (numpy.ndarray): The lower (out[0]) and upper (ou...
juraj-google-style
def _ip_int_from_string(self, ip_str): if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(...
Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address.
juraj-google-style
def add_ipdu(self, information, timeout=(- 1)): uri = (self.URI + '/discover') return self._client.create(information, uri=uri, timeout=timeout)
Add an HP iPDU and bring all components under management by discovery of its management module. Bring the management module under exclusive management by the appliance, configure any management or data collection settings, and create a private set of administrative credentials to enable ongoing communication and manage...
codesearchnet
def SetExtractionConfiguration(self, configuration): self._hasher_file_size_limit = configuration.hasher_file_size_limit self._SetHashers(configuration.hasher_names_string) self._process_archives = configuration.process_archives self._process_compressed_streams = configuration.process_compressed_st...
Sets the extraction configuration settings. Args: configuration (ExtractionConfiguration): extraction configuration.
juraj-google-style
def __init__(self, xid=None, data=None): super().__init__(xid) self.data = data
Create an EchoReply with the optional parameters below. Args: xid (int): xid to be used on the message header. data (bytes): arbitrary-length data field.
juraj-google-style
def get_checklist(self, id, name=None): return self.create_checklist(dict(id=id, name=name))
Get a checklist Returns: Checklist: The checklist with the given `id`
codesearchnet
def warn_logging(logger): def showwarning(message, category, filename, lineno, file=None, line=None): logger.warning(message) return showwarning
Create a `showwarning` function that uses the given logger. Arguments: logger (~logging.Logger): the logger to use. Returns: function: a function that can be used as the `warnings.showwarning` callback.
juraj-google-style
def staged_rewards(self): cubeA_pos = self.sim.data.body_xpos[self.cubeA_body_id] cubeB_pos = self.sim.data.body_xpos[self.cubeB_body_id] gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id] dist = np.linalg.norm((gripper_site_pos - cubeA_pos)) r_reach = ((1 - np.tanh((10.0 * dist))) * 0.25)...
Helper function to return staged rewards based on current physical states. Returns: r_reach (float): reward for reaching and grasping r_lift (float): reward for lifting and aligning r_stack (float): reward for stacking
codesearchnet
def do_REMOTE(self, target: str, remote_command: str, source: list, *args, **kwargs) -> None: if (target == self.messaging._service_name): info = 'target for remote command is the bot itself! Returning the function' self.logger.info(info) return self._handle_command(remote_command, source, *...
Send a remote command to a service. Used Args: target: The service that the command gets set to remote_command: The command to do remotely. source: the binary source of the zmq_socket. Packed to send to the
codesearchnet
def maybe_set_static_shape(tensor, shape): if _ENABLE_MAYBE_SET_STATIC_SHAPE and (not context.executing_eagerly()) and ops.get_default_graph().building_function and (not tensor.shape.is_fully_defined()) and tensor_util.is_tensor(shape): shape = shape_tensor(shape) const_shape = tensor_util.constant_...
Sets the shape of `tensor` to the `shape`'s constant value, if inferrable. This is a temporary workaround to fix shape inference across functional op boundaries. E.g. ```python shape = tf.constant([3]) @tf.function def f(): u = tf.random_uniform(shape) return u ``` If we were to rely solely on C++ shape inference, t...
github-repos
def get_page_artid(self, separator='-'): publication_info = get_value( self.record, 'publication_info[0]', default={} ) return LiteratureReader.get_page_artid_for_publication_info( publication_info, separator )
Return the page range or the article id of a record. Args: separator(basestring): optional page range symbol, defaults to a single dash Returns: string: the page range or the article id of the record. Examples: >>> record = { ... 'publication_info': [ ... {'artid': '054021'}, ... ], ... } >>> Literat...
juraj-google-style
def _get_metrics_result_or_logs(self, logs): metric_logs = self.get_metrics_result() if isinstance(logs, dict) and set(logs.keys()) == set(metric_logs.keys()): return metric_logs return logs
Returns model metrics as a dict if the keys match with input logs. When the training / evaluation is performed with an asynchronous steps, the last scheduled `train / test_step` may not give the latest metrics because it is not guaranteed to be executed the last. This method gets metrics from the model directly instea...
github-repos
def record_kv_cache_memory_metrics(self, cache) -> None: if not _has_opentelemetry: return try: num_used_blocks = cache.num_blocks - len(cache._free_blocks) num_layers = len(cache.key_cache) bytes_per_parameter = 2 if cache.dtype in [torch.float16, torch.bfloat16] else 4 ...
Record memory usage of the PagedAttentionCache without GPU synchronization. This calculates the theoretical memory usage based on cache configuration and the number of blocks currently in use. Args: cache: The PagedAttentionCache object to measure
github-repos
def _checkFunctioncode(functioncode, listOfAllowedValues=[]): FUNCTIONCODE_MIN = 1 FUNCTIONCODE_MAX = 127 _checkInt(functioncode, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode') if (listOfAllowedValues is None): return if (not isinstance(listOfAllowedValues, list)): r...
Check that the given functioncode is in the listOfAllowedValues. Also verifies that 1 <= function code <= 127. Args: * functioncode (int): The function code * listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking. Raises: TypeError, ValueError
codesearchnet
def iterator_cycle(variables: VarType, parent: str) -> Iterable[VarMatrix]: if isinstance(variables, dict): if variables.get("times"): times = int(variables["times"]) del variables["times"] yield list(variable_matrix(variables, parent, "product")) * times e...
Cycle through a list of values a specified number of times Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
juraj-google-style
def by_name(name): devices = discover(all_households=True) for device in (devices or []): if device.player_name == name: return device return None
Return a device by name. Args: name (str): The name of the device to return. Returns: :class:`~.SoCo`: The first device encountered among all zone with the given player name. If none are found `None` is returned.
juraj-google-style
def rotate_view(self, axis_ind=0, angle=0): camera = self.ren.GetActiveCamera() if axis_ind == 0: camera.Roll(angle) elif axis_ind == 1: camera.Azimuth(angle) else: camera.Pitch(angle) self.ren_win.Render()
Rotate the camera view. Args: axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis. angle: Angle to rotate by. Defaults to 0.
juraj-google-style
def _get_shards_by_task(self, sharding_callback: sharding_util.ShardingCallback) -> Sequence[tuple[str, Sequence[sharding_util.Shard]]]: def wrap_tensor(shardable_tensor): tensor_val = shardable_tensor.tensor tensor_shape = shardable_tensor.shape save_spec = shardable_tensor._tensor_save_sp...
Calls the sharding callback with shardable_tensors. Args: sharding_callback: ShardingCallback. The callback function wrapper that splits shardable_tensors into shards. Returns: A list of (task, shards) tuples.
github-repos
def find_stacks(node, strict=False): fso = FindStackOps() fso.visit(node) AnnotateStacks(fso.push_pop_pairs, strict).visit(node) return node
Find pushes and pops to the stack and annotate them as such. Args: node: An AST node that might contain stack pushes and pops. strict: A boolean indicating whether to stringently test whether each push and pop are matched. This is not always possible when taking higher-order derivatives of code generated in split-moti...
codesearchnet
def sg_to_sparse(tensor, opt): r indices = tf.where(tf.not_equal(tensor.sg_float(), 0.)) return tf.SparseTensor(indices=indices, values=tf.gather_nd(tensor, indices) - 1, dense_shape=tf.shape(tensor).sg_cast(dtype=tf.int64))
r"""Converts a dense tensor into a sparse tensor. See `tf.SparseTensor()` in tensorflow. Args: tensor: A `Tensor` with zero-padding (automatically given by chain). opt: name: If provided, replace current tensor's name. Returns: A `SparseTensor`.
juraj-google-style
def infer_inputs_from_restored_call_function(fn): def common_spec(x, y): common_shape = get_common_shape(x.shape, y.shape) if isinstance(x, sparse_tensor.SparseTensorSpec): return sparse_tensor.SparseTensorSpec(common_shape, x.dtype) elif isinstance(x, ragged_tensor.RaggedTensor...
Returns TensorSpec of inputs from a restored call function. Args: fn: Restored layer call function. It is assumed that `fn` has at least one concrete function and that the inputs are in the first argument. Returns: TensorSpec of call function inputs.
github-repos
def _Lock(self, path=None, force=False): if self.lock is None: self.lock = lock.PidFile(filename=path) return self.lock.Lock(force=force)
Grab a system-wide lock for this command. Commands wishing to prevent concurrent operation can invoke this method to acquire a system-wide lock. The lock will be automatically released on object destruction, however an optional Unlock() method is provided for commands wishing a smaller scope of locking. Args: path: ...
github-repos
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckFor...
Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _Inclu...
codesearchnet
def _ParsePlistKeyValue(self, knowledge_base, name, value): if not knowledge_base.GetValue('operating_system_version'): if name in self._PLIST_KEYS: knowledge_base.SetValue('operating_system_version', value)
Parses a plist key value. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. name (str): name of the plist key. value (str): value of the plist key.
juraj-google-style
def AddKeywordsForName(self, name, keywords): data_store.DB.IndexAddKeywordsForName(self.urn, name, keywords)
Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name.
codesearchnet
def get_class(schema_name): global _registry_loaded if (not _registry_loaded): load_message_classes() try: return _schema_name_to_class[schema_name] except KeyError: _log.warning('The schema "%s" is not in the schema registry! Either install the package with its schema definition...
Retrieve the message class associated with the schema name. If no match is found, the default schema is returned and a warning is logged. Args: schema_name (six.text_type): The name of the :class:`Message` sub-class; this is typically the Python path. Returns: Message: A sub-class of :class:`Message` to create the m...
codesearchnet
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(exc...
Processes an event. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event.
juraj-google-style
def convert_to_string(self, productions): symbols = [] for production in tf.unstack(productions, axis=1): lhs, rhs = self.production_rules[tf.argmax(input=production, axis=-1)] if not symbols: if lhs != self.start_symbol: raise ValueError("`productions` must begin with `self...
Converts a sequence of productions into a string of terminal symbols. Args: productions: Tensor of shape [1, num_productions, num_production_rules]. Slices along the `num_productions` dimension represent one-hot vectors. Returns: str that concatenates all terminal symbols from `productions`. Raises: ValueError: If t...
juraj-google-style
def Page(self, text=None, show_percent=None): if (text is not None): self._text += text if (show_percent is None): show_percent = (text is None) self._show_percent = show_percent text = LineWrap(self._text).splitlines() while True: self._newlines = text[self._displayed:(self....
Page text. Continues to page through any text supplied in the constructor. Also, any text supplied to this method will be appended to the total text to be displayed. The method returns when all available text has been displayed to the user, or the user quits the pager. Args: text: A string, extra text to be paged. sh...
codesearchnet
def _CreateRoutesFolder(self, schedule, doc, route_type=None): def GetRouteName(route): 'Return a placemark name for the route.\n\n Args:\n route: The transitfeed.Route instance.\n\n Returns:\n The name as a string.\n ' name_parts = [] if route.route_short_name:...
Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing p...
codesearchnet
def sequence_path(self, fasta_path): if not fasta_path: self.sequence_dir = None self.sequence_file = None else: if not op.exists(fasta_path): raise OSError('{}: file does not exist'.format(fasta_path)) if not op.dirname(fasta_pa...
Provide pointers to the paths of the FASTA file Args: fasta_path: Path to FASTA file
juraj-google-style
def explicit_method_override(method): setattr(method, '__explicit_override__', True) return method
Decorator that marks a member method as explicitly overridden. In PyGlove, many methods are managed by the framework - for example - ``pg.Object.__init__``. It's easy for users to override these methods unconsciously. Therefore, we introduce this decorator to catch error at the first place when such overrides incident...
github-repos
def document(self, name, file_name, **kwargs): group_obj = Document(name, file_name, **kwargs) return self._group(group_obj)
Add Document data to Batch object. Args: name (str): The name for this Group. file_name (str): The name for the attached file for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. file_content (str;method, kwargs): The file contents or callback method to retrieve file content. malware...
codesearchnet
def rhombohedral(a: float, alpha: float): return Lattice.from_parameters(a, a, a, alpha, alpha, alpha)
Convenience constructor for a rhombohedral lattice. Args: a (float): *a* lattice parameter of the rhombohedral cell. alpha (float): Angle for the rhombohedral lattice in degrees. Returns: Rhombohedral lattice of dimensions a x a x a.
juraj-google-style
def setupSerialPort(loopback, port): if loopback: testSerial = SerialTestClass() serialPort = testSerial.serialPort else: serialPort = serial.Serial(port, 115200, timeout=0) return serialPort
Sets up serial port by connecting to phsyical or software port. Depending on command line options, this function will either connect to a SerialTestClass() port for loopback testing or to the specified port from the command line option. If loopback is True it overrides the physical port specification. Args: loopback:...
juraj-google-style
def fit(self, volumes, energies): eos_fit = self.model(np.array(volumes), np.array(energies)) eos_fit.fit() return eos_fit
Fit energies as function of volumes. Args: volumes (list/np.array) energies (list/np.array) Returns: EOSBase: EOSBase object
codesearchnet
def _ModifyInterface( self, interface_config, config_key, config_value, replace=False): config_entry = '%s=%s' % (config_key, config_value) if not open(interface_config).read().count(config_key): with open(interface_config, 'a') as config: config.write('%s\n' % config_entry) elif re...
Write a value to a config file if not already present. Args: interface_config: string, the path to a config file. config_key: string, the configuration key to set. config_value: string, the value to set for the configuration key. replace: bool, replace the configuration option if already present.
juraj-google-style
def square(duration: int, amp: complex, period: float = None, phase: float = 0, name: str = None) -> SamplePulse: if period is None: period = duration return _sampled_square_pulse(duration, amp, period, phase=phase, name=name)
Generates square wave `SamplePulse`. Applies `left` sampling strategy to generate discrete pulse from continuous function. Args: duration: Duration of pulse. Must be greater than zero. amp: Pulse amplitude. Wave range is [-amp, amp]. period: Pulse period, units of dt. If `None` defaults to single cycle. phase: Pulse ...
juraj-google-style
def scalar_projection(v1, v2): return (np.dot(v1, v2) / np.linalg.norm(v2))
compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v
codesearchnet
class CustomHFIndex(HFIndexBase): def __init__(self, vector_size: int, dataset, index_path=None): requires_backends(self, ['faiss']) super().__init__(vector_size, dataset, index_initialized=index_path is None) self.index_path = index_path @classmethod def load_from_disk(cls, vector...
A wrapper around an instance of [`~datasets.Datasets`]. The dataset and the index are both loaded from the indicated paths on disk. Args: vector_size (`int`): the dimension of the passages embeddings used by the index dataset_path (`str`): The path to the serialized dataset on disk. The dataset should have 3 columns: ...
github-repos
def score(self, data, metric='accuracy', break_ties='random', verbose=True, print_confusion_matrix=True, **kwargs): (Y_p, Y, Y_s) = self._get_predictions(data, break_ties=break_ties, return_probs=True, **kwargs) return_list = isinstance(metric, list) metric_list = (metric if isinstance(metric, list) else [m...
Scores the predictive performance of the Classifier on all tasks Args: data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y): X: The input for the predict method Y: An [n] or [n, 1] torch.Tensor or np.ndarray of target labels in {1,...,k} metric: A metric (string) with which to score performance or a list o...
codesearchnet
def add_comment(self, comment): if (not comment): return self.__comments[comment.name] = comment self.comment_added_signal(self, comment)
Add a comment to the database. Args: comment (hotdoc.core.Comment): comment to add
codesearchnet
def from_callable(cls, fn: Callable) -> Optional['IOTypeHints']: if _disable_from_callable or getattr(fn, '_beam_no_annotations', False): return None signature = get_signature(fn) if all((param.annotation == param.empty for param in signature.parameters.values())) and signature.return_annotation == ...
Construct an IOTypeHints object from a callable's signature. Supports Python 3 annotations. For partial annotations, sets unknown types to Any, _ANY_VAR_POSITIONAL, or _ANY_VAR_KEYWORD. Returns: A new IOTypeHints or None if no annotations found.
github-repos
def del_hparam(self, name): if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter.
juraj-google-style
def create_magic_packet(macaddress): if len(macaddress) == 12: pass elif len(macaddress) == 17: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') data = b'FFFFFFFFFFFF' + (macaddress * 16).encode...
Create a magic packet. A magic packet is a packet that can be used with the for wake on lan protocol to wake up a computer. The packet is constructed from the mac address given as a parameter. Args: macaddress (str): the mac address that should be parsed into a magic packet.
juraj-google-style
def trim_whitespace(self, text): lines = text.split('\n') new_lines = [x.lstrip() for x in lines] return '\n'.join(new_lines)
Remove leading whitespace from each line of a multiline string Args: text (string): The text to be unindented Returns: string: The unindented block of text
juraj-google-style
def MakeJoint(pmf1, pmf2): joint = Joint() for (v1, p1) in pmf1.Items(): for (v2, p2) in pmf2.Items(): joint.Set((v1, v2), (p1 * p2)) return joint
Joint distribution of values from pmf1 and pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: Joint pmf of value pairs
codesearchnet
def get_snpeff_info(snpeff_string, snpeff_header): snpeff_annotations = [ dict(zip(snpeff_header, snpeff_annotation.split('|'))) for snpeff_annotation in snpeff_string.split(',') ] return snpeff_annotations
Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. Args: snpeff_string (string): A string with the ANN annotation snpeff_header (list): A list with the ...
juraj-google-style
def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type): def populate_sweep_param(scripts, parameter_list, trace=''): "\n\n Args:\n scripts: a dict of {'class name': <class object>} pairs\n\n Returns: A list of all parameters of the inp...
assigning the actual script settings depending on the iterator type this might be overwritten by classes that inherit form ScriptIterator Args: sub_scripts: dictionary with the subscripts script_order: execution order of subscripts script_execution_freq: execution frequency of subscripts Returns: the default setting...
codesearchnet
def get_ituz(self, callsign, timestamp=timestamp_now): return self.get_all(callsign, timestamp)[const.ITUZ]
Returns ITU Zone of a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: containing the callsign's CQ Zone Raises: KeyError: No ITU Zone found for callsign Note: Currently, only Country-files.com lookup database contains ITU Zones
juraj-google-style
def plot_hall_carriers(self, temp=300): import matplotlib.pyplot as plt hall_carriers = [abs(i) for i in self._bz.get_hall_carrier_concentration()[temp]] plt.semilogy(self._bz.mu_steps, hall_carriers, linewidth=3.0, color='r') self._plot_bg_limits() self._plot_doping(temp) plt.xlim((- 0.5), (sel...
Plot the Hall carrier concentration in function of Fermi level Args: temp: the temperature Returns: a matplotlib object
codesearchnet
def get_sources(self, prefix=''): prefix = prefix.replace('-', '_') prefixed = '%s_sources' % prefix if prefixed in self.__cli: sources = self.__cli.get(prefixed) from_conf = False else: sources = self.__config.get(prefixed) from_...
Retrieve a set of absolute paths to sources, according to `prefix` `ConfigParser` will perform wildcard expansion and filtering. Args: prefix: str, the desired prefix. Returns: utils.utils.OrderedSet: The set of sources for the given `prefix`.
juraj-google-style
def get_memory_growth(device): return context.context().get_memory_growth(device)
Get if memory growth is enabled for a `PhysicalDevice`. If memory growth is enabled for a `PhysicalDevice`, the runtime initialization will not allocate all memory on the device. For example: >>> physical_devices = tf.config.list_physical_devices('GPU') >>> try: ... tf.config.experimental.set_memory_growth(physica...
github-repos
def seek_to_end(self, *partitions): if (not all([isinstance(p, TopicPartition) for p in partitions])): raise TypeError('partitions must be TopicPartition namedtuples') if (not partitions): partitions = self._subscription.assigned_partitions() assert partitions, 'No partitions are current...
Seek to the most recent available offset for partitions. Arguments: *partitions: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. Raises: AssertionError: If any partition is not currently assigned, or if no partitions are assigned.
codesearchnet
def _get_shoulds(options): if options.version == '2.0': return shoulds20.list_shoulds(options) else: return shoulds21.list_shoulds(options)
Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version.
juraj-google-style
def __init__( self, input_columns: t.List[Column], output_columns: t.List[Column], column_transform,) -> None: self.input_columns = input_columns self.output_columns = output_columns self.column_transform = column_transform
Construct a new ``CompoundColumn`` object. Args: input_columns (list, Column): A list of ``Column`` objects representing column(s) from the SOURCE table. output_columns (list, Column): A list of ``Column`` objects representing column(s) from the FINAL table. column_transform (Callable): Function accepting the table ob...
juraj-google-style
def imfrombytes(content, flag='color'): img_np = np.frombuffer(content, np.uint8) flag = (imread_flags[flag] if is_str(flag) else flag) img = cv2.imdecode(img_np, flag) return img
Read an image from bytes. Args: content (bytes): Image bytes got from files or other streams. flag (str): Same as :func:`imread`. Returns: ndarray: Loaded image array.
codesearchnet
def orth_chol(order, dist, normed=True, sort='GR', cross_truncation=1.0, **kws): dim = len(dist) basis = chaospy.poly.basis(start=1, stop=order, dim=dim, sort=sort, cross_truncation=cross_truncation) length = len(basis) cholmat = chaospy.chol.gill_king(chaospy.descriptives.Cov(basis, dist)) cholmat_...
Create orthogonal polynomial expansion from Cholesky decomposition. Args: order (int): Order of polynomial expansion dist (Dist): Distribution space where polynomials are orthogonal normed (bool): If True orthonormal polynomials will be used instead of monic. sort (str): Ordering argument passed to poly.basis. If cus...
codesearchnet
def as_dict(self): return {'@module': self.__class__.__module__, '@class': self.__class__.__name__, 'r': jsanitize(self.r), 'energies': jsanitize(self.energies), 'forces': jsanitize(self.forces), 'structures': [s.as_dict() for s in self.structures]}
Dict representation of NEBAnalysis. Returns: JSON serializable dict representation.
codesearchnet
def ConvertStringToFilename(name): return re.sub('\\W', (lambda x: ('%%%02X' % ord(x.group(0)))), name, flags=re.UNICODE).rstrip('/')
Converts an unicode string to a filesystem safe filename. For maximum compatibility we escape all chars which are not alphanumeric (in the unicode sense). Args: name: a unicode string that is part of a subject. Returns: A safe filename with escaped special chars.
codesearchnet
def __init__(self, config_files, use_tc=None, **kwargs): super(VIIRSSDRReader, self).__init__(config_files, **kwargs) self.use_tc = use_tc
Initialize file reader and adjust geolocation preferences. Args: config_files (iterable): yaml config files passed to base class use_tc (boolean): If `True` use the terrain corrected files. If `False`, switch to non-TC files. If `None` (default), use TC if available, non-TC otherwise.
juraj-google-style
def delete(filething): f = FLAC(filething) filething.fileobj.seek(0) f.delete(filething)
Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError
juraj-google-style
def __init__(self, config: Dict[str, str], default_level: str): self._should_log: Dict[Tuple[str, str], bool] = {} self._default_level = config.get('', default_level) self._log_rules = [ (logger.split('.') if logger else list(), level) for logger, level ...
Initializes a new `LogFilter` Args: config: Dictionary mapping module names to logging level default_level: The default logging level
juraj-google-style
def make_json_formatted_for_single_chart(mutant_features, inference_result_proto, index_to_mutate): x_label = 'step' y_label = 'scalar' if isinstance(inference_result_proto, classification_pb2.ClassificationResponse): series = {} for (idx, classification) in enumerate(inference_result_proto....
Returns JSON formatted for a single mutant chart. Args: mutant_features: An iterable of `MutantFeatureValue`s representing the X-axis. inference_result_proto: A ClassificationResponse or RegressionResponse returned by Servo, representing the Y-axis. It contains one 'classification' or 'regression' for every Example th...
codesearchnet
def decode(obj, content_type): try: decoder = _decoders_map[content_type] return decoder(obj) except KeyError: raise _errors.UnsupportedFormatError(content_type)
Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded object.
juraj-google-style
def _process_assignments(self, feed_item, creative_assignments, placement_assignments, event_tag_assignments, campaign): assigned_creatives = [] assigned_placements = [] assigned_event_tags = [] for assignment in feed_item['creative_assignment']: creative = self._creative_dao.get(assignment, req...
Updates the ad by setting the values of child objects based on secondary feeds. Args: feed_item: Feed item representing the ad from the Bulkdozer feed. creative_assignments: Feed items representing creative assignments related with the current ad. placement_assignments: Feed items representing placement assignments re...
github-repos
def initialize(self, table): check_table_dtypes(table, self._keys.dtype, self._values.dtype) with ops.name_scope(self._name, values=(table.resource_handle, self._keys, self._values)): init_op = gen_lookup_ops.lookup_table_import_v2(table.resource_handle, self._keys, self._values) ops.add_to_collecti...
Initializes the given `table` with `keys` and `values` tensors. Args: table: The table to initialize. Returns: The operation that initializes the table. Raises: TypeError: when the keys and values data types do not match the table key and value data types.
github-repos
def trigger(self, attr, old, new, hint=None, setter=None): def invoke(): callbacks = self._callbacks.get(attr) if callbacks: for callback in callbacks: callback(attr, old, new) if (hasattr(self, '_document') and (self._document is not None)): self._document._...
Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None
codesearchnet
def num_fmt(num, max_digits=None): if (num is None): return 'None' def num_in_mag(num, mag): return ((mag > num) and (num > ((- 1) * mag))) if (max_digits is None): if num_in_mag(num, 1): if num_in_mag(num, 0.1): max_digits = 4 else: ...
r""" Weird function. Not very well written. Very special case-y Args: num (int or float): max_digits (int): Returns: str: CommandLine: python -m utool.util_num --test-num_fmt Example: >>> # DISABLE_DOCTEST >>> from utool.util_num import * # NOQA >>> # build test data >>> num_list = [0, 0.0, 1.2, 1003232, 41431232....
codesearchnet
def are_equal(self, mol1, mol2): b1 = set(self._get_bonds(mol1)) b2 = set(self._get_bonds(mol2)) return (b1 == b2)
Compare the bond table of the two molecules. Args: mol1: first molecule. pymatgen Molecule object. mol2: second moleculs. pymatgen Molecule objec.
codesearchnet
def __init__(self, stream): super(BinaryWriter, self).__init__() self.stream = stream
Create an instance. Args: stream (BytesIO): a stream to operate on. i.e. a neo.IO.MemoryStream or raw BytesIO.
juraj-google-style
def __init__(self, key, b64secret, passphrase, api_url="https: super(AuthenticatedClient, self).__init__(api_url) self.auth = CBProAuth(key, b64secret, passphrase) self.session = requests.Session()
Create an instance of the AuthenticatedClient class. Args: key (str): Your API key. b64secret (str): The secret key matching your API key. passphrase (str): Passphrase chosen when setting up key. api_url (Optional[str]): API URL. Defaults to cbpro API.
juraj-google-style
def _to_proto_sparse_tensor(sparse_tensor, nested_proto, process_leafs, already_processed): already_processed.add(id(sparse_tensor)) nested_proto.named_tuple.name = _SPARSE_TENSOR_NAME for str_key in _SPARSE_TENSOR_FIELD: tensor = getattr(sparse_tensor, str_key) nested_proto.named_tuple.map[...
Serializes a `tf.SparseTensor` into `nested_proto`. Args: sparse_tensor: An instance of `tf.SparseTensor`. nested_proto: A `module_pb2.NestedData` instance to be filled from `sparse_tensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. already_processed: Set of already processed ...
codesearchnet
def create_runner(ns_path, script, runner_type='Auto', optimized=True): if ((runner_type == 'Auto') and DRMAA_AVAILABLE): runner_type = 'GridRunner' elif (runner_type == 'Auto'): runner_type = 'ParallelRunner' return locals().get(runner_type, globals().get(runner_type))(ns_path, script, opti...
Create a SimulationRunner from a string containing the desired class implementation, and return it. Args: ns_path (str): path to the ns-3 installation to employ in this SimulationRunner. script (str): ns-3 script that will be executed to run simulations. runner_type (str): implementation of the SimulationRunner to use...
codesearchnet
def copy_default_config_to_user_directory( basename, clobber=False, dst_dir='~/.config/scriptabit'): dst_dir = os.path.expanduser(dst_dir) dst = os.path.join(dst_dir, basename) src = resource_filename( Requirement.parse("scriptabit"), os.path.join('scriptabit', b...
Copies the default configuration file into the user config directory. Args: basename (str): The base filename. clobber (bool): If True, the default will be written even if a user config already exists. dst_dir (str): The destination directory.
juraj-google-style
def decode(model_path_prefix: Union[(str, Path)], input_paths: Sequence[Path], label_set: Set[str], *, feature_type: str='fbank', batch_size: int=64, feat_dir: Optional[Path]=None, batch_x_name: str='batch_x:0', batch_x_lens_name: str='batch_x_lens:0', output_name: str='hyp_dense_decoded:0') -> List[List[str]]: if ...
Use an existing tensorflow model that exists on disk to decode WAV files. Args: model_path_prefix: The path to the saved tensorflow model. This is the full prefix to the ".ckpt" file. input_paths: A sequence of `pathlib.Path`s to WAV files to put through the model provided. label_set: The set of all the labels this mo...
codesearchnet
def GetArtifactsInProperOrder(self): artifact_list = [] while self.reachable_nodes: node_name = self.reachable_nodes.pop() node = self.graph[node_name] if node.is_artifact: artifact_list.append(node_name) for next_node_name in node.outgoing: if (next_node_...
Bring the artifacts in a linear order that resolves dependencies. This method obtains a linear ordering of the nodes and then returns the list of artifact names. Returns: A list of `ArtifactName` instances such that if they are collected in the given order their dependencies are resolved.
codesearchnet
def getMonthsBuffer(self, direction): if (direction == ReadMonths.kWhReverse): return self.m_rev_mons return self.m_mons
Get the months tariff SerialBlock for meter. Args: direction (int): A :class:`~ekmmeters.ReadMonths` value. Returns: SerialBlock: Requested months tariffs buffer.
codesearchnet
def get_tokens(max_value): vocab = [str(i) for i in range(max_value)] vocab = set(vocab) vocab.update(CodeOp.LITERALS) vocab.update(CodeOp.KEYWORDS) vocab |= set(''.join(vocab)) return sorted(vocab)
Defines tokens. Args: max_value: the maximum numeric range for the token. Returns: list of string tokens in vocabulary.
codesearchnet
def __init__(self, url, username, password, enterprise, apiversion, sdk_identifier, monolithe_config): self.url = url self.username = username self.password = password self.enterprise = enterprise self.apiversion = apiversion self.monolithe_config = monolithe_con...
Initializes Courgette Args: url (string): the url of the server with its port username (string): the username to launch tests password (string): the password to connect to the server enterprise (string): the name of the enterprise to connect to the server apiversion (float): the version of the API to connect sdk (stri...
juraj-google-style
def _expand_and_tile(tensor, multiple, dim=0, name=None): if multiple < 1: raise ValueError(f'Invalid argument multiple={multiple} for expand_and_tile call. `multiple` must be an integer > 0') with ops.name_scope(name, 'expand_and_tile', (tensor, multiple, dim)) as scope: tensor = sparse_tensor...
Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. multiple: Integer, number of times to tile. dim: Integer, dimension along whic...
github-repos
def _configure(self, session_config=None, cluster_spec=None, task_type=None, task_id=None): if cluster_spec: cluster_resolver = cluster_resolver_lib.SimpleClusterResolver(cluster_spec=multi_worker_util.normalize_cluster_spec(cluster_spec), task_type=task_type, task_id=task_id, num_accelerators={'GPU': self....
Configures the strategy class with `cluster_spec`. The strategy object will be re-initialized if `cluster_spec` is passed to `configure` but was not passed when instantiating the strategy. Args: session_config: Session config object. cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the cluster config...
github-repos
def __init__(self, max_batch_size: int=5000, project: str=None, retry: Retry=None, timeout: float=120, metadata: Sequence[Tuple[str, str]]=(), catalog_name: str='default_catalog', event_store: str='default_event_store'): self.max_batch_size = max_batch_size self.project = project self.retry = retry self...
Initializes a :class:`WriteUserEvent` transform. Args: batch_size (int): Required. Maximum number of catalogitems per request. project (str): Optional. GCP project name in which the catalog data will be imported. retry: Optional. Designation of what errors, if any, should be retried. timeout (float): Optional. The amo...
github-repos