content stringlengths 42 6.51k |
|---|
def has_colours(stream):
"""Determine if an output stream supports colours.
Args:
stream: the output stream to check
Returns:
True if more than 2 colours are supported; else False
"""
if hasattr(stream, 'isatty') and stream.isatty():
try:
import curses
curses.setupterm()
return curses.tigetnum('colors') > 2
except Exception:
pass
return False |
def calc_amount_p(fraction_bound, l, kdax):
""" Calculate amount of protein for a given fraction bound and KD"""
return (-(kdax*fraction_bound) - l*fraction_bound + l*fraction_bound*fraction_bound)/(-1 + fraction_bound) |
def lr_gamma(initial_lr=1e-5, last_lr=1e-3, total=50, step=5, mode="log10"):
"""
Compute the gamma of learning rate to be stepped, where gamma can be
larger or equal than 1 or less than 1.
"""
num_step = (total // step) - 1
assert num_step > 0
gamma = (last_lr / initial_lr) ** (1/num_step)
return gamma |
def maybe_parentheses(obj, operator: str = " ") -> str:
"""
Wrap the string (or object's string representation) in parentheses, but only if required.
:param obj:
The object to (potentially) wrap up in parentheses. If it is not a string, it is converted
to a string first.
:param operator:
The operator that needs precedence rules clarified. The default is ``' '`` (a space).
:return: The (possibly) parenthesized string.
"""
s = str(obj)
if operator not in s:
return s
# if there are already wrapping punctuation marks, there may not be a need to add additional
# ones
open_mark = s[0]
if open_mark in "([{":
groupings = [s[0]]
for c in s[1:-1]:
if c in "([{":
groupings.append(c)
elif c == "}":
if groupings[-1] == "{":
groupings.pop()
else:
groupings.clear()
elif c == "]":
if groupings[-1] == "[":
groupings.pop()
else:
groupings.clear()
elif c == ")":
if groupings[-1] == "(":
groupings.pop()
else:
groupings.clear()
if not groupings:
# we balanced out all groupings (or just his a syntax error in unmatched groupings);
# add clarifying parentheses
return "(" + s + ")"
if (
(groupings[0] == "(" and groupings[-1] == ")")
or (groupings[0] == "[" and groupings[-1] == "]")
or (groupings[0] == "{" and groupings[-1] == "}")
):
return s
return "(" + s + ")" if operator in s else s |
def get_instances_invited(game, player):
""" Return the instance ids of instances that player has been invited to.
Args:
game: The parent Game database model to query for instances.
player: The email address of the player to look for in instances.
Returns:
An empty list if game is None. Else, returns a list of the
instance ids of all instances with game as their parent that have
player in their invited list.
"""
if game is None:
return []
query = game.get_invited_instance_keys_query(player)
return [key.name() for key in query] |
def index_to_coord(index):
"""Returns relative chunk coodinates (x,y,z) given a chunk index.
Args:
index (int): Index of a chunk location.
"""
y = index // 256
z = (index - y * 256) // 16
x = index - y * 256 - z * 16
return x, y, z |
def read_binary_file(filepath):
"""Read the contents of a binary file."""
with open(filepath, 'rb') as file_handle:
data = file_handle.read()
return data |
def undo(rovar):
"""Translates rovarspraket into english"""
for low, upper in zip("bcdfghjklmnpqrstvwxyz", "BCDFGHJKLMNPQRSTVWXYZ"):
rovar = f"{upper}".join(f"{low}".join(rovar.split(f"{low}o{low}")).split(f"{upper}o{low}"))
return rovar |
def isPerfect(x):
"""Returns whether or not the given number x is perfect.
A number is said to be perfect if it is equal to the sum of all its
factors (for obvious reasons the list of factors being considered does
not include the number itself).
Example: 6 = 3 + 2 + 1, hence 6 is perfect.
Example: 28 is another example since 1 + 2 + 4 + 7 + 14 is 28.
Note, the number 1 is not a perfect number.
"""
# your code here
Perfect_num = False
sum = 0
for i in range(1, x):
if(x % i == 0):
sum += i
if (sum == x):
Perfect_num = True
else:
Perfect_num = False
return Perfect_num |
def intToBin(i):
""" Integer to two bytes """
# divide in two parts (bytes)
i1 = i % 256
i2 = int( i/256)
# make string (little endian)
return i.to_bytes(2,byteorder='little') |
def calc_iou_wh(box1_wh, box2_wh):
"""
param box1_wh (list, tuple): Width and height of a box
param box2_wh (list, tuple): Width and height of a box
return (float): iou
"""
min_w = min(box1_wh[0], box2_wh[0])
min_h = min(box1_wh[1], box2_wh[1])
area_r1 = box1_wh[0] * box1_wh[1]
area_r2 = box2_wh[0] * box2_wh[1]
intersect = min_w * min_h
union = area_r1 + area_r2 - intersect
return intersect / union |
def normalise_U(U):
"""
This de-fuzzifies the U, at the end of the clustering. It would assume that the point is a member of the cluster whoes membership is maximum.
"""
for i in range(0,len(U)):
maximum = max(U[i])
for j in range(0,len(U[0])):
if U[i][j] != maximum:
U[i][j] = 0
else:
U[i][j] = 1
return U |
def to_uint8_bytes(val: int) -> bytes:
"""Convert an integer to uint8."""
return val.to_bytes(1, byteorder="little") |
def _footer(settings):
"""
Return the footer of the Latex document.
Returns:
tex_footer_str (string): Latex document footer.
"""
return "\n\n\end{tikzpicture}\n\end{document}" |
def chunkify(lst, n):
"""
Splits a list into roughly n equal parts.
http://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts
"""
return [lst[i::n] for i in range(n)] |
def get_indices_pattern(lines, pattern, num_lines, offset):
"""Processes the output file of the QM software used to
find the first occurence of a specifie pattern. Useful
if this block will be in the file only once and if there
is no line that explicitly indicates the end of the block.
Args:
lines (list):
Log file of the QM software to be processed.
pattern (str):
The pattern of the block.
num_lines (int):
How many line should be read.
offset (int):
How many lines are between the pattern and the first line of the block.
Returns:
list: Indices of the first and the last line of the block (including the offset).
"""
idxs = [None] * 2
for i, line in enumerate(lines):
if pattern in line:
# only go with first occurence
idxs[0] = i + offset
idxs[1] = i + num_lines + offset
break
return idxs |
def wrap(obj, start_angle, range_angle):
"""
Wrap obj between start_angle and (start_angle + range_angle).
:param obj: number or array to be wrapped
:param start_angle: start angle of the range
:param range_angle: range
:return: wrapped angle in [start_angle, start_angle+range[
"""
return (obj - start_angle + range_angle) % range_angle + start_angle |
def ceillog( n ) : ## ceil( log_2 ( n )) [Used by LZ.py]
"""
>>> print(ceillog(3), ceillog(4), ceillog(5))
2 2 3
"""
assert n>=1
c = 0
while 2**c<n :
c += 1
return c |
def _resort_categorical_level(col_mapping):
"""
Resort the levels in the categorical encoders if all levels can be converted
to numbers (integer or float).
Args:
col_mapping: the dictionary that maps level string to int
Returns:
New col_mapping if all levels can be converted to numbers, otherwise
the original col_mapping
"""
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
if all(map(is_number, col_mapping.keys())):
key_tuples = [(k, float(k)) for k in col_mapping.keys()]
sorted_key_tuples = sorted(key_tuples, key=lambda x: x[1])
new_mapping = {}
value = 1
for t in sorted_key_tuples:
new_mapping[t[0]] = value
value += 1
return new_mapping
else:
return col_mapping |
def get_lines(stdout_text):
"""Assumes your console uses utf-8"""
return stdout_text.strip().decode('utf-8').split('\n') |
def greatest_sum_of_subarrays(nums):
"""
:param nums: array
:return: max sum of subarray
"""
max = sub_sum = float('-inf')
for n in nums:
if sub_sum + n <= n:
sub_sum = n
else:
sub_sum += n
if sub_sum > max:
max = sub_sum
return max |
def clear(keyword):
"""``clear`` property validation."""
return keyword in ('left', 'right', 'both', 'none') |
def build_url(tail, variation, base_url):
"""
Takes the passed parameters and builds a URL to query the OMA database
Args:
tail(str): The path and REST parameters that returns the desired info
variation(list): A list of strings that contain the parameters unique
to the query
base_url(str): The website that is being accessed, without any slashes
"""
url = base_url + tail
url = url.format(*variation)
return url |
def _check_if_searching(search_form):
"""
Presentation logic for showing 'clear search' and the adv. form.
Needed to check that the form fields have non-empty value and to say
that searching on 'text_query' only should not show adv. form.
"""
searching = False
adv_searching = False
if not search_form:
return searching, adv_searching
for field in search_form:
if field.data:
# If filtering, show 'clear search' button.
searching = True
if field.name != 'text_query':
# If filtering by adv fields, don't hide the adv field form.
adv_searching = True
break
return searching, adv_searching |
def findIndexes(text, subString):
"""
Returns a set of all indexes of subString in text.
"""
indexes = set()
lastFoundIndex = 0
while True:
foundIndex = text.find(subString, lastFoundIndex)
if foundIndex == -1:
break
indexes.add(foundIndex)
lastFoundIndex = foundIndex + 1
return indexes |
def _eth(dst, src, data):
"""Builds an Ethernet frame with and IP packet as payload"""
packet = (
dst + # dst
src + # src
b'' + # vlan
b'\x08\x00' # type
) + data
return packet |
def lower(input_string: str) -> str:
"""Convert the complete string to lowercase."""
return input_string.lower() |
def create_dt_hparams(max_depth=None, min_samples_split=2):
"""
Creates hparam dict for input into create_DNN_model or other similar functions. Contain Hyperparameter info
:return: hparam dict
"""
names = ['max_depth','min_samples_split']
values = [max_depth, min_samples_split]
hparams = dict(zip(names, values))
return hparams |
def item_brand(item, attributes_dict, attribute_values_dict):
"""Return an item brand.
This field is required.
Read more:
https://support.google.com/merchants/answer/6324351?hl=en&ref_topic=6324338
"""
brand = None
brand_attribute_pk = attributes_dict.get('brand')
publisher_attribute_pk = attributes_dict.get('publisher')
if brand_attribute_pk:
brand = item.attributes.get(str(brand_attribute_pk))
if brand is None:
brand = item.product.attributes.get(str(brand_attribute_pk))
if brand is None and publisher_attribute_pk is not None:
brand = item.attributes.get(str(publisher_attribute_pk))
if brand is None:
brand = item.product.attributes.get(str(publisher_attribute_pk))
if brand is not None:
brand_name = attribute_values_dict.get(brand)
if brand_name is not None:
return brand_name
return brand |
def jaccardIndexFaces(face1, face2):
"""Compute the Jaccard index between two faces"""
face1Set = set(face1)
face2Set = set(face2)
inter = len(face1Set.intersection(face2Set))
union = len(face1Set.union(face2Set))
if union == 0:
return 1
else:
return float(inter) / float(union) |
def get_switchport_config_commands(interface, existing, proposed):
"""Gets commands required to config a given switchport interface
"""
proposed_mode = proposed.get('mode')
existing_mode = existing.get('mode')
commands = []
command = None
if proposed_mode != existing_mode:
if proposed_mode == 'trunk':
command = 'switchport mode trunk'
elif proposed_mode == 'access':
command = 'switchport mode access'
if command:
commands.append(command)
if proposed_mode == 'access':
av_check = existing.get('access_vlan') == proposed.get('access_vlan')
if not av_check:
command = 'switchport access vlan {0}'.format(
proposed.get('access_vlan'))
commands.append(command)
elif proposed_mode == 'trunk':
tv_check = existing.get('trunk_vlans_list') == proposed.get('trunk_vlans_list')
if not tv_check:
vlans_to_add = False
for vlan in proposed.get('trunk_vlans_list'):
if vlan not in existing.get('trunk_vlans_list'):
vlans_to_add = True
break
if vlans_to_add:
command = 'switchport trunk allowed vlan add {0}'.format(proposed.get('trunk_vlans'))
commands.append(command)
native_check = existing.get(
'native_vlan') == proposed.get('native_vlan')
if not native_check and proposed.get('native_vlan'):
command = 'switchport trunk native vlan {0}'.format(
proposed.get('native_vlan'))
commands.append(command)
if commands:
commands.insert(0, 'interface ' + interface)
return commands |
def mergeDict(dict1, dict2):
""" Merge dictionaries and keep values of common keys in list"""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = [value, dict1[key]]
return dict3 |
def get_camera_kapture_id_from_colmap_id(camera_id_colmap) -> str:
"""
Create a deterministic kapture camera identifier from the colmap camera identifier:
sensor_id = "cam_xxxxx" where "xxxxx" is the colmap ID.
:param camera_id_colmap: colmap camera identifier
:return: kapture camera identifier.
"""
assert isinstance(camera_id_colmap, int)
return f'cam_{camera_id_colmap:05d}' |
def set_results(to, from_):
"""
sets the main results dict.
:param to:
:param from_:
:return:
"""
to["url"].append(from_["url"])
to["description"].append(from_["description"])
to["price"].append(from_["price"])
to["site"].append(from_["site"])
return to |
def equip_sensors(worldmap, sensors):
"""
Args:
worldmap (str): a string that describes the initial state of the world.
sensors (dict) a map from robot character representation (e.g. 'r') to a
string that describes its sensor (e.g. 'laser fov=90 min_range=1 max_range=5
angle_increment=5')
Returns:
str: A string that can be used as input to the `interpret` function
"""
worldmap += "\n***\n"
for robot_char in sensors:
worldmap += "%s: %s\n" % (robot_char, sensors[robot_char])
return worldmap |
def csv_list(csv_str):
"""
Parser function to turn a string of comma-separated values into a list.
"""
return [int(i) for i in csv_str.split(",")] |
def isDeployed(item):
""" query a SNIPEIT asset about its deployment status """
return (item['status_label']['status_meta']=='deployed') |
def empirical_fpr(n_fp, n_nt):
"""Compute empirical false positive rate (FPR).
Input arguments:
================
n_fp : int
The observed number of false positives.
n_nt : int
The number of hypotheses for which the null is true.
Output arguments:
=================
fpr : float
Empirical false positive rate.
"""
return float(n_fp) / float(n_nt) |
def is_symbol (c):
""" Checks whether a character is a symbol.
A symbol is defined as any character that is neither a lowercase letter, uppercase letter or digit.
Args:
c (char): The character to check.
Returns:
bool: True if the character is a symbol, otherwise false.
"""
return (not c.islower() and not c.isupper() and not c.isdigit()) |
def To2(x, n):
"""
:param x: the value you want to convert
:param n: keep n bits
:return: binary value
"""
X = x
N = n
m = bin(X)
m = m.lstrip('0b')
a = []
L = []
if len(m) < N:
for i in range(N - len(m)):
a.append('0')
a = ''.join(a)
k = a + m
else:
k = m
for j in range(len(k)):
L.append(k[j])
return L |
def pad_line(line):
# borrowed from from pdb-tools (:
"""Helper function to pad line to 80 characters in case it is shorter"""
size_of_line = len(line)
if size_of_line < 80:
padding = 80 - size_of_line + 1
line = line.strip('\n') + ' ' * padding + '\n'
return line[:81] |
def print_xml(i, s, m, v, com, d):
"""Create gazebo xml code for the given joint properties"""
# Convert joint properties to xml code
# NOTE: https://www.physicsforums.com/threads/how-does-the-moment-of-inertia-scale.703101/ # noqa: E501
v = v / s ** 3
com = [x / s for x in com]
for key in d.keys():
d[key] = d[key] / s ** 5 * m / v
print("link_{}".format(i))
print("<inertial>")
print(' <mass value="{}" />'.format(m))
print(' <origin xyz="{} {} {}" rpy="0 0 0" />'.format(com[0], com[1], com[2]))
print(
' <inertia ixx="{ixx}" ixy="{ixy}" ixz="{ixz}" iyy="{iyy}" iyz="{iyz}" izz="{izz}" />'.format( # noqa: E501
**d
)
)
print("</inertial>")
print()
return True |
def get_human_readable(duration):
"""
Blatenly stole from:
https://github.com/s16h/py-must-watch/blob/master/add_youtube_durations.py
"""
hours = duration[0]
minutes = duration[1]
seconds = duration[2]
output = ''
if hours == '':
output += '00'
else:
output += '0' + str(hours)
output += ':'
if minutes == '':
output += '00'
elif int(minutes) < 10:
output += '0' + str(minutes)
else:
output += str(minutes)
output += ':'
if seconds == '':
output += '00'
elif int(seconds) < 10:
output += '0' + str(seconds)
else:
output += str(seconds)
return output |
def searchList(sNeedle, aHaystack):
"""Get the index of element in a list or return false"""
try:
return aHaystack.index(sNeedle)
except ValueError:
return False |
def parse_file_string(filestring):
"""
>>> parse_file_string("File 123: ABC (X, Y) Z")
('ABC (X, Y) Z', '')
>>> parse_file_string("File 123: ABC (X) Y (Z)")
('ABC (X) Y', 'Z')
>>> parse_file_string("File: ABC")
('ABC', '')
>>> parse_file_string("File 2: A, B, 1-2")
('A, B, 1-2', '')
"""
if filestring.strip()[-1] != ")":
filestring=filestring.strip()+"()"
rhs = filestring.partition(":")[2]
chunks = rhs.split('(')
indname = '('.join(chunks[:-1])
units = chunks[-1].replace(')','')
return indname.strip(), units.strip() |
def formatSize(sizeBytes):
"""
Format a size in bytes into a human-readable string with metric unit
prefixes.
:param sizeBytes: the size in bytes to format.
:returns: the formatted size string.
"""
suffixes = ['B', 'kB', 'MB', 'GB', 'TB']
if sizeBytes < 20000:
return '%d %s' % (sizeBytes, suffixes[0])
idx = 0
sizeVal = float(sizeBytes)
while sizeVal >= 1024 and idx + 1 < len(suffixes):
sizeVal /= 1024
idx += 1
if sizeVal < 10:
precision = 3
elif sizeVal < 100:
precision = 2
else:
precision = 1
return '%.*f %s' % (precision, sizeVal, suffixes[idx]) |
def find_true_link(s):
"""
Sometimes Google wraps our links inside sneaky tracking links, which often fail and slow us down
so remove them.
"""
# Convert "/url?q=<real_url>" to "<real_url>".
if s and s.startswith('/') and 'http' in s:
s = s[s.find('http'):]
return s |
def has_flush(h):
"""
Flush: All cards of the same suit.
return: (hand value, remaining cards) or None
"""
suits = {suit for _, suit in h}
if len(suits) == 1:
return max([value for value, _ in h]), []
else:
return None |
def _get_mean_runtime(data: list):
"""
Calculates the average runtime/image for clustering from prior training c-means.
-----------------------------------------------------------------------------------
!!! For statistical evaluation !!!
-----------------------------------------------------------------------------------
Parameters:
-----------------------------------------------------------------------------------
data: List (ndarray, int)
Result from fcm_train().
Returns:
-----------------------------------------------------------------------------------
runtime: float
The average runtime of the algorithm in seconds.
"""
mean_runtime = 0
for item in data:
mean_runtime += item[7] / len(data)
return mean_runtime |
def make_toc(state, cls, sections):
"""
Create the class TOC.
"""
n = []
for section_cls in sections:
section = section_cls(state, cls)
section.check()
n += section.format()
return n |
def cria_peca(char):
"""
Devolve a peca correspondente ah string inserida
:param char: string
:return: peca
Recebe uma string e devolve a peca correspondente a essa string.
Caso o argumento seja invalido e nao corresponda a nenhum peca, a funcao gera um erro
"""
if char not in ("X", "O", " "):
raise ValueError("cria_peca: argumento invalido")
return char |
def chmax(dp, i, x):
"""chmax; same as:
dp[i] = max(dp[i], x)
ref: https://twitter.com/cs_c_r_5/status/1266610488210681857
Args:
dp (list): one dimensional list
i (int): index of dp
x (int): value to be compared with
Returns:
bool: True if update is done
ex:
# one dimensional dp
chmax(dp,i,x)
# two dimensional dp
chmax(dp[i],j,x)
"""
if x > dp[i]:
dp[i] = x
return True
return False |
def trapezoid_score_function(x, lower_bound, upper_bound, softness=0.5):
"""
Compute a score on a scale from 0 to 1 that indicate whether values from x belong
to the interval (lbound, ubound) with a softened boundary.
If a point lies inside the interval, its score is equal to 1.
If the point is further away than the interval length multiplied by the softness parameter,
its score is equal to zero.
Otherwise the score is given by a linear function.
"""
interval_width = upper_bound - lower_bound
subound = upper_bound + softness * interval_width
slbound = lower_bound - (softness * interval_width) * 0.1
swidth = softness * interval_width # width of the soft boundary
if lower_bound <= x <= upper_bound:
return 1.0
elif x <= slbound or x >= subound:
return 0.0
elif slbound <= x <= lower_bound:
return 1.0 - (lower_bound - x) / swidth
elif upper_bound <= x <= subound:
return 1.0 - (x - upper_bound) / swidth |
def TimeToSeconds(time):
"""
Converts a timestamp to just seconds elapsed
@param time: HH:MM:SS.SSS timestamp
@type time: tuple<int, int, int, int>
@return: seconds equivalence
@rtype: float
"""
return 3600 * time[0] + 60 * time[1] + time[2] + 0.001 * time[3] |
def parse_colon_dict(data):
"""
Parse colon seperated values into a dictionary, treating lines
lacking a colon as continutation lines.
Any leading lines without a colon will be associated with the key
``None``.
This is the format output by ``rpm --query`` and ``dpkg --info``.
:param bytes data: Data to parse
:return: A ``dict`` containing the parsed data.
"""
result = {}
key = None
for line in data.splitlines():
parts = [value.strip() for value in line.split(':', 1)]
if len(parts) == 2:
key, val = parts
result[key] = val
else:
result.setdefault(key, '')
result[key] += parts[0]
return result |
def group_seqs_by_length(seqs_info):
"""group sequences by their length
Args:
seqs_info: dictionary comprsing info about the sequences
it has this form {seq_id:{T:length of sequence}}
.. note::
sequences that are with unique sequence length are grouped together as singeltons
"""
grouped_seqs = {}
for seq_id, seq_info in seqs_info.items():
T = seq_info["T"]
if T in grouped_seqs:
grouped_seqs[T].append(seq_id)
else:
grouped_seqs[T] = [seq_id]
# loop to regroup single sequences
singelton = [T for T, seqs_id in grouped_seqs.items() if len(seqs_id) == 1]
singelton_seqs = []
for T in singelton:
singelton_seqs += grouped_seqs[T]
del grouped_seqs[T]
grouped_seqs["singleton"] = singelton_seqs
return grouped_seqs |
def ptime(s: float) -> str:
"""
Pretty print a time in the format H:M:S.ms. Empty leading fields are disgarded with the
exception of times under 60 seconds which show 0 minutes.
>>> ptime(234.2)
'3:54.200'
>>> ptime(23275.24)
'6:27:55.240'
>>> ptime(51)
'0:51'
>>> ptime(325)
'5:25'
"""
m, s = divmod(s, 60)
h, m = divmod(m, 60)
ms = int(round(s % 1 * 1000))
if not h:
if not ms:
return "{}:{:02d}".format(int(m), int(s))
return "{}:{:02d}.{:03d}".format(int(m), int(s), ms)
if not ms:
return "{}:{:02d}:{:02d}".format(int(h), int(m), int(s))
return "{}:{:02d}:{:02d}.{:03d}".format(int(h), int(m), int(s), ms) |
def is_visible(lat, lon, domain_boundaries, cross_dateline) -> bool:
"""Check if a point (city) is inside the domain.
Args:
lat float latitude of city
lon float longitude of city
domain_boundaries list lon/lat range of domain
cross_dateline bool if cross_dateline --> western lon values need to be shifted
Returns:
bool True if city is within domain boundaries, else false.
"""
if cross_dateline:
if lon < 0:
lon = 360 - abs(lon)
in_domain = (
domain_boundaries[0] <= float(lon) <= domain_boundaries[1]
and domain_boundaries[2] <= float(lat) <= domain_boundaries[3]
)
if in_domain:
return True
else:
return False |
def make_qs(listname: list) -> str:
"""Create a list of '?'s for use in a query string.
This is a convenience function that will take a list and return a string
composed of len(list) queston marks joined by commas for use in an sql
VALUES() clause.
Args:
listname: The list to use for generation.
"""
return ",".join(["?" for _ in range(len(listname))]) |
def test_columns(data_frame):
"""
Checks that the dataframe has the required columns.
:params dataframe data_frame:
:returns bool:
"""
required_columns = True
cols = list(data_frame)
for col in cols:
if col not in ['Draw Date', 'Winning Numbers', 'Mega Ball', 'Multiplier']:
required_columns = False
break
else:
pass
return required_columns |
def transform_init_state_cause(cause, message):
"""
Transforms the init failure cause to a user-friendly message.
:param cause: cause of failure
:param message: failure message
:return: transformed message
"""
return {
'credentials': 'No or invalid credentials provided',
'token': 'JWT retrieval failed: [{}]'.format(message),
'config': 'One or more invalid settings were encountered: [{}]'.format(message),
'api': 'Client API failed to start: [{}]'.format(message),
}.get(cause, message) |
def reduce_powers(element, powers, exponent=2):
"""
>>> reduce_powers((2, 2), [[], [], []])
((), True)
>>> reduce_powers((), [[], [], []])
((), False)
>>> reduce_powers((2, 1, 0), [[], [], []])
((2, 1, 0), False)
"""
l = []
current = None
count = 0
changed = False
for x in element[::-1]:
if current is None:
current = x
count = 1
else:
if x == current:
count = count + 1
if count == exponent:
for g in powers[x][::-1]:
l.append(g)
count = 0
current = None
changed = True
else:
for i in range(0, count):
l.append(current)
current = x
count = 1
for i in range(0, count):
l.append(current)
return tuple(l[::-1]), changed |
def wrap_with_license(block, view, frag, context): # pylint: disable=unused-argument
"""
In the LMS, display the custom license underneath the XBlock.
"""
license = getattr(block, "license", None) # pylint: disable=redefined-builtin
if license:
context = {"license": license}
frag.content += block.runtime.render_template('license_wrapper.html', context)
return frag |
def get_methods(object, include_special=True):
"""Returns a list of methods (functions) within object"""
if include_special:
return [method_name for method_name in dir(object) if callable(getattr(object, method_name))]
return [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name] |
def parse_key_id(key_id):
"""validate the key_id and break it into segments
:arg key_id: The key_id as supplied by the user. A valid key_id will be
8, 16, or more hexadecimal chars with an optional leading ``0x``.
:returns: The portion of key_id suitable for apt-key del, the portion
suitable for comparisons with --list-public-keys, and the portion that
can be used with --recv-key. If key_id is long enough, these will be
the last 8 characters of key_id, the last 16 characters, and all of
key_id. If key_id is not long enough, some of the values will be the
same.
* apt-key del <= 1.10 has a bug with key_id != 8 chars
* apt-key adv --list-public-keys prints 16 chars
* apt-key adv --recv-key can take more chars
"""
# Make sure the key_id is valid hexadecimal
int(key_id, 16)
key_id = key_id.upper()
if key_id.startswith('0X'):
key_id = key_id[2:]
key_id_len = len(key_id)
if (key_id_len != 8 and key_id_len != 16) and key_id_len <= 16:
raise ValueError('key_id must be 8, 16, or 16+ hexadecimal characters in length')
short_key_id = key_id[-8:]
fingerprint = key_id
if key_id_len > 16:
fingerprint = key_id[-16:]
return short_key_id, fingerprint, key_id |
def get_available_resources(threshold, usage, total):
"""Get a map of the available resource capacity.
:param threshold: A threshold on the maximum allowed resource usage.
:param usage: A map of hosts to the resource usage.
:param total: A map of hosts to the total resource capacity.
:return: A map of hosts to the available resource capacity.
"""
return dict((host, int(threshold * total[host] - resource))
for host, resource in usage.items()) |
def pipe_grav_dp(m_dot=10.0, rho=115.0, z=950.0):
"""
:param m_dot: mass flow [kg/s], (+) injection, (-) withdrawl
:param rho: density [kg/m^3]
:param z: depth/length [m]
:return delta_p: pressure loss [MPa]
"""
# gravitational constant
g = 9.81 # [m/s^2]
if m_dot > 0.0: # injection
delta_p = -rho * g * z
elif m_dot < 0.0: # withdrawl
delta_p = rho * g * z
else: # no activity
delta_p = -rho * g * z
return delta_p * 1.0e-6 |
def _byte_to_keys(keys_as_byte: bytes, num_keys=6) -> list:
"""Return a list of key (bit) numbers for each 1 in keys_as_byte."""
keys_as_int = int.from_bytes(keys_as_byte, 'little')
return [
key
for key in range(num_keys)
if keys_as_int & (1 << key)
] |
def first_and_last(l: list) -> list:
"""Return first and last elements takes list.
::param l: list of integers
::type l: list
::rtype: list of integers
"""
return l[0::len(l) - 1 if len(l) > 1 else None] |
def get_raw_pdb_filename_from_interim_filename(interim_filename, raw_pdb_dir):
"""Get raw pdb filename from interim filename."""
pdb_name = interim_filename
slash_tokens = pdb_name.split('/')
slash_dot_tokens = slash_tokens[-1].split(".")
raw_pdb_filename = raw_pdb_dir + '/' + slash_tokens[-2] + '/' + slash_dot_tokens[0] + '.' + slash_dot_tokens[1]
return raw_pdb_filename |
def humanize_seconds(seconds: int):
"""Convert seconds to readable format."""
seconds = int(seconds)
days = seconds // 86400
hours = (seconds - days * 86400) // 3600
minutes = (seconds - days * 86400 - hours * 3600) // 60
seconds = seconds - days * 86400 - hours * 3600 - minutes * 60
result = (
("{0} day{1}, ".format(days, "s" if days != 1 else "") if days else "")
+ ("{0} hour{1}, ".format(hours, "s" if hours != 1 else "") if hours else "")
+ ("{0} minute{1}, ".format(minutes, "s" if minutes != 1 else "") if minutes else "")
+ ("{0} second{1} ".format(seconds, "s" if seconds != 1 else "") if seconds else "")
)
return result |
def bondTyping(bondType, aromatic):
"""Returns type of bond based on given bondType and whether it was marked aromatic.
:param bondType:
:type bondType: :py:class:`str`
:param aromatic:
:type aromatic: :py:class:`str`
:return: bondType
:rtype: :py:class:`str`
"""
return bondType if aromatic == "N" else "AROM" |
def conj(x):
"""Return conjugate of x."""
return x.conjugate() |
def get_bad_messages(rules, task):
"""
Get the bad messages for a certain task.
:param task: the name of the task
:return: a list of signatures of bad messages.
"""
if task == "service_architecture_workloads":
return ["posix_fallocate failed"]
return rules['bad_messages'] |
def _normalize_jwst_id_part(part):
"""Converts jw88600071001_02101_00001_nrs1 --> jw88600071001_02101_00001.nrs. The former is
common notation for most dataset usages, the latter is the official form for the web API to
the archive parameter service for JWST.
"""
if "_" in part and "." not in part: # not HST and common JWST parlance
bits = part.split("_")
fileSetName = "_".join(bits[:-1])
detector = bits[-1]
return fileSetName + "." + detector # Formal archive API
else:
return part |
def remove_session_message_padding(data: bytes):
"""Removes the custom padding that Session may have added. Returns the unpadded data."""
# Except sometimes it isn't padded, so if we find something other than 0x00 or 0x80 *or* we
# strip off all the 0x00's and then find something that isn't 0x80, then we're supposed to use
# the whole thing (without the 0's stripped off). Session code has a comment "This is dumb"
# describing all of this. I concur.
if data and data[-1] in (b'\x00', b'\x80'):
stripped_data = data.rstrip(b'\x00')
if stripped_data and stripped_data[-1] == 0x80:
data = stripped_data[:-1]
return data |
def temp_to_hex(value: float) -> str:
"""Convert a float to a 2's complement 4-byte hex string."""
assert (
not value or -(2 ** 7) <= value < 2 ** 7
), f"temp_to_hex({value}): is out of 2's complement range"
if value is None:
return "7FFF" # or: "31FF"?
if value is False:
return "7EFF"
temp = int(value * 100)
return f"{temp if temp >= 0 else temp + 2 ** 16:04X}" |
def insert_after(list, new, key):
"""
Return a list with the new item inserted after the first occurrence
of the key (if any).
"""
if list == ():
return ()
else:
head, tail = list
if head == key:
return (head, (new, tail))
else:
return (head, insert_after(tail, new, key)) |
def configurationString(N_1,N_2):
"""This functions returns the filename for the given configuration N_1, N_2."""
string = str(max(N_1,N_2)) + "x" + str(min(N_1,N_2))
return string |
def fibonacci2(num):
"""Permette di calcolare il num-esimo numero di fibonacci.
L'algoritmo proposto e' quello ricorsivo."""
if num == 0:
return 0
elif num <=2:
return 1
else:
return fibonacci2(num-1) + fibonacci2(num-2) |
def _dash_escape(args):
"""Escape all elements of *args* that need escaping.
*args* may be any sequence and is not modified by this function.
Return a new list where every element that needs escaping has been
escaped.
An element needs escaping when it starts with two ASCII hyphens
(``--``). Escaping consists in prepending an element composed of two
ASCII hyphens, i.e., the string ``'--'``.
"""
res = []
for arg in args:
if arg.startswith("--"):
res.extend(("--", arg))
else:
res.append(arg)
return res |
def add_needed_ingredients(f_raw_materials, d_raw_materials, f_secret_points):
""" Check for missing ingredients and add them in.
Params:
f_raw_materials: dict
d_raw_materials: dict
f_secret_points: int
Returns:
str, int
"""
f_secret_points -= 1
for f_raw_material in f_raw_materials:
if f_raw_materials[f_raw_material] > d_raw_materials[f_raw_material]:
d_raw_materials[f_raw_material] += f_raw_materials[f_raw_material]
return 'The elves have restocked the machine. You have {0} secret points left.'.format(f_secret_points), \
f_secret_points |
def convert_number_to_letter(number: int) -> str:
"""
This function receives a number, and converts it to its respective alphabet letter in ascending order,
for example:
1 - A
2 - B
3 - C
4 - D
:param int number: The number to be converted.
:rtype: str
"""
return chr(ord('@') + number + 1) |
def get_column_unit(column_name):
"""Return the unit name of an ivium column, i.e what follows the first '/'."""
if "/" in column_name:
return column_name.split("/", 1)[1] |
def unit_size(size):
""" Convert Byte size to KB/MB/GB/TB.
"""
units = ['KB', 'MB', 'GB', 'TB']
i = 0
size = size / 1024
while size >= 1024 and i<(len(units)-1):
i = i + 1
size = size / 1024
return '%.2f %s'%(size, units[i]) |
def is_same_class(obj, a_class):
"""Returns True if obj is same instance, else False
"""
if type(obj) is a_class:
return True
else:
return False |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
# inmutable
handClone = hand.copy()
# print(word)
# print(handClone.keys())
for i in word:
if i in handClone.keys():
# print(i)
handClone[i] = handClone.get(i, 0) - 1
return handClone |
def get_LA_GeoJson(LA_cd):
"""
returns a link to LSOA geojson file within LA passed from https://github.com/martinjc/UK-GeoJSON/
"""
link_base = 'https://raw.githubusercontent.com/martinjc/UK-GeoJSON/master/json/statistical/eng/lsoa_by_lad/'
new_link = link_base+str(LA_cd)+'.json'
return new_link |
def params_to_string(num_params, units=None, precision=2):
"""Convert parameter number into a string.
Args:
num_params (float): Parameter number to be converted.
units (str | None): Converted FLOPs units. Options are None, 'M',
'K' and ''. If set to None, it will automatically choose the most
suitable unit for Parameter number. Default: None.
precision (int): Digit number after the decimal point. Default: 2.
Returns:
str: The converted parameter number with units.
Examples:
>>> params_to_string(1e9)
'1000.0 M'
>>> params_to_string(2e5)
'200.0 k'
>>> params_to_string(3e-9)
'3e-09'
"""
if units is None:
if num_params // 10 ** 6 > 0:
return str(round(num_params / 10 ** 6, precision)) + " M"
elif num_params // 10 ** 3:
return str(round(num_params / 10 ** 3, precision)) + " k"
else:
return str(num_params)
else:
if units == "M":
return str(round(num_params / 10.0 ** 6, precision)) + " " + units
elif units == "K":
return str(round(num_params / 10.0 ** 3, precision)) + " " + units
else:
return str(num_params) |
def fmt(x, empty="-", role=None):
"""
Format element to a humanized form.
"""
if x is None:
return empty
return str(x) |
def generate_graph_with_template(data, title, yaxis_title, xaxi_title):
"""
This common layout can be used to create Plotly graph layout.
INPUT:
data - a graph required JSON data i.e list
title - a tile of the chart
yaxis_title - Y title
xaxix_title - X title
OUTPUT:
layout for particular graph.
"""
return {
'data': [data],
'layout': {
'title': title,
'yaxis': {
'title': yaxis_title
},
'xaxis': {
'title': xaxi_title
}
}
} |
def _format_ptk_style_name(name):
"""Format PTK style name to be able to include it in a pygments style"""
parts = name.split("-")
return "".join(part.capitalize() for part in parts) |
def trailing_zeros(phenome):
"""The bare-bones trailing-zeros function."""
ret = 0
i = len(phenome) - 1
while i >= 0 and phenome[i] == 0:
ret += 1
i -= 1
return ret |
def precut(layers, links, all_terms, user_info):
"""
This function cuts terms in layers if they do not exist inside
the accuracy file of model 1.
It also cuts all links if one of the terms inside does not exist
inside the accuracy file of model 1.
Finaly it cuts all terms taht do not exist inside the accuracy
file of model 1.
:return:
Cut layers, links (edges) and terms are returned.
"""
new_layers = []
for layer in layers:
new_layer = []
for node in layer:
if node in user_info:
new_layer.append(node)
if len(new_layer) != 0:
new_layers.append(new_layer)
else:
new_layer = []
new_links = set()
for link in links:
if link[0] in user_info and link[1] in user_info:
new_links.add(link)
new_all_terms = {}
for term in all_terms:
if term in user_info:
new_all_terms[term] = all_terms[term]
return new_layers, new_links, new_all_terms |
def _number_power(n, c=0):
"""
This is an odd one, for sure. Given a number, we return a tuple that tells us
the numerical format to use. It makes a little more sense if you think of
the second number in the tuple as a pointer into the list:
('', 'hundred', 'thousand', 'million', ...)
...so, given the input, '100', we return (1, 1), which can be read as (1, 'hundred')
This could easily have been a lookup table of reasonable size,
but what's the fun of that when we can use recursion?
>>> _number_power('1')
(1, 0)
>>> _number_power('10')
(10, 0)
>>> _number_power('23')
(10, 0)
>>> _number_power('100')
(1, 1)
>>> _number_power('200')
(1, 1)
>>> _number_power('1000')
(1, 2)
>>> _number_power('1234')
(1, 2)
>>> _number_power('10000')
(10, 2)
>>> _number_power('100000')
(100, 2)
>>> _number_power('987654')
(100, 2)
>>> _number_power('1000000')
(1, 3)
>>> _number_power('10000000')
(10, 3)
>>> _number_power('100000000')
(100, 3)
>>> _number_power('1000000000')
(1, 4)
"""
s = str(n)
# Regardless of the number passed-in, we only want a leading '1' followed by a string of '0's.
bits = ['1']
for ch in s:
bits.append('0')
s = ''.join(bits[:-1])
n = int(s)
l = len(s)
if l > 3:
num, new_c = _number_power(s[:-3], c + 1)
return (num, new_c)
elif n == 100:
return (100 if c > 0 else 1, c + 1)
elif n == 10:
return (10, c + 1 if c > 0 else 0)
else:
return (1, c + 1 if c > 0 else 0) |
def get_index(node):
"""
returns a key value for a given node
node: a list of two integers representing current state of the jugs
"""
return pow(7, node[0]) * pow(5, node[1]) |
def sort_list_using_sort(lst):
"""
The sort() method sorts the list ascending by default.
While sorting via this method the actual content of the tuple is changed
"""
lst.sort(key=lambda x:x[1])
return lst |
def one_cycle_schedule(step, total_steps, warmup_steps=None, hold_max_steps=0, lr_start=1e-4, lr_max=1e-3):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
if warmup_steps is None:
warmup_steps = (total_steps - hold_max_steps) // 2
if step < warmup_steps:
lr = (lr_max - lr_start) / warmup_steps * step + lr_start
elif step < warmup_steps + hold_max_steps:
lr = lr_max
else:
current_percentage = step / total_steps
if current_percentage <= .9:
lr = lr_max * ((total_steps - step) / (total_steps - warmup_steps - hold_max_steps))
else:
lr = lr_max * ((total_steps - step) / (total_steps - warmup_steps - hold_max_steps) * 0.8)
return lr |
def join_range(r):
"""Converts (1, 2) -> "1:2"
"""
return ":".join(map(str, r)) if r else None |
def layer2namespace(layer):
"""
converts the name of a layer into the name of its namespace, e.g.
'mmax:token' --> 'mmax'
"""
return layer.split(':')[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.