content
stringlengths 42
6.51k
|
|---|
def normalize_project_name(project): # pragma: no cover
"""Return the canonical name for a project specification."""
mapping = {
'nacl': 'nativeclient',
'cros': 'chromium-os',
}
return mapping.get(project, project)
|
def fullname(obj):
"""Returns full name of object"""
if hasattr(obj, '__module__'):
module = obj.__module__
else:
module = obj.__class__.__module__
if hasattr(obj, '__name__'):
name = obj.__name__
else:
name = obj.__class__.__name__
if module is None or module == str.__module__:
return name
return f'{module}.{name}'
|
def int_to_c(k, x_width):
"""
Takes an integer and a width and returns a complex number.
"""
ik = k >> x_width
qk = k % pow(2, x_width)
maxint = pow(2, x_width)-1
i = ik * 2.0 / maxint
q = qk * 2.0 / maxint
if i > 1:
i -= 2
if q > 1:
q -= 2
return i + (0+1j)*q
|
def fibonacci_series_from_to(m, n):
"""This function calculates the fibonacci series from the "m"th
element until the "n"th element
Args:
m (int): The first element of the fibonacci series required
n (int): The last element of the fibonacci series required
Returns:
list: the fibonacci series from the "n"th element until the "n"th
element
"""
l = [0, 1]
for i in range(n - 1):
l = [*l, l[-1] + l[-2]]
return l[m - 1:n]
|
def searchCatchwords(string):
"""
Splits String (at '_', '-' and '.' and searches for non-digit strings that
are longer than 2 characters.
Arguments:
string (string): The string to be searched.
"""
#Exceptions that should not be considered Catchwords
exceptions = ['tif', 'aux', 'ref', 'etrs']
#Create empty list
Catchwords = []
#Split list at underscores
split_list_underscore = string.split('_')
for item in split_list_underscore:
#Split items in list at points
split_list_point = item.split('.')
for item in split_list_point:
#Split items in list at hyphen
split_list = item.split('-')
for item in split_list:
#Make all items lowercase to enable removing duplicates with list(set())
item = item.lower()
if not item in exceptions:
#Do not consider items with digits as Catchwords
if not item.isdigit():
if not len(item)<3:
Catchwords.append(item)
return Catchwords
|
def max_value(table):
"""
brief: give max number of a list
Args:
table: a list of numeric values
Return:
the max number
the index max number
Raises:
ValueError if table is not a list
ValueError if table is empty
"""
if not(isinstance(table, list)):
raise ValueError('Expected a list as input')
if len(table)==0:
raise ValueError('provided list is empty')
maxVal=-99
idx=-11
NMAX=len(table)
for index in range(0,NMAX):
if table[index] > maxVal:
maxVal=table[index]
idx=index
return maxVal,idx
|
def extract_submittable_jobs( waiting ):
"""Return all jobs that aren't yet submitted, but have no dependencies that have
not already been submitted."""
submittable = []
for job in waiting:
unsatisfied = sum([(subjob.submitted==0) for subjob in job.dependencies])
if unsatisfied == 0:
submittable.append( job )
return submittable
|
def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int:
"""
Returns the closest numerator of the fraction immediately to the
left of given fraction (numerator/denominator) from a list of reduced
proper fractions.
>>> solution()
428570
>>> solution(3, 7, 8)
2
>>> solution(6, 7, 60)
47
"""
max_numerator = 0
max_denominator = 1
for current_denominator in range(1, limit + 1):
current_numerator = current_denominator * numerator // denominator
if current_denominator % denominator == 0:
current_numerator -= 1
if current_numerator * max_denominator > current_denominator * max_numerator:
max_numerator = current_numerator
max_denominator = current_denominator
return max_numerator
|
def process_group(grp):
"""
Given a list of list of tokens,
of the form "A B ... C (contains x, y, z)"
where A, B, C are strings of ingredients,
and x, y, z are allergens, determine the
count of the ingredients that definitely
do not contain any allergens.
:param grp: A list of list of tokens.
:return: A count of the occurrences of
"good"(allergen-free) ingredients.
"""
def parse_line(s):
"""
Given a single token
of the form
"A B ... C (contains x, y, z)"
parse it and return a set of
ingredients and its corresponding
allergens.
:param s: A string representing token.
:return a, b: A tuple of sets representing
the ingredients and allergens.
"""
s = s.replace(" (", " ").replace(", ", " ").replace(")", " ")
ingredients, allergens = s.split(" contains ")
a = set(ingredients.split(" "))
b = set(allergens.split(" ")) - {""}
return a, b
aller_to_ing = dict()
computed = []
for idx, line in enumerate(grp):
ing, aller = parse_line(line)
computed.append((set(x for x in ing), set(a for a in aller)))
for a in aller:
if a not in aller_to_ing:
aller_to_ing[a] = {x for x in ing}
else:
aller_to_ing[a] &= ing
# Potentially bad ingredients.
potential = set()
for x in aller_to_ing.values():
potential |= x
counter = 0
for ing, aller in computed:
for x in ing:
if x not in potential:
counter += 1
return counter
|
def count(values):
"""
Returns a dict of counts for each value in the iterable.
"""
counts = dict()
for v in values:
if v not in counts:
counts[v] = 0
counts[v] += 1
return counts
|
def linear_rampup(current, rampup_length):
"""Linear rampup"""
assert current >= 0 and rampup_length >= 0
if current >= rampup_length:
lr = 1.0
else:
lr = current / rampup_length
# print (lr)
return lr
|
def fnv1a_32(string: str, seed=0):
"""
Returns: The FNV-1a (alternate) hash of a given string
"""
#Constants
FNV_prime = 16777619
offset_basis = 2166136261
#FNV-1a Hash Function
hash = offset_basis + seed
for char in string:
hash = hash ^ ord(char)
hash = hash * FNV_prime
return hash
|
def gettype(a):
""" Distinguish between a number and a string:
Returns integer 1 if the argument is a number,
2 if the argument is a string.
"""
import re
type1 = re.compile("(^[+-]?[0-9]*[.]?[0-9]+$)|(^[+-]?[0-9]+[.]?[0-9]*$)|(^[+-]?[0-9]?[.]?[0-9]+[EeDd][+-][0-9]+$)")
if type1.match(a):
return 1
else:
return 2
|
def slug_from_id(page_id: str) -> str:
"""Extract Notion page slug from the given id, e.g. lwuf-kj3r-fdw32-mnaks -> lwufkj3rfdw32mnaks."""
return page_id.replace("-", "")
|
def _method_with_pos_reference_2(fake_value, other_value,
another_fake_value=2):
"""
:type other_value: [list, dict, str]
"""
return other_value.lower()
|
def IsInteger(Value):
"""Determine whether the specified value is an integer by converting it
into an int.
Arguments:
Value (str, int or float): Text
Returns:
bool : True, Value is an integer; Otherwsie, False.
"""
Status = True
if Value is None:
return False
try:
Value = int(Value)
Status = True
except ValueError:
Status = False
return Status
|
def convert_request_to_hashtag_list(title):
""" description
Parameters
----------
title : str
i.e. "#covid #vaccination"
Returns
-------
[str]
i.e. [covid, vaccination]
"""
cleaned_hashtags = []
if ' ' in title:
hashtags = title.split(" ")
for hashtag in hashtags:
cleaned_hashtags.append(hashtag[1:]) # removes the # symbol
else:
cleaned_hashtags.append(title[1:])
return cleaned_hashtags
|
def fix_walletserver_url(url: str) -> str:
"""
Help guide users against including api version suffix in wallet server URL.
"""
for suffix in ["/api/v1/", "/api/v1", "/api/", "/api", "/"]:
if not url.endswith(suffix):
continue
print(
f'There\'s no need to add "{suffix}" to the wallet server URL. '
"Removing it and continuing..."
)
url = url[: -len(suffix)]
return url
|
def pressure_to_elevation(pressure: float, p0: float) -> float:
"""
Calculate the elevation for a given pressure.
Args:
pressure: The pressure, in hPa (mbars)
p0: P0, the pressure at sea level.
Returns: Elevation in meters
"""
return (1 - ((pressure / p0) ** 0.190284)) * 145366.45 * 0.3048
|
def keyfunc(line):
"""Return the key from a TAB-delimited key-value pair."""
return line.partition("\t")[0]
|
def eval_expr(expr):
""" Evaluate an expression without parantheses.
"""
current = "".join(expr)
result = 1
for subexpr in current.split("*"):
result *= eval(subexpr)
return result
|
def has_numbers(inputString):
"""Check if there is a number in a string list and return True or False."""
return any(char.isdigit() for char in inputString)
|
def translate_to_hsv(in_color):
"""
Standard algorithm to switch from one color system (**RGB**) to another (**HSV**).
:param tuple(float,float,float) in_color: The RGB tuple list that gets translated to HSV system. The values of each element of the tuple is between **0** and **1**.
:return: The translated HSV tuple list. Returned values are *H(0-360)*, *S(0-100)*, *V(0-100)*.
:rtype: tuple(int, int, int)
.. important::
For finding out the differences between **RGB** *(Red, Green, Blue)* color scheme and **HSV** *(Hue, Saturation, Value)*
please check out `this link <https://www.kirupa.com/design/little_about_color_hsv_rgb.htm>`__.
"""
r,g,b = in_color
min_channel = min(in_color)
max_channel = max(in_color)
v = max_channel
delta = max_channel - min_channel
if delta < 0.0001:
s = 0
h = 0
else:
if max_channel > 0:
s = delta / max_channel
if r >= max_channel:
h = (g - b) / delta
elif g >= max_channel:
h = 2.0 + (b - r) / delta
else:
h = 4 + (r - g ) / delta
h = h * 60
if h < 0:
h = h + 360
else:
s = 0
h = 0
return (h, s * 100, v * 100)
|
def _node_parent_listener(target, value, oldvalue, initiator):
"""Listen for Node.parent being modified and update path"""
if value != oldvalue:
if value is not None:
if target._root != (value._root or value):
target._update_root(value._root or value)
target._update_path(newparent=value)
else:
# This node just got orphaned. It's a new root
target._update_root(target)
target._update_path(newparent=target)
return value
|
def validate_config(config):
"""Validates config"""
errors = []
required_config_keys = [
'aws_access_key_id',
'aws_secret_access_key',
's3_bucket'
]
# Check if mandatory keys exist
for k in required_config_keys:
if not config.get(k, None):
errors.append("Required key is missing from config: [{}]".format(k))
return errors
|
def calc_timeout(length, baud):
"""Calculate a timeout given the data and baudrate
Positional arguments:
length - size of data to be sent
baud - baud rate to send data
Calculate a reasonable timeout given the supplied parameters.
This function adds slightly more time then is needed, to accont
for latency and various configurations.
"""
return 12 * float(length) / float(baud) + 0.2
|
def flatten(groups):
"""Flatten a list of lists to a single list"""
return [item
for group in groups if group is not None
for item in group if item is not None]
|
def null_bytes_to_na(string):
"""
(str -> str) replace strings of only null bytes (\x00) with "n/a".
for M3L0 line prefix tables.
"""
if all([char == "\x00" for char in string]):
return "n/a"
return string
|
def make_hashable_list(lst: list) -> tuple:
"""
Recursively converts lists to tuples.
>>> make_hashable_list([1, [2, [3, [4]]]])
(1, (2, (3, (4,))))
"""
for n, index in enumerate(lst):
if isinstance(index, list):
lst[n] = make_hashable_list(index)
return tuple(lst)
|
def distance_greater(vec1, vec2, length):
"""Return whether the distance between two vectors is greater than the given length."""
return ((vec1[0] - vec2[0])**2 + (vec1[1] - vec2[1])**2) > length**2
|
def job_id(username):
"""
The id of the RQ job that is processing this user.
Redis key becomes `rq:job:{job_id(username)}`.
"""
return f'reddrec:recommend:{username.lower()}'
|
def get_deployment_endpoint(project, deployment):
"""Format endpoint service name using default logic.
Args:
project: str. Name of the deployed project.
deployment: str. Name of deployment - e.g. app name.
Returns:
endpoint_name: str. Endpoint service name.
"""
return "{deployment}.endpoints.{project}.cloud.goog".format(
project=project,
deployment=deployment)
|
def count_frequency(word_list):
"""
Count the frequency of each word in the list
by scanning the list of already encountered
words.
"""
D = dict()
for new_word in word_list:
if new_word in D:
D[new_word] = D[new_word] + 1
else:
D[new_word] = 1
return D
|
def find_artifact(artifacts, name):
"""Finds the artifact 'name' among the 'artifacts'
Args:
artifacts: The list of artifacts available to the function
name: The artifact we wish to use
Returns:
The artifact dictionary found
Raises:
Exception: If no matching artifact is found
"""
for artifact in artifacts:
if artifact['name'] == name:
return artifact
raise Exception('Input artifact named "{0}" not found in event'.format(name))
|
def market_on_close_order(liability):
"""
Create market order to be placed in the closing auction.
:param float liability: amount to bet.
:returns: Order information to place a market on close order.
:rtype: dict
"""
return locals().copy()
|
def check_collision_h(x,y,vx,eyes):
"""
eyes = [lx,ly,rx,ry]
"""
if ( (eyes[1] < y) and (y < eyes[3]) and (abs(x - eyes[0]) < abs(vx)) ):
return 2.0 * (y - eyes[1]) / (eyes[3] - eyes[1]) - 1
else:
return None
|
def is_palindrome(s: str) -> bool:
"""
Determine whether the string is palindrome
:param s:
:return: Boolean
>>> is_palindrome("a man a plan a canal panama".replace(" ", ""))
True
>>> is_palindrome("Hello")
False
>>> is_palindrome("Able was I ere I saw Elba")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("Mr. Owl ate my metal worm?")
True
"""
# Since Punctuation, capitalization, and spaces are usually ignored while checking
# Palindrome, we first remove them from our string.
s = "".join([character for character in s.lower() if character.isalnum()])
return s == s[::-1]
|
def case_lower(text):
"""
a function to convert English letters to lower case
"""
return text.lower()
|
def hilite(string, status, bold):
"""
Converts string color to be either red or green
"""
attr = []
if status:
# green
attr.append('32')
else:
# red
attr.append('31')
if bold:
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
|
def construct_hostname(region, account):
"""
Constructs hostname from region and account
"""
if region:
if account.find(u'.') > 0:
account = account[0:account.find(u'.')]
host = u'{0}.{1}.snowflakecomputing.com'.format(account, region)
else:
host = u'{0}.snowflakecomputing.com'.format(account)
return host
|
def colorGlobalRule(scModel, edgeTuples):
"""
:param scModel:
:param edgeTuples:
:return:
"""
found = False
for edgeTuple in edgeTuples:
op = scModel.getGroupOperationLoader().getOperationWithGroups(edgeTuple.edge['op'], fake=True)
if op.category == 'Color' or (op.groupedCategories is not None and 'Color' in op.groupedCategories):
found = True
break
return 'yes' if found else 'no'
|
def get_output_ext(data):
"""
Detects output extension based on file signature
"""
ext = ".bin"
if data[:3] == b'GIF':
ext = ".gif"
elif data[1:4] == b'PNG':
ext = ".png"
return ext
|
def is_list_of_type(check_list, check_type):
"""helper function for checking if it's a list and of a specific type"""
assert isinstance(check_list, list)
assert isinstance(check_list[0], check_type)
return True
|
def _path_from_name(name, type):
"""Expand a 'design/foo' style name to its full path as a list of
segments.
"""
if name.startswith('_'):
return name.split('/')
design, name = name.split('/', 1)
return ['_design', design, type, name]
|
def rect_center(rect):
"""Return the centre of a rectangle as an (x, y) tuple."""
left = min(rect[0], rect[2])
top = min(rect[1], rect[3])
return (left + abs(((rect[2] - rect[0]) / 2)),
top + abs(((rect[3] - rect[1]) / 2)))
|
def iseven(number):
"""
Convenience function to determine if a value is even. Returns boolean
value or numpy array (depending on input)
"""
result = (number % 2) == 0
return result
|
def convertfrom_epoch_time(epoch_time: "int | float"):
"""Takes a given epoch timestamp int or float and converts it to a datetime object.
Examples:
>>> now = get_epoch_time()\n
>>> now\n
1636559940.508071
>>> now_as_dt_obj = convertfrom_epoch_time( now )\n
>>> now_as_dt_obj\n
datetime.datetime(2021, 11, 10, 7, 59, 0, 508071)
>>> convertto_human_readable_time( now_as_dt_obj )\n
'2021-11-10 07:59:00.508071'
Args:
epoch_time (int | float): Reference an epoch timestamp that is an int or a float.
Returns:
datetime.datetime: Returns a datetime object.
"""
import datetime
dt_obj = datetime.datetime.fromtimestamp(epoch_time)
return dt_obj
|
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
scoreboard = {}
for dice in hand:
if dice not in scoreboard.keys():
scoreboard[dice] = dice
else:
scoreboard[dice] += dice
max_score = 0
for dice, score in scoreboard.items():
if score >= max_score:
max_score = score
return max_score
|
def is_sorted(lyst):
""" This function test if a list is sorted and returns true if it is
"""
result = True
for num in range(1, len(lyst)):
if lyst[num-1] > lyst[num]:
result = False
return result
|
def flatten(lst):
"""Flatten `lst` (return the depth first traversal of `lst`)"""
out = []
for v in lst:
if v is None:
continue
if isinstance(v, list):
out.extend(flatten(v))
else:
out.append(v)
return out
|
def stringify_dict(_dict):
"""make all dict values to be string type"""
new_dict = dict((key, str(value)) for key, value in _dict.items())
print(new_dict)
return new_dict
|
def vowel_rule(word):
"""
If word starts with vowel, just add "way" to the end.
Args:
word (str): Word to translate.
Returns:
(str): Translated word.
"""
return word + "way"
|
def nicenum(num):
"""Return a nice string (eg "1.23M") for this integer."""
index = 0;
n = num;
while n >= 1024:
n /= 1024
index += 1
u = " KMGTPE"[index]
if index == 0:
return "%u" % n;
elif n >= 100 or num & ((1024*index)-1) == 0:
# it's an exact multiple of its index, or it wouldn't
# fit as floating point, so print as an integer
return "%u%c" % (n, u)
else:
# due to rounding, it's tricky to tell what precision to
# use; try each precision and see which one fits
for i in (2, 1, 0):
s = "%.*f%c" % (i, float(num) / (1<<(10*index)), u)
if len(s) <= 5:
return s
|
def compose_maxmin(R, S):
"""
X = {1: 0, 2: 0.2, 3: 0.4}
Y = {1: 0, 2: 0.2}
Relation (X*Y) = {(1, 1): 0, (1, 2): 0, (2, 1): 0, (2, 2): 0.04, (3, 1): 0, (3, 2): 0.08}
:param R: a dictionary like above example that
:param S: a dictionary like above example
:return: RoS a composition of R to S
For example:
R = {(1,1):0.7, (1,2):0.3, (2,1):0.8, (2,2):0.4}
S = {(1,1):0.9, (1,2):0.6, (1,3):0.2, (2,1):0.1, (2,2):0.7, (2,3):0.5}
RoS = {(1, 2): 0.6, (1, 3): 0.3, (2, 3): 0.4, (2, 2): 0.6, (1, 1): 0.7, (2, 1): 0.8}
"""
if not isinstance(R, dict):
raise TypeError("input argument should be a dictionary.")
if not isinstance(S, dict):
raise TypeError("input argument should be a dictionary.")
if len(list(R.keys())) < 1:
raise ValueError("dictionary 'R' should have at least one member.")
if len(list(S.keys())) < 1:
raise ValueError("dictionary 'S' should have at least one member.")
X = []
Yx = []
Yz = []
Z = []
for key, value in R.items():
X.append(key[0])
Yx.append(key[1])
if not isinstance(value, float):
raise TypeError("value of dictionary R in "+str(key)+" should be a float.")
elif not 0.0 <= value <= 1.0:
raise TypeError("value of membership of R in "+str(key)+" is not between 0 and 1 ")
for key, value in S.items():
Yz.append(key[0])
Z.append(key[1])
if not isinstance(value, float):
raise TypeError("value of dictionary S in "+str(key)+" should be a float.")
elif not 0.0 <= value <= 1.0:
raise TypeError("value of membership of S in " + str(key) + " is not between 0 and 1 ")
# check Yx equal Yz
if set(Yx) != set(Yz):
raise ValueError("(X --> Y --> Z) Y's in relation R not equal with relation S")
RoS = {}
for x in set(X):
for z in set(Z):
max_membership = 0.0
for y in set(Yx):
min_membership = min(R[(x, y)], S[(y, z)])
if min_membership > max_membership:
max_membership = min_membership
RoS[(x, z)] = max_membership
return RoS
|
def odder(num: int) -> int:
"""Forces a number to be odd"""
if num % 2 == 0:
num += 1
return int(num)
|
def normalize_message(message):
"""Takes in a tuple message and converts it to a list, then lower cases it."""
message = list(message)
for index, i in enumerate(message):
i = i.lower()
message[index] = i
return message
|
def remove_empty_paragraphs(paragraphs):
""" Removes empty paragraphs from a list of paragraphs """
return [para for para in paragraphs if para != ' ' and para != '']
|
def arr_to_string(arr: list, cutoff=float('inf')) -> str:
""" Converts arr to string table, with cutoff length of characters
arr is given as an array of arrays of strings, all of arbitrary length.
expects every string in its list to have the same length
e.g. arr
[
['line 1', 'line 2'],
['line 12', 'line 23', 'line 34']
]
returns:
line 1 | line 12
line 2 | line 23
| line 34
"""
# removes empty columns from arr
lst = [col for col in arr if col]
# catches the error if lst is empty, otherwise max complains
if not lst:
return ''
max_lines = max([len(col) for col in lst])
paddings = [len(col[0]) for col in lst]
totalLen = 0
result = ''
for i in range(max_lines):
nextstr = ''
for col in range(len(lst)):
if col != 0:
nextstr += ' | '
if i >= len(lst[col]):
nextstr += ' ' * paddings[col]
else:
nextstr += lst[col][i]
totalLen += len(nextstr) + 1 # +1 accounts for newline character
if totalLen < cutoff:
result += nextstr + "\n"
else:
break
return result.strip()
|
def dict_merge(*dicts):
"""
Merge all provided dicts into 1 dict.
*dicts : `dict`
dictionaries to merge
"""
merged = {}
for d in dicts:
merged.update(d)
return merged
|
def calc_relevance_scores( n, rel_measure ):
"""
Utility function to compute a sequence of relevance scores using the specified function.
"""
scores = []
for i in range(n):
scores.append( rel_measure.relevance( i + 1 ) )
return scores
|
def floatToString(inp):
"""
Print a float nicely.
"""
return ("%.15f" % inp).rstrip("0").rstrip(".")
|
def color_reducer(c1, c2):
"""Helper function used to add two colors together when averaging."""
return tuple(v1 + v2 for v1, v2 in zip(c1, c2))
|
def is_sequence_of_type(sequence, t):
"""Determine if all items in a sequence are of a specific type.
Parameters
----------
sequence : list or tuple
The sequence of items.
t : object
The item type.
Returns
-------
bool
True if all items in the sequence are of the specified type.
False otherwise.
Examples
--------
>>> is_sequence_of_type([1, 2, 3], int)
True
"""
if any(not isinstance(item, t) for item in sequence):
return False
return True
|
def subsystem_item(subsystem, methods, services):
"""Function that sets the correct structure for subsystem item"""
subsystem_status = 'ERROR'
sorted_methods = []
if methods is not None:
subsystem_status = 'OK'
for method_key in sorted(methods.keys()):
sorted_methods.append(methods[method_key])
return {
'xRoadInstance': subsystem[0],
'memberClass': subsystem[1],
'memberCode': subsystem[2],
'subsystemCode': subsystem[3],
'subsystemStatus': subsystem_status,
'servicesStatus': 'OK' if services is not None else 'ERROR',
'methods': sorted_methods,
'services': services if services is not None else []
}
|
def L10_indicator(row):
"""
Determine the Indicator of L10 as one of five indicators
"""
if row < 40:
return "Excellent"
elif row < 50:
return "Good"
elif row < 61:
return "Fair"
elif row <= 85:
return "Poor"
else:
return "Hazard"
|
def get_tail(text, tailpos, numchars):
"""Return text at end of entity."""
wheretoend = tailpos + numchars
if wheretoend > len(text):
wheretoend = len(text)
thetail = text[tailpos: wheretoend]
return thetail
|
def partition(arr, start, end, i_pivot):
"""
Partition the arr between [start, end) using the given index i_pivot
:param arr: The list to partition.
:param start: Start element.
:param end: End element.
:param i_pivot: The index of the pivot element.
"""
if not arr:
return None
total_length = len(arr)
if start < 0 or start >= end or end > total_length:
raise Exception('Illegal start end argument for partition')
if i_pivot < start or i_pivot >= end:
raise Exception('i_pivot has to be [start, end)')
if i_pivot != start:
arr[i_pivot], arr[start] = arr[start], arr[i_pivot]
left = start
right = end - 1
i_pivot = left
while left < right:
while left < end and arr[left] <= arr[i_pivot]: # Move left if item < pivot
left += 1
while right >= start and arr[right] > arr[i_pivot]: # Move right if item > pivot
right -= 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
# right is then the final location
arr[right], arr[i_pivot] = arr[i_pivot], arr[right]
i_pivot = right
return i_pivot
|
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Kode warna hitam putih yang mengabaikan jarak relatif.
Mandelbrot set berwarna hitam, yang lainnya putih.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
|
def get_project_id_from_service_account_email(service_account_email: str) -> str:
"""
Get GCP project id from service_account_email
>>> get_project_id_from_service_account_email('cromwell-test@tob-wgs.iam.gserviceaccount.com')
'tob-wgs'
"""
# quick and dirty
return service_account_email.split('@')[-1].split('.')[0]
|
def identhashtype(srcHash):
"""
Identifies the hash function type
Now supports: MD5, SHA256, SHA512
:param srcHash: hasf as a string with hexadecimal digits
:return: hash type -MD5, SHA256 or SHA512- as a string
"""
#calculation of bits length of the hexdigest
try:
lenBits = len(srcHash) * 4
if lenBits == 128:
return 'MD5'
elif lenBits == 256:
return 'SHA256'
elif lenBits == 512:
return 'SHA512'
else:
print('unsupported hash type')
exit(0)
except Exception as e:
print(e)
exit(1)
|
def get_feature_filename(
feature_extractor_name,
h_stride,
v_stride,
feature_height,
fov):
"""Returns a filename given feature map parameters."""
return "features_{}_h-{}_v-{}_height-{}_fov-{}.sstable@100".format(
feature_extractor_name, h_stride, v_stride, feature_height, fov)
|
def get_wind(bearing):
"""get wind direction"""
if (bearing <= 22.5) or (bearing > 337.5):
bearing = u'\u2193 N'
elif (bearing > 22.5) and (bearing <= 67.5):
bearing = u'\u2199 NE'
elif (bearing > 67.5) and (bearing <= 112.5):
bearing = u'\u2190 E'
elif (bearing > 112.5) and (bearing <= 157.5):
bearing = u'\u2196 SE'
elif (bearing > 157.5) and (bearing <= 202.5):
bearing = u'\u2191 S'
elif (bearing > 202.5) and (bearing <= 247.5):
bearing = u'\u2197 SW'
elif (bearing > 247.5) and (bearing <= 292.5):
bearing = u'\u2192 W'
elif (bearing > 292.5) and (bearing <= 337.5):
bearing = u'\u2198 NW'
return bearing
|
def get_size_bytes(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor
|
def is_submodule(line):
"""Return True if the line is a valid submodule statement."""
if len(line) < 2:
# XXX: This is just to prevent index error in the next test
# Not entirely sure what this ought to be, come back to it...
return False
if (line[0], line[1]) != ('submodule', '('):
return False
# Not a great test, but enough to get things going.
if len(line) == 5 and line[3] != ')':
return False
if len(line) == 7 and (line[4], line[6]) != (':', ')'):
return False
return True
|
def _is_valid_kwarg(provided: dict, available: dict):
"""
Helper function to check if a user provided dictionary has the correct arguments,
compared to a dictionary with the actual available arguments.
Updates, if no difference found, the dictionary 'available'.
Parameters
----------
provided : `dict`
The user defined dictionary of optional additional arguments.
available : `dict`
The available optional additional arguments possible.
:raises KeyError:
invalid additional keyword argument supplied
"""
diff = provided.keys() - available.keys()
if diff: # if there are differences
msg = "invalid optional keyword argument passed: {}. Available arguments: {}".format(diff, list(available.keys()))
raise KeyError(msg)
available.update(provided)
return available
|
def mirror(spine_pos, pos):
"""
This function .
Parameters:
spine_pos (int): the position of the spine.
pos (int): the position of the middle of the image.
Returns:
spine_pos + (spine_pos - pos) or spine_pos - (pos - spine_pos) (int): mirror
the spine position to left or right of the center of the image.
"""
if pos < spine_pos:
return spine_pos + (spine_pos - pos)
else:
return spine_pos - (pos - spine_pos)
|
def dupCounts(setList,pdup_cnt,opdup_cnt,opdupset_cnt,flagFA,dropOp):
"""This function calculates various counts and returns a list of counts."""
dupset_num = 0
for item in setList:
if len(item) > 1:
opdup_cnt += len(item)
opdupset_cnt += 1
dupset_num += 1
if flagFA:
# If the user asks for FASTA output, store a set of optical
# duplicate headers. I will keep one optical duplicate from
# each set, to create a reduced list and not completely remove
# reads that are optical duplicates.
myList = list(item)
dropOp |= set(myList[1:])
pdup_cnt += len(setList) - dupset_num
return(pdup_cnt,opdup_cnt,opdupset_cnt,dropOp)
|
def hexstr_to_bytes(value):
"""Return bytes object and filter out formatting characters from
a string of hexadecimal numbers."""
return bytes.fromhex(''.join(filter(str.isalnum, value)))
|
def cp_cmtsolution2structure(py, cmtsolution_directory, base_directory):
"""
cp cmtsolution files in cmtsolution_directory to the simulation structure.
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.cp_cmtsolution2structure --cmtsolution_directory {cmtsolution_directory} --base_directory {base_directory}; \n"
return script
|
def is_hidden_cell(cell: dict) -> bool:
"""
Checks if a cell is hidden.
:param line: The cell to be checked.
:returns: True if the cell contains is hidden.
"""
try:
if cell["metadata"]["jupyter"]["source_hidden"] is True:
return True
else:
return False
except KeyError:
return False
|
def maximum_grade(parsed_list, passing_grade, overall_max=True):
"""
This function calculates the maximum grade from the given grades.
:param parsed_list: the parsed list of the grades
:param passing_grade: the grade passing threshold
:param overall_max: True, when calculating the maximum of all the grades,
False, when calculating the maximum of the passing grades
:return: the maximum element of the given as input parsed list
"""
if overall_max is False:
passing_grades_list = (
[item for item in parsed_list if item >= passing_grade]
)
if len(passing_grades_list) > 0:
max_value = max(passing_grades_list)
else:
max_value = "-"
else:
max_value = max(parsed_list)
return max_value
|
def deep_tuple(l):
""" Convert lists of lists of lists (...) into tuples of tuples of tuples, and so on. """
if type(l) != list: return l
return tuple(deep_tuple(a) for a in l)
|
def web_tile_zoom_out(zxy):
""" Compute tile at lower zoom level that contains this tile.
"""
z, x, y = zxy
return (z-1, x//2, y//2)
|
def convert_service_to_p(tot_s_y, s_fueltype_tech):
"""Calculate fraction of service for every technology
of total service
Arguments
----------
tot_s_y : float
Total yearly service
s_fueltype_tech : dict
Service per technology and fueltype
Returns
-------
s_tech_p : dict
All tecnology services are
provided as a fraction of total service
Note
----
Iterate over values in dict and apply calculations
"""
if tot_s_y == 0:
_total_service = 0
else:
_total_service = 1 / tot_s_y
# Iterate all technologies and calculate fraction of total service
s_tech_p = {}
for tech_services in s_fueltype_tech.values():
for tech, service_tech in tech_services.items():
s_tech_p[tech] = _total_service * service_tech
return s_tech_p
|
def end(n, d):
"""Print the final digits of N in reverse order until D is found.
>>> end(34567, 5)
7
6
5
"""
while n > 0:
last, n = n % 10, n // 10
print(last)
if d == last:
return None
|
def generate_path(start, ref, nonref, stop):
"""
Given source, sink, and ref/non-ref nodes enumerate all possible paths
"""
ref_path = [x for x in [start, ref, stop] if x != "0"]
nonref_path = [x for x in [start, nonref, stop] if x != "0"]
return [ref_path, nonref_path]
|
def sort(seq):
"""
Tool function for normal order, should not be used separately
Args:
seq (list): array
Returns:
list: integer e.g. swapped array, number of swaps
"""
swap_counter = 0
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i + 1]:
swap_counter += 1
seq[i], seq[i + 1] = seq[i + 1], seq[i]
changed = True
return seq, swap_counter
|
def xorstrings(str1, str2):
"""Xor 'str1' [bytes] with 'str2' [bytes]."""
res = []
for i in range(min(len(str1), len(str2))):
res.append(str1[i] ^ str2[i])
return bytes(res)
|
def longestCommonPrefix(*sequences):
"""
Returns longest common prefix occuring in given sequences
Reference: http://boredzo.org/blog/archives/2007-01-06/longest-common-prefix-in-python-2
>>> longestCommonPrefix('foobar', 'fobar')
'fo'
"""
if len(sequences) == 1:
return sequences[0]
sequences = [pair[1] for pair in sorted((len(fi), fi) for fi in sequences)]
if not sequences:
return None
for i, comparison_ch in enumerate(sequences[0]):
for fi in sequences[1:]:
ch = fi[i]
if ch != comparison_ch:
return fi[:i]
return sequences[0]
|
def convert_key(value):
"""convert a source file keyname value to a value usable for HotKeys
"""
w_shift = value.startswith('S-')
w_ctrl = value.startswith('C-')
if w_shift or w_ctrl:
value = value[2:]
test = {'Left': '', 'Up': '', 'Right': '', 'Down': '',
'Home': '', 'PageDown': 'PgDn', 'PageUp': 'PgUp', 'End': '',
'Esc': 'esc', 'Help': '', 'Tab': 'Tab', 'Undo': '',
'BS': 'Backspace', 'CR': 'Enter', 'NL': 'Return', 'F1': '',
'Insert': 'Ins', 'Del': '', 'Space': '',
'MiddleMouse': 'mmb', 'LeftMouse': 'lmb', 'RightMouse': 'rmb',
'ScrollWheelUp': 'WhlUp', 'ScrollWheelDown': 'WhlDn',
'ScrollWheelLeft': 'WhlLeft', 'ScrollWheelRight': 'WhlRight', }[value] or value
if w_shift:
test += ' shift'
if w_ctrl:
test += ' ctrl'
return test
|
def normalize_token(token_name: str) -> str:
"""
As of click>=7, underscores in function names are replaced by dashes.
To avoid the need to rename all cli functions, e.g. load_examples to
load-examples, this function is used to convert dashes back to
underscores.
:param token_name: token name possibly containing dashes
:return: token name where dashes are replaced with underscores
"""
return token_name.replace("_", "-")
|
def find_last_slash_pos_in_path(path):
"""
Find last slash position in a path
exampe : files = find_last_slash_pos_in_path("./audioFiles/abc.wav")
output : integer
the value that is the position of the last slash
"""
import os
LastSlashPos = path.rfind(os.path.split(path)[-1]) - 1
return LastSlashPos
|
def get_flag_param_decals_from_bool(option_name: str) -> str:
"""Return a '--do/not-do' style flag param"""
name = option_name.replace("_", "-")
return f'--{name}/--no-{name}'
|
def make_game(serverid, name, extras=None):
"""Create test game instance."""
result = {
'serverid': serverid,
'name': name,
'game_state': {'players': {}, 'min_players': 2, 'max_players': 4},
}
if extras:
result.update(extras)
return result
|
def Boolean(value, message_error=None, message_valid=None):
"""
value : value element DOM. Example : document['id].value
message_error : str message
message_valid: str message
function return tuple
"""
if isinstance(value, str):
value = value.lower()
if value in ('1', 'true', 'yes', 'on', 'enable'):
if message_valid:
return(True, message_valid)
else:
return (True)
if value in ('0', 'false', 'no', 'off', 'disable'):
if message_valid:
return(False, message_valid)
else:
return(False)
else:
return("error", message_error)
|
def _reg2int(reg):
"""Converts 32-bit register value to signed integer in Python.
Parameters
----------
reg: int
A 32-bit register value read from the mailbox.
Returns
-------
int
A signed integer translated from the register value.
"""
result = -(reg >> 31 & 0x1) * (1 << 31)
for i in range(31):
result += (reg >> i & 0x1) * (1 << i)
return result
|
def par_impar(num):
"""
num -> str
Entra un numero y sale si es par o impar
:param num: numero a ser revisado
:return: mensaje dejando saber si es par o no
>>> par_impar(6)
'Es par'
>>> par_impar(7)
'Es impar'
>>> par_impar('d')
Traceback (most recent call last):
..
TypeError: No es valido
"""
if str == type(num):
raise TypeError('No es valido')
elif num % 2 != 0:
return 'Es impar'
else:
return 'Es par'
|
def parse_price(price: str) -> float:
"""Change price from str to float without dollar sign."""
return float(price.lstrip('$'))
|
def process_cpp_benchmark(entry):
"""Process the entry from JSON data"""
name = entry["name"]
iterations = entry["iterations"]
speed = entry["cpu_time"]
unit = entry["time_unit"]
if unit == "ns":
pass
elif unit == "us":
speed *= 1e3
elif unit == "ms":
speed *= 1e6
else:
raise ValueError("Unknown unit: " + unit)
return name, iterations, speed
|
def _cast_to_int(num, param_name):
"""Casts integer-like objects to int.
Args:
num: the number to be casted.
param_name: the name of the parameter to be displayed in an error
message.
Returns:
num as an int.
Raises:
TypeError: if num is not integer-like.
"""
try:
# __index__() is the Pythonic way to convert integer-like objects (e.g.
# np.int64) to an int
return num.__index__()
except (TypeError, AttributeError):
raise TypeError('%s is not integer-like (found type: %s)'
%(param_name, type(num).__name__))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.