content
stringlengths 42
6.51k
|
|---|
def has_duplicate_values(tmp_list):
"""
Checks to see if a given list has any duplicate value.
:returns: False if tmp_list has no duplicate values.
:returns: True if tmp_list has duplicate values.
"""
set_of_elements = set()
for elem in tmp_list:
if elem in set_of_elements:
return True
else:
set_of_elements.add(elem)
return False
|
def encode_text(text):
"""Encode data to help prevent XSS attacks from text in article"""
#Most efficient way is to chain these together ( https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string )
text = text.replace('&','&').replace('<','<').replace('>','>').replace('"','"').replace("'",''')
return text
|
def ComputePrecisionAndRecall(events, interpolate = False):
"""
Given a sorted list of events, compute teh Precision and Recall of each
of the events.
Events are tuples (tp, fp, fn) of float numbers in the range [0, 1], which
indicate whether the given event is a hit (or true positive), a false
positive, or was not detected at all (false negative).
If the `interpolate' option is set to true, the Interpolated Precision
is computed, instead of the regular Precision definition.
The function returns the total number of relevant events, the total
number of detected events and the precision and recall vectors.
"""
# Number of events
N = len(events)
# Total number of relevant events
TR = sum([tp + fn for (tp, _, fn) in events])
# Precision and Recall at each point, sorted in increasing Recall
Pr, Rc = [], []
# Accumulated number of true positives and false positives
TP, FP = 0.0, 0.0
for (tp, fp, fn) in events:
TP, FP = TP + tp, FP + fp
Pr.append(TP / (TP + FP) if TP + FP > 0.0 else 0.0)
Rc.append(TP / TR if TR > 0.0 else 0.0)
# Interpolate precision
if interpolate:
for i in range(N - 1, 0, -1):
Pr[i - 1] = max(Pr[i], Pr[i - 1])
return TR, TP + FP, Pr, Rc
|
def extract_env_version(release_version):
"""Returns environment version based on release version.
A release version consists of 'OSt' and 'MOS' versions: '2014.1.1-5.0.2'
so we need to extract 'MOS' version and returns it as result.
.. todo:: [ikalnitsky] think about introducing a special field in release
:param release_version: a string which represents a release version
:returns: an environment version
"""
separator = '-'
# unfortunately, Fuel 5.0 didn't has an env version in release_version
# so we need to handle that special case
if release_version == '2014.1':
return '5.0'
# we need to extract a second part since it's what we're looking for
return release_version.split(separator)[1]
|
def ts_fromdebris_func(h, a, b, c):
""" estimate surface temperature from debris thickness (h is debris thickness, a and k are coefficients)
Hill Equation"""
return a * h**c / (b**c + h**c)
|
def inverse_mod(k, p):
"""Returns the inverse of k modulo p.
This function returns the only integer x such that (x * k) % p == 1.
k must be non-zero and p must be a prime.
"""
if k == 0:
raise ZeroDivisionError("division by zero")
if k < 0:
# k ** -1 = p - (-k) ** -1 (mod p)
return p - inverse_mod(-k, p)
# Extended Euclidean algorithm.
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = p, k
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
gcd, x, y = old_r, old_s, old_t
assert gcd == 1
assert (k * x) % p == 1
return x % p
|
def is_instance_or_subclass(val, class_):
"""Return True if ``val`` is either a subclass or instance of ``class_``."""
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_)
|
def l2_loss(y_true, y_pred):
"""Implements L2 loss.
y_true and y_pred are typically: [N, 4], but could be any shape.
"""
loss = (y_true - y_pred) ** 2
return loss
|
def get_value(map, key):
"""Returns the value part from the dict, ignoring shorthand variants.
"""
if map[key].__class__ == "".__class__:
return map[key]
else:
return map[key][0]
|
def const(f, *args, **kwargs):
"""
Decorator to maintain constness of parameters.
This should be used on any function that takes ndarrays as parameters.
This helps protect against potential subtle bugs caused by the pass by
reference nature of python arguments.
``copy`` is assumed to a shallow copy.
Parameters
----------
f : func
Function to wrap
args : list
Function ``f`` s args
kwargs : dictionary
Function ``f`` s kwargs
copy : {True, False}, optional
If ``False`` then don't copy the parameters - use with caution
Default : True
"""
copy = kwargs.pop('copy', True)
if copy:
args = [x.copy() for x in args]
kwargs = dict((k, v.copy()) for k, v in kwargs.items())
return f(*args, **kwargs)
|
def read_img_string(img_str):
"""
:param img_str: a string describing an image, like '4_3_3'
:return: integer array of this list. e.g: [4,3,3]
"""
img_array = img_str.split('_')
img_array = list(map(int, img_array))
return img_array
|
def parse_slack_output(slack_client, slack_rtm_output, config, bot_id):
"""
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
"""
at_bot = "<@{0}>".format(bot_id)
output_list = slack_rtm_output
if output_list and len(output_list) > 0:
for output in output_list:
if output and 'text' in output and at_bot in output['text']:
# return text after the @ mention, whitespace removed
return output['user'], output['text'].split(at_bot)[1].strip().lower(), \
output['channel']
return None, None, None
|
def L1(v, dfs_data):
"""The L1 lowpoint of the node."""
return dfs_data['lowpoint_1_lookup'][v]
|
def parse_byte_size_string(string):
"""
Attempts to guess the string format based on default symbols
set and return the corresponding bytes as an integer.
When unable to recognize the format ValueError is raised.
>>> parse_byte_size_string('1 KB')
1024
>>> parse_byte_size_string('2.2 GB')
2362232012
"""
if len(string) == 0:
return
# Find out the numerical part.
initial_string = string
num_string = ""
while len(string) and (string[:1].isdigit() or string[:1] == '.'):
num_string += string[0]
string = string[1:]
num = float(num_string)
# Look for the suffix.
suffix = string.strip() or "B"
suffix_set = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
prefix = {suffix_set[0]: 1}
for i, string in enumerate(suffix_set[1:]):
prefix[string] = 1 << (i+1)*10
# If the data is garbage for some reason, just discard it.
if suffix not in prefix:
return 0
return int(num * prefix[suffix])
|
def get_tracked_zone(name, zones):
"""
What is the tracked zone for the provided hostname?
"""
for zone in zones:
if name.endswith("." + zone) or name == zone:
return zone
return None
|
def remove_links_with_no_month_reference(all_links: list) -> list:
"""
function to remove all links that don't have an association with a month. All entries with None or '\xa0' instead
of month name.
args:
all_links: list -> List of tuples where the first index is the link, second index is the month and third index
is the year.
return:
only_entries_with_month_reference: list -> Returns a list with valid links.
"""
only_links_with_month_reference = [item for item in all_links if item[1] is not None and item[1] != '\xa0']
return only_links_with_month_reference
|
def MangleModuleIfNeeded(module_id):
"""Convert module ID to the format breakpad uses.
See TracingSamplerProfiler::MangleModuleIDIfNeeded().
Warning: this is only relevant in Android, Linux and CrOS.
Linux ELF module IDs are 160bit integers, which we need to mangle
down to 128bit integers to match the id that Breakpad outputs.
Example on version '66.0.3359.170' x64:
Build-ID: "7f0715c2 86f8 b16c 10e4ad349cda3b9b 56c7a773"
Debug-ID "C215077F F886 6CB1 10E4AD349CDA3B9B 0"
Args:
module_id: The module ID provided by crash reports.
Returns:
The module ID in breakpad format.
"""
if len(module_id) == 32 or len(module_id) == 33:
return module_id
if len(module_id) < 32:
return module_id.ljust(32, '0').upper()
return ''.join([
module_id[6:8], module_id[4:6], module_id[2:4], module_id[0:2],
module_id[10:12], module_id[8:10], module_id[14:16], module_id[12:14],
module_id[16:32], '0'
]).upper()
|
def isInCategory(category, categoryData):
"""Check if the event enters category X, given the tuple computed by eventCategory."""
if category==0:
return (categoryData[0]>0 or categoryData[1]>0) and categoryData[2]>=4
elif category==1:
return isInCategory(0,categoryData) and (categoryData[3]>15 or categoryData[4]>15) and categoryData[5]>=4
elif category==2:
return isInCategory(1,categoryData) and categoryData[6]>=2
elif category==3:
return isInCategory(2,categoryData) and categoryData[7]>0
elif category==4:
return isInCategory(2,categoryData) and categoryData[8]>0
elif category==5:
return isInCategory(2,categoryData) and categoryData[9]>0
else:
return False
|
def get_export_from_line(line):
"""Get export name from import statements"""
if not line.startswith("export * from"):
return None
start = line.find("\"")
if start > 0:
return line[start+1:-3] # remove ";\n
return None
|
def seconds_to_string(seconds):
"""
Convert run seconds into string representation
:param seconds: Number of seconds
:type seconds: int
:return: String in the format of 'Xd Xh Xm Xs' based on the provided elapsed time
:rtype: string
"""
day = int(seconds // (24 * 3600))
time_mod = seconds % (24 * 3600)
hour = int(time_mod // 3600)
time_mod %= 3600
minute = int(time_mod // 60)
seconds = int(time_mod % 60)
if day > 0:
res = "{}d {}h {}m {}s".format(day, hour, minute, seconds)
elif hour > 0:
res = "{}h {}m {}s".format(hour, minute, seconds)
elif minute > 0:
res = "{}m {}s".format(minute, seconds)
else:
res = "{}s".format(seconds)
return res
|
def bytes_(s, encoding='utf-8', errors='strict'):
"""
If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``s``
"""
if not isinstance(s, bytes) and s is not None:
s = s.encode(encoding, errors)
return s
|
def edges_path_to(edge_to, src, target):
"""Recover path from src to target."""
if not target in edge_to:
raise ValueError('{} is unreachable from {}'.format(target, src))
path = []
v = target
while v != src:
path.append(v)
v = edge_to[v][0]
# last one to push is the source, which makes it
# the first one to be retrieved
path.append(src)
path.reverse()
return path
|
def get_nterm_mod(seq, mod):
"""Check for a given nterminal mod.
If the sequences contains the mod a 1 is returned, else 0.
"""
if seq.startswith(mod):
return 1
else:
return 0
|
def filter_coefficients(position):
"""
15 quarter-pixel interpolation filters, with coefficients taken directly from VVC implementation
:param position: 1 indicates (0,4) fractional shift, ..., 4 is (4,0), ... 9 is (8,4), ...
:return: 8 filter coefficients for the specified fractional shift
"""
return {
0: [0, 0, 0, 64, 0, 0, 0, 0],
1: [0, 1, -3, 63, 4, -2, 1, 0],
2: [-1, 2, -5, 62, 8, -3, 1, 0],
3: [-1, 3, -8, 60, 13, -4, 1, 0],
4: [-1, 4, -10, 58, 17, -5, 1, 0],
5: [-1, 4, -11, 52, 26, -8, 3, -1],
6: [-1, 3, -9, 47, 31, -10, 4, -1],
7: [-1, 4, -11, 45, 34, -10, 4, -1],
8: [-1, 4, -11, 40, 40, -11, 4, -1],
9: [-1, 4, -10, 34, 45, -11, 4, -1],
10: [-1, 4, -10, 31, 47, -9, 3, -1],
11: [-1, 3, -8, 26, 52, -11, 4, -1],
12: [0, 1, -5, 17, 58, -10, 4, -1],
13: [0, 1, -4, 13, 60, -8, 3, -1],
14: [0, 1, -3, 8, 62, -5, 2, -1],
15: [0, 1, -2, 4, 63, -3, 1, 0]
}.get(position, 'Invalid fractional pixel position!')
|
def transformArrYXToXY(arrYX):
""" transformArrYXToXY(arrYX)
Getting a array of positions invert order.
Parameters
----------
arrYX : Array
List of positions to invert
Returns
-------
List
Returns list with all coordinates inverted inside
a tuple.
"""
points = []
for point in arrYX:
points.append(tuple([point[1], point[0]]))
return points
|
def check_5_characters_functions(strings):
"""
This function checks to see if the user's input has more than, or equal to 5 characters, or not.
:param strings: This variable "strings" saves the user's input
:return: True if the user's input has more than, or equal to 5 characters
return False if the user's input has fewer than 5 characters
"""
if len(strings) >= 5:
#This line checks to see if the string has more than 5 characters or not.
return True
#If the user's input has more than 5 characters, the function will return True
else:
#If the user's input does not have more than 5 characters, the function will return False
return False
|
def integrate_curve(curve_points):
"""
Integrates the curve using the trapezoid method.
:param curve_points: the list of point of the curve
:type curve_points: List[Tuple[float, float]]
:return: the integration of the curve
:rtype: float
"""
area = 0.0
for i in range(1, len(curve_points)):
area += (curve_points[i][0] - curve_points[i - 1][0]) * \
((curve_points[i][1] + curve_points[i - 1][1]) / 2)
return area
|
def prefix_sum_n_mean(A, n_values):
"""
Calculates the average of the n_values ahead of each position of list A
:param A: list
:param n_means: number of values to use for each average
:return: list of averages
"""
n = len(A) - (n_values - 1)
P = [10000] * n
for k in range(n):
P[k] = 0
for i in range(n_values):
P[k] += A[k + i]
P[k] /= n_values
return P
|
def create_pinhole_camera(height, width):
"""
Creates a pinhole camera according to height and width, assuming the principal point is in the center of the image
"""
cx = (width - 1) / 2
cy = (height - 1) / 2
f = max(cx, cy)
return f, cx, cy
|
def dotted_prefixes(dotted_name, reverse=False):
"""
Return the prefixes of a dotted name.
>>> dotted_prefixes("aa.bb.cc")
['aa', 'aa.bb', 'aa.bb.cc']
>>> dotted_prefixes("aa.bb.cc", reverse=True)
['aa.bb.cc', 'aa.bb', 'aa']
:type dotted_name:
``str``
:param reverse:
If False (default), return shortest to longest. If True, return longest
to shortest.
:rtype:
``list`` of ``str``
"""
name_parts = dotted_name.split(".")
if reverse:
idxes = range(len(name_parts), 0, -1)
else:
idxes = range(1, len(name_parts)+1)
result = ['.'.join(name_parts[:i]) or '.' for i in idxes]
return result
|
def SegmentsIntersect(l1, r1, l2, r2):
"""Returns true if [l1, r1) intersects with [l2, r2).
Args:
l1: int. Left border of the first segment.
r1: int. Right border (exclusive) of the second segment.
l2: int. Left border of the second segment.
r2: int. Right border (exclusive) of the second segment.
"""
return l2 < r1 and r2 > l1
|
def hex_to_number(hex_string):
"""
Return a int representation of the encoding code.
:param hex_string: Hex string to convert
:type hex_string: str
:return: The hex string as a number
:type: int
>>> hex_to_number('00F00D') == 0xF00D
True
"""
return int(hex_string, 16)
|
def power(x, y):
"""Power with stricter evaluation rules"""
if x == 0:
if y == 0: raise ValueError("0^0")
elif x < 0:
if y != int(y): raise ValueError("non-integer power of negative")
return x ** y
|
def count(func, lst):
"""
Counts the number of times func(x) is True for x in list 'lst'
See also:
counteq(a, lst) count items equal to a
countneq(a, lst) count items not equal to a
countle(a, lst) count items less than or equal to a
countlt(a, lst) count items less than a
countge(a, lst) count items greater than or equal to a
countgt(a, lst) count items greater than a
"""
n = 0
for i in lst:
if func(i):
n += 1
return n
|
def mergeRegisters(*qregs):
"""
Returns a single register containing all the qubits (or cbits) from multiple registers
"""
bigReg = []
for qreg in qregs:
bigReg += [q for q in qreg]
return bigReg
|
def update_dictionary(a_dictionary, key, value):
"""
updates a dictionary and returns a new copy
original is affected
"""
a_dictionary.update({key: value})
return (a_dictionary.copy())
|
def mysqrt(x, steps=10):
"""Calculate sqrt by Newton's method."""
# Initial guess (guess number 1 of <steps>)
guess = x/2
for i in range(steps-1):
# Next guess given by Newton's formula
guess = (guess + x/guess) / 2
# Result after <steps> iteration
mysqrt = guess
return mysqrt
|
def get_output(values, puzzle_input):
"""returns the value for output
"""
return puzzle_input[values[0]]
|
def pedigree_to_qc_pedigree(samples_pedigree):
"""
extract pedigree for qc for every family member
- input samples accession list
- qc pedigree
"""
qc_pedigree = []
# get samples
for sample in samples_pedigree:
member_qc_pedigree = {
'gender': sample.get('sex', ''),
'individual': sample.get('individual', ''),
'parents': sample.get('parents', []),
'sample_name': sample.get('sample_name', '')
}
qc_pedigree.append(member_qc_pedigree)
return qc_pedigree
|
def PNT2Tidal_Pv14(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,alpha2PNT=0):
""" TaylorT2 2PN Quadrupolar Tidal Coefficient, v^14 Phasing Term.
XA = mass fraction of object
chiA = aligned spin-orbit component of object
chiB = aligned spin-orbit component of companion object
AqmA = dimensionless spin-induced quadrupole moment of object
AqmB = dimensionless spin-induced quadrupole moment of companion object
alpha2PNT = 2PN Quadrupole Tidal Flux coefficient """
XATo2nd = XA*XA
XATo3rd = XATo2nd*XA
XATo4th = XATo3rd*XA
XATo5th = XATo4th*XA
return (351560665)/(254016)+(5*alpha2PNT)/(9) - (738971515*XA)/(1524096) \
- (104525*XATo2nd)/(336) - (2160965*XATo3rd)/(6048)-(7310*XATo4th)/(27) \
+ (4285*XATo5th)/(36) + (-(1065*XATo2nd)/(8)+(875*XATo3rd)/(8) \
+ AqmA*(-130*XATo2nd+(320*XATo3rd)/(3)))*chiA*chiA \
+ (-(1015*XA)/(4)+(1385*XATo2nd)/(3) - (2495*XATo3rd)/(12))*chiA*chiB \
+ (-(1065)/(8)+(3005*XA)/(8)-(2815*XATo2nd)/(8) + (875*XATo3rd)/(8) \
+ AqmB*(-130+(1100*XA)/(3)-(1030*XATo2nd)/(3)+(320*XATo3rd)/(3)))*chiB*chiB
|
def compute_tally(vec):
"""
Here vec is an iterable of hashable elements.
Return dict giving tally of elements.
"""
tally = {}
for x in vec:
tally[x] = tally.get(x, 0) + 1
return tally
|
def scale(mylist, zero_vals=None, one_vals=None):
""" Scales a 2D list by attribute from 0 to 1
Args:
mylist (list of list of obj): The lists to scale
zero_vals (list of numbers): The override of the minimum values to scale to zero with.
one_vals (list of numbers): See zero_vals. Both or neither must be given by the user.
Returns:
mins (list of numbers): The minimum found for each attribute
maxs (list of numbers): The maximum found for each attribute
"""
maxs = []
mins = []
if zero_vals is None and one_vals is None:
for i in range(len(mylist[0])):
maxs.append(mylist[0][i])
mins.append(mylist[0][i])
# Get the mins and maxes
for i in range(len(mylist)):
for j in range(len(mylist[i])):
if mylist[i][j] > maxs[j]:
maxs[j] = mylist[i][j]
elif mylist[i][j] < mins[j]:
mins[j] = mylist[i][j]
elif zero_vals is None or one_vals is None:
raise ValueError("Cannot have one optional arg but not the other.")
else:
maxs = one_vals
mins = zero_vals
# Scale appropriately
for i in range(len(mylist)):
for j in range(len(mylist[i])):
mylist[i][j] = (mylist[i][j] - mins[j]) / (maxs[j] - mins[j])
return mins, maxs
|
def unqualify(name: str) -> str:
"""
Return an unqualified name given a qualified module/package ``name``.
Args:
name: The module name to unqualify.
Returns:
The unqualified module name.
"""
return name.rsplit(".", maxsplit=1)[-1]
|
def sort_all(batch, lens):
""" Sort all fields by descending order of lens, and return the original indices. """
if batch == [[]]:
return [[]], []
unsorted_all = [lens] + [range(len(lens))] + list(batch)
sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))]
return sorted_all[2:], sorted_all[1]
|
def print_color(text):
"""
Print text in yellow :)
:param text: String to be colored
:return: Colored text
"""
return '\033[0;33m' + text + '\033[0m'
|
def rosenbrock(args):
"""
Name: Rosenbrock
Global minimum: f(1,...,1) = 0.0
Search domain: -inf <= xi <= inf, 1 <= i <= n
"""
rosen = 0
for i in range(len(args ) -1):
rosen += 10.0 *((args[i]**2 ) -args[ i +1] )** 2 +( 1 -args[i] )**2
return rosen
|
def stripline(line, stripboth=False):
"""
Default line transformer.
Returns the supplied line after calling rstrip
:param line: string representing a file line
:param stripboth: Optional boolean flag indicating both l and r strip should be applied
:return: The trimmed line
"""
if stripboth:
return line.lstrip().rstrip()
return line.rstrip()
|
def get_wildcard_mask(mask):
""" convert mask length to ip address wildcard mask, i.e. 24 to 0.0.0.255 """
mask_int = ["255"] * 4
value = int(mask)
if value > 32:
return None
if value < 8:
mask_int[0] = str(int(~(0xFF << (8 - value % 8)) & 0xFF))
if value >= 8:
mask_int[0] = '0'
mask_int[1] = str(int(~(0xFF << (16 - (value % 16))) & 0xFF))
if value >= 16:
mask_int[1] = '0'
mask_int[2] = str(int(~(0xFF << (24 - (value % 24))) & 0xFF))
if value >= 24:
mask_int[2] = '0'
mask_int[3] = str(int(~(0xFF << (32 - (value % 32))) & 0xFF))
if value == 32:
mask_int[3] = '0'
return '.'.join(mask_int)
|
def svg_color_tuple(rgb_floats):
"""
Turn an rgb tuple (0-255, 0-255, 0-255) into an svg color definition.
:param rgb_floats: (0-255, 0-255, 0-255)
:return: "rgb(128,128,128)"
"""
r, g, b = (round(x) for x in rgb_floats)
return f"rgb({r},{g},{b})"
|
def sum(val):
"""
>>> sum((1.0, 2.0))
3.0
>>> sum((2.0*meter, 3.0*meter))
Quantity(value=5.0, unit=meter)
>>> sum((2.0*meter, 30.0*centimeter))
Quantity(value=2.3, unit=meter)
"""
if len(val) == 0:
return 0
result = val[0]
for i in range(1, len(val)):
result += val[i]
return result
|
def unique_subjects_sessions_to_subjects_sessions(
unique_subject_list, per_subject_session_list
):
"""Do reverse operation of get_unique_subjects function.
Example:
>>> from clinicaml.utils.participant import unique_subjects_sessions_to_subjects_sessions
>>> unique_subjects_sessions_to_subjects_sessions(['sub-01', 'sub-02'], [['ses-M00', 'ses-M18'], ['ses-M00']])
(['sub-CLNC01', 'sub-01', 'sub-02'], ['ses-M00', 'ses-M18', 'ses-M00'])
"""
list_participants = []
list_sessions = []
for idx, participant_id in enumerate(unique_subject_list):
for session_id in per_subject_session_list[idx]:
list_participants.append(participant_id)
list_sessions.append(session_id)
return list_participants, list_sessions
|
def gcd(*args):
"""Calculate the greatest common divisor (GCD) of the arguments."""
L = len(args)
if L == 0: return 0
if L == 1: return args[0]
if L == 2:
a, b = args
while b:
a, b = b, a % b
return a
return gcd(gcd(args[0], args[1]), *args[2:])
|
def sameThreeCharStartPredicate(field):
"""return first three characters"""
if len(field) < 3:
return ()
return (field[:3], )
|
def balance_tasks_among_levels(max_workers: int, tasks: dict, levels: dict):
"""Rearrange tasks across levels to optimize execution regarding the maximum workers.
The constraint between tasks of same level (no relationship) must be conserved
:param tasks:
:param max_workers:
:param levels:
:return:
"""
levels_count = len(levels)
for _ in levels:
for level_key in range(levels_count - 1):
level = levels[level_key]
next_level = levels[level_key + 1]
if len(level) >= max_workers >= len(next_level):
for task_id in level:
for task in tasks[task_id]:
successors = task.successors
# if next level contains successor don't move this task
next_level_contains_successor = False
for successor in successors:
if successor in next_level:
next_level_contains_successor = True
if not next_level_contains_successor:
# move task from level to next_level
if task_id in levels[level_key]:
levels[level_key].remove(task_id)
if task_id not in levels[level_key + 1]:
levels[level_key + 1].append(task_id)
return levels
|
def is_valid_bio(entity):
""" check if the entity sequence is valid,
'I-' should not at the beginning, and should never follow 'O' neither.
"""
for j, e in enumerate(entity):
if e.startswith('I-') and ( j == 0 or e[2:] != entity[j - 1][2:]):
print(j, entity[j-1], e,)
return False
return True
|
def sat_to_btc(amount_sat: float) -> float:
"""
The value is given in satoshi.
"""
smallest_sat = 1
largest_sat = 99999999
#
if not (smallest_sat <= amount_sat <= largest_sat):
raise ValueError
# else
btc = amount_sat * 1e-8
return btc
|
def go_next(i, z_result, s):
"""
Check if we have to move forward to the next characters or not
"""
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
|
def handle_port_probe_action(action):
"""
Handle the PORT_PROBE action type from the
guard duty finding.
:param data:
:return:
"""
portProbeAction = action.get("portProbeAction")
print("Port Probe action: {}".format(portProbeAction))
portProbeDetails = portProbeAction.get("portProbeDetails")
remoteIpDetails = portProbeDetails[0].get("remoteIpDetails")
ip_address = remoteIpDetails.get("ipAddressV4")
print("Port probe Address originated from {}".format(ip_address))
return ip_address
|
def bring_contact_bonus_list(pb_client, obj_pb_ids, arm_pb_id, table_pb_id):
""" For some bring goals, may be useful to also satisfy an object touching table and
not touching arm condition. """
correct_contacts = []
for o in obj_pb_ids:
o2ee_contact = len(pb_client.getContactPoints(o, arm_pb_id)) > 0
o2t_contact = len(pb_client.getContactPoints(o, table_pb_id)) > 0
correct_contacts.append(not o2ee_contact and o2t_contact)
return correct_contacts
|
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
We will use Naive approach.
Check Divisibility of n with all numbers smaller than n.
If any one of the smaller number is able to divide n, then n is instantly identified as not Prime & we return False.
Else, If none of the smaller numbers in range 2 to n-1 range, were able to divide n then N is surely Prime & we return True.
"""
#Explicitly check if n is '1'
if (n == 1):
return False
#check divisibility of n -by any number in range 2 to n-1.
# a number i.e other than 1 & itself within
i=2
while(i<n):
if n% i == 0:
#it is divisible by i therefore
return False
i = i+1
# n is not divisible by any no. in range 2 to n-1.
return True
|
def calldict2txt(inputDict):
"""
Convert all keys in dict to a string txt, txt file is:
chr1 123 123 . . +
:param inputDict:
:return:
"""
text = ""
for key in inputDict:
text += f'{key[0]}\t{key[1]}\t{key[1]}\t.\t.\t{key[2]}\n'
return text
|
def calculate_colorscale(n_values):
"""
Split the colorscale into n_values + 1 values. The first is black for
points representing pairs of variables not in the same cluster.
:param n_values:
:return:
"""
# First 2 entries define a black colour for the "none" category
colorscale = [[0, "rgb(0,0,0)"], [1 / (n_values + 1), "rgb(0,0,0)"]]
plotly_colorscale = [
"#636EFA",
"#EF553B",
"#00CC96",
"#AB63FA",
"#FFA15A",
"#19D3F3",
"#FF6692",
"#B6E880",
"#FF97FF",
"#FECB52",
]
# Add colours from plotly_colorscale as required.
for i in range(1, n_values + 1):
colorscale.append(
[i / (n_values + 1), plotly_colorscale[(i - 1) % len(plotly_colorscale)]]
)
colorscale.append(
[
(i + 1) / (n_values + 1),
plotly_colorscale[(i - 1) % len(plotly_colorscale)],
]
)
return colorscale
|
def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float:
"""
Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
"""
return round((kelvin - 273.15) * 9 / 5 + 32, ndigits)
|
def wordFinder(string):
"""Takes a string and returns the number of times a word is repeated"""
#begin init of function variables
stringLower=string.lower()
stringList=list(stringLower)
stringList.insert(0,' ')
stringList.append(' ')
spaceList=[]
wordList=[]
charList=[]
repeat=0
#print(stringList)
#end variable create
for m in range (0, len(stringList)): #finds and notes all the spaces
if stringList[m]==' ':
spaceList.append(m)
t=len(spaceList)
# print(t,spaceList)
for i in range(0,t):
start=spaceList[0] ##uses the spaces to find words and add them to a list
if len(spaceList) != 1:
end=spaceList[1]
else:
end=None
charList=stringList[start+1:end]
# print(charList)
for m in charList: ##removes non alpha-numeric characters
if m.isalpha() == False:
charList.remove(m)
# print("removing non-alphaCharacter")
spaceList.pop(0)
wordList.append("".join(charList))
return wordList
|
def getMessageIfFalse(condition, msg):
"""If condition is False, then returns msg, otherwise returns empty string.
:param bool condition: Condition paramater.
:param str msg: Message returned if condition is False.
:return: msg or empty string.
:rtype: str
>>> getMessageIfFalse(False, "Condition is set to False.")
'Condition is set to False.'
"""
if condition:
return ""
else:
return msg
|
def all_validator(value):
"""No validation for value insertion. Returns True always. """
# pylint: disable=unused-argument
return True
|
def parse_short_time_label(label):
"""
Provides the number of seconds corresponding to the formatting used for the
cputime and etime fields of ps:
[[dd-]hh:]mm:ss or mm:ss.ss
::
>>> parse_short_time_label('01:51')
111
>>> parse_short_time_label('6-07:08:20')
544100
:param str label: time entry to be parsed
:returns: **int** with the number of seconds represented by the label
:raises: **ValueError** if input is malformed
"""
days, hours, minutes, seconds = '0', '0', '0', '0'
if '-' in label:
days, label = label.split('-', 1)
time_comp = label.split(':')
if len(time_comp) == 3:
hours, minutes, seconds = time_comp
elif len(time_comp) == 2:
minutes, seconds = time_comp
else:
raise ValueError("Invalid time format, we expected '[[dd-]hh:]mm:ss' or 'mm:ss.ss': %s" % label)
try:
time_sum = int(float(seconds))
time_sum += int(minutes) * 60
time_sum += int(hours) * 3600
time_sum += int(days) * 86400
return time_sum
except ValueError:
raise ValueError('Non-numeric value in time entry: %s' % label)
|
def generate_triangle(n, left="/", right="\\"):
"""This function generates a list of strings which
when printed resembles a triangle
"""
if type(n) is not int:
raise TypeError("Input an integer only")
result = []
for i in range(1, n+1):
line = ' '*(n-i) + left*i + right*i + ' '*(n-i)
result.append(line)
return result
|
def parseCheckOutput(install):
"""Parses the preparsed solver output with respect to fakevariables"""
retstr = '### Keep the following dependencies:\n'
inconStr = ''
consistent = True
for item in install:
if item[1] != '0.0-fake':
retstr += item[0]+' version '+item[1]+'\n'
else:
consistent = False
inconStr += item[0]+'\n'
if not consistent:
retstr += '### WARNING: The dependencies can only be kept consistent without the following packages:\n'
retstr += inconStr
return retstr
|
def pointsToCoordinatesAndProperties(points):
"""Converts points in various formats to a (coordinates, properties) tuple
Arguments:
points (array or tuple): point data to be converted to (coordinates, properties) tuple
Returns:
tuple: (coordinates, properties) tuple
Notes:
Todo: Move this to a class that handles points and their meta data
"""
if isinstance(points, tuple):
if len(points) == 0:
return (None, None)
elif len(points) == 1:
return (points[0], None)
elif len(points) == 2:
return points
else:
raise RuntimeError('points not a tuple of 0 to 2 elements!')
else:
return (points, None)
|
def _get_components(env, *args):
"""Get the objects of the given component(s)
:param env: the SCons environment
:param args: the names of the components
"""
variant_dir = env['COMPONENTS_VARIANT_DIR']
objects = set()
for name in args:
[objects.add(obj) for obj in env['COMPONENTS'][variant_dir][name]]
return list(objects)
|
def find(array, key): # O(N)
"""
Find an element in an array of tuples
>>> find([('human', 42), ('cat', 22)], 'cat')
1
>>> find([('human', 42), ('cat', 22)], 'dog')
-1
"""
length = len(array) # O(1)
for i in range(0, length): # O(N)
element = array[i] # O(1)
if element[0] == key: # O(1)
return i # O(1)
return -1 # O(1)
|
def InvertNaiveSConsQuoting(s):
"""SCons tries to "help" with quoting by naively putting double-quotes around
command-line arguments containing space or tab, which is broken for all
but trivial cases, so we undo it. (See quote_spaces() in Subst.py)"""
if ' ' in s or '\t' in s:
# Then SCons will put double-quotes around this, so add our own quotes
# to close its quotes at the beginning and end.
s = '"' + s + '"'
return s
|
def setup_dict(data, required=None, defaults=None):
"""Setup and validate dict scenario_base. on mandatory keys and default data.
This function reduces code that constructs dict objects
with specific schema (e.g. for API data).
:param data: dict, input data
:param required: list, mandatory keys to check
:param defaults: dict, default data
:returns: dict, with all keys set
:raises: IndexError, ValueError
"""
required = required or []
for i in set(required) - set(data):
raise IndexError("Missed: %s" % i)
defaults = defaults or {}
for i in set(data) - set(required) - set(defaults):
raise ValueError("Unexpected: %s" % i)
defaults.update(data)
return defaults
|
def hex_to_rgb(hex_string):
"""
Convert a hexadecimal string with leading hash into a three item list of values between [0, 1].
E.g. #00ff00 --> [0, 1, 0]
:return: The value of the hexadecimal string as a three element list with values in the range [0. 1].
"""
hex_string = hex_string.lstrip('#')
return [int(hex_string[i:i + 2], 16) / 255.0 for i in (0, 2, 4)]
|
def _import(name):
"""Return module from a package.
These two are equivalent:
> from package import module as bar
> bar = _import('package.module')
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
try:
mod = getattr(mod, comp)
except AttributeError:
raise ImportError("No module named %s" % mod)
return mod
|
def mapfmt_str(fmt: str, size: int) -> str:
"""Same as mapfmt, but works on strings instead of bytes."""
if size == 4:
return fmt
return fmt.replace('i', 'q').replace('f', 'd')
|
def add_to_list(items,new_item):
""" Add the value to the list/tuple. If the item is not a list, create a new
list from the item and the value
Args:
items (list, string or tuple): Single or multiple items
new_item (string): The new value
Returns:
(list): A list of all values
"""
if isinstance(items,tuple):
items=[i for i in items]
if not isinstance(items,list):
items=[items]
return items+[new_item]
|
def escape_jsonpointer_part(part: str) -> str:
"""convert path-part according to the json-pointer standard"""
return str(part).replace("~", "~0").replace("/", "~1")
|
def htTitle(name):
"""Format a `name` as a section title."""
return f'<h2 class="section">{name}</h2>'
|
def prune_pout(pout, in_names):
"""Removes entries marked for deletion in a BigMultiPipe.pipeline() output
Parameters
----------
pout : list of tuples (str or ``None``, dict)
Output of a :meth:`BigMultiPipe.pipeline()
<bigmultipipe.BigMultiPipe.pipeline>` run. The `str` are
pipeline output filenames, the `dict` is the output metadata.
in_names : list of str
Input file names to a :meth:`BigMultiPipe.pipeline()
<bigmultipipe.BigMultiPipe.pipeline>` run. There will
be one ``pout`` for each ``in_name``
Returns
-------
(pruned_pout, pruned_in_names) : list of tuples (str, dict)
Pruned output with the ``None`` output filenames removed in both
the ``pout`` and ``in_name`` lists.
"""
pruned_pout = []
pruned_in_names = []
for i in range(len(pout)):
if pout[i][0] is None and pout[i][1] == {}:
# outfname AND meta are empty
continue
pruned_pout.append(pout[i])
pruned_in_names.append(in_names[i])
return (pruned_pout, pruned_in_names)
|
def _AddDataTableSeries(channel_data, output_data):
"""Adds series to the DataTable inputs.
Args:
channel_data: A dictionary of channel names to their data. Each value in
the dictionary has the same sampling frequency and the same time slice.
output_data: Current graph data for DataTable API.
Returns:
The edited output_data dictionary where the first index represents the
time axis value and the second the series value.
"""
for i in range(len(list(channel_data.values())[0])):
output_data[i].update({channel_name: data[i]
for channel_name, data in channel_data.items()})
return output_data
|
def reverse_strand(strand):
"""Given a strand
:return the opposite strand: if is specify
:return None: if strand is not defined
"""
dict_inverted = dict([('+', '-'), ('-', '+'), (None, None)])
return dict_inverted[strand]
|
def fix_path(path_in: str, path_type='dir') -> str:
"""
Fix path, including slashes.
:param path_in: Path to be fixed.
:param path_type: 'file' or 'dir'
:return: Path with forward slashes.
"""
path = str(path_in).replace('\\', '/')
if not path.endswith("/") and path_type != "file":
path += "/"
return path
|
def dict_to_formula(material_dict):
"""Input a material in element dict form
Returns formula of element (arbitrary order)
"""
formula = ""
for element, val in material_dict.items():
if val != 0:
formula = formula + f'{element}{val}'
return formula
|
def results_to_dict(results):
"""convert result arrays into dict used by json files"""
# video ids and allocate the dict
vidxs = sorted(list(set(results['video-id'])))
results_dict = {}
for vidx in vidxs:
results_dict[vidx] = []
# fill in the dict
for vidx, start, end, label, score in zip(
results['video-id'],
results['t-start'],
results['t-end'],
results['label'],
results['score']
):
results_dict[vidx].append(
{
"label" : int(label),
"score" : float(score),
"segment": [float(start), float(end)],
}
)
return results_dict
|
def _testRGBW(R, G, B, W):
""" RGBW coherence color test
:param R: red value (0;255)
:param G: green value (0;255)
:param B: blue value (0;255)
:param W: white value (0;255)
:return: True if coherent / False otherwise """
try:
if (R != 0) and (G != 0) and (B != 0):
raise ValueError
except ValueError:
print("Incoherent RGBW value: more than 2 color components")
return False
try:
if (R + W) not in range(256) or (G + W) not in range(256) or (B + W) not in range(256):
raise ValueError
except ValueError:
print("Incoherent RGBW value: at least one op overflows")
return False
return True
|
def factorial(n):
""" defined as n * n-1"""
if n <= 1:
return 1
else:
return n * factorial(n-1)
|
def get_magic(name):
"""Get a magic function by name or None if not exists."""
return globals().get("do_" + name)
|
def relative_angle(x, y):
"""Assuming y is clockwise from x, increment y by 360 until it's not less
than x.
Parameters:
x (float): start angle in degrees.
y (float): end angle in degrees.
Returns:
float: y shifted such that it represents the same angle but is greater
than x.
"""
while y - 360.0 >= x:
y -= 360.0
while y < x:
y += 360.0
return y
|
def get_user_host(user_host):
""" Returns a tuple (user, host) from the user_host string. """
if "@" in user_host:
return tuple(user_host.split("@"))
return None, user_host
|
def check_suffix(x, suffixes):
"""check whether string x ends with one of the suffixes in suffixes"""
for suffix in suffixes:
if x.endswith(suffix):
return True
return False
|
def minusX10(a,b):
"""subtracts b from a, multiplies by 10 and retuns the answer"""
c = (a-b)*10
return c
|
def exp_gradients(x, y, a, mu, eta):
"""KL loss gradients of neurons with sigmoid activation
(~ Exponential(lambda=1/mu))."""
delta_b = eta * (1 - (2 + (1 / mu)) * y + (y**2) / mu)
delta_a = (eta / a) + delta_b * x
return delta_a, delta_b
|
def sanitize(val):
"""Escape latex specical characters in string values."""
if isinstance(val, str):
val = val.replace('_', r'\_').replace('%', r'\%')
return val
|
def get_accuracy(y_pred, y_test):
"""
Get the prediction accuracy, which is number of correct predictions / number of all predictions.
:param y_pred:
:param y_test:
:return: prediction accuracy
"""
good = 0
for i, pred in enumerate(y_pred):
if pred == y_test[i]:
good += 1
return (good + 0.0) / len(y_pred)
|
def process_single_service_request_definition_output(res) -> dict:
"""
Process single service request definition response object for output
:param res: service request definition object
:return: processed object for output
"""
service_request_definition_name = ''
for field in res.get('Fields', []):
if field.get('Name', '') == 'title':
service_request_definition_name = field.get('Value', '')
questions = ''
for question in res.get('Questions', []):
questions += (('\n\n' if len(questions) > 0 else '')
+ 'Id: ' + question.get('Id', '')
+ '\nQuestion: ' + question.get('Text', '')
+ '\nIs Required: ' + ('Yes' if question.get('IsRequired', False) else 'No'))
return {
'Service Request Definition Id': res.get('Id', ''),
'Service Request Definition Name': service_request_definition_name,
'Questions': questions
}
|
def decode_labelme_shape(encoded_shape):
"""
Decode the cnn json shape (usually encoded from labelme format)
Return a list of points that are used in labelme
"""
assert isinstance(encoded_shape, str)
points = encoded_shape.split(',')
shape = list()
for point in points:
x, y = point.split('+')
shape.append([float(x), float(y)])
return shape
|
def new_network(address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel):
"""{ address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel }"""
network = {
'address' : address
,'ssid' : ssid
,'frequency' : frequency
,'encrypted' : encrypted
,'encryption_type': encryption_type
,'mode' : mode
,'bit_rates' : bit_rates
,'channel' : channel
}
return network
|
def single_letter_count(word, letter):
"""How many times does letter appear in word (case-insensitively)?"""
return word.lower().count(letter.lower())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.