content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def returns_int(indata: int) -> int:
"""This function returns an int"""
return indata | 894ce7f0094b61f8fc93fbe793ce79d3a3ac9c35 | 542,927 |
def compose1(f, g):
""""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h | 1613e41cf70446755586b4edf0093c1ed75c3915 | 623,442 |
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool:
"""Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s).
Used primarily for checking against the registered command data from Discord.
Will not work great if values inside the dictionary ca... | 46b537ea1353c29c9ada561a0469b8f6658501c3 | 651,036 |
def sort_into_sections(events, categories):
"""Separates events into their distinct (already-defined) categories."""
categorized = {}
for c in categories:
categorized[c] = []
for e in events:
categorized[e["category"]].append(e)
return categorized | 74cb24b59e3079310d08383d535f077d626ba865 | 538,101 |
def _FormatTime(t):
"""Formats a duration as a human-readable string.
Args:
t: A duration in seconds.
Returns:
A formatted duration string.
"""
if t < 1:
return '%dms' % round(t * 1000)
else:
return '%.2fs' % t | 738b8fb6e31b0fdf56d314a9c9e1155f82030003 | 354,779 |
def lookup_dashboard(stackdriver, display_name):
"""Find the dashboard definition with the given display_name."""
parent = 'projects/{0}'.format(stackdriver.project)
dashboards = stackdriver.stub.projects().dashboards()
request = dashboards.list(parent=parent)
while request:
response = request.execute()
... | 5633e6af36fbf927b881aa027ade1f84bd130164 | 505,356 |
def _extract_header_alignment(header, alignments, nt):
"""
With a provided complete header, extract the alignment and process to correct format for fill in zeros
:param header: reference sequence header string
:param alignments: alignments dictionary
:return: sorted_fwd_alignment, sorted_rvs_alignm... | 414ad2ddcf5f876052e737fe27acd7430056846e | 214,069 |
def layer1(self) -> tuple:
"""
Solve first layer corners.
Returns
-------
tuple of (list of str, dict of {'FIRST LAYER': int})
Moves to solve first layer, statistics (move count in ETM).
Notes
-----
A corner on the top layer with a white sticker is rotated so that
it is dir... | 230e44363c57d4429691ca8853aea877a73aa322 | 497,880 |
from typing import Iterable
def get_item(collection, item_path):
"""Retrieve an item from a component's collection, possibly going through
multiple levels of nesting.
:param collection: the collection where the item resides.
:param item_path: a string with the name of the item, or an iterable of
... | 20564a36f384b1813b144bc2e98d6f9335233bf8 | 535,499 |
import json
def response_success(data):
"""Return success response."""
body = {
"error": None,
"code": 200,
}
data.update(body)
return {
"statusCode": 200,
"body": json.dumps(data)
} | 7a432e8a8a9c792cd1a9c9a71036a05994815b05 | 508,351 |
import json
def load_stats(filename):
"""
Loads statistics.
:param filename: File to be loaded.
:return: users, user_stats, global_stats arrays
"""
with open(filename, 'r', encoding='utf-8') as jsonfile:
data = json.load(jsonfile)
return data["users"], data["user_stats"], data[... | 5799e900282ece3cd7ec87164d785b206d1504b6 | 217,326 |
def get_training_cost(
model_path: str,
dataset_path: str,
train_batch_size: int,
run_stats: dict,
gpu_cost_per_hr: float = 0.35, # GCP cost for Tesla T4
) -> float:
"""
Return total cost to train model using GCP compute resource
"""
total_time_s = int(run_stats["hyperopt_results"][... | 97ba0baa299bd7223fe60a262dbd4e3dc5cb4897 | 471,878 |
import io
def make_csv_file(fieldnames, datarows):
"""Helper function to make CSV file-like object using *fieldnames*
(a list of field names) and *datarows* (a list of lists containing
the row values).
"""
init_string = []
init_string.append(','.join(fieldnames)) # Concat cells into row.
f... | f8af4554d16bb5eb5e86abbeff54073128d8ef32 | 194,031 |
def zero_float(string):
"""Try to make a string into a floating point number and make it zero if
it cannot be cast. This function is useful because python will throw an
error if you try to cast a string to a float and it cannot be.
"""
try:
return float(string)
except:
return 0 | 075a49b53a0daf0f92072a5ec33f4b8240cc6885 | 702,546 |
def GetEst(coeff):
"""Extracts the estimated coefficient from a coeff tuple."""
name, est, stderr = coeff
return est | bda62c49252d4078879736046fa606d5d5c1ee33 | 260,136 |
from typing import Callable
from typing import Iterable
def zip_with(func: Callable, *iters) -> Iterable:
"""`zip` all the iters and apply function `func` to each of them
"""
return map(func, zip(*iters)) | 9e0c1635d9f11b133fa54c47310125fa480b91b6 | 633,578 |
import random
def random_bytes(size):
"""Returns a byte array with the given size that contains randomly
generated bytes."""
return bytes(random.randrange(0 ,256) for i in range(size)) | 050945884d4110c43c9ab6c0cf0da2f207d7d046 | 315,099 |
def _formulate_smt_constraints_final_layer(
z3_optimizer, smt_output, delta, label_index):
"""Formulates smt constraints using the logits in the final layer.
Generates constraints by setting the logit corresponding to label_index to be
more than the rest of the logits by an amount delta for the forward pass ... | 1031db93f7821ad8cce1bdcec4a9f6687c582e4c | 525,012 |
def taxdump_from_text(text):
"""Read taxdump from comma-delimited text.
Parameters
----------
text : list of str
multi-line, comma-delimited text
columns: taxId, name, parent taxId, rank
Returns
-------
dict of dict
taxonomy database
"""
res = {}
for lin... | 8213b1aa7f72ef4b1b99e7f8b3eba7f0d6db4721 | 511,773 |
import re
def parse_cg_history(fh):
"""Parse CG history
Keyword Arguments:
fh -- file handle
Returns:
a list of tuples:
[e_1, ..., e_N]
where:
e_i = (i, F, resX, resf|eta)
"""
# step 24 F: -26.34592024007 res: X,fn -6.84493e-04 -8.38853e-01
# step 218 F: -60.5104973... | 7de0778c5dc0efa2909d8dcc1e8169ec0723b879 | 268,450 |
import re
def strip_path(path_to_strip="", uri=""):
"""Strip a particular path from a URI.
Keyword Arguments:
path_to_strip {str} -- Path to remove from the URI (default: {""})
uri {str} -- URI requested (default: {""})
Returns:
{str} -- URI with path stripped out
"""
ret... | 712bb96da31a8c7784b3c1f9de6c0bdb43e6c399 | 204,639 |
def nested_dict_traverse(path, d):
"""Uses path to traverse a nested dictionary and
returns the value at the end of the path.
Assumes path is valid, will return KeyError if it is not.
Warning: if key is in multiple nest levels,
this will only return one of those values."""
val = d
for p in path:
val... | 1f7e4744585ae134ab1f2eface9284756526ed65 | 698,335 |
def _genprop(converter, *apipaths, **kwargs):
"""
This internal helper method returns a property (similar to the
@property decorator). In additional to a simple Python property,
this also adds a type validator (`converter`) and most importantly,
specifies the path within a dictionary where the value... | d4c916df257f5271fc35d7cb993488b1011df9ed | 254,299 |
def split_usn(usn):
"""Split a USN into a UDN and a device or service type.
USN is short for Unique Service Name, and UDN is short for Unique Device
Name. If the USN only contains a UDN, the type is empty.
Return a list of exactly two items.
"""
parts = usn.split('::')
if len(parts) ... | 29811dc8430cf3673a99a1acf8640b8f73c3b1ff | 422,244 |
def has_special_character(password: str) -> bool:
""" checks if password has at least one special character """
return any(char for char in password if not char.isalnum() and not char.isspace()) | 505ee2c9f9c139d587c91acf5dc456c017d06924 | 215,303 |
def format_toml(data):
"""Pretty-formats a given toml string."""
data = data.split('\n')
for i, line in enumerate(data):
if i > 0:
if line.startswith('['):
data[i] = '\n{0}'.format(line)
return '\n'.join(data) | 7f429cb40720f624ceb52cf837a6e523a8cdfb5c | 362,420 |
def get_line_equation(p1, p2):
"""
Solve the system of equations:
y1 = m*x1 + b
y2 = m*x2 + b
This translates to:
m = (y2 - y1) / (x2 - x1)
b = y1 - m*x1
Input:
p1: first point [x1, y1]
p2: second point [x2, y2]
returns: slope, intercept
"""
m = (p2[1] ... | 064a56a62d4295b8ad3c8c0d62ebaefdf0d36678 | 435,612 |
def unscalar_lex(arg):
"""Lexically unwraps a string containing a string or numeric constant,
such as are created by the PyTT parser.
If the argument (presumed to be a string) starts with the string "scalar("
and ends with the string ")", evaluates and returns the portion of the
argument between th... | 5dc13d91ac497269e374b5c2703a7b8debbaa2a1 | 192,523 |
import click
def _prompt(*args, allow_empty=False, **kwargs):
"""
Print a breakline before prompting for input and normalize values to accept
empty input when requested by caller.
Args:
args (any): arguments to click.prompt
allow_empty (boolean): whether to allow prompt to accept empt... | 2e007ea744fd993bc69971208fc70b34e9ebf63e | 567,755 |
def load_candidate_bond_changes_for_one_reaction(line):
"""Load candidate bond changes for a reaction
Parameters
----------
line : str
Candidate bond changes separated by ;. Each candidate bond change takes the
form of atom1, atom2, change_type and change_score.
Returns
-------... | 1dfe4c5e7f53a86e5aaa9d8a7eb3a44c3b2599b7 | 347,335 |
def truncate(x, maxlen=1000):
"""
>>> truncate('1234567890', 8)
'1234 ...'
>>> truncate('1234567890', 10)
'1234567890'
"""
if len(x) > maxlen:
suffix = ' ...'
return '%s%s' % (x[:maxlen - len(suffix)], suffix)
else:
return x | 2923d853b0e3d53aba3bd180f0790d14f143b829 | 492,344 |
def find_tag_column_pairs(tags):
"""
Creates a dict, where k = the user-created tag names, like 'life',
v = db column names, like 'tag1'}
"""
all_tag_columns = {}
counter = 0
for tag in tags:
counter += 1
all_tag_columns[str(tag)] = "tag" + str(counter)
return all_tag_co... | 80984628b3f2daf2fb761a5e958452d5e5521efd | 595,337 |
def fetch_courses(job_config, data_bucket, data_dir ="morf-data/"):
"""
Fetch list of course names in data_bucket/data_dir.
:param job_config: MorfJobConfig object.
:param data_bucket: name of bucket containing data; s3 should have read/copy access to this bucket.
:param data_dir: path to directory ... | 3fe3ed0670d3d22950d8be393404fc9665c4334d | 67,916 |
def markdown_paragraph(text: str) -> str:
"""Return the text as Markdown paragraph."""
return f"\n{text}\n\n" | 38f2a790f565e6417d73a2b2430cc0c5efabc27a | 35,027 |
def height_to_imperial(height):
"""Converts height in cm to feet/inches."""
height_inches = height / 2.54
feet = int(height_inches) // 12
inches = height_inches % 12
return feet, inches | bdec165de4b1576e53f2c81e6d3fc9d60b82d8ee | 19,707 |
def build_stop_names(shape_id):
"""
Create a pair of stop names based on the given shape ID.
"""
return ["Stop {!s} on shape {!s} ".format(i, shape_id) for i in range(2)] | fad14e29bfdd0471d048f9b731a63eba65ad4439 | 336,905 |
def rotl(x, count):
"""Rotates the 64-bit value `x` to the left by `count` bits."""
ret = 0
for i in range(64):
bit = (x >> i) & 1
ret |= bit << ((i + count) % 64)
return ret | 6bba2bf109f9ddd0f9b4c202c3192e14a0cd625f | 31,701 |
import shutil
import logging
def safe_move(src, dst):
"""
Attempt to move a directory or file using shutil.move()
Returns true if it worked, false otherwise.
"""
try:
shutil.move(src, dst)
return True
except Exception as e:
logging.error(f"An error occured while trying ... | 1ef2688d99ab214c6882ead35218bca80d0c3555 | 561,612 |
def py2(h, kr, rho, cp, r):
"""
Calculate the pyrolysis number.
Parameters
----------
h = heat transfer coefficient, W/m^2K
kr = rate constant, 1/s
rho = density, kg/m^3
cp = heat capacity, J/kgK
r = radius, m
Returns
-------
py = pyrolysis number, -
"""
py = h ... | 5a9868feeeaa5a99cf06e2c47671beeab7d45156 | 654,542 |
from datetime import datetime
def get_current_datetime() -> datetime:
"""
Generate datetime in UTC timezone.
Returns:
datetime: datetime.
"""
return datetime.utcnow() | f93af05b4660306545e2e505c50a7fd016ec2773 | 635,359 |
import typing
def days(day: typing.Union[str, int]) -> str:
"""
Humanize the number of days.
Parameters
----------
day: Union[int, str]
The number of days passed.
Returns
-------
str
A formatted string of the number of days passed.
"""
day = int(day)
if da... | f6ae38fa8d8a9a9679854af52716c38e57249061 | 349,108 |
def palindrome(word):
"""
Verify if a word is a palindrome. The palindrome are words
or phrases that you can read equally in both sides.
Whether is palindrome returns True else False
>>> palindrome("radar")
True
>>> palindrome("taco cat")
True
>>> palindrome("holah")
False
... | 5fa97cf41ddc750b1fb1c1c808b829984ed29bbe | 94,783 |
from typing import NamedTuple
def _to_dict(conf: NamedTuple):
"""Convert nested named tuple to dict."""
d = conf._asdict()
for k in conf._fields:
el = getattr(conf, k)
if hasattr(el, '_asdict'):
d[k] = _to_dict(el)
return d | 1ef32f61b3903ace12c80de78df934a50d6d14e1 | 657,284 |
def hide(ans):
"""
To hide the answer form the user.
:param ans: str, the initiated random word
:return riddle: str, has an identical length of ans but with each alphabet covered with '-'
"""
riddle = ''
for i in range(len(ans)):
riddle += '-'
return riddle | 651724593b59ee1d51404d5092a6d109ac3a04df | 144,436 |
def _policy_profile_generator(total_profiles):
"""
Generate policy profile response and return a dictionary.
:param total_profiles: integer representing total number of profiles to
return
"""
profiles = {}
for num in range(1, total_profiles + 1):
name = "pp-%s... | ad7c6eaf9cb9230d74eb0edef7f2051b3b2d181d | 363,555 |
def valid_url(string):
"""Checks if the given url is valid
Parameters
----------
string: str
Url which needs to be validated
Returns
-------
bool
"""
if string and (string[:7] == "http://" or string[:8] == "https://"):
return True
return False | 06ac6a0f62ffd6c0dcbfc07603d84f3e3151eb13 | 331,084 |
def well_row_name(x):
"""Return a well row name for the given zero-based index"""
if x < 26:
return chr(ord("A") + x)
return chr(ord("A") + int(x / 26) - 1) + chr(ord("A") + x % 26) | 76beaba56e67ff1a3b107ea0e47af6f120426d60 | 465,504 |
def crop(img, xmin, xmax, ymin, ymax):
"""Crops a given image."""
if len(img) < xmax:
print('WARNING')
patch = img[xmin: xmax]
patch = [row[ymin: ymax] for row in patch]
return patch | d0b3e628fadd5d5e5cb742a406ead69ed5fd0e3d | 396,147 |
def get_col_names_and_indices(sqlite_description, ignore_gt_cols=False):
"""Return a list of column namanes and a list of the row indices.
Optionally exclude gt_* columns.
"""
col_indices = []
col_names = []
for idx, col_tup in enumerate(sqlite_description):
# e.g., each col in sqlite... | 804d1b80e56ba043a68ff7fa899a8b111a6cd74f | 517,634 |
def aoec_lung_concepts2labels(report_concepts):
"""
Convert the concepts extracted from lung reports to the set of pre-defined labels used for classification
Params:
report_concepts (dict(list)): the dict containing for each lung report the extracted concepts
Returns: a dict containing for each lung report the ... | 37d6ae91c688e0ff02259dd2c3c64d3fdf0b7921 | 355,002 |
def isPandigital10(s):
"""Check if number is pandigital from 0-9, i.e. that it has all digits
from 0 to 9."""
if len(s) != 10:
return False
for i in range(0, 10):
if s.find(str(i)) == -1:
return False
return True | 6529bb56e665cf4fde98624d9d58dbf2b3575f22 | 174,291 |
import collections
import itertools
def merge_mutation_sets(
mutations_a,
mutations_b):
"""Constructs all possible merges of mutations sets `mutations_a` and `mutations_b`.
Merging two mutation sets involves combining all the mutations together into
a combined mutation set. A valid mutation set has mut... | 7294a96ef758e4aebef21ca50950f406c16370a5 | 173,860 |
def same_keys(a, b):
"""Determine if the dicts a and b have the same keys in them"""
for ak in a.keys():
if ak not in b:
return False
for bk in b.keys():
if bk not in a:
return False
return True | 841a6d715fdfcefb9a2557e01b7ccb586fd62c06 | 44,053 |
def print_badges(badges):
"""Return TeX lines for a list of badges."""
lines = []
for badge in badges:
if badge == 'dividertag':
lines.append('\n\\divider\\smallskip\n\n')
elif badge == 'br':
lines.append('\\\\\\smallskip')
else:
lines.append('\\cv... | c13a3dafe96afd136972a13c13548910e357bb31 | 339,625 |
def modeladmin_register(modeladmin_class):
"""
Method for registering ModelAdmin or ModelAdminGroup classes with Wagtail.
"""
instance = modeladmin_class()
instance.register_with_wagtail()
return modeladmin_class | 7694455b26a84e76f313c2121ebb4721fc658d19 | 507,684 |
def numpy_array_reshape(var, isSamples, n_dim):
"""
Reshape a numpy to a give dimensionality by adding dimensions with size one in front (broadcasting). If *isSamples* is true, keep the first dimension.
:param var: the variable to be reshaped.
:type var: numpy.ndarray
:param isSamples: whether the ... | 8d31d3e8856a71cd6b66d9ae5058dda33556fd28 | 552,818 |
def internal(fn):
"""
Decorator which does not affect functionality but it is used as marker
which tells that this object is not interesting for users and it is only used internally
"""
return fn | fa9a31962a4f45f7794ec42fc4f2507c52c4535a | 22,312 |
def determine_refframe(phdr):
"""Determine the reference frame and equinox in standard FITS WCS terms.
Parameters
----------
phdr : `astropy.io.fits.Header`
Primary Header of an observation
Returns
-------
out : str, float
Reference frame ('ICRS', 'FK5', 'FK4') and equinox
... | 0d15f35c044cb993e7568988aebbec15308e2656 | 123,234 |
import hashlib
def hash_md5(file):
"""
返回文件file的md5值
:param file: 文件
:return: md5值
"""
hasher = hashlib.md5()
# chunks()是方法,之前把括号漏了
for chunk in file.chunks():
hasher.update(chunk)
return hasher.hexdigest() | 4475e89adb963c7298eb8ab9066421c082d0e7db | 107,377 |
def get_exponent(bits):
"""Given a value representing a float (in the machine), return the exponent.
"""
return ((bits >> 23) & 0xff) | e4e9d225cee5b86e2da5042228eebf9f2c13fa8e | 485,390 |
import re
def booleannet2bnet(rules):
"""Converts BooleanNet rules to BNet format.
e.g., an input of
"A*=B or C and not D"
returns
A, B | C & !D
Also replaces ~ with !
Parameters
----------
rules : str
BooleanNet formatted rules.
Returns
-------
str
... | d7a2c4a8d291d71690162dd0773d525ab9014a5b | 402,704 |
def loadraw(path, static=False):
"""Loads raw file data from given path with unescaped HTML.
Arguments:
path (str): Path to the file to read.
static (bool):
If True, all the `{` and `}` will be replaced
with `{{` and `}}` respectively.
Example:
>>> # $ cat p... | 438d4128bd72a81f46e581984d1cf53b3d11254a | 19,581 |
def iptup_to_str(formatted_tuple: tuple[str, int]) -> str:
"""
Converts a tuple IP address into a string equivalent
This function is like the opposite of ``ipstr_to_tup``
:param formatted_tuple: A two-element tuple, containing the IP address and the port.
Must be in the format (ip: str, port: ... | ff3cb457a1396935ee0c9d6834fa8f17c65c4970 | 693,762 |
def define_names(r=11,c=11):
"""
Funzione che definisce i nomi delle coordinate degli spettri sul sample. I nomi sono del tipo r1c1,r1c2, ecc.
Come default usa 11 colonne e 11 righe. Il primo nome è wn, che sta per wave number.
"""
#definisco i nomi da assegnare ai punti delli spettri di sampling
... | df32bf9b1b8520269efb14ed6f27f8aa011e182a | 169,396 |
def filter_recursive(x_or_iterable):
"""
Filter out elements that are Falsy (where bool(x) is False) from
potentially recursive lists.
:param x_or_iterable: An element or a list.
:return: If x_or_iterable is not an Iterable, then return x_or_iterable.
Otherwise, return a filtered version of x_o... | 937cc5f1e82d1839c4dde7f29f6106f0a707b64f | 304,769 |
def E(q, r0, x, y):
"""Return the electric field vector E=(Ex,Ey) due to charge q at r0."""
den = ((x-r0[0])**2 + (y-r0[1])**2)**1.5
return q * (x - r0[0]) / den, q * (y - r0[1]) / den | 9934e43075016ea4377395fdf5ee260769d40986 | 156,650 |
import ipaddress
def prefix_to_network(prefix):
"""Convert an IP prefix to an IP-address and network mask."""
ipaddr = ipaddress.ip_interface(prefix) # turn into ipaddress object
address = ipaddr.ip
mask = ipaddr.netmask
return address, mask | ac521405d5bdd90f082bc4d0e5f434b7a5b7f3f7 | 697,476 |
def make_subsequences(x, y, step=1, max_len=2 ** 31):
"""
Creates views to all subsequences of the sequence x. For example if
x = [1,2,3,4]
y = [1,1,0,0]
step = 1
the result is a tuple a, b, where:
a = [[1],
[1,2],
[1,2,3],
[1,2,3,4]
]
b = [1,1,0,0]
Note that only a ... | 6b3b14de8548fa1ec316273a48eb22ebc975021c | 102,130 |
def list_to_string(string_arg):
"""
Some methods arguments parsing of a list to a string.
"""
if string_arg:
return '.'.join(string_arg)
else:
return string_arg | 59bb76e8f9d4956a55ab89441c3a18229e6a5c92 | 221,822 |
from typing import Dict
def get_example_brand_map() -> Dict[str, str]:
"""
Return notebooks brand mapping based on simple regex.
The mapping is from patterns found in menu_items to the items brand.
The returned dictionary {key, value} has the following structure:
key is the regex search pattern
... | 171a3b5de7c3a8f893a3b4f632f62072e38ca5d5 | 680,002 |
def make_name_from_str(string, max_size=100):
""" Return a name that is capitalized and without spaces """
return ''.join(
'%s%s' % (w[0].upper(), w[1:])
for w in string.split()
)[:max_size] | c2492dc09977a6a1ae1ff2476f466825b055d49d | 360,131 |
def addVectors(v1, v2):
"""assumes v1, and v2 are lists of ints.
Returns a list containing the pointwise sum of the elements
in v1 and v2. For example, addVectors([4, 5], [1, 2, 3]) returns
[5, 7, 3], and addVectors([], []) returns []. Does not modify inputs."""
if len(v1) > len(v2):
... | e23cf80cd905b0a7ce957c0f569ae955c14161fc | 444,105 |
def protobuf_name(entry):
"""
Return the protocol buffer field name for input metadata entry
Returns:
A string. Ex: "android_colorCorrection_availableAberrationModes"
"""
return entry.name.replace(".", "_") | 54c63f5f616abd224857986b893b7e9c8ee3f8d6 | 372,827 |
from typing import Counter
def compareLists(a, b):
"""
Compare two lists, return true if they are just the same under a permutation.
Parameters
----------
a, b : list of any
The two lists to compare.
Returns
bool
whether a and b are the same under a permutation.
"... | f23e2d1cf6e9c434c93f95ead4e548e05c4a912d | 585,004 |
def get_new_size_zoom(current_size, target_size):
"""
Returns size (width, height) to scale image so
smallest dimension fits target size.
"""
scale_w = target_size[0] / current_size[0]
scale_h = target_size[1] / current_size[1]
scale_by = max(scale_w, scale_h)
return (int(current_size[0]... | e0b42eab3d35ba5c662282cab1ffa798327ad92a | 704,801 |
import csv
def csv2dict(fname):
"""
read a csv file to a dict when keys and values are
separate by a comma
Parameters
----------
fname: csv fname with two columns separated by a comma
Returns
-------
a python dictionary
"""
reader = csv.reader(open(fname, 'r'))
d = {}
for ro... | 92ea03145e70c3358b44e62cf926eef8366eac58 | 135,514 |
def jaccard(a, b):
"""
Jaccard stability index
"""
a, b = set(a), set(b)
return 1.*len(a.intersection(b))/len(a.union(b)) | 81cc164d4a78dd26ca6158539e0c1e3c06bdce60 | 577,362 |
def abbrev_key (
key: str,
) -> str:
"""
Abbreviate the IRI, if any
key:
string content to abbreviate
returns:
abbreviated IRI content
"""
if key.startswith("@"):
return key[1:]
key = key.split(":")[-1]
key = key.split("/")[-1]
key = key.split("#")[-1]
return key | 6cb2058f32d6320f1be118d8831cc074cd0cc56f | 17,608 |
def cell_from_screenspace(screenspace_coords: tuple, tile_size: int):
"""
Helper function to convert from screenspace coordinates to tile row and column.
Calculations based on texture base tile size; no boundary checking is performed.
Parameters:
screenspace_coords (Tuple[float, float]): The X ... | 717f2f6e60a9bd973ca32bba1c7173734fcb7266 | 595,175 |
def count_false_positives_for_given_class(class_list, class_c):
"""
Count the False positives for the given class
"""
false_positive_count = 0
for item in range(len(class_list)):
if item != class_c:
false_positive_count += class_list[item]
# Return the false positive count... | 24f5050bdc72cd2c9625f79accdb25a1151ccd08 | 518,614 |
import json
def loadJsonFile(filePath: str) -> dict:
"""
Load json file.
:param filePath: File path.
:type filePath: str
:returns: Json data.
:rtype: dict
"""
with open(filePath) as fp:
data = json.load(fp)
return data | 1cb95ce6b904e69edd88704fedcf963d93b3c1f1 | 97,471 |
import string
def clean_document(document):
"""
Removes punctuation from a document, and converts everything to lowercase
"""
return document.translate(None, string.punctuation).lower() | bfbbc4fae38078715b9c3376f977ce5281547af8 | 452,676 |
def f2(a, b):
"""Returns True exactly when a is False and b is True."""
if not a and b:
return True
else:
return False | f4b0dd7d7c9199ee11bad770e8fdb5ee69080be4 | 367,297 |
def expose(operation=None, action='GET', is_long=False):
""" A decorator for exposing methods as BLL operations/actions
Keyword arguments:
* operation
the name of the operation that the caller should supply in
the BLL request. If this optional argument is not supplied,
then the op... | fd10b3460e575c673f68ea6a76f71d27c845c8b7 | 433,779 |
def common_prefix(n: int) -> str:
"""
For a given number of subgraphs, return a common prefix that yields around
16 subgraphs.
>>> [common_prefix(n) for n in (0, 1, 31, 32, 33, 512+15, 512+16, 512+17)]
['', '', '', '', '1', 'f', '01', '11']
"""
hex_digits = '0123456789abcdef'
m = len(he... | 6977533e5f3679335a9ab9a80ae39c75edf0dd04 | 470,942 |
def is_improvement(
best_value: float,
current_value: float,
larger_is_better: bool,
relative_delta: float = 0.0,
) -> bool:
"""
Decide whether the current value is an improvement over the best value.
:param best_value:
The best value so far.
:param current_value:
The cu... | a8ea7f1bbf6e44f52cbda827b153b4286c86645a | 287,500 |
def title_or_url(node):
"""
Returns the `display_name` attribute of the passed in node of the course
tree, if it has one. Otherwise returns the node's url.
"""
title = getattr(node, 'display_name', None)
if not title:
title = str(node.location)
return title | 7a2a90dc683a77490ed005b66d2666151421f940 | 104,234 |
from typing import List
from typing import Any
def reverse(array: List[Any]) -> List[Any]:
"""
Returns a new array with elements in a reverse order of the input array.
The first array element becomes the last, and the last array element
becomes the first.
"""
return array[::-1] | 3a6738f84b4dadbca41a4aa6d8c489a47600216f | 348,371 |
def get_menu_item_params(source, func):
"""
Return the arguments to pass to pm.menuItem to create a menu item matching a shelf
or shelf popup item. source is the name of the shelf/popup, and func is either pm.shelfButton
or pm.menuItem.
"""
properties = ['label', 'image', 'annotation']
cmd ... | 3782491f02ce032f84370d8751c352c04445b80d | 191,669 |
def lookup_clutter_geotype(geotype_lookup, population_density):
"""Return geotype based on population density
Params:
======
geotype_lookup : list of (population_density_upper_bound, geotype) tuples
sorted by population_density_upper_bound ascending
"""
highest_popd, highest_geotype = ... | 4bdcbdaa2e778b26432a9c49edde7ab099e8a031 | 91,260 |
def estimated_total(N: int, sample_mean: float) -> float:
"""Calculates the estimated population total given the sample mean."""
return sample_mean * N | 452ec967fab046f03d4dd9060467831ffe68ad9e | 317,953 |
import hashlib
def hashkey(value):
"""
Provide a consistent hash that can be used in place
of the builtin hash, that no longer behaves consistently
in python3.
:param str/int value: value to hash
:return: hash value
:rtype: int
"""
if isinstance(value, int):
value = str(va... | a858840cd8eaec16897e6fc3df889f7bf78a7bbe | 498,719 |
import re
def _findFirst( pattern, src ):
"""
A helper function that simplifies the logic of using regex to find
the first match in a string.
"""
results = re.findall( pattern, src )
if len(results) > 0:
return results[0]
return None | ced30ea0a31e22c0e78157ea193243ff04816b10 | 82,762 |
import logging
def heart_rate(length_of_strip, count):
"""Determine the average heart rate from the ECG strip
Another of the calculated data was the estimated average heart rate
over the length of the ECG strip. To determine this, two values are
necessary, the duration of the ECG strip and the number... | c9e59a47f53472e75e2be448c01ae903f2263f04 | 408,495 |
import math
def chute_size(mass, velocity=3, drag=0.75, gravity=9.8, air_density=1.22):
"""
Determine the required size of a chute given a mass and a velocity.
mass: mass of rocket in kg
velocity: velocity of the rocket when it hits the earth in m/s
drag: drag coefficie... | 7714ce2328c929700dff053af02d3a28808ad73c | 224,604 |
def gnome_sort(lst: list) -> list:
"""
Pure implementation of the gnome sort algorithm in Python
Take some mutable ordered collection with heterogeneous comparable items inside as
arguments, return the same collection ordered by ascending.
Examples:
>>> gnome_sort([0, 5, 3, 2, 2])
[0, 2, 2... | 5aae393eabd046c20f51125e405d211555ed9bdb | 22,057 |
def valid_parentheses(parens):
"""Are the parentheses validly balanced?
>>> valid_parentheses("()")
True
>>> valid_parentheses("()()")
True
>>> valid_parentheses("(()())")
True
>>> valid_parentheses(")()")
False
>>> valid_parentheses("())"... | 12d65523e1cb7472191094dd54d4f2e12167e504 | 493,158 |
def should_attach_entry_state(current_api_id, session):
"""Returns wether or not entry state should be attached
:param current_api_id: Current API selected.
:param session: Current session data.
:return: True/False
"""
return (
current_api_id == 'cpa' and
bool(session.get('edit... | c22c592c2b65f143d0df5c0735a0c21f7347ee71 | 27,573 |
def get_ancestors(cur, term_id):
"""Return a set of ancestors for a given term ID, all the way to the top-level (below owl:Thing)
:param cur: database Cursor object to query
:param term_id: term ID to get the ancestors of"""
cur.execute(
f"""WITH RECURSIVE ancestors(node) AS (
V... | b051a83eac81d2efdbd8a5f314dd3868e95cdcea | 547,235 |
import re
def unpack_namedtuple(name: str) -> str:
"""Retrieve the original namedtuple class name."""
return re.sub(r"\bnamedtuple[-_]([^-_]+)[-_\w]*", r"\1", name) | 896fd15577a9b23be3855b8e21262478025e7ae0 | 465,186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.