content stringlengths 42 6.51k |
|---|
def pad_line(line, target_length, padding_char=' '):
"""
Pad a line to the desired length
:param line: The line to pad
:param target_length: The target length
:param padding_char: The padding char, defaults to space
:return: The padded string
"""
line = str(line)
extra = target_lengt... |
def is_valid_phone(phone):
""" function evaluates phone number, returns boolean"""
if len(phone) == 10:
return True
else:
return False |
def join_and_sort(*argv):
""" Takes variable number of traces and joins them to one sorted and keyed list."""
joined_trace = list()
for trace in argv:
joined_trace += trace
joined_trace.sort(key=lambda tup: tup[0])
return joined_trace |
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams
Args:
str1(string),str2(string): Strings to be checked if they are anagrams
Returns:
bool: If strings are anagrams or not
"""
# Clean strings and convert to lower case
str1 = str1.replace(" ", "").lo... |
def dict_pop(d, key):
"""
Template filter that looks removes a key-value pair from a dict.
"""
return d.pop(key) |
def index_next_crossing(value, array, starting_index=0, direction=1):
"""
starts at starting_index, and walks through the array until
it finds a crossing point with value
set direction=-1 for down crossing
"""
for n in range(starting_index, len(array)-1):
if (value-array[n] ... |
def isiterable(obj):
"""
Test if the argument is an iterable.
:param obj: Object
:type obj: any
:rtype: boolean
"""
try:
iter(obj)
except TypeError:
return False
return True |
def find_symbol_in_grammer__symmetry_approach(n, k) -> int:
"""
This is the approach discussed in the video, Aditya Verma
"""
if n == 1 and k == 1:
return 0
mid = (2 ** (n - 1)) // 2
if k <= mid:
return find_symbol_in_grammer__symmetry_approach(n - 1, k)
else:
tmp ... |
def clean_netname(netname):
"""
Convert a whois netname into an organization name
"""
# from cdn import cdn_list
ORGS = [
('GOOGLE', ['google']),
('AKAMAI', ['akamai', 'umass']),
('AMAZON', ['at-', 'amazo']),
# ('CLOUDFRONT', []),
('FASTLY', ['fastly']),
... |
def countTriplets(arr, r):
"""
Args:
arr (list): list of integers
r (int): geometric progression multiplier
Returns:
int: substring anagrams count"""
count = 0
numbers_dict = {}
pairs_dict = {}
# count numbers in a loop
# count corresponding pairs in a loop
... |
def slow_fibonacci(n):
"""
This function calculates the fibonacci sequence up to the n'th
member.
"""
x = 0
y = 1
if n == 1:
return 1
for i in range(n):
_tmp = x # the current `x' is stored in a tmp variable
x = y # `x' becomes the previous `y'
y = _tmp ... |
def searchMatrix(matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# our solution will be of logm + logn time complexity
rows, cols = len(matrix), len(matrix[0])
# top row and the bottom row
top, bot = 0, rows - 1
while top <= bo... |
def seconds_from(t, t_reference, unit_conversion=int(1e9)):
"""
Helper function which concerts times into relative times in
specified unit.
:param t: Time
:param t_reference: Reference time e.g. start of an event or first
peak in event.
:param unit_conversion: Conversion factor for time... |
def for_each_in(cls, f, struct):
""" Recursively traversing all lists and tuples in struct, apply f to each
element that is an instance of cls. Returns structure with f applied. """
if isinstance(struct, list):
return map(lambda x: for_each_in(cls, f, x), struct)
elif isinstance(struct, tupl... |
def list_of_dicts_to_dict_of_lists(ld):
""" list of dictionaries to dictionary of lists when all keys are the same.
source: https://stackoverflow.com/a/23551944/99379
"""
return {key: [item[key] for item in ld] for key in ld[0].keys()} |
def xeq(x0, x1, places=15):
"""
Returns true iff `x0` and `x1` are within decimal `places` of each other.
"""
scale = max(abs(x0), abs(x1))
epsilon = scale * 10 ** -places
return abs(x0 - x1) < epsilon |
def parseKey(keyVal):
"""readable keyVal"""
if type(keyVal) is list:
return "[{}]".format("".join(["{}.".format(i) for i in keyVal]))
else:
return str(keyVal) |
def in_bbox(p, bbox):
"""Test, whether point p (lng,lat) is in bbox (minlng, minlat, maxlng, maxlat)
Parameters:
p: Tuple[float, float] 2D point (lng, lat) (WGS84) Longitude (-180, 180) Latitude (-90, 90)
bbox: Tuple[float, float, float, float] Bounding box, (minlng, minlat, maxlng, maxlat)
... |
def convert_25d_3d(path):
"""
Convert plan in 2.5D to 3D grid map
"""
path_3d = [path[0]]
previous = path[0]
for i in range(1, len(path)):
current = path[i]
if previous[2] > current[2]:
path_3d.append((current[0], current[1], previous[2]))
elif previous[2] < c... |
def logs_dirname(src_version, dest_version):
"""Name of the directory to put log files into."""
return "kabi-diff-{}_{}".format(src_version, dest_version) |
def _sequence_to_latex(seq, style='ket'):
"""
For a sequence of particle states generate LaTeX code.
Parameters
----------
seq : list of ints
List of coordinates for each particle.
style : 'ket' (default), 'bra' or 'bare'
Style of LaTeX (i.e. |01> or <01| or 01, respectively).
... |
def apply_normalization_schedule(perc, layer_idx):
"""Transform percentile according to some rule, depending on layer index.
Parameters
----------
perc: float
Original percentile.
layer_idx: int
Layer index, used to decrease the scale factor in higher layers, to
maintain h... |
def get_experiment_label_long(path):
"""Extracts long experiment name from file path"""
label = path.split("/")
label = ".".join([*label[1:4], label[5]])
label = label.replace(".metrics", "")
label = label.replace(".main", "")
return label |
def date_tuple(ovls):
"""
We should have a list of overlays from which to extract day month
year.
"""
day = month = year = 0
for o in ovls:
if 'day' in o.props:
day = o.value
if 'month' in o.props:
month = o.value
if 'year' in o.props:
... |
def _parse_float(value, default=0):
"""
Attempt to cast *value* into a float, returning *default* if it fails.
"""
if value is None:
return default
try:
return float(value)
except ValueError:
return default |
def train_model(model, X_train, y_train, epochsPerTrial, nRounds, batchSize,
saveResults=True,
saveFileName=''):
"""
Function to train the NBGNet model.
Args:
model: model to be trained
X_train: Dictionary, where single-trial input data is stored in co... |
def hispanic_recode(cenhisp: str):
"""
Calculate the valid hispanic variable value from a row and the variable names for cenhisp
:param row: A Row object containing the cenhisp variable
:param hispanic_varname_list:
:return:
"""
assert cenhisp in [
"1",
"2",
], f"CEF CEN... |
def evaluate_model_tokens(labels, predicted):
"""
Function that extracts stats on token-basis
Input: array of true labels, array of predicted labels
Output: stats for the two given arrays
"""
stats = {'FP': 0, 'TP': 0, 'FN': 0}
for idx, label in enumerate(labels):
if label == 1 ... |
def aColor(codeString):
"""returns ANSI encoded string for a given set of ; separated format codes"""
# define ANSI codes
ansiCodeMask = '\033[{0}m'
ansiColorCodes = {
'OFF': 0,
'BOLD': 1,
'ITALIC': 3,
'UNDERLINE': 4,
'BLINK': 5,
'BLACK': 30,
'RED... |
def is_a_number(number):
"""This function returns whether a string contains a number
This function uses a try-except statement to check whether a
string is numeric. It does so by trying to take the float of
a string and returning True if it is successful and False if
unsuccessful.
Args:
... |
def check_box(box,img_wh):
""" Test whether a box is within image size.
Parameters
----------
box : list
A list of [x,y,width,height] where x,y in the top-left
point coordinates
Returns
-------
bool
A boolean indicating whether the box inside the image
di... |
def build_terminal(tok):
"""Builds a terminal statement for xml output"""
terminal = "<" + tok["type"] + ">" + " " + \
str(tok["value"]) + " " + "</" + tok["type"] + ">\n"
return terminal |
def add_tag(py_dict, tag_dict):
"""
Helper function to add tags to the NSX object body.
@param py_dict: the NSX object body as dict format
@param tag_dict: tags to add. dict format.
e.g. {"ncp/cluster": "k8scluster"}
"""
# Check exsiting tags
existing_tags = []
if "t... |
def get_precision(mx):
"""Gets precision or positive predictive value (PPV)"""
[tp, fp], [fn, tn] = mx
return tp / (tp + fp) |
def get_tuple_in_list(list_of_tuples, key):
"""
returns the first tuple (key, value) for a given key in a list
"""
for k, v in list_of_tuples:
if k == key:
return k, v
return None |
def one_hot(elements, classes):
"""
This function transform a list of labels in a matrix where each line is a one-hot encoding of
the corresponding label in the list. If the labels are not in classes, the corresponding vector has all the
values set to 0.
:param elements: list of labels to transform ... |
def find_external_nodes(digraph):
"""Return a set of external nodes in a directed graph.
External nodes are node that are referenced as a dependency not defined as
a key in the graph dictionary.
"""
external_nodes = set()
for ni in digraph:
for nj in digraph[ni]:
if nj not i... |
def get_names(st_count):
"""Getting names of students"""
return [input('Student #{} name > '.format(i + 1))
for i in range(st_count)] |
def getPositionMapper(direction):
"""
Based on the depth direction the indices of the world position are ordered
to match the users input.
:param str direction: Acceptable arguments are 'x', 'y' and 'z'
:return: List of indices
:rtype: list
"""
# variables
order = []
# build or... |
def _labelled(obj):
"""
Returns labelled element of the object (extractor or labelled region)
"""
if hasattr(obj, "annotation"):
return obj.annotation
return obj |
def DictCopyWithoutCodebase(template_dict):
"""Returns a copy of template_dict w/o the 'codebase' key.
Args:
template_dict: The dict to clone.
Returns:
The cloned dict, w/o a 'codebase' key.
"""
result = dict(template_dict)
if 'codebase' in result:
result.pop('codebase')
return result |
def _get_warmup_factor_at_iter(
method: str, iter: int, warmup_iters: int, warmup_factor: float
) -> float:
"""
Return the learning rate warmup factor at a specific iteration.
See :paper:`ImageNet in 1h` for more details.
Args:
method (str): warmup method; either "constant" or "linear".
... |
def fit(x, a, p, b):
"""
Define the fitting curve.
"""
return a * (p ** x) + b |
def to_int(value):
"""
Converting any value to int.
Returns empty string on any error.
"""
try:
return int(value)
except (ValueError, TypeError):
return '' |
def scl_gt_map(x_elem):
"""Maps one element from SCL to the given class on SCL ranged from 1 to 4
Parameters:
x_elem (int): class value from the classification
Returns:
int: class number in the SCL format
"""
if x_elem == 3:
return 2
if x_elem == 4:
return 3
i... |
def centered_rectangle(width, height):
"""
creates a rectangle tuple with a centered rectangle for use with sim.Animate
Parameters
----------
width : float
width of the rectangle
height : float
height of the rectangle
"""
return -width / 2, -height / 2, width / 2, heigh... |
def intersection_n (l1, * ls) :
"""Compute intersection of `l1` and all elements of `ls`."""
result = set (l1)
for l in ls :
result.intersection_update (l)
return result |
def exists(path, **kwargs):
"""Check if file or directory exists"""
import os.path
return os.path.exists(path, **kwargs) |
def get_digit_num_helper(num, count):
"""
return the number of zeros for x-digit number
e.g. three-digit number --> 10**2, four-digit number --> 10**3
:param num:
:param count:
:return:
"""
if num == 0:
return count-1
return get_digit_num_helper(num//10, count+1) |
def _round(value):
""" round redefinition for using the same format consistently. """
return round(value, 1) |
def _intersect(rect1, rect2):
"""
Check whether two rectangles intersect.
:param rect1, rect2: a rectangle represented with a turple(x,y,w,h,approxPoly_corner_count)
:return whether the two rectangles intersect
"""
# check x
x_intersect = False
if rect1[0] <= rect2[0] and rect2[0] - rect... |
def pic24_compact(data):
"""
Compacts an 8-byte raw data block into a 6-byte PIC24 compact frame
:param data: raw data
:return: compact data
"""
while len(data) % 8:
data.append(0)
output = []
for i in range(0, len(data), 8):
output.append(data[i])
output.append(... |
def indpm(x, y):
"""Plus-minus indicator function"""
return 1 if x == y else -1 |
def numDecodings(s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# DP Solution
dp = [0]*(len(s)+1)
dp[0] = 1
dp[1] = 0 if s[0] == "0" else 1
for i in range(2, len(s) + 1):
if 0 < int(s[i-1:i]) <= 9:
dp[i] += dp[i - 1]
... |
def frange(start, end, n):
"""frange(start, end, n): Python's range(), for floats and complexes."""
# If the arguments are already float or complex, this won't hurt.
# If they're int, they will become float.
start *= 1.0
end *= 1.0
step = (end - start) / n
list = []
current = start
for k in range(0, n):
... |
def get_field(data, key):
"""
Get a field separated by dots
"""
if isinstance(key, str):
key = key.split('.')
else:
print(type(key))
while key:
data = data[key.pop(0)]
return data |
def floater(item):
"""
Attempts to convert any item given to a float. Returns item if it fails.
"""
try:
return float(item)
except ValueError:
return item |
def isvector(t):
"""Returns true if the 4D tuple is a vector (w = 0.0)."""
return t[3] < 1.0 |
def add_entity_product_name(package_leaflets):
"""
Make leaflet's product_name to be the first entity in entity_recognition for every section_content
:param package_leaflets: list, collection of package leaflets
:return: package_leaflets with update entity_recognition for each section
"""
for ... |
def every(predicate, iterable):
"""
>>> every(lambda x: x > 1, [2, 0, 3])
False
>>> every(lambda x: x >= 0, [2, 0, 3])
True
"""
return all(map(predicate, iterable)) |
def _add_solr_language_info(res, obj):
"""
:param res: Solr document, i.e. a dict to which new keys will be added.
:param obj: object which is searched for language information.
:return: mutated dict res
"""
if getattr(obj, 'language', None):
res['language_t'] = obj.language.name
... |
def get_error(e, path=''):
""" Recursively dereferences `path` (a period-separated sequence of dict
keys) in `e` (an error dict or value), returns the final resolution IIF it's
an str, otherwise returns None
"""
for k in (path.split('.') if path else []):
if not isinstance(e, dict):
... |
def is_alignment_consistent(start, end, token_to_node, node_to_token):
"""
Check whether alignment between token span start:end and corresponding DMRS nodes is consistent.
:param start: Start token index
:param end: End token index
:param token_to_node: Token to node alignment dictionary
:param ... |
def check_if_descriptive(elect_date):
"""Check for the format of the index.
Args:
elect_date (str): election year and month. e.g., '199811'
Returns:
bool: indicates whether the index is in a descriptive format (True) or not (False).
Note:
True when index is like this:
PCT 110... |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_uniquen... |
def rebuilding(lst):
"""
This function rebuilds columns into new row
>>> rebuilding(['**12*', '12345', '23456', '**23*'])
[['*', '1', '2', '*'], ['*', '2', '3', '*'], ['1', '3', '4', '2'], ['2', '4', '5', '3'], ['*', '5', '6', '*']]
"""
prom_res = []
for i in lst:
prom_res.append(lis... |
def _get(d, *paths):
""" Query into configuration dictionary, return None on any error
usag:
_get(d, 'k1.2.k3.k4', 2, 'name')
"""
if d is None:
return None
if paths is None:
return None
for path in paths:
if path is None:
return None
path = path.split('.')
for key in path:
... |
def sort_dict_by_key(dict1: dict, reverse=False):
"""For a given dictionary, returns a sorted list of tuples for each item based on the value.
Examples:
>>> employees = {'Alice' : 100000,
... 'Bob' : 99817,
... 'Carol' : 122908,
... 'Frank'... |
def saffir_simpson(spd):
"""Static method that returns the equivalent saffir-simpson scale rating,
based on wind-speed in knots.
This is the most-common index used to generalize tropical cyclone
intensity.
Example: saffir_simpson(100) --> 3 (implying category 3).
"""
if 34 <= spd <= 63: ... |
def compare_measurements(spanner, alchemy):
"""
Compare the original Spanner client performance measures
with Spanner dialect for SQLAlchemy ones.
"""
comparison = {}
for key in spanner.keys():
comparison[key] = {
"Spanner, sec": spanner[key],
"SQLAlchemy, sec": a... |
def _balanced_tree_indexer(num_leaves, num_branches):
"""Makes num_branches buckets and fills the buckets as evenly as possible
with num_leaves
leaves then returns a set of start and end indices for slicing the list
of leaves. """
floor = num_leaves // num_branches
widths = [floor] * num_branche... |
def color_percent(p):
"""Return the adapted color for `p` percent achievement. `0`
percent will be dark red, `100` percent will be dark gren. A
linear interpolation is returned beetween these extrema but a
coefficient increases the luminosity around the midle `50`.
TESTS:
>>> color_percent(0)... |
def is_numeric(s):
"""Source: https://stackoverflow.com/q/354038."""
try:
float(s)
return True
except ValueError:
return False |
def is_number(number, *, dtype=float):
"""Check if argument can be interpreated as number.
Parameters
----------
number : string, float, int
Variable to be check if it can be casted to float.
dtype : dtype, optional
Check for different dtypes, so if is float or if it is int.
R... |
def pos_check(curr_x, curr_y, targ_x, targ_y, base_dir):
"""
:param curr_x: the current x-coordinate of the camera
:param curr_y: the current y-coordinate of the camera
:param targ_x: the target x-coordinate
:param targ_y: the target y-coordinate
:param base_dir: the direction from the previous ... |
def format_title(host: str) -> str:
"""Format the title for config entries."""
return "Controller ({})".format(host) |
def flatten(in_list):
"""Flatten list.
>>> flatten([])
[]
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten(([[1], [2, 3]]))
[1, 2, 3]
>>> flatten([1, [[2], 3]])
[1, 2, 3]
"""
def flatten_generator(in_list_inner):
for item in in_list_inner:
try:
... |
def is_absorbed_checker(list):
"""
Checks if list is absorbing
"""
for i in range(len(list)):
if list[i] != list[i - 1] and list[i] != list[(i + 1) % len(list)]:
return False
return True |
def override_from(cfg, recipient, namespace="walt"):
"""override_from iterates over `cfg` and looks for respective keys in
`recipient`. If a key exists, it's value is overridden on `cfg`"""
for key, value in cfg.items():
if key.endswith("_list") or key.endswith("_map"):
continue
... |
def get_class_name(type_):
"""
Get just the class name (w/o module(s) from the type.
Args:
type_ (type): Class as a type.
Returns:
(str|None): Just the name of the class or None.
"""
try:
return str(type_).rsplit('.', 1)[1].rstrip("'>")
except IndexError:
re... |
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
n = 1
total = 0
while total <= k:
# print(total, n)
if total == k:
return True
total += n
n += 1
return False |
def f_string_3(value):
"""Round value with 3 decimals."""
return f'{value:.3f}' |
def normalize_urls(zone_name, files):
"""Return a function that builds absolute URLs."""
def normalize_url(url):
"""Prepend the zone name if the url is not absolute."""
# print(url)
if not url.startswith('http://') and not url.startswith('https://'):
return 'https://{}/{}'.fo... |
def load_properties(file_path):
"""
Read properties file into map.
"""
props = {}
with open(file_path, "rt") as f:
for line in f:
line = line.strip()
if not line.startswith("#"):
pair = line.split("=", 1)
if len(pair) > 1:
... |
def map_aemo_facility_status(facility_status: str) -> str:
"""
Maps an AEMO facility status to an Opennem facility status
"""
unit_status = facility_status.lower().strip()
if unit_status.startswith("in service"):
return "operating"
if unit_status.startswith("in commissioning"):
... |
def unwrap_method(method):
"""Return the function object for the given method object."""
try:
# Python 2
return method.im_func
except AttributeError:
try:
# Python 3
return method.__func__
except AttributeError:
# Not a method.
... |
def get_signal_by_name(module, name):
"""Return the signal struct with the type input/output/inout
"""
result = None
for s in module["available_input_list"] + module[
"available_output_list"] + module["available_inout_list"]:
if s["name"] == name:
result = s
b... |
def convert_contract(contract):
"""
Map a contract from the DB format to what we want to send back
"""
return {
"_id": contract["_id"],
"title": contract["temp_type"],
"body": contract["template"],
} |
def polynom_prmzt(x, t, order):
"""
Polynomial (deterministic) parameterization of fast variables (Y).
NB: Only valid for system settings of Wilks'2005.
Note: In order to observe an improvement in DA performance w
higher orders, the EnKF must be reasonably tuned with
There is very ... |
def dict_failed_keys(table):
"""Returns all failed keys of the dict match comparison result table."""
failed = []
for _, key, result, _, _ in table:
if key and result == 'Failed':
failed.append(key)
return tuple(sorted(failed)) |
def islistoflists(arg):
"""Return True if item is a list of lists.
"""
claim = False
if isinstance(arg, list):
if isinstance(arg[0], list):
claim = True
return claim |
def bytes_to_hex_str(bytes_hex: bytes, prefix="") -> str:
"""Convert bytes to hex string."""
return prefix + bytes_hex.hex() |
def as_dict(x):
"""
Coerce argument to dictionary.
"""
if x is None:
return {}
elif isinstance(x, dict):
return x
else:
return dict(x) |
def mean(x):
"""Finds mean value of data set x"""
return sum(x) / len(x) |
def normalise_bytes(buffer_object):
"""Cast the input into array of bytes."""
return memoryview(buffer_object).cast("B") |
def clip(x, lower, upper):
"""Clip ``x`` to [``lower``, ``upper``]."""
return min(max(x, lower), upper) |
def split_lstring(buf):
"""split a list of length-prefixed strings into python not-length-prefixed bytes"""
result = []
mv = memoryview(buf)
while mv:
length = mv[0]
result.append(bytes(mv[1:1 + length]))
mv = mv[1 + length:]
return result |
def ravelIndex(pos, shape):
"""
ravelIndex()
"""
res = 0
acc = 1
for pi, si in zip(reversed(pos), reversed(shape)):
res += pi * acc
acc *= si
return res |
def _compare_match_length(item1, item2):
"""Compare two matches from the Pattern Matcher by the last matching index.
:param item1: first matches item
:param item2: second matches item
:return: comparison result where -1 means item1 < item2, 1 means item1 >
item2 and 0 means item1 == item2
"""
... |
def format_as_index(container, indices):
"""
Construct a single string containing indexing operations for the indices.
For example for a container ``bar``, [1, 2, "foo"] -> bar[1][2]["foo"]
Arguments:
container (str):
A word to use for the thing being indexed
indices (se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.