content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def callback_pos(instance, value):
"""Give back the value of a certain position."""
print('The widget', instance, 'moved to', value)
return value | d7f85a46c6841134312a7ced302d5d952bd358da | 654,071 |
def parse_num(maybe_num) -> int:
"""parses number path suffixes, returns -1 on error"""
try:
return int(maybe_num)
except ValueError:
return -1 | ced37994602084cd8f6c7bc272ad50e7974639bc | 654,072 |
def flen(filename):
"""
File LENgth computes and returns the number of lines in a file. @filename <string> is path to a file. This is an epensive method to call for the whole file is read to determine the number of lines.
returns: <integer> line count
"""
# Read and count lines.
with open(filename, 'r') as i... | 3b8a807a1a30b357e71ba1e90bb8e82038dcadf8 | 654,074 |
def offset_snp(snp, offset, invert=False):
"""Translate SNP positions by a given ofsset."""
orientation, tail = snp.split("@")
pos, base_change = tail.split(":")
base_from, base_to = base_change.split(">")
pos = int(pos) + offset
if invert:
tmp = base_from
base_from = base_to
... | f5c386e8abdbb7de6dbbd4a82dc7354379c311f5 | 654,075 |
def snap_to_cube(q_start, q_stop, chunk_depth=16, q_index=1):
"""
For any q in {x, y, z, t}
Takes in a q-range and returns a 1D bound that starts at a cube
boundary and ends at another cube boundary and includes the volume
inside the bounds. For instance, snap_to_cube(2, 3) = (1, 17)
Arguments:... | ca4b1bc09d289ac3ecad4d8c0ceedb23ab121882 | 654,076 |
import os
def get_shortcut_paths(directory):
"""get_shortcut_paths("Programs") => ["...\Internet Explorer.lnk", ...]
Returns the list of Windows shortcuts contained in a directory.
"""
return [os.path.join(directory, f) for f in os.listdir(directory)
if os.path.splitext(f)[1] == '... | 07cfad6746506b78885b3dba9500bc1531a0fd9c | 654,077 |
def main(*, a, b):
"""entrypoint function for this component
Usage example:
>>> main(
... a = pd.Series(
... {
... "2019-08-01T15:20:12": 1.2,
... "2019-08-01T15:44:12": None,
... "2019-08-03T16:20:15": 0.3,
... "2019-08-05T12:0... | 6ae580cb71b076ee542d145716a34134470c9cc3 | 654,078 |
def nrz_decision(x,t):
"""produces nrz symbol from analog voltage
Parameters
----------
x : float
the analog voltage
t: float
voltage threshold between 0 and 1 symbol
Returns
-------
int
the nrz symbol that represents x
"""
if x<t:
r... | 03b6d24c3fe5ea4ac043a7c10fce4a33c9038622 | 654,079 |
def selection_sort(integers):
"""Search through a list of Integers using the selection sorting method.
Search elements 0 through n - 1 and select smallest, swap with element at
index 0, iteratively search through elements n - 1 and swap with smallest.
"""
integers_clone = list(integers)
for ind... | 2752b2bc9e7239bb3a5f928aafad558dd987e62c | 654,080 |
def get_school_round(a_in, n_in):
"""
https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python
:param a_in:
:param n_in:
:return: float
"""
if (a_in * 10 ** (n_in + 1)) % 10 == 5:
return round(a_in + 1 / 10 ** (n_in + 1), n_in)
else:
... | ab10d02bac81b73b9dfe8e83d500e0abae68078a | 654,081 |
def serialize_quantity(quantity):
"""Serializes a propertyestimator.unit.Quantity into a dictionary of the form
`{'value': quantity.value_in_unit(quantity.unit), 'unit': quantity.unit}`
Parameters
----------
quantity : unit.Quantity
The quantity to serialize
Returns
-------
dic... | 8d25f1461615b042ed522938024265942ef6e691 | 654,082 |
from typing import Dict
import os
import json
def default_params() -> Dict:
""" load default parameters """
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, "data", "parameters.json")) as f:
return json.load(f) | 3491e9020d94f21607020d4434f40d788a81476c | 654,083 |
def migrate(engine):
"""Replace 'backend' with 'store' in meta_data column of image_locations"""
sql_query = ("UPDATE image_locations SET meta_data = REPLACE(meta_data, "
"'\"backend\":', '\"store\":') where INSTR(meta_data, "
" '\"backend\":') > 0")
# NOTE(abhishekk): INS... | 6d7fa2beed8cf38cb7debe556663950a820af1c2 | 654,084 |
import itertools
def xml2d(e):
"""Convert an etree into a dict structure
@type e: etree.Element
@param e: the root of the tree
@return: The dictionary representation of the XML tree
"""
def _xml2d(e):
kids = dict(e.attrib)
for k, g in itertools.groupby(e, lambda x: x.tag):
... | a111ecb86c1b1b048a030fb8e3b807a2c5334d3c | 654,085 |
def update_alpha_vec(alpha,Q,C):
"""
Args: alpha: 1d array
Q, C: 2d array
Return: 1d array
"""
t = len(alpha)-1
return alpha[:t]-alpha[t]/(C[t,t]+Q[t,t])*(Q[t,:t]+C[t,:t]) | 95c78e1ffc43d41e4e905e8be28efc62272fe17d | 654,086 |
def get_all_collections(self):
"""Return all collections in the database"""
return self.app.db.table('collections').all() | 5cd86ad43992c6e6f07dee716408e7ea25692007 | 654,087 |
import os
def find_innosetup():
"""
find InnoSetup executable
@return executable
"""
exe = r"C:\Program Files (x86)\Inno Setup 5\compil32.exe"
if not os.path.exists(exe):
raise FileNotFoundError(exe)
return exe | 933baeb2df2cc96b64ae59acbaac378e6f11e32e | 654,088 |
import argparse
def make_parser():
"""
:return:
"""
parser = argparse.ArgumentParser("YOLOX TensorRT deploy")
parser.add_argument("-expn",
"--experiment-name",
type=str,
default="",
help="")
parser... | 92abcce1f6e96d354907586d74d07421d4756237 | 654,089 |
import os
def running_installer_test():
"""Return True if currently running installer test"""
return bool(int(os.environ.get('INSTALLER_TEST', '0'))) | e5bb630112297bd6007b03b4e5e39e6bf9ce3ca5 | 654,090 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
file = open(path, 'r')
return [line.strip() for line in file.readlines()] | 50d4ea64d816d486bd27e106d4977ae2c594e1f6 | 654,091 |
def gov_text(info):
"""
input: a country's infobox (rdflib graph node)
uotput: list of strings of text from the government table cell
"""
try:
res = info.xpath(".//tr[.//th//a[contains(text(), 'Government')]][1]")[0]
except IndexError:
try:
res = info.xpath(".//tr[.//... | 54e1861c656492a1a85a24390a86115b3f46fa37 | 654,092 |
def mongodb_authn():
"""Parses a MongoDB connection key into a configuration dict
"""
authn = 'bW9uZ29kYjovL2NhdGFsb2c6Y2F0YWxvZ0Bsb2NhbGhvc3Q6MjcwMTcvY2F0YWxvZ19sb2NhbD9yZWFkUHJlZmVyZW5jZT1wcmltYXJ5'
return {'authn': authn, 'database': 'catalog_local'} | 577ae0cfa816fb9aafc2506c7c799205f26e26a1 | 654,093 |
def make_ops_ast(expr, nfops, is_write=False):
"""
Transform a devito expression into an OPS expression.
Only the interested nodes are rebuilt.
Parameters
----------
expr : Node
Initial tree node.
nfops : OPSNodeFactory
Generate OPS specific nodes.
Returns
-------
... | 70068e5a48194467fff1f095460225e86dab5215 | 654,094 |
import torch
def resort_points(points, idx):
"""
Resort Set of points along G dim
:param points: [N, G, 3]
:param idx: [N, G]
:return: [N, G, 3]
"""
device = points.device
N, G, _ = points.shape
n_indices = torch.arange(N, dtype=torch.long).to(device).view([N, 1]).repeat([1, G])
... | a886b1c694a2c8c1ef5a3c2bdccf201aa7a53812 | 654,095 |
def is_square(n: int) -> bool:
"""
>>> is_square(64)
True
>>> is_square(56)
False
"""
if n == 0:
return True
i = 1
while i * i <= n:
if (n % i == 0) and (n / i == i):
return True
i = i + 1
return False | 69f4b4adbc70ca5b560ddbadea14ec58d4299f42 | 654,096 |
import argparse
def parse_args():
"""
Return a list of command line arguments (using argparse module).
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-l', '--last-minutes', default=0, type=int,
help='download only the news of last n minutes')
p... | b70ffeff552de1d509dbd7d5187b83eb82143cbe | 654,097 |
def _string_escape(text):
"""
>>> from .pycompat import bytechr as chr
>>> d = {b'nl': chr(10), b'bs': chr(92), b'cr': chr(13), b'nul': chr(0)}
>>> s = b"ab%(nl)scd%(bs)s%(bs)sn%(nul)sab%(cr)scd%(bs)s%(nl)s" % d
>>> s
'ab\\ncd\\\\\\\\n\\x00ab\\rcd\\\\\\n'
>>> res = _string_escape(s)
>>> ... | 2a7435249f69bd03c01bc6b461e94b801cc634c4 | 654,098 |
import re
def _include_local_or_system(x):
"""Wrap **x** in quotes if it is not wrapped in angle brackets."""
if re.fullmatch("<.*>", x):
return x
return '"' + x.strip('"') + '"' | 6175b8449f2ff76baf209a701939aac42763feb9 | 654,099 |
import argparse
def process_args(args, defaults, description):
"""
Handle the command line.
args - list of command line arguments (not including executable name)
defaults - a name space with variables corresponding to each of
the required default command line values.
descriptio... | ae6cc0dd57319accc44d5457780cb8112543649c | 654,101 |
import os
def read_package_variable(key, filename="__init__.py"):
"""Read the value of a variable from the package without importing."""
module_path = os.path.join("src/nebulo", filename)
with open(module_path) as module:
for line in module:
parts = line.strip().split(" ", 2)
... | c8c94d13b85202fbcf6dd992c85b6d79a38036e6 | 654,103 |
def is_ambiguous(num_sensed_blocked: int, num_confirmed_blocked: int, num_sensed_unblocked: int,
num_confirmed_unblocked: int):
"""
Check whether the conditions are ambiguous or not
:param num_sensed_blocked: number of sensed blocks
:param num_confirmed_blocked: number of confirmed bloc... | 26f03c0a82120f90f0e6d3b35205b8b6eea34636 | 654,104 |
import platform
import resource
def get_cur_memory():
""" Return the used memory in MB """
if platform.system() == 'Linux':
# Slightly more accurate than below
with open('/proc/self/status') as f:
for line in f:
if line.startswith('VmRSS:'):
ret... | 86323ea70f56f089a0a6a04cecdd554bb4cc1a71 | 654,105 |
import json
def enjson(obj, indent=4, encoding='UTF-8'):
"""
Dumps unicode json allowing non-ascii characters encoded as needed.
"""
return json.dumps(obj, indent=indent, ensure_ascii=False).encode(encoding) | 13f29ec422a026d076eef57a1f6f13db1305402c | 654,106 |
def display(order, start):
""" Convert to readable format.
"""
res = []
c = start
while len(res) < len(order)-1:
res.append(str(c))
c = order[c]
return " ".join(res) | 21983e2300874c1e075ea62146755e0be11351f7 | 654,107 |
def compare_dicts(cloud1, cloud2, ignores):
"""
Compare the dicts containing cloud info
"""
if not cloud1 or not cloud2:
return False
for item in cloud1:
if item in cloud2:
if cloud1[item] != cloud2[item] and item not in ignores:
return False
elif... | cfc6667f33c1df0829178b05953c63ec59d129f5 | 654,109 |
def _select_xticks(x):
"""
Heuristically decide how many x-axis labels will be printed, in
order to avoid obfuscating each other, due to figure's fixed width.
"""
if len(x) < 19:
# print all
return x
else:
# print every two
return x[0:-1:2] | 99dde531e9acd95dfea43484aaac689d63a2cc2e | 654,110 |
def nombre_sommets(G):
"""Renvoie le nombre de sommets d'un graphe"""
return len(G.keys()) | c322dfe32b0a351c1b4be1f62254621a7089125c | 654,111 |
def headingToYaw(heading):
""" Convert heading (degrees, NED) to yaw (degrees, ENU).
Args:
heading: float heading: degrees, NED
Returns:
Float, yaw: degrees, ENU
"""
return 90.0-heading | 120e7c80638d2fec5d507102cf8e30a7eb18d6da | 654,112 |
def opts_dd(lbl, value):
"""Format an individual item in a Dash dcc dropdown list.
Args:
lbl: Dropdown label
value: Dropdown value
Returns:
dict: keys `label` and `value` for dcc.dropdown()
"""
return {'label': str(lbl), 'value': value} | d9a9b97b9c586691d9de01c8b927e4924eba3a3e | 654,113 |
def numba_leastsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation.
from https://stackoverflow.com/questions/23550483/numba-and-cython-arent-improving-the-performance-compared-to-cpython-significan"""
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x... | 464af109bc7d821f3001a5ea7b1d6feb19545aff | 654,114 |
def filter_args(args):
"""Removes "amp;" from request keys"""
return {key.replace("amp;", ""):value for key, value in args.items()} | f86c1c25efbd0f16a9a1d838c658ed6d738ed2d3 | 654,115 |
import torch
def d(tensor=None):
"""
Returns a device string either for the best available device,
or for the device corresponding to the argument
:param tensor:
:return:
"""
if tensor is None:
return 'cuda' if torch.cuda.is_available() else 'cpu'
return 'cuda' if tensor.is_cud... | 59fb3c9b0fb749c016499126cc69cce2f1fb8264 | 654,116 |
def rc_to_xy(row, col, rows):
"""
Convert from (row, col) coordinates (eg: numpy array) to (x, y) coordinates (bottom left = 0,0)
(x, y) convention
* (0,0) in bottom left
* x +ve to the right
* y +ve up
(row,col) convention:
* (0,0) in top left
* row +ve down
* col +ve to the... | 529f88a99ba5c3143c528df3eb844be834568c20 | 654,117 |
def has_relative_protocol(uri):
"""Return True if URI has relative protocol '//' """
start = uri[:2]
if start == '//':
return True
return False | 40c37b5f7ec6ea6de2ed02b742b2f2d0b149bc32 | 654,118 |
def calc_wmr(BMR, PAL):
"""Total requirement depending on PAL = physical activity level"""
return BMR * (PAL - 1) | 79ed3d8ad7bdc73aa8d980f449385d80a92cf31b | 654,119 |
def wrap(value):
"""Return *value* as a list.
Reader._parse(elem, unwrap=True) returns single children of *elem* as bare
objects. wrap() ensures they are a list.
"""
return value if isinstance(value, list) else [value] | 13611946b2235eec9c55b038be287342a728568c | 654,122 |
def tokenize(tokenizer, text):
"""
Tokenizes a given text.
Parameters
----------
tokenizer: transformers.PreTrainedTokenizer
A tokenizer object from the HuggingFace's `transformers` package.
text: str
The text to be tokenized.
Returns
-------
list(str)
A lis... | 892efc4e269f7807ef15f297a9c3d2e3a5ddff63 | 654,123 |
def solution(A): # O(N^2)
"""
Sort numbers in list A using bubble sort.
>>> solution([5, 2, 2, 4, 1, 3, 7, 9])
[1, 2, 2, 3, 4, 5, 7, 9]
>>> solution([2, 4, 6, 2, 0, 8])
[0, 2, 2, 4, 6, 8]
>>> solution([1, 3, 5, 7, 3, 9, 1, 5])
[1, 1, 3,... | 702db60295b6e06c0d4d52dde01c37d6fa6d79ae | 654,124 |
def get_labelled_idxs(dataset):
"""
Get all indices with labels
"""
split_dict = dataset.get_idx_split()
train_idx = split_dict['train']
valid_idx = split_dict['valid']
test_idx = split_dict['test']
idxs_labelled = set(train_idx)
idxs_labelled = idxs_labelled.union(set(valid_idx))
... | 716a4d95aa33753ffa2bedbfecb44797cdc5763e | 654,125 |
import os
def file_to_link(path):
"""
Given a raw Wikipedia article, this method extracts its title,
and returns a link to its page
"""
with open(os.path.abspath(path), "r") as article:
header = article.readline()
title = header[7:]
return "https://en.wikipedia.org/wiki/" + title.r... | abccf37d525eb72d32a62a7f7756c82b443e3d92 | 654,126 |
from typing import Union
from typing import Tuple
from typing import Optional
def utm_region_code(
epsg: Union[int, Tuple[int, int, int]], tidx: Optional[Tuple[int, int]] = None
) -> str:
"""
Construct UTM gridspec identifier.
Examples:
- 32751 -> "51S"
- 32633, 10, 2 -> "33N_10_02... | 41fe8ffa6c195d70bd26bc6b71ab0c12b6929b2f | 654,127 |
def build_mp_addresses_from_constituency(addresses_request_xml):
""" Build a python object containing addresses about an MP """
# print etree.tostring(addresses_request_xml, pretty_print=True)
#ERROR HANDLING
mp_address = {}
mp_address["official_ID"] = addresses_request_xml[0].get('Member_Id')
m... | e9e11526743380edcee5e5d8f2814415ce2392d1 | 654,128 |
def pi_rho(parameters, rho, theta_v):
"""
Returns an expression for the derivative of Exner pressure
with respect to density.
:arg parameters: a CompressibleParameters object.
:arg rho: the dry density of air in kg / m^3.
:arg theta: the potential temperature (or the virtual
pot... | 08deb664e3791ad5e50ab946d850a01772eb3231 | 654,129 |
def unique(a):
"""Find unique elements, retaining order."""
b = []
for x in a:
if x not in b:
b.append(x)
return b | 3455b9934842c426d450019721e6779dcf31f0e8 | 654,130 |
def upload_tenx_library_path(instance, filename):
"""Make a proper file path for uploading 10x library files."""
return "{0}/{1}/{2}".format(
'tenxlibrary',
instance.library.id,
filename
) | aabbb48a7aa082e466e8f623a15e49c52b77bea7 | 654,131 |
import hashlib
import base64
def get_file_hash(filename, algorithm='md5'):
"""Linux equivalent: openssl <algorithm> -binary <filename> | base64"""
hash_obj = getattr(hashlib, algorithm)()
with open(filename, 'rb') as file_:
for chunk in iter(lambda: file_.read(1024), b""):
hash_obj.upd... | ff90f5ce1c7ac0f8b51597e9a93d1fe4d349b4e3 | 654,132 |
def mock_interface_settings_mismatch_subclass(mock_interface_settings, invalid_usb_device_subclass):
"""
Fixture that yields mock USB interface settings that is an unsupported device subclass.
"""
mock_interface_settings.getSubClass.return_value = invalid_usb_device_subclass
return mock_interface_se... | 04f934206eb026763aff90080483366a190880ee | 654,134 |
import torch
def kl_divergence(d1, d2, K=100):
"""Computes closed-form KL if available, else computes a MC estimate."""
if (type(d1), type(d2)) in torch.distributions.kl._KL_REGISTRY:
return torch.distributions.kl_divergence(d1, d2)
else:
samples = d1.rsample(torch.Size([K]))
retur... | b575ad3d7bab340cf0242dd1b4cb0eb52cbc1ba3 | 654,135 |
from typing import Dict
from typing import Any
import json
def format_request(payload: Dict[str, Any]) -> str:
"""Converts the request into json"""
return json.dumps(payload, sort_keys=False, check_circular=False, separators=(',', ':')) | fb5d07c3038617f10f865631cf45bc12d346165b | 654,136 |
import numpy
def prepare_sequences(notes, pitchnames, n_vocab):
""" Prepare the sequences used by the Neural Network """
# map between notes and integers and back
note_to_int = dict((note, number) for number, note in enumerate(pitchnames))
sequence_length = 100
network_input = []
output = []
... | 262558fd73235ac0328944adfaac7ba032d35354 | 654,137 |
def forcerange(colval):
"""Caps a value at 0 and 255"""
if colval > 255:
return 255
elif colval < 0:
return 0
else:
return colval | d0895fcf53788eb3a09a400576f2f6fc472ec654 | 654,138 |
import calendar
def weekday_of_birth_date(date):
"""Takes a date object and returns the corresponding weekday string"""
get_weekday = date.weekday()
weekday = calendar.day_name[get_weekday]
return weekday | 38ac564e7f6607aca5778e036346389b8c0531ef | 654,139 |
def r_to_q_Ri(params, substep, state_history, prev_state, policy_input):
"""
For a 'r to q' trade this function returns the amount of token UNI_R for the respective asset depending on the policy_input
"""
asset_id = policy_input['asset_id'] # defines asset subscript
r = (policy_input['ri_sold']) #am... | 1ce600ae3bb448a60a612bcb4eca8372c8ab3f3d | 654,140 |
import numpy
def relu(sop):
"""
Applies the rectified linear unit (ReLU) function.
sop: The input to which the relu function is applied.
Returns the result of the ReLU function.
"""
if not (type(sop) in [list, tuple, numpy.ndarray]):
if sop < 0:
return 0
else:
... | 906c253c94d2b13db9bde19bf340902466556de8 | 654,141 |
def _add_log_filter(logger, patterns):
"""Add a Filter to the logger based on a regexp of the filter_str."""
def filter_func(logrecord):
return not any(p.search(logrecord.getMessage()) for p in patterns)
logger.addFilter(filter_func) | f4d8b7eecd020c22b308afe57863914d3498942a | 654,142 |
import six
def _hex2rgb(h):
"""Transform rgb hex representation into rgb tuple of ints representation"""
assert isinstance(h, six.string_types)
if h.lower().startswith('0x'):
h = h[2:]
if len(h) == 3:
return (int(h[0] * 2, base=16), int(h[1] * 2, base=16), int(h[2] * 2, base=16))
i... | 6f5cf531c22d8f51107924d6c7f9cc6cca75b5bc | 654,144 |
from typing import Optional
from typing import List
from typing import Set
def select_functions(vw, asked_functions: Optional[List[int]]) -> Set[int]:
"""
Given a workspace and an optional list of function addresses,
collect the set of valid functions,
or all valid function addresses.
arguments:
... | 0e98af6a0e6da85d6e9612cc03cc7389fd5b7555 | 654,145 |
def twenty_seventeen():
"""Come up with the most creative expression that evaluates to 2017,
using only numbers and the +, *, and - operators.
>>> twenty_seventeen()
2017
>>> twenty_seventeen() + twenty_seventeen()
4034
>>> twenty_seventeen() * 3
6051
>>> twenty_seventeen() / 2
... | f337c2d506d432040e1ec4474c7fb673df4357ec | 654,146 |
import torch
def load_model(model, load_path, device):
"""Load torch model."""
model.load_state_dict(torch.load(load_path, map_location = device))
return model | 90e29764afd6ad46522c475c97bca6dc2af93299 | 654,147 |
from typing import Callable
from typing import Optional
from typing import Tuple
def many_parser(
sub_parser: Callable[[str], Optional[Tuple[str, str]]], text: str
) -> Optional[Tuple[str, str]]:
"""
changes a parser by repeating it an indefinite number
of times.
So a parser that parses only "a", will parse "aaa... | b22ecd25ca7a33480d851c8ed5dae867ee801d18 | 654,150 |
import os
import json
def load_json(path: str) -> dict:
"""
This reads and loads json into python from a file.
Args:
path: The path to read from.
Returns:
data: The json data.
"""
if not os.path.exists(path):
return {}
with open(path) as fp:
return json.lo... | 1179a04bbfe99ffae3044fdd1475bfbac225ec6d | 654,151 |
import inspect
import os
def mkprefix(tag = None, cls = None):
"""
Create a temporary file prefix PROGNAME:[CLASSNAME.]FUNCTION-TAG-
:param str tag: a tag to append to the prefixb
:param type cls: an optional type to prefix FUNCTION
:returns: the prefix
:rtype: str
"""
assert isinstan... | 5fe69dae59d8ea66073136db799b6666072bcb5c | 654,152 |
def is_encrypted_value(value):
"""
Checks value on surrounding braces.
:param value: Value to check
:return: Returns true when value is encrypted, tagged by surrounding braces "{" and "}".
"""
return value is not None and value.startswith("{") and value.endswith("}") | ba7a9b8d74f11d85afcfc1f156dd01a4c443d1a9 | 654,153 |
def no_of_misplaced_tiles(node):
"""Function to get the number of misplaced tiles for a
particular configuration
Parameters
----------
node : [list]
[list to check for the heuristics]
Return
------
[int]
[returns the heuristic distance for a particular node]
"""
... | 77e1f06861cb3a3d5c43d07a3133e06feb9a49d5 | 654,154 |
def join_args(*arglists):
"""Join split argument tokens."""
return ", ".join(arg for args in arglists for arg in args if arg) | ab76d123ff8184e6a23294a54c874fad06fdb684 | 654,155 |
def add_book(book_dict: dict, new_book_data: tuple) -> dict:
"""
Function designed by Spencer Green.
Returns a dictionary containing original sets of book data, with the addition of a new book's data set when given the book dictionary that the new book should be added to, and all seven data requirements of ... | 0f6343574fbba7d640fee5a85c3e83253d6bf849 | 654,156 |
def score_by_event_threat_level(event, attributes):
""" Score based on exponential of an event's threat level """
score = 0
if event["threat_level_id"] == "1": # High
score += 100
elif event["threat_level_id"] == "2": # Medium
score += 50
elif event["threat_level_id"] == "3": # L... | d01a224fbc3c4353a43a8c927b93cfcb27d29801 | 654,157 |
def str_para_posicao(p):
"""
Tranformador posicao.
Recebe uma cadeia de caracteres que a representa uma posicao e devolve a posicao.
:param p: string, representacao externa da posicao.
:return: tuple, posicao do tabuleiro de jogo.
"""
return p[0], p[1] | 438bbd62cd5324588a5f48a800a6a9d121e161c6 | 654,159 |
def duplicates(L):
"""
Return a list of the duplicates occurring in a given list L.
If there are no duplicates, return empty list.
"""
dupes = list()
seen = set()
for x in L:
if x in seen:
dupes.append(x)
seen.add(x)
return dupes | 631c77c7ecab6cc22776b4994c4b8fe173cd3ce1 | 654,160 |
def make_regexps_for_path(path):
"""
given a path like a/b/c/d/e.ipynb, return
many regexps mathing this path. specifically,
[^/]+/b/c/d/e.ipy
a/[^/]+/c/d/e.ipy
a/b/[^/]+/d/e.ipy
a/b/c/[^/]+/e.ipy
a/b/c/d/[^/]+
"""
components = path.split("/")
patterns = []
for i in range... | 6caccb8c25a50db4c5c86465fbde98cdca944585 | 654,161 |
def platform_status_interpreter(response=None):
"""
iterprets request status codes results and raises appropriate msg to
be passed to gui
args:
response response return by Platform API
return:
(status, response) tuple (str, dict)
"""
if response is not None:
code = re... | 94de40416eb65c912e785c379c84f22b152d0ace | 654,162 |
def format_math(expr):
"""Replace math symbols with HTML conterparts
:param expr: expression to format
:type expr: str
:returns: replaced string
"""
expr2 = expr.replace(".gt.", ">")
expr2 = expr2.replace(".geq.", ">=")
expr2 = expr2.replace(".lt.", "<")
expr2 = expr2.repl... | b31590c807bfadb698ca1ffef15dbc101bbe05ea | 654,163 |
def order_nuclide_per_a(nucl_list):
"""Orders a list of nuclides' z-a-m ids according to their mass number (a).
Parameters
----------
nucl_list: List of str
List of nuclides' z-a-m ids
"""
changed = True
while changed:
changed = False
for i in range(len(nucl_list) -... | 97ee8000f40ba72f5c7f849431cad1a95ab66e69 | 654,164 |
import requests
def get_github_list(base_url):
"""
Helper to traverse paginated results from the GitHub API.
Used to retrieve lists of tags and releases.
"""
results = []
per_page = 100
page_number = 1
while True:
response = requests.get("%s?per_page=%s&page=%s" %
(... | bc10abf6317802091b7f504f7760ff7628cbf2ac | 654,165 |
import os
def get_legacy_description(location):
"""
Return the text of a legacy DESCRIPTION.rst file.
"""
location = os.path.join(location, 'DESCRIPTION.rst')
if os.path.exists(location):
with open(location) as i:
return i.read() | 50dcfbc25ed27c6597542df7a808216d66daa0ff | 654,166 |
import os
def load_requirements(fname):
"""Turn requirements.txt into a list"""
requirements = []
if os.path.exists(fname):
with open(fname, "r") as fp:
requirements = [line.strip() for line in fp]
return requirements | 550e5cfef3541e5217c1738ccd5ac6b61238a128 | 654,167 |
def add_labels_to_predictions_strict(preds, golds, strict=True):
"""
Returns predictions and missed gold annotations with
a "label" key, which can take one of "TP", "FP", or "FN".
"""
pred_spans = {(s["start"], s["end"]) for s in preds}
gold_spans = {(s["start"], s["end"]) for s in golds}
ou... | 5092b1179225038eac0b33e9997176adc16b4ff8 | 654,168 |
import math
def sigmoid(x: float):
"""Sigmoid function.
Parameters
----------
x
"""
if x < -30:
return 0
if x > 30:
return 1
return 1 / (1 + math.exp(-x)) | 0ad0fa8945e604c98a2674acc0141de0a93f64b1 | 654,169 |
def elem_L(w, L):
"""
Simulation Function: -L-
Returns the impedance of an inductor
Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com)
Inputs
----------
w = Angular frequency [1/s]
L = Inductance [ohm * s]
"""
return 1j*w*L | f853da25556e6246c07e42d513501d8e6b8f29b8 | 654,170 |
def test_cache_memoize_func_attrs(cache):
"""Test that cache.memoize() adds attributes to decorated function."""
marker = 1
value = {}
def original(a):
return (a, marker)
memoized = cache.memoize()(original)
assert memoized.cache is cache
assert memoized.uncached is original
... | 7a49b5bafa47b07a8ee03f70c12585d031fbcc49 | 654,171 |
def connection_mock_factory(mocker):
"""Factory of DB connection mocks."""
def factory(vendor, fetch_one_result=None):
connection_mock = mocker.MagicMock(vendor=vendor)
cursor_mock = connection_mock.cursor.return_value
cursor_mock = cursor_mock.__enter__.return_value # noqa: WPS609
... | ce559c55024e3a2db181ca50509a264888036b16 | 654,172 |
import torch
def nms(boxes, scores, overlap=0.45, top_k=200):
"""
boxes: [num_box, 4]
scores: [num_box]
"""
count = 0
keep = scores.new(scores.size(0)).zero_().long()
# boxes coordinate
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
# area of boxe... | 87bd0f403ae212cd52bf272d50d0831d44658cb2 | 654,173 |
def _get_longest_match(digraph, html_files):
"""Find the longest match between ``digraph`` and the contents of ``html_files``.
Parameters
----------
digraph : str
The ``digraph`` attribute of a :py:class:`Dotfile` object
html_files : list
A list of the Sphinx html files
Returns... | 3a4bbf2adee7e50c2512b724daa7c75c9a8ef6df | 654,174 |
import os
import pathlib
def secrets_file(file_name):
""" First try $HOME/.file_name, else tries /run/secrets/file_name, else raises an exception"""
file_path_in_home_directory = os.path.join(str(pathlib.Path.home()), "." + file_name)
if os.path.exists(file_path_in_home_directory):
return file_pat... | b395091ef70ccb0b46c5714efa66e305ac046640 | 654,175 |
def get_attributes(parent, selector, attribute):
"""Get a list of attribute values for child elements of parent matching the given CSS selector"""
return [child.get(attribute) for child in parent.cssselect(selector)] | f4fecaf7aa16465a63e3e1dd062465b4cc810ad8 | 654,176 |
from typing import List
def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List:
"""
This is a mock function for random.choice(). It generates a deterministic sequence of the
candidates, each one with frequency weights[i] (count: int(len(candidates) * k). If the
sum of total ... | c60aebb59aeb299e6e36b9b7ed24a0fe6e0882b3 | 654,177 |
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str:
"""Put a period in the right place because the MIMIC-3 data files exclude them.
Generally, procedure ICD codes have dots after the first two digits, while diagnosis
ICD codes have dots after the first three digits.
Adopted from: https://... | 988893c9994785fc18d08b5afc2ea644e6fc4201 | 654,178 |
def helper(character_dict, current_dict, word_length, word, word_lst):
"""
:param character_dict: dict, a dictionary that accommodates all the characters from a word
:param current_dict: dict, users should input an empty dictionary
:param word_length: int, the length of the word
:param word: str, th... | bab2382c7c3c790eb9b58c0ddc55fc9efc6cd3f7 | 654,180 |
import glob
import os
def get_image_list(image_dir, recursive=True):
"""
Get list of image paths
:param image_dir: path to image directory
:type image_dir: str
:param recursive: whether or not to use recursive mode
:type recursive: bool
:return: list of image paths
:rtype: list[str]
... | e114b54c1ba0d805b254fff7c999d692d8308306 | 654,181 |
def parse(prog):
"""Parse a Chicken program into bytecode."""
opcodes = []
prog = prog.split('\n')
for i, line in enumerate(prog, 1):
count = 0
for j, word in enumerate(line.split(), 1):
if word != 'chicken':
raise SyntaxError('line %d word %d: expected "chi... | 69e8213d87742f9b1176c9441cc9b7d5c5dd1362 | 654,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.