content stringlengths 42 6.51k |
|---|
def better_abs_of_steel(n):
"""
Function to illustrate the use of duck typing for make an abs function that works on iterables and scalars.
:param n: List or scalar
:return: The absolute value of the iterable or scalar.
"""
try:
# Assume that abs will work, and try to run it.
re... |
def check_valid_input(the_guess):
"""
:param: the_guess:
:type: string
:return: if valid guess for the game
:rtype: bool
"""
ENGLISH_FLAG = the_guess.isascii()
LENGTH_FLAG = len(the_guess) < 2
SIGNS_FLAG = the_guess.isalpha()
if (LENGTH_FLAG is False and # IN CASE MORE THAN 1 ... |
def pad_for_rsa(data):
"""
Pad data out to the crypto block size (8 bytes)
"""
data = data + chr(0x00)*(16-len(data))
return chr(0x01) + chr(0xff)*(127-len(data)-2) + chr(0x00) + data |
def pack(*values):
"""Unpack a return tuple to a yield expression return value."""
# Schizophrenic returns from asyncs. Inspired by
# gi.overrides.Gio.DBusProxy.
if len(values) == 0:
return None
elif len(values) == 1:
return values[0]
else:
return values |
def codes(edge):
"""Return forward and backward codes for the given tile edge, a list
of the characters ("0" or "1") on an edge of the matrix.
"""
fwd = int("".join(edge), 2)
back = int("".join(reversed(edge)), 2)
return fwd, back |
def reformat_version(version: str) -> str:
"""Hack to reformat old versions ending on '-alpha' to match pip format."""
if version.endswith("-alpha"):
return version.replace("-alpha", "a0")
return version.replace("-alpha", "a") |
def diff(A,B):
"""subtract elements in lists"""
#A-B
x = list(set(A) - set(B))
#B-A
y = list(set(B) - set(A))
return x, y |
def getEbiLink(pdb_code):
"""Returns the html path to the pdb file on the ebi server
"""
pdb_loc = 'https://www.ebi.ac.uk/pdbe/entry/pdb/' + pdb_code
return pdb_loc |
def id_fixture_function(fixture_value):
"""
# First variant of implementation
if fixture_value[0] == yandex_url:
return " Yandex"
elif fixture_value[1] == google_url:
return " Google"
else:
return None
"""
# second variant of implementation
return "Url: '{}'. Titl... |
def map_to_bin(bin_inds, data, n_bins):
"""
takes bin indices, puts relevant data in relevant bin
bins is 1+max value in bin_inds lists of lists
"""
assert len(bin_inds) == len(data), "data (len {}) and bin indices array (len {}) should be the same length".format(len(data), len(bin_inds))
bins =... |
def format_interval(timeValue):
"""
Formats a number of seconds as a clock time, [H:]MM:SS
Parameters
----------
t : int
Number of seconds.
Returns
-------
out : str
[H:]MM:SS
"""
# https://github.com/tqdm/tqdm/blob/0cd9448b2bc08125e74538a2aea6af42ee1a7b6f/tqdm/... |
def API_fatal(description):
"""Create an API fatal error message."""
return {"status": "fatal", "error": description} |
def extract_path(request):
"""Separate routing information and data from an incoming request."""
i = request.index(b"")
return request[:i+1], request[i+1:] |
def build_targets_from_builder_dict(builder_dict):
"""Return a list of targets to build, depending on the builder type."""
if builder_dict.get('extra_config') == 'iOS':
return ['iOSShell']
if 'SAN' in builder_dict.get('extra_config', ''):
# 'most' does not compile under MSAN.
return ['dm', 'nanobench'... |
def part1(dataset):
"""
Execute the actions and record their index until the current action
would execute an action already in the list of recoded indices.
Break and return the accumulation value.
"""
bootSuccessful = True
accumulation = 0
recordedActions = []
i = 0
while i < ... |
def sanitize_destination(path : str) -> str:
""" Function removes the leading / characters. They're
messing up the directory structure.
"""
if not path:
path = ""
while len(path) > 0 and path[0] == '/':
path = path[1:]
return path |
def checkSeq(x, length):
""" Returns true if the length of the weave 'x' is less than or equal to 'length' """
s = 0
for elem in x:
s += abs(elem)
return s <= length |
def _varying(number, vert):
"""Generates ARB assembly for a varying attribute. """
if vert: return 'result.texcoord[{}]' .format(number)
else: return 'fragment.texcoord[{}]'.format(number) |
def heron(a, b, c):
"""Obliczanie pola powierzchni trojkata za pomoca wzoru
Herona. Dlugosci bokow trojkata wynosza a, b, c."""
from math import sqrt
if a + b > c and \
a + c > b and \
b + c > a and \
a > 0 and b > 0 and c > 0:
p = (a + b + c) / 2.0
are... |
def is_string(value) -> bool:
"""
Is the value a string
"""
return isinstance(value, str) |
def decode(digits, base):
"""Decode given digits in given base to number in base 10.
digits: str -- string representation of number (in given base)
base: int -- base of given number
return: int -- integer representation of number (in base 10)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <... |
def get_extrusion_command(x: float, y: float, extrusion: float) -> str:
"""Format a gcode string from the X, Y coordinates and extrusion value.
Args:
x (float): X coordinate
y (float): Y coordinate
extrusion (float): Extrusion value
Returns:
str: Gcode line
"""
retu... |
def list_formatter(values):
"""
Return string with comma separated values
:param values:
Value to check
"""
return u', '.join(values) |
def ensure_collection(value, collection_type):
"""Ensures that `value` is a `collection_type` collection.
:param value: A string or a collection
:param collection_type: A collection type, e.g. `set` or `list`
:return: a `collection_type` object containing the value
"""
return collection_type((v... |
def get_column_type(column, ignored=None): # pylint: disable=unused-argument
"""Get column sort type attribute"""
return getattr(column, 'sort_type', None) |
def _from_timestamp_float(timestamp):
"""Convert timestamp from a pure floating point value
inf is decoded as None
"""
if timestamp == float('inf'):
return None
else:
return timestamp |
def XOR(a, b):
"""
>>> XOR("01010101", "00001111")
'01011010'
"""
res = ""
for i in range(len(a)):
if a[i] == b[i]:
res += "0"
else:
res += "1"
return res |
def binomialCoeff(n, k):
"""
Calculate the number of way 'n' things can be chosen 'k' at-a-time,
'n'-choose-'k'. This is a simple implementation of the
scipy.special.comb function.
:param n: (int) The number of things
:param k: (int) The number of things to be chosen at one time
:return: (i... |
def get_bucket_color(i):
"""Return diverging color for unique buckets.
Generated using:
```python
import seaborn as sns
colors = sns.color_palette("Set2")
rgbs = []
for r,g,b in list(colors):
rgbs.append(
f"rgb({int(r*255)},{int(g*255)},{int(b*255)})"
)
```
... |
def make_transition_automaton(pattern):
"""
Make a transition (automaton) matrix from a
single pattern, e.g. [3,2,1]
"""
t = []
c = 0
for i in range(len(pattern)):
t.append((c,0,c)) # 0*
for _j in range(pattern[i]):
t.append((c,1,c+1)) # 1{pattern[i]}
c += 1
t.append((c,0,c... |
def add_carry_bits(res, carry, MASK=0xFFFFFFFF):
"""Adds bits at each position
1 + 1 = 0
1 + 0 = 1
Examples:
>>> res, carry = int("0101", 2), int("0011", 2)
>>> bin(add_carry_bits(res, carry))
'0b110'
"""
return (res ^ carry) & MASK |
def info_from_petstore_auth(token: str) -> dict:
"""
Validate and decode token.
Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
'scope' or 'scopes' will be... |
def check_not_an_email_address(value: str) -> str:
"""
Validate that client_id does not contain an email address literal.
"""
assert value.find("@") == -1, "client_id must not be identifiable"
return value |
def get_dependencies(modules, module_name):
"""Return a set of all the dependencies in deep of the module_name.
The module_name is included in the result."""
result = set()
for dependency in modules.get(module_name, {}).get('depends', []):
result |= get_dependencies(modules, dependency)
retu... |
def get_query_type(key):
"""
Translates numerical key into the string value for dns query type.
:param key: Numerical value to be translated
:return: Translated query type
"""
return {
1: 'A', 2: 'NS', 3: 'MD', 4: 'MF', 5: 'CNAME', 6: 'SOA', 7: 'MB', 8: 'MG', 9: 'MR0', 10: 'NULL... |
def b_to_gb(value):
"""Bytes to Gibibytes"""
return round(int(value) / (1000**3), 3) |
def invert_dictionary(dict, make_unique=False):
"""returns an inverted dictionary with keys and values swapped.
"""
inv = {}
if make_unique:
for k, v in dict.items():
inv[v] = k
else:
for k, v in dict.items():
inv.setdefault(v, []).append(k)
return inv |
def IsPrivilegedUser(user_email, is_admin):
"""Returns True if the given email account is authorized for access."""
return is_admin or (user_email and user_email.endswith('@google.com')) |
def is_private(event):
"""Check if private slack channel."""
return event.get("channel").startswith("D") |
def seconds_to_milliseconds(seconds):
"""
Convert seconds to milliseconds.
NB: Rounds to the nearest whole millisecond.
"""
return int(round(seconds*1000)) |
def idfy(var: str, *args):
"""Append ids to the variable."""
for arg in args:
var += '_' + str(arg)
return var |
def string_length_fraction(str_list_1, str_list_2):
"""
Calculate the percentage difference in length between two strings, such that s1 / (s1 + s2)
:param str_list_1: List of strings.
:param str_list_2: List of strings.
:return: Float (0 to 1).
"""
str1_size = sum(sum(len(j.strip()) for j in... |
def _odd(x: int) -> bool:
"""Checks if integer is odd"""
return x%2 == 1 |
def string_to_boolean(x):
"""Return either a boolean or None, based on the user's intent."""
if isinstance(x, bool):
return x
if x is None:
return None
if x in ["null", "Null", "none", "None"]:
return None
if x in ["true", "True", "1"]:
return True
elif x in ["... |
def evaluate(answer, generated):
"""Evaluate answer array
Args:
answer(list): answer array
generated(list): generated array
"""
result = []
for a, b in zip(answer, generated):
if a == b:
match = 1
else:
match = 0
result.append(matc... |
def Pk(k, alpha=-11.0 / 3, fknee=1):
"""Simple power law formula"""
return (k / fknee) ** alpha |
def str_to_ints(str_arg):
"""Helper function to convert a list of comma separated strings into
integers.
Args:
str_arg: String containing list of comma-separated ints. For convenience
reasons, we allow the user to also pass single integers that a put
into a list of length 1 b... |
def friendly_time(secs):
"""
turn a float/int number of seconds into a friendly looking string,
like '2 seconds' or '18 minutes'
"""
if secs < 60:
if int(secs) == 1:
unit = "second"
else:
unit = "seconds"
return "%1d %s" % (secs,unit)
elif secs < 3600:
mins = (secs / 60)
if int(mins) == 1:
uni... |
def make_hashable(data):
"""Make the given object hashable.
It makes it ready to use in a `hash()` call, making sure that
it's always the same for lists and dictionaries if they have the same items.
:param object data: the object to hash
:return: a hashable object
:rtype: object
"""
if... |
def avg_wordlen(values,delimiter = " "):
"""
#### returns the average length of given values:
if not specified, space will be the basic delimiter
#### Example:
x = avg_wordlen("One two three four five six")
### print("avg is: ",x)
>>> avg is 3.6666666666666665
"""
enteredValue... |
def parse_anchor_body(anchor_body):
"""
Given the body of an anchor, parse it to determine what topic ID it's
anchored to and what text the anchor uses in the source help file.
This always returns a 2-tuple, though based on the anchor body in the file
it may end up thinking that the topic ID and th... |
def gen_head_webfonts(family, styles, subsets=None):
"""Gen the html snippet to load fonts"""
server = '"https://fonts.googleapis.com/css?family='
if subsets:
return '<link href=%s%s:%s&subset=%s" /rel="stylesheet">' % (
server, family.replace(' ', '+'), ','.join(styles), ','.join(subsets)
)
r... |
def get_json_dict(service, file_ids):
"""
Gets comments from the API for the file_ids.
Parameters:
service, the API service object
file_ids, a dictionary of filenames:file_ids, returned by get_file_ids()
Returns:
c_json_dict, a dictionary of json responses for each comment
... |
def get_tachycardia_level(bpm, age):
"""
This function returns the level 0->1->2 where 2 is the maximum of tachycardia
:param bpm: the registered bpm
:param age: the age of the patient
:return: the level of tachycardia
"""
if age <= 45:
if bpm > 180:
return 2
elif... |
def ce(actual, predicted):
"""
Computes the classification error.
This function computes the classification error between two lists
Parameters
----------
actual : list
A list of the true classes
predicted : list
A list of the predicted classes
Returns
... |
def safe_name(dbname):
"""Returns a database name with non letter, digit, _ characters removed."""
char_list = [c for c in dbname if c.isalnum() or c == '_']
return "".join(char_list) |
def convert_to_str_array(scanpaths):
"""
Converts the dict-formatted scanpaths into an array of strings for similarity calculations. Even though an array is
not good for searching scanpath by IDs (O(n) time), it provides an easy way to get the size, n-th element or index.
From: [{'fixations': [['A', '15... |
def dedupe_with_order(dupes):
"""Given a list, return it without duplicates and order preserved."""
seen = set()
deduped = []
for c in dupes:
if c not in seen:
seen.add(c)
deduped.append(c)
return deduped |
def to_netstring(buff):
"""
Converts a buffer into a netstring.
>>> to_netstring(b'hello')
b'5:hello,'
>>> to_netstring(b'with a nul\\x00')
b'11:with a nul\\x00,'
"""
bytes_length = str(len(buff)).encode('ascii')
return bytes_length + b':' + buff + b',' |
def set_async_call_stack_depth(maxDepth: int) -> dict:
"""Enables or disables async call stacks tracking.
Parameters
----------
maxDepth: int
Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async
call stacks (default).
"""
return {
... |
def pick_subdevice(u):
"""
The user didn't specify a subdevice on the command line.
If there's a daughterboard on A, select A.
If there's a daughterboard on B, select B.
Otherwise, select A.
"""
#if u.db[0][0].dbid() >= 0: # dbid is < 0 if there's no d'board or a problem
# retur... |
def mdc(a, b):
""" Retorna o MDC entre a e b.
"""
if a < b:
temp = a
a = b
b = temp
while b != 0:
r = a % b
a = b
b = r
return a |
def _unblast(name2vals, name_map):
"""Helper function to lift str -> bool maps used by aiger
to the word level. Dual of the `_blast` function."""
def _collect(names):
return tuple(name2vals[n] for n in names)
return {bvname: _collect(names) for bvname, names in name_map} |
def caption(picture):
"""
Filter to format the caption for a picture.
Usage: {{ picture|caption }}
If an object without a name or desciption is used, an empty string is returned.
"""
if hasattr(picture, 'name') and hasattr(picture, 'description'):
return '<a href="%s">%s</a><p>... |
def xy_to_uv60(x, y): # CIE1931 to CIE1960
""" convert CIE1931 xy to CIE1960 uv coordinates
:param x: x value (CIE1931)
:param y: y value (CIE1931)
:return: CIE1960 u, v """
denominator = ((-2 * x) + (12 * y) + 3)
if denominator == 0.0:
u60, v60 = 0.0, 0.0
else:
u6... |
def _parse_mount_location(mount_output, device_location):
"""
GENERAL ASSUMPTION:
Mount output is ALWAYS the same, and it looks like this:
<DEV_LOCATION> on <MOUNT_LOCATION> type (Disk Specs ...)
By splitting ' on ' AND ' type '
we can always retrieve <MOUNT_LOCATION>
"""
for li... |
def get_deadline_delta(target_horizon):
"""Returns number of days between official contest submission deadline date
and start date of target period
(14 for week 3-4 target, as it's 14 days away,
28 for week 5-6 target, as it's 28 days away)
Args:
target_horizon: "34w" or "56w" indicating whe... |
def largest(A):
"""
Requires N-1 invocations of less-than to determine max of N>0 elements.
"""
my_max = A[0]
for idx in range(1, len(A)):
if my_max < A[idx]:
my_max = A[idx]
return my_max |
def jinja_filter_param_value_str(value, str_quote_style=""):
""" Convert a parameter value to string suitable to be passed to an EDA tool
Rules:
- Booleans are represented as 0/1
- Strings are either passed through or enclosed in the characters specified
in str_quote_style (e.g. '"' or '\\"')
... |
def mat_compose(mats, f):
"""
Compose a sequence of matrices using the given mapping function
Parameters
----------
mats: list[list]
A sequence of matrices with equal dimensions
f: callable
A function that performs the mapping f:mats->composite,
where 'composite' is the ... |
def FileCrossRefLabel(msg_name):
"""File cross reference label."""
return 'envoy_api_file_%s' % msg_name |
def isprime(number):
"""
Check if a number is a prime number
number:
The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True |
def __count_statistic(pkey, pvalue, ptotalurls, ptotaltime):
"""
Count stat by each url
:param pkey: url
:param pvalue: list of req.times
:param ptotalurls: total urls
:param ptotaltime: total time
:return: list of data [
count of requests,
... |
def calc_f1(precision: float, recall: float) -> float:
"""
Compute F1 from precision and recall.
"""
return 2 * (precision * recall) / (precision + recall) |
def _map_uni_to_alpha(uni):
"""Maps [A-Z a-z] to numbers 0-52."""
if 65 <= uni <= 90:
return uni - 65
return uni - 97 + 26 |
def argsparselist(txt):
"""
Validate the list of txt argument.
:param txt: argument with comma separated int strings.
:return: list of strings.
"""
txt = txt.split(',')
listarg = [i.strip() for i in txt]
return listarg |
def test_bool(bool_var):
""" Test if a boolean is true and exists """
try:
bool_var
except NameError:
print("Failure with bool_var")
else:
return True |
def json_set(item, path, value):
"""
Set the value corresponding to the path in a dict.
Arguments:
item (dict): The object where we want to put a field.
path (str): The path separated with dots to the field.
value: The value to set on the field.
Return:
(dict): The update... |
def calc_confidence(freq_set, H, support_data, rules, min_confidence, verbose=False):
"""Evaluates the generated rules.
One measurement for quantifying the goodness of association rules is
confidence. The confidence for a rule 'P implies H' (P -> H) is defined as
the support for P and H divided by th... |
def ftest(x, y, z, w=10):
""" Test Documentation """
return x + y + z + w |
def safedel_message(key):
"""
Create safe deletion log message.
:param hashable key: unmapped key for which deletion/removal was tried
:return str: message to log unmapped key deletion attempt.
"""
return "No key {} to delete".format(key) |
def fromBase(num_base: int, dec: int) -> float:
"""returns value in e.g. ETH (taking e.g. wei as input)"""
return float(num_base / (10**dec)) |
def get_pivot_vars(rid):
"""Method to get pivot variables."""
try:
if rid == 1:
cols = ["case_year", "case_month"]
idx = ["county", "sub_county", "org_unit"]
elif rid == 3:
cols = ["sex"]
idx = ["unit_type", "org_unit"]
else:
co... |
def escape(s, quote=None):
"""Replace special characters '&', '<' and '>' by SGML entities."""
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
if quote:
s = s.replace('"', """)
return s |
def get_next_page_url(url: str) -> str:
"""Get the next page of a Flaticon search
Args:
url (str): URL for the current flaticon page
Returns:
str: URL for the next flaticon page
"""
if "/search" in url:
(base_url, args) = url.split("?", 1)
split_url = base_url.split... |
def jaccard_similarity(list1, list2):
"""
Calculate Jaccard Similarity between two sets
"""
intersection = len(list(set(list1).intersection((set(list2)))))
union = len(list1) + len(list2) - intersection
return float(intersection) / union |
def strip_brackets(string):
"""
remove parenthesis from a string
leave parenthesis between "<a></a>" tags in place
"""
string = "" + str(string)
d = 0
k = 0
out = ''
for i in string:
#check for tag when not in parantheses mode
if d < 1:
if i == '>':
... |
def decimal_to_binary(decimal):
"""Converts a decimal(int) into binary(str)"""
binary_result = ''
# new_decimal = int(decimal)
while decimal > 0:
remainder = decimal % 2
binary_result = str(remainder) + binary_result
decimal = int(decimal / 2)
return binary_result |
def stuff(a, b):
"""
:param a:
:param b:
:return:
"""
out = a + b
return out |
def linear_cell_to_tuple(c1, repeat_units):
"""
Convert a linear index into a tuple assuming lexicographic indexing.
:arg c1: (int) Linear index.
:arg repeat_units: (3 int indexable) Dimensions of grid.
"""
c1 = int(c1)
c1x = c1 % repeat_units[0]
c1y = ((c1 - c1x) // re... |
def listify(entry, names):
"""
Convert newline delimited strings into a list of strings.
Remove trailing newline which will generate a blank line.
Or replace None with "" in a list.
Accept a dictionary and return a new dictionary.
splicer:
c: |
// line 1
// line 2
c_... |
def tri_to_hex(x, y, z):
"""Given a triangle co-ordinate as specified in updown_tri, finds the hex that contains it"""
# Rotate the co-ordinate system by 30 degrees, and discretize.
# I'm not totally sure why this works.
# Thanks to https://justinpombrio.net/programming/2020/04/28/pixel-to-hex.html
... |
def duration(first, last):
"""Evaluate duration
Parameters
----------
first : int
First timestamp
last : int
Last timestamp
Returns
-------
str
Formatted string
"""
ret = ''
diff = last - first
if diff <= 0:
return ''
mm = divmod(di... |
def isEven(num:int) -> bool:
"""Add the missing code here to make sure that this
function returns true only for even numbers
>>> isEven(num=42)
True
>>> isEven(num=3)
False
"""
return not (num&1) |
def str_to_bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueError('Argument needs to be a boolean, got {}'.format(s))
return {'true': True, 'false': False}[s.lower()] |
def _timex_pairs(timexes):
"""Return a list of timex pairs where the first element occurs before the
second element on the input list."""
pairs = []
for i in range(len(timexes)):
for j in range(len(timexes)):
if i < j:
pairs.append([timexes[i], timexes[j]])
return... |
def convert_bytes(byte_amt):
"""
Stolen from http://www.5dollarwhitebox.org/drupal/node/84
"""
byte_amt = float(byte_amt)
if byte_amt >= 1099511627776:
terabytes = byte_amt / 1099511627776
size = '%.2fT' % terabytes
elif byte_amt >= 1073741824:
gigabytes = byte_amt / ... |
def tokens_to_sovatoms(tokens: float) -> int:
"""Convert tokens to sovatoms."""
return int(tokens * 100000000) |
def print_info_post_get(info_get=None):
"""Print information about the downloaded item from lbrynet get.
Parameters
----------
info_get: dict
A dictionary with the information obtained from downloading
a claim.
::
info_get = lbrynet_get(get_cmd)
Returns
----... |
def getYearDigits(a_year):
"""Returns year digits , given year"""
return abs(a_year % 100) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.