content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def make_key(obj):
"""Returns a key for this object."""
return id(obj) | b3380bfadba5c8e64d087573d5de7e299339e0d6 | 409,393 |
from typing import Tuple
def parse_notification(notification: dict) -> Tuple[str, str]:
"""valdiates notification payload
Args:
notification(dict): Pub/Sub Storage Notification
https://cloud.google.com/storage/docs/pubsub-notifications
Or Cloud Functions direct trigger
https://... | 80e1c6c43047817dcf9e401347ed52609f3588c8 | 386,459 |
def get_at(doc, path, create_anyway=False):
"""Get the value, if any, of the document at the given path, optionally
mutating the document to create nested dictionaries as necessary.
"""
node = doc
last = len(path) - 1
if last == 0:
return doc.get(path[0])
for index, edge in e... | ff3cf22a878b40e17a41d2ad4ec8b410b130b323 | 550,829 |
import random
def split_dataset(ids, validation_split=0.2):
"""Split dataset for training and validation."""
random.shuffle(ids)
split_index = int((1 - validation_split) * len(ids))
train_ids = ids[:split_index]
valid_ids = ids[split_index:]
print('Training count: %s' % len(train_ids))
pri... | e2bc9dee16885a442b889ac90cd50d4e64fdcb44 | 436,494 |
def anglicize1to19(n):
"""
Returns the English equiv of n.
Parameter: the integer to anglicize
Precondition: n in 1..19
"""
if n == 1:
return 'one'
elif n == 2:
return 'two'
elif n == 3:
return 'three'
elif n == 4:
return 'four'
elif n == 5:
... | faa87aa7fa8db485da22715e7c754098babe5af2 | 623,159 |
def pi_using_float(precision):
"""Get value of pi via BBP formula to specified precision using floats.
See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
:param precision: Precision to retrieve.
:return: Pi value with specified precision.
"""
value = 0
for k i... | a68126129c5fac24ed643af0bd43fcb0a6a65137 | 589,539 |
def join_distributions(a, b):
"""joins two distributions of absolute class counts by adding the values
of each key"""
assert a.keys() == b.keys()
return {k: a[k] + b[k] for k in a} | 0d74e844d13f11cb29c17c71610881e3392c1f37 | 373,633 |
import importlib
def import_func(func):
"""
Imports a function from the autocnet package.
Parameters
----------
func : str
import path. For example, to import the place_points_in_overlap function,
this func can be called with: 'spatial.overlap.place_points_in_overlap'
R... | f7830c3d26e02349c7f4a8f7ae0b790b98b0e7d4 | 625,777 |
def _deslugify(string):
"""Deslugify string."""
return string.replace("_", " ").title() | 4238631831d99fc8016ba2f423443802d7cfc131 | 313,373 |
def job_runner(job):
"""
Run a job. Called in a Process pool.
"""
return job.run() | 7c76225cc8d19e08231ba2973bee0ba7ff4827cc | 589,802 |
def overlaps(mc1, mc2):
"""Compare two motifs and/or clusters to see if their location ranges overlap."""
return (mc1.start < mc2.end) and (mc1.end > mc2.start) | f87622c473d58172448ffa0bbe3d4fab99cc1fb7 | 65,517 |
def is_ip_in_subnet(ip, subnet):
"""
Return True if the IP is in the subnet, return False otherwise.
This implementation uses bitwise arithmetic and operators on
IPv4 subnets. Currently, this implementation does not accomodate
IPv6 address/subnet definitions. This should be added in the
future,... | 2dfa9806ba88e2e35235a17a98d32cb8bf5a26fd | 148,295 |
import asyncio
async def await_other_fixture(loop):
"""Await all other task but the current task."""
async def wait_for_tasks(current_task):
"""Wait for the tasks."""
tasks = asyncio.all_tasks() - {current_task}
await asyncio.gather(*tasks)
return wait_for_tasks | e124a45585ede8f13c0a191f10ba440ce4a63942 | 363,150 |
def ReleasePowerAssertion(io_lib, assertion_id):
"""Releases a power assertion.
Assertions are released with IOPMAssertionRelease, however if they are not,
assertions are automatically released when the process exits, dies or
crashes, i.e. a crashed process will not prevent idle sleep indefinitely.
Args:
... | a96a10785571e28f488350f7068e8c72980a7018 | 193,276 |
def get_branch_condition(branch):
"""
Extract branchCondition_GuardedBranchTransition from specification, e.g.
"type.VALUE == "graphical"" -> "#graphical"
:param branch: "branches_Branch"
:return: extracted condition string
"""
branch_condition = branch.find("./branchCondition_Guar... | 6a8bb3dc05fce391e19a05abc01a3fca370bb33b | 613,044 |
def format_gpus(connection, node_id: int):
"""
Returns GPUs formatted in Dash friendly manner.
:return: list of Dicts
"""
gpus = connection.get_gpus(node_id)
res = []
for gpu in gpus:
res.append({'label': f'{gpu}', 'value': gpu})
return res | 34e646a1fe989d5552a197d45fad49616fcc1d0f | 314,845 |
def fails_if_called(test, msg="This function must not be called.",
arguments=True):
"""
Return a new function (accepting any arguments)
that will call test.fail(msg) if it is called.
:keyword bool arguments: If set to ``False``, then we will
not accept any arguments. This ca... | a234b141a8e24a74a15a98929aee02a181721f5c | 677,002 |
def _version_string(version):
"""Convert version from bytes to a string.
Args:
version: version in byte format.
Returns:
Three byte version string in hex format: 0x00 0x00 0x00
"""
return ' '.join('0x{:02x}'.format(ord(b)) for b in version) | cb17c4efb4d3ccab5b1d13ca5b90471841b1f9a4 | 621,020 |
def add_sets(*args):
"""
Add sets. The arguments need not be sets. Returns a set of unique
values. If the arguments include unhashable types, raises a TypeError.
"""
out = set()
for arg in args:
for thing in arg:
out.add(thing)
return out | 32277f8ac5a7e23f074aeba88335227182ae828d | 145,265 |
def MakeGray(rgbTuple, factor, maskColour):
"""
Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be
changed.
:param `rgbTuple`: a tuple representing a pixel colour;
:param `factor`: a graying-out factor;
:param `maskColour`: a colour mask.
"""
if rgbTuple != mas... | 949e88735522cadc9d7060b630a6b4781c484782 | 649,618 |
def nCWRk(n, r):
"""Returns nCk(n+r-1, n-1) optimized for large n and small r."""
val = 1
for i in range(1, r+1):
val *= n + r - i
val //= i
return val | 6ed2307192f8cff91c6fd345c73867170fc5ede5 | 359,102 |
import warnings
def preprocess_metrics(input_metrics, metrics_dict):
"""Preprocess the inputed metrics so that it maps
with the appropriate function in metrics_dict global variable.
input_metrics can have str or function. If it's a string
then it has to be a key from metrics_dict global variable dict... | 1c455f45d628ff63422bf0b22f14d34d5db4d7d0 | 533,512 |
import torch
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor): # pragma: no cover
"""
Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.L... | d91b3c52fffeda87383a6ef9f8748259a6cf9f34 | 320,574 |
def remove_sql_comments(sql):
"""Strip SQL comments starting with --"""
return ' \n'.join(map(lambda x: x.split('--')[0], sql.split('\n'))) | e3849a59495485f2a014fbabf53bcad83639961d | 256,759 |
def build_pwsh_test_command() -> str:
""" Build command for powershell test
Returns:
str: powershell test command
"""
command = "Invoke-Pester"
# Return exit code when finished
command += ' -Configuration \'@{Run=@{Exit=$true}; Output=@{Verbosity="Detailed"}}\''
return f"pwsh -Comma... | 9a2ee76785891ebbf4c906b4be630e7004a62eac | 460,973 |
import re
def remove_hanging_parenthesis(sample_string):
"""
Removes parenthesis at the end of strings.
Args:
sample_string (str): Input string
Returns:
str
"""
return re.sub(r"[^.*]\($", "", sample_string).strip() | 23d4deb582973e209c5bb04f9b573c93997c7388 | 630,675 |
def _captalize(arg1):
"""Returns the string with an initial capital"""
return str(arg1).title() | eab47f235edc16ae47840d35c15422f45686822a | 321,624 |
def trim_silence(audio, noise_threshold=150):
""" Removes the silence at the beginning and end of the passed audio data
:param audio: numpy array of audio
:param noise_threshold: the maximum amount of noise that is considered silence
:return: a trimmed numpy array
"""
start = None
end = Non... | cee7e4db02c9ed9074e4b023d13f78f47a25fd2a | 231,731 |
def is_cn_char(ch):
""" Test if a char is a Chinese character. """
return ch >= u'\u4e00' and ch <= u'\u9fa5' | 63d26e6d2ff4b446f2e80cb80588bce214b648a6 | 468,612 |
def _lcs_length(x, y):
"""
Computes the length of the longest common subsequence (lcs) between two
strings. The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
>... | 808ba58208b72bef91443e7466d1497b82d545ee | 323,779 |
def compare_simple(x, y, context):
"""
Returns a very simple textual difference between the two supplied objects.
"""
if x != y:
return context.label('x', repr(x)) + ' != ' + context.label('y', repr(y)) | 467009d5f232e9ab8c40bddc750fcba51b80cb00 | 359,440 |
def permute_all_atoms(labels, coords, permutation):
"""
labels - atom labels
coords - a set of coordinates
permuation - a permutation of atoms
Returns the permuted labels and coordinates
"""
new_coords = coords[:]
new_labels = labels[:]
for i in range(len(permutation)):
new_... | ba8aa571afd9039725347a0b5a04885dfafb02b3 | 655,836 |
def ts_candle_from_ts(ts, timeframe_int):
"""Return candle timestamp from a timestamp and a given timeframe (integer)"""
return((ts // timeframe_int) * timeframe_int) | 351636aca4ac03f6733a54811620580d31e18599 | 433,623 |
def validateFitMohrCoulomb(value):
"""
Validate fit to Mohr-Coulomb yield surface.
"""
if not value in ["inscribed", "middle", "circumscribed"]:
raise ValueError("Unknown fit to Mohr-Coulomb yield surface.")
return value | af7f59454c35caa33aa98f4457593d82c7186278 | 543,061 |
def get_ls_user_line(user: dict) -> str:
"""Get a string representing a user in the User Ls command.
:param user: User data.
:returns: User string.
"""
line = user["id"] + " | "
username = user["username"]
c = len(username)
if c <= 20:
username = username + (" " * (20 - c))
... | cfe34e988fa53182855406473214e4e59a75ffc8 | 209,706 |
import math
def borders_ms_to_frames(borders, rate):
"""
Function to convert a list of 2-item lists or tuples from milliseconds to
frames.
Parameters
----------
borders : list
a list of 2-item lists or tuples, each item of which is a number of
milliseconds
rate : float
... | 0d9faf19be3da2ec4b40c71b13826a6eae0cdc02 | 446,683 |
import time
def strftime_utc(epoch):
"""Convert seconds from epoch into UTC time string."""
return time.strftime("%a, %d %b %Y %H:%M:%S+0000", time.gmtime(epoch)) | acc40d25c482c6ba3f3ef6fe684e225e8e9754f3 | 152,455 |
def bps_mbps(val: float) -> float:
"""
Converts bits per second (bps) into megabits per second (mbps).
Args:
val (float): The value in bits per second to convert.
Returns:
float: Returns val in megabits per second.
Examples:
>>> bps_mbps(1000000)
1.0
>>> b... | 13520e00c393a647ccdc2ba0021445970e169fd2 | 70,921 |
from typing import Callable
import asyncio
def add_async_job(target: Callable, *args):
"""Add a callable to the event loop."""
loop = asyncio.get_event_loop()
if asyncio.iscoroutine(target):
task = loop.create_task(target)
elif asyncio.iscoroutinefunction(target):
task = loop.create_t... | 590bce904241c598e742d6c7370ebf2563aba5f1 | 690,451 |
def index_dependent_values(self, chromosome):
"""Test of the GA's ability to improve fitness when the value is index-dependent.
If a gene is equal to its index in the chromosome + 1, fitness is incremented.
"""
# Overall fitness value
fitness = 0
for i, gene in enumerate(chromosome):
... | 20df3cc47ef566f34fbdba4eca84a85795a02408 | 662,450 |
def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... | 0a4fdb3271dc9fdd0a3258f56e248f0f1a4e439b | 311,754 |
import torch
def get_obs_y_dict(select_pairs, x_a, x_s):
"""
Input
-------
select_pairs: pairs of (alpha, beta) selected
x_a: array holding avoidance count for all dogs & all trials, example for 30 dogs & 25 trials, shaped (30, 25)
x_s: array holding shock count for all dogs & all trials,... | a0e7b86cb010ca00ba9dd53befdcd64fa7abad01 | 129,582 |
import multiprocessing
import functools
def in_separate_process(func):
"""Decorator that runs a function in a separate process, to force garbage collection
collection upon termination of that process, limiting long-term memory usage.
Parameters
----------
func : function
Function to r... | ccdbba74dc6637928d53d5aad19a2a274f8c0ae4 | 139,062 |
from typing import List
def ensure_size(arr: List, default, size: int) -> List:
"""Ensures the size of an array by using the default
when an element does not exist.
"""
return [arr[x] if x < len(arr) else default for x in range(size)] | 8cc6d4274f156e0ebc8615f37f46200075feba1b | 382,024 |
import base64
def _dbase64_encode(b):
"""Internal helper to encode bytes using our base64 variant.
This is like urlsafe base64 encode but strips the trailing '='
padding. Also, it returns a string, not a bytes object.
"""
bb = base64.urlsafe_b64encode(b)
ss = str(bb.decode('ascii'))
s = ... | b7c35f5708e5607f4edbf126733c608f6969a579 | 354,870 |
import string
def num_Ponctuation(Instr):
"""
this function return the number of ponctuation characters in a String
"""
nonpuc = [c for c in Instr if c not in string.punctuation]
nonpuc = "".join(nonpuc)
if "." in nonpuc:
nonpuc = nonpuc + "." # this line just to ignore the period for... | b2cfea49828d483fb4b0033fb52cdfedfe9e8d7b | 549,625 |
def create_bool_mask(mask, label, ignore_label):
"""Creates a boolean mask for plant region or individual class.
Args:
mask: Array representing a mask with integer labels
ignore_label: Integer, pixel value of label to exclude.
label: String, which label to return. 'plant_region' returns mask for whole ... | 5b8bafba20364e373b4699bd285d638568c8c4b0 | 498,346 |
def create_paper(paper_id, paper_title, paper_abstract, paper_year, paper_citations):
"""Initialize a paper."""
paper = {
"id": paper_id,
"title": paper_title,
"abstract": paper_abstract,
"year": paper_year,
"is_influential": False,
"citations": paper_citations,
... | d1094c23549dc6d2108c0b08e79b8ad60c8343e6 | 167,014 |
def isnumber(*args):
"""Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0.
"""
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args)) | 6ee42132a517c0d2d7c3b745a2faa2c18693c02f | 143,340 |
import ssl
import aiohttp
def get_os_session(*, os_cacert, insecure, log):
"""
Returns a secure - or insecure - HTTP session depending
on configuration settings.
Works for both HTTP and HTTPS endpoints.
"""
if os_cacert:
ssl_context = ssl.create_default_context(cafile=os_cacert)
... | 50cb11785a20d7828fa72f474f8a326064503e90 | 98,195 |
def reverse_word(word):
"""
description: reverse the characters in a word
input:
'word': the word to be reversed
output:
the reversed word
"""
i = len(word)
reversed_word = ""
while i > 0:
reversed_word += word[i-1]
i = i-1
return reversed_word | 4bc72fc43db0f07766c035f79bd9815d2d6502db | 203,074 |
import itertools
def all_segments(N):
"""Return (start, end) pairs of indexes that form segments of tour of length N."""
return (
(start, end)
for (start, end) in itertools.combinations(range(N), 2)
if end > start+1
) | 993c93a182cf2fc0be4d25962144842c0c1db181 | 142,140 |
def shash(s):
"""Get the shallow hash of a statement."""
return s.get_hash(shallow=True) | 3e140937078fac8657d3bd51b12635b07545e1e2 | 246,673 |
def create_element(number,etype):
"""
Create an element:
Parameters
----------
number : int
Number of element
etype : str
Element type
::
# Example
create_element(1, "PLANE182") # -> ET,1,PLANE182
"""
_el = "ET,%g,%s"%(number,etyp... | ea9b1ddcdd8f6a33ea6d2f7a1f3cadb1b29219dd | 354,007 |
import math
def calculate_zoom(fov, height=1.0):
"""Calculates the zoom (distance) from the camera
with the specified FOV and height of image.
:param float fov: The FOV to use.
:param float height: The height of the image at the
desired distance.
:rtype: A float representing the zoom (dis... | ddd3fa00a0855c9900ee3ea33bb65379f182818b | 572,062 |
def get_nested_value_by_path(nested_dict, path, default=None, mode='mix'):
"""
Get a nested value of nested dict by path
:param nested_dict: nested dict object
{
"club": [
{
"manager": {
"last_name": "Lionel",
"first_name": "Messi"
... | ed7f94f516690737188d90d086835de0a914bf7e | 215,323 |
def decode(s):
"""
Run length decoding
(str) -> str
>>> decode('1B5W1B4W')
'BWWWWWBWWWW'
"""
ret = ''
sizeStr = ''
for ch in s:
if ch.isalpha():
if sizeStr:
ret += ch * int(sizeStr)
sizeStr = ''
else:
sizeSt... | 6f092db0a6ab5058abe2165a6adb227b7865c097 | 592,840 |
def choose_condition(data, events, condition):
"""Filters out a specific condition from the data.
:param data: data from which to extract conditions from
:type data: numpy array
:param events: event data of shape [trials x 4]
:type events: numpy array
:param condition: Condition to be filtered ... | 8fa8cc12a11561c3a69a067b1f302dd1ccaf1b31 | 661,747 |
def get_columns(c, table, verbose=False):
"""Get all columns in a specified table."""
head = c.execute("select * from " + table)
names = list(map(lambda x: x[0], head.description))
if verbose:
print(names)
return(names) | cdf0166b1057224cb1ba308b9f5f10b88d688891 | 126,220 |
import socket
def createTestSocket(test, addressFamily, socketType):
"""
Create a socket for the duration of the given test.
@param test: the test to add cleanup to.
@param addressFamily: an C{AF_*} constant
@param socketType: a C{SOCK_*} constant.
@return: a socket object.
"""
skt... | 3b8e9d63e29151adb1bd2d2c4e48d07cb1bd4e6a | 663,796 |
import pickle
def read_pic(dir, file):
"""
Function that reads a pickle variable file and returns it.
Arguments:
dir -- directory that contains the file
file -- name of the pickle file
Returns:
x -- pickle variable contained in the file
"""
f = open(dir + '/' + fil... | 18ab2f6764b86e919258829cace0d693077f9a41 | 215,295 |
def decode_extra_length(bits, length):
"""Decode extra bits for a match length symbol."""
if length == 285:
return 258
extra = (length - 257) / 4 - 1
length = length - 254
if extra > 0:
ebits = bits.read(extra)
length = 2**(extra+2) + 3 + (((length + 1) % 4) * (2**extra)) + e... | 64bc02f4c9ada7eb1fa38b58765832129470b15b | 496,550 |
import time
def seconds_from_now_to_hhmm(seconds_from_now: int) -> str:
"""
Takes a time in seconds and returns the time at which
those seconds will elapse in the form of hh:mm
"""
now_hhmm = time.strftime("%H:%M")
now_hrs, now_mins = map(int,now_hhmm.split(':'))
now_secs = now_hrs*3600 + ... | 9a3749403f2b46d20015f0ebf4361ee3f1153d5f | 377,162 |
def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False,
default=None):
"""Returns the edge boundary of `nbunch1`.
The *edge boundary* of a set *S* with respect to a set *T* is the
set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*.
If *T* is not specified, i... | 28af02017c9e166089f167a576cca59779da06ce | 432,919 |
def parse_row(row):
"""Parse a row into a nice dictionary."""
old_match = dict()
old_match["year"] = row[0]
old_match["eventshort"] = row[1]
old_match["complevel"] = row[2]
old_match["matchnumber"] = row[3]
old_match["red1"] = row[4]
old_match["red2"] = row[5]
old_match["red3"] = row... | 9a05599242679c22d5e0743c6851586e7b415a2c | 477,511 |
def format_topic_code(topic_code: str) -> str:
"""Takes a topic code string and formats it as
human readable text.
"""
return str.title(topic_code.replace('_', ' ')) | 30936e9b134f6b3c30b7daaf717ca0a8c732d587 | 257,579 |
def _process_results(results, keep_N, correlation_threshold=0, thresholds=None):
"""
Given the results of the CPA, output an array of arrays sorted by most likely candidate first and an array of
likely incorrect bytes
"""
possible_keys = []
likely_wrong = set()
# plot(results[0])
for i... | 20efa02fddd05995fb395f8a059ebb4849db6c32 | 80,139 |
import logging
def get_mac_from_port(port, neutronclient):
"""Get mac address from port, with tenacity due to openstack async.
:param port: neutron port
:type port: neutron port
:param neutronclient: Authenticated neutronclient
:type neutronclient: neutronclient.Client object
:returns: mac ad... | 039feeb1a8950a50da2b1ccd9397c17c8f5849b7 | 481,900 |
def is_collection(collection):
"""Return ``True`` if passed object is Collection and ``False`` otherwise."""
return type(collection).__name__ == 'Collection' | 6c8c613a48106d1aae81010a536cc5165ebe7b33 | 460,027 |
def _gcd(num1: int, num2: int) -> int:
"""Get the GCD of the given two numbers"""
while num1 % num2 != 0:
old_num1 = num1
old_num2 = num2
num1 = old_num2
num2 = old_num1 % old_num2
return num2 | 1b6df1855fe018e7f7ae2e6638a1d0c69a8970c6 | 203,941 |
def get_agegroups_from_breakpoints(breakpoints):
"""
This function consolidates get_strat_from_breakpoints from Romain's age_strat module and define_age_structure from
James' model.py method into one function that can return either a dictionary or a list for the model stratification.
(One reason for usi... | c637d9d86582fb06dc9920fa362126b29353804a | 432,092 |
def _sigma_from_hybrid(psfc, hya, hyb, p0=100000.):
"""Calculate sigma at the hybrid levels."""
# sig(k) = hya(k) * p0 / psfc + hyb(k)
# This will be in Pa
return hya * p0 / psfc + hyb | 61a7751ba4195d9e3c73369d173dd947785ce26d | 541,875 |
def _strip_after_pound(string):
"""
Treat "#" as a comment character and remove everything after.
"""
msg = ""
for char in string:
if char != "#":
msg = msg + char
else:
return msg
return msg | 6a8052ce2e78283b21af9eabb40a2f695a0eb87b | 285,744 |
import json
def analyse_line_dataturk_format(line):
"""
scans a json file line and returns the file name and label
the format is specifically for the one returned by the dataturks labelling
platform
Args:
line: string read from json file
Returns:
file_name: sting with name o... | 1154bfa98608f2fa8f1e30a7dad781e8e489453c | 106,774 |
def artifact_version_unsupported(artifact_version, supported_major_version):
"""artifact_version_unsupported message"""
return "The decisioning artifact version ({}) is not supported. " \
"This library is compatible with this major version: " \
"{}".format(artifact_version, supported_major... | 12228c330dbee93d8ffb1ab7e594dfce8dc0b83c | 610,556 |
def basic_variant_dict(request):
"""Return a variant dict with the required information"""
variant = {
'CHROM': '1',
'ID': '.',
'POS': '10',
'REF': 'A',
'ALT': 'C',
'QUAL': '100',
'FILTER': 'PASS',
'FORMAT': 'GT',
'INFO': '.',
'info... | ff4c15e1c5308176951812f2e259332d59ce5dc8 | 574,309 |
def create_short2element(elements):
"""
Returns a map of case normalized short name to element description.
Format of the element description is defined in the instruction.
"""
return dict( (short.casefold(),f"{long} ({short})") for short,long in elements.items() ) | d9b04f01660e972e398867a5485bddeaef02517b | 491,594 |
def path_dictionary(path_dict):
"""Creates a dictionary listing all possible types of cells"""
# Cells which are dead ends.
path_dict[(False, False, True, False)] = 0
path_dict[(False, False, False, True)] = 0
path_dict[(True, False, False, False)] = 0
path_dict[(False, True, False, False)] = 0
... | 1a3b815717e18f4261afc356b7fef8047d50721b | 497,585 |
import re
def parse_bytes(bytestr):
"""Parse a string indicating a byte quantity into an integer., example format: 536.71KiB, 31.5 mb, etc...
modified from original source at youtube-dl.common"""
try:
# if input value is int return it as it is
if isinstance(bytestr, int):
retu... | c82752dc58e43e95e31783533690ef3738dd9b70 | 111,658 |
def explicit_no_context(arg):
"""Expected explicit_no_context __doc__"""
return "explicit_no_context - Expected result: %s" % arg | d9e5abd375768adf8c53a4f9b11f9f2d83fd39de | 437,550 |
import re
def inline_whitespace(text: str) -> str:
"""Collapse multiple spaces or tabs within a string into one space
character.
Args:
text: The input string.
Returns:
Text with collapsed spaces and tabs.
"""
return re.sub(r"[ \t]+", " ", text) | 03799aa3a1f2f0b415687223ac87d812e2b7d1d3 | 445,313 |
def removeGame(gtitle: str) -> str:
"""Return a query to remove a given game from the database."""
return (f"DELETE FROM game "
f"WHERE title='{gtitle}';"
) | 589096681b70232cbd199f7b2f5bd4685418888d | 101,671 |
def log(rv):
"""
Returns the natural logarithm of a random variable
"""
return rv.log() | ff6db73f2bca02d9d298578f4c23166827a33f07 | 531,553 |
def _process_custom_formatters(formatters, columns):
"""Re-keys a dict of custom formatters to only use column indices.
Args:
formatters: A dict of formatters, keyed by column index or name.
columns: The list of columns names.
Returns:
A dict of formatters keyed only by column index.
"""
if not ... | 266fc3e8d4f78e6c65d18bdc87591c2e5b0c688b | 463,405 |
def _format_counters(counters, indent='\t'):
"""Convert a map from group -> counter name -> amount to a message
similar to that printed by the Hadoop binary, with no trailing newline.
"""
num_counters = sum(len(counter_to_amount)
for group, counter_to_amount in counters.items())
... | 7d763a6ddd92e86e71628d3fa8a82e117077e51e | 526,348 |
def pep440_version(date, ref, dirty=False):
"""Build a PEP440-compliant version number from the passed information."""
return "{date}+g{ref}{dirty}".format(
date=date.strftime("%Y%m%d"), ref=ref, dirty=".dirty" if dirty else ""
) | 984c51b60f13ff3b8f86fb0ad5e29458ce81f337 | 426,606 |
def format_notes(section):
"""Format the "Notes" section."""
assert len(section) == 1
return '!!! note "Notes"\n {0}'.format(section[0].strip()) | 639fce05e775ad76bb906cba8ba902fc4f6f5ac8 | 98,021 |
from typing import OrderedDict
def _deep_convert_dict(layer):
"""Helper function to convert dictionary back from OrderedDict"""
to_ret = layer
if isinstance(layer, OrderedDict):
to_ret = dict(layer)
try:
for key, value in list(to_ret.items()):
to_ret[key] = _deep_convert_di... | 0404aaf7278fbc8a118602e4bd71022d6ddb467c | 272,983 |
def distinct_brightness(dictionary):
"""Given the brightness dictionary returns the dictionary that has
no items with the same brightness."""
distinct, unique_values = {}, set()
for char, brightness in dictionary.items():
if brightness not in unique_values:
distinct[char] = brightnes... | 7f7bb5dba9bab113e15cc4f90ddd4dfda7bb5f01 | 12,826 |
def convert_to_image_file_format(format_str):
"""Converts a legacy file format string to an ImageFileFormat enum value.
Args:
format_str: A string describing an image file format that was passed to
one of the functions in ee.data that takes image file formats.
Returns:
A best guess at the correspo... | d42affe700f8bf3639d9a713d24e32548c4ac932 | 501,441 |
def lerp(v0, v1, t):
"""
Simple linear interpolation between v0 and v1 with parameter t, 0 ≤ t ≤ 1
"""
return v0 + (v1 - v0) * t | dda9cb7532ad59eab4fa67716e0f940452b0cf88 | 613,274 |
import re
def check_email_valid(submission):
"""
Check if submission is a valid email address
"""
if re.match(r"[^@]+@[^@]+\.[^@]+", submission):
return True
else:
return False | 1528df90d59c4e0cedc8c030acec1cfcd6984e64 | 19,760 |
def check_login(session):
"""
Function to check if the specified session has a logged in user
:param session: current flask session
:return: Boolean, true if session has a google_token and user_id
"""
# Check that session has a google_token
if session.get('google_token') and session.get('use... | cd5651ce622ffd108ea7d0b8c1c4f70b1b4947ab | 32,571 |
import pkgutil
import encodings
def encoding_exists(encoding):
"""Check if an encoding is available in Python"""
false_positives = set(["aliases"])
found = set(name for imp, name, ispkg in pkgutil.iter_modules(encodings.__path__) if not ispkg)
found.difference_update(false_positives)
if encoding:
... | 2e5d1bb114a15010523a9ed29636375fe2c6e87e | 42,880 |
def parse_frontmatter(raw_text: str) -> dict:
"""
Parser for markdown file front matter. This parser has the following features:
* Simple key-value pairings (`key: value`)
* Comma-separated lists between brackets (`list: ['value1', 'value2']`)
* Keys are case insensitive
Args:
... | 0b0411917084fc7ae6abcec028d6f7c15916b3c4 | 369,759 |
def get_zip_filename(book_id):
""" Get the filename for a zip document with the book identifier. """
return book_id + ".zip" | 2919ca946c887a4c51a98af2d7abea1c74816161 | 657,662 |
from typing import Union
def ppu2mpp(ppu: int, units: Union[str, int]) -> float:
"""Convert pixels per unit (ppu) to microns per pixel (mpp)
Args:
ppu (int):
Pixels per unit.
units (Uniont[str, int]):
Units of pixels per unit. Valid options are "cm",
"centi... | 078d3dbdb368174fed7bed7cc31470147dbed20b | 339,580 |
import six
def split_address(address):
"""Split an e-mail address into local part and domain."""
assert isinstance(address, six.text_type),\
"address should be of type %s" % six.text_type.__name__
if "@" not in address:
local_part = address
domain = None
else:
local_par... | 2576badcb48fbeb5e95cfb40a29e8f9029e432b7 | 561,724 |
def print_functions(s):
"""
Define edge and point drawing functions.
EXAMPLES::
sage: from sage.graphs.print_graphs import print_functions
sage: print(print_functions(''))
/point %% input: x y
{ moveto
gsave
currentpoint translate
0 0 2 0 360 a... | 8fb3772d60613cba8141f417976bce1230a8db29 | 333,207 |
def get_seconds_from_minutes(minutes: int) -> int:
""" Simple utility to convert minutes into seconds """
return minutes * 60 | 1a4c7a85a500a6d7848537058518114e4a8eb93b | 390,031 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.