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.
return abs(n)
except TypeError:
# If it doesn't work, catch the exception, and try to apply map to it.
return list(map(better_abs_of_steel, n)) |
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 LETTER BUT ELSE IS FINE
ENGLISH_FLAG is True and
SIGNS_FLAG is True):
return False
elif (LENGTH_FLAG is True and # NOT IN ENGLISH AND SIGNS BUT IN LENGTH
SIGNS_FLAG is False):
return False
elif (ENGLISH_FLAG is False or # SAME AS UP BUT LONG STRING
(SIGNS_FLAG is False and
LENGTH_FLAG is False)):
return False
else:
return True |
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: '{}'. Title: '{}'".format(*fixture_value) |
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 = [[] for i in range(n_bins)] #make bins for up and down data
for i in range(len(data)):
bins[bin_inds[i]].append(data[i])
return 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/std.py#L228
try:
mins, s = divmod(int(timeValue), 60)
h, m = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
else:
return '{0:02d}:{1:02d}'.format(m, s)
except:
return None |
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']
else:
return ['most'] |
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 < len(dataset):
recordedActions.append(i)
action = dataset[i]
value = int(action.split(' ', 1)[-1])
if 'acc' in action:
accumulation += value
i += 1
elif 'jmp' in action:
i += value
elif 'nop' in action:
i += 1
if i in recordedActions:
bootSuccessful = False
break
return bootSuccessful, accumulation |
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
area = sqrt(p * (p - a) * (p - b) * (p - c))
return area
else:
raise ValueError("I can't calculate area of this triangle") |
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 <= 36, 'base is out of range: {}'.format(base)
digits = digits[::-1]
base_ten_conversion = 0
char_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'b':11,'c':12,'d':13,'e':14,'f':15,'g':16,'h':17,'i':18,'j':19,'k':20,'l':21,'m':22,'n':23,'o':24,'p':25,'q':26,'r':27,'s':28,'t':29,'u':30,'v':31,'w':32,'x':33,'y':34,'z':35}
base_mult = 1
for i, num in enumerate(digits):
base_ten_conversion += char_dict[num] * (base**i)
''' Was trying anther faster methode to do exponential mult '''
# base_ten_conversion += char_dict[num] * base_mult
# base_mult *= base_mult
# print(base_ten_conversion)
return base_ten_conversion
'''
decimalnum = 0
digits = digits[::-1]
for i in ranf(len(digits)):
digit = int(digits[i], base=base)
decimalnum = ------
return decimalnum
''' |
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
"""
return "G1 X{} Y{} E{}".format(round(x, 3), round(y, 3), round(extrusion, 5)) |
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((value,)) if value and isinstance(value, str) else collection_type(value) |
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: (int) The total number of combinations
"""
if k < 0 or k > n:
return 0
if k > n-k:
k = n-k
c = 1
for i in range(k):
c = c*(n - (k - (i+1)))
c = c // (i+1)
return c |
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)})"
)
```
Args:
i: number to return a color string for
"""
if i < 0:
return "rgb(189,189,189)" # light grey for specials
elif i % 8 == 0:
return "rgb(102,194,165)"
elif i % 8 == 1:
return "rgb(252,141,98)"
elif i % 8 == 2:
return "rgb(141,160,203)"
elif i % 8 == 3:
return "rgb(231,138,195)"
elif i % 8 == 4:
return "rgb(166,216,84)"
elif i % 8 == 5:
return "rgb(255,217,47)"
elif i % 8 == 6:
return "rgb(229,196,148)"
elif i % 8 == 7:
return "rgb(179,179,179)"
else:
raise NotImplementedError("") |
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+1)) # 0+
c+=1
t.append((c,0,c)) # 0*
return t, 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 passed to scope validation function.
Should return None if token is invalid or does not allow access to called API.
"""
return {'scopes': ['read:pets', 'write:pets'], 'uid': 'user_id'} |
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)
return result | set([module_name]) |
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', 11: 'WKS',
12: 'PTR', 13: 'HINFO', 14: 'MINFO', 15: 'MX', 16: 'TXT', 17: 'RP', 18: 'AFSDB', 19: 'X25', 20: 'ISDN',
21: 'RT', 22: 'NSAP', 23: 'NSAP-PTR', 24: 'SIG', 25: 'KEY', 26: 'PX', 27: 'GPOS', 28: 'AAAA', 29: 'LOC',
30: 'NXT', 31: 'EID', 32: 'NIMLOC', 33: 'SRV', 34: 'ATMA', 35: 'NAPTR', 36: 'KX', 37: 'CERT', 38: 'A6',
39: 'DNAME', 49: 'DHCID', 50: 'NSEC3', 51: 'NSEC3PARAM', 52: 'TLSA', 53: 'SMIMEA', 55: 'HIP', 56: 'NINFO',
57: 'RKEY', 58: 'TALINK', 59: 'CDS', 60: 'CDNSKEY', 61: 'OPENPGPKEY', 62: 'CSYNC', 99: 'SPF', 100: 'UINFO',
101: 'UID', 102: 'GID', 103: 'UNSPEC', 104: 'NID', 105: 'L32', 106: 'L64', 107: 'LP', 108: 'EUI48',
109: 'EUI164', 249: 'TKEY', 250: 'TSIG', 251: 'IXFR', 252: 'AXFR', 253: 'MAILB', 254: 'MAILA', 255: '*',
256: 'URI', 257: 'CAA', 258: 'AVC', 32768: 'TA', 32769: 'DLV'
}.get(key, 'OTHER') |
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 i) for i in str_list_1)
str2_size = sum(sum(len(j.strip()) for j in i) for i in str_list_2)
return str1_size/(str1_size + str2_size) |
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 ["false", "False", "0"]:
return False
raise Exception |
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(match)
return result |
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 by this function.
Returns:
List of integers.
"""
if isinstance(str_arg, int):
return [str_arg]
if len(str_arg) > 0:
return [int(s) for s in str_arg.split(',')]
else:
return [] |
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:
unit = "minute"
else:
unit = "minutes"
return "%1d %s" % (mins,unit)
else:
hrs = (secs / 3600)
if int(hrs) == 1:
unit = "hour"
else:
unit = "hours"
ret = ("%1d %s" % (hrs,unit))
if (secs % 3600):
ret = ret + " and " + friendly_time(secs % 3600)
return ret |
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 isinstance(data, (list, tuple)):
return tuple((make_hashable(item) for item in data))
elif isinstance(data, dict):
return tuple(
(key, make_hashable(value))
for key, value in sorted(data.items())
)
else:
return data |
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
"""
enteredValues=values.split(" ")
x=0
for value in range(len(enteredValues)):
x=x+len(enteredValues[value])
return x/len(enteredValues) |
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 the text are identical.
"""
c_pos = anchor_body.find(':')
if c_pos >= 0:
id_val = anchor_body[:c_pos]
anchor_body = anchor_body[c_pos+1:]
id_val = id_val or anchor_body
else:
id_val = anchor_body
return (id_val.casefold().rstrip(), anchor_body.strip()) |
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)
)
return '<link href=%s%s:%s" /rel="stylesheet">' % (
server, family.replace(' ', '+'), ','.join(styles)
) |
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
"""
c_json_dict = {}
for name, file_id in file_ids.items():
service_c = service.comments()
c_json_dict[name] = service_c.list(pageSize=100,
fileId=file_id,
fields="comments,kind,nextPageToken").execute()
return c_json_dict |
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 bpm > 153:
return 1
else:
return 0
elif age <= 50:
if bpm > 175:
return 2
elif bpm > 149:
return 1
else:
return 0
elif age <= 55:
if bpm > 170:
return 2
elif bpm > 145:
return 1
else:
return 0
elif age <= 60:
if bpm > 165:
return 2
elif bpm > 140:
return 1
else:
return 0
elif age <= 65:
if bpm > 160:
return 2
elif bpm > 136:
return 1
else:
return 0
elif age <= 70:
if bpm > 155:
return 2
elif bpm > 132:
return 1
else:
return 0
elif age > 70:
if bpm > 150:
return 2
elif bpm > 128:
return 1
else:
return 0 |
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
-------
score : double
The classification error between actual and predicted
"""
return (sum([1.0 for x,y in zip(actual,predicted) if x != y]) /
len(actual)) |
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', '150'], ['B', '750'], ['C', '300']], 'identifier': '02'}, ..]
To: [{'raw_str': 'ABC', 'identifier': '02'}, {'raw_str': 'AC', 'identifier': '03'}, .. ]
"""
scanpath_strs = []
# Extract scanpaths as raw string sequences with identifiers
for act_scanpath in scanpaths:
act_scanpath_str = ''
for fixation in act_scanpath['fixations']:
act_scanpath_str += fixation[0]
# Store the identifier and extracted string sequence in an object
temp_scanpath = {
'identifier': act_scanpath['identifier'],
'raw_str': act_scanpath_str
}
# Push the object to the array
scanpath_strs.append(temp_scanpath)
return scanpath_strs |
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 {
"method": "Runtime.setAsyncCallStackDepth",
"params": {"maxDepth": maxDepth},
} |
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
# return (0, 0)
#if u.db[1][0].dbid() >= 0:
# return (1, 0)
return (0, 0) |
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>%s</p>' % \
(picture.get_absolute_url(), picture.name, picture.description or '')
else:
return '' |
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:
u60 = (4 * x) / denominator
v60 = (6 * y) / denominator
return u60, v60 |
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 line in mount_output.split("\n"):
if device_location not in line:
continue
before_text_idx = line.find(" on ") + 4
after_text_idx = line.find(" type ")
if before_text_idx == -1 or after_text_idx == -1:
return ""
return line[before_text_idx:after_text_idx] |
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 whether target period is
weeks 3 & 4 or weeks 5 & 6
"""
if target_horizon == "34w":
deadline_delta = 14
elif target_horizon == "56w":
deadline_delta = 28
else:
raise ValueError("Unrecognized target_horizon "+target_horizon)
return deadline_delta |
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 '\\"')
- Everything else (including int, float, etc.) are converted using the str()
function.
"""
if type(value) == bool:
if (value) == True:
return '1'
else:
return '0'
elif type(value) == str:
return str_quote_style + str(value) + str_quote_style
else:
return str(value) |
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 resulting matrix. The function
f(m1[i,j],...,mn[i,j]) is applied to all elements of the
n matrices for each point.
Returns
-------
list[list]
The composite matrix
"""
return [[*map(f, *t)] for t in zip(*mats)]
# Solution 2
# Note: in this case f() must be a vector function
# return [*itertools.starmap(f, [*zip(*mats)])] |
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,
avarage url req.time,
max url req.time,
sum url req.time,
url,
median url req.time,
time in %,
number requests in %
"""
return [len(pvalue),
round(sum(t for t in pvalue) / len(pvalue), 3),
round(max(pvalue), 3),
round(sum(t for t in pvalue), 3),
pkey,
round(sorted(pvalue)[len(pvalue) // 2]
if len(pvalue) % 2
else sum(sorted(pvalue)[
len(pvalue) // 2 - 1:
len(pvalue) // 2 + 1]) / 2,
3),
round(sum(t for t in pvalue) * 100 / ptotaltime, 3),
round(len(pvalue) * 100 / ptotalurls, 3)
] |
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 updated object.
"""
tab = path.split(u".")
if tab[0] not in item and len(tab) > 1:
item[tab[0]] = {}
if len(tab) == 1:
item[tab[0]] = value
else:
item[tab[0]] = json_set(item[tab[0]], u".".join(tab[1:]), value)
return item |
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 the support for P
(support (P|H) / support(P)), where the | symbol denotes the set union
(thus P|H means all the items in set P or in set H).
To calculate the confidence, we iterate through the frequent itemsets and
associated support data. For each frequent itemset, we divide the support
of the itemset by the support of the antecedent (left-hand-side of the
rule).
Parameters
----------
freq_set : frozenset
The complete list of frequent itemsets.
H : list
A list of frequent itemsets (of a particular length).
min_support : float
The minimum support threshold.
rules : list
A potentially incomplete set of candidate rules above the minimum
confidence threshold.
min_confidence : float
The minimum confidence threshold. Defaults to 0.5.
Returns
-------
pruned_H : list
The list of candidate rules above the minimum confidence threshold.
"""
pruned_H = [] # list of candidate rules above the minimum confidence threshold
for conseq in H: # iterate over the frequent itemsets
conf = support_data[freq_set] / support_data[freq_set - conseq]
if conf >= min_confidence:
rules.append((freq_set - conseq, conseq, conf))
pruned_H.append(conseq)
if verbose:
print("" \
+ "{" \
+ "".join([str(i) + ", " for i in iter(freq_set-conseq)]).rstrip(', ') \
+ "}" \
+ " ---> " \
+ "{" \
+ "".join([str(i) + ", " for i in iter(conseq)]).rstrip(', ') \
+ "}" \
+ ": conf = " + str(round(conf, 3)) \
+ ", sup = " + str(round(support_data[freq_set], 3)))
return pruned_H |
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:
cols = ["agerange", "sex"]
idx = ["case_category"]
except Exception as e:
raise e
else:
return cols, idx |
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("/")
last_part = base_url.split("/")[-1]
if last_part.isnumeric():
split_url[-1] = str(int(last_part) + 1)
base_url = "/".join(split_url)
else:
base_url = base_url + "/2"
return base_url + "?" + args
else:
split_url = url.split("/")
last_part = url.split("/")[-1]
if last_part.isnumeric():
split_url[-1] = str(int(last_part) + 1)
return "/".join(split_url)
else:
return url + "/2" |
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 == '>':
k-=1
if i =="<":
k += 1
#check for parentheses
if k < 1:
if i == '(':
d += 1
if d > 0:
out += ' '
else:
out += i
if i == ')' :
d -= 1
else:
out +=i
return out |
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) // repeat_units[0]) % repeat_units[1]
c1z = (c1 - c1x - c1y * repeat_units[0]) // (repeat_units[0] * repeat_units[1])
return c1x, c1y, c1z |
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_buf:
- // Test adding a blank line below.
-
fstatements:
f:
local_var: pointer
call: |
blah blah
yada yada yada
Args:
entry - dictionary
names - key names which must be lists.
"""
new = {}
for key, value in entry.items():
if isinstance(value, dict):
new[key] = listify(value, names)
elif key in names:
if isinstance(value, str):
# if value[-1] == "\n":
# new[key] = [ value[:-1] ]
# else:
# new[key] = [ value ]
new[key] = value.split("\n")
if value[-1] == "\n":
new[key].pop()
elif isinstance(value, list):
new[key] = ["" if v is None else v for v in value]
else:
new[key] = [ str(value) ]
else:
new[key] = value
return new |
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
return (
round((x - z) / 3),
round((y - x) / 3),
round((z - y) / 3),
) |
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(diff, 60)[0]
if mm == 0:
# don't bother unless we have some minutes
return ''
hh, mm = divmod(mm, 60)
if hh > 24:
dd, hh = divmod(hh, 24)
ret = "%2dd %02dh" % (dd, hh)
elif hh > 0:
ret = "%2dh %02dm" % (hh, mm)
else:
ret = "%02dm" % (mm)
return ret |
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 pairs |
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 / 1073741824
size = '%.2fG' % gigabytes
elif byte_amt >= 1048576:
megabytes = byte_amt / 1048576
size = '%.2fM' % megabytes
elif byte_amt >= 1024:
kilobytes = byte_amt / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % byte_amt
return size |
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
-------
bool
It returns `True` if the information was read and printed
without problems.
If there is a problem or no item, it will return `False`.
"""
if not info_get:
print("Error: no item information. "
"Get the information with `lbrynet_get(cmd)`")
return False
err = False
if "error" in info_get:
print(">>> Error: " + info_get["error"])
err = True
elif not info_get["blobs_in_stream"]:
# In certain cases the information does not have blobs in the stream
# nor download path. This may need to be checked if it causes
# an error that cannot be handled later.
# elif (not info_get["blobs_in_stream"]
# or not info_get["download_path"]):
# print(info_get)
print(">>> Error in downloading claim, "
f"blobs_in_stream={info_get['blobs_in_stream']}, "
f"download_path={info_get['download_path']}")
err = True
if not err:
print("blobs_completed: {}".format(info_get["blobs_completed"]))
print("blobs_in_stream: {}".format(info_get["blobs_in_stream"]))
print("download_path: {}".format(info_get["download_path"]))
print("completed: {}".format(info_get["completed"]))
else:
print(">>> Skip download.")
return True |
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.