content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_L_dashdash_d_t(L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t, L_dashdash_b1_d_t, L_dashdash_b2_d_t,
L_dashdash_ba1_d_t):
"""
Args:
L_dashdash_k_d_t: 1時間当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/h)
L_dashdash_s_d_t: 1時間当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/h)
L_dashdash_w_d_t: 1... | 4e51146e4b5e8823dcf8cb39c9b69740c943919d | 643,321 |
def add_one(x: int):
"""Add one to `x`
Args:
x: an integer
"""
return x + 1 | 878d5e795ac45e67b471cbfce6d215c55f44f69f | 643,322 |
def cleanMinim(minimizerResult, weightCount=1):
"""returns "optimal" weight, bias, success (ie: whether vals are trustworthy)"""
results = minimizerResult.x.tolist()
weights = results[:weightCount]
bias = results[weightCount]
return [weights, bias, minimizerResult.success] | 3b2bede5597f45961a5d2410ae33cd7c815f30bf | 643,323 |
def discard_empty_elements(soup, exempt=()):
"""Remove HTML elements that have no/whitespace-only content"""
for tag in soup.find_all():
if len(tag.get_text(strip=True)) == 0 and tag.name not in exempt:
tag.extract()
return soup | 8c50b0bf611a66327631f5fe044a6b52464f14d3 | 643,324 |
from typing import Tuple
def get_color_for_figure(n_vertices: int) -> Tuple[int, int, int]:
"""Returns an RBG color tuple depending on the number of vertices."""
if n_vertices == 3:
return (200, 0, 0)
elif n_vertices == 4:
return (0, 200, 0)
elif n_vertices >= 10:
return (0, ... | d917f8d357f3fd4be2902a970d4224695f3a7dcf | 643,325 |
import math
def dist(p0, p1):
""" Calculates the distance between two xy coordinates, each
each coordinated supplied by a tupel"""
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) | 87f1ce3e1062d1d365bab27066e9d4271e4a251d | 643,326 |
def get_ages(df, sex):
"""Returns the ages of men or women, whom Embarked from section C.
Parameters:
df(pyspark.sql.DataFrame): based on the titanic.csv module
sex(str): for our dataset, it is a binary classification of 'male' or 'female'
Returns: List[float]
"""
... | 93d49fc11845b8dc560c7235e441eb7b101d19d1 | 643,327 |
def add_spelling_errors(dataf, aug, text_col="text"):
"""Applies the keyboard typos to a column in the dataframe."""
return dataf.assign(**{text_col: lambda d: aug.augment(list(d[text_col]), n=1)}) | c8f09d05a31ab08098997ca0f3e4e0763c7b16bb | 643,328 |
def regression_problem(problem):
"""Filter and regression problem."""
regression_problem, _ = problem
return regression_problem | 5fc601e6516a69588654cf670b73a788cf750b49 | 643,329 |
def build_list_from_queryset(query_set):
""" Returns a list of serialized objects """
result = []
for x in query_set:
result.append(x.serialize())
return result | 0859e852234bb78373aea01915d625e7eac6ff08 | 643,330 |
import torch
def expand_z_where(z_where):
"""
:param z_where: batch. [s, x, y]
:return: [[s, 0, x], [0, s, y]]
"""
bs = z_where.size(0)
dev = z_where.device
# [s, x, y] -> [s, 0, x, 0, s, y]
z_where = torch.cat((torch.zeros(bs, 1, device=dev), z_where), dim=1)
expansion_indices = ... | d11586908419793f5290064b1dac70adf6c320b2 | 643,331 |
def pb_dict(message):
"""Create dict representation of a protobuf message"""
return dict([(field.name, value) for field, value in message.ListFields()]) | 6c2d592b44436244ff2d5a508222eace151a3a75 | 643,333 |
def get_resource_bar(avail, total, text='', long=False):
"""Create a long/short progress bar with text overlaid. Formatting handled in css."""
if long:
long_str = ' class=long'
else:
long_str = ''
bar = (f'<div class="progress" data-text="{text}">'
f'<progress{long_str} max="... | c0c1c492a05c96aca31367825f91441f3a1f600b | 643,336 |
def dongers(l, b, i):
"""ヽ༼ຈل͜ຈ༽ノ"""
b.l_say(dongers.__doc__, i)
return True | 4da1f390eedd827b35d09e891359c03958cc4db4 | 643,337 |
import unicodedata
def strip_accents(s):
"""Strip accents of a string.
>>> strip_accents('productName')
'productName'
>>> strip_accents('génèse')
'genese'
>>> strip_accents('preserve-punct-special-chars:;,?!§%$£œ')
'preserve-punct-special-chars:;,?!§%$£œ'
"""
# Mn stands for a non... | c49a0cbdf2a0d238d5175d5a22ed7f0d393a1f9c | 643,338 |
def build_pem(tls_container):
"""Concatenate TLS container fields to create a PEM
encoded certificate file
:param tls_container: Object container TLS certificates
:returns: Pem encoded certificate file
"""
pem = [tls_container.certificate]
if tls_container.private_key:
pem.append(t... | 17ee6b0f389fa9c0a58c464a1957068b8295c1ed | 643,339 |
def to_camel_case(text, split=" "):
"""
Converts text to camel case, e.g. ("the camel is huge" => "theCamelIsHuge")
Args:
text (string): Text to be camel-cased
split (char): Char to split text into
"""
camel_case_text = text
splitter = text.split(split)
if splitter:
c... | 6fc02f75ec86a246c1fed1425b3050304184f7e3 | 643,340 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
lines = []
with open(path, 'r', encoding='utf-8') as file:
for line in file:
lines.append(line.strip())
return lines | 5ea07d7a4e150296c0dda74cf38bea2b476cde11 | 643,341 |
def calc_scale(created_in='matplotlib'):
"""Convert to correct size in pixels.
There's a bizarre issue that makes it so the size of the figure saved out
from matplotlib as an svg is not the same as the SVG element created here.
this wouldn't be an issue (because SVGs scale nicely and all that) except
... | 4dd92fd9d473d84e3c1f6cf78daad4d0d8bd75c2 | 643,342 |
import torch
def check_random_state(seed, device=torch.device("cuda")):
"""Turn seed into a torch.Generator instance
Parameters
----------
seed : None | int | instance of torch.Generator
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a n... | ffd35e2e588be3e49094720b2bea892229f6db45 | 643,343 |
def swedish_translator(firstname, lastname):
"""Check if 'firstname lastname' is a Swedish translator."""
swedish_translators = [
"Linnea Åshede"
]
name = firstname + " " + lastname
if name in swedish_translators:
return True
return False | c23cb86f3f3d434c37fd20a680309244889536d5 | 643,344 |
from pathlib import Path
def get_stock_root(path: Path) -> Path:
"""
Traverse from given path up till root of the system to figure out the root of the
stock repo. A stock repo must be hangar repo, a git repo and must have a head.stock
file. The head.stock file has the information required for stockroo... | 86a80f300a79b7e7e7e9b3f1714127e1f23efa88 | 643,345 |
from pathlib import Path
import shutil
def pwhich(command: str) -> Path:
"""Path to given command.
shutil.which only returns a string.
:returns: Path to command
:rtype: pathlib.Path
"""
path_str = shutil.which(command)
assert path_str, f"{command} not found"
return Path(path_str) | a926850cab35bace6c2187933438c44001d01eeb | 643,347 |
def removeprefix(text, prefix):
"""Removes a prefix from a string.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, returns the original string. This function has been added in
Python3.9 as the builtin `str.removeprefix`, but is defined here to support
previous v... | a3a2cff3cd6b16626760ff332f4a702e20b7fffb | 643,348 |
def _get_class_name(property_repr: str) -> str:
"""
Extract the class name from the property representation.
:param property_repr: The representation
:type property_repr: str
:return: The class name
:rtype: str
"""
return property_repr[: property_repr.index("(")] | 1d99a452288c0d6909692cfb535d614989ba8540 | 643,350 |
def fixed_crops(X, crop_shape, crop_type):
"""
Take center or corner crops of images.
Inputs:
- X: Input data, of shape (N, C, H, W)
- crop_shape: Tuple of integers (HH, WW) giving the size to which each
image will be cropped.
- crop_type: One of the following strings, giving the type of crop to
co... | af35228a6e61e62920a60df7b3fd5431b047ff38 | 643,351 |
def mp0(en):
"""Return the 0th order energy."""
return en.sum() | 64d16e66e58e421c829b093a89c6faeea7026690 | 643,352 |
def date_str(date):
"""The way we show dates in reports."""
return date.strftime('%Y-%m-%d') | 93c3ccec65702f6fb1a8d5aa9818f099dac960e9 | 643,353 |
import copy
def check_match_patterns(p: str, s: str, mapping={}):
"""
Check if string, e.g. 'postmanpostman', matches a pattern, e.g. 'abab'.
@param p: pattern string.
@param s: substring or source input string.
@param mapping: an internal dictionary (initialized as {}) that maps
a charac... | 7b3962700b6e5f5dd8179799cd5c991582627770 | 643,354 |
def strip_numbers(text):
"""Strip numbers from text."""
return ''.join(filter(lambda u: not u.isdigit(), text)) | 1a2bb26577dbf67c7a47435043af0eea4859d926 | 643,355 |
import re
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
p = '\\'+ begin + '(.+)' + '\\'+end
m = re.findall(p, text)
if m:
return m[0]
return '' | 0bceff096118f297648d81681640ddeba2204343 | 643,356 |
def sessions(request):
"""# Cookies prepeocessor """
context = {}
# site_description = 'Asesalud Laboral 2727 C.A'
# context['site_description'] = site_description
return context | 72d1f775518471c17bedcfc85958f476e2a112c0 | 643,357 |
def create_minio_dispatcher_node(name):
"""
Args:
name(str): Name of the minio node
Returns:
dict: A dictionnary with the minio node configuration
"""
return {
"endpoint_url": "http://{:s}:9000/".format(name),
"aws_access_key_id": "playcloud",
"aws_secret_acce... | df313dfa7152944332551dd70aab4b0a0e36ff56 | 643,358 |
def lipschitz_constraint(weights):
"""Lipschitz constraint on weights.
https://arxiv.org/abs/1811.05381
"""
return weights / abs(weights).sum(0) | c22b476013f640ac40d3955fd9f17af1923d239c | 643,359 |
def sum_numbers(n: int) -> float:
"""
BIG-O Notation = O(c)
"""
return (n * (n + 1)) / 2 | dbc23c6b0b58cf90fa0eeb01756d10afac529b84 | 643,360 |
def r_to_depth(x, interval):
"""Computes rainfall depth (mm) from rainfall intensity (mm/h)
Parameters
----------
x : float,
float or array of float
rainfall intensity in mm/h
interval : number
time interval (s) the values of `x` represent
Returns
-------
output... | 6472b75518c4ac9fa709d0efb9d2690cfabdca3f | 643,362 |
def decode_string(string):
"""Decode String Data Type.
The "string" data type encodes binary data as a sequence of undistinguished
octets. Where the range of lengths for a particular attribute is limited to
a subset of possible lengths, specifications MUST define the valid range.
Attributes with le... | bfdfc2d15f161cfa806c21b8bec66d16865e6f1e | 643,363 |
import random
def create_lotto(ran):
"""
gets a list with a random, non repeating sample
"""
lotto = random.sample(range(1,ran+1), ran)
return [str(num) for num in lotto ] | de4f03e7412bc54523a54df36fd75e6e08fa013f | 643,364 |
def RunLintOverAllFiles(linter, filenames):
"""Runs linter over the contents of all files.
Args:
lint: subclass of BaseLint, implementing RunOnFile()
filenames: list of all files whose contents will be linted
Returns:
A list of tuples with format [(filename, line number, msg), ...] with any
viol... | b810322ad99185c06431336688f8e522ae72f8fc | 643,365 |
def import_words(filename):
"""Imports words from a given .txt file and returns it.
"""
# Initialize resuts variable
results = []
# This with statement ensures the file is only open for a certain amount of time.
# This can save RAM and processing speeds in larger projects
# Rename the spri... | 56954768e1bcff7c857c1b104cf1b5dff93e1124 | 643,367 |
def get_transactions_out(data):
"""
Calcul le nombre de prise de vélo qu'il y a eu pour une même station entre 2 points de données
Parameters
----------
data : DataFrame
Activité des stations Vcub
Returns
-------
data : DataFrame
Ajout de colonne 'transactions_out'
... | d06db59486b28f01dd78f5c17072c35c7e5b522c | 643,368 |
def order_to_degree(order):
"""Compute the degree given the order of a B-spline."""
return int(order) - 1 | f2078b7fd7c19202d3bc7826807cbed53cd2a1d7 | 643,369 |
import argparse
def parse_args():
"""Parse the commandline arguments"""
parser = argparse.ArgumentParser(description='This script hides a given text from a file steganographically in a given image. The result is saved to <imagefile>.ste.bmp')
parser.add_argument('filetohide', metavar='textfile', type=argp... | 6b1d9c31589aa7dd7db2d02b454b3f158be5a2fc | 643,370 |
from pathlib import Path
import os
def find_executable_win32(executable):
"""Emulates how cmd.exe seemingly searches for executables."""
def fixcase(p):
return str(Path(p).resolve())
pathext = os.environ.get('PATHEXT', '.EXE')
pathexts = list(x.upper() for x in pathext.split(os.pathsep))
... | 5b7bc12622ea3bc8651c32707c8153235a376b9e | 643,371 |
from typing import Union
def add(num1: Union[int, float], num2: Union[int, float], *args) -> Union[int, float]:
"""Adds given numbers"""
sum: Union[int, float] = num1 + num2
for num in args:
sum += num
return sum | a342065c8d7d6215630b7a4de9e116be71f44f1c | 643,372 |
def _get_object_from_classname(classname, data):
""" Returns an object instance for given classname and data dictionary.
Args:
classname (str): Full classname as string including the modules, e.g. repo.Y if class Y is defined in module repo.
data (dict): dictionary of data used to initialize th... | 28f965a819efcbdc595d2eb4528ed4550459cef5 | 643,373 |
import zlib
def anonymize(user_uid: str, user_ip: str) -> str:
"""Make a user-readable hashed identity."""
if user_uid:
return "Goog#%d" % (zlib.adler32(user_uid.encode()) % 10000,)
return "Anon#%d" % (zlib.adler32(user_ip.encode()) % 10000,) | 3304ac298c605211a4c010dfbf9cc462ddaa315b | 643,374 |
import math
def deg2num(lat_deg, lon_deg, zoom):
"""Convert latitude and longitude to x/y tile coordinates."""
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
... | fad28865630fa73827fd95945783ba4e6269e6e9 | 643,375 |
import random
def hex_rand(n):
"""
Generates a hexadecimal string with `n` random bits.
"""
return "%x" % random.SystemRandom().getrandbits(n) | 8531068ab3c99433d1a244556f548b91f0ea1e2e | 643,376 |
def _default(stmt):
""" Default parameter generator for SQLAlchemy statement. """
return stmt.params | dcc6a85c169b049ffd1e98e42bad903c5d7d87fb | 643,377 |
import os
import subprocess
def run_kmeralign_exe(fast5_path, nuc_sequence, model_file, dest, path_to_bin="./", tmp_directory=None,
delete_tmp_fasta=True, write_failed_alignments=False):
"""Run kmerEventAlign. Generates alignment file
:param fast5_path: path to fast5
:param nuc_seque... | 5944263a8aa7afca224ab0097e47ec2a189e5022 | 643,378 |
def iterate_bus_ids(timestamp, bus_ids):
"""Iterate through bus ID's, skip X's and multiply until you get
the closest timestamp to the original. Then subtract the two timestamps
and multiply by the bus ID that had the closest departing timestamp.
"""
ids = bus_ids[0].split(',')
new_timestamps = ... | 9a1c3ec5fa5ee53d2346a52bcc1e8eb5e8cc536e | 643,381 |
def is_tcp_rst(tcp_data):
"""is TCP RST?"""
return tcp_data["flags"]["rst"] == 1 | 8f6f77c097e054e766863516300830656082084a | 643,382 |
import os
def get_headers():
"""
GitHub API only allows 60 calls per hour from an unauthorized IP.
To authenticate, you need to create a personal access token:
https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
After creating the token, set it as an envir... | 5cb6dae2ef57e687e1a23ef8058839f31b7855c7 | 643,383 |
def load_from_file(file_name, gdrive=None):
""" load training data from file"""
f = open('data/' + file_name, 'r')
data = f.read()
f.close()
return data | 66c4ea8e82c91cd6fc04087466ad33160f7a6989 | 643,384 |
import copy
def merge_dicts(dict1, dict2, recycle=True):
"""
Recursively merge two dictionaries. dict2's values will override dict1's
:param recycle: if True then write the merged dictionary into dict1, otherwise do not modify dict1
:return: a single dictionary
"""
assert type(dict1) is dict... | e390593e62aec70a598be5517e4a0639a243a575 | 643,385 |
import os
def get_modules():
"""Get all available modules"""
basepath = os.path.join(os.path.dirname(__file__), "modules")
return {os.path.splitext(os.path.basename(path))[0]: os.path.join(basepath, path) for path in os.listdir(basepath)} | 1049cd7ecd44323fae910c747935e0a83aeacfbc | 643,387 |
def rec_apply(func, n):
"""
Used to determine parent directory n levels up
by repeatedly applying os.path.dirname
"""
if n > 1:
rec_func = rec_apply(func, n - 1)
return lambda x: func(rec_func(x))
return func | da0af3af1e45bc777d0646526bde04770dd84a10 | 643,388 |
def serialize_config( config_data ):
"""
Generate a .ini-formatted configuration string to e.g. save to disk.
"""
return "[syndicate]\n" + "\n".join( ["%s=%s" % (config_key, config_value) for (config_key, config_value) in config_data.items()] ) | 45cd607770341efa0600c6c253b9a68e8617af0c | 643,389 |
def transpose(list):
"""
a transpose command, rotates a mtrix or equivalent by 90
more like a transpose from R than anything else.
"""
newl = []
try:
rows = len(list[0])
except:
rows = 1 # probably.
cols = len(list)
for row in range(rows):
newl.append([0 for... | 26c4214258872b18407968699abedffa42952861 | 643,390 |
import struct
import fcntl
import termios
def terminal_size():
"""Returns terminal size. Taken from https://gist.github.com/marsam/7268750
but removed win32 support which depends on 3rd party extension.
"""
width, height = None, None
try:
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcn... | 17177228cf768d36eb92a03969e2305560eb681a | 643,392 |
from datetime import datetime
def get_date_from_str(date: str, format_: str = "%d.%m.%y") -> datetime:
"""
Covert string to datetime.
:param date: date as string.
:param format_: format string.
:return: None
"""
return datetime.strptime(date, format_) | df77e0c041451b6c26044fb7e50b25ae2f9240a2 | 643,393 |
def clamp(num):
"""
Return a "clamped" version of the given num,
converted to be an int limited to the range 0..255 for 1 byte.
"""
num = int(num)
if num < 0:
return 0
if num >= 256:
return 255
return num | 8b5eb6160c7763216b4361a75938e9492e9fc97c | 643,394 |
def name(cls):
"""Get a nice name for this object."""
return cls.__class__.__name__ | 9db47520de07a1940320380e5171e4560a60ca71 | 643,395 |
from typing import List
from typing import Tuple
def partition_data(data: List[List[str]]
) -> Tuple[List[List[str]], List[List[str]]]:
"""Partitions data into train and test partitions.
The train partition consists of 80% of the data.
The test partition consists of 20% of the data.
... | ef89fdef573f1cf1807ecac7cdbc5df7cc2a3fef | 643,396 |
def _first(iterable, what, test='equality'):
"""return the index of the first occurance of ``what`` in ``iterable``
"""
if test=='equality':
for index, item in enumerate(iterable):
if item == what:
break
else:
index = None
else:
raise N... | 0421ac9aa5c6c2f0e2f55a913fa49d9bf79edb63 | 643,397 |
def equal_probs(num_values):
"""Make an array of equal probabilities."""
prob = 1.0 / num_values
probs = [prob for i in range(num_values)]
return probs | bf72642ada23a8f408167d1af36b34ec58d85437 | 643,398 |
def _GenerateLocalProperties(sdk_dir):
"""Returns the data for project.properties as a string."""
return '\n'.join([
'# Generated by //build/android/gradle/generate_gradle.py',
'sdk.dir=%s' % sdk_dir,
'']) | e4cf034c1d597650bc2132a183448f8dc4790f76 | 643,399 |
def query_fuel_burn():
"""
Specialized input for how much fuel to burn.
:return: Amount of fuel to burn
:rtype: float
"""
while True:
to_burn = input("How much fuel you want to burn? ")
try:
# Avoid that the game crashes due to bad input
return float(to_... | 24c8b2d964a0d365e53c3bf9d032ae72473a5c38 | 643,400 |
import torch
def NearZero(z):
"""Determines whether a scalar is small enough to be treated as zero
:param z: A scalar input to check
:return: True if z is close to zero, false otherwise
Example Input:
z = -1e-7
Output:
True
"""
return torch.abs(z) < 1e-6 | d8b3458f4cbcba0495a238545cd958fcbb1cab67 | 643,401 |
from operator import add
def add_lists(list_a, list_b):
""" Appends 0 if list A or B is too short. Does the operation '+' to two lists (vectors, etc.) """
if len(list_a) > len(list_b):
# Swap elements if the other is larger
t = list_a
list_a = list_b
list_b = t
return list(... | 6387d61b5875c2c8e9f096045bf36bf039fcc5f4 | 643,402 |
def set_contourf_properties(stroke_width, fcolor, fill_opacity, level, unit):
"""Set property values for Polygon."""
return {
"stroke": fcolor,
"stroke-width": stroke_width,
"stroke-opacity": 1,
"fill": fcolor,
"fill-opacity": fill_opacity,
"title": "{} {}".format... | 0585253cf9fc6a5be2974584c48cbd645d8b4085 | 643,403 |
def beacon(width, height):
"""Populate the board with a beacon."""
initial_state = [
[ False
for y in range(0, height) ]
for x in range (0, width)
]
x = width//2 - 6
y = height//2 - 6
def row_one(x, y):
x = x + 2
initial_state[x][y] = True
x += 1
initial_state[x][y] = True
... | 65315c52c8db6f274be04e3827ec986676cf3dd0 | 643,404 |
def _random_access_reader_memoize(cls):
"""A class decorator for KaldiRandomAccessReader that caches items"""
class _Wrapper(cls):
def __init__(self, path, kaldi_dtype, utt2spk=""):
self.cache_dict = dict()
super(_Wrapper, self).__init__(path, kaldi_dtype, utt2spk=utt2spk)
... | 98862170198e472cb1e4578ae871a5f552ee5db3 | 643,407 |
def _preprocess_padding(padding):
"""Convert keras' padding to tensorflow's padding.
# Arguments
padding: string, `"same"` or `"valid"`.
# Returns
a string, `"SAME"` or `"VALID"`.
# Raises
ValueError: if `padding` is invalid.
"""
if padding == 'same':
padding = 'S... | 6f50f6d99df0f55c7015d60c2abe39165ab736fe | 643,408 |
import os
def get_largest(directory):
"""returns name of largest file in directory"""
largest_so_far = 0
filename = ''
for name in os.listdir(directory):
size = os.path.getsize(os.path.join(directory, name))
if size > largest_so_far:
largest_so_far = size
filena... | 1c390df0c6eb15e9563fbbcb9b6d1eeaf05c7622 | 643,409 |
from bs4 import BeautifulSoup
def check_length(caption: str, limit: int = 1024) -> str:
"""checks length of message against Telegram limits
Args:
caption (str): Message string.
limit (int, optional): Message length limit. Defaults to 1024.
Returns:
str: If caption length minus en... | 4cb4ed635d05eada6ff1e86f9b3d9cb07d0cec28 | 643,410 |
import sys
def get_player_move(towers):
"""Asks the player for a move. Returns (fromTower, toTower)."""
while True: # Keep asking player until they enter a valid move.
print('Enter the letters of "from" and "to" towers, or QUIT.')
print("(e.g., AB to moves a disk from tower A to tower B.)")... | 71423babf23eaba13c41bc7141a22bc0c238ec41 | 643,411 |
def get_target_dimension_order(out_dims, direction_to_names):
"""
Takes in an iterable of directions ('x', 'y', 'z', or '*') and a dictionary
mapping those directions to a list of names corresponding to those
directions. Returns a list of names in the same order as in out_dims,
preserving the order ... | f208f9d7e287a92968ecfebddeee92e6afcd2155 | 643,412 |
import re
def processor_field_string(s, l, tt):
"""
:param s:
:param l:
:param tt:
:return:
"""
# Parse s as simple_ident
if re.match(r"[a-zA-Z_]\w*", s):
return {'type': 'ProcessorField', 'value': s}
else:
raise Exception("Syntax error validating Processor field st... | 5a3d9ef9c0079a077ed6511c9cb02f5f29ec0e46 | 643,413 |
def _read_details_txt(file_contents: str) -> dict:
"""Parse the contents of a daplink-compatible device's details.txt.
Args:
file_contents: The contents of the details.txt file.
"""
output = {}
for line in file_contents.splitlines():
# Ignore any comments in the file contents
... | 8c99a45f06ea412ab27e94d0120535c12c58b938 | 643,414 |
import tqdm
def group_rows_by_trio(combined_str_calls_df):
"""Returns a list of 3-tuples containing the row of the proband, father and mother for full trios, as well as a
2nd list of rows for samples that aren't part of a full trio.
"""
print("Caching paternal & maternal genotypes")
all_rows = {}
... | 0cd5f5b3c89812b287afd96317d01105bccdcd9c | 643,415 |
def add_claims_to_jwt_token(user):
"""
Return the claims that should be added to the JWT token.
This function is called whenever create_access_token is called.
"""
return {
"roles": list(map(lambda r: r.name, user.roles)),
"permissions": list(map(lambda p: p.name, user.permissions))... | cdbb2dc11c54e085d758535e5a7e874251fa0871 | 643,417 |
def create_titoli(conn, titoliTuple):
"""
Create a new record into the titoli table
:param conn:
:param titoliTuple:
:return: titoliRecord id
"""
sql = ''' INSERT INTO titoliCounter('cvid', 'titolo-01', 'titolo-02','titolo-03','titolo-04','titolo-05','titolo-06','titolo-07','titolo-08','titolo-09','titolo-10','t... | f66cc4bc107026650de69d97d57710c9b4778c05 | 643,420 |
def status(level, solved, err):
"""Calculate status from status and err."""
if solved:
if err:
status = 'multiple solution'
else:
status = 'level ' + str(level)
else:
if err:
status = 'no solution'
else:
status = 'give up'
r... | 616c9468e07e978146f7f64bfbcd9acae744a436 | 643,422 |
import math
def calc_woe(self):
"""
calc woe
only have EVENT records or Non-Event records
Parameters
----------
self object
Returns event rate
non event rate
woe value
-------
"""
if self.event_count == 0 or self.non_event_count == 0:
event_rat... | dd1171c9be0e11f9524273e124251f6dc48e8c7b | 643,423 |
def get_target_info(target):
"""Return target information as a version tuple."""
return tuple(int(x) for x in target) | 82010bc8f6bfbc5773ba79e365dabc2f60e42951 | 643,424 |
def to_string(number):
""" Convert float/int to string
>>> to_string(13)
'13'
"""
return str(int(number)) | 7f1d0f90c6de7cde246b755f020a121975330ddf | 643,425 |
import requests
def _send(data):
"""Sends the data to the default tensorflow/serving port.
"""
response = requests.post("http://localhost:8501/v1/models/pose_detection:predict", data=data,
headers={"content-type": "application/json"})
return response | 40aa980c4a8011ee3e3350da365cb184bcfa0172 | 643,427 |
def custom_returns(prices, predicted_prices, is_returns, frequency=252):
"""
Calculates expected return from user fed predicted prices or returns.
:param prices: historical price data
:type prices: pd.DataFrame
:param predicted_prices: predicted data of asset prices or returns
:type predicted_... | d6f26ce5587816c1308bbaac40766b474dfb0e36 | 643,428 |
def binary_search(source, target):
"""二分探索. 計算量: O(log n) """
start, end = 0, len(source)
while start <= end:
index = (start + end) // 2 # index: 中央値
if source[index] == target:
# 見つかったらそのindexを返す
return index
elif source[index] < target:
# 検索範囲... | c9e9adf63149deb74112d5beafd27eb412bc3eb5 | 643,429 |
from typing import Tuple
from typing import List
def cell_regions(
x_len: float, y_len: float, factor: float = 2 / 3, buffer: float = 3.5
) -> Tuple[List[List[float]], ...]:
"""Calculate the boundary of the different regions used for classification.
When running an interface simulation there is a region ... | 91fedc00ee899175b5bbfdc523ba59510aa0462b | 643,430 |
import time
def TimeStamp():
"""Create a formatted time stamp of current time
@return: Time stamp of the current time (Day Month Date HH:MM:SS Year)
@rtype: string
"""
now = time.localtime(time.time())
now = time.asctime(now)
return now | 83a2e81e3ed9e3c578bf732231574f4492e10d9e | 643,431 |
def notas(* val, sit=False):
"""Função para analisar notas e situações do aluno.
Keyword Arguments:
val {list} -- uma ou mais notas dos alunos (aceita varias)
sit {bool} -- (opcional) Indica ou não se deve mostrar a situação do aluno (default: {False})
Returns:
[dict] -- dicionário... | 4387ef1096bef4e55fcf6d1138d61991730a93b8 | 643,432 |
def get_post_match(child, args, index, child_dict):
"""
matching function for post nodes
Args:
child: the matched child from which we check post tokens.
args: list of incoming tokens.
index: position in args list where comparison continues.
child_dict: the dictionary that is ... | e1ed82c7e83e37bea3c812be7c6a5c1e657d75b1 | 643,434 |
import subprocess
def git_commit_count():
""" Returns the output of `git rev-list --count HEAD` as an int.
Note: http://programmers.stackexchange.com/a/151558 """
return int(subprocess.check_output(["git", "rev-list", "--count", "HEAD"])) | 5d8d49530cf4df2f9257a7d907e501a01a0ecc84 | 643,435 |
def cursorNextOrNone(cursor):
"""
Given a Mongo cursor, return the next value if there is one. If not,
return None.
:param cursor: a cursor to get a value from.
:returns: the next value or None.
"""
try:
return cursor.next() # noqa - B305
except StopIteration:
return N... | 8445490505c74ac128da94de41ad805019e05812 | 643,436 |
def wordinset_wild(word, wordset, wild='*'):
"""Return True if word not in wordset, nor matched by wildcard.
Note: accepts a wildcard (default '*') for '0 or more letters'.
"""
if word in wordset:
return True
else:
if word[-1] != wild:
word += wild
while len(word... | 7c94e4082437fb7389deb05a525df365b4b7fa17 | 643,437 |
from typing import Tuple
def _parse_block(block: str) -> Tuple[str, str]:
"""Extract question and answer from a text block."""
question_start = block.find('\n', block.find('Вопрос')) + 1
question_end = block.find('\n\n', question_start)
question = block[question_start:question_end]
question = " ".... | 033c2e94e942ce2d570cc39d5cef26ce2c5685d4 | 643,438 |
def reroute_to_dedicated(tool_spec, user_roles):
"""
Re-route users to correct destinations. Some users will be part of a role
with dedicated training resources.
"""
# Collect their possible training roles identifiers.
training_roles = [role for role in user_roles if role.startswith('training-')... | 3d7c1225c7e207e38424efb364654504bd5fb070 | 643,439 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.