content stringlengths 42 6.51k |
|---|
def say_again(s, exclaim):
"""
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s # can also use "s * 3" which is faster (Why?)
if exclaim:
result = result + '!!!'
return result |
def sort_by_tc(events):
"""Sorts events by their rec_start_tc."""
events.sort(key=lambda e: (e.rec_start_tc.frames, e.track))
return events |
def inOrderTestTreeNode(root):
"""
"""
lst = []
if root is None:
return lst
if root.left is not None:
lst.extend(inOrderTestTreeNode(root.left))
lst.append(root.data)
if root.right is not None:
lst.extend(inOrderTestTreeNode(root.right))
return lst |
def _comment(string: str) -> str:
"""Return string as a comment."""
lines = [line.strip() for line in string.splitlines()]
sep = "\n"
return "# " + f"{sep}# ".join(lines) |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
max_sum = 0
current... |
def splitAndTrim(string, delimiter):
""" split the string and remove all empty parts """
parts = string.split(delimiter)
results = []
for item in parts:
if len(item) == 0:
continue
results.append(item)
return results |
def to_xml_name(name):
"""Convert field name to tag-like name as used in QuickBase XML.
>>> to_xml_name('This is a Field')
'this_is_a_field'
>>> to_xml_name('800 Number')
'_800_number'
>>> to_xml_name('A & B')
'a___b'
>>> to_xml_name('# of Whatevers')
'___of_whatevers'
"""
... |
def unique_days_of_one_stream(input_dict: dict) -> set:
"""
This function takes a dictionary of stream ids with dates of each stream
and makes a unique set of dates for all the stream ids
:param dict input_dict: a dictionary of stream ids as keys with dates as values
:return: a set of dates for all... |
def make_unscored_output_diac(x_entropies, y_entropies, test_set, vocab_map1, vocab_map2):
"""
Append test items and their entropy values in two vector spaces.
:param x_entropies: dictionary, mapping targets to entropy values
:param y_entropies: dictionary, mapping targets to entropy values
:pa... |
def count_bags_dfs(graph, start):
"""DFS. `queue` contains (node, multiplier) tuples."""
total_bags = 0
queue = [(start, 1)]
while len(queue):
at, multiplier = queue.pop()
total_bags += multiplier
for next in graph[at].keys():
queue.append((next, multiplier * graph[at... |
def get_device_hostnames(device_response):
"""Return a dictionary that maps device mac addresses to hostnames."""
return dict(
zip(
[value["mac"] for value in device_response["data"]],
[value["hostname"] for value in device_response["data"]],
)
) |
def dfs_imp_list(g, s):
"""
Imperative Depth First Search for adjacency list
:param g: the graph to visit. It is assumed the list only contains int data type.
:type g: list(list(int))
:param s: the vertex to start from.
:type s: int
:return: list of visited vertices
"""
... |
def indent(t, indent=0, sep='\n'):
# type: (str, int, str) -> str
"""Indent text."""
return sep.join(' ' * indent + p for p in t.split(sep)) |
def fcn_VR_FMS(r_div_R):
""" Transversal velocity factor of FMS in Eq. (31) in [2]
"""
return (1/4.)*(3.*r_div_R - r_div_R**3.0 + 2.0) |
def unreliable_test(test_fr, unacceptable_fr, test_runs, min_run):
"""Check for an unreliable test.
A test should be added to the set of tests believed not to run reliably when it has more
than min_run executions with a failure percentage greater than unacceptable_fr.
"""
return test_runs >= min_ru... |
def keywords2tag(tag) :
"""
remove the last number in tag
e.g. "span1" to "span"
"""
i = 0
for x in tag[::-1] : # reversed checking
if x.isdigit():
i += 1
if i > 0 :
return tag[:-i]
else :
return tag |
def get_direction_sign(here, there):
"""Return sign (+1 or -1) required to move from here to there."""
return 1 if here < there else -1 |
def _get_dbg_fn(code):
"""
Create a wrapper for the python statements, that encodes the debugging
logic for the decision tree.
"""
spacer_basic = ' '
# Create a function.
wrapper_code = "def debug_fn(): \n"
# For each line, add a tab in front and a newline at the end.
upd_code = [... |
def get_parameter_name(name):
"""
Gets parameter name from parameter key.
"""
return name[name.rfind(".") + 1 :] |
def _conf_string_to_bool(conf_string: str):
"""Normally in Python all non empty strings convert to True.
We want it to not be as easy to accidentally turn on a configuration flag, so we only treat
the explicit string "true" as True. Casing doesn't matter.
"""
return conf_string.lower() == 'true' |
def float_eq(__x: float, __y: float) -> bool:
"""
Function: float_eq
Summary: returns if 2 float nums are equal
Examples:
>>> a = 0.1 + 0.1 + 0.1
>>> b = 0.3
>>> float_eq(a, b)
>>> True
Attributes:
@param (__x): just a numbe... |
def egcd(a,b): # a > b > 0
""" Extended great common divisor, returns x , y
and gcd(a,b) so ax + by = gcd(a,b) """
if a%b==0: return (0,1,b)
q=[]
while a%b != 0:
q.append(-1*(a//b))
(a,b)=(b,a%b)
(a,b,gcd)=(1,q.pop(),b)
while q:(a,b)=(b,b*q.pop()+a)
retu... |
def find_carg_coverages(carg_node_list, reference_coverage, coverages):
"""
Find CARG coverages by searching coverages for the ones with 1 in exactly the places carg requires it to be and nowhere else.
e.g. CARG is in node_id 2, reference coverage is [0,1,2,3], CARG coverages are [0,0,1,X0], [0,0,1,0] but n... |
def validate_dice_seed(dice, min_length):
"""
Validates dice data (i.e. ensures all digits are between 1 and 6).
returns => <boolean>
dice: <string> representing list of dice rolls (e.g. "5261435236...")
"""
if len(dice) < min_length:
print("Error: You must provide at least {0} dice rol... |
def bitdepth(name):
"""Converts the name of numpy.dtype (string) to bit-depth (string)
Args:
name (str): Supported types: ['uint8', 'uint16', 'float32']
Returns:
str: The NSI equivalent of the datatype for a volume.
Raise:
TypeError: If requested type is not supported.
""... |
def normalizeDuration(periodType, timeToElapse):
"""Returns number of days given periodType and timeToElapse"""
if periodType == "weeks":
return timeToElapse*7
if periodType == "months":
return timeToElapse*30
return timeToElapse |
def is_npy(filename):
"""
The first bytes are: x93NUMPY
see: https://github.com/numpy/numpy/blob/master/doc/neps/npy-format.rst
"""
from numpy.lib.format import MAGIC_PREFIX
with open(filename, 'rb') as infile:
return infile.read(6) == MAGIC_PREFIX |
def standardizeCapitalization(input_string, algorithm):
"""
Converts title case words (e.g., ' The ') to lowercase e.g., ' the '). Allows conversion algorithms for multiple
scenarios (e.g., author names vs titles) and languages via keyword arguments of 'algorithm' parameter.
Args:
input_string ... |
def rot32(w, n_left):
""" Rotate 32-bit word left by nLeft or right by -nLeft
without creating a Python long.
Timing depends on nLeft but not on w.
"""
n_left &= 31 # which makes nLeft >= 0
if n_left == 0:
return w
# Note: now 1 <= nLeft <= 31.
# RRRsLLLLLL There ... |
def compress(ls,ind):
"""create sublist from given indices
>>> compress([7,8,9,10],[2,3])
[9, 10]
"""
return [ls[i] for i in ind] |
def prefix_mask(lenght):
"""return a prefix legnth that matches the first "lenght" bit of the address"""
return (2**128-1)-(2**(128-lenght) -1) |
def remove_docstring_indent(doc_str: str) -> str:
"""Remove the additional indent of a multiline docstring.
This can be helpful, if docstrings are combined programmatically.
"""
lines = doc_str.split("\n")
if len(lines) <= 1:
return doc_str
first_non_summary_line = next(line for line in... |
def data_to_line(data, sep='\t'):
"""Transform iterable into line to write in a file, with a separarator."""
data_str_list = [str(x) for x in data]
data_str_all = sep.join(data_str_list)
return data_str_all + '\n' |
def calculate_dir(start, target):
"""
Calculate the direction in which to go to get from start to target.
start: a tuple representing an (x,y) point
target: a tuple representing an (x,y) point
as_coord: whether you want a coordinate (-1,0) or a direction (S, NW, etc.)
"""
dx = target[0] - st... |
def merge_config(*dicts):
"""
This takes a list of python dicts and merges them into a single dict. It is set up to
assure that later arguments will take precedence over earlier ones by default.
Parameters
----------
dicts: list
List of dicts to merge into a single dict
Returns
... |
def calc_cos_plant_uptake(GEE, LRU, CO2, COS):
"""
calculate plant COS uptake from CO2 gross ecosystem
productivity, leaf relative uptake, atmospheric CO2
concentration, and atmospheric COS concentration.
INPUT PARAMETERS:
GEE: np.ndarray of gross primary production, kg C m-2 s-1
LRU: leaf r... |
def is_downloadable(url):
"""
check if the url contains a downloadable resource
"""
if (url.find('pdf')!=-1) or (url.find('epub')!=-1) or (url.find('mobi')!=-1):
print(url)
return True
else:
return False |
def get_true_anomalies(w, dtheta):
"""
Compute the initial and final true anomalies.
Parameters
----------
w: float
Argument of periapsis.
dtheta: float
Transfer angle.
Returns
-------
nu_1: float
Initial true anomaly.
nu_2: float
Final true anom... |
def get_best(summary, metric, fields=None):
"""Filters a summary to obtain the best average total of a metric for each optimizer."""
rv = dict()
for summary_key, value in summary.items():
if fields is None:
rv_key = None
else:
rv_key = tuple([summary_key._asdict()[fie... |
def translate_list(dictionary, list_to_be_translated):
"""For a given list with entries and a dictionary, it return a new list
with the translated entries"""
translated = []
for i in list_to_be_translated:
translated.append(dictionary[i])
return translated |
def generate_block_number(
chapter_number, heading_number, subheading_number, paragraph_number
):
"""
Returns chapter_number.subheading_number.paragraph_number if chapter_number is
available, or heading_number.subheading_number.paragraph_number if not.
Doesn't include any part that isn't available.... |
def create_errors(error, error_barwidth):
"""Creates dict of errors for barplot"""
if isinstance(error, str):
error_y = {}
else:
error_y = {
'type': 'data',
'array': error,
'thickness': error_barwidth,
'width': int((error_barwidth * 2.5) / 2)... |
def restrict_to_vocab(txt, vocab):
"""
Remove characters that do not belong the a vocabulary.
"""
txt = ''.join(char for char in txt if char in vocab)
return txt |
def format_dnb_company_investigation(data):
"""
Format DNB company investigation payload to something
DNBCompanyInvestigationSerlizer can parse.
"""
data['dnb_investigation_data'] = {
'telephone_number': data.pop('telephone_number', None),
}
return data |
def convert_list_for_sql(my_list):
""" Convert a python list to a SQL list.
The function is primarly used when trying to format SQL queries by passing an argument.
Arguments:
my_list: list of elements to be used in a SQL query
Example:
1. convert_list_for_sql([1, 2, 3]) returns '1, 2, ... |
def _lod_to_dol(lod):
"""Convert a list-of-dicts into a dict-of-lists.
All the dicts in the input list must have the same keys.
"""
assert isinstance(lod, list)
assert len(lod) > 0
keys = lod[0].keys()
dol = {k: [] for k in keys}
for d in lod:
for k in keys:
dol[... |
def parse_dict(d):
"""
Given a single layer dictionary d, return a string representation
of the form "key1=val1,key2=val2,..."
d (dict): Any dictionary, preferrably with no nesting
returns (str): String represenation of d described above
"""
return ",".join([str(key)+"="+str(value)... |
def ip2int(ip_addr):
"""Converts string IP address representation into integer."""
i = [int(x) for x in ip_addr.split('.')]
return (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3] |
def _bit_count(num):
"""
return number of set bits
Counting bits set, Brian Kernighan's way*
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{ v &= v - 1; } //clear ... |
def natTftp(ctx, mach, nicnum, nat, args):
"""This command shows/alters TFTP settings
usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
prefix - alters prefix TFTP settings
bootfile - alters bootfile TFTP settings
server - sets booting server
"""
if len(arg... |
def splitted(_set):
""" Transforms a set {0,1,2} into a list of singletons [[0],[1],[2]]"""
splitted = []
for el in _set:
splitted.append([el])
return splitted |
def removeDuplicates(l):
"""Return a list that is l with the duplicate entries removed."""
#The JavaScript idiom for this is:
# results = results.filter(function (v, i) {
# return results.indexOf(v) === i;
# });
# This can't be done like this in Python because the filter callback
# only ... |
def glob_to_re(glob):
"""Translate a shell glob-like pattern to a regular expression.
Currently there is no way to quote glob metacharacters "*" and "?".
Parameters:
glob (str) : A glob like pattern using "*" to match any number of chars and "?" to match a single char.
Returns:
str : ... |
def ior(a, b):
"""Same as a |= b."""
a |= b
return a |
def preprocess(image):
"""
modify image range from [0,1] to [-1, 1]
return: range modified image
"""
return image * 2 - 1 |
def get_forecast_variable(gt_id):
"""Returns forecast variable name for the given ground truth id
Args:
gt_id: ground truth data string ending in "precip" or "tmp2m"
"""
if "tmp2m" in gt_id:
return "tmp2m"
if "precip" in gt_id:
return "prate"
raise ValueError("Unrecognize... |
def checksum(sin):
"""
Determine validity of a Canadian Social Insurance Number.
Validation is performed using a modified Luhn Algorithm. To check
the Every second digit of the SIN is doubled and the result is
summed. If the result is a multiple of ten, the Social Insurance
Number is considere... |
def page_not_found(e):
"""Return a custom 404 error."""
return 'nothing here!', 404 |
def prefix_replace(original, old, new):
"""
Replaces the old prefix of the original string by a new suffix
:param original: string
:param old: string
:param new: string
:return: string
"""
return new + original[len(old):] |
def merge_dicts(dict_a, dict_b, default_key="default"):
"""
Recursively merge two nested dicts into a single dict.
When keys match their values are merged using
a recursive call to this function,
otherwise they are just added to the output dict.
"""
if dict_a is None or dict_a == {}:
... |
def convert_taxa(rough_taxa, formatting_keys='%1.2f', hundredx=False):
"""Formats lists of numbers for table generation
INPUTS:
rough_taxa -- a list of lists with a descriptor string followed by
a list of corresponding values
formatting_keys -- a string describing the way t... |
def __natoms(natoms, nshells):
""" Number of atoms for computing coordination """
from numpy import sum
if natoms > 0:
return natoms
# based on fcc
result = sum([12, 6, 24, 12, 24, 8, 48, 6, 32][:nshells])
result = int(result)
if nshells < 12:
result += 6
else:
re... |
def list2str(list):
"""Given a list return a string"""
return "[" + ", ".join([str(x) for x in list]) + "]" |
def vals_are_constant(vlist, cval=None):
"""determine whether every value in vlist is equal to cval
(if cval == None, use vlist[0])"""
if vlist == None: return 1
if len(vlist) < 2: return 1
if cval == None: cval = vlist[0]
for val in vlist:
if val != cval: return 0
return 1 |
def price(value):
"""Returns the number as decimal with 5-digit precision"""
try:
value = round(float(value), 5)
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '${0:0.5f}'.format(value) |
def name_sorting(nodes, direction, data):
"""Sort nodes by name."""
reverse = direction == 'desc'
return sorted(nodes, reverse=reverse, key=lambda n: str(n)) |
def alphabetic(string: str, decimals: bool = True):
"""Removes all of the non alphabetical letters from the string"""
if string is None:
return ""
if decimals:
return "".join(l for l in str(string) if l.isalpha() or l.isdecimal())
return "".join(l for l in str(string) if l.isalpha()) |
def identical(a,b):
"""Are arrays a and b identical?"""
from numpy import all
if len(a) != len(b): value = False
else: value = all(a==b)
return value |
def viscosity(T, mu_0=1.83245E-5, T_0=296.15, S=110.4):
""" calculates viscosity of the air
Parameters
----------
T : float
measurement temperature
mu_0 : float
reference viscosity
T_0 : float
reference temperature
S : float
Sutherland constant of ai... |
def kronecker(i, j):
"""Kronecker delta function, 1 if i = j, otherwise 0."""
return 1 if i == j else 0 |
def _split_uppercase(word: str) -> set:
"""
EverGreen -> Ever, Green
"""
pos_upper = [pos for pos, letter in enumerate(word) if letter.isupper()]
pos_upper.append(len(word))
simple_words = set([])
for left, right in zip(pos_upper[:-1], pos_upper[1:]):
simple_words.add(word[left: righ... |
def hmsToHour(s, h, m, sec):
"""Convert signed RA/HA hours, minutes, seconds to floating point hours."""
return s * (h + m/60.0 + sec/3600.0) |
def MultipleReplace(Text, ReplaceDict):
"""
Perform multiple replacements in one go using the replace dictionary
in format: { 'search' : 'replace' }
"""
NewText = Text
for Search, Replace in ReplaceDict.items():
NewText = NewText.replace(Search, str(Replace))
return NewText |
def run(path: str, timeoutSeconds: int, arguments: dict) -> str:
"""
This method runs a notebook and returns its exit value
"""
print("skip dbutils.notebook.run({},{},{})".format(path, timeoutSeconds, arguments))
return '' |
def _get_node(response, *ancestors):
""" Traverse tree to node """
document = response
for ancestor in ancestors:
if ancestor not in document:
return {}
else:
document = document[ancestor]
return document |
def get_distance(a, b):
"""Return the manhattan distance between
points a and b."""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
def get_leaves(node):
"""
Get the leaf nodes in the passed expression
tree (the logical expression operands)
"""
if not node:
return []
leaves = []
stack = [node]
while stack:
n = stack.pop()
if not n:
continue
if not (n.left or n.right):
leaves.append(n)
else:
stack.append(n.left)
stack.... |
def line(loc, strg):
"""
Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
return strg[lastCR + 1 : nextCR] if nextCR >= 0 else strg[lastCR + 1 :] |
def weekday_to_str(num):
"""
Translate weekday to string
"""
data = {
'0': 'mon',
'1': 'tue',
'2': 'wed',
'3': 'thu',
'4': 'fri',
'5': 'sat',
'6': 'sun',
}
return data.get(str(num)) |
def url(pattern, handler, kwargs=None, name=None):
"""Converts parameters to tupple of length four.
Used for convenience to name parameters and skip
unused.
"""
return pattern, handler, kwargs, name |
def member( x, set ):
"""test for set membership"""
try:
set.index( x )
return True
except ValueError:
return False |
def pct_diff(x, y):
"""
pct_diff(x, y)
Returns the percent difference between two numbers, base number x, and
"new" number y.
"""
pct = round((abs(y - x) / x) * 100, 2)
print(str(pct) + '%')
return pct/100 |
def equivalent_interest(i, c, p):
"""
Author: Thomas Richmond
Purpose: Convert a periodically compounded interest rate to an
equivalent interest for a certain payment period
Parameters: i [float] - Interest being compounded at rate c,
expressed as a decimal
... |
def is_crack(x, y):
"""Determine whether a pair of particles define the crack."""
crack_length = 0.3
output = 0
p1 = x
p2 = y
if x[0] > y[0]:
p2 = x
p1 = y
# 1e-6 makes it fall one side of central line of particles
if p1[0] < 0.5 + 1e-6 and p2[0] > 0.5 + 1e-6:
# d... |
def get_spec_id(spec):
"""Get a quasi identifier for the spec, with the name, version, hash, spackmon id"""
return "%s@%s/%s:%s" % (
spec["name"],
spec["version"],
spec["full_hash"],
spec["id"],
) |
def _count_dependency_matches(deps1, deps2):
"""
Checks how many of the deps1 have a matching dependency in deps2
:param deps1: list or set of Dependency objects
:param deps2: list or set of Dependency objects
:return: integer
"""
matches = 0
for dep1 in deps1:
for dep2 in deps2... |
def generate_performance_payload(start_time, cpu_util_pct, mem_util_pct, net_info):
"""
Request POST the cipher result to the django and mysql
:param cipher_result: CipherResult
:return: payload
"""
payload = "{\"startTime\":\"" + str(start_time) \
+ "\",\"cpuUtilPct\":\"" + '%0.4f'... |
def is_use_existing(exists, expected, use_anyway):
"""Determine if the resource is an existing resource that can be used.
:param exists: Whether we found the resource in target API.
:param expected: Whether we expected to find the resource in target API.
:param use_anyway: If we should use it, even if ... |
def extract_project_name(content):
"""
Extract the Cargo project name from the Cargo.toml file.
:param str content: The Cargo.toml parsed dictionnary
:returns: The project name, otherwise None
:rtype: str
"""
try:
return content['package']['name']
except KeyError:
return... |
def list_ep(als,step=1):
"""
Return a nested list of ends of consecutive runs given an ordered list of numbers.
Arguments:
- als - an ordered list of numbers
- step - step size, to define "consecutive runs" [ 1 ]
"""
# first check if the input list is sorted in ascending order
try:
... |
def safe_str(maybe_str):
"""To help with testing between python 2 and 3, this function attempts to
decode a string, and if it cannot decode it just returns the string.
"""
try:
return maybe_str.decode('utf-8')
except AttributeError:
return maybe_str |
def diff_to_str(diff: int) -> str:
"""Convert a diff id to a string with leading "D"."""
return 'D{}'.format(diff) |
def filter_n(*args):
"""
Filter any number of lists of corresponding items based on some function of
the first list.
"""
filter_function = args[0]
to_filter = args[1:]
to_return = [list() for _ in to_filter]
for i in range(len(to_filter[0])):
# For each run of... |
def lists2dict(list_of_pipeline_description, url, d):
""" Convert a list of splited module names to a hierachic dictionary with
list leafs that contain the url to the module docuementation.
Parameters
----------
list_of_pipeline_description: list of list of str (mandatory)
the splited modul... |
def linearize_subtable(subtable, table_page_title, table_section_title):
"""Linearize the highlighted subtable and return a string of its contents."""
table_str = ""
if table_page_title:
table_str += "<page_title> " + table_page_title + " </page_title> "
if table_section_title:
table_str += "<section_ti... |
def postorder_traverse_re(root):
"""Post-order traversal (recursive)."""
values = []
def traverse(node):
if not node:
return
traverse(node.left)
traverse(node.right)
values.append(node.val)
traverse(root)
return values |
def format_str_timestamp(timestamp_str):
"""Format a str timestamp adding teh char `Z` in the end of it, if needed
For instance: the '2014-12-10T12:00:00.123123' is converted to '2014-12-10T12:00:00.123123Z'.
Args:
timestamp_str (str): The timestamp of the monitoring metric
Returns:
s... |
def encode_keys(mapping, key_encode):
"""Encodes all keys in mapping with ``key_encode`` callable.
Returns tuple of: key mapping (encoded key => key) and
value mapping (encoded key => value).
>>> mapping = {'k1': 1, 'k2': 2}
>>> keys, mapping = encode_keys(mapping,
... lambda k: str(bas... |
def flatten_dict(multi_level_dict) -> dict:
"""Flatten a dictionary."""
flattened_dict = {}
for entry in multi_level_dict:
if isinstance(multi_level_dict[entry], dict):
new_elements = flatten_dict(multi_level_dict[entry])
flattened_dict.update(new_elements)
else:
... |
def is_source_line(source_str, file_ext):
"""Returns True if the line appears to contain source code, False otherwise."""
if file_ext in ['.c', '.cpp', '.cxx', '.h', '.m', '.java', '.rs']:
if source_str.find(';') > 0:
return True
elif file_ext in ['.py']:
if len(source_str) > 0:
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.