code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def search(self, search_phrase, limit=None): search_phrase = search_phrase.replace('-', '_') terms = SearchTermParser().parse(search_phrase) from_year = terms.pop('from', None) to_year = terms.pop('to', None) query, query_params = self._make_...
Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Generates: PartitionSearchResult instances.
juraj-google-style
def sg_lookup(tensor, opt): r assert opt.emb is not None, 'emb is mandatory.' return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name)
r"""Looks up the `tensor`, which is the embedding matrix. Args: tensor: A tensor ( automatically given by chain ) opt: emb: A 2-D `Tensor`. An embedding matrix. name: If provided, replace current tensor's name. Returns: A `Tensor`.
juraj-google-style
def __driver_completer(self, toks, text, state): if (state != 0): return self.__completion_candidates[state] if ((not toks) or ((len(toks) == 1) and (text == toks[0]))): try: self.__completion_candidates = self.__complete_cmds(text) except: self.stderr.write('\n')...
Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the index of the candidate out of the list of candidates. Returns: A string, the candidate.
codesearchnet
def get_version(package_name): module = 'prosper.' + package_name + '._version' package = importlib.import_module(module) version = package.__version__ return version
find __version__ for making package Args: package_name (str): path to _version.py folder (abspath > relpath) Returns: str: __version__ value
juraj-google-style
def delaunay_reduce(lattice, eps=1e-05): _set_no_error() delaunay_lattice = np.array(np.transpose(lattice), dtype='double', order='C') result = spg.delaunay_reduce(delaunay_lattice, float(eps)) _set_error_message() if (result == 0): return None else: return np.array(np.transpose(...
Run Delaunay reduction Args: lattice: Lattice parameters in the form of [[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]] symprec: float: Tolerance to check if volume is close to zero or not and if two basis vectors are orthogonal by the value of dot product being close to zero or not. Returns: if the Delaunay redu...
codesearchnet
def clear_worker_output(self): self.data_store.clear_worker_output() self.plugin_manager.load_all_plugins() self._store_information()
Drops all of the worker output collections Args: None Returns: Nothing
juraj-google-style
def port(alias_name, default=None, allow_none=False): warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2) try: return int(_split_docker_link(alias_name)[2]) except KeyError as err: if (default or allow_none): return default else: raise e...
Get the port from the docker link alias or return the default. Args: alias_name: The docker link alias default: The default value if the link isn't available allow_none: If the return value can be `None` (i.e. optional) Examples: Assuming a Docker link was created with ``docker --link postgres:db`` and the resulting ...
codesearchnet
def decode_list_oov(self, ids, source_oov_id_to_token): seq = reversed(ids) if self._reverse else ids tokens = [] for cur_id in seq: if cur_id in self._id_to_token: tokens.append(self._id_to_token[cur_id]) else: tokens.append(source_oov_id_to_token[cur_id - self.vocab_size])...
decode ids back to tokens, considering OOVs temporary IDs. Args: ids: vocab ids. Could possibly include source temporary OOV ID starting from vocab_size. source_oov_id_to_token: a list of source OOV tokens, with the order the same as they appear in the source. Returns: decoded tokens, possibly including source OOV to...
juraj-google-style
def add_loss(self, loss, name=None, regularization=False, add_summaries=True): _ = name if regularization: self._g.add_to_collection(GraphKeys.REGULARIZATION_LOSSES, loss) tf.add_to_collection(GraphKeys.LOSSES, loss) if add_summaries: self.add_scalar_summary(loss, 'loss') self.ad...
Append a loss to the total loss for the network. Args: loss: append this loss operation name: The name for this loss, defaults to loss.op.name regularization: Set to True if this is a regularization loss. add_summaries: Set to True if you want to see scalar and average summary.
codesearchnet
def import_subview(self, idx, subview): subview.corpus = self self._subviews[idx] = subview
Add the given subview to the corpus. Args: idx (str): An idx that is unique in the corpus for identifying the subview. If already a subview exists with the given id it will be overridden. subview (Subview): The subview to add.
juraj-google-style
def _set_verbosity_from(posarg): def decorator(f): def wrapper(*args, **kwargs): options = kwargs.get('options', args[posarg]) with config.verbosity_from(options): return f(*args, **kwargs) return wrapper return decorator
Decorator to set the verbosity for a function that takes an options arg. Assumes that the function has an argument named `options` that is a config.Options object. Arguments: posarg: The index of `options` in the positional arguments. Returns: The decorator.
github-repos
def default_search_space(): matrix = [[pg.oneof([0, 1], hints=EDGE_HINTS) if y > x else 0 for y in range(NUM_VERTICES)] for x in range(NUM_VERTICES)] return model_spec(pg.manyof(NUM_VERTICES - 2, ALLOWED_OPS, choices_distinct=False, hints=OP_HINTS), matrix)
The default search space in NAS-Bench. This equals to the default search space of NAS-Bench, which mutate candidate ops and their connections. Returns: A hyper model object that repesents a search space.
github-repos
def _is_definition_section(source): try: definitions = textwrap.dedent(source).split('\n', 1)[1].splitlines() return all((re.match('\\s\\s+((?!\\s\\s).+)\\s\\s+.+', s) for s in definitions)) except IndexError: return False
Determine if the source is a definition section. Args: source: The usage string source that may be a section. Returns: True if the source describes a definition section; otherwise, False.
codesearchnet
def pkg_config(pkg_libraries): libraries=[] library_dirs=[] include_dirs=[] for pkg in pkg_libraries: if os.system('pkg-config --exists %s 2>/dev/null' % pkg) == 0: pass else: print("Could not find library {0}".format(pkg)) sys.exit(1) ...
Use pkg-config to query for the location of libraries, library directories, and header directories Arguments: pkg_libries(list): A list of packages as strings Returns: libraries(list), library_dirs(list), include_dirs(list)
juraj-google-style
def add_columns(tree_view, df_py_dtypes, list_store): tree_view.set_model(list_store) for (column_i, (i, dtype_i)) in df_py_dtypes[['i', 'dtype']].iterrows(): tree_column_i = gtk.TreeViewColumn(column_i) tree_column_i.set_name(column_i) if (dtype_i in (int, long)): property_n...
Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`. Args: tree_view (gtk.TreeView) : Tree view to append columns to. df_py_dtypes (pandas.DataFrame) : Data frame containing type information for one or more columns in `list_store`. list_store (gtk.ListStore) : Model data. Returns: None
codesearchnet
def _bfs_path_states(self, graph, start): pathstates = {} queue = [] visited = [] queue.append([['', start]]) while queue: path = queue.pop(0) node = path[-1][1] if node.stateid ...
Find state access strings (DFA shortest paths for every state) using BFS Args: graph (DFA): The DFA states start (int): The DFA initial state Return: list: A list of all the DFA shortest paths for every state
juraj-google-style
def dataframe(self, force_refresh=False): if force_refresh: self.clear_cache() if self._dataframe is None: self._dataframe = self._fetch_dataframe() return self._dataframe
A pandas dataframe with lots of interesting results about this object. Created by calling SageMaker List and Describe APIs and converting them into a convenient tabular summary. Args: force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
juraj-google-style
def wind_direction(self, value=999.0): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `wind_direction`'.format(value)) if (value < 0.0): raise ValueError('value need to be ...
Corresponds to IDD Field `wind_direction` Args: value (float): value for IDD Field `wind_direction` Unit: degrees value >= 0.0 value <= 360.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid valu...
codesearchnet
def size(self, name=None): with ops.name_scope(name, '%s_Size' % self.name, [self.resource_handle]): with ops.colocate_with(self.resource_handle): return gen_lookup_ops.lookup_table_size_v2(self.resource_handle)
Compute the number of elements in this table. Args: name: A name for the operation (optional). Returns: A scalar tensor containing the number of elements in this table.
github-repos
def _add_dispatcher(self, path_regex, dispatch_function): self._dispatchers.append((re.compile(path_regex), dispatch_function))
Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body.
codesearchnet
def add_group_maintainer(self, name, user): self.service.add_group_maintainer( name, user, self.url_prefix, self.auth, self.session, self.session_send_opts)
Add the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user (string): User to add to group. version (optional[string]): Version of the Boss API to use. Defaults to the latest supported version. Raises: requests.HTTPError on failure.
juraj-google-style
def check(self, check_req): self.start() res = self._check_aggregator.check(check_req) if res: _logger.debug(u'using cached check response for %s: %s', check_request, res) return res try: transport = self._create_transport() resp = transport.services.Check(check_req) ...
Process a check_request. The req is first passed to the check_aggregator. If there is a valid cached response, that is returned, otherwise a response is obtained from the transport. Args: check_req (``ServicecontrolServicesCheckRequest``): to be sent to the service control service Returns: ``CheckResponse``: either...
codesearchnet
def with_context(cls, setup_phases, teardown_phases): setup = flatten_phases_and_groups(setup_phases) teardown = flatten_phases_and_groups(teardown_phases) def _context_wrapper(*phases): return cls(setup=setup, main=flatten_phases_and_groups(phases), teardown=teardown) return _context_wrapper
Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from the created function. teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups...
codesearchnet
def period(self, value: float): if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=value)
Set the period. Args: value (float): seconds
juraj-google-style
def ReverseCloseExpression(clean_lines, linenum, pos): line = clean_lines.elided[linenum] if (line[pos] not in ')}]>'): return (line, 0, (- 1)) (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if (start_pos > (- 1)): return (line, linenum, start_pos) while (stack and (...
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A ...
codesearchnet
def __init__(self, package, ad): super().__init__(app_name=package, ad=ad) self.package = package self._ad = ad self._adb = ad.adb self._proc = None self._user_id = None
Initializes a SnippetClient. Args: package: (str) The package name of the apk where the snippets are defined. ad: (AndroidDevice) the device object associated with this client.
github-repos
def nb_ll_row(params, data_row): p = params[0] r = params[1] n = len(data_row) ll = (np.sum(gammaln((data_row + r))) - np.sum(gammaln((data_row + 1)))) ll -= (n * gammaln(r)) ll += (np.sum(data_row) * np.log(p)) ll += ((n * r) * np.log((1 - p))) return (- ll)
returns the negative LL of a single row. Args: params (array) - [p, r] data_row (array) - 1d array of data Returns: LL of row
codesearchnet
def decrypt(key, ciphertext): index = 0 decrypted = '' for char in ciphertext: if (char in ((string.punctuation + string.whitespace) + string.digits)): decrypted += char continue alphabet = (string.ascii_uppercase if key[index].isupper() else string.ascii_lowercase) ...
Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext
codesearchnet
def add_send_last_message(self, connection, send_last_message): self._send_last_message[connection] = send_last_message LOGGER.debug('Added send_last_message function for connection %s', connection)
Adds a send_last_message function to the Dispatcher's dictionary of functions indexed by connection. Args: connection (str): A locally unique identifier provided by the receiver of messages. send_last_message (fn): The method that should be called by the dispatcher to respond to messages which arrive via connection, w...
codesearchnet
def __setitem__(self, key, item): if isinstance(key, str): column = item self.columns.add(key) if len(column) > len(self.rows): for i, value in enumerate(column): if i < len(self.rows): self.rows[i][key] = v...
Set a column or row for a dataset. Args: key (str or int): String referencing a column or integer referencing a row item (list or dict): Column or rows to set in the dataset.
juraj-google-style
def create_in_hdx(self): self.check_required_fields() id = self.data.get('id') if (id and self._load_from_hdx('resource', id)): logger.warning(('%s exists. Updating %s' % ('resource', id))) if (self.file_to_upload and ('url' in self.data)): del self.data['url'] self._merg...
Check if resource exists in HDX and if so, update it, otherwise create it Returns: None
codesearchnet
def molecule(lines): count_line = lines[3] num_atoms = int(count_line[0:3]) num_bonds = int(count_line[3:6]) compound = Compound() compound.graph._node = atoms(lines[4:(num_atoms + 4)]) compound.graph._adj = bonds(lines[(num_atoms + 4):((num_atoms + num_bonds) + 4)], compound.graph._node.keys())...
Parse molfile part into molecule object Args: lines (list): lines of molfile part Raises: ValueError: Symbol not defined in periodictable.yaml (Polymer expression not supported yet)
codesearchnet
def most_frequent_terms(self, depth): counts = self.term_counts() top_terms = set(list(counts.keys())[:depth]) end_count = list(counts.values())[:depth][(- 1)] bucket = self.term_count_buckets()[end_count] return top_terms.union(set(bucket))
Get the X most frequent terms in the text, and then probe down to get any other terms that have the same count as the last term. Args: depth (int): The number of terms. Returns: set: The set of frequent terms.
codesearchnet
def _AddNextStateToQueue(penalty, previous_node, newline, count, p_queue): must_split = previous_node.state.MustSplit() if newline and (not previous_node.state.CanSplit(must_split)): return count if not newline and must_split: return count node = _StateNode(previous_node.state, newline, ...
Add the following state to the analysis queue. Assume the current state is 'previous_node' and has been reached with a penalty of 'penalty'. Insert a line break if 'newline' is True. Arguments: penalty: (int) The penalty associated with the path up to this point. previous_node: (_StateNode) The last _StateNode insert...
github-repos
def _save_model(self): if not file_utils.exists(self.backup_dir): file_utils.makedirs(self.backup_dir) if self.double_checkpoint and file_utils.exists(self._weights_path): file_utils.copy(self._weights_path, self._prev_weights_path) if self.double_checkpoint and file_utils.exists(self._train...
Saves the model. Args: epoch: the epoch this iteration is in. batch: the batch this iteration is in. `None` if the `save_freq` is set to `"epoch"`. logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`.
github-repos
def ensure_tf_install(): try: import tensorflow as tf except ImportError: print('\n\nFailed to import TensorFlow. Please note that TensorFlow is not installed by default when you install TensorFlow Datasets. This is so that users can decide whether to install the GPU-enabled TensorFlow package. ...
Attempt to import tensorflow, and ensure its version is sufficient. Raises: ImportError: if either tensorflow is not importable or its version is inadequate.
codesearchnet
def __init__(self, name="", default=None, description="", friendly_name="", hidden=False): self.name = name self.default = default self.description = description self.hidden = hidden if not friendly_name: friendly_...
Build a TypeInfo type descriptor. Args: name: The name of the parameter that this Type info corresponds to. default: The default value that should be specified if the parameter was not set. description: A string describing this flow argument. friendly_name: A human readable name which may be provided. hidden: Should t...
juraj-google-style
def CreateDataTypeMap(self, definition_name): data_type_definition = self._definitions_registry.GetDefinitionByName( definition_name) if not data_type_definition: return None return DataTypeMapFactory.CreateDataTypeMapByType(data_type_definition)
Creates a specific data type map by name. Args: definition_name (str): name of the data type definition. Returns: DataTypeMap: data type map or None if the date type definition is not available.
juraj-google-style
def memory_write64(self, addr, data, zone=None): words = [] bitmask = 0xFFFFFFFF for long_word in data: words.append(long_word & bitmask) words.append((long_word >> 32) & bitmask) return self.memory_write32(addr, words, zone=zone)
Writes long words to memory of a target system. Note: This is little-endian. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of long words to write zone (str): optional memory zone to access Returns: Number of long words written to target. Raises: JLinkException: o...
juraj-google-style
def gripper_factory(name): if name == "TwoFingerGripper": return TwoFingerGripper() if name == "LeftTwoFingerGripper": return LeftTwoFingerGripper() if name == "PR2Gripper": return PR2Gripper() if name == "RobotiqGripper": return RobotiqGripper() if name == "Push...
Genreator for grippers Creates a Gripper instance with the provided name. Args: name: the name of the gripper class Returns: gripper: Gripper instance Raises: XMLError: [description]
juraj-google-style
def plot_kdes(self, mnemonic, alias=None, uwi_regex=None, return_fig=False): wells = self.find_wells_with_curve(mnemonic, alias=alias) (fig, axs) = plt.subplots(len(self), 1, figsize=(10, (1.5 * len(self)))) curves = [w.get_curve(mnemonic, alias=alias) for w in wells] all_data = np.hstack(curves) al...
Plot KDEs for all curves with the given name. Args: menmonic (str): the name of the curve to look for. alias (dict): a welly alias dictionary. uwi_regex (str): a regex pattern. Only this part of the UWI will be displayed on the plot of KDEs. return_fig (bool): whether to return the matplotlib figure object. Returns: ...
codesearchnet
def GetAnalyzerInstances(cls, analyzer_names): analyzer_instances = [] for (analyzer_name, analyzer_class) in iter(cls.GetAnalyzers()): if (analyzer_name in analyzer_names): analyzer_instances.append(analyzer_class()) return analyzer_instances
Retrieves instances for all the specified analyzers. Args: analyzer_names (list[str]): names of the analyzers to retrieve. Returns: list[BaseAnalyzer]: analyzer instances.
codesearchnet
def __init__(self, solution_size, population_size=20): super(ExhaustiveBinary, self).__init__(solution_size, population_size) self._next_int = 0
Create an object that optimizes a given fitness function. Args: solution_size: The number of bits in every solution. population_size: The number of solutions in every iteration.
juraj-google-style
def delete_existing_cname(env, zone_id, dns_name): client = boto3.Session(profile_name=env).client('route53') startrecord = None newrecord_name = dns_name startrecord = find_existing_record(env, zone_id, newrecord_name, check_key='Type', check_value='CNAME') if startrecord: LOG.info("De...
Delete an existing CNAME record. This is used when updating to multi-region for deleting old records. The record can not just be upserted since it changes types. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update.
juraj-google-style
def to_qsw(orbit): (pos, vel) = _split(orbit) q = (pos / norm(pos)) w = (np.cross(pos, vel) / (norm(pos) * norm(vel))) s = np.cross(w, q) return np.array([q, s, w])
In the QSW Local Orbital Reference Frame, x is oriented along the position vector, z along the angular momentum, and y complete the frame. The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local Vertical Local Horizontal). Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix t...
codesearchnet
def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]: if already_has_special_tokens: if token_ids_1 is not None: raise ValueError('You should not supply a second sequence if the provided sequence of ...
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of ids. token_ids_1 (`List[int]`, *optional*, defaults to `None`): Optional second list of IDs for sequence p...
github-repos
def TSKVolumeGetBytesPerSector(tsk_volume): if (hasattr(tsk_volume, 'info') and (tsk_volume.info is not None)): block_size = getattr(tsk_volume.info, 'block_size', 512) else: block_size = 512 return block_size
Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default.
codesearchnet
def mock(self, slot, rpc_id, value): address = slot.address if address not in self.mock_rpcs: self.mock_rpcs[address] = {} self.mock_rpcs[address][rpc_id] = value
Store a mock return value for an RPC Args: slot (SlotIdentifier): The slot we are mocking rpc_id (int): The rpc we are mocking value (int): The value that should be returned when the RPC is called.
juraj-google-style
class PerKey(PTransform): def __init__(self, num_quantiles, key=None, reverse=False, weighted=False, input_batched=False): self._num_quantiles = num_quantiles self._key = key self._reverse = reverse self._weighted = weighted self._input_batched = input_batched def expan...
PTransform takes PCollection of KV and returns a list based on each key whose single value is list of approximate N-tiles of the input element of the key. Args: num_quantiles: number of elements in the resulting quantiles values list. key: (optional) Key is a mapping of elements to a comparable key, similar to the ke...
github-repos
def CheckNextIncludeOrder(self, header_type): error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if (header_type == _C_SYS_HEADER): if (self._section <= self._C_SECTION): self._section = self._C_SECTION...
Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing w...
codesearchnet
def get_as(access_token, subscription_id, resource_group, as_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/availabilitySets/', as_name, ...
Get availability set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the new availability set. Returns: HTTP response. JSON body of the availability set properties.
juraj-google-style
def list_matching(self, ref_name: str, filter_: str) -> Iterable[ListEntry]: (canonical, canonical_i) = self._get_pattern((ref_name + filter_)) for entry in self.list(): if (entry.name == 'INBOX'): if canonical_i.match('INBOX'): (yield entry) elif canonical.match(entr...
Return all the entries in the list tree that match the given query. Args: ref_name: Mailbox reference name. filter_: Mailbox name with possible wildcards.
codesearchnet
def call(self, inputs_embeds, attention_mask: tf.Tensor | None=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, training: Optional[bool]=None) -> Union[Tuple, TFBaseModelOutput]: output_attentions = output_attentions if output_attentions is n...
Args: inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Embedded representation of the inputs. Should be float, not int tokens. attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values sel...
github-repos
def _batched_mask_to_box(masks: 'torch.Tensor'): if torch.numel(masks) == 0: return torch.zeros(*masks.shape[:-2], 4, device=masks.device) shape = masks.shape height, width = shape[-2:] in_height, _ = torch.max(masks, dim=-1) in_height_coords = in_height * torch.arange(height, device=in_heig...
Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which corresponds the following required indices: - LEFT: left hand side of the bounding box - TOP: top of the bounding box - RIGHT: right of the bounding box - BOTTOM: bottom of the bounding box Return [0,0,0,0] for an...
github-repos
def accountSummary(self, account: str = '') -> List[AccountValue]: if not self.wrapper.acctSummary: self.reqAccountSummary() if account: return [v for v in self.wrapper.acctSummary.values() if v.account == account] else: ...
List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name.
juraj-google-style
def stop_standing_subprocess(proc): import psutil pid = proc.pid logging.debug('Stopping standing subprocess %d', pid) process = psutil.Process(pid) failed = [] try: children = process.children(recursive=True) except AttributeError: children = pro...
Stops a subprocess started by start_standing_subprocess. Before killing the process, we check if the process is running, if it has terminated, Error is raised. Catches and ignores the PermissionError which only happens on Macs. Args: proc: Subprocess to terminate. Raises: Error: if the subprocess could not be stopp...
juraj-google-style
def compute_nats_and_bits_per_dim(data_dim, latent_dim, average_reconstruction, average_prior): with tf.name_scope(None, default_name='compute_nats_per_dim'): data_dim = tf.cast(data_dim, average_reconstruction.dtype) latent_dim = tf.cast(latent_dim, average_prior.dtype) negative_log_likelih...
Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicating data dimensionality. latent_dim: int-like indicating latent dimensionality. average_reconstruction: Scalar Tensor indicating the reconstruction cost averaged over all data dimensions and any data batches. av...
codesearchnet
def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): campaign_service = client.GetService('CampaignService', version='v201809') campaign = { 'name': 'Interplanetary Cruise 'budget': { 'budgetId': budget_id }, 'biddingStrategyConfiguration': { ...
Create a Campaign with a Shared Bidding Strategy. Args: client: AdWordsClient the client to run the example with. bidding_strategy_id: string the bidding strategy ID to use. budget_id: string the shared budget ID to use. Returns: dict An object representing a campaign.
juraj-google-style
def register_array_types_from_sources(self, source_files): for fname in source_files: if is_vhdl(fname): self._register_array_types(self.extract_objects(fname))
Add array type definitions from a file list to internal registry Args: source_files (list of str): Files to parse for array definitions
juraj-google-style
def _generate_legacy_type_checks(types=()): types = dict(types) def gen_type_check(pytypes): pytypes = _utils.flatten(pytypes) def type_check(checker, instance): if isinstance(instance, bool): if bool not in pytypes: return False ...
Generate newer-style type checks out of JSON-type-name-to-type mappings. Arguments: types (dict): A mapping of type names to their Python types Returns: A dictionary of definitions to pass to `TypeChecker`
juraj-google-style
def around(A, decimals=0): if isinstance(A, Poly): B = A.A.copy() for key in A.keys: B[key] = around(B[key], decimals) return Poly(B, A.dim, A.shape, A.dtype) return numpy.around(A, decimals)
Evenly round to the given number of decimals. Args: A (Poly, numpy.ndarray): Input data. decimals (int): Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. Returns: (Poly, numpy.ndarray): Same type as A. Examples: >>> P ...
codesearchnet
def _ParseRecord(self, parser_mediator, file_object, record_offset): record_strings_data_offset = file_object.tell() record_strings_data_size = (record_offset - record_strings_data_offset) record_strings_data = self._ReadData(file_object, record_strings_data_offset, record_strings_data_size) record_map ...
Parses a record and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. Returns: int: next record offset. Rais...
codesearchnet
def apply_gradients(self, grads_and_vars, global_step=None, name=None): (self._grad, self._vars) = zip(*[(g, t) for (g, t) in grads_and_vars if (g is not None)]) with tf.variable_scope('apply_updates'): if (self._clip_thresh_var is not None): (self._grad, _) = tf.clip_by_global_norm(self._gr...
Applying gradients and tune hyperparams with YellowFin. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to t...
codesearchnet
def _retrieve_info(self, http): if self.invalid: info = _metadata.get_service_account_info(http, service_account=(self.service_account_email or 'default')) self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes']
Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests.
codesearchnet
def attachment_to_multidim_measurement(attachment, name=None): data = json.loads(attachment.data) name = name or data.get('name') attachment_dims = data.get('dimensions', []) attachment_values = data.get('value') attachment_outcome_str = data.get('outcome') if attachment_outcome_str not in TEST_R...
Convert an OpenHTF test record attachment to a multi-dim measurement. This is a best effort attempt to reverse, as some data is lost in converting from a multidim to an attachment. Args: attachment: an `openhtf.test_record.Attachment` from a multi-dim. name: an optional name for the measurement. If not provided will...
juraj-google-style
def _hash_sequence(self, sighash_type, anyone_can_pay): if (anyone_can_pay or (sighash_type == shared.SIGHASH_SINGLE)): return (b'\x00' * 32) else: sequences = ByteData() for tx_in in self.tx_ins: sequences += tx_in.sequence return utils.hash256(sequences.to_bytes())
BIP143 hashSequence implementation Args: sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL anyone_can_pay (bool): true if ANYONECANPAY should be set Returns: (bytes): the hashSequence, a 32 byte hash
codesearchnet
def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed): num_entries = ((num_rows * (num_rows + 1)) / 2) ones = tf.ones(shape=[num_entries], dtype=dtype) unifs = uniform.Uniform((- ones), ones).sample(batch_shape, seed=seed) tril = util.fill_triangular(unifs) symmetric = (tril + tf....
Returns a uniformly random `Tensor` of "correlation-like" matrices. A "correlation-like" matrix is a symmetric square matrix with all entries between -1 and 1 (inclusive) and 1s on the main diagonal. Of these, the ones that are positive semi-definite are exactly the correlation matrices. Args: num_rows: Python `int`...
codesearchnet
def __setitem__(self, key, value): if key == 'resources': self.add_update_resources(value, ignore_datasetid=True) return super(Dataset, self).__setitem__(key, value)
Set dictionary items but do not allow setting of resources Args: key (Any): Key in dictionary value (Any): Value to put in dictionary Returns: None
juraj-google-style
def cmap_from_color(color, dark=False): if dark: return sns.dark_palette(color, as_cmap=True) else: return sns.light_palette(color, as_cmap=True)
Generates a matplotlib colormap from a single color. Colormap will be built, by default, from white to ``color``. Args: color: Can be one of several things: 1. Hex code 2. HTML color name 3. RGB tuple dark (bool): If ``True``, colormap will be built from ``color`` to black. Default is ``False``, which builds a col...
juraj-google-style
async def get_participants(self, force_update=False) -> list: if (force_update or (self.participants is None)): res = (await self.connection('GET', 'tournaments/{}/participants'.format(self._id))) self._refresh_participants_from_json(res) return (self.participants or [])
get all participants |methcoro| Args: force_update (default=False): True to force an update to the Challonge API Returns: list[Participant]: Raises: APIException
codesearchnet
def scatter_sub(self, sparse_delta, use_locking=False, name=None): if not isinstance(sparse_delta, indexed_slices.IndexedSlices): raise TypeError(f'Argument `sparse_delta` must be a `tf.IndexedSlices`. Received arg: {sparse_delta}') return self._lazy_read(gen_resource_variable_ops.resource_scatter_sub(s...
Subtracts `tf.IndexedSlices` from this variable. Args: sparse_delta: `tf.IndexedSlices` to be subtracted from this variable. use_locking: If `True`, use locking during the operation. name: the name of the operation. Returns: The updated variable. Raises: TypeError: if `sparse_delta` is not an `IndexedSlices`.
github-repos
def asdict(self): timestamp_str = None if (self.reading_time is not None): timestamp_str = self.reading_time.isoformat() return {'stream': self.stream, 'device_timestamp': self.raw_time, 'streamer_local_id': self.reading_id, 'timestamp': timestamp_str, 'value': self.value}
Encode the data in this reading into a dictionary. Returns: dict: A dictionary containing the information from this reading.
codesearchnet
def flownet2_sd(self, x): with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activatio...
Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W]
juraj-google-style
def _add_namespace(marc_xml): dom = marc_xml if isinstance(dom, basestring): dom = dhtmlparser.parseString(marc_xml) root = dom.find("root") if root: root[0].params = {} for record in dom.find("record"): record.params = {} collections = dom.find("collection") ...
Add proper XML namespace to the `marc_xml` record. Args: marc_xml (str): String representation of the XML record. Returns: str: XML with namespace.
juraj-google-style
def iterate_ngrams(text, n): if n <= 0: raise ValueError("n must be a positive integer") return [text[i: i + n] for i in range(len(text) - n + 1)]
Generator to yield ngrams in ``text``. Example: >>> for ngram in iterate_ngrams("example", 4): ... print(ngram) exam xamp ampl mple Args: text (str): text to iterate over n (int): size of window for iteration Returns: Generator expression to yield the next ngram in the text Raises: ValueError: If n is non posit...
juraj-google-style
def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''): (_, ext) = os.path.splitext(filename) if (ext != '.png'): filename += '.png' gnuplot_cmds = '\n set datafile separator ","\n set term pngcairo size 30cm,25cm\n set out filename\n\n unset key\n set border lw 1.5\n set...
Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x-axis label. y_label (str): y-axis label.
codesearchnet
def _CreateClassTemplate(cls, data_type_definition): type_name = data_type_definition.name type_description = data_type_definition.description or type_name while type_description.endswith('.'): type_description = type_description[:-1] class_attributes_description = [] init_arguments = [...
Creates the class template. Args: data_type_definition (DataTypeDefinition): data type definition. Returns: str: class template.
juraj-google-style
def conditionally_create_security_groups(env, service_name, service_type): if service_type not in SG_SERVICE_TYPES: print_if_verbose("not eligible for security group(s); service type: {}".format(service_type)) return target_name = "{}-{}".format(env, service_name) if service_type == "aws_ec2": sg_...
Create security groups as needed; name and number created depend on service_type Args: env: the environment the SG will be created in service_name: name of the service in service registry service_type: service registry service type: 'aws_ec2', 'aws_lambda', 'aws_security_group', or 'http_service'
juraj-google-style
def get_current_human_time(): return time.strftime('%m-%d-%Y %H:%M:%S ')
Returns the current time in human readable format. Returns: The current time stamp in Month-Day-Year Hour:Min:Sec format.
github-repos
def split_key(key, max_keys=0): parts = [x for x in re.split(SPLIT_REGEX, key) if (x != '.')] result = [] while (len(parts) > 0): if ((max_keys > 0) and (len(result) == max_keys)): break result.append(parts.pop(0)) if (len(parts) > 0): result.append('.'.join(parts)) ...
Splits a key but allows dots in the key name if they're scaped properly. Splitting this complex key: complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme." split_key(complex_key) results in: ['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', ''] Args: key (basestring): The k...
codesearchnet
def __init__(self, func, type): self.func = func self.type = type
Instantiates a bound method object. Args: func (types.FunctionType): The method's underlying function type (type): The class of the method.
github-repos
def minimize_peak_memory(graph, scheduler_alg): if scheduler_alg == 'NAIVE': return _minimize_peak_memory_naive(graph) elif scheduler_alg == 'LIST': return _minimize_peak_memory_list(graph) else: raise NotImplementedError('{} is not a scheduler algorithm. It should be ' ...
Computes a schedule to minimize peak memory. Args: graph: an mtf.auto_mtf.graph_interface.GraphInterface. scheduler_alg: a string, one of 'NAIVE' or 'LIST' Returns: an iterable of integers representing the schedule.
juraj-google-style
def set_nsxcontroller_port(self, **kwargs): name = kwargs.pop('name') port = str(kwargs.pop('port')) port_args = dict(name=name, port=port) method_name = 'nsx_controller_connection_addr_port' method_class = self._brocade_tunnels nsxcontroller_attr = getattr(metho...
Set Nsx Controller pot on the switch Args: port (int): 1 to 65535. callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
juraj-google-style
def _print_contained_resource(self, contained_resource: message.Message) -> None: for _, set_field_value in contained_resource.ListFields(): if self.json_format == _FhirJsonFormat.ANALYTIC: structure_definition_url = annotation_utils.get_structure_definition_url(set_field_value) self...
Prints the set fields of the contained resource. If the _FhirJsonFormat is set to ANALYTIC, this method only prints the url. Args: contained_resource: The contained resource to iterate over and print.
github-repos
def market_if_touched_replace(self, accountID, orderID, **kwargs): return self.replace(accountID, orderID, order=MarketIfTouchedOrderRequest(**kwargs))
Shortcut to replace a pending MarketIfTouched Order in an Account Args: accountID : The ID of the Account orderID : The ID of the MarketIfTouched Order to replace kwargs : The arguments to create a MarketIfTouchedOrderRequest Returns: v20.response.Response containing the results from submitting the request
codesearchnet
def is_significant(sample1, sample2): deg_freedom = ((len(sample1) + len(sample2)) - 2) critical_value = tdist95conf_level(deg_freedom) t_score = tscore(sample1, sample2) return ((abs(t_score) >= critical_value), t_score)
Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool indicating whether the two samples differ significantly; t_score is the score from...
codesearchnet
def covariance_to_correlations(covariance): diagonal_ind = np.arange(covariance.shape[1]) diagonal_els = covariance[:, diagonal_ind, diagonal_ind] result = covariance / np.sqrt(diagonal_els[:, :, None] * diagonal_els[:, None, :]) result[np.isinf(result)] = 0 return np.clip(np.nan_to_num(result)...
Transform a covariance matrix into a correlations matrix. This can be seen as dividing a covariance matrix by the outer product of the diagonal. As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1]. Args: covariance (ndarray): a matrix of shape (n, p, p) with for n prob...
juraj-google-style
def test_antithetic_sample_paths_mean_2d(self, random_type, seed): mu = np.array([0.2, 0.7]) a = np.array([[0.4, 0.1], [0.3, 0.2]]) b = np.array([[0.33, -0.03], [0.21, 0.5]]) def drift_fn(t, x): del x return mu * tf.sqrt(t) def vol_fn(t, x): del x return (a * t + b)...
Tests path properties for 2-dimentional anthithetic variates method. The same test as above but with `PSEUDO_ANTITHETIC` random type. We construct the following Ito processes. dX_1 = mu_1 sqrt(t) dt + s11 dW_1 + s12 dW_2 dX_2 = mu_2 sqrt(t) dt + s21 dW_1 + s22 dW_2 mu_1, mu_2 are constants. s_ij = a_ij t + b_ij For...
github-repos
def get_metrics_namespace(self) -> str: return 'BeamML_HuggingFaceModelHandler_KeyedTensor'
Returns: A namespace for metrics collected by the RunInference transform.
github-repos
def get_value(value_proto): field = value_proto.WhichOneof('value_type') if (field in __native_value_types): return getattr(value_proto, field) if (field == 'timestamp_value'): return from_timestamp(value_proto.timestamp_value) if (field == 'array_value'): return [get_value(sub_v...
Gets the python object equivalent for the given value proto. Args: value_proto: datastore.Value proto message. Returns: the corresponding python object value. timestamps are converted to datetime, and datastore.Value is returned for blob_key_value.
codesearchnet
def get_time_series(sdat, var, tstart, tend): tseries = sdat.tseries_between(tstart, tend) if (var in tseries.columns): series = tseries[var] time = None if (var in phyvars.TIME): meta = phyvars.TIME[var] else: meta = phyvars.Vart(var, None, '1') elif ...
Extract or compute and rescale a time series. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. var (str): time series name, a key of :data:`stagpy.phyvars.TIME` or :data:`stagpy.phyvars.TIME_EXTRA`. tstart (float): starting time of desired series. Set to None to start at the beginning of ava...
codesearchnet
def split_input(cls, mapper_spec, _reader=blobstore.BlobReader): params = _get_params(mapper_spec) blob_key = params[cls.BLOB_KEY_PARAM] zip_input = zipfile.ZipFile(_reader(blob_key)) zfiles = zip_input.infolist() total_size = sum(x.file_size for x in zfiles) num_shards = min(mapper_spec.sh...
Returns a list of input shard states for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_key' parameter with one blob key. _reader: a callable that returns a file-like object for reading blobs. Used for dependency injection. Returns: A list of InputReaders spanning files wit...
juraj-google-style
def remove_temp_dirpath(dirpath, strategy): if strategy is None: strategy = distribute_lib.get_strategy() if strategy is None: return if strategy.extended._in_multi_worker_mode() and (not strategy.extended.should_checkpoint): file_io.delete_recursively(_get_temp_dir(dirpath, strategy...
Removes the temp path after writing is finished. Args: dirpath: Original dirpath that would be used without distribution. strategy: The tf.distribute strategy object currently used.
github-repos
def _GenerateUniqueRandomInputTensor(self, shape): num_elements = 1 for size in shape: num_elements *= size x = np.arange(num_elements, dtype=np.float32) self._PRNG.shuffle(x) return x.reshape(shape)
Generate 'unique' random input tensor. 'Unique' means there's no collision values in the tensor, all elements are different. This is done by generating sequence of integers with step of 1 and then randomly shuffle these integers. Args: shape: Shape of the tensor desired. Returns: A numpy ndarray with size = shape an...
github-repos
def add_other_location(self, location, exact=True, alterror=None, locations=None): (hdx_code, match) = Locations.get_HDX_code_from_location_partial(location, locations=locations, configuration=self.configuration) if ((hdx_code is None) or ((exact is True) and (match is False))): if (alterror is None): ...
Add a location which is not a country or region. Value is parsed and compared to existing locations in HDX. If the location is already added, it is ignored. Args: location (str): Location to add exact (bool): True for exact matching or False to allow fuzzy matching. Defaults to True. alterror (Optional[str]): Alternat...
codesearchnet
def feat(self, subset): r = None for f in self: if (isinstance(f, Feature) and (f.subset == subset)): if r: if isinstance(r, list): r.append(f.cls) else: r = [r, f.cls] else: r = f.cls if ...
Obtain the feature class value of the specific subset. If a feature occurs multiple times, the values will be returned in a list. Example:: sense = word.annotation(folia.Sense) synset = sense.feat('synset') Returns: str or list
codesearchnet
def execute_before(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator stream_a, trigger_a = self._convert_trigger(self.trigger_a, parent) if self.trigger_b is None: new_scope = TriggerScope(sensor_graph, scope_stack, (stream_a, tri...
Execute statement before children are executed. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested scopes that may influence how this statement allocates clocks or other stream resources.
juraj-google-style
def list_profile(self, args, screen_info=None): screen_cols = 80 if screen_info and 'cols' in screen_info: screen_cols = screen_info['cols'] parsed = self._arg_parsers['list_profile'].parse_args(args) op_time_interval = command_parser.parse_time_interval(parsed.op_time) if parsed.op_time else No...
Command handler for list_profile. List per-operation profile information. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object.
github-repos
def _broadcast_and_set_attrs(self, local_dict): del local_dict['self'] self.remove_axis = False max_length = 0 for key in local_dict: try: length = len(local_dict[key]) if (length > max_length): max_length = length except TypeError: pas...
Cast all inputs to correct dimensions. This method fixes inputs who have different lengths. Namely one input as an array and others that are scalara or of len-1. Raises: Value Error: Multiple length arrays of len>1
codesearchnet
def do_state(args): rest_client = RestClient(args.url, args.user) if (args.subcommand == 'list'): response = rest_client.list_state(args.subtree, args.head) leaves = response['data'] head = response['head'] keys = ('address', 'size', 'data') headers = tuple((k.upper() for...
Runs the batch list or batch show command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
codesearchnet