content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def is_prime(N: int)->bool:
""" 素数判断函数,True 是, False 否。
Input: any integer which is greater than 1.
Output: bool True represent integer is prime number.
不需要用math.sqrt()函数,也不用乘方(**0.5),改用 i*i < N.
首先排除素数 2 和大于 2 的偶数
don't use math.sqrt,at first skip all even number except 2
>>> is_prime(2)
True
>>> is_prime(20)
False
>>> is_prime(-7)
True
"""
number = N if N > 0 else -N
# 以下快速筛查2,3,5,7的倍数
if number%2 == 0:
return (number==2) # 唯一的偶数2,-2是素数
if number%3 == 0:
return (number==3) # 第一条语句已经清除了偶素数2,现在只要清除2以外的偶数
if number%5 == 0:
return (number==5)
if number%7 == 0:
return (number==7)
# upper = int(number ** 0.5)+1 # only one operation sqrt()
i = 11 # 起始数是奇数3,间隔为偶数2,就是判断3以后的奇数是否为素数?奇数不可能有偶因子
while i*i <= number: # for i in range(11, upper, 2):
if not (number % i): # replace number % i == 0:
return False # 只要找到一个因数,就不是素数
i += 2
return True
|
23ed441f5f18caa7705ddf88053cb50be9b4de0a
| 234,704 |
def in_bisect(s,target):
"""Returns true if target is in sorted list.
s: sorted list
target: item to search for
"""
# Base case, down to one element.
if len(s)==1:
if s[0] == target:
return True
return False
if s[0] <= target <= s[-1]:
mid_index = int(len(s)/2)
mid = s[mid_index]
if target < mid:
return in_bisect(s[:mid_index], target)
else:
return in_bisect(s[mid_index:], target)
return False
|
2ca888536ea5b63c972b9caf04523c45ebff6aa9
| 477,182 |
import requests
def _get_token(ZC, username, password):
"""Gets the client's token using a username and password."""
url = '{}/oauth/token/'.format(ZC.HOME)
data = {'username': username, 'password': password, 'noexpire': True}
r = requests.post(url, json=data)
if r.status_code != 200:
raise Exception(f'Couldn\'t set token, bad response ({r.status_code})'
'\nWas your username/password correct?')
j = r.json()
return j['token']
|
192c113d6e904f6d7756e28e7a80147b9d20cb54
| 662,891 |
import csv
def read_snp(handle):
""" Reads a mummer snp file """
dialect = csv.Sniffer().sniff(handle.read(1024))
handle.seek(0)
reader = csv.DictReader(
handle,
fieldnames=[
"pos_ref",
"allele_ref",
"allele_query",
"pos_query",
"buff", # Distance from this SNP to the nearest mismatch
"dist", # Distance from this SNP to the nearest sequence end.
"len_ref",
"len_query",
"strand_ref",
"strand_query",
"id_ref",
"id_query",
],
dialect=dialect,
)
return reader
|
46cb06d8aedca29af5779d7628c5e9ad4c4f0f4b
| 198,474 |
def _CredentialFrom(messages, credential_data):
"""Translate a dict of credential data into a message object.
Args:
messages: The API message to use.
credential_data: A dict containing credential data.
Returns:
An Credential message object derived from credential_data.
"""
basic_auth = messages.BasicAuth(
password=credential_data['basicAuth']['password'],
user=credential_data['basicAuth']['user'])
return messages.Credential(basicAuth=basic_auth)
|
c96acdf28dab1ba60acc0c5b1bee73585c20106f
| 44,843 |
def rsync(s, d, test=False, config='dts', reverse=False):
"""Set up rsync command.
Parameters
----------
s : :class:`str`
Source directory.
d : :class:`str`
Destination directory.
test : :class:`bool`, optional
If ``True``, add ``--dry-run`` to the command.
config : :class:`str`, optional
Pass this configuration to the ssh command.
reverse : :class:`bool`
If ``True``, attach `config` to `d` instead of `s`.
Returns
-------
:class:`list`
A list suitable for passing to :class:`subprocess.Popen`.
"""
c = ['/bin/rsync', '--verbose', '--recursive',
'--copy-dirlinks', '--times', '--omit-dir-times']
if reverse:
c += [s + '/', config + ':' + d + '/']
else:
c += [config + ':' + s + '/', d + '/']
if test:
c.insert(1, '--dry-run')
return c
|
74d02e5ae5abbc6acfe3b3622f64942865e86c0b
| 116,858 |
import torch
def random_choice(x, n, dim=0):
"""Emulate numpy.random.choice."""
assert dim == 0, 'Currently support only dim 0.'
inds = torch.randint(0, x.size(dim), (n,), device=x.device)
return x[inds]
|
91c6601b6e4c6f4c4e19c0b44eadb5c8aad967ef
| 443,309 |
def create_adj_elem(root):
""" Small helper function to add left/right nodes to adj list """
out = []
if root.left is not None:
out.append('node' + str(root.left.nid))
if root.right is not None:
out.append('node' + str(root.right.nid))
return out
|
31eca3e2b75c8e45d088993aaf30d4d14a4df8d4
| 443,190 |
def get_class_split(num_classes, num_gpus):
""" split the num of classes by num of gpus
"""
class_split = []
for i in range(num_gpus):
_class_num = num_classes // num_gpus
if i < (num_classes % num_gpus):
_class_num += 1
class_split.append(_class_num)
return class_split
|
73bb06dc8ec5a828cece3c36387b1649466529b8
| 303,449 |
import array
import math
def _fold_sizes(num_rows, num_folds):
"""Generates fold sizes to partition specified number of rows into number of folds.
:param num_rows: number of rows (instances)
:type num_rows: integer
:param num_folds: number of folds
:type num_folds: integer
:returns: an array.array of fold sizes (of length num_folds)
"""
sizes = array.array('i', [0] * num_folds)
for i in range(num_folds):
sizes[i] = int(math.floor(float(num_rows - sum(sizes)) / (num_folds - i)))
return sizes
|
f621bd5564b7e6c0614af6f4dd6757a026b4e313
| 599,798 |
import torch
import math
def _get_survey_extents_one_side(pad, side, source_locations,
receiver_locations, shape, dx):
"""Get the survey extent for the left or right side of one dimension.
Args:
pad: Positive float specifying padding for the side
side: 'left' or 'right'
source/receiver_locations: Tensor with coordinates for the current
dimension
shape: Int specifying length of full model in current dimension
dx: Float specifying cell spacing in current dimension
Returns:
Min/max index as int or None
"""
if pad is None:
return None
if side == 'left':
pad = -pad
op = torch.min
nearest = math.floor
else:
pad = +pad
op = torch.max
nearest = math.ceil
extreme_source = op(source_locations + pad)
extreme_receiver = op(receiver_locations + pad)
extreme_cell = nearest(op(extreme_source, extreme_receiver).item() / dx)
if side == 'right':
extreme_cell += 1
if (extreme_cell <= 0) or (extreme_cell >= shape):
extreme_cell = None
return extreme_cell
|
761fe0e282fd30c1bbd8cbbc9a9d5249b7a8c04f
| 128,236 |
def luma(p):
"""
Returns brightness of a pixel, based on relative luminance
This is based on ITU-R BT.709. Note that human eyes are most sensitive to green light.
:param p: A tuple of (R,G,B) values
:return: The relative luminance of a pixel (in the range [0, 255]).
"""
return 0.2126*p[0] + 0.7152*p[1] + 0.0722*p[2]
|
9996673dfd9dad54e38236627b2639bc2047aed8
| 509,399 |
def xywh_to_xyxy(a):
""" Converts a single box from XYWH to XYXY format
a: box in XYWH coordinates
"""
return [a[0], a[1], a[0]+a[2]-1, a[1]+a[3]-1]
|
66acb23bad07d0ca658091bc8be67a572c0ab192
| 476,335 |
from datetime import datetime
def timestamp_to_weekday(timestamp):
"""
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
"""
return int(datetime.fromtimestamp(timestamp / 1000.0).strftime("%w"))
|
fad8b84ee638adc80774993888ee4152ee76fc18
| 669,517 |
def boundary_overflow(posX, posY):
"""
Correct coordinates for boudary overflow
Treating the 8x8 boundaries as if they don't exist.
(8,8) is the same as (0,0), (-1,-1) same as (7,7)
"""
x_field = posX
y_field = posY
if x_field > 7:
x_field = 0
if x_field < 0:
x_field = 7
if y_field > 7:
y_field = 0
if y_field < 0:
y_field = 7
return [x_field, y_field]
|
decc28d060eb302bc9a12b91e5f1d3cbaf7dde4c
| 274,005 |
def smallest_prime_factor(n):
"""Return the smallest k > 1 that evenly divides n."""
k = 2
while n % k != 0:
k = k + 1
return k
|
1b19c3aeae1a814a1836023bb646c3a72acfa87e
| 524,869 |
def get_max_sense(instance_dict, instances=None):
"""
Return a list of senses with maximum graded sense score.
>>> d = {1: [('s1', 9), ('s2', 8.9), ('s6', 12)], 2: [('s2', 1), ('s3', 7)]}
>>> get_max_sense(d)
['s6', 's3']
>>> get_max_sense(d, [1])
['s6']
"""
if instances is not None:
senses = []
for i in instances:
senses.append(max(instance_dict[i], key=lambda x: x[1])[0])
else:
senses = [max(e, key=lambda x: x[1])[0] for e in instance_dict.values()]
return senses
|
b2357f81049d0ce10dbc8cad949d859e8ff2f188
| 300,640 |
def preprocessLines(sourceLines):
"""
Delete comments from the lines and change them to upper case
sourceLines - array of assembly lines with comments
return: resulting array of lines
"""
for i, line in enumerate(sourceLines):
line = line.upper()
line = line.split(";")[0] # trim comments
sourceLines[i] = line
return sourceLines
|
6909d36cb62359c429b7637f50b31722d534d875
| 483,019 |
from typing import List
def assert_empty_line_between_description_and_param_list(
docstring: List[str]
) -> List[str]:
"""
make sure empty line between description and list of params
find first param in docstring and check if there is description above it
if so, make sure that there is empty line between description and param list
:param docstring: list of lines in docstring
:return: list of lines in docstring
"""
prefixes = [":param", ":return", ":raises"]
start_of_param_list = -1
for i in range(len(docstring)):
line = docstring[i].strip()
# check if it starts with prefix
for prefix in prefixes:
if line.startswith(prefix) and i > 1:
start_of_param_list = i
break
if start_of_param_list != -1:
break
if start_of_param_list == -1:
return docstring
# remove all empty lines before param list and enter a single empty line before param list
while docstring[start_of_param_list - 1].strip() == "":
docstring.pop(start_of_param_list - 1)
start_of_param_list -= 1
docstring.insert(start_of_param_list, "")
return docstring
|
d03eb05064609928020c84785b561cd6b7bfa1f6
| 685,412 |
import hashlib
def hash(value):
"""Generate a hash from a given value
:param value:
:rtype: str
"""
hash_ = hashlib.md5()
hash_.update(repr(value).encode('utf8'))
return hash_.hexdigest()
|
8c7bc042cedccafa3a2c3d39e34a32d4c2fff3a4
| 516,861 |
def edge_overlap(A, B):
"""
Compute edge overlap between two graphs (amount of shared edges).
Args:
A (sp.csr.csr_matrix): First input adjacency matrix.
B (sp.csr.csr_matrix): Second input adjacency matrix.
Returns:
Edge overlap.
"""
return A.multiply(B).sum() / 2
|
f2d87e1a7b7a0f90bc240c57c6505ab37c6f55f4
| 392,812 |
def FormatUserScoreSum(element):
"""Format a KV of user and their score to a BigQuery TableRow."""
user, total_score = element
return {'user': user, 'total_score': total_score}
|
9a7e6bd8945bf2b14d1b7ae7429e96c0de974cf0
| 197,377 |
def symmetric_tour_list(n_cities, start_index = 0):
"""
Returns a numpy array representiung a symmetric tour of cities
length = n_cities + 1
First and last cities are index 'start_index' e.g. for
start_index = 0 then for 5 cities tour =
[0, 1, 2, 3, 4, 0]
"""
tour = [x for x in range(n_cities)]
tour.remove(start_index)
tour.insert(0, start_index)
tour.append(start_index)
return tour
|
cbd56e827dba952e18a1e5b1b5996777c932e7c0
| 587,590 |
import torch
def conv1x1(in_planes, out_planes, init='no', cnv_args={
'bias': True,
'kernel_size': 1,
}, std=0.01):
"""1x1 convolution"""
cnv = torch.nn.Conv2d(in_planes, out_planes, **cnv_args)
# init weights ...
if init == 'no':
pass
elif init == 'normal0.01':
cnv.weight.data.normal_(0., std)
if cnv.bias is not None:
cnv.bias.data.fill_(0.)
else:
assert False
return cnv
|
15d54e38b1574cfed3659642a3d86e635c124e20
| 113,689 |
def concat_environment(env1, env2):
""" Concatenate two environments.
1 - Check duplicated keys and concatenate their values.
2 - Update the concatenated environment.
Parameters
----------
env1: dict (mandatory)
First environment.
env2: dict (mandatory)
Second environment.
Returns
-------
concat_env: dict
Updated environment where the duplicated keys values are concatenated
with ':'.
"""
concat_env = env1
for key, value in env2.items():
if key in concat_env.keys():
if value != concat_env[key]:
concat_env[key] += ":" + env2[key]
else:
concat_env[key] = env2[key]
return concat_env
|
25f7aee5a9316ab0604f2e38538a1f67a5333b08
| 15,072 |
import glob
def get_possible_sites(user):
"""Returns a set of sites available for the specified user. Each site
is represented by an image in the 'images' directory. """
files=()
if user.lower().endswith("ur"):
#ASSERT: the username indicates unrelated condition
files=(file.replace('images/', '') for file in glob.glob('images/ur_*'))
elif user.lower().endswith("r"):
#ASSERT: the username indicates related condition
files=(file.replace('images/', '') for file in glob.glob('images/r_*'))
return set(files)
|
8f8bddaaaefcf1d414ea11002828c94040b93868
| 275,119 |
def find_all(text, pat):
"""Returns list of all overlapping occurrences of a pattern in a text.
Each item in the (sorted) list is the index of one of the matches.
"""
result = []
last = 0
try:
while 1:
curr = text.index(pat, last)
result.append(curr)
last = curr + 1
except ValueError: #raised when no more matches
return result
|
cfdb8f0f53a0d016a433c2a9d180595883ad0ca8
| 383,759 |
def pmelt_T_iceV(T):
"""
EQ 3 / Melting pressure of ice V
"""
T_star = 256.164
p_star = 350.1
theta = T / T_star
pi_melt = 1 - 1.18721 * (1.0 - theta ** 8)
return pi_melt * p_star
|
9d4f830c498b58e1d244c8ca32c20cfff6f827df
| 242,198 |
import math
def angle_rad(coord, origin=(0.0, 0.0)):
""" Absolute angle (radians) of coordinate with respect to origin"""
return math.atan2(coord[1] - origin[1], coord[0] - origin[0])
|
34b35f945c4c226c4f64aa4584286116c206b872
| 92,521 |
from typing import List
from typing import Tuple
def nondegenerate_tests_two_variables() -> List[Tuple[float, float, float, float, float]]:
"""Each entry in the list represents two Gaussian variables X1, X2 in the following format:
(mean1, mean2, sigma1, sigma2, correlation between X1 and X2)
"""
return [
(1.0, 2.0, 0.5, 0.7, 0.4),
(1.0, 3.0, 0.5, 1.0, 0.1),
(0.0, 1.0, 10.0, 2.0, 0.3),
(0.8, 1.0, 0.1, 0.2, 0.7),
]
|
913ee09bbf9dc08505d38308b8dfb2f8c96899b5
| 397,815 |
import math
def some_function(n: float) -> float:
"""
An approximation of the gamma function.
>>> round(some_function(4), 3)
24.0
"""
s = sum(
(
1,
1/((2**1)*(6*n)**1),
1/((2**3)*(6*n)**2),
-139/((2**3)*(2*3*5)*(6*n)**3),
-571/((2**6)*(2*3*5)*(6*n)**4),
)
)
return math.sqrt(2*math.pi*n)*(n/math.e)**n*s
|
a260c9570627143a52195b1fe912cd980c83c454
| 547,656 |
def filter_for(mapper, filter_fn):
"""Filter records out during the mapping phase.
Examples:
>>> @dataclass
... class Foo:
... id: int
>>> items = [Foo(id=1), Foo(id=2), Foo(id=3)]
Normally the mapper would be the thing that turns raw json into the above `items`
>>> noop = lambda x: x
>>> mapper = filter_for(noop, lambda r: r.id <= 2)
>>> mapper(items)
[Foo(id=1), Foo(id=2)]
"""
def decorator(response):
return list(filter(filter_fn, mapper(response)))
return decorator
|
fe5e828f788952ce3db32dfb6b4c015243429749
| 187,288 |
def getCurrencyPair(baseCurrency, cryptoCurrency):
"""Returns the currency pair in the format expected in Coinbase Pro"""
return cryptoCurrency + "-" + baseCurrency
|
3a0f8e206f6b3a153a89ff4a6d8aaf9c0116930c
| 203,378 |
def iterate_array(client, url, http_method='GET', limit=100, offset=0, params=None):
"""
Get a list of objects from the Podio API and provide a generator to iterate
over these items. Use this for
e.g. to read all the items of one app use:
url = 'https://api.podio.com/comment/item/{}/'.format(item_id)
for item in iterate_array(client, url, 'GET'):
print(item)
"""
all_elements = []
if params is None:
params = dict(limit=limit, offset=offset)
else:
params['limit'] = limit
params['offset'] = offset
do_requests = True
while do_requests == True:
if http_method == 'POST':
api_resp = client.post(url, data=params)
elif http_method == 'GET':
api_resp = client.get(url, params=params)
else:
raise Exception("Method not supported.")
if api_resp.status_code != 200:
raise Exception('Podio API response was bad: {}'.format(api_resp.content))
resp = api_resp.json()
num_entries = len(resp)
if num_entries < limit or num_entries <= 0:
do_requests = False
params['offset'] += limit
all_elements.extend(resp)
# print(f"array of {len(all_elements)}")
return all_elements
|
745e3209e5add0b0a8a64aea1878ac5b2897afb9
| 47,311 |
def is_file_included(filename, model):
"""
Determines if a file is included by a model. Also checks
for indirect inclusions (files included by included files).
Args:
filename: the file to be checked (filename is normalized)
model: the owning model
Returns:
True if the file is included, else False
(Note: if no _tx_model_repository is present,
the function always returns False)
"""
if (hasattr(model, "_tx_model_repository")):
all_entries = model._tx_model_repository.all_models
return all_entries.has_model(filename)
else:
return False
|
f50d83a7288494408df8b540c79f2b52053ee87a
| 582,253 |
def has_equal_properties(obj, property_dict):
"""
Returns True if the given object has the properties indicated by the keys of the given dict, and the values
of those properties match the values of the dict
"""
for field, value in property_dict.items():
try:
if getattr(obj, field) != value:
return False
except AttributeError:
return False
return True
|
d96b17124121af5db31c9db096b5010aff01b233
| 8,972 |
def mass_surface_balsa_monokote_cf(
chord,
span,
mean_t_over_c=0.08
):
"""
Estimates the mass of a lifting surface constructed with balsa-monokote-carbon-fiber construction techniques.
Warning: Not well validated; spar sizing is a guessed scaling and not based on structural analysis.
:param chord: wing mean chord [m]
:param span: wing span [m]
:param mean_t_over_c: wing thickness-to-chord ratio [unitless]
:return: estimated surface mass [kg]
"""
mean_t = chord * mean_t_over_c
### Balsa wood + Monokote + a 1" dia CF tube spar.
monokote_mass = 0.061 * chord * span * 2 # 0.2 oz/sqft
rib_density = 200 # mass density, in kg/m^3
rib_spacing = 0.1 # one rib every x meters
rib_width = 0.003 # width of an individual rib
ribs_mass = (
(mean_t * chord * rib_width) * # volume of a rib
rib_density * # density of a rib
(span / rib_spacing) # number of ribs
)
spar_mass_1_inch = 0.2113 * span * 1.5 # assuming 1.5x 1" CF tube spar
spar_mass = spar_mass_1_inch * (
mean_t / 0.0254) ** 2 # Rough GUESS for scaling, FIX THIS before using seriously!
return (monokote_mass + ribs_mass + spar_mass) * 1.2
|
fa0d9a3cda6fa01e973fa01e0a02f7e4a69b991b
| 593,735 |
def flatten(x):
"""Converts a list of lists into a flat list
Args:
x (list): An input list
Returns:
list: A flat list
"""
output = [_ for z in x for _ in z]
return output
|
4069dd52f755a0ffdb4cb7a3a6f20367ee2bc723
| 195,757 |
import re
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
fcb43a8f5eaf3e8b999472d65f5f7d2066885af6
| 377,268 |
def last_added_num(path):
"""
Returns last added frame number for a `path` directory.
`path` is a pathlib.Path object.
Return 0 if no files in directory.
"""
files = list(path.iterdir())
if not files:
return 0
# Get all frame numbers.
numbers = [int(str(file.name).split('.')[0]) for file in files]
return max(numbers)
|
ba92d0b625772693fc92670c3d4cb42546aa8903
| 338,630 |
import json
def getdata_from_file(file_path):
"""Retrieve json data from a file by filepath"""
with open(file_path, 'r') as file:
data = json.load(file)
return data
|
bc9f6b8d53879c42ac501ab9d4ec7ff10344538b
| 460,879 |
def get_protected_attr_values(attr, df, privileged_group, privileged=True):
"""Retrieves all values given the privileged_group argument.
If privileged is True and privileged_group[attr] is a list then it returns
the list, if it's a function then values of df[attr] for which the function
returns True.
If privileged is False and privileged_group[attr] is a list then it returns
values of df[attr] not in the list else if it's a function returns values
of df[attr] for which the function returns False.
Parameters
----------
attr: str
Protected attribute which is a key of the privileged_group
dictionnary
df: pd.DataFrame
Dataframe to extract privilieged group from.
privileged_group: dict
Dictionnary with protected attribute as key (e.g. age or gender)
and a list of favorable value (like ['Male']) or a function
returning a boolean corresponding to a privileged group
privileged: bool (default True)
Boolean prescribing whether to
condition this metric on the `privileged_groups`, if `True`, or
the `unprivileged_groups`, if `False`.
Returns
-------
list:
List of privileged values of the protected attribyte attr
if privileged is True else unprivileged values
Raises
------
ValueError:
attr must be in privileged_group
"""
if attr not in privileged_group:
raise ValueError('attr must be in privileged_group')
val = privileged_group[attr]
if type(val) == list:
if privileged:
return val
def fn(x): return x in val
else:
fn = val
cond = df[attr].apply(fn) == privileged
return df[cond][attr].unique().astype(str).tolist()
|
5bff379b4564917f6786abeede86e32b10a0f5a1
| 239,105 |
def AttachUserList(client, ad_group_id, user_list_id):
"""Links the provided ad group and user list.
Args:
client: an AdWordsClient instance.
ad_group_id: an int ad group ID.
user_list_id: an int user list ID.
Returns:
The ad group criterion that was successfully created.
"""
ad_group_criterion_service = client.GetService(
'AdGroupCriterionService', 'v201809')
user_list = {
'xsi_type': 'CriterionUserList',
'userListId': user_list_id
}
ad_group_criterion = {
'xsi_type': 'BiddableAdGroupCriterion',
'criterion': user_list,
'adGroupId': ad_group_id
}
operations = [{
'operator': 'ADD',
'operand': ad_group_criterion
}]
return ad_group_criterion_service.mutate(operations)['value'][0]
|
84b49c98158f56b3d05220ff1f1049f40fdcf6a8
| 244,756 |
def _convert_int_to_i64(val):
"""Convert integer to signed int64 (i64)"""
if val > 0x7FFFFFFFFFFFFFFF:
val -= 0x10000000000000000
return val
|
51df23605ce76e4ebe1b18cb94e53b94f6c0e6a3
| 451,958 |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall
|
8f3513e11f8adad111eee32740c271aad31fbe28
| 706,992 |
def __get_skip_select_quit(prompt):
"""Repeatedly prompts the user until they return a valid selection from skip/select/quit."""
while True:
response = input(prompt + " [enter to skip, 's' to select, 'q' to quit]")
if response == "":
return "skip"
if response == "s":
return "select"
if response == "q":
return "quit"
|
d88ce8e88d17aa1d531f5b850798137037c7fac6
| 605,969 |
from pathlib import Path
import filecmp
def are_dirs_equal(dir1: Path, dir2: Path) -> bool:
"""Compare the content of two directories, recursively."""
comparison = filecmp.dircmp(str(dir1), str(dir2))
return comparison.diff_files == []
|
69895f6f0ba4111a0daa5656cc7aed2199f63e98
| 519,980 |
import math
def distance(pos1, pos2):
"""
Euclidean distance
"""
return math.sqrt((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2)
|
04af24bfb1a5e6501f615ed2eb9d72efac531626
| 291,650 |
def wordCount(cleantext):
"""
This function counts words from a text and returns a dictionary.
Does not fix for punctuation and special characters, so for example 'why' and 'why?' will be counted as two different words. This doesn't matter in the case of youtube subtitles.
INPUT: string
OUTPUT: dictionary where keys are words, and the values are counts.
"""
words = cleantext.split()
#Counting words and saving count in dictionary
count = {}
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
return count
|
aefade151775bff1a392c96f4690165caf96098f
| 491,210 |
import torch
def get_random_seed() -> int:
"""Get a randomly created seed to use for seeding rng objects."""
seed = int(torch.empty((), dtype=torch.int64).random_(to=2**32).item())
return seed
|
4945f41f9504b3df4e67e8d9700e7b1180175a4c
| 475,646 |
def H_simple(t, T, **params):
"""
Implements Eq. 9.123 from Nawalka, Beliaeva, Soto (pg. 460)
"""
if params['risk_free']:
delta = params['delta']
else:
delta = params['delta'] + params['spread']
return delta * (T - t)
|
54eae4741dc973af9d083b3c99894d91bb085d7f
| 397,789 |
def get_vgroups(variables):
""" Returns a list of unique vgroup found in the given variables
object.
Parameters
----------
variables : list
Decipher variables object, which is a list of dictionaries
Returns
-------
vgroups : list
List of unique vgroups found in variables
"""
vgroups = []
for var in variables:
if not var['vgroup'] in vgroups:
vgroups.append(var['vgroup'])
return vgroups
|
118fd6da0c62ad80caf39f157bac786bb27e6110
| 481,611 |
def to_str(membership):
"""Convert membership array to pretty string.
Example:
>>> from graphy import partitions
>>> print(partitions.to_str([0,0,0,1,1,1]))
[0 0 0 1 1 1]
Parameters
----------
membership : np.array or list
Membership array to convert
Returns
-------
str
Pretty string
"""
return "[" + " ".join(map(str, membership)) + "]"
|
2500fbf4a953aff812cb9b4b639e5d3129af2229
| 271,651 |
def get_private_indicator(data):
"""Gets the private section indicator from the given section data
Parses the given array of section data bytes and returns the private section indicator. If True, then this
is a private table. If False then it is a normal mpeg ts table (PAT, PMT, CAT).
"""
if data[1] & int('01000000', 2): return True
return False
|
e804b96647b73e551e4cae842b1774d792a42ed3
| 133,556 |
def get_document_shortcut(connection, document_id, instance_id, error_msg=None):
"""Retrieve a published shortcut from the document definition.
Args:
connection: MicroStrategy REST API connection object
document_id (string): Document ID
instance_id (string): Instance ID
error_msg (string, optional): Custom Error Message for Error Handling
Returns:
Complete HTTP response object.
"""
endpoint_url = f'/api/documents/{document_id}/instances/{instance_id}/shortcut'
return connection.get(connection.base_url + endpoint_url)
|
36e26344248782d4e346e8cb32add35a63771f80
| 221,206 |
def getCombineSet(listDict, names):
"""
Calculate the union of a dict of lists.
Parameters
----------
listDict : dict of list of any
The dict of lists to be combined.
names : list of str
The keys of lists to be combined.
Returns
-------
list of any
The union of lists in listDict whose key is in names.
"""
res = []
for name in names:
assert (name in listDict), 'Error: name asked {} does not exist in listDict with keys {}.'.format(name, list(listDict.keys()))
res = res + listDict[name]
return set(res)
|
40cd68648b7d00614eeff4f3858b784c3a675c62
| 257,975 |
import re
def meant_to_say(client, channel, nick, message, matches):
"""
A plugin so users can correct what they have said. For example::
<sduncan> this is a foo message
<sduncan> s/foo/bar
<helga> sduncan meant to say: this is a bar message
"""
try:
last = client.last_message[channel][nick]
except KeyError:
return None
old, new, reflags = matches[0]
count = 1
if re.search('g', reflags, re.I):
count = 0
if re.search('i', reflags, re.I):
regex = re.compile(old, re.I)
else:
regex = re.compile(old)
modified = regex.sub(new, last, count)
# Don't respond if we don't replace anything ... it's annoying
if modified != last:
return u'{0} meant to say: {1}'.format(nick, modified)
|
f59ff2555588dbb8b45393b9a6384a6c3351dff7
| 52,950 |
def load_class(class_path):
"""
Load and return the class from the given module.
Args:
class_path (str): full path to class to be loaded, e. g.
sklearn.linear_model.LinearRegression
Returns:
class
"""
module_path, class_name = class_path.rsplit('.', 1)
mod = __import__(module_path, globals(), locals(), [class_name], 0)
return getattr(mod, class_name)
|
90cebbef4e305fde84adea8e7c2b42a1eac7d402
| 182,839 |
def replace_cpi_escapes(cpi: str) -> str:
"""Replace escaped characters in CPI URIs
Args:
cpi (str): CPI pure identity URI
Returns:
str: CPI escaped URI
"""
return cpi.replace("%23", "#").replace("%2F", "/")
|
454c7b6c1421ee55b35a36573e922578788cf6c7
| 417,436 |
def _nindent(msg, n, char=' '):
"""Add custom indentation to a line"""
tab = ''
for i in range(n):
tab += char
return tab+msg
|
c78686a652bc2dfb5645c661e9f314322901e452
| 478,269 |
def normalize_weights(weights):
"""Normalises a list of numerical values (weights) into probabilities.
Every weight in the list is assigned a probability proportional to its
value divided by the sum of all values.
Args:
weights (list): A list of numerical values
Returns:
list: A list containing values which sum to 1.
"""
total = sum(weights)
return [weight / total for weight in weights]
|
9ba33102b89d168463042756fee1c14066855583
| 205,474 |
def button_control_name(v, idx=None):
"""Return the name of a setting's button
v - the setting
idx - if present, the index of one of several buttons for the setting
"""
if idx is None:
return "%s_button" % (str(v.key()))
else:
return "%s_button_%d" % (str(v.key()), idx)
|
3d98aca881d6ba14bc8e6b934b5abfe2d3b1c846
| 515,977 |
import uuid
def is_uuid_valid(value: str) -> bool:
"""Validate if is uuid.
Args:
value (str): uuid.
Returns:
bool: true if is valid else false.
"""
try:
uuid.UUID(value)
return True
except ValueError:
return False
|
c597c297f8f8e45ddee95e767e8d27e263f1d988
| 378,251 |
def evidence_type_number_to_name(num: int) -> str:
"""
Transforms evidence type number to it's corresponding name
:param num: The evidence type number
:return: The string name of the evidence type
"""
name: str = str()
supported_types = ['Network', 'Process', 'File', 'Registry', 'Security', 'Image', 'DNS']
try:
name = supported_types[num - 1]
except IndexError:
name = 'Unknown'
finally:
return name
|
1f6a8e57334e08e997a3f86e629df04cb9602594
| 699,699 |
def to_flag(arg_str: str) -> str:
"""
Utility method to convert from the name of an argparse Namespace attribute / variable
(which often is adopted elsewhere in this code, as well) to the corresponding flag
:param arg_str: Name of the arg
:return: The name of the flag (sans "--")
"""
return arg_str.replace("_", "-")
|
0ced03481b70b82ca7fdadd9474f72cb443bda1f
| 221,611 |
def set_configuration_atoms_from_ase(config, ase_atoms):
"""
Set the atom positions of a configuration given a set of ASE atoms
:param config: (gt.Configuration)
:param ase_atoms: (ase.Atoms)
"""
for i, coord in enumerate(ase_atoms.get_positions()):
config.atoms[i].coord = coord
return None
|
3175682efd3ad629044f54c06ac4f8924b912e05
| 505,641 |
def get_column_letter(column_index):
"""
Returns the spreadsheet column letter that corresponds to a given index (e.g.: 0 -> 'A', 3 -> 'D')
Args:
column_index (int):
Returns:
str: The column index expressed as a letter
"""
if column_index > 25:
raise ValueError("Cannot generate a column letter past 'Z'")
uppercase_a_ord = ord("A")
return chr(column_index + uppercase_a_ord)
|
78a25887caa88ba2d2298f8eccc71b5fca2421a4
| 381,714 |
def from_lane_to_hex_string(lane, w):
"""Convert a lane value to a string of bytes written in hexadecimal"""
lane_hex_b_e = ((b"%%0%dX" % (w // 4)) % lane)
# Perform the conversion
temp = b''
length = len(lane_hex_b_e) // 2
for i in range(length):
offset = (length - i - 1) * 2
temp += lane_hex_b_e[offset:offset + 2]
return temp.upper()
|
1ac34c30fef88f9a49d91eeacd86b8d14caf6551
| 337,999 |
def clean_row_author_info(row_author_info):
"""Returns a string of author info stripped of parentheses or numericals"""
clean_row_author_info = ""
for i in range(len(row_author_info)):
undesirable_characters = "()-"
if row_author_info[i].isnumeric() or row_author_info[i] in undesirable_characters:
continue
clean_row_author_info += row_author_info[i]
return clean_row_author_info
|
1b3e930d016bd872ddc9099f6f0a9604d0c58d29
| 573,667 |
def should_skip_request(pin, request):
"""Helper to determine if the provided request should be traced"""
if not pin or not pin.enabled():
return True
api = pin.tracer.writer.api
return request.host == api.hostname and request.port == api.port
|
fe10521efda0bc6803e02a76d20e8e0f4038e20f
| 584,445 |
def infer_action(player_before, player_after):
"""Reconstruct that action that leads to the next state."""
if not player_before.active:
return "inactive"
if player_after.speed > player_before.speed:
return "speed_up"
if player_after.speed < player_before.speed:
return "slow_down"
if player_after.direction == player_before.direction.turn_left():
return "turn_left"
if player_after.direction == player_before.direction.turn_right():
return "turn_right"
if player_before.x == player_after.x and player_before.y == player_after.y and not player_after.active:
return "invalid"
return "change_nothing"
|
0b10e7e7ffbb1cde84a9790ecf38a29c8ed33fef
| 314,587 |
def get_vd_dialogue(d_id, dataset):
"""Retrieve a VisDial dialogue."""
caption = dataset['data']['dialogs'][d_id]['caption'] + '.'
turns = []
for qa in dataset['data']['dialogs'][d_id]['dialog']:
q = dataset['data']['questions'][qa['question']] + '? '
a = dataset['data']['answers'][qa['answer']] + '.'
turns.append((q + a))
return caption, turns
|
57797674712770647af5ba5cb74628e6b227986a
| 468,360 |
def solve_new_captcha(line):
"""
>>> solve_new_captcha('1212')
6
>>> solve_new_captcha('1221')
0
>>> solve_new_captcha('123425')
4
>>> solve_new_captcha('123123')
12
>>> solve_new_captcha('12131415')
4
"""
return sum(int(x) for x, y in zip(line, line[len(line) // 2 :] + line[: len(line) // 2]) if x == y)
|
b4e9d117006b6f9d9d45e78bfd4bed196e62e882
| 93,773 |
def truncate_hour(tval):
"""Truncate tval to nearest hour."""
return((int(tval)/3600) * 3600)
|
bc0a9177a14ad3d222b19bdaf5fa2e118f0ee8c7
| 433,582 |
import token
def trailing_comma(node):
"""Determine if there is a trailing comma"""
if node.children:
return node.children[-1].type == token.COMMA
return False
|
0a7a1a4c1b6d9998152b910f2b510f3377c1c964
| 427,183 |
def openFile(file_name):
"""Opens file and returns the contents unmodified
Args:
file_name (str): file name
Returns:
(str): file content
"""
with open(file_name, 'r') as fp:
return fp.read()
|
d48003a1be34686bdd33dffa3ad869b411edeaeb
| 496,273 |
def getValueListName(protocolResponseClass):
"""
Returns the name of the attribute in the specified protocol class
that is used to hold the values in a search response.
"""
return protocolResponseClass.DESCRIPTOR.fields_by_number[1].name
|
910c0bbc1539b16f4a34811e97b496442e708d66
| 298,566 |
def get_target_shape(shape, size_factor):
"""
Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions
is a multiple of size_factor
:param shape: tuple of integers
:param size_factor: integer
:return: tuple of integers
"""
target_shape = []
for dimension in shape:
rounded_down_dimension = size_factor * (dimension // size_factor)
rounded_up_dimension = rounded_down_dimension + size_factor
rounded_down_difference = abs(dimension - rounded_down_dimension)
rounded_up_difference = abs(dimension - rounded_up_dimension)
target_dimension = \
rounded_down_dimension if rounded_down_difference <= rounded_up_difference else rounded_up_dimension
target_shape.append(target_dimension)
return tuple(target_shape)
|
83c60a72e19cca5606995c9cdf324017156012ac
| 682,273 |
def harmonic_number(n, s):
"""Returns the generalized harmonic number Hn,s."""
return sum(1 / (i**s) for i in range(1, n+1))
|
98905e80c362f2b87bf68f89beaeaf9d46bbf071
| 503,851 |
import re
def strip_ansi_sequences(text):
"""Return a string cleaned of ANSI sequences"""
# This snippet of code is from Martijn Pieters
# https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
return ansi_escape.sub('', text)
|
89699eb64ae6053c6b440844810b7b56721c39de
| 120,712 |
import pytz
from datetime import datetime
def is_it_june() -> bool:
"""
determines if it is currently June in Madison, Wisconsin
Returns:
True if it is June, False otherwise
"""
tz = pytz.timezone("US/Central")
the_now = datetime.now(tz)
return datetime.date(the_now).month == 6
|
e1018f1ec92fd7fadf9b305d338dfdf234d3db46
| 660,974 |
def preprocess_input(cin: str):
"""
Maps user input into matrix indexes
Parameters
----------
cin : str
For example F5
Returns
-------
If the case was F5, it will return 4, 5
"""
letter = cin[0]
number = int(cin[1])
d = {'A': 0, 'B': 1, 'C': 2,
'D': 3, 'E': 4, 'F': 5,
'G': 6, 'H': 7}
x = d[letter]
y = number - 1
return x, y
|
54a85b79b8b1bb49d740d78a0a3894c203c82b6a
| 626,019 |
def hydro_area_lookup(area_id, df_ref, area_key):
"""Get max row in data file of a particular area's grid cells to reduce row count for performance
:param area_id: ID of area to find it's grid cells
:type area_id: int
:param df_ref: Reference dataframe
:type df_ref: dataframe
:area_key: Type of area (country or basin)
:type area_key: str
:return: int; Max row of area in file data
"""
# get which grid cells are associated with the target basin
target_idx_list = df_ref[df_ref[area_key] == area_id].copy()
return max(target_idx_list['grid_id'])
|
e50ba88508b93e1cea681d14bf6f426c3f562223
| 396,975 |
def adjust_var_name(var_to_check, var_names):
"""
Check if upper or lower case version of name is in namelist and adjust.
Parameters
----------
var_to_check : Str.
var_names : List of Str.
Returns
-------
var_to_check : Str.
"""
if var_to_check not in var_names:
for name in var_names:
if (var_to_check.upper() == name) or (
var_to_check.lower() == name):
var_to_check = name
break
return var_to_check
|
850f3261f6f359cde8243c15b1ea790372d057fb
| 622,924 |
import types
def monkeypatch_wagtail_as_syntax(image_node):
"""
If you use wagtails 'as' syntax like this:
{% srcset_image photo width-300 as thumbnail %}
image_node["attrs"] are not resolved. This patch resolves
srcset and attaches it to the returned rendition. It's a
bit hacky but should work.
"""
def render_patched(self, context):
result = self._original_render(context)
if self.output_var_name:
rendition = context[self.output_var_name]
rendition.srcset = self.attrs["srcset"].resolve(context)
rendition.original = self.attrs["srcset"].original_url
return result
image_node._original_render = image_node.render
image_node.render = types.MethodType(render_patched, image_node)
return image_node
|
6420bdf57cd30aa6acac8bee7c65e70e4e60d35d
| 537,384 |
def parseOptions(userOptions, jobOptions):
"""
Verifies that user supplied options fit the criteria for a set of
job options
Args:
userOptions: a set of user supplied options
jobOptions: an option schema for a job
Returns:
a list of errors (can be empty)
options to send to the job server
"""
sendOptions = {}
errors = []
for name, info in jobOptions.items():
# grab info about the option
optionType = info["TYPE"]
required = info["REQUIRED"]
default = info.get("DEFAULT",None)
# retrieve the user value for an option
value = userOptions.get(name,None)
# handle default/required case
if value is None:
if default is not None:
value = default
else:
if required:
errors.append("The option '%s' is required" % name)
continue
# coerce the type of an option
if optionType == "string":
value = str(value)
elif optionType == "int":
value = int(value)
elif optionType == "float":
value = float(value)
sendOptions[name] = value
return errors, sendOptions
|
166ce216cbe511b5a2c25e6b928b94e0ffd1f66e
| 80,837 |
def null_count(df):
"""
This function will return the number of null values contained
within a DataFrame
"""
return df.isnull().sum().sum()
|
089c9ff3ecb39449eec4e61923031fa38fcbeb28
| 132,488 |
def _get_submission_submitter(syn, submission):
"""Get submitter id and name from a submission object"""
submitterid = submission.get("teamId")
if submitterid is not None:
submitter_name = syn.getTeam(submitterid)['name']
else:
submitterid = submission.userId
submitter_name = syn.getUserProfile(submitterid)['userName']
return {'submitterid': submitterid,
'submitter_name': submitter_name}
|
dbfa16f989a5a11ac78d56f6fb7e097d53bcdeb6
| 454,487 |
import torch
def _compute_dx(x, grid):
"""
x: [n_batch, n_dim]
grid: [n_batch, n_dim, n_grid]
returns
dx: [n_batch, n_dim, n_grid]
"""
x = x.unsqueeze(-1)
# grid = grid.unsqueeze(0)
dx = x - grid
dx = torch.cat([dx[..., [0]], dx], dim=-1)
return dx
|
43166e113370a89111a276c418f47fbe1be0ecbe
| 168,387 |
def D_rvmu(r: float, v: float, mu: float) -> float:
"""
D = r * v * v / mu
:param r: radius vector
:type r: float
:param v: velocity
:type v: float
:param mu: G * (m1 + m2)
:type mu: float
:return: D
:rtype: float
"""
return r * v * v / mu
|
cd46798a793f444035ea7c42a74a96311f488b47
| 432,140 |
import csv
def read_csv(filepath):
"""Returns a list of dictionaries where each dictionary is formed from the data.
Parameters:
filepath (str): a filepath that includes a filename with its extension
Returns:
list: a list of dictionaries where each dictionary is formed from the data
"""
with open(filepath, mode='r', newline='', encoding='utf-8-sig') as file_obj:
data = list(csv.DictReader(file_obj))
return data
|
37a507090e71009cd2f0fa944cab35087e834d76
| 295,755 |
def empty_string_to_none(string):
"""Given a string, return None if string == "", and the string value
(with type str) otherwise
"""
if string == '':
return None
else:
return str(string)
|
3510cc65306e56f5845a9f0fbad737e3660d4f2e
| 665,113 |
def is_two_qubit_gate_layer(moment):
"""Helper function to check whether a moment in a circuit contains
one- or two-qubit gates."""
if len(next(iter(moment)).qubits) == 1:
return False
return True
|
bbfede1f73dd1b5782f0d3d3a2dbce1faf00577a
| 216,113 |
def validate_identity_token(connection, identity_token):
"""Validate an identity token.
Args:
connection: MicroStrategy REST API connection object
identity_token: Identity token
Returns:
Complete HTTP response object.
"""
return connection.get(
url=f'{connection.base_url}/api/auth/identityToken',
headers={'X-MSTR-IdentityToken': identity_token},
)
|
f3946117433f08a2580e16dcebcbecd01fd10d5d
| 517,915 |
def get_abs_part(poly):
"""Returns a part of a polynomial which contains absolute errors"""
result = [m.copy() for m in poly if m.abs_errs]
return result
|
3cfff0b95296b332ffe735db240d6ce0b100c32d
| 186,959 |
import itertools
def split_every(n, iterable):
"""Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377."""
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))
|
de47464f0d0dba19540d7f1fc56ed7ce5c6e2c0b
| 604,532 |
def top_n(lis, n):
"""Get index of top n item from list with value
Args:
lis:``list``
list
n:``int``
number of top value
Return:
dict of top value and index: ``dict``
"""
top = sorted(range(len(lis)), key=lambda i: lis[i], reverse=True)[:n]
value = [lis[i] for i in top]
return {"index": top, "value": value}
|
2aec294faf07b7a42d3ac1cba45f9a145c48964a
| 477,452 |
def unquote(name):
"""Remove string quotes from simple `name` repr."""
return name.replace("'","").replace('"','')
|
ccfaa777215a111a12e5374e28efbebc41688fbd
| 230,200 |
def sample(i):
"""Helper method to generate a meaningful sample value."""
return 'sample{}'.format(i)
|
492be8f764c6cd5b7bf799a802ecf7435b62e7c4
| 556,847 |
def aggregate_values(values_list, values_keys):
"""
Returns a string with concatenated values based on a dictionary values and a list of keys
:param dict values_list: The dictionary to get values from
:param str[] values_keys: A list of strings to be used as keys
:return str:
"""
output = ""
for key in values_keys:
output += values_list.get(key, "")
return output
|
2d867560f41e1487c55e498ccdca74ef0c280d32
| 663,410 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.