content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Tuple
import collections
def shortest_path_grid(grid: List[List[int]], start:Tuple[int, int], end:Tuple[int, int]):
"""
Finds shortest path in a grid of mxn using BFS and returns it's path length including start and end.
Uses direction vetors and each cell treats... | 249fb474764a4d19abad33fb887e649138f30301 | 668,000 |
def intercalate_sigma_into_peak_params(reduced_peak_params, sigmas):
"""
Insert the sigmas back into reduced_peak_params to form peak_params.
To describe N peaks,
Input
-----
reduced_peak_params : A vector of length = 2*N.
Every odd element describe an amplitude,
... | 388f277e3c0f258a0b18a42efb225a8657319531 | 668,001 |
from datetime import datetime
def parse_iso_date(txt: str) -> datetime:
"""Parse a datetime in ISO format."""
return datetime.strptime(txt[:19], "%Y-%m-%d %H:%M:%S") | 840fb5865ec3b86bdb1811ae117c8db9de8ec9fb | 668,003 |
def profit_filler(df, max_length):
"""Takes a dataframe and ensures all the profit rows are the same length for
adding together profits over the number of games, shorter rows will be
filled with their final value.
example: row 0 = [1,2,3,4], row 1 = [1,2,3] -> row 0 = [1,2,3,4],
row 1 = [1,2,3,3]
... | 0cc6e787f46fffdbc9890da408ead248d49e1ac6 | 668,011 |
def progress_bar(val, val_max, val_min=0, prefix="", suffix="", bar_len=20):
"""
Displays a progress bar in the simulation tree.
:param val: current value
:param val_max: maximum value
:param val_min: minimum value
:param prefix: marker for the completed part
:param suffix: marker for the in... | 141fe08ad0b6aa4222d739e0399b60078297acde | 668,012 |
def iteratively_query_dict(path: list, d: dict):
"""
Query a multidimensional dict with a list as the key.
:param path:
:param d:
:return:
"""
tmp = d
for key in path:
tmp = tmp[key]
return tmp | d006e88642eb3413e7e8ee69c269e51e13977de5 | 668,013 |
from textwrap import dedent
def indent(text, spaces=4, strip=False):
"""Return the ``text`` indented by the given number of ``spaces``."""
if not hasattr(text, 'splitlines'):
text = '\n'.join(text)
if strip:
text = dedent(text)
prefix = ' ' * spaces
output = '\n'.join(prefix + lin... | 3e715643eb367061cb13cdf9162e11004a732346 | 668,019 |
def fseq_sign_changes(f, arr, i):
"""
Checks whether a sequence's i'th image through a function f has different
sign from the i+1'th element
"""
return f(arr[i]) * f(arr[i+1]) < 0 | 61df4cda92281fe44364036a90db41ab3f2a8f5d | 668,020 |
import re
def parseTargetUrl(url):
"""
Parse target URL
"""
retVal = url
if not re.search("^http[s]*://", retVal, re.I) and not re.search("^ws[s]*://", retVal, re.I):
if re.search(":443[/]*$", retVal):
retVal = "https://" + retVal
else:
retVal = "http://" +... | 9538bb30f4d46d9282385c79cddb6e7e6bca7d61 | 668,022 |
def _get_word_ids(tokens, model_type="bert"):
"""Given the BPE split results, mark each token with its original word ids.
Args:
tokens: a list of BPE units
For example, if original sentnece is `iran and afghanistan speak the same language .`, then the roberta
tokens will be:
['ir', 'an', '... | c261ad5f760e57aaf5e5eac9ed88a4f9544f2537 | 668,023 |
def _FilterForImageType(artifacts, image_type):
"""Return only images for given |image_type|."""
return [i for i in artifacts if i.image_type == image_type] | 0193ca72067a76c8bbb9d56d966687f2466b9fd3 | 668,024 |
import json
def createJSONPackage(data):
"""
Returns a JSON package.
Args:
data (dict) : A dictionary consisting of the data to JSONify.
"""
return json.dumps(data) | eb0e2be865932b8ba32f48b2b59bbb6252d12382 | 668,027 |
def objective(model):
"""
The objective function of the model.
Parameters
----------
model : pyomo model object
The pyomo model that the optimization shall be run on.
Returns
-------
dev : float
The summed squared deviation between the resulting charging load
(... | 66e29fd8e6cf184049f0f31d8efde6b406f8878a | 668,028 |
def get_property_annotations(self, all=False):
"""Returns a dict with non-empty property annotations.
If `all` is true, also annotations with no value are included."""
onto = self.namespace.ontology
d = {a.label.first(): a._get_values_for_class(self)
for a in onto.annotation_properties()}
... | 2a86cc27d091a6cb8ecfd1cb567c8c0b9d6c3e04 | 668,033 |
def recurse_access_key(current_val, keys):
""" Given a list of keys and a dictionary, recursively access the dicionary
using the keys until we find the key its looking for
If a key is an integer, it will convert it and use it as a list index
Example:
>>> recurse_access_key({'a': 'b'}, ['a'])
... | d63f3da3a44f062a70985da031d91c4fbb961d4e | 668,036 |
def comment_command(mwdb, file_or_hash, comment):
"""
Add comment to object
"""
obj = mwdb.query(file_or_hash)
obj.add_comment(comment)
return dict(message="Added comment {object_id}", object_id=obj.id) | 13ddf5729cc5cbe71f896e3b13bfcc8bb6d64a3d | 668,037 |
from typing import Tuple
def _get_brackets(range_: str) -> Tuple[bool, bool]:
"""Extract the bracket types from the provided range."""
if range_[0] not in {"[", "("}:
raise ValueError(f"Invalid range bracket {range_[0]}" f", should be [ or (.")
if range_[-1] not in {"]", ")"}:
raise ValueE... | be92e74a875c83700508c81e58f40c8a3d5c5989 | 668,038 |
def conductivity_to_imaginary_permittivity(freq: float,
conductivity: float) -> float:
"""Converts between conductivity and imaginary permittivity
This is a simple and straightforward conversion between the value
of conductivity, in S/m, and the imaginary part of ... | 7e156a2f0bbad8235cb40978303d34d5b44899dd | 668,040 |
import click
import functools
def common_args(func):
"""
Decorator to contain CLI args that will be common to both CLI and GUI: title and engine args.
"""
@click.option("--title", "-t", help="Title to display (if omitted will use file name).")
@click.option(
"--layout",
"-l",
... | 3eb652645ff929952aa14af108732af17eee39d6 | 668,041 |
import itertools
def _split_doctest(code):
"""Split a single doctest string into multiple code block strings"""
def is_code(x):
return x.startswith(">>>") or x.startswith("...")
groups = itertools.groupby(code.splitlines(), is_code)
raw_code_blocks = (lines for is_code, lines in groups if is... | 22811d2b0598ac53d7a17c0e3fb496549ed32989 | 668,042 |
def add_cp(results, nodes, probabilities):
"""
Add the F-N cumulative frequency.
See equation (1) from Oughton et al. 2019.
Parameters
----------
results : list of dicts
All iterations generated in the simulation function.
nodes : int
Number of substations for the scenario.... | b189d07baf7ad3fe1d19afff39cfd0bf9d7a0c6c | 668,044 |
import pickle
def load_detectron_predictions(detectron_root):
"""Load detectron predictions from root directort.
Args:
detectron_root (Path): Points to a directory which contains a
subdirectory for each sequence, which in turn contains a .pickle
file for each frame in the sequ... | bc9c999aeab998bdb8de49343e770b5b7a7b99ed | 668,046 |
import re
def process_history(post_hist : list) -> dict:
"""Parses history metadata for title, date, student uid, and creation date.
:param post_hist: post history
:returns: dictionary with relevant history data pulled.
"""
hist_result = {}
init_post = post_hist[-1]
hist_result["student u... | 40098f0b62e81e74f7d82d431115c08cd2064597 | 668,047 |
def bool_2_uint8(bool_arr):
"""
Converts a boolean array to a black-and-white
uint8 array (0 and 255).
PARAMETERS:
im : (M x N) numpy array of bools
boolean array to convert
RETURNS:
(result) : (M x N) numpy array of uint8s
uint8 array of 0s (False) and 255s (... | 78e03b5e830486602d0f78d2250777c80a0a476d | 668,049 |
def input_new(s=""):
"""
Wrapper for the data entry function.
:param s: Description of the input value(Default value = "")
"""
return input(s) | 989a17a9e0a34d11eeddad3c5f826b3b47feb5e7 | 668,050 |
def step_learning_rate(base_lr, epoch, step_epoch, multiplier=0.1):
"""Sets the learning rate to the base LR decayed by 10 every step epochs"""
lr = base_lr * (multiplier ** (epoch // step_epoch))
return lr | 27c012e53421c91838f63e6319f8d4f03d0ff76c | 668,051 |
def get_multi_async(keys, **ctx_options):
"""Fetches a sequence of keys.
Args:
keys: A sequence of keys.
**ctx_options: Context options.
Returns:
A list of futures.
"""
return [key.get_async(**ctx_options) for key in keys] | 55e2c47c884d5d3b6aac41a64b9a938dadec222f | 668,052 |
def get_permission_names(perm_int):
"""Takes an integer representing a set of permissions and returns a list
of corresponding permission names."""
pms = {'God': 16, 'Admin': 8, 'Builder': 2, 'Player': 1, 'DM': 4}
perm_list = []
for key, value in pms.items():
if perm_int & value:
... | d9175a1fffe1599ae470519611f6e80adbb4f3fe | 668,056 |
def edgelist_from_synapse_df(syn_df,
pre_column='pre_pt_root_id',
post_column='post_pt_root_id',
weight_column='size',
agg='count'):
"""Compute a list of pre to post edges from a synapse-query-style d... | ff2301ea1beeb799bf5887e2e140dc8a31be406b | 668,058 |
from typing import Dict
def remove_margin_lines(obj: Dict) -> bool:
"""Remove the lines that are inside the margins
Useful for 106 D and E/F - mostly for split pages
:param obj: PDF character
:return: True or False
"""
if obj["width"] < 10:
return False
if 70 < obj["x0"] < 75:
... | 1dbe69af10a4a3e0cc87041187b67ae8277f5ade | 668,064 |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Any
def get_best_attribute(item: Dict[str, Optional[str]], keys: Tuple, fallback: Any = None) -> Optional[str]:
"""
Due to the weird nature of data exported from Last.fm, we need to check multiple keys to find the ... | 94fdc893ec7239c698d99d72c797a8ad67bb093c | 668,066 |
def calc_accu(a, b):
"""
Returns the accuracy (in %) between arrays <a> and <b>. The two arrays must
be column/row vectors.
"""
a = a.flatten()
b = b.flatten()
accu = 100.0 * (a == b).sum() / len(a)
return accu | 3f91e0805b3fc950da0ae02b34c8c0fb383e78c6 | 668,067 |
import hashlib
def message_to_hash(message_string):
"""Generate a hash deterministically from an arbitrary string."""
message = hashlib.sha256()
message.update(message_string.encode()) # Encode as UTF-8.
return int(message.digest().hex(), 16) >> 5 | 11b4d37488860cb3dae3525ced90f0d5072ffa0b | 668,068 |
def frequencies(colorings):
"""
Procedure for computing the frequency of each colour in a given coloring.
:param colorings: The given coloring.
:return: An array of colour frequencies.
"""
maxvalue = -1
frequency = [0] * (len(colorings))
for i in colorings:
maxvalue = max(maxvalu... | f9509e4c6ff253656a5e3d734e3b913c4428ec1c | 668,071 |
import torch
def pairwise_l2_sq(
x1,
x2,
):
"""Compute pairwise squared Euclidean distances."""
return torch.cdist(x1, x2).pow(2) | 12b147cba24fcd5a668ba614020a521225def3ae | 668,072 |
def update_function(func, invars, energized):
"""Return the output of the a Function's update method."""
return func.update(*invars, energized=energized) | 2e60daa5f99bda175d8308218b404c7d592920a9 | 668,075 |
import torch
def boxes3d_to_bev_torch_lidar(boxes3d):
"""
:param boxes3d: (N, 7) [x, y, z, w, l, h, ry] in LiDAR coords
:return:
boxes_bev: (N, 5) [x1, y1, x2, y2, ry]
"""
boxes_bev = boxes3d.new(torch.Size((boxes3d.shape[0], 5)))
cu, cv = boxes3d[:, 0], boxes3d[:, 1]
half_l, half... | 80c906865ab5b6465cc9189dda137a3010987115 | 668,076 |
def unpack(value):
"""Return a three tuple of data, code, and headers"""
if not isinstance(value, tuple):
return value, 200, {}
value_len = len(value)
if value_len == 2:
return value[0], value[1], {}
elif value_len == 3:
return value[0], value[1], value[2]
else:
r... | cc7f500534866b0f080d6e237ce89b90635c2782 | 668,081 |
def is_condition_key_match(document_key, some_str):
""" Given a documented condition key and one from a policy, determine if they match
Examples:
- s3:prefix and s3:prefix obviously match
- s3:ExistingObjectTag/<key> and s3:ExistingObjectTag/backup match
"""
# Normalize both
document_key = ... | e79c7b0e5fc8732d5b333893edf6eaf3cd234164 | 668,082 |
def read_best_fit(path):
"""
Return a 2-tuple consisting of the name and the best-fit objective function value,
given the path to sorted_params.txt
"""
with open(path) as f:
f.readline() # header
line = f.readline() # first pset (best)
parts = line.split()
n... | 3804f0d58fff62ccb78ccbad6a77ccdd9f827aa5 | 668,083 |
import torch
def ssm_vr_loss(energy_model, x, n_slices=1):
"""SSM-VR (variance reduction) loss from
Sliced Score Matching: A Scalable Approach to Density and Score Estimation
The loss is computed as
s = -dE(x)/dx
loss = vT*(ds/dx)*v + 1/2*||s||^2
Args:
x (torch.Tensor): input samples... | 914f74b661244fd2c098d2e01c4124359bb78111 | 668,084 |
def get_z_sample(xbar, mu, SE):
"""
Return the z-score of a sample, from a sampling distribution.
Parameters
----------
* xbar: mean of the current sample.
* mu: mean of the population from where the sample is drawn.
* SE: standard error of the sampling distribution (population SD / root(po... | be1b19d6c0ff6a9f47425e3b12813b6da68938f1 | 668,085 |
def round_filters(channels, global_params, skip=False):
"""
Calculate and round number of channels based on depth multiplier.
Args:
channels (int): base number of channels.
global_params (EasyDict): global args, see: class: `EfficientNet`.
skip (bool): if True, do nothing and return... | c30ddaaacf73812efa3cbc3032498204785c7c6b | 668,088 |
def ConstructNameFilterExpression(requested_name_regexes):
"""Construct a name filter expression.
Args:
requested_name_regexes: A list of name regular expressions that can
be used to filter the resources by name on the server side.
Returns:
A string expression suitable for the requested names, or ... | dc9fc587abab52e400866b6675102a48533431a1 | 668,090 |
def for_text_write(fpath):
""" For Python3 we often should open as a text file (like for json, csv.reader, etc) """
return open(fpath, "w") | 6cc53a98b6f869550271d21210173cf84e5b2c67 | 668,091 |
def split_heads(x, num_heads):
""" Split heads
:param x: A tensor with shape [batch, length, channels]
:param num_heads: An integer
:returns: A tensor with shape [batch, heads, length, channels / heads]
"""
assert x.shape[-1] % num_heads == 0, str(x.shape)
return x.reshape(x.shape[:-1] + (... | be77a96a531f89ae32098394028dd317073dba67 | 668,092 |
def right_child(node, new_node=None):
""" Set right child: right_child(node, new_right_child); Get right node: right_child(node). """
if new_node is not None:
node[2] = new_node
return node[2] | 545bc3a187f669bdf56bf88390a0dac3ff5fc80e | 668,098 |
def square(number: int):
"""Calculate square of a given number."""
return number ** 2 | c028a462b49cb743299820c4c0768543333f402b | 668,099 |
def calculatePostIapAggregateInterference(q_p, num_sas, iap_interfs):
"""Computes post IAP allowed aggregate interference.
Routine to calculate aggregate interference from all the CBSDs managed by the
SAS at protected entity.
Args:
q_p: Pre IAP threshold value for protection type (mW)
num_sas: Number ... | 269aa10ff5a4a22193525698248ab56e59759fb6 | 668,103 |
def get_plain_texts(input_dict):
"""
Widget transforms Annotated Document Corpus to string.
:param adc: Annotated Document Corpus.
:param feature_annotation: Select a feature annotation.
:param delimiter: Delimiter for token concatenation.
:param include_doc_id: Include Document Identifier.
... | 16fb2269cc590f40d9b9b5ca3010080a726773fc | 668,105 |
import string
def is_starting(token, alphabet=string.ascii_lowercase):
"""
Determines if the token starts a new word
"""
return len(token) > 1 and token.startswith(' ') and token[1].lower() in alphabet | 6ba4ad1a5310b6a55f9c53301b5a551c983e6ec3 | 668,106 |
def create_term_query(key, values, query_type):
"""Return an all or any term query for es"""
if query_type == "or":
return [{"terms": {key: values}}]
else:
return [{"term": {key: value}} for value in values] | c26091100a102f6d311864b53362f6917dd6803f | 668,110 |
def get_version(nb):
"""Get the version of a notebook.
Parameters
----------
nb : dict
NotebookNode or dict containing notebook data.
Returns
-------
Tuple containing major (int) and minor (int) version numbers
"""
major = nb.get('nbformat', 1)
minor = nb.get('nbformat_... | d99d4487dfff7c85fbc0d77c5a8f45a9a5838fdb | 668,112 |
from typing import Counter
def check_duplicate_fields(field_names):
"""
Check that there are no duplicate in the `field_names` list of field name
strings, ignoring case. Return a list of unique duplicated field names.
"""
counted = Counter(c.lower() for c in field_names)
return [field for fiel... | 1eb9bf82486a1e9e717154dfca91fae0ebc3ddd1 | 668,113 |
def get_access_token(request):
"""
Find access token in request in next order:
- acc_token query param
- X-Access-Token header
- access.token body value (for POST, PUT, PATCH and application/json content type)
Raise ValueError if no token provided
"""
token = request.params.get(... | aea859a6e937b5a6c855b142f53282c28ba8eefc | 668,114 |
def tree_to_s2t(tree_str):
"""
linearized the phrase tree to token sequences.
Args:
tree_str:(TOP (NP (NNP EDUCATION) (NNPS ADS) (: :)))
Return:
s2t format:
words: EDUCATION ADS :
tokens: NP NNP NNPS : /NP
"""
stack, tokens, words = [], [], []
for tok... | cadf1b09dad21b34ac23695a32fe6cada7885a25 | 668,115 |
def get_client_class_name_from_module(module):
"""Being a module that is an Autorest generation, get the client name."""
# Using the fact that Client is always the first element in __all__
# I externalize that code in a class in case we need to be smarter later
return module.__all__[0] | a8811200027b6c2ca969c758148f49256354ad76 | 668,117 |
def build_train_and_test_features(
df_columns,
features_to_process,
predict_feature,
ignore_features):
"""build_train_and_test_features
Order matters when slicing up datasets using scalers...
if not, then something that is an int/bool can get into a float
column and tha... | 08a9e6dc7651d71a36b9a947145618ead1fa3cee | 668,122 |
import time
def logarithmic_progress(iterable, verbose=True):
"""A funny type of progress bar I use a lot.
This does two things:
* Return a true/false flag if the iteration is a power of two, or
the last iteration. Usually I want to save results at this point, or
print an update to screen.
* ... | ec85fbf67c50902949b61904036a7b5da0b5e211 | 668,125 |
def nullish_coalescing(value, default):
"""
nullish coalescing utility call
Provides a return of the provided value unless the value is a ``None``,
which instead the provided default value is returned instead.
Args:
value: the value
default: the default value
Returns:
... | 7c2afd1cd2deda0bfa5aa71bb956b1997d0fac40 | 668,127 |
def convert_ft_to_psi(fthead, sg = None, W = None):
"""
Conversion formula for calculating head in psi if head in ft is known, as well
as either the specific gravity or Specific weight (ex. W for water = 62.32 lb/ft^3 @ 68 deg C)
ex:
>>> x = tdh.convert_ft_to_psi(15.0, sg = 1.0)
or
>>> ... | 3f0e5482ba7b10a3cd5d771f920a35f13094b499 | 668,129 |
import math
def nextpow2(n):
"""
Return the smallest power of two greater than or equal to n.
"""
return int(math.ceil(math.log(n) / math.log(2))) | 0048fde09533378a28c05fccf17b3b2864e8717f | 668,132 |
def extract_http_req_body(contents):
"""
Splits the HTTP request by new lines and gets the
last line which is the HTTP payload body
"""
return contents.split(b"\n")[-1] | 31966a68c0bb7522a454a9cdda769785eec3bb2f | 668,133 |
def serialize_value(value):
"""
Serialize a value in an DeepImageJ XML compatible manner.
:param value:
:return:
"""
if isinstance(value, bool):
return str(value).lower()
else:
return str(value) | dcc4ac70c778460cc6e6494e37a5035ce0d96f41 | 668,136 |
from typing import Iterable
from typing import Counter
def number_of_clusters(_, labels: Iterable) -> float:
"""Number of total clusters.
Args:
_: Dummy, pass anything or None
labels (Iterable): Vector of sample labels.
Returns (int):
Number of clusters.
"""
ret... | 3beb16b847fecb434fcdd98b86695131c38f3072 | 668,137 |
from typing import Union
def device_id_from_mac_address(mac_address: Union[str, bytearray]) -> str:
"""
Convert device's physical address to a device ID
:param mac_address: MAC-address in dash/colon/spaced/concatenated format
:type mac_address: str, bytes, bytearray
:return: Device ID
:rtype: ... | a18012bf6e9bfd691d31136510a0c5fff66951fe | 668,138 |
from typing import List
def assert_optional_type_hints(contents: List[str]) -> List[str]:
"""
Find parameters with default value None and add Optional[type] to them.
:param contents: list of lines in file
:return: list of lines in file
"""
i = 0
while i < len(contents) - 1:
line ... | d95a3eec4c3e2ef0874d5ee974c614eecdddc8a7 | 668,142 |
import torch
def hinge_loss_rec(positive: torch.Tensor, negative: torch.Tensor, margin=1) -> torch.Tensor:
"""Hinge loss for recommendations"""
dist = positive - negative
return torch.sum(torch.maximum(margin - dist, torch.Tensor([0]))) | 42b888c45ca521dad7737b485ff48265c905bced | 668,144 |
def set_recomputation_options(opts,
allow_recompute=True,
allow_stateful_recompute=None): # pylint: disable=unused-argument
"""Set re-computation options.
Args:
allow_recompute: Whether or not to re-compute instructions during training.
If this... | d0e4a6fbaf23401f5e5bba2ec9759627880529fc | 668,146 |
def passthrough_scorer(estimator, *args, **kwargs):
"""Function that wraps estimator.score"""
return estimator.score(*args, **kwargs) | 4fe20ee2f611adc523eb70d58f170775cdcabf69 | 668,149 |
def convert_to_bundleClass_format(samcc_selection):
"""converts samcc selection from this library to original format used by bundleClass
input: samcc-ready selection, list of helices, each helix a list of format [ chain_id(string), start_residue(int), stop_residue(int) ]
output: BundleClass-ready selection, list of ... | 3b9c20e3d337757a1d7926302b0d2fdec80410b4 | 668,150 |
def create_ca_file(anchor_list, filename):
"""
Concatenate all the certificates (PEM format for the export) in
'anchor_list' and write the result to file 'filename'. On success
'filename' is returned, None otherwise.
If you are used to OpenSSL tools, this function builds a CAfile
that can be us... | cc9eae17844be858f54369041849acba94f70890 | 668,151 |
def uppercase_range(code1, code2):
"""
If the range of characters from code1 to code2-1 includes any
lower case letters, return the corresponding upper case range.
"""
code3 = max(code1, ord('a'))
code4 = min(code2, ord('z') + 1)
if code3 < code4:
d = ord('A') - ord('a')
retu... | bf682dc8dcc2c1bb545ae7adf4065f346e92fa71 | 668,156 |
def int_to_bin_string(x, bits_for_element):
"""
Convert an integer to a binary string and put initial padding
to make it long bits_for_element
x: integer
bit_for_element: bit length of machine words
Returns:
string
"""
encoded_text = "{0:b}".format(x)
len_bin = len(... | e8590223d0581985f7dcd256fa0290878ba95f68 | 668,157 |
def get_record_meta(record_list):
"""Get meta data of FASTA record.
"""
acc_code = record_list[0]
organism = record_list[1]
EC_code = record_list[2].replace("__", " ")
species = record_list[3].replace("__", " ")
note = record_list[4]
return acc_code, organism, EC_code, species, note | 9a1382bc9473d8da19cc9de9bdffec0e273cb4b8 | 668,159 |
def str_to_list(string, key_name=""):
"""Evaluates a string as a list. Checks if border characters are
'[' and ']', to avoid bad typing.
key_name : string (optional)
Name of the parameter. Useful for error message.
"""
if string[0] == '[' and string[-1] == ']':
return list(eval(stri... | fdbfe4314649b4797c2620b9cdc78026c7f24717 | 668,161 |
def clip_grad_by_norm_(grad, max_norm):
"""
in-place gradient clipping.
:param grad: list of gradients
:param max_norm: maximum norm allowable
:return: average norm
"""
total_norm = 0
counter = 0
for g in grad:
param_norm = g.data.norm(2)
total_norm += param_norm.ite... | 462ff13b7b60b09ac9025805e19fe1228e67be41 | 668,165 |
import re
def idsub(tag):
"""In aSc, "id" fields may only contain ASCII alphanumeric characters,
'-' and '_'. Substitute anything else by '_'.
"""
return re.sub('[^-_A-Za-z0-9]', '_', tag) | 3299b7a88e512e32686780e31e52b71565cf6944 | 668,166 |
def reverse_geometric_key(gkey):
"""Reverse a geometric key string into xyz coordinates.
Parameters
----------
gkey : str
A geometric key.
Returns
-------
list of float
A list of XYZ coordinates.
Examples
--------
>>> from math import pi
>>> xyz = [pi, pi, ... | 0619ed7ee45efe646d5836c6f767b35217ea3f6f | 668,167 |
import json
def to_json_string(obj):
"""Convert object as a JSON string."""
return json.JSONEncoder(indent=2).encode(obj) | 5e6377365ec5f5a2550533af733b3c5babbd81fa | 668,170 |
import json
def make_base_config(config_file, kwargs, par):
"""
Make a config file for `fps_single.py`.
Args:
config_file (str): path to general config file
kwargs (dict): extra dictionary items to put in it
par (bool): whether we're going to be using
this to make finge... | 13c88ae5976881222af04bac282378fbea1de9b2 | 668,172 |
def sim_file_to_run(file):
"""Extracts run number from a simulation file path
Parameters
----------
file : str
Simulation file path.
Returns
-------
run : int
Run number for simulation file
Examples
--------
>>> file = '/data/ana/CosmicRay/IceTop_level3/sim/IC7... | cdbd04a85da96b163da95595dc3313be2c64dec8 | 668,173 |
def calculate_number_of_pay_periods(period_payment, frequency, max_tax):
"""
Calculate the number of pay periods that it will take to pay off a tax burden
Param: period_payment: (float)
How much is being taken off per pay
Param: frequency: (int)
How many payments per year
Param: ma... | 6660bb5edae99cde5d98e86e53c8f82c40ad7cb7 | 668,174 |
from typing import Tuple
from typing import List
import re
def parse_mate_info_from_id(
seq_id: str
) -> Tuple[int, str]:
"""Extracts mate information from sequence identifier.
Args:
seq_id: Sequence identifier.
Returns:
An integer representing the mate information and the sequence
... | 00f9d91b259a51bfc7d7d810089f0af0805047ef | 668,176 |
def coord2act(board, coords):
"""Convert coordinate to action."""
return coords[0] * board.shape[-1] + coords[1] | 1d7aafe280ae7832eb756b8945a6d56bb3929305 | 668,177 |
from functools import reduce
def multiply_ints_list(tokens):
"""
parse action to multiply integers in a VBA expression with operator '*'
"""
# extract argument from the tokens:
# expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...]
integers = tokens[0][::2]
retu... | bf6c37d12532f81bc960b7d8ecc8c14d0fc2d997 | 668,181 |
def stringify(grid: dict, n: int) -> str:
"""Stringify with (0, 0) in the lower-left corner."""
rows = []
for y in reversed(range(n)):
row = []
for x in range(n):
value = grid.get((x, y), "-")
row.append(value)
rows.append(row)
return "\n".join("".join(r... | 728d1dced3a28f9c9435707adaa8794c64ce59ce | 668,189 |
def get_winner(game):
"""
Returns the winner player if any, or None otherwise.
"""
return game["winner"] | e21c3bc0d5965f181361bf2edea78543b448b346 | 668,190 |
def results_config(current_page):
"""Returns a config for each source's search results page."""
return {
"coindesk": {
"page_url": "https://www.coindesk.com/page/" + str(current_page) + "/?s=Bitcoin",
"item_XPATH": '//div[@class="post-info"]', # XPATH for the search result item ... | 83c4e5789e89bd15aed33d77aeaf7b588bfa1d38 | 668,193 |
def find_google_fileid_tree(service, fileId):
"""Find the folder tree of a file
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/goo... | 7daaf3cda1f9677de87fa7f30d693f61806c62b7 | 668,195 |
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the accelerat... | 646ddccdd8d27d3fc949469868afb1c59ff9b740 | 668,196 |
def word_preprocessing(word, ignore_non_alnumspc=True, ignore_space=True, ignore_numeric=True, ignore_case=True):
"""
Function for word preprocessing
|
| Argument
| | word: a string to be processed
|
| Parameter
| | ignore_non_alnumspc: whether to remove all non alpha/numeric/space characters
| | ignore_space... | b5c1737cc5b92337e05e0c1f58950146d94f95e4 | 668,198 |
def floyd_warshall(weight):
"""All pairs shortest paths by Floyd-Warshall
:param weight: edge weight matrix
:modifies: weight matrix to contain distances in graph
:returns: True if there are negative cycles
:complexity: :math:`O(|V|^3)`
"""
V = range(len(weight))
for k in V:
for... | 018a9908a59269532256b556619936f331261390 | 668,199 |
def test_api_key(client, BinanceAPIException):
"""Checks to see if API keys supplied returns errors
Args:
client (class): binance client class
BinanceAPIException (clas): binance exeptions class
Returns:
bool | msg: true/false depending on success, and message
"""
try:
... | 56f189b63b6418b044c21360ae97360afa194c7b | 668,204 |
def find_primary_and_secondaries(users):
"""Given a list of users with the same username, find the user who should be the primary
user into which the other users will be merged. Return a tuple (primary_user, list_of_secondary_users)
"""
actives = [each for each in users if each.is_active]
# If there... | 6e776028ffdf60acdb07314c0aeff325c9d2fbe9 | 668,206 |
def _extract_open_mpi(version_buffer_str):
"""
Parses the typical OpenMPI library version message, eg:
Open MPI v4.0.1, package: Open MPI Distribution, ident: 4.0.1, repo rev: v4.0.1, Mar 26, 2019
"""
return version_buffer_str.split("v", 1)[1].split(",", 1)[0] | a20d1ed65f9b40c50ec5c28a17fd73f11a470c9e | 668,209 |
import torch
def make_valid_from_train(dataset, cut=0.9):
"""
Split training data to get validation set
:param dataset: Training dataset
:param cut: Percentage of dataset to be kept for training purpose
"""
tr_ds, val_ds = [], []
for task_ds in dataset:
x_t, y_t = task_ds
# shuffle before spli... | 3f6fa8fe97af132e9dd575df9416145874717f4a | 668,211 |
def find_history_active_at(obj, time):
"""Assumes obj has a corresponding history model (e.g. obj could
be Person with a corresponding PersonHistory model), then either
returns the object itself if it was active at time, or the history
object active at time, or None if time predates the object and its
... | 9fc8b43484d8de979c1e237950287a9e90439544 | 668,212 |
import collections
def fetch_for_subscriptions(weboob_proxy, method, subscriptions, backend):
"""
Fetch related items for a given list of subscriptions.
:param weboob_proxy: An instance of ``WeboobProxy`` class.
:param method: The method to call on the bakend to fetch items.
:param subscriptions:... | f32099c576f8aa2f6c40fe740edcf3b420ff19a5 | 668,214 |
def make_tile_type_name(cells):
"""
Generate the tile type name from cell types
"""
cell_types = sorted([c.type for c in cells])
cell_counts = {t: 0 for t in cell_types}
for cell in cells:
cell_counts[cell.type] += 1
parts = []
for t, c in cell_counts.items():
if c == 1... | a011bf07b778b24b38cc87f7e9979d150745d839 | 668,218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.