content stringlengths 42 6.51k |
|---|
def truncate_float(f: float, n: int):
"""Truncates/pads a float f to n decimal places without rounding"""
s = "{}".format(f)
if "e" in s or "E" in s:
return "{0:.{1}f}".format(f, n)
i, p, d = s.partition(".")
return ".".join([i, (d + "0" * n)[:n]]) |
def checkBuried(Nmass1, Nmass2):
"""
returns True if an interaction is buried
"""
if (Nmass1 + Nmass2 <= 900) and (Nmass1 <= 400 or Nmass2 <= 400):
return False
else:
return True |
def get_target_name(label):
"""
Try to extract the target_name from a given PDS label.
Parameters
----------
label : Object
Any type of pds object that can be indexed
Returns
-------
target_name : str
The defined target_name from the label. If this is None a target name
could not be pulled from the label
"""
try:
target_name = label['TARGET_NAME']
except KeyError:
return None
return target_name |
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e.,
'?' present on the game board.
Returns True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', \
'4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', \
'423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', \
'423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
for row in board:
if row.find('?') != -1:
return False
else:
continue
return True |
def remove_rev_dep(stix_objects):
"""Remove any revoked or deprecated objects from queries made to the data source"""
# Note we use .get() because the property may not be present in the JSON data. The default is False
# if the property is not set.
return list(
filter(
lambda x: x.get('x_mitre_deprecated', False) is False and x.get('revoked', False) is False,
stix_objects
)
) |
def get_indented_block(prefix_lines):
"""Returns an integer.
The return value is the number of lines that belong to block begun
on the first line.
Parameters
----------
prefix_lines : list of basestring pairs
Each pair corresponds to a line of SHPAML source code. The
first element of each pair is indentation. The second is the
remaining part of the line, except for trailing newline.
"""
prefix, line = prefix_lines[0]
len_prefix = len(prefix)
# Find the first nonempty line with len(prefix) <= len(prefix)
i = 1
while i < len(prefix_lines):
new_prefix, line = prefix_lines[i]
if line and len(new_prefix) <= len_prefix:
break
i += 1
# Rewind to exclude empty lines
while i-1 > 0 and prefix_lines[i-1][1] == '':
i -= 1
return i |
def find_it(seq):
"""Return the int that is in seq odd amount of times."""
for num in seq:
if seq.count(num) % 2 != 0:
return num |
def humanise_bytes(bytes):
"""
Returns humanised tuple of a number, typically bytes.
For example, (1, 'MB') for 1'000'000 bytes.
"""
if bytes >= 1e12:
return (bytes/1e12, 'TB')
elif bytes >= 1e9:
return (bytes/1e9, 'GB')
elif bytes >= 1e6:
return (bytes/1e6, 'MB')
elif bytes >= 1e3:
return (bytes/1e3, 'KB')
elif bytes > 1:
return (bytes, 'bytes')
else:
return (bytes, 'byte') |
def isHTML (fileS):
"""If the last file ends with HTML"""
if fileS.endswith("htm") or fileS.endswith("html") :
return 1
return 0 |
def _prefix(tree, value):
"""Find the largest index with all leaves before it aggregating to
at most the specified value.
Details
-------
This does not work unless the binary tree aggregates using `sum` and
has exactly a power-of-two number of leaves.
"""
# XXX the binary tree search logic is buggy for capacities that are not
# power of two.
assert (len(tree) & (len(tree) - 1) == 0) # power of two or zero
j, size = 1, len(tree) // 2
while j < size:
# value is less than the sum of the left slice: search to the left
if tree[2*j] >= value:
j = 2 * j
# value exceeds the left sum: search to the right for the residual
else:
value -= tree[2*j]
j = 2 * j + 1
return j - size |
def _fullqualname_function_py3(obj):
"""Fully qualified name for 'function' objects in Python 3.
"""
if hasattr(obj, "__wrapped__"):
# Required for decorator.__version__ <= 4.0.0.
qualname = obj.__wrapped__.__qualname__
else:
qualname = obj.__qualname__
return obj.__module__ + '.' + qualname |
def insert_row(table_name, values):
"""Inserts a row in 'table_name' with values as 'values'"""
query = f'INSERT INTO {table_name} VALUES ('
no_attrs = len(values)
# Add values to query
for i in range(0, no_attrs - 1):
query += f'{values[i]}, '
# Add semicolon for last value
query += f'{values[no_attrs - 1]});'
return query |
def get_current_rid(config):
"""
returns current radio id
"""
firstuser_file = '/etc/first_rid'
first_user = config['general'].get('id', None)
if first_user:
with open(firstuser_file,"w") as fi:
fi.write(first_user)
else:
return "0000000"
return first_user |
def build_mapping(triples, entity_path, relation_path):
"""build mapping of entities and triples"""
entity2id = {}
relation2id = {}
for triple in triples:
head, rel, tail = triple[0], triple[1], triple[2]
if head not in entity2id.keys():
entity2id[head] = len(entity2id)
if tail not in entity2id.keys():
entity2id[tail] = len(entity2id)
if rel not in relation2id.keys():
relation2id[rel] = len(relation2id)
with open(entity_path, 'w') as f_e:
for entity, idx in entity2id.items():
f_e.write(entity + " " + str(idx))
f_e.write('\n')
with open(relation_path, 'w') as f_r:
for relation, idx in relation2id.items():
f_r.write(relation + " " + str(idx))
f_r.write('\n')
id2entity = {v:k for k,v in entity2id.items()}
id2relation = {v:k for k,v in relation2id.items()}
return entity2id, id2entity, relation2id, id2relation |
def _getOrientation(orig_channel, orient):
"""
Return a character representing the orientation of a channel.
Args:
orig_channel (string):
String representing the seed channel (e.g. 'HNZ'). The
final character is assumed to be the (uppercase) orientation.
orient (str or None):
Gives the orientation of the channel, overriding channel
codes that end in numbers. Must be one of 'h' (horizontal)
or 'v' (vertical), or None if the orientation has not been
explicitly specified in the "comp" element.
Returns:
Character representing the channel orientation. One of 'N',
'E', 'Z', 'H' (for horizontal), or 'U' (for unknown).
"""
if orig_channel == 'mmi' or orig_channel == 'DERIVED':
orientation = 'H' # mmi is arbitrarily horizontal
elif orig_channel[-1] in ('N', 'E', 'Z'):
orientation = orig_channel[-1]
elif orig_channel == "UNK": # Channel is "UNK"; assume horizontal
orientation = 'H'
elif orig_channel == 'H1' or orig_channel == 'H2':
orientation = 'H'
elif orig_channel[-1].isdigit():
if orient == 'h':
orientation = 'H'
elif orient == 'v':
orientation = 'Z'
else:
orientation = 'U'
else:
orientation = 'U' # this is unknown
return orientation |
def WLF(Temp, RefT, WLF_C1, WLF_C2):
"""
Calculate the Williams-Landel-Ferry (WLF) equation [1].
Parameters
----------
Temp : numeric
Evaluation temperature of the shift factor.
RefT : numeric
Reference temperature chosen to construct the master curve.
WLF_C1, WLF_C2 : numeric
Empirical constants. (Obtained from fitting the shift factor a_T)
Returns
-------
log_aT : numeric
The decadic logarithm of the WLF shift factor.
References
----------
[1] Williams, Malcolm L.; Landel, Robert F.; Ferry, John D. (1955).
"The Temperature Dependence of Relaxation Mechanisms in Amorphous Polymers
and Other Glass-forming Liquids". J. Amer. Chem. Soc. 77 (14): 3701-3707.
doi:10.1021/ja01619a008
"""
log_aT = -WLF_C1*(Temp - RefT)/(WLF_C2+(Temp - RefT))
return log_aT |
def pathify(basenames, examples_dir="examples/"): # pragma: no cover
"""*nix to python module path"""
example = examples_dir.replace("/", ".")
return [example + basename for basename in basenames] |
def remove_prefix(string, prefix):
"""Returns |string| without the leading substring |prefix|."""
# Match behavior of removeprefix from python3.9:
# https://www.python.org/dev/peps/pep-0616/
if string.startswith(prefix):
return string[len(prefix):]
return string |
def _calc_shortest_path(nodes_process, dist):
"""
Calculate shortest path
Args:
nodes_process: nodes that we met on path
dist: distances
Returns:
int: length shortest path
"""
shortest_path = 10 ** 16
for node in nodes_process[1] + nodes_process[0]:
if node in dist[0] and node in dist[1] and dist[0][node] + dist[1][node] < shortest_path:
shortest_path = dist[0][node] + dist[1][node]
return shortest_path |
def is_even(x):
""" True if obj is even. """
return (x % 2) == 0 |
def modifier_ve(score: int, attr: str) -> str: # pylint: disable=unused-argument
"""computes an attribute modifier with Vieja Escuela rules"""
result = ""
if score > 17:
result = "+2"
elif score > 14:
result = "+1"
elif score > 6:
result = ""
elif score > 3:
result = "-1"
elif score > 0:
result = "-2"
if result:
return f" ({result})"
return "" |
def get_provenance_record(ancestor_files):
"""Create a provenance record."""
record = {
'caption':
"Forcings for the PCR-GLOBWB hydrological model.",
'domains': ['global'],
'authors': [
'aerts_jerom',
'andela_bouwe',
'alidoost_sarah',
'kalverla_peter',
],
'projects': [
'ewatercycle',
],
'references': [
'acknow_project',
],
'ancestors': ancestor_files,
}
return record |
def poly (*args):
"""
f(x) = a*x + b * x**2 + c * x**3 + ...
*args = (x,a,b)
"""
if len(args) ==1:
raise Exception ("You have only entered a value for x, and no coefficents.")
x = args[0] # X value
coef = args[1:]
result = 0
for power, c in enumerate(coef):
result += c * (x ** power + 1)
return result |
def validate_sequences(seed_sequence, extracted_full_seq, rnac=True):
"""
Validates whether the SEED sequence matches the sequence
extracted at specific coordinates
seed_sequence: A DNA/RNA sequecne extracted from the SEED alignment
extracted_full: A DNA/RNA subsequence extracted at specific locations
return: True if the sequences match, False otherwise. Returns False by default
"""
new_seed_sequence = seed_sequence
if rnac is False:
new_seed_sequence = seed_sequence.replace('U', 'T')
if extracted_full_seq.find(new_seed_sequence) != -1:
return True
return False |
def can_contact_customer_support(botengine):
"""
Leverages the com.domain.YourBot/domain.py file or organization properties to determine if customer support is available for this bot
:return:
"""
import importlib
try:
properties = importlib.import_module('properties')
except ImportError:
return False
if properties.get_property(botengine, "CS_SCHEDULE_URL") is not None:
if len(properties.get_property(botengine, "CS_SCHEDULE_URL")) > 0:
return True
if properties.get_property(botengine, "CS_EMAIL_ADDRESS") is not None:
if len(properties.get_property(botengine, "CS_EMAIL_ADDRESS")) > 0:
return True
if properties.get_property(botengine, "CS_PHONE_NUMBER") is not None:
if len(properties.get_property(botengine, "CS_PHONE_NUMBER")) > 0:
return True |
def _make_col_qual_name(col_name, parent_table_name):
"""
Generate a standardized qualified name for column entities.
:param str col_name: The column name.
:param str parent_table_name: The parent table name.
:return: The qualified name for the column.
:rtype: str
"""
return f"{parent_table_name}#{col_name}" |
def _quote_identifier(identifier):
"""Quote identifiers"""
return "\"" + identifier + "\"" |
def has_variable(formula, variable):
"""
Function that detects if a formula contains an ID. It traverses the
recursive structure checking for the field "id" in the dictionaries.
:param formula: node element at the top of the formula
:param variable: ID to search for
:return: Boolean encoding if formula has id.
"""
if 'condition' in formula:
# Node is a condition, get the values of the sub clases and take a
# disjunction of the results.
return any([has_variable(x, variable) for x in formula['rules']])
return formula['id'] == variable |
def remove_duplicates(hashtags):
"""Removes duplicates from given hashtag list
Parameters:
hashtags (list): list of hashtags
Returns:
List of hashtags without duplicate entries
"""
result = list(dict.fromkeys(hashtags))
return result |
def derive_platform_name(input: str) -> str:
"""
derive platform info, needed to create schemaaspect
urn:li:dataset:(urn:li:dataPlatform:{platform},{name},{env})
"""
platform_name_env = input.replace("urn:li:dataset:(urn:li:dataPlatform:", "")
platform = platform_name_env.split(",")[0]
platform_name = f"urn:li:dataPlatform:{platform}"
return platform_name |
def cleanup_coords(coords):
"""
remove coordinates that are closer than 0.01 (1cm)
:param coords: list of (x, y) coordinates
:return: list of (x, y) coordinates
"""
result = []
last_coord = coords[-1]
for coord in coords:
if ((coord[0] - last_coord[0]) ** 2 + (coord[1] - last_coord[1]) ** 2) ** 0.5 >= 0.01:
result.append(coord)
last_coord = coord
return result |
def find_supports(combinations, supports, combination):
"""
find supports of combinations
Parameters
----------
combinations : list
combinations to find supports.
supports : list
support of combinations.
combination : list
combination to find support from combinations
Returns
-------
supports of combination.
"""
for i, comb in enumerate(combinations):
if set(comb) == set(combination):
return supports[i]
return 0 |
def determine_linestyle(boundary, boundary_list, kpp, swb, diffusion_type):
"""
Given the boundary and diffusion of a run we are plotting, specifying which linestyle to use
:return:
"""
if len(boundary_list) is 1:
if swb and kpp:
if diffusion_type is 'SWB':
return '-'
elif diffusion_type is 'KPP':
return '--'
elif swb:
return '-'
elif kpp:
return '--'
# For when we are trying to plot multiple boundary conditions in one plot
else:
line_style = {'Reflect': '-', 'Reflect_Markov': '--'}
return line_style[boundary] |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] |
def warmup_linear(x, warmup=0.002):
"""Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step.
After `t_total`-th training step, learning rate is zero."""
if x < warmup:
return x / warmup
return max((x - 1.0) / (warmup - 1.0), 0) |
def getID(string):
"""
get ICSD id from strings like "Al1H3O3_ICSD_26830"
"""
return string.split('_')[-1] |
def encode_with(string, encoding):
"""Encoding ``string`` with ``encoding`` if necessary.
:param str string: If string is a bytes object, it will not encode it.
Otherwise, this function will encode it with the provided encoding.
:param str encoding: The encoding with which to encode string.
:returns: encoded bytes object
"""
if not (string is None or isinstance(string, bytes)):
return string.encode(encoding)
return string |
def check_field(rule: tuple, field: int) -> bool:
"""check if a field is valid given a rule"""
for min_range, max_range in rule:
if min_range <= field <= max_range:
return True
return False |
def calculate_building_intersection_matrix(bn):
"""
:param bn: total number of buildings on both sides
:return: matrix of number of buildings between any two building
"""
int_mat = [[0 for col in range(bn)] for row in range(bn)]
bn_eachside = int(bn/2)
i = 0
while i < (bn_eachside - 1):
j = i + 2
bval = 1
while j < bn_eachside:
int_mat[i][j] = bval
bval += 1
j += 1
i += 1
for i in range(0, bn_eachside):
for j in range(0, bn_eachside):
if (i != j):
int_mat[j][i] = int_mat[i][j]
i = bn_eachside
while i < (bn - 1):
j = i + 2
bval = 1
while j < bn:
int_mat[i][j] = bval
bval += 1
j += 1
i += 1
for i in range(bn_eachside, bn):
for j in range(bn_eachside, bn):
if (i != j):
int_mat[j][i] = int_mat[i][j]
return int_mat |
def macaddr_unpack(data):
"""
Unpack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c
"""
# This is easy, just go for standard macaddr format,
# just like PGSQL in src/util/adt/mac.c macaddr_out()
if len(data) != 6:
raise ValueError('macaddr has incorrect length')
return ("%02x:%02x:%02x:%02x:%02x:%02x" % tuple(data)) |
def TabSpacer(number_spaces, string):
"""Configuration indentation utility function."""
blank_space = ' '
return (blank_space * number_spaces) + string |
def pretty_len_filterer(words, sol_length):
"""Filtering by length including underscore and space between words (in the case of multi word solutions)
before filtering by length of individual words seperate by underscore
Args:
words : list of words to filter
sol_length : lengthg os olution word t filter by
"""
keep = []
for word in words:
if len(word) == sol_length:
keep.append(word)
return keep |
def cosine_similarity(exp1, exp2):
""" calculate the cosine similarity of 2 experiments """
words1, vector1 = exp1
words2, vector2 = exp2
similarity = 0.0
for idx1, word in enumerate(words1):
# if a word is in both exp1 and exp2, similarity increased by tfidf1 * tfidf2
if word in words2:
idx2 = words2.index(word)
similarity += vector1[idx1] * vector2[idx2]
return similarity |
def get_size(volume_size: int):
""" Convert Mbs to Bytes"""
tmp = int(volume_size) * 1024 * 1024
return tmp |
def get_header(metrics):
""" Get header name from metrics dict. """
return f'{metrics["display_name"]} ({metrics["unit"]})' |
def copy_dict(source, destination):
"""
Populates a destination dictionary with the values from the source
:param source: source dict to read from
:param destination: destination dict to write to
:returns: destination
:rtype: dict
"""
for name, value in source.items():
destination[name] = value
return destination |
def UNKNOWN_BRANCH(project_id, branch_id):
"""Error message for requests that access project branches.
Parameters
----------
project_id: string
Unique project identifier.
branch_id: string
Unique branch identifier.
Returns
-------
string
"""
msg = "unknown branch '{}' or project '{}'"
return msg.format(branch_id, project_id) |
def bernoulli2ising(bernoulli: int) -> int:
"""
Transfers variable form Bernoulli random to Ising random; see
https://en.wikipedia.org/wiki/Bernoulli_distribution
https://en.wikipedia.org/wiki/Ising_model
:param bernoulli: int
:return:
"""
if bernoulli == 1:
return 1
elif bernoulli == 0:
return -1
else:
raise Exception(f'Unexpected value of Bernoulli distribution: {bernoulli}') |
def deep_merge_dict(dict_x, dict_y, path=None):
""" Recursively merges dict_y into dict_x.
Args:
dict_x: A dict.
dict_y: A dict.
path:
Returns: An updated dict of dict_x
"""
if path is None: path = []
for key in dict_y:
if key in dict_x:
if isinstance(dict_x[key], dict) and isinstance(dict_y[key], dict):
deep_merge_dict(dict_x[key], dict_y[key], path + [str(key)])
elif dict_x[key] == dict_y[key]:
pass # same leaf value
else:
dict_x[key] = dict_y[key]
else:
dict_x[key] = dict_y[key]
return dict_x |
def get_short_version(framework_version):
"""Return short version in the format of x.x
Args:
framework_version: The version string to be shortened.
Returns:
str: The short version string
"""
return ".".join(framework_version.split(".")[:2]) |
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s |
def cescape(string):
"""Escapes special characters needed for color codes.
Replaces the following symbols with their equivalent literal forms:
===== ======
``@`` ``@@``
``}`` ``}}``
===== ======
Parameters:
string (str): the string to escape
Returns:
(str): the string with color codes escaped
"""
string = str(string)
string = string.replace('@', '@@')
string = string.replace('}', '}}')
return string |
def format_msg(message):
"""
Used to format user messages.
Replaces newline characters with spaces, '\\n' with newlines, etc.
:type message: str
:rtype: str
"""
return (
message
.strip()
.replace('\\n\n', '\\n')
.replace('\n', ' ')
.replace('\\n', '\n')
) |
def format_duration(seconds):
"""
Format a duration into a human-readable string.
"""
mins, secs = divmod(seconds, 60)
fmt = '{:.0f}'
if mins:
return '{} minutes {} seconds'.format(fmt, fmt).format(mins, secs)
else:
return '{} seconds'.format(fmt).format(secs) |
def is_int(s):
"""Returns true if s represents an integer"""
try:
int(s)
return True
except ValueError:
return False |
def RPL_INVITING(sender, receipient, message):
""" Reply Code 341 """
return "<" + sender + ">: " + message |
def _round_to_multiple_of(val, divisor, round_up_bias=0.9):
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
bias, will round up, unless the number is no more than 10% greater than the
smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """
assert 0.0 < round_up_bias < 1.0
new_val = max(divisor, int(val + divisor / 2) // divisor * divisor)
return new_val if new_val >= round_up_bias * val else new_val + divisor |
def format_response(status_code, headers, body):
"""
Helper function: Generic response formatter
"""
response = {
'statusCode': status_code,
'headers': headers,
'body': body
}
return response |
def get_data_id(data) -> int:
"""Return the data_id to use for this layer.
Parameters
----------
data
Get the data_id for this data.
Notes
-----
We use data_id rather than just the layer_id, because if someone
changes the data out from under a layer, we do not want to use the
wrong chunks.
"""
if isinstance(data, list):
assert data # data should not be empty for image layers.
return id(data[0]) # Just use the ID from the 0'th layer.
return id(data) |
def process_activities(activities_str: str) -> list:
"""
Split activities as a pipe-separated string into a list of activities.
"""
activities_split = activities_str.split(" | ")
# Ignore row of no activities, which will be a single null string after
# splitting.
if len(activities_split) == 1 and activities_split[0] == "":
activities_list = []
else:
activities_list = [activity.strip() for activity in activities_split]
return activities_list |
def blend_color_burn(cb: float, cs: float) -> float:
"""Blend mode 'burn'."""
if cb == 1:
return 1
elif cs == 0:
return 0
else:
return 1 - min(1, (1 - cb) / cs) |
def declare(var_name, var_type):
"""Creates an SMTLIB declaration formatted string
Parameters
----------
var_name: string
The name of the variable
var_type:
The type of the variable (Int, Bool, etc.)
"""
return "(declare-fun " + var_name + " () " + var_type + ")\n" |
def quote_fname(fname):
"""quote file name or any string to avoid problems with file/directory names
that contain spaces or any other kind of nasty characters
"""
return '"%s"' % (
fname
.replace('\\', '\\\\')
.replace('"', '\"')
.replace('$', '\$')
.replace('`', '\`')
.replace('!', '\!')
) |
def cat_ranges_for_reorder(page_count, new_order):
"""
Returns a list of integers. Each number in the list
is correctly positioned (newly ordered) page.
Examples:
If in document with 4 pages first and second pages were
swapped, then returned list will be:
[2, 1, 3, 4]
If first page was swapped with last one (also 4 paegs document)
result list will look like:
[4, 2, 3, 1]
"""
results = []
# key = page_num
# value = page_order
page_map = {}
for item in new_order:
k = int(item['page_order'])
v = int(item['page_num'])
page_map[k] = v
for number in range(1, page_count + 1):
results.append(
page_map[number]
)
return results |
def format_iter(iterable, *, fmt='{!r}', sep=', '):
"""Format and join items in iterable with the given format string and separator"""
return sep.join(fmt.format(x) for x in iterable) |
def binary_search(x, arr, include_equal = False):
"""
Returns the index of the smallest element in an array which is larger
than a specified element. This assumes that the array is sorted in
non-decreasing order. If the element is larger than the largest element
in the array, then the length of the array is returned instead.
Arguments:
x (:int) - the element to be searched for
arr (:int list) - the array sorted in non-decreasing order
Returns:
the position of the largest element in 'arr' greater than 'x'
Examples:
>>> binary_search(2, [0, 2, 3])
>>> 2
>>> binary_search(-1, [0, 2, 3])
>>> 0
>>> binary_search(99, [0, 2, 3])
>>> 3
"""
if x > arr[-1]:
return len(arr)
elif x < arr[0]:
return 0
l, r = 0, len(arr) - 1
while l <= r:
m = (l + r) >> 1
if arr[m] == x:
return m + 1 if not include_equal else m
elif arr[m] < x:
l = m + 1
else:
r = m - 1
return l |
def ean_digit(arg):
"""Calculate UPCA/EAN13/NVE checksum for any given string consiting of an arbitary number of digits.
>>> ean_digit('400599871650')
'2'
>>> ean_digit('34005998000000027')
'5'
"""
factor = 3
summe = 0
for index in range(len(arg) - 1, -1, -1):
summe += int(arg[index]) * factor
factor = 4 - factor
return str((10 - (summe % 10)) % 10) |
def is_posix_path(my_path: str) -> bool:
"""Return whether or not a given path is Posix-based."""
return "/" in str(my_path) |
def _get_member_groups(get_member_group_func, identifier, security_enabled_only):
"""Call 'directoryObject: getMemberGroups' API with specified get_member_group_func.
https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups
"""
body = {
"securityEnabledOnly": security_enabled_only
}
return get_member_group_func(identifier, body) |
def _padded_hex(i, pad_width=4, uppercase=True):
"""
Helper function for taking an integer and returning a hex string. The string will be padded on the left with zeroes
until the string is of the specified width. For example:
_padded_hex(31, pad_width=4, uppercase=True) -> "001F"
:param i: integer to convert to a hex string
:param pad_width: (int specifying the minimum width of the output string. String will be padded on the left with '0'
as needed.
:param uppercase: Boolean indicating if we should use uppercase characters in the output string (default=True).
:return: Hex string representation of the input integer.
"""
result = hex(i)[2:] # Remove the leading "0x"
if uppercase:
result = result.upper()
return result.zfill(pad_width) |
def get_dict_modes(dict):
"""Finds the keys of the modes of a dictionary
@param dict: A dictionary of the form {"key":#}
"""
highest_count = dict[max(dict)]
modes = []
for key in dict:
if dict[key] == highest_count:
modes.append(key)
return modes |
def add_metadata(data):
"""
Decorates a set of data (as produced by `normalised_sheet`)
with metadata. At this time, this only wraps the results in
a `data` key
"""
# In the future this could add additional top-level fields like
# date-created, original data source, alerts, and so on.
return {
"data": data
} |
def average_difference(dictA, dictB):
"""Return the average difference of
values in dictA minus dictB, only
using values in dictA.
If a value is missing from dictB, raise Exception.
"""
total_diff = 0.0
for (k, va) in dictA.items():
vb = dictB[k]
total_diff += (va - vb)
return total_diff / len(dictA) |
def limit_string(string, limit):
"""
Cuts off a string on last word instead of max chars and adds ellipsis at the end
Args:
string (unicode)
limit (int)
"""
string = string.strip()
if len(string) > limit:
string = string[:limit - 3]
string = string.rsplit(' ', 1)[0] + '...'
return string |
def url_for(key):
"""Return URL for request type."""
return {
"query_user": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/user/v1",
"get_devices": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/sortdevices/v1/devices",
"get_device": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/device/v1/getdevice",
"device_data": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/devicedata/v1/getdata",
"refresh_device": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/devicestatus/v1/getstatus",
"turn_device": "https://vxhewp40e8.execute-api.us-east-1.amazonaws.com/beta/v1/action",
}.get(key) |
def _get_crc_7(message):
"""
Calculates and returns the integrity verification byte for the given message. Used only by the serial controller.
For more details, see section "Cyclic Redundancy Check (CRC) error detection" at https://www.pololu.com/docs/0J71/9
"""
crc = 0
for i in range(len(message)):
crc ^= message[i]
for j in range(8):
if crc & 1:
crc ^= 0x91
crc >>= 1
return crc.to_bytes(1, 'little') |
def delete_duplicated_node(head):
"""
:param head: head of ListNode
:return: head
"""
cur = head
pre = None
while cur:
pre = cur
cur = cur.next
while cur and cur.val == pre.val:
cur = cur.next
pre.next = cur
return head |
def digit_sum(num: int) -> int:
"""Calculate the sum of a number's digits."""
total = 0
while num:
total, num = total + num % 10, num // 10
return total |
def which(program):
"""works like unix which"""
# stolen from https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None |
def _a1inv(x):
"""Compute inverse function.
Inverse function of the ratio of the first and
zeroth order Bessel functions of the first kind.
Returns the value k, such that a1inv(x) = k, i.e. a1(k) = x.
"""
if 0 <= x < 0.53:
return 2 * x + x ** 3 + (5 * x ** 5) / 6
elif x < 0.85:
return -0.4 + 1.39 * x + 0.43 / (1 - x)
else:
return 1 / (x ** 3 - 4 * x ** 2 + 3 * x) |
def calculate_color( value ):
"""! @brief calculates color for given value """
r = 255-int( 255*value**4 )
g = 255-int( 255*value**4 )
b = 255
color = '#%02x%02x%02x' % (r, g, b)
return color |
def v1_add(matrix1, matrix2):
"""Add corresponding numbers in given 2-D matrices.
Using the zip function to iterate over the 2 matrices at the same time.
"""
combined = []
for rows in zip(matrix1, matrix2):
row = []
for items in zip(rows[0], rows[1]):
row.append(items[0] + items[1])
combined.append(row)
return combined |
def formatbytes(bytes: float):
"""
Return the given bytes as a human friendly KB, MB, GB, or TB string
"""
bytes_float = float(bytes)
KB = float(1024)
MB = float(KB**2) # 1,048,576
GB = float(KB**3) # 1,073,741,824
TB = float(KB**4) # 1,099,511,627,776
if bytes_float < KB:
return "{0} {1}".format(bytes_float, "Bytes" if bytes_float > 1 else "Byte")
elif KB <= bytes_float < MB:
return "{0:.2f} KB".format(bytes_float / KB)
elif MB <= bytes_float < GB:
return "{0:.2f} MB".format(bytes_float / MB)
elif GB <= bytes_float < TB:
return "{0:.2f} GB".format(bytes_float / GB)
elif TB <= bytes_float:
return "{0:.2f} TB".format(bytes_float / TB) |
def custom_user_authentication_rule(user):
"""
Override the default user authentication rule for Simple JWT Token to return true if there is a user and let
serializer check whether user is active or not to return an appropriate error
:param user: user to be authenticated
:return: True if user is not None
"""
return True if user is not None else False |
def frames_to_ms(num_frames: int) -> int:
"""at 60 fps, each frame would happen in 16.67 ms"""
return int(16.67 * num_frames) |
def sub(vector1, vector2):
"""
Subtracts a vector from a vector and returns the result as a new vector.
:param vector1: vector
:param vector2: vector
:return: vector
"""
new_vector = []
for index, item in enumerate(vector1):
new_vector.append(vector1[index] - vector2[index])
return new_vector |
def change_variation(change: float) -> float:
"""Helper to convert change variation
Parameters
----------
change: float
percentage change
Returns
-------
float:
converted value
"""
return (100 + change) / 100 |
def cleaner(element, accept, level=0, key_only=False):
"""
Clean a structure (list or dict based) based on cleanfunc()
:param element: element to clean
:param accept: function to call to determine acceptance
:param level: recursion level
:return: cleaned element
"""
if isinstance(element, dict):
# handle a dictionary
result = dict()
for k, v in element.items():
if accept(k) and (key_only or accept(v)):
# recurse to clean elements
res = cleaner(v, accept, level + 1, key_only=key_only)
# if none is returned, don't propogate
if res is not None:
result[k] = res
return result
if isinstance(element, (list, tuple, set)):
# handle a list
result = []
for item in element:
res = cleaner(item, accept, level + 1, key_only=key_only)
if res is not None:
result.append(res)
return set(result) if isinstance(element, set) else tuple(result) if isinstance(element, tuple) else result
return element if key_only or accept(element) else None |
def _left_child(node):
"""
Args:
node: index of a binary tree node
Returns:
index of node's left child
"""
return 2 * node + 1 |
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0:
return s
if len(s) == 1 and s[0] == " ":
return ""
# Brute force: Tokenize on space, add it to list
l = s.split()
r = " ".join(l[::-1])
return r |
def func_star(a_b, func):
"""Convert `f([1,2])` to `f(1,2)` call."""
return func(*a_b) |
def format_author_line(author_names):
"""authorLine format depends on if there is 1, 2 or more than 2 authors"""
author_line = None
if not author_names:
return author_line
if len(author_names) <= 2:
author_line = ", ".join(author_names)
elif len(author_names) > 2:
author_line = author_names[0] + " et al."
return author_line |
def create_keypoint(n,*args):
"""
Parameters:
-----------
n : int
Keypoint number
*args: tuple, int, float
*args must be a tuple of (x,y,z) coordinates or x, y and z
coordinates as arguments.
::
# Example
kp1 = 1
kp2 = 2
create_keypoint(kp1,(0,0,0)) # x,y,z as tuple
create_keypoint(kp2,1,1,1) # x,y,z as arguments
"""
if len(args)==1 and isinstance(args[0],tuple):
x,y,z = args[0][0],args[0][1],args[0][2]
else:
x,y,z = args[0], args[1], args[2]
_kp = "K,%g,%g,%g,%g"%(n,x,y,z)
return _kp |
def get_shared_values(param_list):
"""
For the given list of parameter dictionaries, make a dictionary of the
keys and values that are the same for every set in the list
>>> get_shared_values([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}])
{'a': 0}
>>> get_shared_values([{'a':0, 'd':3}, {'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':2}])
{'a': 0}
>>> get_shared_values([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'1'}])
{'a': 0}
>>> s = get_shared_values([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'c': 3, 'a':0, 'b':1}])
>>> len(s)
2
"""
if not param_list:
return
keys = [p.keys() for p in param_list]
shared_keys = set(keys[0]).intersection(*keys)
shared = {k: param_list[0][k] for k in shared_keys}
for p in param_list:
for k in p:
if k in shared and shared[k] != p[k]:
shared.pop(k)
return shared |
def choices_from_list(source, prepend_blank=True):
"""
Convert a list to a format that's compatible with WTForm's choices.
It also optionally prepends a "Please select one..." value.
Example:
# Convert this data structure:
TIMEZONES = (
'Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa'
)
# Into this:
choices = [('', 'Please select one...'),
('Africa/Abidjan', 'Africa/Abidjan) ...]
:param source: Input source
:type source: list or tuple
:param prepend_blank: An optional blank item
:type prepend_blank: bool
:return: list
"""
choices = []
if prepend_blank:
choices.append(("", "Please select one..."))
for item in source:
pair = (item, item)
choices.append(pair)
return choices |
def make_full_request_type(
service_name: str,
request_type: str,
) -> str:
"""Return the full GRPC request type by combining service name and request type
Args:
service_name (str): ex: magma.lte.LocalSessionManager
request_type (str): ex: CreateSession
Returns:
str: full request type
"""
return '%s/%s' % (service_name, request_type) |
def flatten(sequence):
"""Given a sequence possibly containing nested lists or tuples,
flatten the sequence to a single non-nested list of primitives.
>>> flatten((('META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')))
['META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME', 'META.OBSERVATION.DATE', 'META.OBSERVATION.TIME']
"""
flattened = []
for elem in sequence:
if isinstance(elem, (list, tuple)):
elem = flatten(elem)
else:
elem = [elem]
flattened.extend(elem)
return flattened |
def bigger_max(nums1: set, nums2: set) -> set:
"""Return the set that has the larger maximum.
Return nums1 if there is a tie.
This assumes that both sets are non-empty, and that they only contain integers.
NOTE: Use the builtin function isinstance to check whether a value has a certain
type. For example, isinstance(3, int) is True, and isinstance('hi', int) is False.
Preconditions:
- len(nums1) > 0
- len(nums2) > 0
- all([isinstance(val, int) for val in nums1])
- all([isinstance(val, int) for val in nums2])
>>> bigger_max({1, 2, 3}, {4})
{4}
>>> bigger_max({1, 2, 3}, {1, 3})
{1, 2, 3}
>>> bigger_max({1, 3}, {1, 2, 3})
{1, 3}
"""
max1 = max(nums1)
max2 = max(nums2)
big_max = max(max1, max2)
# This always puts overrides max2 with max1 when they have the same max
return {max2: nums2, max1: nums1}[big_max] |
def get_by_path(d, path):
"""Access an element of the dict d using the (possibly dotted) path.
For example, 'foo.bar.baz' would return d['foo']['bar']['baz'].
Args:
d (dict):
(nested) dictionary
path (str):
path to access the dictionary
Returns:
the value corresponding to d[p1][p2]...
Raises:
KeyError:
if any key along the path was not found.
"""
current_node = d
for p in path.split('.'):
try:
current_node = current_node[p]
except KeyError:
raise KeyError(
'Path "{}" could not be resolved. Key "{}" missing. Available '
'keys are: [{}]'.format(
path, p, ", ".join(sorted(current_node.keys()))))
return current_node |
def get_command_name(command):
"""
Only alpha/number/-/_/+ will be kept. Spaces will be replaced to ".".
Others will be replaced to "+".
"""
name = ""
for char in command:
if char.isalnum() or char == "-" or char == "_":
name += char
elif char == " ":
name += "."
else:
name += "+"
return name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.