code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
class _TrainingTarget(object): def __init__(self, target, feedable=False, skip_target_weights=True): self._target = target self._feedable = feedable self._skip_target_weights = skip_target_weights @property def target(self): return self._target @property def feedab...
Container for a target tensor (y_true) and its metadata (shape, loss...). Args: target: A target tensor for the model. It may be `None` if the output is excluded from loss computation. It is still kept as None since each output of the model should have a corresponding target. If the target is None, the rest of the att...
github-repos
def energy(self, sample_like, dtype=np.float): (energy,) = self.energies(sample_like, dtype=dtype) return energy
The energy of the given sample. Args: sample_like (samples_like): A raw sample. `sample_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`, optional): The data type of the returned energies. Defaults to float. Returns: The energy.
codesearchnet
def Unlock(fd, path): try: fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB) except IOError as e: if e.errno == errno.EWOULDBLOCK: raise IOError('Exception unlocking %s. Locked by another process.' % path) else: raise IOError('Exception unlocking %s. %s.' % (path, str(e)))
Release the lock on the file. Args: fd: int, the file descriptor of the file to unlock. path: string, the name of the file to lock. Raises: IOError, raised from flock while attempting to release a file lock.
juraj-google-style
def ParseOptions(self, options): helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=['data_location']) signature_identifiers = self.ParseStringOption( options, 'signature_identifiers') if signature_identifiers == 'list': self.list_signature_identif...
Parses the options and initializes the front-end. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
juraj-google-style
def convert_and_export_with_cache(model: PreTrainedModel, example_input_ids: Optional[torch.Tensor]=None, example_cache_position: Optional[torch.Tensor]=None, dynamic_shapes: Optional[dict]=None, strict: Optional[bool]=None): if not is_torch_greater_or_equal_than_2_3: raise ImportError('torch >= 2.3 is requ...
Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`. Args: model (`PreTrainedModel`): The pretrained model to be exported. example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`. examp...
github-repos
def write(self, brightness): if (not isinstance(brightness, (bool, int))): raise TypeError('Invalid brightness type, should be bool or int.') if isinstance(brightness, bool): brightness = (self._max_brightness if brightness else 0) elif (not (0 <= brightness <= self._max_brightness)): ...
Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS error occurs. TypeError: if `brightness` type is not bool or int.
codesearchnet
def InitFromNotification(self, notification, is_pending=False): self.timestamp = notification.timestamp self.message = notification.message self.subject = str(notification.subject) self.is_pending = is_pending reference_type_enum = ApiNotificationReference.Type le...
Initializes this object from an existing notification. Args: notification: A rdfvalues.flows.Notification object. is_pending: Indicates whether the user has already seen this notification or not. Returns: The current instance.
juraj-google-style
def napalm_configure(task: Task, dry_run: Optional[bool]=None, filename: Optional[str]=None, configuration: Optional[str]=None, replace: bool=False) -> Result: device = task.host.get_connection('napalm', task.nornir.config) if replace: device.load_replace_candidate(filename=filename, config=configuratio...
Loads configuration into a network devices using napalm Arguments: dry_run: Whether to apply changes or not filename: filename containing the configuration to load into the device configuration: configuration to load into the device replace: whether to replace or merge the configuration Returns: Result object with th...
codesearchnet
def get_linux_config(browser: str) -> dict: if browser.lower() == 'chrome': cookie_file = '~/.config/google-chrome/Default/Cookies' elif browser.lower() == "chromium": cookie_file = '~/.config/chromium/Default/Cookies' else: raise ValueError("Browser must be either Chrome o...
Get the settings for Chrome/Chromium cookies on Linux. Args: browser: Either "Chrome" or "Chromium" Returns: Config dictionary for Chrome/Chromium cookie decryption
juraj-google-style
def record(self, flat_outputs, inference_args, input_tangents): backward_function, to_record = self._backward(flat_outputs) record.record_operation(self._inference_function.cached_definition.signature.name, to_record, inference_args + input_tangents, backward_function)
Record the function call operation. _DelayedRewriteGradientFunctions supports only first-order backprop tape gradients (and then only when graph building). It does not work with higher-order tape gradients or forward autodiff, but does work with higher-order symbolic gradients (tf.gradients). Args: flat_outputs: The ...
github-repos
def _MultipleModulesFoundError(path, candidates): assert (len(candidates) > 1) params = ([path] + _StripCommonPathPrefix(candidates[:2])) if (len(candidates) == 2): fmt = ERROR_LOCATION_MULTIPLE_MODULES_3 else: fmt = ERROR_LOCATION_MULTIPLE_MODULES_4 params.append(str((len(candid...
Generates an error message to be used when multiple matches are found. Args: path: The breakpoint location path that the user provided. candidates: List of paths that match the user provided path. Must contain at least 2 entries (throws AssertionError otherwise). Returns: A (format, parameters) tuple that should be u...
codesearchnet
def isexe(*components): _path = path(*components) return isfile(_path) and os.access(_path, os.X_OK)
Return whether a path is an executable file. Arguments: path (str): Path of the file to check. Examples: >>> fs.isexe("/bin/ls") True >>> fs.isexe("/home") False >>> fs.isexe("/not/a/real/path") False Returns: bool: True if file is executable, else false.
juraj-google-style
def _find_dtype(value, preferred): result = _find_dtype_helper(value, preferred) if result == dtypes.int64 or result == dtypes.int32 or result is None: return result raise ValueError('Illegal dtype: ' + str(result))
Returns the preferred dtype of value or preferred if preferred != None. This is used as an operator to pass over multiple objects in decreasing order of priority until there is a preferred dtype for one. For example, if you were adding three tensor-ish things (some tensors, some lists), and needed a preferred dtype, y...
github-repos
def incoming_edges(self, node): edges = self.edges() in_edges = [] for out_node, in_node in edges: if node is in_node: in_edges.append((out_node, in_node)) return tuple(in_edges)
Returns a ``tuple`` of incoming edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for incoming edges.
juraj-google-style
def get_lock_request(name, version, patch_lock, weak=True): ch = ('~' if weak else '') if (patch_lock == PatchLock.lock): s = ('%s%s==%s' % (ch, name, str(version))) return PackageRequest(s) elif ((patch_lock == PatchLock.no_lock) or (not version)): return None version_ = version...
Given a package and patch lock, return the equivalent request. For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent request is '~foo-1.2'. This restricts updates to foo to patch-or-lower version changes only. For objects not versioned down to a given lock level, the closest possible lock is appl...
codesearchnet
def _tpu_service(self): if self._service: return self._service if not _GOOGLE_API_CLIENT_INSTALLED: raise RuntimeError('Missing runtime dependency on the Google API client. Run `pip install cloud-tpu-client` to fix.') credentials = self._credentials if credentials is None or credentials ...
Creates a new Cloud TPU API object. This works around an issue where the underlying HTTP connection sometimes times out when the script has been running for too long. Other methods in this object call this method to get a new API object whenever they need to communicate with the Cloud API. Raises: RuntimeError: If th...
github-repos
def build_gemini_query(self, query, extra_info): if 'WHERE' in query: return "{0} AND {1}".format(query, extra_info) else: return "{0} WHERE {1}".format(query, extra_info)
Append sql to a gemini query Args: query(str): The gemini query extra_info(str): The text that should be added Return: extended_query(str)
juraj-google-style
def sample_variants(self, variants, sample_name, category = 'snv'): LOG.info('Retrieving variants for subject : {0}'.format(sample_name)) has_allele = re.compile('1|2') query = { '$and': [ {'_id' : { '$in' : variants}}, {'category' : categor...
Given a list of variants get variant objects found in a specific patient Args: variants(list): a list of variant ids sample_name(str): a sample display name category(str): 'snv', 'sv' .. Returns: result(iterable(Variant))
juraj-google-style
def __call__(self, shape, dtype=dtypes.float32, **kwargs): self._validate_kwargs(kwargs) dtype = _assert_float_dtype(dtype) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] return self._random_generator.random_normal(shape, self.mean, self.stddev, dtype)
Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. **kwargs: Additional keyword arguments. Raises: ValueError: If the dtype is not floating point
github-repos
def recipe_bulkdozer(config, recipe_timezone, account_id, dcm_profile_id, sheet_url): traffic(config, {'hour': [], 'account_id': account_id, 'dcm_profile_id': dcm_profile_id, 'auth': 'user', 'sheet_url': sheet_url, 'timezone': recipe_timezone})
Bulkdozer is a tool that can reduce trafficking time in Campaign Manager by up to 80%% by providing automated bulk editing capabilities. Args: recipe_timezone (timezone) - Timezone for report dates. account_id (string) - Campaign Manager Network ID (optional if profile id provided) dcm_profile_id (string) - Campaign M...
github-repos
def kron_with_controls(*matrices: np.ndarray) -> np.ndarray: product = kron(*matrices) for i in range(product.shape[0]): for j in range(product.shape[1]): if np.isnan(product[(i, j)]): product[(i, j)] = (1 if (i == j) else 0) return product
Computes the kronecker product of a sequence of matrices and controls. Use linalg.CONTROL_TAG to represent controls. Any entry of the output matrix corresponding to a situation where the control is not satisfied will be overwritten by identity matrix elements. The control logic works by imbuing NaN with the meaning "...
codesearchnet
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
Train model using CloudML. See local_train() for a description of the args. Args: config: A CloudTrainingConfig object. job_name: Training job name. A default will be picked if None.
juraj-google-style
def to_diff_dict(self) -> dict[str, Any]: config_dict = self.to_dict() default_config_dict = PretrainedConfig().to_dict() class_config_dict = self.__class__().to_dict() if not self.has_no_defaults_at_init else {} serializable_config_dict = {} for key, value in config_dict.items(): if isinsta...
Removes all attributes from the configuration that correspond to the default config attributes for better readability, while always retaining the `config` attribute from the class. Serializes to a Python dictionary. Returns: Dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
github-repos
def service_messages(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return list(self.services[short_name]['state'].messages)
Get the messages stored for a service. Args: short_name (string): The short name of the service to get messages for Returns: list(ServiceMessage): A list of the ServiceMessages stored for this service
juraj-google-style
def _PrintExtractionStatusUpdateWindow(self, processing_status): if self._stdout_output_writer: self._ClearScreen() output_text = 'plaso - {0:s} version {1:s}\n\n'.format(self._tool_name, plaso.__version__) self._output_writer.Write(output_text) self.PrintExtractionStatusHeader(processing_status...
Prints an extraction status update in window mode. Args: processing_status (ProcessingStatus): processing status.
codesearchnet
class StackedRNNCells(Layer): def __init__(self, cells, **kwargs): super().__init__(**kwargs) for cell in cells: if 'call' not in dir(cell): raise ValueError(f'All cells must have a `call` method. Received cell without a `call` method: {cell}') if 'state_size...
Wrapper allowing a stack of RNN cells to behave as a single cell. Used to implement efficient stacked RNNs. Args: cells: List of RNN cell instances. Example: ```python batch_size = 3 sentence_length = 5 num_features = 2 new_shape = (batch_size, sentence_length, num_features) x = np.reshape(np.arange(30), new_shape)...
github-repos
def _update_data(self, data): self.data = data child_change_dict = {} for name in self.children: child_data = getattr(data, name, None) if (child_data is None): child_change_dict[name] = [[]] else: child_change_dict[name] = [[], child_data] return child_ch...
Set our data and notify any subscribers of children what has changed Args: data (object): The new data Returns: dict: {child_name: [path_list, optional child_data]} of the change that needs to be passed to a child as a result of this
codesearchnet
def _BatchNormGrad(grad_y, x, scale, pop_mean, pop_var, epsilon, data_format, is_training=True): x_dtype = x.dtype.base_dtype if x_dtype == dtypes.float16 or x_dtype == dtypes.bfloat16: x = math_ops.cast(x, dtypes.float32) grad_y = math_ops.cast(grad_y, dtypes.float32) if is_training: ...
Returns the gradients for the 3 inputs of BatchNorm. Args: grad_y: A `Tensor` of 4 or 5 dimensions for gradient for y. x: A `Tensor` of 4 or 5 dimensions for x. scale: A `Tensor` of 1 dimension for scaling. pop_mean: A `Tensor` of 1 dimension for the population mean. Only used when is_training=False. pop_var: A `Tenso...
github-repos
def _predictResponseSize(mode, functioncode, payloadToSlave): MIN_PAYLOAD_LENGTH = 4 BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4 NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1 RTU_TO_ASCII_PAYLOAD_FACTOR = 2 NUMBER_OF_RTU_RESPONSE_STARTBYT...
Calculate the number of bytes that should be received from the slave. Args: * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Modbus function code. * payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string) Returns: The preducted number of bytes...
juraj-google-style
def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') return response
Modifies the response object prior to sending it to the client. Used to add CORS headers to the request Args: response (response): Flask response object Returns: `None`
juraj-google-style
def decode_bu64(b): s = b s = s.replace(b'-', b'+') s = s.replace(b'_', b'/') p = len(s) % 4 if p == 0: pass elif p == 2: s += b'==' elif p == 3: s += b'=' else: raise ValueError('Illegal Base64url string') return base64.standard_b64decode(s)
Encode bytes to a URL safe flavor of Base64 used by JWTs. - Reverse of encode_bu64(). Args: b: bytes URL safe Base64 encoded bytes to encode. Returns: bytes: Decoded bytes.
juraj-google-style
def get_init_tokens_op(self, num_tokens=-1): if self._gradients_applied is False: raise ValueError('get_init_tokens_op() should be called after apply_gradients().') tokens_needed = self._replicas_to_aggregate - self._total_num_replicas if num_tokens == -1: num_tokens = self._replicas_to_aggr...
Returns the op to fill the sync_token_queue with the tokens. This is supposed to be executed in the beginning of the chief/sync thread so that even if the total_num_replicas is less than replicas_to_aggregate, the model can still proceed as the replicas can compute multiple steps per variable update. Make sure: `num_t...
github-repos
def _GetFieldByName(message_descriptor, field_name): try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError(('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name)))
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name.
codesearchnet
def reflection(normal, origin=(0, 0, 0)): n = np.array(normal, dtype=float) / np.linalg.norm(normal) u, v, w = n translation = np.eye(4) translation[0:3, 3] = -np.array(origin) xx = 1 - 2 * u ** 2 yy = 1 - 2 * v ** 2 zz = 1 - 2 * w ** 2 ...
Returns reflection symmetry operation. Args: normal (3x1 array): Vector of the normal to the plane of reflection. origin (3x1 array): A point in which the mirror plane passes through. Returns: SymmOp for the reflection about the plane
juraj-google-style
def _save_state_and_schedule_next(self, shard_state, tstate, task_directive): spec = tstate.mapreduce_spec if task_directive == self._TASK_DIRECTIVE.DROP_TASK: return if task_directive in (self._TASK_DIRECTIVE.RETRY_SLICE, self._TASK_DIRECTIVE.RETRY_TASK): ...
Save state and schedule task. Save shard state to datastore. Schedule next slice if needed. Set HTTP response code. No modification to any shard_state or tstate. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. task_directive: enum _TASK_DIRECTIVE. Returns: ...
juraj-google-style
def __call__(self, shape, dtype=None, **kwargs): raise NotImplementedError
Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. **kwargs: Additional keyword arguments.
github-repos
def tarfile_extract(fileobj, dest_path): tar = tarfile.open(mode='r|', fileobj=fileobj, bufsize=pipebuf.PIPE_BUF_BYTES) dest_path = os.path.realpath(dest_path) extracted_files = [] for member in tar: assert (not member.name.startswith('/')) relpath = os.path.join(dest_path, member.name) ...
Extract a tarfile described by a file object to a specified path. Args: fileobj (file): File object wrapping the target tarfile. dest_path (str): Path to extract the contents of the tarfile to.
codesearchnet
def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from append iterator") if not isinstance(variables, list): raise ValueError( f"Append keyword only takes a list of arguments, got {variables} of type {type(variables)}" ) ...
This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` function to achieve this. This function is particularly useful for specifying multi...
juraj-google-style
def process_rewards(self, rewards): (min_reward, max_reward) = self.reward_range rewards = np.clip(rewards, min_reward, max_reward) rewards = np.around(rewards, decimals=0).astype(np.int64) return rewards
Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64
codesearchnet
def get_arrays(self, type_img): if type_img.lower() == 'lola': return LolaMap(self.ppdlola, *self.window, path_pdsfile=self.path_pdsfiles).image() elif type_img.lower() == 'wac': return WacMap(self.ppdwac, *self.window, path_pdsfile=self.path_pdsfiles).image() e...
Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted for the region of interest. Note: The argument has to be either lola or wac. Note case sensitive....
juraj-google-style
def _get_object_checkpoint_renames(path, variable_names): fname = checkpoint_utils._get_checkpoint_filename(path) try: names_to_keys = saver_lib.object_graph_key_mapping(fname) except errors.NotFoundError: return {} missing_names = set(variable_names) - set(names_to_keys.keys()) if m...
Returns a dictionary mapping variable names to checkpoint keys. The warm-starting utility expects variable names to match with the variable names in the checkpoint. For object-based checkpoints, the variable names and names in the checkpoint are different. Thus, for object-based checkpoints, this function is used to o...
github-repos
def emit(self, record): record.task = self.cur_task if record.levelno >= self.dump_level and self.cur_task: self.tasks[self.cur_task].failed = True self.tasks[self.cur_task].force_show = True is_start = START_TASK_REG.match(str(record.msg)) if ...
Handle the given record, this is the entry point from the python logging facility Params: record (logging.LogRecord): log record to handle Returns: None
juraj-google-style
def indent(self, node, dirty=True): if node.subitems: return self._subitems[node.id] = node node.super_list_item_id = self.id node.parent_item = self if dirty: node.touch(True)
Indent an item. Does nothing if the target has subitems. Args: node (gkeepapi.node.ListItem): Item to indent. dirty (bool): Whether this node should be marked dirty.
juraj-google-style
def __init__(self, details): if not isinstance(details, dict): raise ValueError('details') if '__hash__' not in details: raise KeyError('__hash__') if '__optional__' in details: bOptional = details['__optional__'] del details['__optional__'] else: bOptional = None if detai...
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: KeyError ValueError Returns: HashNode
juraj-google-style
def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]: if bo.ast: bo = validate_functions(bo.ast, bo) if error_level == "WARNING": bo = validate_arg_values(bo.ast, bo) else: bo.validation_messages.append(("ERROR", "Invalid BEL Stateme...
Semantically validate BEL AST Add errors and warnings to bel_obj.validation_messages Error Levels are similar to log levels - selecting WARNING includes both WARNING and ERROR, selecting ERROR just includes ERROR Args: bo: main BEL language object error_level: return ERRORs only or also WARNINGs Returns: Tuple[bool...
juraj-google-style
def verify_tensor_all_finite(t=None, msg=None, name=None, x=None, message=None): x = deprecation.deprecated_argument_lookup('x', x, 't', t) message = deprecation.deprecated_argument_lookup('message', message, 'msg', msg) return verify_tensor_all_finite_v2(x, message, name)
Assert that the tensor does not contain any NaN's or Inf's. Args: t: Tensor to check. msg: Message to log on failure. name: A name for this operation (optional). x: Alias for t. message: Alias for msg. Returns: Same tensor as `t`.
github-repos
def get_svg_layers(svg_sources): layers = [] (width, height) = (None, None) def extract_length(attr): 'Extract length in pixels.' match = CRE_MM_LENGTH.match(attr) if match: return (INKSCAPE_PPmm.magnitude * float(match.group('length'))) else: return ...
Collect layers from input svg sources. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. Returns ------- (width, height), layers : (int, int), list The first item in the tuple is the shape of the largest layer, and the second item is a list of ``Element`` objects (from :...
codesearchnet
def normalize_keypoints(keypoints: torch.Tensor, height: int, width: int) -> torch.Tensor: size = torch.tensor([width, height], device=keypoints.device, dtype=keypoints.dtype)[None] center = size / 2 scaling = size.max(1, keepdim=True).values * 0.7 return (keypoints - center[:, None, :]) / scaling[:, No...
Normalize keypoints locations based on image image_shape Args: keypoints (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`): Keypoints locations in (x, y) format. height (`int`): Image height. width (`int`): Image width. Returns: Normalized keypoints locations of shape (`torch.Tensor` of shape `(batch_size, n...
github-repos
def read_string_array(self, key, embedded=True): data = None if key is not None: key_type = self.variable_type(key) data = self.db.read(key.strip()) if embedded: data = self.read_embedded(data, key_type) if data is not None: ...
Read method of CRUD operation for string array data. Args: key (string): The variable to read from the DB. embedded (boolean): Resolve embedded variables. Returns: (list): Results retrieved from DB.
juraj-google-style
def _OpenFile(self, path): if not self._registry_file_reader: return None return self._registry_file_reader.Open( path, ascii_codepage=self._ascii_codepage)
Opens a Windows Registry file. Args: path (str): path of the Windows Registry file. Returns: WinRegistryFile: Windows Registry file or None if not available.
juraj-google-style
def _validate_oneof_field_multi_mapping(src_pb, dest_pb, ignored_fields): ignored_fields_set = set(ignored_fields) src_oneof_names_dict = src_pb.DESCRIPTOR.oneofs_by_name dest_oneof_dict = _get_fields_to_oneof_dict(dest_pb.DESCRIPTOR.oneofs_by_name) dest_field_names = set(dest_pb.DESCRIPTOR.fields_by_na...
Validates if the oneof field on src_pb maps to multiple fields. Args: src_pb: the proto to check oneof from. dest_pb: the proto to check oneof against. ignored_fields: fields that skip the check. Exception: Raises NotImplementedError if any oneof field in src_pb maps to multiple fields from dest_pb.
github-repos
def is_likely_link(text): text = text.lower() if (text.startswith('http: return True (dummy, dot, file_extension) = text.rpartition('.') if (dot and file_extension and (len(file_extension) <= 4)): file_extension_set = frozenset(file_extension) if (file_extension_set and (file_ext...
Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
codesearchnet
def GetMerger(self, cls): for merger in self._mergers: if isinstance(merger, cls): return merger raise LookupError('No matching DataSetMerger found')
Looks for an added DataSetMerger derived from the given class. Args: cls: A class derived from DataSetMerger. Returns: The matching DataSetMerger instance. Raises: LookupError: No matching DataSetMerger has been added.
codesearchnet
def __init__(self, nrows=None, nvals=None, uniform_row_length=None, dtype=dtypes.int64): nrows = tensor_shape.TensorShape([nrows]) nvals = tensor_shape.TensorShape([nvals]) if not isinstance(uniform_row_length, tensor_shape.TensorShape): uniform_row_length = tensor_shape.TensorShape([uniform_row_len...
Constructs a new RowPartitionSpec. Args: nrows: The number of rows in the RowPartition, or `None` if unspecified. nvals: The number of values partitioned by the RowPartition, or `None` if unspecified. uniform_row_length: The number of values in each row for this RowPartition, or `None` if rows are ragged or row length...
github-repos
def _check_dep(self, depinfo, deptile, resolver): try: settings = self._load_depsettings(deptile) except IOError: return False if (settings['resolver'] != resolver.__class__.__name__): return None resolver_settings = {} if ('settings' in settings): resolver_settings =...
Check if a dependency tile is up to date Returns: bool: True if it is up to date, False if it not and None if this resolver cannot assess whether or not it is up to date.
codesearchnet
def git_clone(prettyname: str, url: str, directory: str, branch: str = None, commit: str = None, clone_options: List[str] = None, run_func: Callable[[List[str]], Any] = None) -> bool: run_func = run_func or subprocess.check_call clone_options = clone_...
Fetches a Git repository, unless we have it already. Args: prettyname: name to display to user url: URL directory: destination directory branch: repository branch commit: repository commit tag clone_options: additional options to pass to ``git clone`` run_func: function to use to call an external command Returns: did...
juraj-google-style
def _GetDistinctValues(self, field_name): self._cursor.execute('SELECT {0:s}, COUNT({0:s}) FROM log2timeline GROUP BY {0:s}'.format(field_name)) result = {} row = self._cursor.fetchone() while row: if row[0]: result[row[0]] = row[1] row = self._cursor.fetchone() return re...
Query database for unique field types. Args: field_name (str): name of the filed to retrieve. Returns: dict[str, int]: counts of field types by name.
codesearchnet
def HasStorage(self): from neo.Core.State.ContractState import ContractPropertyState return ((self.ContractProperties & ContractPropertyState.HasStorage) > 0)
Flag indicating if storage is available. Returns: bool: True if available. False otherwise.
codesearchnet
def download_artifact_bundle(self, id_or_uri, file_path): uri = ((self.DOWNLOAD_PATH + '/') + extract_id_from_uri(id_or_uri)) return self._client.download(uri, file_path)
Download the Artifact Bundle. Args: id_or_uri: ID or URI of the Artifact Bundle. file_path(str): Destination file path. Returns: bool: Successfully downloaded.
codesearchnet
def time_range_to_frame_range(self, start, end, sr): start_sample = seconds_to_sample(start, sr) end_sample = seconds_to_sample(end, sr) return (self.sample_to_frame_range(start_sample)[0], self.sample_to_frame_range((end_sample - 1))[1])
Calculate the frames containing samples from the given time range in seconds. Args: start (float): Start time in seconds. end (float): End time in seconds. sr (int): The sampling rate to use for time-to-sample conversion. Returns: tuple: A tuple containing the start and end (exclusive) frame indices.
codesearchnet
def canonicalize(self, namespace_targets: Mapping[(str, List[str])]=None) -> 'BEL': if (not self.ast): return self if (not self.ast.collected_nsarg_norms): self = self.collect_nsarg_norms() self.ast.canonicalize() return self
Takes an AST and returns a canonicalized BEL statement string. Args: namespace_targets (Mapping[str, List[str]]): override default canonicalization settings of BEL.bio API api_url - see {api_url}/status to get default canonicalization settings Returns: BEL: returns self
codesearchnet
def mod(x1, x2): if any_symbolic_tensors((x1, x2)): return Mod().symbolic_call(x1, x2) return backend.numpy.mod(x1, x2)
Returns the element-wise remainder of division. Args: x1: First tensor. x2: Second tensor. Returns: Output tensor, element-wise remainder of division.
github-repos
async def snap(self, user=None, view=None): if (view is None): view = self.view if (user is None): user = self.auth.getUserByName('root') snap = (await view.snap(user)) return snap
Return a transaction object for the default view. Args: write (bool): Set to True for a write transaction. Returns: (synapse.lib.snap.Snap) NOTE: This must be used in a with block.
codesearchnet
def set_json(self, obj, status=HttpStatusCodes.HTTP_200): obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x)) self.set_status(status) self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json') self.set_content(obj)
Helper method to set a JSON response. Args: obj (:obj:`object`): JSON serializable object status (:obj:`str`, optional): Status code of the response
juraj-google-style
def placeOrder(self, contract: Contract, order: Order) -> Trade: orderId = (order.orderId or self.client.getReqId()) self.client.placeOrder(orderId, contract, order) now = datetime.datetime.now(datetime.timezone.utc) key = self.wrapper.orderKey(self.wrapper.clientId, orderId, order.permId) trade = s...
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes, fills, etc. Args: contract: Contract to use for order. order: The order to be placed.
codesearchnet
def _ParseLastRunTime(self, parser_mediator, fixed_length_section): systemtime_struct = fixed_length_section.last_run_time system_time_tuple = ( systemtime_struct.year, systemtime_struct.month, systemtime_struct.weekday, systemtime_struct.day_of_month, systemtime_struct.hours, syste...
Parses the last run time from a fixed-length data section. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. fixed_length_section (job_fixed_length_data_section): a Windows Scheduled Task job fixed-length data section. Returns: dfdatetime.Da...
juraj-google-style
def add_notification_listener(self, notification_type, notification_callback): if (notification_type not in self.notifications): self.notifications[notification_type] = [(self.notification_id, notification_callback)] else: if (reduce((lambda a, b: (a + 1)), filter((lambda tup: (tup[1] == notific...
Add a notification callback to the notification center. Args: notification_type: A string representing the notification type from .helpers.enums.NotificationTypes notification_callback: closure of function to call when event is triggered. Returns: Integer notification id used to remove the notification or -1 if the n...
codesearchnet
def list_permissions(self, group_name=None, resource=None): self.project_service.set_auth(self._token_project) return self.project_service.list_permissions(group_name, resource)
List permission sets associated filtering by group and/or resource. Args: group_name (string): Name of group. resource (intern.resource.boss.Resource): Identifies which data model object to operate on. Returns: (list): List of permissions. Raises: requests.HTTPError on failure.
juraj-google-style
def _Upgrade2To3(self, data): buffers = [{'data': []}] for subgraph in data['subgraphs']: if 'tensors' not in subgraph: continue for tensor in subgraph['tensors']: if 'data_buffer' not in tensor: tensor['buffer'] = 0 else: if te...
Upgrade data from Version 2 to Version 3. Changed actual read-only tensor data to be in a buffers table instead of inline with the tensor. Args: data: Dictionary representing the TensorFlow lite data to be upgraded. This will be modified in-place to be an upgraded version.
github-repos
def resume(self, email, master_token, state=None, sync=True): auth = APIAuth(self.OAUTH_SCOPES) ret = auth.load(email, master_token, android_id=get_mac()) if ret: self.load(auth, state, sync) return ret
Authenticate to Google with the provided master token & sync. Args: email (str): The account to use. master_token (str): The master token. state (dict): Serialized state to load. Raises: LoginException: If there was a problem logging in.
juraj-google-style
class Embedding: dense_embedding: Optional[List[float]] = None sparse_embedding: Optional[Tuple[List[int], List[float]]] = None
Represents vector embeddings. Args: dense_embedding: Dense vector representation sparse_embedding: Optional sparse vector representation for hybrid search
github-repos
def VisitFunction(self, f): signatures = tuple((ex for s in f.signatures for ex in ExpandSignature(s))) return f.Replace(signatures=signatures)
Rebuild the function with the new signatures. This is called after its children (i.e. when VisitSignature has already converted each signature into a list) and rebuilds the function using the new signatures. Arguments: f: A pytd.Function instance. Returns: Function with the new signatures.
github-repos
def __init__(self, channel): self.NewSession = channel.unary_unary('/tensorflow.ProfileAnalysis/NewSession', request_serializer=third__party_dot_tensorflow_dot_core_dot_profiler_dot_profiler__analysis__pb2.NewProfileSessionRequest.SerializeToString, response_deserializer=third__party_dot_tensorflow_dot_core_dot_pro...
Constructor. Args: channel: A grpc.Channel.
github-repos
def traverse_inorder(self, leaves=True, internal=True): c = self s = deque() done = False while (not done): if (c is None): if (len(s) == 0): done = True else: c = s.pop() if ((leaves and c.is_leaf()) or (internal and (not c...
Perform an inorder traversal starting at this ``Node`` object Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
codesearchnet
def find_in_mailbox(cls, session, mailbox_or_id): if hasattr(mailbox_or_id, 'id'): mailbox_or_id = mailbox_or_id.id return cls( '/mailboxes/%d/users.json' % mailbox_or_id, session=session, )
Get the users that are associated to a Mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox_or_id (MailboxRef or int): Mailbox of the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.User): Users iterator.
juraj-google-style
def make_df_from_batch(batch_name, batch_col="b01", reader=None, reader_label=None): batch_name = batch_name batch_col = batch_col logger.debug(f"batch_name, batch_col: {batch_name}, {batch_col}") if reader is None: reader_obj = get_db_reader(reader_label) reader = reader_obj() ...
Create a pandas DataFrame with the info needed for ``cellpy`` to load the runs. Args: batch_name (str): Name of the batch. batch_col (str): The column where the batch name is in the db. reader (method): the db-loader method. reader_label (str): the label for the db-loader (if db-loader method is not given) Returns: i...
juraj-google-style
def remove_config(reset=False): cmd = 'Stop-DscConfiguration' log.info('DSC: Stopping Running Configuration') try: _pshell(cmd) except CommandExecutionError as exc: if (exc.info['retcode'] != 0): raise CommandExecutionError('Failed to Stop DSC Configuration', info=exc.info) ...
Remove the current DSC Configuration. Removes current, pending, and previous dsc configurations. .. versionadded:: 2017.7.5 Args: reset (bool): Attempts to reset the DSC configuration by removing the following from ``C:\\Windows\\System32\\Configuration``: - File: DSCStatusHistory.mof - File: DSCEngineCache.mof - Di...
codesearchnet
def json(self, json): self._request.json = json self.add_matcher(matcher('JSONMatcher', json))
Defines the JSON body to match. ``json`` argument can be an JSON string, a JSON serializable Python structure, such as a ``dict`` or ``list`` or it can be a regular expression used to match the body. Arguments: json (str|dict|list|regex): body JSON to match. Returns: self: current Mock instance.
juraj-google-style
def get_gpus(num_gpu=1, worker_index=-1): list_gpus = subprocess.check_output(["nvidia-smi", "--list-gpus"]).decode() logging.debug("all GPUs:\n{0}".format(list_gpus)) gpus = [x for x in list_gpus.split('\n') if len(x) > 0] def parse_gpu(gpu_str): cols = gpu_str.split(' ') return cols[5].spli...
Get list of free GPUs according to nvidia-smi. This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available. Args: :num_gpu: number of GPUs desired. :worker_index: index "hint" for allocation of available GPUs. Returns: Comma-delimited string of GPU ids, or raises an Exception if the re...
juraj-google-style
def prettyprint_cfg_tree(root, decorate_after_node=0, full=False, forward=False): if forward: children = lambda node: node.outgoing else: children = lambda node: node.incoming desc = lambda node: prettyprint_cfg_node(node, decorate_after_node, full) return ascii_tree(root, get_children=c...
Pretty print a cfg tree with the bindings at each node. Args: root: The root node. decorate_after_node: Don't print bindings unless node_id > this. full: Print the full string representation of a binding's data forward: Traverse the tree forwards if true. Returns: A prettyprinted tree.
github-repos
def _convert_bytes_to_cc_source(data, array_name, max_line_width=80, include_guard=None, include_path=None, use_tensorflow_license=False): starting_pad = ' ' array_lines = [] array_line = starting_pad for value in bytearray(data): if len(array_line) + 4 > max_line_width: array_line...
Returns strings representing a C++ constant array containing `data`. Args: data: Byte array that will be converted into a C++ constant. array_name: String to use as the variable name for the constant array. max_line_width: The longest line length, for formatting purposes. include_guard: Name to use for the include gua...
github-repos
def create_from_binary(cls, binary_view): nw_obj = cls() offset = 0 previous_dr_offset = 0 header_size = cls._INFO.size while binary_view[offset] != 0: header = cls._INFO.unpack(binary_view[offset:offset+header_size])[0] length_len = header &...
Creates a new object DataRuns from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary stream with the information of the attribute Returns: DataRuns: New object using hte binary stream as source
juraj-google-style
def create_nsg(access_token, subscription_id, resource_group, nsg_name, location): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurity...
Create network security group (use create_nsg_rule() to add rules to it). Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the new NSG. location (str): Azure data center location. E.g. we...
juraj-google-style
def build_frontend(self, frontend_node): proxy_name = frontend_node.frontend_header.proxy_name.text service_address_node = frontend_node.frontend_header.service_address config_block_lines = self.__build_config_block(frontend_node.config_block) (host, port) = ('', '') if isinstance(service_address_no...
parse `frontend` sections, and return a config.Frontend Args: frontend_node (TreeNode): Description Raises: Exception: Description Returns: config.Frontend: an object
codesearchnet
def compose(*parameter_functions): def composed_fn(var_name, variable, phase): for fn in parameter_functions: variable = fn(var_name, variable, phase) return variable return composed_fn
Composes multiple modification functions in order. Args: *parameter_functions: The functions to compose. Returns: A parameter modification function that consists of applying all the provided functions.
juraj-google-style
def get_import(self, file_prefixes_to_strip: Sequence[str], module_prefix: str, use_lazy_loading: bool) -> str: module_import_path = _get_import_path(self.exported_symbol.file_name, file_prefixes_to_strip, module_prefix) alias = '' symbol_name = self.exported_symbol.symbol_name if self.name != symbol_na...
Returns the import statement for this entrypoint. Args: file_prefixes_to_strip: List of prefixes to strip from the file name. module_prefix: A prefix to add to the import. use_lazy_loading: Whether to use lazy loading or not.
github-repos
def extract_issuer_ca_cert_url(cert_obj): for extension in cert_obj.extensions: if (extension.oid.dotted_string == AUTHORITY_INFO_ACCESS_OID): authority_info_access = extension.value for access_description in authority_info_access: if (access_description.access_method...
Extract issuer CA certificate URL from certificate. Certificates may include a URL where the root certificate for the CA which was used for signing the certificate can be downloaded. This function returns the URL if present. The primary use for this is to fix validation failure due to non-trusted issuer by downloadin...
codesearchnet
def WriteEvent(self, event): self.WriteEventStart() try: self.WriteEventBody(event) except errors.NoFormatterFound as exception: error_message = 'unable to retrieve formatter with error: {0!s}'.format(exception) self._ReportEventError(event, error_message) except errors.WrongForm...
Writes the event to the output. Args: event (EventObject): event.
codesearchnet
def parse_float(value: Any) -> Numeric: return float(value)
Attempts to parse a valid floating point value from the provided value. Args: * value: of Any type Returns: * float value: if valid Raises: * ValueError: if parsing failed
github-repos
def time_to_readable_str(value_us, force_time_unit=None): if not value_us: return '0' if force_time_unit: if force_time_unit not in TIME_UNITS: raise ValueError('Invalid time unit: %s' % force_time_unit) order = TIME_UNITS.index(force_time_unit) time_unit = force_time...
Convert time value to human-readable string. Args: value_us: time value in microseconds. force_time_unit: force the output to use the specified time unit. Must be in TIME_UNITS. Returns: Human-readable string representation of the time value. Raises: ValueError: if force_time_unit value is not in TIME_UNITS.
github-repos
def write_weights(file_path: str, weights: Array, features: typing.List[str]) -> None: with open(file_path, 'w') as f: f.write('\n'.join(['%s\t%.6f' % (feature, weights[i]) for i, feature in enumerate(features)]))
Writes learned weights and corresponsing features to a file. Args: file_path: A file path for the weights file. weights: A weight vector. features: A list of feature identifiers.
github-repos
def probe_services(self, handle, conn_id, callback): self._command_task.async_command(['_probe_services', handle], callback, {'connection_id': conn_id, 'handle': handle})
Given a connected device, probe for its GATT services and characteristics Args: handle (int): a handle to the connection on the BLED112 dongle conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): Callback to be called when this procedure finishes
codesearchnet
def AddFilesWithUnknownHashes(client_path_blob_refs, use_external_stores=True): hash_id_blob_refs = dict() client_path_hash_id = dict() metadatas = dict() all_client_path_blob_refs = list() for (client_path, blob_refs) in iteritems(client_path_blob_refs): if (len(blob_refs) <= 1): ...
Adds new files consisting of given blob references. Args: client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to lists of blob references. use_external_stores: A flag indicating if the files should also be added to external file stores. Returns: A dictionary mapping `db.ClientPath` to hash ids of th...
codesearchnet
def delete_document(project_id, knowledge_base_id, document_id): import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() document_path = client.document_path(project_id, knowledge_base_id, document_id) response = client.delete_document(document_path) print('operation running:\n...
Deletes a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.
codesearchnet
def __init__(self, size=3, **kwargs): self.size = size self.kwargs = kwargs self._in_use = set() self._lock = threading.Lock()
Initializes the pool. Args: size: size of pool (default 3) **kwargs: arguments for Browser(...)
juraj-google-style
def __init__(self, rfile, maxlen): self.rfile = rfile self.maxlen = maxlen self.bytes_read = 0
Initialize SizeCheckWrapper instance. Args: rfile (file): file of a limited size maxlen (int): maximum length of the file being read
juraj-google-style
def _plot_depth_track(self, ax, md, kind='MD'): if (kind == 'MD'): ax.set_yscale('bounded', vmin=md.min(), vmax=md.max()) elif (kind == 'TVD'): tvd = self.location.md2tvd(md) ax.set_yscale('piecewise', x=tvd, y=md) else: raise Exception('Kind must be MD or TVD') for sp in...
Private function. Depth track plotting. Args: ax (ax): A matplotlib axis. md (ndarray): The measured depths of the track. kind (str): The kind of track to plot. Returns: ax.
codesearchnet
class QuantileThreshold(ThresholdFn): def __init__(self, quantile: Optional[float]=0.95, quantile_tracker: Optional[QuantileTracker]=None, **kwargs): super().__init__(**kwargs) if quantile_tracker is not None: self._tracker = quantile_tracker else: self._tracker = Bu...
Applies a quantile-based dynamic threshold to anomaly scores. This `ThresholdFn` is stateful and uses a quantile tracker to dynamically determine the threshold for anomaly detection. It estimates the specified quantile of the incoming anomaly scores and uses this quantile value as the threshold. The threshold adapts ...
github-repos
def _ReadFloatingPointDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.FloatingPointDefinition, definition_name, self._SUPPO...
Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type definition is a member data t...
juraj-google-style
def create_context(pip_version=None, python_version=None): if pip_version: pip_req = "pip-%s" % str(pip_version) else: pip_req = "pip" if python_version: ver = Version(str(python_version)) major_minor_ver = ver.trim(2) py_req = "python-%s" % str(major_minor...
Create a context containing the specific pip and python. Args: pip_version (str or `Version`): Version of pip to use, or latest if None. python_version (str or `Version`): Python version to use, or latest if None. Returns: `ResolvedContext`: Context containing pip and python.
juraj-google-style