code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def read_index(fn): index = None with open(fn, 'rb') as i_file: if (i_file.read(len(_CHECK_STRING)) != _CHECK_STRING): raise ValueError('{}: not a valid index file'.format(fn)) index = pd.read_csv(io.StringIO(zlib.decompress(i_file.read()).decode(encoding='utf-8'))) return index
Reads index from file. Args: fn (str): the name of the file containing the index. Returns: pandas.DataFrame: the index of the file. Before reading the index, we check the first couple of bytes to see if it is a valid index file.
codesearchnet
def remove_padding_from_sc(value_in_checkpoint: tensor.Tensor, variable_shape: tuple[int, int]) -> tensor.Tensor: checkpoint_value_shape = value_in_checkpoint.shape.as_list() is_init_value_padded = all([i >= j for i, j in zip(checkpoint_value_shape, variable_shape)]) if not is_init_value_padded: ret...
Removes padding, if any, from sparsecore checkpoint. Args: value_in_checkpoint: input tensor value, usually from checkpoint. variable_shape: Expected shape of tensor after removing padding. Returns: A slice of the input tensor to match the variable_shape if the variable shape is a valid slice if the input tensor.
github-repos
def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False): changed_files = CTX.repo.changed_files() changelog_file_path: Path = config.CHANGELOG_FILE_PATH() changelog_file_name = changelog_file_path.name if changelog_file_name in changed_files: ...
Writes the changelog Args: amend: amend last commit with changes stage: stage changes next_version: indicates next version auto_next_version: infer next version from VCS
juraj-google-style
def from_dict(cls, video_processor_dict: Dict[str, Any], **kwargs): video_processor_dict = video_processor_dict.copy() return_unused_kwargs = kwargs.pop('return_unused_kwargs', False) if 'size' in kwargs and 'size' in video_processor_dict: video_processor_dict['size'] = kwargs.pop('size') if 'cr...
Instantiates a type of [`~video_processing_utils.VideoProcessorBase`] from a Python dictionary of parameters. Args: video_processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the video processor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~video...
github-repos
def IsSynced(self): if (Blockchain.Default().Height == 0): return False if (int(((100 * self._current_height) / Blockchain.Default().Height)) < 100): return False else: return True
Check if wallet is synced. Returns: bool: True if wallet is synced.
codesearchnet
def change_password(username, new_password): assert (username in passwd_reader.load_users()), ("Username '%s' not found!" % username) sh.ftpasswd('--change-password', passwd=True, name=username, stdin=True, file=settings.LOGIN_FILE, _in=new_password) reload_configuration()
Change password for given `username`. Args: username (str): User's name. new_password (str): User's new password.
codesearchnet
def format(self, record): if ((not FLAGS['showprefixforinfo'].value) and (FLAGS['verbosity'].value == converter.ABSL_INFO) and (record.levelno == logging.INFO) and (_absl_handler.python_handler.stream == sys.stderr)): prefix = '' else: prefix = get_absl_log_prefix(record) return (prefix + su...
Appends the message from the record to the results of the prefix. Args: record: logging.LogRecord, the record to be formatted. Returns: The formatted string representing the record.
codesearchnet
def command_factory(command): def communicate(body={}, root_dir=None): 'Communicate with the daemon.\n\n This function sends a payload to the daemon and returns the unpickled\n object sent by the daemon.\n\n Args:\n body (dir): Any other arguments that should be put into the...
A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should be. This determines as what kind of instruction this will...
codesearchnet
def read_until(self, s, echo=None): s_len = len(s) buf = self.read(s_len, echo) while buf[-s_len:] != s: buf += self.read(1, echo) return buf
Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed.
juraj-google-style
def assign(self, variable, value): variable.assign(value)
Assign a value to a variable. This should be used in optimizers instead of `variable.assign(value)` to support backend specific optimizations. Note that the variable can be a model variable or an optimizer variable; it can be a backend native variable or a Keras variable. Args: variable: The variable to update. value...
github-repos
def add_cell_argument(self, name, help, required=False): for action in self._actions: if action.dest == name: raise ValueError('Arg "%s" was added by add_argument already.' % name) self._cell_args[name] = {'required': required, 'help': help}
Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content.
juraj-google-style
def silu(x): if any_symbolic_tensors((x,)): return Silu().symbolic_call(x) return backend.nn.silu(x)
Sigmoid Linear Unit (SiLU) activation function, also known as Swish. The SiLU activation function is computed by the sigmoid function multiplied by its input. It is defined as `f(x) = x * sigmoid(x)`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor(...
github-repos
def to_dict(self, drop_null=True, camel=False): def to_dict(obj, drop_null, camel): 'Recursively constructs the dict.' if isinstance(obj, (Body, BodyChild)): obj = obj.__dict__ if isinstance(obj, dict): data = {} for (attr, val) in six.iteritems(obj): ...
Serialize self as dict. Args: drop_null: bool, default True. Remove 'empty' attributes. camel: bool, default True. Convert keys to camelCase. Return: dict: object params.
codesearchnet
def count_star(session: Union[Session, Engine, Connection], tablename: str, *criteria: Any) -> int: query = select([func.count()]).select_from(table(tablename)) for criterion in criteria: query = query.where(criterion) return session.execute(query).scalar...
Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria Returns: a scalar
juraj-google-style
def ConvertToWireFormat(self, value): output = _SerializeEntries(((python_format, wire_format, value.type_descriptor) for (python_format, wire_format) in value.wrapped_list)) return (b'', b'', output)
Convert to the wire format. Args: value: is of type RepeatedFieldHelper. Returns: A wire format representation of the value.
codesearchnet
def decode(self, ids, strip_extraneous=False): if strip_extraneous: ids = strip_ids(ids, list(range(self._num_reserved_ids or 0))) return " ".join(self.decode_list(ids))
Transform a sequence of int ids into a human-readable string. EOS is not expected in ids. Args: ids: list of integers to be converted. strip_extraneous: bool, whether to strip off extraneous tokens (EOS and PAD). Returns: s: human-readable string.
juraj-google-style
def groups(self, group_type=None, filters=None, params=None): group = self._tcex.ti.group(group_type) for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params): (yield g)
Gets all groups from a tag. Args: filters: params: group_type:
codesearchnet
def Execute(self, http): self._Execute(http) for key in self.__request_response_handlers: response = self.__request_response_handlers[key].response callback = self.__request_response_handlers[key].handler exception = None if (response.status_code >= 300): exception = ...
Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format.
codesearchnet
def add_error(self, error, critical=False): self.errors.append((error, critical))
Adds an error to the state. Args: error: The text that will be added to the error list. critical: If set to True and the error is checked with check_errors, will dfTimewolf will abort.
juraj-google-style
def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): loss_per_instance = self.fn_loss_per_instance(states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, next_states=next_states, next_internals=next_internals, update=up...
Creates the TensorFlow operations for calculating the full loss of a batch. Args: states: Dict of state tensors. internals: List of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward tensor. next_states: Dict of successor state tensors. next_internals: List...
codesearchnet
def ReadClientMetadata(self, client_id): result = self.MultiReadClientMetadata([client_id]) try: return result[client_id] except KeyError: raise UnknownClientError(client_id)
Reads the ClientMetadata record for a single client. Args: client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7". Returns: An rdfvalues.object.ClientMetadata object. Raises: UnknownClientError: if no client with corresponding id was found.
juraj-google-style
def get_tensor_from_tensor_info(tensor_info, graph=None, import_scope=None): graph = graph or ops.get_default_graph() def _get_tensor(name): return graph.get_tensor_by_name(ops.prepend_name_scope(name, import_scope=import_scope)) encoding = tensor_info.WhichOneof('encoding') if encoding == 'nam...
Returns the Tensor or CompositeTensor described by a TensorInfo proto. Args: tensor_info: A TensorInfo proto describing a Tensor or SparseTensor or CompositeTensor. graph: The tf.Graph in which tensors are looked up. If None, the current default graph is used. import_scope: If not None, names in `tensor_info` are pref...
github-repos
def write_bashrc(_path): cfg_mounts = CFG["container"]["mounts"].value cfg_prefix = CFG["container"]["prefixes"].value path.mkfile_uchroot("/etc/portage/bashrc") mounts = uchroot.mounts("mnt", cfg_mounts) p_paths, p_libs = uchroot.env(cfg_prefix) paths, libs = uchroot.env(mounts) path...
Write a valid gentoo bashrc file to :path:. Args: path - The output path of the make.conf
juraj-google-style
def read(self, x): access_logits = self._address_content(x) weights = tf.nn.softmax(access_logits) retrieved_mem = tf.reduce_sum(tf.multiply(tf.expand_dims(weights, 3), tf.expand_dims(self.mem_vals, axis=1)), axis=2) return (access_logits, retrieved_mem)
Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of [batch_size, length, memory_size]. retrieved_mem: the retrieved ...
codesearchnet
def is20(msg): if allzeros(msg): return False d = hex2bin(data(msg)) if d[0:8] != '00100000': return False cs = cs20(msg) if ' return False return True
Check if a message is likely to be BDS code 2,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
juraj-google-style
def read_tree_nexus(nexus): if not isinstance(nexus, str): raise TypeError("nexus must be a str") if nexus.lower().endswith('.gz'): f = gopen(expanduser(nexus)) elif isfile(expanduser(nexus)): f = open(expanduser(nexus)) else: f = nexus.splitlines() trees = dic...
Read a tree from a Nexus string or file Args: ``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped) Returns: ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects
juraj-google-style
def parse_line(self, line): line = line.lstrip() toks = shlex.split(line) cmd = toks[0] arg = line[len(cmd):] return (cmd, [arg])
Parser for the debugging shell. Treat everything after the first token as one literal entity. Whitespace characters between the first token and the next first non-whitespace character are preserved. For example, ' foo dicj didiw ' is parsed as ( 'foo', ' dicj didiw ' ) Returns: A tuple (cmd, args), where the ...
codesearchnet
def stop_gradient(input_layer): if input_layer.is_sequence(): result = [tf.stop_gradient(t) for t in input_layer.sequence] return input_layer.with_sequence(result) else: return tf.stop_gradient(input_layer)
Cuts off the gradient at this point. This works on both sequence and regular Pretty Tensors. Args: input_layer: The input. Returns: A new Pretty Tensor of the same type with stop_gradient applied.
juraj-google-style
def get(url, params={}): request_url = url if len(params): request_url = '{}?{}'.format(url, urlencode(params)) try: req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'}) response = json.loads(urlopen(req).read().decode('utf-8')) return response except HTTPErr...
Invoke an HTTP GET request on a url Args: url (string): URL endpoint to request params (dict): Dictionary of url parameters Returns: dict: JSON response as a dictionary
codesearchnet
def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port): (_, block_index) = lhs.index_in_block(out_port) bs = lhs.block_structure (nbefore, nblock, nafter) = (sum(bs[:block_index]), bs[block_index], sum(bs[(block_index + 1):])) (before, block, after) = lhs.get_blocks((nbefore, nblock, nafter))...
In a self-Feedback of a series product, where the left-most operand is reducible, pull all non-trivial blocks outside of the feedback. Args: lhs (Circuit): The reducible circuit rest (tuple): The other SeriesProduct operands out_port (int): The feedback output port index in_port (int): The feedback input port index R...
codesearchnet
def __init__(self, fail_on_unset: bool = False, default: str = 'none'): self.fail_on_unset = bool(fail_on_unset) self.default = str(default)
Initializer. Args: fail_on_unset (bool): If set to True an exception will be raised when the environment variable is unset; otherwise the default value (see next) will be used instead. default (str): If a environment variable is unset, it will get this value instead.
juraj-google-style
def addStreamHandler(self,lvl=20): sh = logging.StreamHandler(sys.stdout) sh.setLevel(lvl) sFrmt = logging.Formatter('%(message)s') if False: sFrmt = logging.Formatter('%(name)s - %(levelname)s - %(message)s') sh.setFormatter(sFrmt) self....
This function will add a stream handler to a log with the provided level. Args: lvl (int): The severity level of messages printed to the screen with the stream handler, default = 20.
juraj-google-style
def search(cls, session, queries): return super(Customers, cls).search(session, queries, SearchCustomer)
Search for a customer given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In th...
codesearchnet
def codify(combination): if (isinstance(combination, int) and ((combination < 0) or (combination >= LIMIT))): raise errors.FlagError('Out-of-range flag-combination!') codes = [] for enum in (Style, Color, Fill): for flag in enum: if (combination & flag): codes.app...
Gets escape-codes for flag combinations. Arguments: combination (int): Either a single integer-convertible flag or an OR'd flag-combination. Returns: A semi-colon-delimited string of appropriate escape sequences. Raises: errors.FlagError if the combination is out-of-range.
codesearchnet
def _match_instance_against_type(self, left, other_type, subst, view): if isinstance(other_type, abstract.LiteralClass): other_value = other_type.value if isinstance(left, abstract.ConcreteValue) and isinstance(other_value, abstract.ConcreteValue): return subst if left.pyval == other_val...
Checks whether an instance of a type is compatible with a (formal) type. Args: left: An instance of a type. other_type: A formal type. E.g. abstract.Class or abstract.Union. subst: The current type parameter assignment. view: The current mapping of Variable to Value. Returns: A new type parameter assignment if the ma...
github-repos
def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool...
Returns: Example: ```python >>> import jax.numpy as jnp >>> from transformers import AutoTokenizer, FlaxMarianMTModel >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de") >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de") >>> text = "My friends are cool but they eat t...
github-repos
def shift_by_n_processors(self, x, mesh_axis, offset, wrap): n = self.shape[mesh_axis].size source_pcoord = [] for i in xrange(n): c = (i - offset) if (c != (c % n)): if wrap: c = (c % n) else: c = None source_pcoord.append(c) ...
Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
codesearchnet
def _wrap_usage_section(source, width): if not any(len(line) > width for line in source.splitlines()): return source section_header = source[:source.index(':') + 1].strip() lines = [section_header] for commands, args in parse_commands(source): command = ' {} '.format(' '.join(...
Wrap the given usage section string to the current terminal size. Note: Commands arguments are wrapped to the column that the arguments began on the first line of the command. Args: source: The section string to wrap. Returns: The wrapped section string.
juraj-google-style
def _find_all_hints_in_nodes(nodes): func_calls = _collections.defaultdict(_LiteFuncCall) for node in nodes: attr = node.attr if OpHint.FUNCTION_UUID_ATTR not in attr or not attr[OpHint.FUNCTION_UUID_ATTR].s: continue uuid = attr[OpHint.FUNCTION_UUID_ATTR].s call_def ...
Look at the all the input nodes and return a list of LiteFuncCall objs. Args: nodes: A TensorFlow graph_def to look for LiteFuncCalls. Returns: a list of `LifeFuncCall` objects in the form
github-repos
def verify(self, byts, sign): try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash))) return True except I...
Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise.
codesearchnet
def _count_and_gen_subtokens(token_counts, alphabet, subtoken_dict, max_subtoken_length): subtoken_counts = collections.defaultdict(int) for (token, count) in six.iteritems(token_counts): token = _escape_token(token, alphabet) subtokens = _split_token_to_subtokens(token, subtoken_dict, max_subto...
Count number of times subtokens appear, and generate new subtokens. Args: token_counts: dict mapping tokens to the number of times they appear in the original files. alphabet: list of allowed characters. Used to escape the tokens, which guarantees that all tokens can be split into subtokens. subtoken_dict: dict mappin...
codesearchnet
def print_variant(variant_line, outfile=None, silent=False): variant_line = variant_line.rstrip() if not variant_line.startswith(' if outfile: outfile.write(variant_line+'\n') else: if not silent: print(variant_line) return
Print a variant. If a result file is provided the variante will be appended to the file, otherwise they are printed to stdout. Args: variants_file (str): A string with the path to a file outfile (FileHandle): An opened file_handle silent (bool): Bool. If nothing should be printed.
juraj-google-style
def id_to_int(cls, _id: Union[int, ObjectId]) -> int: if isinstance(_id, int): return _id ints = struct.unpack('>III', _id.binary) return (ints[0] << 64) + (ints[1] << 32) + ints[2]
Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value.
github-repos
def drop_dimension(self, dimensions): dimensions = [dimensions] if np.isscalar(dimensions) else dimensions dims = [d for d in self.kdims if d not in dimensions] dim_inds = [self.get_dimension_index(d) for d in dims] key_getter = itemgetter(*dim_inds) return self.clone([(...
Drops dimension(s) from keys Args: dimensions: Dimension(s) to drop Returns: Clone of object with with dropped dimension(s)
juraj-google-style
def normalize(x, axis=-1, order=2, epsilon=None): if any_symbolic_tensors((x,)): return Normalize(axis=axis, order=order, epsilon=epsilon).symbolic_call(x) return _normalize(x, axis=axis, order=order, epsilon=epsilon)
Normalizes `x` over the specified axis. It is defined as: `normalize(x) = x / max(norm(x), epsilon)`. Args: x: Input tensor. axis: The axis or axes along which to perform normalization. Default to -1. order: The exponent value in the norm formulation. Defaults to 2. epsilon: A lower bound value for the norm. Defaults...
github-repos
def bundle_apps(self, bundle_name, bundle_apps): bundle_file = os.path.join( self.app_path, self.args.outdir, '{}-bundle.zip'.format(bundle_name) ) z = zipfile.ZipFile(bundle_file, 'w') for app in bundle_apps: self.package_data['bundle'].appe...
Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file. Args: bundle_name (str): The output name of the bundle zip file. bundle_apps (list): A list of Apps to include in the bundle.
juraj-google-style
def get_numpy_to_framework_fn(arr) -> Callable: if isinstance(arr, np.ndarray): return np.array if is_tf_available() and is_tf_tensor(arr): import tensorflow as tf return tf.convert_to_tensor if is_torch_available() and is_torch_tensor(arr): import torch return torch....
Returns a function that converts a numpy array to the framework of the input array. Args: arr (`np.ndarray`): The array to convert.
github-repos
def _jvp_helper_wrapper(op_name, attr_tuple, inputs, outputs, tangents, use_batch): if use_batch: for primal, tangent in zip(inputs, tangents): if not tangent.shape.is_compatible_with([None] + primal.shape): raise ValueError('Tangent {} was expected to be of shape {} but is inste...
Computes a batch of Jacobian-vector product for an op. Args: op_name: A string, the type of operation being executed. attr_tuple: Attributes of the operation. inputs: A flat list of input Tensors to the operation. outputs: A flat list of output Tensors from the operation. tangents: A flat list of Tensors, compatible w...
github-repos
def full_like(x, fill_value, dtype=None): if any_symbolic_tensors((x, fill_value)): return FullLike(dtype=dtype).symbolic_call(x, fill_value) return backend.numpy.full_like(x, fill_value, dtype=dtype)
Return a full tensor with the same shape and type as the given tensor. Args: x: Input tensor. fill_value: Fill value. dtype: Overrides data type of the result. Returns: Tensor of `fill_value` with the same shape and type as `x`.
github-repos
def _view_options(self): return {'window_mapping_fn': self._window_mapping_fn, 'coder': self._windowed_coder()}
Internal options corresponding to specific view. Intended for internal use by runner implementations. Returns: Tuple of options for the given view.
github-repos
def merge_sites(self, tol=0.01, mode="sum"): mode = mode.lower()[0] from scipy.spatial.distance import squareform from scipy.cluster.hierarchy import fcluster, linkage d = self.distance_matrix np.fill_diagonal(d, 0) clusters = fcluster(linkage(squareform((d + d....
Merges sites (adding occupancies) within tol of each other. Removes site properties. Args: tol (float): Tolerance for distance to merge sites. mode (str): Three modes supported. "delete" means duplicate sites are deleted. "sum" means the occupancies are summed for the sites. "average" means that the site is deleted bu...
juraj-google-style
def buckets_delete(self, bucket): url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation.
juraj-google-style
def _get_validation_labels(val_path): labels_path = tfds.core.get_tfds_path(_VALIDATION_LABELS_FNAME) with tf.io.gfile.GFile(labels_path) as labels_f: labels = labels_f.read().strip().split('\n') with tf.io.gfile.GFile(val_path, 'rb') as tar_f_obj: tar = tarfile.open(mode='r:', fileobj=tar_f...
Returns labels for validation. Args: val_path: path to TAR file containing validation images. It is used to retrieve the name of pictures and associate them to labels. Returns: dict, mapping from image name (str) to label (str).
codesearchnet
def apply_grad_processors(opt, gradprocs): assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs...
Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables.
juraj-google-style
def get_intersection(self, range_): result = [] for entry in self.entries: package, value = entry if value is None: continue if package.version not in range_: continue if isinstance(value, list): ...
Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects.
juraj-google-style
def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names): print('Converting adaptive_avg_pool2d...') if names == 'short': tf_name = 'APOL' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random...
Convert convert_adaptive_max_pool2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def get_optimizer_group(self, param: Optional[Union[str, torch.nn.parameter.Parameter]]=None): if self.optimizer is None: raise ValueError('Trainer optimizer is None, please make sure you have setup the optimizer before.') if param is not None: for group in self.optimizer.param_groups: ...
Returns optimizer group for a parameter if given, else returns all optimizer groups for params. Args: param (`str` or `torch.nn.parameter.Parameter`, *optional*): The parameter for which optimizer group needs to be returned.
github-repos
def __init__(self, api, path, options): self._init(api, path, options)
Initialize. Args: api: storage_api instance. path: bucket path of form '/bucket'. options: a dict of listbucket options. Please see listbucket doc.
juraj-google-style
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(candidates) - 2)) return fmt...
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...
juraj-google-style
def save_aggregate_reports_to_kafka(self, aggregate_reports, aggregate_topic): if (type(aggregate_reports) == dict or type(aggregate_reports) == OrderedDict): aggregate_reports = [aggregate_reports] if len(aggregate_reports) < 1: ...
Saves aggregate DMARC reports to Kafka Args: aggregate_reports (list): A list of aggregate report dictionaries to save to Kafka aggregate_topic (str): The name of the Kafka topic
juraj-google-style
def _isbn_pairing(items): NameWrapper = namedtuple('NameWrapper', ['name', 'obj']) metas = map((lambda x: NameWrapper(_just_name(x.filename), x)), filter((lambda x: isinstance(x, MetadataFile)), items)) ebooks = map((lambda x: NameWrapper(_just_name(x.filename), x)), filter((lambda x: isinstance(x, EbookFil...
Pair `items` with same ISBN into `DataPair` objects. Args: items (list): list of items, which will be searched. Returns: list: list with paired items. Paired items are removed, `DataPair` is \ added instead.
codesearchnet
def main(args=None): parser = get_parser() args = parser.parse_args(args=args) if not (args.matrix or args.dependencies or args.treemap or args.graph): args.matrix = True packages = [] for arg in args.packages: if ',' in arg: for package in arg.split(','): ...
Main function. This function is the command line entry point. Args: args (list of str): the arguments passed to the program. Returns: int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
juraj-google-style
def authenticate(self, request, username=None, password=None): if not isinstance(username, str): return None username = re.sub(r'\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if krb_ticket == "reset": user, stat...
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `User`
juraj-google-style
def graphviz_imshow(self, ax=None, figsize=None, dpi=300, fmt="png", **kwargs): graph = self.get_graphviz(**kwargs) graph.format = fmt graph.attr(dpi=str(dpi)) _, tmpname = tempfile.mkstemp() path = graph.render(tmpname, view=False, cleanup=True) ax, fig...
Generate flow graph in the DOT language and plot it with matplotlib. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. figsize: matplotlib figure size (None to use default) dpi: DPI value. fmt: Select format for output image Return: matplotlib Figure
juraj-google-style
def start_after(self, document_fields): query = query_mod.Query(self) return query.start_after(document_fields)
Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representi...
codesearchnet
def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): campaign_service = client.GetService('CampaignService', version='v201809') operations = [{ 'operator': 'SET', 'operand': { 'id': campaign_id, 'campaignGroupId': campaign_group_id } } for campaign_id ...
Adds multiple campaigns to a campaign group. Args: client: an AdWordsClient instance. campaign_group_id: an integer ID for the campaign group. campaign_ids: a list of integer IDs for campaigns.
juraj-google-style
def auto_plot_array(*, video_min_num_frames: int=15, height: None | int | tuple[int, int]=(100, 250), show_images_kwargs: Optional[dict[str, Any]]=None, show_videos_kwargs: Optional[dict[str, Any]]=None) -> None: ipython = IPython.get_ipython() if ipython is None: return array_repr_html_fn = functoo...
If called, 2d/3d imgage arrays will be plotted as images in colab/jupyter. Usage: >>> ecolab.auto_plot_array() >>> np.zeros((28, 28, 3)) # Displayed as image Args: video_min_num_frames: Video `(num_frames, h, w, c)` with less than this number of frames will be displayed as individual images height: `(min, max)` ima...
github-repos
def from_key(cls, *args): key = (args if (len(args) > 1) else args[0]) return cls._instances.get(key, None)
Return flyweight object with specified key, if it has already been created. Returns: cls or None: Previously constructed flyweight object with given key or None if key not found
codesearchnet
def fix_variables(self, fixed): for (v, val) in fixed.items(): self.fix_variable(v, val)
Fix the value of the variables and remove it from a binary quadratic model. Args: fixed (dict): A dictionary of variable assignments. Examples: >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN) >>> bqm.fix_variables({'a': -1, 'b': +1})
codesearchnet
def resolve_type(arg): arg_type = type(arg) if (arg_type == list): assert isinstance(arg, list) sample = arg[:min(4, len(arg))] tentative_type = TentativeType() for sample_item in sample: tentative_type.add(resolve_type(sample_item)) return ListType(tentative_...
Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve
codesearchnet
def to_obj(self, wd=False, pack=False, relpath=None): obj = CommentedMap() if pack: obj['run'] = self.orig elif (relpath is not None): if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.relpath(self.run, relpath) elif wd: if self.fr...
Return the step as an dict that can be written to a yaml file. Returns: dict: yaml representation of the step.
codesearchnet
def artifact_bundles(self): if (not self.__artifact_bundles): self.__artifact_bundles = ArtifactBundles(self.__connection) return self.__artifact_bundles
Gets the Artifact Bundles API client. Returns: ArtifactBundles:
codesearchnet
def enclosure_groups(self): if (not self.__enclosure_groups): self.__enclosure_groups = EnclosureGroups(self.__connection) return self.__enclosure_groups
Gets the EnclosureGroups API client. Returns: EnclosureGroups:
codesearchnet
def step(self, action): observ, reward, done, info = self._env.step(action) observ = self._convert_observ(observ) reward = self._convert_reward(reward) return observ, reward, done, info
Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object.
juraj-google-style
def set_weight_collections(self, weight_collections): self._weight_collections = weight_collections
Sets the weight collections for the layer. Args: weight_collections: A list of collection names to which the Variable will be added.
github-repos
def find_all(container): if isinstance(container, dict): names = container.keys() else: names = dir(container) built_context = BasicContext() for name in names: if name.startswith('_'): continue if isinstance(container, dict): obj = container[name]...
Find all annotated function inside of a container. Annotated functions are identified as those that: - do not start with a _ character - are either annotated with metadata - or strings that point to lazily loaded modules Args: container (object): The container to search for annotated functions. Returns: dict: A dict...
codesearchnet
def complete(command_line, current_token, position, shell: arg(choices=('bash', 'fish'))): position = int(position) tokens = shlex.split(command_line[:position]) (all_argv, run_argv, command_argv) = run.partition_argv(tokens[1:]) run_args = run.parse_args(run_argv) module = run_args.get('commands_mo...
Find completions for current command. This assumes that we'll handle all completion logic here and that the shell's automatic file name completion is disabled. Args: command_line: Command line current_token: Token at cursor position: Current cursor position shell: Name of shell
codesearchnet
def check_against_mro(ctx: 'context.Context', target: '_base.BaseValue', class_spec: '_instance_base.SimpleValue') -> bool | None: classes = [] ambiguous = flatten(class_spec, classes) for c in classes: if ctx.matcher(None).match_from_mro(target, c, allow_compat_builtins=False): return T...
Check if any of the classes are in the target's MRO. Args: ctx: The abstract context. target: A BaseValue whose MRO will be checked. class_spec: A Class or PythonConstant tuple of classes (i.e. the second argument to isinstance or issubclass). Returns: True if any class in classes is found in the target's MRO, False ...
github-repos
def GetNewSessionID(self, **_): return rdfvalue.SessionID(base='aff4:/hunts', queue=self.runner_args.queue)
Returns a random integer session ID for this hunt. All hunts are created under the aff4:/hunts namespace. Returns: a formatted session id string.
codesearchnet
def set(self, context_id, address_value_list): if (context_id not in self._contexts): LOGGER.warning('Context_id not in contexts, %s', context_id) return False context = self._contexts.get(context_id) add_value_dict = {} for d in address_value_list: for (add, val) in d.items(): ...
Within a context, sets addresses to a value. Args: context_id (str): the context id returned by create_context address_value_list (list): list of {address: value} dicts Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a known context. Raises: AuthorizationException if a...
codesearchnet
def __parse_tonodes(self, text, **kwargs): n = self.options.get('nbest', 1) try: if self._KW_BOUNDARY in kwargs: patt = kwargs.get(self._KW_BOUNDARY, '.') tokens = list(self.__split_pattern(text, patt)) text = ''.join([t[0] for t in t...
Builds and returns the MeCab function for parsing to nodes using morpheme boundary constraints. Args: format_feature: flag indicating whether or not to format the feature value for each node yielded. Returns: A function which returns a Generator, tailored to using boundary constraints and parsing as nodes, using eith...
juraj-google-style
def parse(self, stream, parser=None): (force, parsers) = self._get_parsers(parser) try: stream.seek(0) lookup = stream.read(1024) stream.seek(0) except (io.UnsupportedOperation, AttributeError): lookup = None for p in parsers: if p.hook(path=self.path, force=force...
Parse the given file using available `BaseParser` instances. Raises: TypeError: when the parser argument is not a string or None. ValueError: when the parser argument is a string that does not name a `BaseParser`.
codesearchnet
def run(self, data): result_type = namedtuple('Result', 'code messages') if self.passes is True: result = result_type(Checker.Code.PASSED, '') elif self.passes is False: if self.allow_failure: result = result_type(Checker.Code.IGNORED, '') ...
Run the check method and format the result for analysis. Args: data (DSM/DMM/MDM): DSM/DMM/MDM instance to check. Returns: tuple (int, str): status constant from Checker class and messages.
juraj-google-style
def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''): log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('Stops automatically in %ss', search_duratio_sec) log.info('MACs: %s', macs) datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_durat...
Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors
codesearchnet
def log_run_info(self, model_name): run_info = { "model_name": model_name, "machine_config": {}, "run_date": datetime.datetime.now().strftime(_DATE_TIME_FORMAT_PATTERN)} _collect_tensorflow_info(run_info) _collect_tensorflow_environment_variables(run_info) _collect_cpu_info(...
Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model.
juraj-google-style
def flatten_zip_dataset(*args): flattened = tf.data.Dataset.from_tensors(args[0]) for ex in args[1:]: flattened = flattened.concatenate(tf.data.Dataset.from_tensors(ex)) return flattened
A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flattened: A new datas...
juraj-google-style
def determine_drift(self): try: response = self._cloud_formation.detect_stack_drift(StackName=self._stack_name) drift_request_id = response.get('StackDriftDetectionId', None) if drift_request_id: logging.info('drift_request_id: %s - polling', drift_request_id) drift_c...
Determine the drift of the stack. Args: None Returns: Good or Bad; True or False
codesearchnet
def delete_jobs(self, user_ids, job_ids, task_ids, labels, create_time_min=None, create_time_max=None): tasks = list(self.lookup_job_tasks({'RUNNING'}, user_ids=user_ids, job_ids=job_ids, task_ids=task_ids, labels=labels, create_time_min=create_time_min, create_time_max=create_time_max)) print(('Found %d tasks ...
Kills the operations associated with the specified job or job.task. Args: user_ids: List of user ids who "own" the job(s) to cancel. job_ids: List of job_ids to cancel. task_ids: List of task-ids to cancel. labels: List of LabelParam, each must match the job(s) to be canceled. create_time_min: a timezone-aware datetim...
codesearchnet
def ShlexSplit(string): precondition.AssertType(string, Text) if PY2: string = string.encode("utf-8") parts = shlex.split(string) if PY2: parts = [part.decode("utf-8") for part in parts] return parts
A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string to split. Returns: A list of unicode strings representing parts of the input string.
juraj-google-style
class ThresholdedReLU(Layer): def __init__(self, theta=1.0, **kwargs): super(ThresholdedReLU, self).__init__(**kwargs) if theta is None: raise ValueError('Theta of a Thresholded ReLU layer cannot be None, requires a float. Got %s' % theta) if theta < 0: raise ValueEr...
Thresholded Rectified Linear Unit. It follows: ``` f(x) = x for x > theta f(x) = 0 otherwise` ``` Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Args: t...
github-repos
def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray: size = get_size_dict(size, default_to_square=False) ...
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling....
github-repos
def event(self, **kwargs): if (self.callback.noargs and (self.streams == [])): self.param.warning('No streams declared. To update a DynamicMaps using generators (or callables without arguments) use streams=[Next()]') return if (self.streams == []): self.param.warning('No streams on Dynam...
Updates attached streams and triggers events Automatically find streams matching the supplied kwargs to update and trigger events on them. Args: **kwargs: Events to update streams with
codesearchnet
def _build_url(self, path): if (path.startswith('http: return path else: return ('%s%s' % (self._url, path))
Returns the full url from path. If path is already a url, return it unchanged. If it's a path, append it to the stored url. Returns: str: The full URL
codesearchnet
def ReadDataAtOffset(self, file_offset, size): self._file_object.seek(file_offset, os.SEEK_SET) return self._file_object.read(size)
Reads a byte string from the file-like object at a specific offset. Args: file_offset (int): file offset. size (int): number of bytes to read. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed.
codesearchnet
def solve(a, b): if any_symbolic_tensors((a, b)): return Solve().symbolic_call(a, b) return _solve(a, b)
Solves a linear system of equations given by `a x = b`. Args: a: A tensor of shape `(..., M, M)` representing the coefficients matrix. b: A tensor of shape `(..., M)` or `(..., M, N)` representing the right-hand side or "dependent variable" matrix. Returns: A tensor of shape `(..., M)` or `(..., M, N)` representing t...
github-repos
def minmax(self, minimum=None, maximum=None): if minimum is None and maximum is None: return {"minimum": self._minimum, "maximum": self._maximum}; if minimum != None: if self._type in ['base64', 'date', 'datetime', 'ip', 'time']: if not isinstance(minimum, basestring) \ or not _...
Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns: None | dict
juraj-google-style
def _restart(self, downtime_secs, job): self._cluster.kill_task(job, 0) time.sleep(downtime_secs) self.assertFalse(context.check_alive('/job:%s/replica:0/task:0' % job)) self._cluster.start_task(job, 0) while not context.check_alive('/job:%s/replica:0/task:0' % job): time.sleep(1)
Kills `job` (index: 0) and restarts it after `downtime_secs`. Args: downtime_secs: secs before restarting the job. job: a string specifying the job to restart.
github-repos
def eval_from_json(json): closes = poloniex.get_attribute(json, 'close') volumes = poloniex.get_attribute(json, 'volume') obv = 0 for date in range(1, len(json)): curr = {'close': closes[date], 'volume': volumes[date]} prev = {'close': closes[date - 1], '...
Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV
juraj-google-style
def _Execute(self, funcname, *args, **kwargs): wait_for_completion = kwargs.get('wait_for_completion', False) rpc_dict = {'func': funcname, 'args': args} self._Send(json.dumps(rpc_dict)) timeout = (TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT) result_string = self._Recv(timeout) t...
Send an RPC request to the gdb-internal python. Blocks for 3 seconds by default and returns any results. Args: funcname: the name of the function to call. *args: the function's arguments. **kwargs: Only the key 'wait_for_completion' is inspected, which decides whether to wait forever for completion or just 3 seconds. ...
codesearchnet
def route(cls, route, config=None): def decorator(wrapped_class, **kwds): cls._routes.append(dict(url=route, request_handler=wrapped_class)) return wrapped_class return decorator
This method provides a decorator for adding endpoints to the http server. Args: route (str): The url to be handled by the RequestHandled config (dict): Configuration for the request handler Example: .. code-block:: python import nautilus from nauilus.network.http import RequestHandler class MyService(nautilus.Serv...
codesearchnet