content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def make_argument_parser():
"""
Creates an ArgumentParser to read the options for this script from
sys.argv
:return:
"""
parser = argparse.ArgumentParser(
description="Find matches between the real and simulated tiles"
)
parser.add_argument('--size', '-S',
... | b3c644f0f3860722e9019955e8bc41718952b18b | 26,932 |
def public(*args):
"""
This decorator identifies which methods should be included in the abi file.
"""
def public_wrapper():
pass
return public_wrapper | b62ff44fbaa365c0f275c1c71ca723c97ec7ebe1 | 26,933 |
import re
def as_string(node):
"""
We can get a simple string from a node by flattening it to give us a Tree
with all string children, then joining those strings.
On top of this, we heuristically try to push punctuation back up to the
previous token using a regex, so things like
"Is this ... | 245db63b04c2707ac7411af9908644dcbed9f740 | 26,935 |
def normalise_period(val):
"""Return an integer from 1 to 12.
Parameters
----------
val : str or int
Variant for period. Should at least contain numeric characters.
Returns
-------
int
Number corresponding to financial period.
Examples
--------
>>> normalise_... | bf1d5e334d49d98404193fbbc2047bf41f7b24e5 | 26,937 |
def select_in_between_user_login_and_create_profile():
"""
it checks the user option recursively till user do not select the valid input.
:return: it returns an integer value.
"""
option = int(input("select your option (1)/(2): "))
if option == 1:
return 1
elif option == 2:
... | d8d5708982dbb2f14ee3227177d78989db16d5be | 26,938 |
from datetime import datetime
def humanize_timestamp(utc_timestamp, verbose=False):
"""
Convert a utc timestamp into a human readable relative-time.
"""
timedelta = datetime.utcnow() - datetime.utcfromtimestamp(utc_timestamp)
seconds = int(timedelta.total_seconds())
if seconds < 60:
... | 62a402607f8c96775606892771850d07795a160b | 26,939 |
import glob
def task_pot():
"""Re-create .pot ."""
return {
'actions': ['pybabel extract -o localization/telbot.pot src'],
'file_dep': glob.glob('src/*.py'),
'targets': ['localization/telbot.pot'],
} | 99ef42549e94950ecbf37a51bb09769a6fb484f4 | 26,940 |
def get_marker(label, chunk):
"""
Returns marker instance from chunk based on the label correspondence
"""
for marker in chunk.markers:
if label == marker.label:
return marker
print("Marker not found! " + label)
return False | e479568f5b6bc96be0bcdfbf7a428820ab953cce | 26,941 |
import os
def get_counts():
"""return test counts that are set via pyt environment variables when pyt
runs the test
:returns: dict, 3 keys (classes, tests, modules) and how many tests of each
were found by pyt
"""
counts = {}
ks = [
('PYT_TEST_CLASS_COUNT', "classes"),
... | c32b167917e5922659438a5b04a16bb661bb2ba7 | 26,942 |
def check_default_empty(default):
"""Helper function to validate if a default parameter is empty based on type"""
if isinstance(default, str) or isinstance(default, list):
return len(default) == 0
elif isinstance(default, int):
return False
elif isinstance(default, dict):
return ... | 19b94f3b25450d39c5c2b3ddc0af2758e1fc1b5f | 26,943 |
def knight_moves(start):
"""
Returns a list of positions that are legal knight moves
from 'start' on a chessboard that is represented as an list(64)
"""
rel_pos = [(-1, -2), (1, -2), (-2, -1), (2, -1),
(-2, 1), (2, 1), (-1, 2), (1, 2)]
res = []
for (x, y) in rel_pos:
a... | 92f75aac5090b9f105a0fbc1be4a39a2d542dbdb | 26,944 |
import itertools
def flatten(iterable):
"""Reduce dimensionality of iterable containing iterables
Args:
iterable: A multi-dimensional iterable
Returns:
A one dimensional iterable
"""
return itertools.chain.from_iterable(iterable) | 3869bbc5f2e1377d5c893ce7e35c3b91988916a7 | 26,945 |
def get_max(current_max, input_score):
"""
compare two input numbers, and return bigger one.
:param current_max: int, the current max score.
:param input_score: int, the score just input.
:return: int, compare two numbers and return bigger one.
"""
if current_max != 0 and current_max > input... | ad6c195219e4fb522e4a5802ad931b064da3dcc4 | 26,946 |
def check_lead_zero(to_check):
"""Check if a number has a leading 0.
Args:
to_check (str): The number to be checked.
Returns:
True if a leading 0 is found or the string is empty, False otherwise.
"""
if str(to_check) in (None, ''):
return True
elif str(to_check[0]) != '... | 39302f3f57ac2d9714d3057a744130cd3a5e5aa9 | 26,948 |
def dec2bin(x: int, n: int = 2) -> str:
"""Converts a single decimal integer to it binary representation
and returns as string for length >= n.
"""
return str(int(bin(x)[2:])).zfill(n) | cf5713c5f8855c5f737e4533f780ac75ee3abfa1 | 26,950 |
import math
def convert_bytes_to_string(number: int) -> str:
"""Returns the conversion from bytes to the correct
version (1024 bytes = 1 KB) as a string.
:param number: number to convert to a readable string
:return: the specified number converted to a readable string
"""
num = number
fa... | ca8f5d3417ad989bc12b2bf9cb76a561c735c548 | 26,954 |
def _get_location(location_text):
"""Used to preprocess the input location_text for URL encoding.
Doesn't do much right now. But provides a place to add such steps in future.
"""
return location_text.strip().lower() | 979471af5d40f0a58a2c4e4e7e26af18779ca890 | 26,955 |
import fnmatch
def _match_in_cache(cache_tree, list_of_names):
"""
:type cache_tree: defaultdict
:description cache_tree: a defaultdict initialized with the tree() function. Contains names
of entries in the kairosdb, separated by "." per the graphite convention.
:type li... | e559125f4b62a87956e0d30f5d8c3e4b2c7abef8 | 26,956 |
import requests
def ping(url: str) -> requests.Response:
"""
Pings the Server on the base url to make sure it's available.
"""
return requests.get(url) | a01cef7755a51ac8e235d5b22930b066cc83a08e | 26,957 |
def range_intersect(a, b, extend=0):
"""
Returns the intersection between two reanges.
>>> range_intersect((30, 45), (55, 65))
>>> range_intersect((48, 65), (45, 55))
[48, 55]
"""
a_min, a_max = a
if a_min > a_max:
a_min, a_max = a_max, a_min
b_min, b_max = b
if b_min > ... | 9184172de3921cfb74bccaeee9b15405045a1327 | 26,958 |
import codecs
def rot13(s: str) -> str:
"""ROT-13 encode a string.
This is not a useful thing to do, but serves as an example of a
transformation that we might apply."""
return codecs.encode(s, "rot_13") | a2413c3bd835dc09b445eb030aa6179e14411e17 | 26,960 |
import sys
def bbox_from_polygon(polygon):
"""Construct a numeric list representing a bounding box from polygon coordinates in numeric list representation."""
minx = sys.maxsize
miny = sys.maxsize
maxx = -sys.maxsize
maxy = -sys.maxsize
for xy in polygon:
if xy[0] < minx:
m... | 0518faeb45ea99834528072930829a5860576b03 | 26,962 |
from typing import Any
def is_numeric_scalar(x: Any) -> bool:
"""
Returns if the given item is numeric
>>> is_numeric_scalar("hello")
False
>>> is_numeric_scalar("234")
True
>>> is_numeric_scalar("1e-5")
True
>>> is_numeric_scalar(2.5)
True
"""
if isinstance(x, (float, ... | 7a0b8bd35be91b4ad6bda49d6a3543c1ca8f5ac7 | 26,963 |
def is_file_image(filename):
"""Return if a file's extension is an image's.
Args:
filename(str): file path.
Returns:
(bool): if the file is image or not.
"""
img_ex = ['jpg', 'png', 'bmp', 'jpeg', 'tiff']
if '.' not in filename:
return False
s = filename.split('.')... | 68df1997c4874cd990ca24739c91555378fc73fd | 26,964 |
def get_coords(rect):
"""Takes an np.array with coords of rectangle.
Returns max / min height / width
"""
lw = min(rect[:,0])
uw = max(rect[:,0])
lh = min(rect[:,1])
uh = max(rect[:,1])
return(lw, uw, lh, uh) | 021b718fbfc0c1c0cdd46e116972b647c780caff | 26,966 |
def _get_jgroup(grouped_data):
"""Get the JVM object that backs this grouped data, taking into account the different
spark versions."""
d = dir(grouped_data)
if '_jdf' in d:
return grouped_data._jdf
if '_jgd' in d:
return grouped_data._jgd
raise ValueError('Could not find a dataf... | 99b2ac71cd6d0ccf98976df43966ccabf14bcb98 | 26,967 |
def parse_fasta (lines):
"""Returns 2 lists: one is for the descriptions and other one for the sequences"""
descs, seqs, data = [], [], ''
for line in lines:
if line.startswith('>'):
if data: # have collected a sequence, push to seqs
seqs.append(data)
da... | 4dea579720f43f348389e53751c0308f1c493296 | 26,968 |
def format_response(event):
"""Determine what response to provide based upon event data.
Args:
event: A dictionary with the event data.
"""
text = ""
# Case 1: The bot was added to a room
if event['type'] == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM':
text = 'Thanks ... | b0ee2412ac35398fb3481e06ecd1c044742f0c50 | 26,969 |
def look_for_obj_by_att_val(my_obj_list, my_att, my_value):
"""Search for an Obj with an attribute of a given value, for methods that return list of Obj."""
ret_obj = None
for my_obj in my_obj_list:
if my_att in dir(my_obj):
# print(getattr(my_obj, my_att), my_value)
if geta... | 60ec811148260b490a36976234c6c3163d0d12b3 | 26,970 |
def weighted_soft_dice_loss(probs, labels, weights):
"""
Args:
probs: [B, 1, H, W]
labels: [B, 1,H, W]
weights: [B, 1, H, W]
"""
num = labels.size(0)
w = weights.view(num, -1)
w2 = w * w
m1 = probs.view(num, -1)
m2 = labels.view(num, -1)
intersection = m1 * m2... | 064b1ea07adcd11b39a0687d738b3e62d6c1f500 | 26,972 |
def is_bool(obj):
"""Returns ``True`` if `obj` is a ``bool``."""
return isinstance(obj, bool) | 6b63b9479c8a388a056c80cc62be74c548ac3504 | 26,974 |
def files_are_identical(pathA, pathB):
"""
Compare two files, ignoring carriage returns,
leading whitespace, and trailing whitespace
"""
f1 = [l.strip() for l in pathA.read_bytes().splitlines()]
f2 = [l.strip() for l in pathB.read_bytes().splitlines()]
return f1 == f2 | 60eeba55aa443577e98c45a46c10c1dc585e6c9f | 26,975 |
import uuid
def _maybe_convert(value):
"""Possibly convert the value to a :py:class:`uuid.UUID` or
:py:class:`datetime.datetime` if possible, otherwise just return the value
:param str value: The value to convert
:rtype: uuid.UUID|datetime.datetime|str
"""
try:
return uuid.UUID(value... | 66e70d33bd9b09c19c762ca66d4f50638a225821 | 26,976 |
from typing import List
def _poker_convert_shape(data: List[str]) -> list:
"""Converts card icons into shapes"""
return [row.replace("â£", " Clubs").replace("â¦", " Diamonds").replace("â¥", " Hearts").replace("â", " Spades") for row in data] | 4942fbf1551f2fa2dfdcefddf6977c706393b0ee | 26,977 |
import pickle
def load(name: str) -> object:
"""load an object using pickle
Args:
name: the name to load
Returns:
the unpickled object.
"""
with open(name, "rb") as file:
obj = pickle.load(file)
return obj | b8e11b703bea907386e2248c313c390429453a99 | 26,978 |
def decodeAny(string):
"""Try to decode the string from UTF-8 or latin9 encoding."""
if isinstance(string, str):
return string
try:
return string.decode('utf-8')
except UnicodeError:
# decoding latin9 never fails, since any byte is a valid
# character there
return... | 4acd087710118e72d8e142a230b36c57a5b70253 | 26,979 |
def clean_text(review, model):
"""preprocess a string (tokens, stopwords, lowercase, lemma & stemming) returns the cleaned result
params: review - a string
model - a spacy model
returns: list of cleaned tokens
"""
new_doc = ''
doc = model(review)
for word in doc:
... | a315f4d5bc581dce915f509023c65bba46f718a7 | 26,980 |
def regularize(np_arr):
"""
Project from [0, 255] to [0, 1]
:type np_arr: numpy array
:rtype: Projected numpy array
"""
return np_arr/255 | ba9f3f64f4d1d02b357d296299ee0635b2c93196 | 26,981 |
import pkg_resources
def python_package_version(package: str) -> str:
"""
Determine the version of an installed Python package
:param package: package name
:return: version number, if could be determined, else ''
"""
try:
return pkg_resources.get_distribution(package).version
exce... | 53f8de290418b1d64355f44efde162bed3a36b45 | 26,982 |
def set_extension(path, ext):
"""Set the extension of file.
Given the path to a file and the desired extension, set the extension of the
file to the given one.
Args:
path: path to a file
ext: desired extension
Return:
path with the correct extension
"""
ext = ext.re... | 5764e085a204aa209f085dbeb8d043c710734e11 | 26,983 |
import re
def get_select_cols_and_rest(query):
"""
Separate the a list of selected columns from
the rest of the query
Returns:
1. a list of the selected columns
2. a string of the rest of the query after the SELECT
"""
from_loc = query.lower().find("from")
raw_select_clau... | 33b397e7894792c0b354c41f219c609dc4df5927 | 26,984 |
import os
def check_env_variable_values(environment_variable):
"""
check environment variable value
Parameters
---------
environment_variable: str
Returns
-------
Any
"""
environment_variable_value = os.getenv(environment_variable)
if environment_variable_value is None ... | 3122ef5b763baa18094349bdc145dfcd65bdaeea | 26,987 |
def extract_ner(labels, masks=None):
"""
labels: list
return: entities list
根据labels提取一句话中的实体, 并输出实体list
"""
if masks is None:
masks = [1] * len(labels)
entities = []
cur_entity = ""
for i, (label, mask) in enumerate(zip(labels, masks)):
if mask == 0:
brea... | bafdfd35f7714a4d5ad9e34fd3d5d7b5a2747b7b | 26,988 |
import logging
import argparse
def logging_level(string):
"""Convert a string to a logging level"""
if string.isdigit():
return int(string)
level = getattr(logging, string.upper(), None)
if not isinstance(level, int):
raise argparse.ArgumentTypeError("invalid log level {}".format(strin... | daf2aa631508f13d1684e76939e052e8faf42486 | 26,989 |
def getTableHTML(rows):
""" Binds rows items into HTML table code.
:param list rows: an array of row items
:return: HTML table code with items at rows
:rtype: str
>>> getTableHTML([["Name", "Radek"], ["Street", "Chvalinska"]])
'<table><tr><td>Name</td><td>Radek</td></tr><tr><td>Street</td><td... | 931c8af65052c6a4455feae7f2f3a0f65d33a347 | 26,990 |
def build_complement(c):
"""
The function convert alphabets in input c into certain alphabets.
:param c: str, can be 'A','T','G','C','a','t','g','c'
:return: The string of converted alphabets.
"""
c = c.upper() # The Str Class method changes input c into capital.
total = ''
for i in ran... | 6fece325432ac061d5f7577c85cb59c19918ed83 | 26,992 |
import argparse
import logging
def arg_parse_params():
""" parse the input parameters
:return dict: parameters
"""
# SEE: https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--path_out', type=str, required=False, help='path to the outpu... | 4e65925f5d788011a42fdee646217509b2626e6d | 26,993 |
def normalise_reward(reward, prev_lives, curr_lives):
"""
No reward normalisation is required in pong; -1 indicates opponent has
scored, 0 indicates game is still in play and 1 indicates player has
scored.
"""
return reward | ff3c537ac6090692a05c7ee8c6f5bde890ed4d40 | 26,996 |
import torch
def _make_input(t, requires_grad=False, device=torch.device('cpu')):
"""Make zero inputs for AE loss.
Args:
t (torch.Tensor): input
requires_grad (bool): Option to use requires_grad.
device: torch device
Returns:
torch.Tensor: zero input.
"""
inp = tor... | c65c4ba243d786471b810d48af2251fff94c5d5f | 26,997 |
import os
def envor(envkey: str, default: str) -> str:
"""Returns an environment var value, or default.
Parameters:
envkey (str): An environment variable name.
default (str): A default value to return, in case the environment
variable ain't defined or have a value.
Returns:
s... | 35d5f74a2417ff134d331eebedc63d121ceffdfc | 26,998 |
import torch
def bce_loss(pred, target, false_pos_weight=1.0, false_neg_weight=1.0):
"""Custom loss function with options to independently penalise
false positives and false negatives.
"""
norm = torch.tensor(1.0 / float(len(pred)))
tiny = torch.finfo(pred.dtype).tiny
false_neg = torch.sum(tar... | b9ed60d886212bc821fed3f21c4e58e6953b1e02 | 26,999 |
def bernoulli_kl(q_probs, p_probs):
"""
computes the KL divergence per batch between two Bernoulli distributions
parametrized by q_probs and p_probs
Note: EPS is added for numerical stability, see
https://github.com/pytorch/pytorch/issues/15288
Args:
q_probs (torch tensor): mea... | 52253d4cd07b6ceb5081236ea5167b87b754c2fc | 27,001 |
def formatGpuCount(gpuCount):
"""
Convert the GPU Count from the SLurm DB, to an int
The Slurm DB will store a string in the form "gpu:1" if a GPU was requested
If a GPU was not requested, it will be empty
"""
if gpuCount:
intGpuCount = int("0"+gpuCount.split(":")[1])
return intG... | bb15f87da94d5994c9a08ff0614f5381eb3265de | 27,002 |
import argparse
def default_pseudo_arg_parser():
"""
Create ArgumentParser for pseudo device.
:rtype: argparse.ArgumentParser
:return: Default argument parser.
"""
arg_parser = argparse.ArgumentParser(
description="pseudo device main.")
# arg_parser.add_argument("-a", "--host", ty... | 98df8a7092d86c464636ffebdc5b1f233d9872b8 | 27,003 |
from typing import MutableMapping
from typing import Any
def to_nested_dict(d: dict):
"""
Converts a flat dictionary with '.' joined keys back into
a nested dictionary, e.g., {a.b: 1} -> {a: {b: 1}}
"""
new_config: MutableMapping[str, Any] = {}
for k, v in d.items():
if "." in k:
... | 18230ecf0798ee5f2c9b74dccfb90b28547354e8 | 27,004 |
import os
def name(path: str) -> str:
"""
finds name for file
"""
name_extension = os.path.basename(path)
return name_extension.rsplit(".", 1)[0] | 07e067b984de39df3996bf2d403c3435af806137 | 27,005 |
from typing import Any
def validate_boolean(var: Any) -> bool:
"""Evaluates whether an argument is boolean True/False
Args:
var: the input argument to validate
Returns:
var: the value if it passes validation
Raises:
AssertionError: `var` was not boolean
"""
assert is... | 67d8751a60fa6621f0fb366ab44cd017dfe3bd8c | 27,008 |
def force_slash(x):
"""convert backslashes to slashes"""
return x.replace('\\', '/') | a7d9faafa61b5eaa09171e960c8f2498e03bce2e | 27,009 |
def simplify_int_labels(int_labels, threshold=5):
"""
Given a sequence of integer labels, finds out unique labels in repetitions.
For example:
[0,10,10,10,10,10,10,0,12,12,12,12,12] to [10,12]
Args:
int_labels:
threshold: number of consecutive occurrences before selecting a label.
... | 0888c632e443e51e4a697450622c0c8237b6ba84 | 27,010 |
import re
import sys
def get_region_tag(sample_file_path):
"""Extracts the region tag from the given sample.
Errors if the number of region tags found is not equal to one. Ignores the
*_core tags.
"""
start_region_tag_exp = r'\[START ([a-zA-Z0-9_]*)\]'
end_region_tag_exp = r'\[END ([a-zA-Z0-9_]*)\]'
re... | 3bcd70474b3499c070731d39689fe90ccedf4946 | 27,011 |
import functools
def or_none(fn):
"""
Wraps `fn` to return `None` if its first argument is `None`.
>>> @or_none
... def myfunc(x):
... return 2 * x + 3
>>> myfunc(4)
11
>>> myfunc(None)
"""
@functools.wraps(fn)
def wrapped(arg, *args, **kw_args):
... | 54346619090c1aab12498297a31bb017d85377f5 | 27,012 |
import os
def load_dataset(filename, data_path="data"):
""" Load full dataset (all tasks)
"""
sentences = []
with open(os.path.join(data_path, filename), 'r') as file:
file = iter(file)
sentence = []
while True:
try:
line = next(file)
exc... | 1ed50c971f1b50f67fbbdae97df9fa99f8f85493 | 27,014 |
def start_connection(puzzle, length):
"""Make connection between words"""
connection = [0] * (length ** 2)
for i in range(length ** 2):
connection[i] = [False] * (length ** 2)
for i, j in enumerate(puzzle):
if j == '0':
continue
col, row = i // length, i % length
... | c3b42d341f1f4eb08bc83fb2dabd88d16837ee8e | 27,016 |
import os
def needbinarypatch():
"""return True if patches should be applied in binary mode by default."""
return os.name == 'nt' | b7c3d8f9455620c3a14b51fe77b51db9e655bf29 | 27,017 |
def get_segment_output_path(output_path, muxing_output_path):
"""
Returns the output path for a stream segment.
"""
segment_path = muxing_output_path
substr = muxing_output_path[0:len(output_path)]
if substr == output_path:
return muxing_output_path[len(output_path):]
return segmen... | 7c35c5becf6b6eb4f20399f6fa5b3367bce5af79 | 27,018 |
def read_flat_parameters(fname):
"""Read flat channel rejection parameters from .cov or .ave config file"""
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
reject_names = ['gradFlat', 'magFlat', 'eegFlat', 'e... | 34ca5d9f4946d8ee087126b7932596949081b0c3 | 27,019 |
import re
import sys
def expand_rows( string_in, element_coordinates = [ None, None ] ):
"""
Expand a P7 row specification to a list of rows.
Acceptable row specifications include
o single row
o B
o row range
o E-G
o single and/or ranges of rows separated by commas
o ... | d2325300ecc5889226bfe7e80cca8d2b789a99dd | 27,020 |
def get_rectangle_coordinates(win):
"""
Gets the coordinates of two opposite points that define a rectangle and
returns them as Point objects.
"""
point_1 = win.getMouse()
point_2 = win.getMouse()
return point_1, point_2 | 75a605ea628c8d9c6817bf727de3542894ac555f | 27,021 |
import calendar
def get_days_of_month(year, month):
"""
返回天数
"""
return calendar.monthrange(year, month)[1] | 2606f3b93b1d94ba3668d3a979f6d84a96e6ac00 | 27,022 |
def identifyL23(addition):
"""Check if it is L2 or L3 delta request."""
return 'L3' if 'routes' in list(addition.keys()) else 'L2' | 63c47a0de8142ddae8559d2e4cc236e2f5e972fd | 27,024 |
def find_border_crossing(subset, path, final_state):
"""
Find the transition that steps outside the safe L{subset}.
@param subset: Set of states that are safe.
@type subset: C{set} of L{State}
@param path: Path from starting state to L{final_state}, sequence of state
and its outg... | 8cf7953897066af2453c4bb428fb01326a4aa25f | 27,026 |
def randomize(df, seed):
"""Randomizes the order of a Pandas dataframe"""
return df.sample(len(df), random_state=seed).reset_index(drop=True) | deb6f1327b993a5a39255bdf2a2b22bc61cdd0a3 | 27,028 |
def clean(df, verbose=False):
"""Nettoie le tableau de données"""
# on supprime les URLs qui ne pointent pas vers le site de la ville
if verbose:
print("Suppression des URLs : pas sur le site de la ville")
print(df.loc[~df["url"].str.contains("marseille.fr"), "url"])
df.loc[~df["url"].st... | 92182cdd84424c11ca318131ef92eac03fe2b242 | 27,030 |
import re
def count_expr_arity(str_desc):
""" Determine the arity of an expression directly from its str
descriptor """
# we start by extracting all words in the string
# and then count the unique occurence of words matching "x", "y", "z" or "t"
return len(set(var for var in re.findall("\w+", ... | 6e94b6da17b90de4b6b4734add65311842af467d | 27,031 |
from numpy import asarray, mean
def mean_reciprocal_rank(rs):
"""Score is reciprocal of the rank of the first relevant item
First element is 'rank 1'. Relevance is binary (nonzero is relevant).
Example from http://en.wikipedia.org/wiki/Mean_reciprocal_rank
>>> rs = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]... | 60cdba9ff4c75aa96931f3368cc7fcfcb33a785a | 27,032 |
def attrsetter(attr, value):
""" Return a function that sets ``attr`` on its argument and returns it. """
return lambda method: setattr(method, attr, value) or method | 355bf2e63051fbcdbc6a881c49ddd9fc404f4b75 | 27,033 |
def get_definition_end_position(self):
"""
The (row, column) of the end of the definition range. Rows start with
1, columns start with 0.
:rtype: Optional[Tuple[int, int]]
Returns:
int: The end position
"""
if self._name.tree_name is None:
return None
definition = self._... | d7ceff7a03d63f5e96ce0727196f82ba4cadb980 | 27,034 |
import math
def sq_sign(x):
"""
Squares the magnitude but keeps the sign
:param x:
:return:
"""
return math.copysign(x * x, x) | c7ecbd665345be1fa30b0cf84e3692bfe7b139e5 | 27,035 |
from typing import Callable
def call(func: Callable, **kwargs):
"""Configurable version of `func(**kwargs)`."""
return func(**kwargs) | 7ec9f1dc47444bbf9f0ecb6bfbe35fe03b6c5b42 | 27,037 |
import torch
def rmspe_loss(targets: torch.Tensor, predictions: torch.Tensor) -> torch.Tensor:
"""Root mean square percentage error."""
loss = torch.sqrt(torch.mean(((targets - predictions).float() / targets) ** 2))
return loss | 76f94f6b1e21cad495108b1550e9d4afef3aafa6 | 27,039 |
from pkg_resources import EntryPoint
def resolveDotted(dotted_or_ep):
""" Resolve a dotted name or setuptools entry point to a callable.
"""
return EntryPoint.parse('x=%s' % dotted_or_ep).resolve() | 504b73a7a3735753db57ae8b86361594b580a3cd | 27,040 |
def get_request_header(headers):
"""
Get all headers that should be included in the pre-signed S3 URL. We do not add headers that will be
applied after transformation, such as Range.
:param headers: Headers from the GetObject request
:return: Headers to be sent with pre-signed-url
"""
new_h... | 97af84f361bc4265d934dbd2cf5398ad4f744e1e | 27,043 |
def check_game(board, last_move):
"""
check if any player has managed to get 3 marks in a row, column or diagonally.
:param {String[]} board : current board with marker locations of both players
:param {int} last_move : between 1-9 where the most recent marker was put.
:return {Boolean} : True if player who play... | 59bc4f5e38b469cd49b59b342ca402b50d591948 | 27,045 |
import re
def __fix_tz(text: str) -> str:
"""Overrides certain timezones with more relevant ones"""
replacements = {
"BST": "+0100", # British Summer Time
"IST": "+0530", # Indian Standard Time
}
for timezone, offset in replacements.items():
text = re.sub(fr"\b{timezone}\b", ... | d31c3ac3899cecc7030583f83b06883ca00222bb | 27,047 |
def grant_url(focus_area, month):
"""Use the focus area and donation date information to get the original grant URL."""
fa = {
"community-development": 13,
"education-youth": 28,
"religion": 11,
}[focus_area]
month_param = month[2:]
return f"https://lillyendowment.org/for-cu... | 6ae83240afbec368038aba07b3f37d44ea0d1afe | 27,049 |
def parse_srg(srg_filename):
"""Reads a SeargeRG file and returns a dictionary of lists for packages, classes, methods and fields"""
srg_types = {'PK:': ['obf_name', 'deobf_name'],
'CL:': ['obf_name', 'deobf_name'],
'FD:': ['obf_name', 'deobf_name'],
'MD:': ['o... | ac33b56fc52831a80f1e38261b38c47407fd1bfb | 27,050 |
import random
def choose(bot, trigger):
""".choice option1|option2|option3 - Makes a difficult choice easy."""
if not trigger.group(2):
return bot.reply('I\'d choose an option, but you didn\'t give me any.')
choices = [trigger.group(2)]
for delim in '|\\/, ':
choices = trigger.group(2)... | ad4fd246e9db86d45a7a6cb06ef5b9813c0a0d5f | 27,051 |
def slkBlocking(rec_dict, fam_name_attr_ind, giv_name_attr_ind,
dob_attr_ind, gender_attr_ind):
"""Build the blocking index data structure (dictionary) to store blocking
key values (BKV) as keys and the corresponding list of record identifiers.
This function should implement the statistical... | bceb7765e05f2d242d282c40688e18d110b5f32e | 27,053 |
def caption_from_metadata(metadata):
"""
converts metadata list-of-lists to caption string which is one antinode per line
"""
caption = ""
for an in range(len(metadata)):
[cx, cy, a, b, angle, rings] = metadata[an]
#this_caption = "[{0}, {1}, {2}, {3}, {4}, {5}]".format(cx, cy, a, b,... | 49f7172601db54c855780243797a6635cfc10dfa | 27,054 |
from typing import List
def primes(max: int) -> List[int]:
"""
Return a list of all primes numbers up to max.
>>> primes(10)
[2, 3, 5, 7]
>>> primes(11)
[2, 3, 5, 7, 11]
>>> primes(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> primes(1_000_000)[-1]
999983
"""
max += 1
nu... | 1fbdda28414f9a846d2ea1dc945af619df6aeea7 | 27,055 |
def current_user(self):
"""Get current user"""
return self.handler.current_user | 790a3478390dbb5439380ef1a35b6bc67f89721a | 27,056 |
def _get_notebook_outputs(nb_node):
"""Returns a dictionary of the notebook outputs."""
outputs = {}
for cell in nb_node.cells:
for output in cell.get('outputs', []):
if 'papermill' in output.get('metadata', {}):
output_name = output.metadata.papermill.get('name')
... | 8eda7268f36839703dbc94f31903e0c5d37f5e5b | 27,058 |
def count_jobs(api, name, all=False):
"""Count how many zapps have already been submitted."""
if all:
sched = api.statistics.scheduler()
return sched['running_length']
execs = api.executions.list(status='submitted', name=name)
execs += api.executions.list(status='queued', name=name)
... | ed5ca077769b656b101fc9dd71a85878fe9ae8ef | 27,059 |
import torch
from typing import Tuple
def _split_crossval(xy: torch.Tensor, crossval_count: int, crossval_index: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Generates a split of the given dataset along the first dimension for cross-validation.
:param xy: The data that should be split. The split will b... | 211146bdac3396da475b6c6b74d990031a537af7 | 27,061 |
from typing import Optional
from typing import Any
from typing import List
from typing import Iterable
def as_list(value: Optional[Any]) -> List[Any]:
"""Normalizes the value input as a list.
>>> as_list(None)
[]
>>> as_list("foo")
['foo']
>>> as_list(123)
[123]
>>> as_list(["foo", "b... | 54f13890437dfafd779583a3bbdc42ae769312f4 | 27,062 |
from typing import List
def get_cell_density(lstfile: str, n_phases: int) -> List[dict]:
"""
Parse .lst file to get new cell values with errors and density from a refinement.
Parameters
----------
lstfile : str
Path to GSASII .lst file.
n_phases : int
Number of phases in the .... | 00460f9d3c0628710617ecdb270c56b7be153f0a | 27,063 |
import re
def smooth(text):
"""Get rid the noise in the wikipedia corpus"""
text = re.sub(r"=+(.*)=+", "", text) # remove headers
# if it is lists or items, regard their contents as sentenses
# (append an extra comma to each)
text = re.sub(r"(\*|\#|:|;)+(.*)\n", "\g<2>。\n", text)
text = re.su... | 392852a80f45b0f15e9f3ae9e80da68197fe8d95 | 27,064 |
def mcs(G):
"""Maximum cardinality search.
Returns an ordering of the vertices as described in [TY84Simple].
The ordering is not reversed to make sure than G[V[0:i]] is connected.
"""
n = G.number_of_nodes()
sets = []
size = {}
ordering = []
orderingDict = {}
for v in G.node... | c1b59f45e5592ef31387124e65768b11cbd6ac2d | 27,066 |
import time
def now():
""" return current time. """
if time.daylight: ttime = time.ctime(time.time() + int(time.timezone) + 3600)
else: ttime = time.ctime(time.time() + int(time.timezone))
return ttime | 97fd12e2737b49e6a6f30ef67db5092d4f927c9e | 27,068 |
from unittest.mock import Mock
def functions():
"""Test for regular function name completion."""
mock_func = Mock()
return {
"domain.func_1": mock_func,
"domain.func_2": mock_func,
"helpers.get_today": mock_func,
"helpers.entity_id": mock_func,
} | 0281b5fa3fba5b2dd7b56c8291af1629d13c9b84 | 27,071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.