content stringlengths 42 6.51k |
|---|
def get_prime_factors(n):
"""Function returns the prime factors of the number provided as an argument. E.g. 12 = 2*2*3"""
factors = []
i = 2
while (i * i <= n):
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors |
def guess_angles(bonds):
"""Given a list of Bonds, find all angles that exist between atoms.
Works by assuming that if atoms 1 & 2 are bonded, and 2 & 3 are bonded,
then (1,2,3) must be an angle.
Returns
-------
list of tuples
List of tuples defining the angles.
Suitable for use in u._topology
See Also
--------
:meth:`guess_bonds`
.. versionadded 0.9.0
"""
angles_found = set()
for b in bonds:
for atom in b:
other_a = b.partner(atom) # who's my friend currently in Bond
for other_b in atom.bonds:
if other_b != b: # if not the same bond I start as
third_a = other_b.partner(atom)
desc = tuple([other_a.index, atom.index, third_a.index])
if desc[0] > desc[-1]: # first index always less than last
desc = desc[::-1]
angles_found.add(desc)
return tuple(angles_found) |
def problem_8_4(data):
""" Write a method to compute all permutations of a string. """
def inject(letter, s):
""" Inserts a given letter in evey possion of s. Complexity: O(n^2). """
out = []
for i in range(len(s)+1):
t = s[:i]+letter+s[i:]
out.append(t)
return out
def permutations(s):
""" Compute all permutation of a given string s, recursively by
computing the permutations of the string without the first letter,
then injecting the letter in evey possible locations.
"""
if len(s) == 1:
return [s]
head = s[0]
tail = s[1:]
perms = permutations(tail)
out = []
for p in perms:
out.extend(inject(head, p))
return out
return permutations(data) |
def name_here(my_name):
"""
Print a line about being a demo
Args:
my_name (str): person's name
Returns:
string with name and message
"""
output = "{} was ere".format(my_name)
return output |
def _pack_bytes(byte_list):
"""Packs a list of bytes to be a single unsigned int.
The MSB is the leftmost byte (index 0).
The LSB is the rightmost byte (index -1 or len(byte_list) - 1).
Big Endian order.
Each value in byte_list is assumed to be a byte (range [0, 255]).
This assumption is not validated in this function.
Args:
byte_list (list):
Returns:
The number resulting from the packed bytes.
"""
return int.from_bytes(byte_list, 'big', signed=False) |
def count_values(dictionary: dict) -> int:
""" Input is a dictionary and the output is the number of distict values it has"""
return len(set(dictionary.values())) |
def make_batches(size, batch_size):
"""
generates a list of (start_idx, end_idx) tuples for batching data
of the given size and batch_size
size: size of the data to create batches for
batch_size: batch size
returns: list of tuples of indices for data
"""
num_batches = (size + batch_size - 1) // batch_size # round up
return [
(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(num_batches)
] |
def _get_eth_link(vif, ifc_num):
"""Get a VIF or physical NIC representation.
:param vif: Neutron VIF
:param ifc_num: Interface index for generating name if the VIF's
'devname' isn't defined.
:return: A dict with 'id', 'vif_id', 'type', 'mtu' and
'ethernet_mac_address' as keys
"""
link_id = vif.get('devname')
if not link_id:
link_id = 'interface%d' % ifc_num
# Use 'phy' for physical links. Ethernet can be confusing
if vif.get('type') == 'ethernet':
nic_type = 'phy'
else:
nic_type = vif.get('type')
link = {
'id': link_id,
'vif_id': vif['id'],
'type': nic_type,
'mtu': vif['network']['meta'].get('mtu'),
'ethernet_mac_address': vif.get('address'),
}
return link |
def is_document(data):
""" Determine whether :data: is a valid document.
To be considered valid, data must:
* Be an instance of dict
* Have '_type' key in it
"""
return isinstance(data, dict) and '_type' in data |
def sub(slice_left, slice_right):
"""
Removes the right slice from the left. Does NOT account for slices on the right that do not touch the border of the
left
"""
start = 0
stop = 0
if slice_left.start == slice_right.start:
start = min(slice_left.stop, slice_right.stop)
stop = max(slice_left.stop, slice_right.stop)
if slice_left.stop == slice_right.stop:
start = min(slice_left.start, slice_right.start)
stop = max(slice_left.start, slice_right.start)
return slice(start, stop) |
def CalculateTFD(torsions1, torsions2, weights=None):
""" Calculate the torsion deviation fingerprint (TFD) given two lists of
torsion angles.
Arguments;
- torsions1: torsion angles of conformation 1
- torsions2: torsion angles of conformation 2
- weights: list of torsion weights (default: None)
Return: TFD value (float)
"""
if len(torsions1) != len(torsions2):
raise ValueError("List of torsions angles must have the same size.")
# calculate deviations and normalize (divide by max. possible deviation)
deviations = []
for t1, t2 in zip(torsions1, torsions2):
diff = abs(t1[0]-t2[0])
if (360.0-diff) < diff: # we do not care about direction
diff = 360.0 - diff
deviations.append(diff/t1[1])
# do we use weights?
if weights is not None:
if len(weights) != len(torsions1):
raise ValueError("List of torsions angles and weights must have the same size.")
deviations = [d*w for d,w in zip(deviations, weights)]
sum_weights = sum(weights)
else:
sum_weights = len(deviations)
tfd = sum(deviations)
if sum_weights != 0: # avoid division by zero
tfd /= sum_weights
return tfd |
def fibonacci_series_to(n):
"""This function calculates the fibonacci series until the "n"th element
Args:
n (int): The last element of the fibonacci series required
Returns:
list: the fibonacci series until the "n"th element
"""
l = [0, 1]
for i in range(n - 1):
l = [*l, l[-1] + l[-2]]
return l[:n] |
def evaluate_apartment(area: float, distance_to_underground: int) -> float:
"""Estimate price of an apartment."""
price = 200000 * area - 1000 * distance_to_underground
return price |
def declare(id, dtype):
"""
Create a SMT declaration
Args:
id (str): variable name
dtype (str): variable type
Returns:
str: declaration
"""
return '(declare-const ' + id + ' ' + dtype + ')\n' |
def parse_settings(settings):
"""
Parse the free-text entry field and
create a dictionary of parameters for
optimus
Parameters
----------
settings : str
a string containing settings to be past to
optimus
Returns
-------
dict
a dictionary full of parameters
not unlike a kwargs
"""
settings = settings.split(',')
settings = [s.split(':') for s in settings]
def _clean(s):
s = s.strip().lower()
try:
s = eval(s)
except:
pass
return s
settings = [list(map(_clean, l)) for l in settings]
return {l[0]:l[1] for l in settings} |
def avoid_tweets_from_users(current_user, users_to_avoid, reply_id):
"""
This function avoid tweets from certain users, to prevent shadowban
"""
avoid_tweet = False
if current_user in users_to_avoid:
print("Tweet ID: ", reply_id , "is from user", current_user, " | AVOIDED")
avoid_tweet = True
return avoid_tweet |
def gen_key_i(i, kappa, K):
"""
Create key value where key equals kappa, except:
key_(i mod n) = kappa_(i mod n) XOR K_(i mod n)
Parameters:
i -- integer in [0,n-1]
kappa -- string
K -- string
Return:
key -- list of bool
"""
# Transform string into list of booleans
kappa = list(kappa)
kappa = [bool(int(j)) for j in kappa]
K = list(K)
K = [bool(int(j)) for j in K]
# Initialize new key value
key_i = kappa.copy()
# XOR at indice i
key_i[i] = K[i] ^ kappa[i]
return key_i |
def color565(r, g, b):
"""Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As
a convenience this is also available in the parent adafruit_rgb_display
package namespace."""
return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3 |
def fib(n: int) -> int:
"""Fibonacci numbers with naive recursion
>>> fib(20)
6765
>>> fib(1)
1
"""
if n == 0: return 0
if n == 1: return 1
return fib(n-1) + fib(n-2) |
def case(text, casingformat='sentence'):
"""
Change the casing of some text.
:type text: string
:param text: The text to change the casing of.
:type casingformat: string
:param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'.
:raises ValueError: Invalid text format specified.
>>> case("HELLO world", "uppercase")
'HELLO WORLD'
"""
# If the lowercase version of the casing format is 'uppercase'
if casingformat.lower() == 'uppercase':
# Return the uppercase version
return str(text.upper())
# If the lowercase version of the casing format is 'lowercase'
elif casingformat.lower() == 'lowercase':
# Return the lowercase version
return str(text.lower())
# If the lowercase version of the casing format is 'sentence'
elif casingformat.lower() == 'sentence':
# Return the sentence case version
return str(text[0].upper()) + str(text[1:])
# If the lowercase version of the casing format is 'caterpillar'
elif casingformat.lower() == 'caterpillar':
# Return the caterpillar case version
return str(text.lower().replace(" ", "_"))
# Raise a warning
raise ValueError("Invalid text format specified.") |
def find_offsets(text, search_fn):
"""Find the start and end of an appendix, supplement, etc."""
start = search_fn(text)
if start is None or start == -1:
return None
post_start_text = text[start + 1:]
end = search_fn(post_start_text)
if end and end > -1:
return (start, start + end + 1)
else:
return (start, len(text)) |
def fib(n: int) -> int:
"""A recursive implementation of computation of Fibonacci numbers in Python. Will be slow in pretty much all languages, actually."""
# These will be needlessly evaluated on every internal call to fib() also.
if not isinstance(n, int):
raise TypeError("fib() takes an int.")
if n < 0:
raise ValueError("Value for n must be non-negative.")
if n == 0 or n == 1:
return 1
else:
# The same sub-computation for numbers less than n will be redone multiple times!
return fib(n - 1) + fib(n - 2) |
def join_s3_uri(bucket: str, key: str) -> str:
"""
Join AWS S3 URI from bucket and key.
"""
return "s3://{}/{}".format(bucket, key) |
def deg2arg(theta):
""" adjust angle to be in bounds of an argument angle
Parameters
----------
theta : unit=degrees
Returns
-------
theta : unit=degrees, range=-180...+180
See Also
--------
deg2compass
Notes
-----
The angle is declared in the following coordinate frame:
.. code-block:: text
^ North & y
|
- <--|--> +
|
+----> East & x
"""
return ((theta + 180) % 360) -180 |
def counts_to_probabilities(counts):
""" Convert a dictionary of counts to probalities.
Argument:
counts - a dictionary mapping from items to integers
Returns:
A new dictionary where each count has been divided by the sum
of all entries in counts.
Example:
>>> counts_to_probabilities({'a':9, 'b':1})
{'a': 0.9, 'b': 0.1}
"""
probabilities = {}
total = 0
for item in counts:
total += counts[item]
for item in counts:
probabilities[item] = counts[item] / float(total)
return probabilities |
def upper_first(text: str) -> str:
"""
Capitalizes the first letter of the text.
>>> upper_first(text='some text')
'Some text'
>>> upper_first(text='Some text')
'Some text'
>>> upper_first(text='')
''
:param text: to be capitalized
:return: text with the first letter capitalized
"""
if len(text) == 0:
return ''
return text[0].upper() + text[1:] |
def gpsfix2str(fix: int) -> str:
"""
Convert GPS fix integer to descriptive string
:param int fix: GPS fix time
:return GPS fix type as string
:rtype str
"""
if fix == 5:
fixs = "TIME ONLY"
elif fix == 4:
fixs = "GPS + DR"
elif fix == 3:
fixs = "3D"
elif fix == 2:
fixs = "2D"
elif fix == 1:
fixs = "DR"
else:
fixs = "NO FIX"
return fixs |
def sumOfSquares(n):
""" sumOfSquares
Output the sum of the first n positive integers, where
n is provided by the user.
passes:
n:
Output the sum of the first n positive integers, where
n is provided by the user.
returns:
Returns an array of the sum of the nth squared integers.
"""
sumVars = []
for x in range(1,n+1):
sumVars.append(x**2)
return sumVars |
def boolean_bitarray_get(integer, index):
"""The index-th-lowest bit of the integer, as a boolean."""
return bool((integer >> index) & 0x01) |
def format_orbital_configuration(orbital_configuration: list) -> str:
"""Prettily format an orbital configuration.
:param orbital_configuration: the list of the number of s, p, d and f orbitals.
:return: a nice string representation.
"""
orbital_names = ['s', 'p', 'd', 'f']
orbital_configuration_string = ''
for orbital, name in zip(orbital_configuration, orbital_names):
if orbital > 0:
orbital_configuration_string += f'{name}{orbital}'
return orbital_configuration_string |
def split(p):
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
i = p.rfind('/') + 1
head, tail = p[:i], p[i:]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head, tail |
def exempt(a, b):
"""
exempts b from a
"""
if a is None:
return set()
if b is None:
return a
return set(a) - set(b) |
def set_difference(A,B):
"""
Return elements of A not in B and elements of B not in A
"""
try:
return list(set(A) - set(B)), list(set(B) - set(A))
except Exception:
print ("Not hashable, trying again ... ")
Ahashable = [tuple(z) for z in A]
Bhashable = [tuple(z) for z in B]
return set_difference(Ahashable, Bhashable) |
def yes_no(flag: bool):
"""Boolean to natural readable string."""
return "Yes" if flag else "No" |
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
"""
To check equality of floats
:param a:
:param b:
:param rel_tol:
:param abs_tol:
:return:
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def m_pq(f, p, q):
"""
Two-dimensional (p+q)th order moment of image f(x,y)
where p,q = 0, 1, 2, ...
"""
m = 0
# Loop in f(x,y)
for x in range(0, len(f)):
for y in range(0, len(f[0])):
# +1 is used because if it wasn't, the first row and column would
# be ignored
m += ((x+1)**p)*((y+1)**q)*f[x][y]
return m |
def momentum(YYYYMM, YYYYMM_to_prc):
"""
Takes date string and dictionary that maps YYYYMM to price
Computed as (price month t-1 / price month t-12) - 1
Return "" (empty string) if date not compatible
Returns STRING
"""
# Get return t-1 key
YYYY = YYYYMM[:4]
MM = str(int(YYYYMM[4:]) - 1)
if len(MM) < 2: # Changing to int removes leading 0
MM = "0" + MM
YYYYMM_t1 = YYYY + MM
if YYYYMM[4:] == "01": # Current month is Jan.
YYYYMM_t1 = str(int(YYYYMM[:4]) - 1) + "12"
# Get return t-12 key
YYYYMM_t12 = str(int(YYYYMM[:4]) - 1) + YYYYMM[4:]
if YYYYMM_t1 in YYYYMM_to_prc and YYYYMM_t12 in YYYYMM_to_prc:
return str(YYYYMM_to_prc[YYYYMM_t1] / YYYYMM_to_prc[YYYYMM_t12] - 1)
else:
return "" |
def get_data_id(data) -> int:
"""Return the data_id to use for this layer.
Parameters
----------
layer
The layer to get the data_id from.
Notes
-----
We use data_id rather than just the layer_id, because if someone
changes the data out from under a layer, we do not want to use the
wrong chunks.
"""
if isinstance(data, list):
assert data # data should not be empty for image layers.
return id(data[0]) # Just use the ID from the 0'th layer.
return id(data) |
def is_rate_limited(sensor_name: str) -> bool:
"""Test whether sensor will have rate-limited updates."""
return sensor_name.startswith('pos_') |
def roll_mod(dice_string):
"""Return a dice roll modifier"""
return (int(dice_string),dice_string) |
def add_operator(_index, _operator):
"""Adds a an operator if index > 0, used in loops when making conditions."""
if _index > 0:
return ' ' + _operator + ' '
else:
return '' |
def get_users (db, filterspec, start, end) :
""" Get all users in filterspec (including department, organisation,
etc. where the user belongs to the given entity via a valid dyn
user record between start and end)
"""
users = filterspec.get ('user', [])
sv = dict ((i, 1) for i in filterspec.get ('supervisor', []))
svu = []
if sv :
svu = db.user.find (supervisor = sv)
users = dict ((u, 1) for u in users + svu)
found = bool (users)
olo = None
if 'organisation' in filterspec :
olo = db.org_location.filter \
(None, dict (organisation = filterspec ['organisation']))
for cl in 'department', 'org_location', 'org' :
if cl == 'org' :
cl = 'org_location'
spec = olo
else :
spec = filterspec.get (cl, [])
if spec :
found = True
for i in db.user_dynamic.filter \
( None
, {cl : spec, 'valid_from' : end.pretty (';%Y-%m-%d')}
) :
ud = db.user_dynamic.getnode (i)
if ( ud.valid_from <= end
and (not ud.valid_to or ud.valid_to > start)
) :
users [ud.user] = 1
if not found :
users = dict ((i, 1) for i in db.user.getnodeids (retired = False))
return users |
def oddsDueToChance(percentage, num_users = 5, num_choices = 2):
"""Simulates the odds that agreement is due to chance based off of a coinflip"""
#print('simulating chance')
return .5
if percentage<.5:
return 1
percentages = np.zeros(0)
for i in range(10000):
flips = np.random.choice(num_choices, num_users)
for choice in range(num_choices):
counts = []
counts.append(np.sum(flips == choice))
highCount = max(counts)
highScore = highCount/num_users
percentages = np.append(percentages, highScore)
#print(flips, counts, highCount,highScore, percentages)
winRate = np.sum(percentages>=percentage)/10000
#print('Done')
return winRate |
def cleanup_test_name(name, strip_tags=True, strip_scenarios=False):
"""Clean up the test name for display.
By default we strip out the tags in the test because they don't help us
in identifying the test that is run to it's result.
Make it possible to strip out the testscenarios information (not to
be confused with tempest scenarios) however that's often needed to
indentify generated negative tests.
"""
if strip_tags:
tags_start = name.find('[')
tags_end = name.find(']')
if tags_start > 0 and tags_end > tags_start:
newname = name[:tags_start]
newname += name[tags_end + 1:]
name = newname
if strip_scenarios:
tags_start = name.find('(')
tags_end = name.find(')')
if tags_start > 0 and tags_end > tags_start:
newname = name[:tags_start]
newname += name[tags_end + 1:]
name = newname
return name |
def id_2_path(
image_id: str,
is_train: bool = True,
data_dir: str = "../input/g2net-gravitational-wave-detection",
) -> str:
"""
modify from https://www.kaggle.com/ihelon/g2net-eda-and-modeling
"""
folder = "train" if is_train else "test"
return "{}/{}/{}/{}/{}/{}.npy".format(
data_dir, folder, image_id[0], image_id[1], image_id[2], image_id
) |
def get_popular_list(list_type):
"""
function to check the user supplied a valid list type for tracked
:param list_type: User supplied list
:return: A valid list type for the trakt api
"""
# if we got nothing set the default
if list_type is None:
list_type = 'boxoffice'
# fixing box office to slug type
if list_type == 'box office':
list_type = 'boxoffice'
x = ('popular', ' boxoffice', ' box office', 'trending', 'collected', 'played', 'watched')
if list_type not in x:
list_type = 'boxoffice'
return list_type |
def binary_search_array(array, x, left=None, right=None, side="left"):
"""
Binary search through a sorted array.
"""
left = 0 if left is None else left
right = len(array) - 1 if right is None else right
mid = left + (right - left) // 2
if left > right:
return left if side == "left" else right
if array[mid] == x:
return mid
if x < array[mid]:
return binary_search_array(array, x, left=left, right=mid - 1)
return binary_search_array(array, x, left=mid + 1, right=right) |
def find_values(obj, keys, key=None, val_type=list):
"""Find dictionary values of a certain type specified with certain keys.
Args:
obj (obj): a python object; initially the dictionary to search
keys (list): list of keys to find their matching list values
key (str, optional): key to check for a match. Defaults to None.
Returns:
dict: a dictionary of each matching key and its value
"""
def add_matches(found):
"""Add found matches to the match dictionary entry of the same key.
If a match does not already exist for this key add all the found values.
When a match already exists for a key, append the existing match with
any new found values.
For example:
Match Found Updated Match
--------- ------------ -------------
None [A, B] [A, B]
[A, B] [C] [A, B, C]
[A, B, C] [A, B, C, D] [A, B, C, D]
Args:
found (dict): dictionary of matches found for each key
"""
for found_key in found:
if found_key not in matches:
# Simply add the new value found for this key
matches[found_key] = found[found_key]
else:
is_list = isinstance(matches[found_key], list)
if not is_list:
matches[found_key] = [matches[found_key]]
if isinstance(found[found_key], list):
for found_item in found[found_key]:
if found_item not in matches[found_key]:
matches[found_key].append(found_item)
elif found[found_key] not in matches[found_key]:
matches[found_key].append(found[found_key])
if not is_list and len(matches[found_key]) == 1:
matches[found_key] = matches[found_key][0]
matches = {}
if isinstance(obj, val_type) and isinstance(key, str) and key in keys:
# Match found
matches[key] = obj
elif isinstance(obj, dict):
# Recursively look for matches in each dictionary entry
for obj_key, obj_val in list(obj.items()):
add_matches(find_values(obj_val, keys, obj_key, val_type))
elif isinstance(obj, list):
# Recursively look for matches in each list entry
for item in obj:
add_matches(find_values(item, keys, None, val_type))
return matches |
def represents_int(s: str) -> bool:
"""Checks if a string can be an integer
:param s: [description]
:type s: str
:raises RuntimeError: [description]
:raises ValueError: [description]
:return: [description]
:rtype: bool
"""
try:
int(s)
return True
except ValueError:
return False |
def binary_search(L, v):
"""(list, object) -> int
Return the index of the first occurrence of value in L, or return -1
if value is not in L.
>>> binary_search([1, 3, 4, 4, 5, 7, 9, 10], 1)
0
"""
i = 0
j = len(L) - 1
while i != j + 1:
m = (i + j) // 2
if L[m] < v:
i = m + 1
else:
j = m - 1
if 0 <= i < len(L) and L[i] == v:
return i
else:
return -1 |
def configure_policy(dims, params):
"""configures the policy and returns it"""
policy = None # SomePolicy(dims, params)
return policy |
def is_longer(L1: list, L2: list) -> bool:
"""Return True if and only if the length of L1 is longer than the length
of L2.
>>> is_longer([1, 2, 3], [4, 5])
True
>>> is_longer(['abcdef'], ['ab', 'cd', 'ef'])
False
>>> is_longer(['a', 'b', 'c'], [1, 2, 3])
False
"""
if len(L1) > len(L2):
return True
else:
return False |
def snake(string):
"""Convert to snake case.
Word word -> word_word
"""
return "_".join([word.lower() for word in string.split()]) |
def clues_login(text: str) -> bool:
""" Check for any "failed login" clues in the response code """
text = text.lower()
for clue in ("username", "password", "invalid", "authen", "access denied"):
if clue in text:
return True
return False |
def getIndicesOfNames(names_short, names_all):
"""Get the indices of the names of the first list in the second list.
names_short
is the first list
names_all
is the second list
Returns
a list of tuples with the index of the occurence in the list names_all
and the name
"""
indices = []
for count, name in enumerate(names_short):
if name:
matches = [(s, i)
for i, s in enumerate(names_all) if name in s]
if len(matches) == 0:
print("Did not found " + name)
elif len(matches) == 1:
indices.append((count, matches[0][1]))
else:
print("Multiple matches for " + name + ":")
for m in matches:
indices.append((count, m[1]))
return indices |
def check_isinstance(_types, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* is an instance
of one of *_types*; if not, raise an appropriate TypeError.
As a special case, a ``None`` entry in *_types* is treated as NoneType.
Examples
--------
>>> _api.check_isinstance((SomeClass, None), arg=arg)
"""
types = _types
none_type = type(None)
types = ((types,) if isinstance(types, type) else
(none_type,) if types is None else
tuple(none_type if tp is None else tp for tp in types))
def type_name(tp):
return ("None" if tp is none_type
else tp.__qualname__ if tp.__module__ == "builtins"
else f"{tp.__module__}.{tp.__qualname__}")
for k, v in kwargs.items():
if not isinstance(v, types):
names = [*map(type_name, types)]
if "None" in names: # Move it to the end for better wording.
names.remove("None")
names.append("None")
raise TypeError(
"{!r} must be an instance of {}, not a {}".format(
k,
", ".join(names[:-1]) + " or " + names[-1]
if len(names) > 1 else names[0],
type_name(type(v)))) |
def is_valid_input(input):
"""
Checks if the value in the speed changes textboxes are valid input
"""
try:
float(input)
except ValueError:
return False
return True |
def sort_dict_by_key(d):
"""Sort a dict by key, return sorted dict."""
return dict(sorted(d.items(), key=lambda k: k[0])) |
def resolve_digests(digests, short_digests):
""" resolves a list of short_digests into full digests
returns the list of list of digests and a error flag
"""
result = []
error = False
for inner_short_digests in (short_digests or []):
inner_result = []
for short_digest in inner_short_digests:
found = [d for d in digests if d.startswith(short_digest)]
if len(found) != 1:
if not found:
print(f"{short_digest} not found!")
else:
print(f"{short_digest} amigous: {', '.join(found)}!")
error = True
else:
inner_result.append(found[0])
result.append(inner_result)
return result, error |
def valid_role(role):
"""
returns the valid role from a role mention
:param role: role to validate
:return: role of id, None otherwise
"""
if role is None:
return None
if role[0:3] == "<@&" and role[len(role)-1] == ">":
id = role[3:len(role)-1]
if id.isdigit():
return id
else:
return None
return None |
def combine_json_dict(body_dict, surf_dict):
"""
combine the json dict for both the surface wave and the body wave
"""
for net_sta in body_dict:
for level1_key in ["misfit_r", "misfit_t", "misfit_z", "property_times"]:
for level2_key in body_dict[net_sta][level1_key]:
body_dict[net_sta][level1_key][level2_key] = body_dict[net_sta][
level1_key][level2_key] or surf_dict[net_sta][level1_key][level2_key]
for level1_key in ["window_length", "amplitude"]:
for level2_key in body_dict[net_sta][level1_key]:
for level3_key in body_dict[net_sta][level1_key][level2_key]:
body_dict[net_sta][level1_key][level2_key][level3_key] = body_dict[net_sta][level1_key][
level2_key][level3_key] or surf_dict[net_sta][level1_key][level2_key][level3_key]
return body_dict |
def pair_glb(a, b, lattice, encoding):
"""Calculates the greatest lower bound of the pair (`a`, `b`)."""
if lattice[a][b] == 1:
return b
elif lattice[b][a] == 1:
return a
else:
entry = [a * b for a, b in zip(lattice[a], lattice[b])]
return encoding.get(tuple(entry), 0) |
def digitsum(number):
"""The digitsum function returns the sum of each digit in
a number."""
digits = [int(digit) for digit in str(number)]
return sum(digits) |
def site_stat_stmt(table, site_col, values_col, fun):
"""
Function to produce an SQL statement to make a basic summary grouped by a sites column.
Parameters
----------
table : str
The database table.
site_col : str
The column containing the sites.
values_col : str
The column containing the values to be summarised.
fun : str
The function to apply.
Returns
-------
str
SQL statement.
"""
fun_dict = {'mean': 'avg', 'sum': 'sum', 'count': 'count', 'min': 'min', 'max': 'max'}
cols_str = ', '.join([site_col, fun_dict[fun] + '(' + values_col + ') as ' + values_col])
stmt1 = "SELECT " + cols_str + " FROM " + table + " GROUP BY " + site_col
return stmt1 |
def s(s, name=""):
"""Return wapitified unigram/bigram output features"""
return "*:%s=%s" % (name, s) |
def readFile(sFile, sMode = 'rb'):
"""
Reads the entire file.
"""
oFile = open(sFile, sMode);
sRet = oFile.read();
oFile.close();
return sRet; |
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('editorial_features', None))
) |
def length_from(index, text, expansion_length=0):
"""Find the expansion length of the sub-palindrome centered at index, by direct character comparisons."""
start = index - expansion_length
end = index + expansion_length
while start > 0 and end < (len(text) - 1):
if text[start - 1] == text[end + 1]:
start -= 1
end += 1
expansion_length += 1
else:
break
return expansion_length |
def to_int16(y1, y2):
"""Convert two 8 bit bytes to a signed 16 bit integer."""
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x |
def isfused(cycle_sets):
"""Determine whether all cycles (represented as sets of node IDs) share at least one node."""
intersection = cycle_sets[0]
for cycle in cycle_sets[1:]:
intersection = intersection.intersection(cycle)
return len(intersection) > 0 |
def format_byte(size: int, decimal_places: int = 3):
"""
Formats a given size and outputs a string equivalent to B, KB, MB, or GB
"""
if size < 1e03:
return f"{round(size, decimal_places)} B"
if size < 1e06:
return f"{round(size / 1e3, decimal_places)} KB"
if size < 1e09:
return f"{round(size / 1e6, decimal_places)} MB"
return f"{round(size / 1e9, decimal_places)} GB" |
def polygon_clip(subjectPolygon, clipPolygon):
""" Clip a polygon with another polygon.
Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python
Args:
subjectPolygon: a list of (x,y) 2d points, any polygon.
clipPolygon: a list of (x,y) 2d points, has to be *convex*
Note:
**points have to be counter-clockwise ordered**
Return:
a list of (x,y) vertex point for the intersection polygon.
"""
def inside(p):
return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0])
def computeIntersection():
dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]]
dp = [s[0] - e[0], s[1] - e[1]]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s): outputList.append(computeIntersection())
outputList.append(e)
elif inside(s):
outputList.append(computeIntersection())
s = e
cp1 = cp2
if len(outputList) == 0: return None
return (outputList) |
def runtime_enabled_function(name):
"""Returns a function call of a runtime enabled feature."""
return 'RuntimeEnabledFeatures::%sEnabled()' % name |
def edit(a, b):
"""Calculate the simple edit distance between two strings."""
def snake(m, n, k, pp, ppp):
y = max(pp, ppp)
x = y - k
while x < m and y < n and a[x] == b[y]:
x += 1
y += 1
return y
m = len(a)
n = len(b)
if m >= n:
a, b = b, a
m, n = n, m
offset = m + 1
delta = n - m
size = m + n + 3
fp = [-1] * size
p = -1
while True:
p += 1
for k in range(-p, delta):
fp[k + offset] = snake(m, n, k, fp[k - 1 + offset] + 1, fp[k + 1 + offset])
for k in range(delta + p, delta, -1):
fp[k + offset] = snake(m, n, k, fp[k - 1 + offset] + 1, fp[k + 1 + offset])
fp[delta + offset] = snake(m, n, delta, fp[delta - 1 + offset] + 1, fp[delta + 1 + offset])
if fp[delta + offset] >= n:
break
return delta + 2 * p |
def is_palindrome_recursive(text):
"""Best and worst case running time: O(n) because must be traversed to at
least halfway through the list"""
if len(text) <= 1:
return True
while len(text) > 0 and not text[0].isalpha():
text = text[1:]
while len(text) > 0 and not text[len(text)-1].isalpha():
text = text[:len(text)-1]
if text[0].lower() != text[len(text)-1].lower():
return False
else:
text = text[1:len(text)-1]
while len(text) > 0 and not text[0].isalpha():
text = text[1:]
while len(text) > 0 and not text[len(text)-1].isalpha():
text = text[:len(text)-1]
return is_palindrome_recursive(text) |
def is_issn(s):
"""
Does the `s` looks like valid ISSN.
Warning:
This function doesn't check the ISSN validity, just the basic
differentiation between URL and ISSN:
"""
return all([
c.isdigit() or c in "-x "
for c in s.lower()
]) |
def gen_api_request_packet(opcode, body=""):
"""
Generate api request packet
"""
return "{}\n{}\n{}".format(opcode, len(body), body) |
def findTimeSpaceIndexs(a, timeToSearch):
"""
>>> findTimeSpaceIndexs([1,2,3], 3.6)
(2, 2)
>>> findTimeSpaceIndexs([1,2,3], 2.6)
(1, 2)
>>> findTimeSpaceIndexs([1,2,3], 0.6)
(0, 0)
"""
(i, v) = min(enumerate(a), key=lambda x: abs(x[1] - timeToSearch))
if v > timeToSearch:
if i > 0:
return (i - 1, i)
else:
return (i, i)
else:
if i < len(a) -1:
return (i, i+1)
else:
return (i,i) |
def same_ranks(ranks):
"""
Return `True` if the cards in a list of ranks are all of the same
rank, false otherwise.
"""
set_length = len(set(ranks))
return set_length == 1 or set_length == 0 |
def _string_contains(arg, substr):
"""
Determine if indicated string is exactly contained in the calling string.
Parameters
----------
substr
Returns
-------
contains : boolean
"""
return arg.find(substr) >= 0 |
def linear_search_1(array, item):
"""Returns position of item in array if item is found in array
else returns length(array).
Time Complexity O(n)
"""
for i in range(len(array)):
if array[i] == item:
return i
return len(array) |
def _calculate_meta(meta, bases):
"""Calculate the most derived metaclass."""
winner = meta
for base in bases:
base_meta = type(base)
if issubclass(winner, base_meta):
continue
if issubclass(base_meta, winner):
winner = base_meta
continue
# else:
raise TypeError("metaclass conflict: "
"the metaclass of a derived class "
"must be a (non-strict) subclass "
"of the metaclasses of all its bases")
return winner |
def samplesheet_headers_to_dict(samplesheet_headers: list) -> dict:
"""
Given a list of headers extracted with extract_samplesheet_header_fields, will parse them into a dictionary
:param samplesheet_headers: List of header lines
:return: Dictionary containing data that can be fed directly into the RunSamplesheet model (keys are attributes)
"""
attr_dict = {}
for line in samplesheet_headers:
components = line.split(',')
_attr = components[0].lower().replace(" ", "_")
try:
_val = components[1]
except IndexError:
_val = ""
attr_dict[_attr] = _val
return attr_dict |
def listtimes(list, c):
"""multiplies the elements in the list by the given scalar value c"""
ret = []
for i in range(0, len(list)):
ret.extend([list[i]]*c);
return ret; |
def new_context(context_name, cluster_ca, config, username):
"""Build a new context and return cluster and context dictionaries."""
cluster_address = config['contexts'][context_name]['cluster_address']
cluster_dict = {'cluster': {'api-version': 'v1',
'certificate-authority-data': cluster_ca, 'server':
cluster_address}, 'name': context_name}
context_dict = {'context': {'cluster': context_name, 'user': username},
'name': context_name}
return {'context': context_dict, 'context_cluster': cluster_dict} |
def _ensure_unicode(data):
"""Ensures that bytes are decoded.
Args:
data: The data to decode if not already decoded.
Returns:
The decoded data.
"""
if isinstance(data, bytes):
data = data.decode('UTF-8')
return data |
def remove_non_ascii(text):
"""Returns A String with Non ASCII removed"""
import unicodedata
result = (
unicodedata.normalize("NFKD", text)
.encode("ascii", "ignore")
.decode("utf-8", "ignore")
)
return result |
def kickstarter_prediction(main_category, deadline, goal, launched):
"""Uses params to return if results will be successful or not"""
results = "SUCCESS! You're project is likely to succeed."
return results |
def check_upgrades_link_back(item_id, all_items_data):
"""Every upgrade this item can build into should list this item
as a component.
Return a list with the errors encountered."""
item_data = all_items_data[item_id]
if 'into' not in item_data:
return []
errors = []
upgrades = item_data['into']
for upgrade_id in upgrades:
if upgrade_id not in all_items_data:
# Upgrade doesn't exist.
message = "{} lists {} as an upgrade, but it doesn't exist."
errors.append(message.format(item_id, upgrade_id))
else:
upgrade = all_items_data[upgrade_id]
if "from" not in upgrade or item_id not in upgrade['from']:
message = "{} upgrades to {}, but isn't listed as a component"
errors.append(message.format(item_id, upgrade_id))
return errors |
def NormalizeEol(context, text):
"""
Normalizes end-of-line characters in input string, returning the
normalized string. Normalization involves replacing "\n\r", "\r\n"
or "\r" with "\n"
"""
text = text.replace("\n\r", "\n")
text = text.replace("\r\n", "\n")
text = text.replace("\r", "\n")
return text |
def sign(x):
"""Returns sign of x. -1 if x is negative, 1 if positive and zero if 0.
>>> x and (1, -1)[x < 0]
"""
return x and (1, -1)[x < 0] |
def quote_remover(var):
"""
Helper function for removing extra quotes from a variable in case it's a string.
"""
if type(var) == str:
# If string, replace quotes, strip spaces
return var.replace("'", "").replace('"','').strip()
else:
# If not string, return input
return |
def clip(minval, val, maxval):
"""Clips a value between min and max (both including)."""
if val < minval:
return minval
elif val > maxval:
return maxval
else:
return val |
def addon_apt(sources, packages):
"""Standard addon for apt."""
return {
"apt": {
"sources": sources,
"packages": packages
}
} |
def srnirnarrowre1(b5, b8a):
"""
Simple NIR and Red-edge 1 Ratio (Datt, 1999b).
.. math:: SRNIRnarrowRE1 = b8a/b5
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
:returns SRNIRnarrowRE1: Index value
.. Tip::
Datt, B. 1999b. Visible/near infrared reflectance and chlorophyll \
content in Eucalyptus leaves. International Journal of Remote Sensing \
20, 2741-2759. doi:10.1080/014311699211778.
"""
SRNIRnarrowRE1 = b8a/b5
return SRNIRnarrowRE1 |
def mergeToRanges(ls):
""" Takes a list like ['1', '2', '3', '5', '8', 9'] and returns a list like
['1-3', '5', '8', '9'] """
if len(ls) < 2:
return ls
i = 0
while i < len(ls)-1 and \
((ls[i].isdigit() and ls[i+1].isdigit() and \
int(ls[i])+1 == int(ls[i+1])) or \
(len(ls[i]) == 1 and len(ls[i+1]) == 1 and \
ord(ls[i])+1 == ord(ls[i+1]))):
i += 1
if i < 2:
return ls[0:i+1]+mergeToRanges(ls[i+1:])
else:
return [ls[0]+'-'+ls[i]]+mergeToRanges(ls[i+1:]) |
def merge_dicts(dicts, kkey, vkey):
"""
Map kkey value to vkey value from dicts in dicts.
Parameters
----------
dicts : iterable
Dicts.
kkey : hashable
The key to fetch values from dicts to be used as keys.
vkey : hashable
The key to fetch values from dicts to be used as values.
Returns
-------
dict
A new dict that maps kkey values from dicts to vkey values from
dicts.
"""
return {d.get(kkey): d.get(vkey) for d in dicts if kkey in d and vkey in d} |
def bw2nw(bw, n, fs, halfint=True):
"""Full BW to NW, given sequence length n"""
# nw = tw = t(bw)/2 = (n/fs)(bw)/2
bw, n, fs = list(map(float, (bw, n, fs)))
nw = (n / fs) * (bw / 2)
if halfint:
# round 2NW to the closest integer and then halve again
nw = round(2 * nw) / 2.0
return nw |
def intersection(r1, r2):
"""
Helper method to obtain intersection of two rectangles
r1 = [x1,y1,w1,h1]
r2 = [x2,y2,w2,h2]
returns [x,y,w,h]
"""
assert len(r1) == 4 and len(r2) == 4, "Rectangles should be defined as [x,y,w,h]"
rOut = [0, 0, 0, 0]
rOut[0] = max(r1[0], r2[0])
rOut[1] = max(r1[1], r2[1])
rOut[2] = min(r1[0] + r1[2] - 1, r2[0] + r2[2] - 1) - rOut[0] + 1
rOut[3] = min(r1[1] + r1[3] - 1, r2[1] + r2[3] - 1) - rOut[1] + 1
if rOut[2] <= 0 or rOut[3] <= 0:
return None
return rOut |
def build_command_line_parameter(name, value):
"""
Some parameters are passed as command line arguments. In order to be able
to recognize them they are passed following the expression below.
Note that strings are always encoded to base64, so it is guaranteed that
we will always have exactly two underscores on the parameter.
:param name: Name of the parameter
:param value: Value of the parameter
:return: *PARAM_name_value. Example, variable y equals 3 => *PARAM_y_3
"""
return '*INLINE_%s_%s' % (name, str(value)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.