content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Optional
def _truncate_doc(
doc: str,
max_len: Optional[int] = None,
) -> str:
"""
Truncate a document to max_len by the rough number of tokens
"""
if not max_len:
return doc
if len(doc.split()) > max_len:
doc = " ".join(doc.split()[:max_len])
ret... | e0fe82ece4e206f0023cdf25dbb74a4da8df77ed | 649,821 |
def _maybe_get_and_apply(dictionary, key, apply_fn):
"""Returns the result of apply_fn on the value of the key if not None."""
if key not in dictionary:
return None
return apply_fn(dictionary[key]) | 35407e8a2a64fd32969fff39703075e0f062ecdc | 649,822 |
def extract_validatable_type(type_name, models):
"""Returns a jsonschema-compatible typename from the Swagger type.
This is necessary because for our Swagger specs to be compatible with
swagger-ui, they must not use a $ref to internal models.
:returns: A key-value that jsonschema can validate. Key wil... | bf1badf1ddf5c2754bc9b71a7387e4a37166db7c | 649,823 |
def nflatten_map(_map):
""" Flattens the nested mapping and returns an array of the values
Args:
_map (dict): output of get_map
Returns:
(arr): an array of the values within nflatten_map
"""
values = []
if isinstance(_map, dict):
values += [nflatten_map(val) for val in _m... | 6bf101a36f2254500f0f923a7dd771f18f48a1d9 | 649,825 |
import time
def timing(function, *args):
"""
Run a fonction and eturn the run time and the result of the function
If the function requires arguments, those can be passed in
"""
startTime = time.time()
result = function(*args)
print('{} function took {:.3f}ms'.format(function.__name__, (tim... | 99d078686c4b2e8c175b5aaa0b297aed9aaba31f | 649,826 |
def ModifyAutohealingPolicies(current_policies, messages, args,
health_check_url):
"""Modifies existing autohealing policy from args."""
if args.clear_autohealing:
return [messages.InstanceGroupManagerAutoHealingPolicy()]
if not health_check_url and not args.initial_delay:
# ... | 90fff8afb42fffa5e91298fc0c7963a6e0ecf77e | 649,827 |
import requests
def gov_orgs():
"""
Returns a list of the names of US Government GitHub organizations
Based on: https://government.github.com/community/
Example return:
{'llnl', '18f', 'gsa', 'dhs-ncats', 'spack', ...}
"""
us_gov_github_orgs = set()
gov_orgs = requests.get("http... | 5b28fdef772d23c925b773ced20cdd0c39fcd18f | 649,829 |
import torch
from typing import List
import random
def get_indices(targets: torch.Tensor, per_class: bool = True,
count: int = 4, seed: int = 0) -> List[int]:
"""Samples indices to visualize
:param targets: ground truths
:type targets: torch.Tensor
:param per_class: whether count mean... | 9b7aa4420669c1a5f44f16af93fd0f220bb22a05 | 649,831 |
def list_concat_tail(funk, left, right, result=None):
"""
This corresponds to:
[X] ~> [MyArray]
Note that this operation will allocate the resulting
list in the Heap.
"""
funk.emitter.add_comment('Concatenating two arrays')
ptr_left = left.eval(result=result)
ptr_right = right... | 455504bb7a482a0e781a094b6bc6aef763b2db05 | 649,832 |
import time
def nonce():
"""Returns a nonce."""
return str(int(time.time() * 1000000)) | 618d96e158988cfedd330227465753d16e286dd9 | 649,833 |
import torch
def NB_log_prob(x, mu, theta, eps=1e-8):
"""
Adapted from https://github.com/YosefLab/scVI/blob/master/scvi/models/log_likelihood.py
"""
log_theta_mu_eps = torch.log(theta + mu + eps)
res = (
theta * (torch.log(theta + eps) - log_theta_mu_eps)
+ x * (torch.log(mu + e... | f105cca7bf095cae8678aceab7fb88d1644aa418 | 649,834 |
import time
def time_stamp():
"""
Return ISO-8601 compliant date/time format
:return: time information
"""
tmptz = time.timezone
sign_str = '+'
if tmptz > 0:
sign_str = '-'
tmptz_hours = int(tmptz / 3600)
return str("%s%s%02d:%02d" % (time.strftime("%Y-%m-%dT%H:%M:%S", t... | bcfc0507a837ddc8cee185d8a31f3d7876605536 | 649,836 |
import os
def __get_interface_subdirectory(interface):
"""Get the subdirectory the files for this interface should reside in."""
sub_path = ""
directories = interface.get_name_components()[0:-1]
for d in directories:
sub_path = os.path.join(sub_path, d)
return sub_path | 30ef378331d74c1fa0e2102caedfe1d4a7d7ecf4 | 649,837 |
def validar_correo(usuario: str, dominio: str = '@calufa.com') -> bool:
"""Función que valida si un correo electrónico pertenece al dominio
calufa.com
:param usuario: correo electrónico a validar
:type usuario: str
:param dominio: dominio a validar
:type dominio: str
:return: True si perten... | 46af169b1045347a05927afd9b4d3db70e53b8f3 | 649,838 |
def sanitize_delimiter(delimiter, is_tab):
"""
Return a single character delimiter from the given (possibly unicode)
string. If is_tab is True, always return a single tab. If delimiter is None
then return None. Raise an Exception if the delimiter can't be converted to
a single character.
Why is... | ebd6e948911842cb584fc12fa97d858a110a6f98 | 649,839 |
import torch
def compute_dihedrals(xyz, particle_index):
""" Compute dihedral angles between sets of four particles.
Parameters:
-----------
xyz: torch.Tensor
input tensor of shape :math:`(\text{frames} , \text{particles} , 3)`
particle_index: torch.LongTensor
particle index tens... | 67294f93b3237b3e1e37b8b4484cb1bf78bfe1c9 | 649,841 |
def _find_next_target_op(op, graph, target_op_idx, sc_path):
""" Find the target op from other branch in the shortcut """
if op.idx() == target_op_idx:
return True
n_ops = graph.next_ops(op)
for n_op in n_ops:
sc_path.append(n_op.type())
return _find_next_target_op(n_op, graph, t... | c284e8500b6d55ea182604ba380d532cbe1ee0b2 | 649,842 |
import numpy
def comparefloats(a, b, precision = 0.0001 ):
"""Compare two float scalars or arrays"""
aa = numpy.ravel(numpy.array(a))
bb = numpy.ravel(numpy.array(b))
if len(aa) == len(bb) == 0: return True
if len(aa) != len(bb): return False
diff = numpy.abs(aa-bb)
if diff.max() > precis... | 8b8f3a3827143e4babd73f7e411e554b9e667923 | 649,843 |
import os
import subprocess
def is_return_code_zero(args):
"""Return true iff the given command's return code is zero.
All the messages to stdout or stderr are suppressed.
"""
FNULL = open(os.devnull, 'w')
try:
subprocess.check_call(args, stdout=FNULL, stderr=FNULL)
except subprocess.... | 787d6cd2a69b5aec9e2cf487c3e888a9af23d94f | 649,844 |
import re
def get_forward_returns_columns(columns):
"""
返回远期收益的序列
"""
pattern = re.compile(r"^(return\(.+\))$", re.IGNORECASE)
valid_columns = [(pattern.match(col) is not None) for col in columns]
return columns[valid_columns] | d93d60b3090e6ad7ea863b8da68346b2dcc2b059 | 649,847 |
def degdiff(angle1, angle2):
"""
The difference of two angles given in degrees. The answer is an angle from
-180 to 180. Positive angles imply angle2 is clockwise from angle1 and -ve
angles imply counter-clockwise.
>>> int(degdiff(40, 30))
-10
>>> int(degdiff(30, 40))
10
>>> int(deg... | cb5ff913ccfff49dd0ccb4b6ce1e748ab3f9e4ba | 649,848 |
def mul(a, b):
"""
>>> mul(2,3)
6
>>> mul('a',2)
'aa'
"""
return a*b | d74be2cf2cf4ca4673cb8a24a2c1d8813ed4e4d6 | 649,849 |
def quote(string):
""" Surround a string with double quotes """
return f'"{string}"' | fb025db6c19e78a0e980f1a2eecb2a8edc51c671 | 649,850 |
def fill_missing_doi_for_8DayEVI_Landsat_from_human_system_time(land_df):
"""
input: land_df: a dataframe that has come from the 8-day EVI landsat date set.
it includes human_system_time which is in the form of year-month-day
and it is of type timestamp
... | e1eb6433a1d84e3e602959d0f2ee16dd7c7de25c | 649,851 |
def permissions2str(n):
"""Convert permission representation into a string representation.
Used as a Jinja2 custom filter.
"""
perms = {0: 'a', 1: 's', 2: 'm', 3: 'u', 4: 'c', 5: 'w', 6: 'f', 7: 'r'}
perm_str = "{0:0>8}".format(bin(n).lstrip('0b'))
result = ''
for k in perms.keys():
... | 52f6b96bc08ecc6602acf48f7ae4d9ac6707dd35 | 649,852 |
def get_entities(tracker, entites_list):
"""Filter entites from text."""
entites_set = set(entites_list)
filtered_entites = {en['entity']: en['value']
for en in tracker.latest_message.entities}
return {en: filtered_entites.get(en) for en in entites_set.intersection(set(filtered_e... | 03db209bbc0fc7960bf7dfed90afe3fda016dd29 | 649,853 |
def filter_top_exchange_addresses(exhanges_df, min_balance = 2000, min_txn_count = 400000):
"""
Filter exchanges with balance > min_balance and transaction count > min_txn_count
Args:
exchanges_df: (pd.Dataframe) Exchanges with atleast columns 'balance'(float), 'txn_count'(float) and 'address' (str... | 088265f4e0021095a8b03977bc5209ed2a103a09 | 649,854 |
def retrieve_unnamed_argument(args, default_value=None):
"""Retrieves the first argument provided by concatenating each following separate line. When an argument starts with '-', the first argument is done.
"""
argument_value = default_value
argument_val_list = []
NameCheck = True
for arg in arg... | 4799483dc230003cc424e60627bc2a353867accd | 649,855 |
def _serology_paired(df):
"""Helper method serology paired for one patient.
"""
# Paired samples
ps = []
for e in df.rolling(window=2, min_periods=2):
if e.shape[0] == 1:
ps.append(None)
continue
try:
# Create sign combination
k... | 04e4bb6d74503c99f93d954005e7ef45a45232c0 | 649,856 |
from typing import Optional
from typing import List
def drop_duplicates(df, columns: Optional[List[str]]):
"""
Remove duplicate rows
---
### Parameters
*mandatory :*
- `columns` (*list*): columns to consider to identify duplicates (set to null to use all the columns)
### Example
*... | 6f328a760b50454f7b5f578eead8decc8d561819 | 649,857 |
from bs4 import BeautifulSoup
def get_soup(page):
"""Beatiful Soup wrapper of HTTPResponse.data .
Args:
response (HTTPResponse): an HTTPResponse instance.
Returns:
BeatifulSoup instance of response.data with html.parser.
"""
return BeautifulSoup(page, "lxml") | f57f1d2377f0f02ee781ba4087e5760936296e75 | 649,859 |
def _entities_from_messages(messages):
"""Return all entities that occur in at least one of the messages."""
return list({e["entity"] for m in messages for e in m.data.get("entities", [])}) | d0858c09bea65a396ed33079385590167a8280f7 | 649,860 |
def remove_indent(s):
"""Remove indention of paragraph."""
s = "\n".join(i.lstrip() for i in s.splitlines())
return s | 4874aabeae73033813308b24e06f88575c0d53fd | 649,861 |
import torch
def save_model(save_dir, model, architecture, optimizer, train_dataset, device=None):
"""Save a checkpoint for the model."""
# Input size map for various architectures
input_sizes = {
'vgg13': 25088,
'vgg16': 25088,
'densenet': 1024,
#'inception': 2048,
... | 8024d5de30669118fb8f589bc3bdbdafb2a38424 | 649,862 |
import socket
def find_free_port() -> int:
"""
Find a free port
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
_host, port = s.getsockname()
return port | 6a63058c8db249489acb6652b9e46bad23f9f9ae | 649,863 |
def ngrams(sequence, n):
"""Create ngrams from sequence, e.g. ([1,2,3], 2) -> [(1,2), (2,3)]
Note that fewer sequence items than n results in an empty list being returned"""
# credit: http://stackoverflow.com/questions/2380394/simple-implementation-of-n-gram-tf-idf-and-cosine-similarity-in-python
seq... | 8c630e38da0cc511f2005df651e45dee3abae818 | 649,864 |
import six
def combine_logged_values(*logged_values_dicts):
"""Combine logged values dicts. Throws if there are any repeated keys."""
combined_dict = dict()
for logged_values in logged_values_dicts:
for k, v in six.iteritems(logged_values):
if k in combined_dict:
raise ValueError('Key "%s" is ... | 023d384886d9dcb22360badc900e74bbe33a0877 | 649,865 |
def fit(text, length, orientation="l", fillCharakter=" ", endCharakter=" ..."):
"""Return input text, but cut to a maximum length"""
text, length, fillCharakter = str(text), int(length), str(fillCharakter)
if len(text) <= length:
orientation = orientation.lower()[0]
if orientation == "c":
leftLen = (length - ... | 563d0fdcd25e084c19168262c732ba8b17144751 | 649,866 |
import re
def convert_abfss_path_to_https(abfss_path: str) -> str:
""" Convert the abfss path to https path style """
pattern = r'abfss:\/\/([^@]+)@([^.]+)[^\/]+\/(.+)'
regex = re.compile(pattern)
match = regex.search(abfss_path)
if not match:
raise ValueError(f"Invalid abfss path {abfss_p... | cdba1ee39bdfa10639b593666483e486566d7d3c | 649,868 |
def _section_has_changes(section_data) -> bool:
"""
Looks for a section containing something other than "No changes."
:param section_data: list of lines
:return: boolean
"""
non_empty_lines = [line.strip() for line in section_data[1:] if line.strip()]
if len(non_empty_lines) == 0:
r... | 9e460ca8ceea5048c627fcdc77a9e6af4655cfca | 649,869 |
import re
def parse_phone(phone):
"""Parses the given phone, or returns `None` if it's invalid."""
if isinstance(phone, int):
return str(phone)
else:
phone = re.sub(r'[+()\s-]', '', str(phone))
if phone.isdigit():
return phone | fbf0f2324a49bf16354c59efedcfa6b3f3f70998 | 649,870 |
def list_sequence(lst, seq):
"""Return sequences of seq in lst"""
sequences = []
count = 0
len_seq = len(seq)
upper_bound = len(lst)-len_seq+1
for i in range(upper_bound):
if lst[i:i+len_seq] == seq:
count += 1
sequences.append([i,i+len_seq])
return sequences | ef03e1a848497eff09db3327571cf6a63ea8ac36 | 649,871 |
def moffat(x, amplitude=1, center=0., sigma=1, beta=1.):
""" 1 dimensional moffat function:
moffat(amplitude, center, sigma, beta) = amplitude / (((x - center)/sigma)**2 + 1)**beta
"""
return amplitude / (((x - center)/sigma)**2 + 1)**beta | cc5db5f6fd675be4ab26ae7297cd6468fcdcc8b5 | 649,872 |
def round_filters(filters, mconfig, skip=False):
"""Round number of filters based on depth multiplier."""
multiplier = mconfig.width_coefficient
divisor = mconfig.depth_divisor
min_depth = mconfig.min_depth
if skip or not multiplier:
return filters
filters *= multiplier
min_depth = min_depth or divis... | 32105b3c1d9649940d1100cfd6ade3838f463981 | 649,873 |
def p_cond(p, k, p_1):
"""
:param p: The probability of returning a random value instead of the true one
:param k: The probability of returning 1 when generating a random value
:param p_1: The probability of a person to have an attribute value x_i=1
"""
return (1-p*k)*p_1/((1-p)*p_1+p*(1-k)) | bba4af00cc200e3bb807802b8370441e789378d0 | 649,876 |
def get_spectral_w(w_pars,energy):
"""
Return spectral weight of an event
Parameters
----------
w_pars: parameters obtained with get_spectral_w_pars() function
energy: energy of the event in GeV
Returns
-------
float w
"""
E0 = w_pars[0]
index = w_pars[1]
index_w =... | 9a9d9479a8f62ac007dddee1f1bf742ddce44bec | 649,878 |
def get_yrange(alt_bot, alt_top, df_height):
"""Define values for lower and upper boundary of plot.
Args:
alt_bot (int):
alt_top (int):
df_height (pandas Series):
Returns:
tuple of float: min height, max height
"""
if alt_bot is None:
ymin = int(df_height.v... | 46176d6ed339568739cd420e90181011e50d37ad | 649,879 |
import cmath
def spoles_to_zpoles(spoles, T):
""" Convert the continouous s-plane poles to the discrete z-plane poles
with the given sampling interval T.
Args:
spoles (list): The s-plane poles
T: The sampling interval in seconds.
"""
return [ cmath.exp(spole * T) for spole in... | a56a3c7e9dc2a8074d450b32feaf8c1c617c9d29 | 649,880 |
def load_a_list_of_ints():
"""
Loads a list of integers by first asking for its length.
"""
L = list()
n = int(input("The number of list elements: "))
for k in range(n):
L.append(int(input(str(k+1) + ". element: ")))
return L | 5b6d50c7e15f09f3e8682d3683376cd91bd6cb8c | 649,881 |
def get_org_parties(_client, user):
"""
Return a list of organisations that the user's organisation (law firm) has access to
"""
user_org_id = user.organisation.get("id")
org_parties = {}
user_org_cases = _client.get_user_cases(outer=True)
for case in user_org_cases:
representing = c... | 641ddd487336ac28a9ce75e32c944de27356efe0 | 649,883 |
import hashlib
def sha1_hash_lst(byte_lst):
"""
Compute the SHA-1 hash of a list with byte streams.
"""
sha = hashlib.sha1()
for l in byte_lst:
sha.update(l)
return sha.digest() | 3a77d6d58c805146804d1d5513f8619765775f4a | 649,884 |
import random
def similar_value(callable_gen, other_values, *args, **kwargs):
"""
Guarantees matching values for most of ones pass in other_values.
"""
result = []
for i in range(len(other_values)):
if random.random() < 0.8:
result.append(other_values[i])
else:
... | c194341cf078c3df224e4c7b9fac942659ab915c | 649,885 |
def bs3_cols(num_entries):
"""Return the appropriate bootstrap framework column width.
Args:
num_entries (int): The number of entries to determine column width for.
Returns:
int: The integer value for column width.
"""
if not isinstance(num_entries, int):
return 12
mapp... | dfc882f7177551d38b309a58bc8a26755e4ea034 | 649,886 |
def tufenkji_eta0(row):
"""
notes: the empirical constants are derived empirically for use with CFT.
references:
(1) Nathalie Tufenkji and Menachem Elimelech.
"Correlation Equation for Predicting Single-Collector
Efficiency in Physicochemical Filtration in Saturated
... | 8b7237aa51d47ae69badf299f7ede432a888d115 | 649,887 |
def get_boxes(boxes, labels, thresh):
"""Get all of the results above a threshold"""
v_boxes, v_labels, v_scores = list(), list(), list()
# enumerate all boxes
for box in boxes:
# enumerate all possible labels
for i in range(len(labels)):
# check if the threshold for this lab... | 28c5a79416b140abccc8332a07f572f9cbb3ec8c | 649,888 |
import re
def extract_money(text):
""" Extracts money amount from the text given """
if text is None: return None
fmt = "\$\s?(?:\d+,\d\d\d)?\d*(?:\.\d{1,2})?"
lst = re.findall(fmt, text)
amount = None
if lst:
try:
amount = float(lst[0].replace("$","").replace(",","").stri... | be09a03565f568ffe40f244f73cc536489eca1d7 | 649,889 |
def one_of_k_encoding_unk(x, allowable_set):
"""
Maps inputs not in the allowable set to the last element.
Unlike `one_of_k_encoding`, if `x` is not in `allowable_set`, this method
pretends that `x` is the last element of `allowable_set`.
Parameters
----------
x: object
Must be present i... | fbcad4bece352976d87952966eee5d16c0684160 | 649,891 |
import requests
def apost(url, **kwargs):
"""
Async version of post
"""
return requests.post(url, **kwargs) | e06c66b1d409b8e24070c2f0eea292538866f30a | 649,892 |
def all_children(model):
"""Return a list of all child modules of the model, and their children, and their children's children, ..."""
children = list(model.children())
for child in model.children():
children.extend(all_children(child))
return children | d6bbb247e27013349ab6428dc6b6fe215bbfb991 | 649,893 |
import time
def get_seconds():
""" Retrieve Epoch time in seconds. """
millis = int(round(time.time() * 1000))
return round(millis / 1000) | 9bba4f3666337b147310ce06a3752058d9baaee7 | 649,894 |
from pathlib import Path
import re
def make_unique_name(path: Path, copy: str = " copy") -> Path:
""" Generate unique name for file copied file. """
cur_dir = path.parent
cur_name = path.name
last_dot = cur_name.rfind(".")
ext = new_name = ""
if not path.is_dir() and re.search(r"\..{3}\.(gz|b... | cdc4f1456210d2bd22b530d12b7922e87848ab65 | 649,895 |
def check_korea(old, new):
"""대한민국 데이터가 변했는지 체크
데이터: 확진환자, 완치, 사망
Args:
old: _world.json의 S. Korea 데이터
new: scraper_korea.py의 main() 함수 반환값 (새로 수집한 데이터)
Returns:
새로 업데이트 해야하는 경우: True
새로 업데이트 하지 않아도 되는 경우: False
"""
if new is None or old == new:
return ... | c8e8e905562d0423dcec54c0ae0e50b6ade8fb4c | 649,896 |
def get_options_jsonschema(options, required):
"""
Returns multiple choice options for schema questions
"""
for item, option in enumerate(options):
if isinstance(option, dict) and option.get('text'):
options[item] = option.get('text')
value = {'enum': options}
if not require... | df754322b0381aa555f08b061fecc183e8e9b35c | 649,897 |
def problem_48_self_powers(series_limit, digits):
""" Problem 48: Find the last digits of series n^n (n = 1 to series limit).
Args:
series_limit (int): The maximum base and power in the series.
digits (int): The number of last digits to take from sum.
"""
result = 0
for number in ra... | a1b5cbb89724b264cef2867588391f7756eba128 | 649,898 |
def mapd(f, d):
"""Map function over dictionary values"""
return {k: f(v) for k, v in d.items()} | b7ff21ca57f83fbf8d331cbe3b50d9b2b6ef19be | 649,899 |
def all():
"""
Returns all the visual layers
:return: list(object, object, ...)
"""
return list() | 91846b1d8e630f481c9e65d431bc29a7c5848b65 | 649,900 |
def lt(y, x):
"""Returns true if the first argument is less than the second; false
otherwise"""
return x < y | c6cb678617c634d4af03a010e157edb1e6023cf9 | 649,901 |
def find_key(dic, val):
"""Return the keys of dictionary dic with the value val."""
return [k for k, v in dic.iteritems() if v == val] | 158060d8be64d8f547bc5c3762452861a5ba0bec | 649,902 |
def relu(x):
""" ReLU Activation Function
"""
return x.clamp_min(0.) | 5223f81fe0d5c4266f01a70640ab9d474b2dd207 | 649,903 |
def exponential_smoothing(constant, target="close"):
"""
| Calculates the exponential smoothing
| Name: exponential\_smoothing\_\ **constant**\ %\_of\_\ **target**
:param constant: Smoothing constant for the calculation. Use function days_to_constant_
:type constant: float
:param target: Data c... | 765b32d8128c9a74bd298a11b1937469d0ef08e5 | 649,904 |
import re
def translate_dict(cmd_list, label_map, dict_key='label'):
"""Create a translate dictionary of labels
Parameters
----------
cmd_list : list of dict
The Benchpress commands to translate
label_map : dict
Dictionary mapping old to new labels: {'old_label': 'new_label'}.... | 2bdb013fc476e6b77c0e61dd396c099a1c98e3bf | 649,905 |
import os
import shutil
import sys
import time
def create_folders(arguments):
"""
Creates the folder structure needed to save logs and checkpoints depending on the
@param arguments: run configuration
@return: log_path where to save logs and models_path where to save the checkpoints.
"""
if arg... | 7d749f19def5c293b8cce24d3ac3c9c704ef704f | 649,906 |
def choose_max_efficiency(efficiencies):
"""
Given a single or list of DOM efficiencies choose the highest
"""
if type(efficiencies) == list or type(efficiencies) == tuple:
return max(map(float,efficiencies))
else:
return float(efficiencies) | 736327b6d33d84125aa8df1f1b31a018d0ec8691 | 649,907 |
import re
import fnmatch
def FilterTestNames(all_tests, gtest_filter):
"""Filter a list of test names based on the given gtest filter.
See https://github.com/google/googletest/blob/main/docs/advanced.md
for gtest_filter specification.
Args:
all_tests: List of test names.
gtest_filter: Filter to appl... | 4d6af4f6abf3f2d04d457f27c3ef2701dfe47a01 | 649,908 |
import torch
def unique_corners(centers, feat):
"""
Given a [N, 3] list of points, return the list of unique corners.
"""
pts = centers
N = pts.shape[0]
_vs = torch.zeros(8, N, 3, device=pts.device).long()
_vs[0] = torch.stack([pts[...,0]+0, pts[...,1]+0, pts[...,2]+0], dim=-1)
_vs[1] ... | 7425b5dae2e82ece33895c3425cc2062005034d2 | 649,909 |
def seeds():
"""
A list with two 3d vectors.
"""
return [[0.0, 0.0, 1.0], [0.0, 2.0, 0.0]] | 16b1fae898545e685d27f6c0aa753cf9d37a3c31 | 649,910 |
def _predict_proba_estimator(clf, X):
"""Helper to get prediction method"""
# XXX this is not safe. Maybe add explicit 1st level scoring param.
# try predict_proba
predict_proba = getattr(clf, "predict_proba", None)
if callable(predict_proba):
return clf.predict_proba(X)
# or decision_... | 4d89d842a7ad5b1126110013b19dc06a25bbad07 | 649,911 |
def chartx(x, clen=70, c='#'):
"""generate a string of max length clen which is a bargraph of
floating point value 0. <= x <= 1 consisting of character c """
if x > 1.:
x = 1.
slen = int(x*clen)
cstr = [c for s in range(slen)]
return "".join(cstr) | 597ce3cf4b9486c66c92be99b728f4cc1786cbfc | 649,912 |
import argparse
def parse_arguments():
"""Parses command-line flags.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-l",
"--eval_list",
help="Text file containing names of videos to be evaluated on.",
type=argparse.FileType("r"),
required=True)
... | 97665278e8cd129205573220d06625b26dfd4ae5 | 649,913 |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns a value that refers to the "color distance" between a pixel and a mean RGB value.
Input:
pixel (Pixel): the pixel with RGB values to be compared
red (int): the average red value of the pixels to be compared
green (int): the av... | ab55a4f60134f848eabc658e5deef9b69c6c2183 | 649,914 |
def process_datafile(filename):
""" process_datafile -> (universities,enrollments,total_number_of_students)
universities: list of University
namesenrollments: corresponding list with enrollments
total_number_of_students: over all universities"""
universities=[]
enrollments=[]
with open(file... | ac80107cba1f60709cd221f2667219de92a50bfb | 649,916 |
def _to_j2kt_native_name(name):
"""Convert a label name used in j2cl to be used in j2kt native"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-native" % name | 2b3f95353486aea658ff8e001dff61d73913e32f | 649,917 |
def validating_property(func, allow_del=False):
"""Factory that makes properties that perform some user-specified
validation when setting values. The returned function must be used as a
descriptor to create a class variable before setting the instance
attribute.
Parameters
----------
func: ... | 5f1a6e3343a41176f78a8c9126ed9c3da3abbe63 | 649,918 |
def _lockedSql(db, func, *args):
"""
Ensure write lock on database, otherwise concurrent access can result in
"schema has changed" errors.
"""
if not db.inTransaction():
db.cursor().execute('BEGIN IMMEDIATE')
return func(*args) | 530043b26007ead588ff3a1255e908d1436757fa | 649,919 |
def eval_agent(env, agent, num_episodes):
"""Evaluates `agent` for `num_episodes`."""
rewards = 0.0
for _ in range(num_episodes):
time_step = env.reset()
episode_reward = 0
while not time_step.last():
agent_output = agent.step(time_step, is_evaluation=True)
time_step = env.step([agent_outp... | 97eddda4c5a675ef991b3610411183ef5516ea4a | 649,921 |
import requests
def requestHTML(url):
"""
サイトからHTMLソースを取得する。
Parameters
----------
url : str
サイトのURL。
Returns
-------
HTML_Source : str
HTMLソース。
"""
HTML_Source = requests.get(url).text
return HTML_Source | 916b030f7898a4b4e5a616ed674249ae8924cfee | 649,922 |
import sys
def is_macos_x():
""" True if OS is mac """
return sys.platform == 'darwin' | 4cc393c51a1ae0958144e4afb2c47456a0d7bd15 | 649,923 |
def _handle(request, handler, *rest): # pragma: no cover
"""invoke the next handler"""
return handler(request, *rest) | 4bb0506f7b42cd3441d4e3694ebd41ba8973a39d | 649,924 |
import requests
def get_json(uname, pword, ssl, location):
"""
Performs a GET using the passed URL location
"""
r = requests.get(location, auth=(uname, pword), verify=ssl)
return r.json() | 47bb782c1fe2073c2f74fde51fd48f5b6a649c73 | 649,925 |
def realign_dtype(dtype, offsets):
"""
Given a Numpy struct dtype object an a list of integer offsets, with one
offset per field in the dtype, returns a new dtype where each field has the
given offset.
All offsets must be non-negative integers, but otherwise have no
restrictions, and may overla... | 865589ae25d42582e10d57e17ae63120ec397348 | 649,927 |
def exact_find(gis, name, typ):
"""
The ArcGIS online search function picks up inexact matches. Double-check
whether we are getting the right item
"""
res = gis.content.search('title: {}'.format(name), typ)
for item in res:
if item.title == name:
return item | 442621b6b801c5f1e13d356489b9a8e4f5dedcf6 | 649,928 |
def transpose(matrix):
""" :returns the matrix transposed """
zipped_rows = zip(*matrix)
transpose_matrix = [list(row) for row in zipped_rows]
return transpose_matrix | 785048000206374c240ec324367bfbfbbec2f169 | 649,929 |
def get_optional_height_names(num=4):
"""
Get list of possible column names for optional extrapolation. (of form Ane_WS_Ht1, for example)
:param num: number of possible Additional Comparison Heights (int)
:return: list of allowed names
"""
optionalData = []
for typ in ['Ane', 'RSD']:
... | 51ff796c0471f8940720f77be28f43b4771db1b2 | 649,930 |
def towers_holding_water(heights):
""" You are given an array whose each element represents the height of the
tower. The width of every tower is 1. It starts raining. How much water
is collected between the towers?
Eg: [1,5,3,7,2] - then answer is 2 units between towers 5 and 7
Complexity: O(n)
... | c69ec26232db9fbba7ae6d309bcc26951785a312 | 649,931 |
def split_records(line_record):
"""split_records(line_record)-> list of strings(records)
standard separator list separator is space, records containting encapsulated by " """
split_result=[]
quote_pos=line_record.find('"')
while quote_pos!=-1:
if quote_pos>0:
split_res... | 5b59db597b2572210e166e056816b2aa2e823f6f | 649,932 |
def full_record(marc21_record, marc21_metadata):
"""Full record as is expected by the UI serializer."""
marc21_record
marc21_record["id"] = "9jkx5-hx115"
marc21_record["pid"] = {
"pk": 58,
"status": "R",
"obj_type": "rec",
"pid_type": "marcid",
}
marc21_record["f... | 0ae2d50e8d2bee97d34f353ca1914d291ca6a585 | 649,933 |
def train_by_shape(X, X_dep_feat, y, my_embedding):
"""
Separates the features and labels by its shape
:param X: Word-features
:param y: Labels
:return: 3 dictionaries of sublists of the parameters separated by there size
"""
x_shapes = {}
y_shapes = {}
x_dep_shapes = {}
my_embed... | 95f4ad594b2a45b14dedaae86c39b4e2a7f59c7b | 649,934 |
def iter_in(value, seq, cmp):
"""
A function behaving like the "in" Python operator, but which works with a
a comparator function. This function checks whether the given value is
contained in the given iterable.
Args:
value: A value
seq: An iterable
cmp: A 2-arg comparator ... | 68b4231b009c7b07e0f7d56e4068e5e3d4a7a3f1 | 649,937 |
def label_blockstructures(blockstructures):
"""Conversion between long-hand and short-hand
for MTL block structures.
"""
conversion = {
'trueshare' : 'I',
'mhushare' : 'Y',
'split' : 'V',
'attenshare' : 'W',
}
labels = []
for blockstructure in blockstructures... | f23d7d89c46e9ea140725a421039ca01fd8e9e47 | 649,938 |
def urljoin_bytes(*atoms):
"""Return the given path `*atoms`, joined into a single URL.
This will correctly join a SCRIPT_NAME and PATH_INFO into the
original URL, even if either atom is blank.
"""
url = b'/'.join([x for x in atoms if x])
while b'//' in url:
url = url.replace(b'//', b'/... | 6aac4294f530bb3ff7cabc9d12ecbe1234918a3f | 649,939 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.