content stringlengths 42 6.51k |
|---|
def merge(a, b, path=None):
"""merges b into a
>>> a={1:{"a":"A"},2:{"b":"B"}, 8:[]}
>>> b={2:{"c":"C"},3:{"d":"D"}}
>>> c = merge(a, b)
>>> c == a == {8: [], 1: {"a": "A"}, 2: {"c": "C", "b": "B"}, 3: {"d": "D"}}
True
>>> c = merge(a, {1: "a"})
>>> print(c[1])
a
"""
if pa... |
def rem_dupl(seq, seq2=None):
"""Remove duplicates from a sequence and keep the order of elements.
Do it in unison with a sequence 2."""
seen = set()
seen_add = seen.add
if seq2 is None:
return [x for x in seq if not (x in seen or seen_add(x))]
else:
a = [x for x in seq if not (x... |
def scale_mem_nlin(chan_id, rvals):
"""
scale memory/non-linearity values
"""
if chan_id < 6:
return 1.25 * (rvals + 37)
if chan_id == 6:
return 1.25 * (rvals + 102)
if chan_id == 7:
return 1.5 * (rvals + 102)
if chan_id == 8:
return 1.25 * (rvals + 126)
... |
def extract(input_data: str) -> list:
"""take input data and return the appropriate data structure"""
return list(map(int, input_data)) |
def uniquify(words):
"""Remove duplicates from a list.
Args:
words (list): The list of words
Returns:
list: An updated word list with duplicates removed.
"""
return {}.fromkeys(words).keys() if words is not None else words |
def StringList_to_File(string_list,file_name="test"):
"""Saves a string list as a file"""
out_file=open(file_name,"w")
for line in string_list:
out_file.write(line)
out_file.close()
return file_name |
def sep_by_10s(s):
"""Insert a period every ten characters, starting from the back."""
# return s
t = ""
for i, c in enumerate(reversed(s)):
t += c
if i % 10 == 9:
t += '.'
return ''.join(reversed(t)) |
def class_size(cls):
"""Get the number of bytes per element for a given data type.
Parameters:
cls (str): Name of the data type
Returns:
int: Number of byte per element
"""
if cls in ['float64', 'int64', 'uint64']:
n_byte = 8
elif cls in ['float32', 'int32', 'uint32']:
... |
def filtered(alert, rules):
"""Determine if an alert meets an exclusion rule
:param alert: The alert to test
:param rules: An array of exclusion rules to test against
:returns: Boolean - True if the alert should be dropped
"""
return any(rule(alert) for rule in rules) |
def flatten_dict(dictionary):
"""
Utility Function: flatten_dict
Used to (potentially recursively) flatten the input dictionary into a list of strings containing all of the keys and
values present in the input dictionary.
"""
flat_list = list()
for key in dictionary.keys():
flat_li... |
def check_number_edges(ugraph):
""" dict -> int
Just a sanity check to find the number of nodes on a undirected graph.
"""
directed_edges = 0
for node in ugraph:
directed_edges += len(ugraph[node])
if directed_edges % 2 == 0:
return directed_edges / 2
else:
return "No... |
def ordered_keys(tuples):
"""
:param tuples: input array
:return: list of keys
"""
keys = list()
for el in tuples:
keys.append(el[0])
return keys |
def zip_dicts(dict1, dict2):
"""
defines a dictionary update rules that are required for a proper dictionary update
:param dict1: dictionary #1
:param dict2: dictionary #2
"""
for key in dict2.keys():
if key not in dict1.keys():
dict1[key] = dict2[key] # never used in produc... |
def percentageOfSeries(dataList:list,percentage:float):
"""
This function returns the percentage of a list.
Parameters
----------
dataList : list
The list holding data
percentage : float
The percentage number. 99 means 99% percentage.
Returns
-------
None
"""
length = len(dataList)
sortedData = sorted... |
def signature_matches(func, template_func):
"""
Checks if the given *func* is of type `function` or `instancemethod`.
If it is, it also verifies if the argument count matches the one from the given *template_func*.
When the function is not callable or the signature does not match, ``False`` is returned.... |
def is_number(s):
""" Check if given var is / can be converted to float """
try:
float(s)
return True
except ValueError:
return False |
def find(func, iteratee):
"""Returns the first element that match the query"""
for value in iteratee:
if func(value):
return value
return None |
def dextrose_equivalent(n):
"""
Return the dextrose equivalent of starch given the degree of polymerization.
Parameters
----------
n : int
Degree of polymerization.
Returns
-------
DE : float
Dextrose equivalent.
Notes
-----
The dextrose equivalent (DE) is ... |
def primality(n):
"""
@brief Checks if n is a prime number: O(sqrt(n))
"""
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True |
def fi_wiki_url(name):
""" Create a finnish wikipedia page url from a persons name """
name = name.replace(' ', '_')
return 'https://fi.wikipedia.org/wiki/'+name |
def main(argv):
""" Main entry point of the program """
print('This is a boilerplate') # NOTE: indented using two tabs or 4 spaces
return 0 |
def largest_element(a):
""" Return the largest element of a sequence a.
"""
try:
maxval = a[0]
loc = 0
for i, f in enumerate(a):
if a[i] > maxval:
maxval = a[i]
loc = i
return maxval, loc
except ValueError:
print('ValueE... |
def _vtk_solib_name(basename, version = None):
"""Constructs Linux-specific name of vtk libraries"""
version = "" if not version else "-" + version
return "lib{}{}.so".format(basename, version) |
def distance(point1, point2):
"""L2 distance"""
return sum((point1[i]-point2[i])**2 for i in range(len(point1)))**0.5 |
def parse_nuclide(nuclide: str) -> str:
"""
Parses a nuclide string from e.g. '241Pu' or 'Pu241' format to 'Pu-241' format. Not this
function works for both radioactive and stable nuclides.
Parameters
----------
nuclide : str
Nuclide string.
Returns
-------
str
Nucl... |
def get_nodata_value(max_value):
"""
Calculate the appropriate nodata value based on max of value range for the
output image type
Parameters
----------
max_value : number
max encoded value
Returns
-------
int, nodata value
"""
if max_value < 255: # uint8 / graysca... |
def clean_warning(message, category, filename, lineno, file=None, line=""):
"""Formats the standard warning output."""
return f"{category.__name__}: {filename}:{lineno}\n{message}" |
def format_setting_name(token):
"""Returns string in style in upper case
with underscores to separate words"""
token = token.replace(' ', '_')
token = token.replace('-', '_')
bits = token.split('_')
return '_'.join(bits).upper() |
def normalise_line_tail(line):
"""Replace white-space characters at the end of the line with a newline character"""
return line.rstrip() + '\n' |
def remove_duplicates(lst):
"""Remove duplicate tuples from a list of tuples."""
return [t for t in (set(tuple(i) for i in lst))] |
def translate_plural(n, single, middle, multiple):
"""
Chooses which form of plural to use. Based on https://doc.qt.io/qt-5/i18n-plural-rules.html.
:param n: the number itself
:param single: string to use by rule 1
:param middle: string to use by rule 2
:param multiple: string to use by rule 3
... |
def check_in_all_possible_transbordements(all_possible_transbordements, mmsi_a, mmsi_b):
"""check if there's already a possible transhipment found for the two ships
represented by their mmsi.
If it is the case, then this function returns True and the index (key) of
the possible transhipment in all_possible_transbo... |
def read_file(text_file):
"""
Function that reads a text file and returns the data from the text file
"""
try:
with open(text_file,'r') as handle:
data = handle.read()
return data
except FileNotFoundError:
return None |
def create_table_string(data, highlight=(True, False, False, False), table_class='wikitable', style=''):
"""
Takes a list and returns a wikitable.
@param data: The list that is converted to a wikitable.
@type data: List (Nested)
@param highlight: Tuple of rows and columns that should be highlighte... |
def coord_to_rect(coord, height, width):
"""
Convert 4 point boundbox coordinate to matplotlib rectangle coordinate
"""
x1, y1, x2, y2 = coord[0], coord[1], coord[2] - coord[0], coord[3] - coord[1]
return x1 * width, y1 * height, x2 * width, y2 * height |
def group(iterable, n):
"""Splits an iterable set into groups of size n and a group
of the remaining elements if needed.
Args:
iterable (list): The list whose elements are to be split into
groups of size n.
n (int): The number of elements per group.
... |
def no_c(my_string):
"""
removes all instances of 'c' & 'C' from string
"""
new_str = ""
for i in range(len(my_string)):
if my_string[i] != 'c' and my_string[i] != 'C':
new_str += my_string[i]
return (new_str) |
def exists(env):
""" Check if `cflow` tool is imported in the environment """
return env['CFLOW'] if 'CFLOW' in env else None |
def get_foo(dummy_context, dummy_request):
""" View callable for top-level resource
"""
return {
'uri': '/foo',
} |
def convert_to_3_digits(number):
""" #### convert enetered number to 3 digits chunks
Input number
return list of 3 digits chunks
"""
number = str(number)
number = number[::-1]
number_list = []
for i in range(0, len(number), 3):
number_list.append(number[i:i+3][::-1])
... |
def legendre(a, m):
"""
This function returns the Legendre symbol (a/m).
If m is an odd composite then this is the Jacobi symbol.
"""
a = a % m
symbol = 1
while a != 0:
while a & 1 == 0:
a >>= 1
if m & 7 == 3 or m & 7 == 5:
symbol = -symbol
... |
def error_result(error: str) -> dict:
"""
A utility function for creating a `dict` used for updating setup state related to configuring `data_path`.
:param error: a string identifying the error
:return: an error update for the setup state
"""
return {
"path": "",
"error": error... |
def percent(num, total): # type: (int, int) -> float
"""Calculate a percent"""
perc = num * 100 / total if total is not 0 else 0
return float(round(perc, 2)) |
def score_match_possible_ids(possible_ids_1, possible_ids_2, match_c=1, mismatch_c=-0.25):
"""
just a scoring system. if one instance doesnt have an id we dont penalize
if the ids match we benefit the match, if they dont we add a minor penalty.
The penalty is lower since we assume databases already have... |
def _quote(text):
"""Enclose the string with quotation characters"""
return '\'{0}\''.format(text) |
def Mach(a, V):
"""
Calculates flow Mach number
"""
Ma = V / a
return Ma |
def process_taskline(taskline, commit_uri_prefix):
"""Retrieve issue_id, url, and title from a taskline in a todo file.
>>> process_taskline('12345 TEST-123 2018-08-12 TEST-123 foo\\n', 'http://git.HOST.TLD/my-project/my-repository/commit/')
('TEST-123', 'http://git.HOST.TLD/my-project/my-repository/commit... |
def price_to_profit(lst):
"""
Given a list of stock prices like the one above,
return a list of of the change in value each day.
The list of the profit returned from this function will be our input in max_profit.
>>> price_to_profit([100, 105, 97, 200, 150])
[0, 5, -8, 103, -50]
>>> price_t... |
def sol2(limit) -> int:
"""
A little more pythonic solution with list comprehension to generate the list
"""
total = 0
numbers = [x for x in range(limit) if x % 3 == 0 or x % 5 == 0]
for x in numbers:
total += x
return total |
def check_row_winner(input_list, size):
"""
Check the winner number in row direction.
Arguments:
input_list -- a two dimensional list for checking.
size -- the length for winning.
Returns:
winner -- the winner player number, if no winner return None.
"""
for line in input_... |
def process_coords(coords, size, psize):
"""
centers object to be pasted on card
:param coords: coords of the object to be pasted
:param size: size of the object we are pasting on
:param psize: size of the object to be pasted
:return: proper coords of the object to be pasted
"""
if coord... |
def cand_median(dataPoints):
"""Calculate the first candidate median as the geometric mean."""
tempLat = 0.0
tempLon = 0.0
for i in range(0, len(dataPoints)):
tempLat += dataPoints[i][0]
tempLon += dataPoints[i][1]
return (tempLat / len(dataPoints), tempLon / len(dataPoints)) |
def header_name(name):
"""Convert header name like HTTP_XXXX_XXX to Xxxx-Xxx:"""
words = name[5:].split('_')
for i in range(len(words)):
words[i] = words[i][0].upper() + words[i][1:].lower()
result = '-'.join(words)
return result |
def to_flags(cli_input: dict) -> list:
"""Turn dictionary of CLI input into a list of CLI flags ready for use in FlaskCliRunner.invoke().
Example:
cli_input = {
"year": 2020,
"country": "NL",
}
cli_flags = to_flags(cli_input) # ["--year", 2020, "--country", "NL"... |
def round_partial(value, resolution):
"""Rounds a number to a partial interval. Good for rounding things
up/down to the nearest value of 5 for example.
Thanks to http://stackoverflow.com/a/8118808 for this neat trick
"""
return round(value / resolution) * resolution |
def cap_sentence(s):
"""
* Remove extra space
* Lower all letters if word.isupper() and len(word) > 3
* Capitalize the first letter of each word
"""
sentence = " ".join(
[c.lower() if c.isupper() and len(c) > 3 else c for c in s.split()]
)
return "".join(
c.upper() if i =... |
def delta(n_1, n_2) -> int:
"""Kronicka-delta function, yields 1 if indexing is the same, else zero."""
if n_1 == n_2:
return 1
else:
return 0 |
def enumerate_installation_candidates(installation_candidates):
"""
Parameters
----------
installation_candidates : list
Returns
-------
install_candidates_numbered: list
"""
install_candidates_numbered = [f"[{i}] {elem}" for i, elem in enumerate(installation_candidates)]
return install_candidates_numbered |
def get_values(scale_values: dict):
"""Get recursively the inner most values from a recursive dict."""
values = []
for key in scale_values.keys():
if isinstance(scale_values[key], dict):
values.extend(get_values(scale_values[key]))
elif isinstance(scale_values[key], list):
... |
def calculate_accuracy(predicts, labels):
"""
:param predicts: encoded predict result
:param labels: ground true label
:return: accuracy
"""
assert len(predicts) == len(labels)
correct_count = 0
for i, p_label in enumerate(predicts):
if p_label == labels[i]:
correct_... |
def _get_bit(byte, ii):
"""Return the bit value at index `ii` of `byte`.
Bit index is 0 = MSB, 7 = LSB
"""
return (byte >> (7 - ii)) & 1 |
def round_half_integer(x):
""" Rounds number to nearest floating point half integer.
Args:
x (number): quantity to be rounded
Returns:
float: number rounded to (generally exact) integer or half integer
"""
return round(2*float(x))/2 |
def get_formatted_time(s):
"""
This function gets an amount of seconds started when the game began and converts it to minutes:second format
:param s: float
:return: string
"""
seconds = int(s % 60)
minutes = int(s / 60)
# hours = int(minutes / 60)
return ('{0}:{1}').format(minutes, ... |
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
Returns:
parameters -- python diction... |
def split_param_filter_index1(s):
"""
Split a parameter name into the <string><number> components
where <string> is the parameter name and <number> is the filter
index (1-based). If there is no number at the end for a filter
index, then return None for the second argument.
Returns
---------... |
def assign_wl_vals(teams, picker):
"""
Assign winners and losers in future games.
"""
if len(teams) == 1:
return []
evens = teams[::2]
odds = teams[1:][::2]
retv = []
for count, evenp in enumerate(evens):
if picker[count] == 1:
retv.append(odds[count])
... |
def convert_to_unicode_string(data):
"""Recursively convert dictionary keys and values to unicode strings"""
if isinstance(data, dict):
return {
convert_to_unicode_string(k): convert_to_unicode_string(v)
for k, v in data.items()
}
elif isinstance(data, list):
... |
def isimage(filename):
"""true if the filename's extension is in the content-type lookup"""
ext2conttype = {"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif"}
filename = filename.lower()
return filename[filename.... |
def map(value, in_low, in_high, out_low, out_high):
"""map."""
result = None
# based on http://arduino.cc/en/Reference/Map
result = ((value - in_low) * (out_high - out_low)) / \
(in_high - in_low) + out_low
# http://stackoverflow.com/a/5650012/574981
# result = out_low + \
# ((... |
def append_str(*strs):
"""Append strings."""
return ''.join(list(strs)) |
def get_padding(size, kernel_size, strides):
""" Calculate the padding array for same padding in the Tensorflow fashion.\\
See https://www.tensorflow.org/api_guides/python/nn#Convolution for more.
"""
if size[0] % strides[0] == 0:
pad_h = max(kernel_size[0] - strides[0], 0)
else:
pad_h = max(kernel_si... |
def is_view_func_public(func):
"""
Returns whether a view is public or not (ie/ has the STRONGHOLD_IS_PUBLIC
attribute set)
"""
return getattr(func, 'STRONGHOLD_IS_PUBLIC', False) |
def madc(matrix, mean_value):
"""
Calculate the absolute mean deviation of numbers in list.
"""
abs_deviation = 0
for idx in range(len(matrix)):
abs_deviation += (abs(matrix[idx] - mean_value) / len(matrix))
return abs_deviation |
def precision(relevance_vector):
"""
Calculates the precision of the given relevance vector.
Args:
-----
relevance_vector : list
A non-empty list of relevance values (0 or 1) for
each rank of a query result.
Returns:
--------
precision : float
... |
def split_dict(adict):
"""
Split a dictionary type into a list of keys and values
"""
if isinstance(adict, dict):
keys = list(adict.keys())
values = list(adict.values())
return keys, values
else:
print('Error: Attempted to split a non-dict '
'object into... |
def square_summation(limit):
"""
Returns the summation of all squared natural numbers from 0 to limit
Uses the short form summation formula for summation of squares
:param limit: {int}
:return: {int}
"""
return (limit * (limit + 1) * (2 * limit + 1)) // 6 if limit >= 0 else 0 |
def quad_func(x, a, b, c):
""" a*x**2 + b*x + c """
return a*x**2 + b*x + c |
def get_match_ref_color(is_match):
"""
Get color for base matching to reference
:param is_match: If true, base matches to reference
:return:
"""
if 48 <= is_match <= 52:
return 0
elif is_match == 254:
return 1 |
def map_a_number_into_minus_half_to_half(number):
"""map a number into [-0.5, 0.5]"""
while number > 0.5:
number -= 1
while number < -0.5:
number += 1
return number |
def get_from_flattened_config_dict(dic, flattened_key, default=None):
"""
Reads out a value from the nested config dict using flattened config key (i.e. all
keys from each level put together with "." separator), the default value is returned
if the flattened key doesn't exist.
e.g. if the config dic... |
def teacher(i, K, categories, output_activations):
"""
Function that calculates the feedback in learning, which is supplied in the form of teacher values (equation 4b in
[Krus92]_)
Parameters
----------
i : int
Stimulus ID or stimulus number
K : int
Category number
categ... |
def fix_method_type(string: str) -> str:
"""Fixes the method type.
Args:
string: A parameter type declaration
Returns:
A fixed up string replacing pointers to concrete types with pointers to
void, e.g. "const int*" -> "const void*".
"""
method_type = string.strip()
# Const pointer
if "*" i... |
def shorten_rule(rule):
"""
If possible, this method removes redundant parts of the given rule.
>>> shorten_rule((['ukr_itself_place', 'ukr_itself_place'],
[4.5, 1.5], [True, True], 'voiced'))
(['ukr_itself_place'], [1.5], [True], 'voiced')
Keyword arguments:
rule: A tuple... |
def amdahls_law(p, s):
"""Speedup relative to proportion parallel
Amdahl's Law gives an idealized speedup we
can expect for an algorithm given the proportion
that algorithm can be parallelized and the speed
we gain from that parallelization. The best case
scenario is that the speedup, `s`, is eq... |
def group(src):
""" Method that takes a list of elements
and returns a list of groups of elements
if there are equal lements that can be
groupped """
dst = []
tmp = []
tmp.append(src.pop(0))
llen = len(src)
while llen > 0:
if src[0] in tmp:
tmp.append(src.pop(0)... |
def re_wrap(p):
"""
Wrap a regular expression if necessary, i.e., if it contains unescaped '|'
in the outermost level.
"""
escaped = False
level = 0
for c in p:
if c == '\\':
escaped = not escaped
elif c == '(' and not escaped:
level += 1
elif... |
def merge(left, right):
"""Merge two lists in ascending order."""
lst = []
while left and right:
if left[0] < right[0]:
lst.append(left.pop(0))
else:
lst.append(right.pop(0))
if left:
lst.extend(left)
if right:
lst.extend(right)
... |
def standardize_method_to_len_3(name, padding="--", joiner=","):
"""Standardize an LCIA method name to a length 3 tuple.
``name`` is the current name.
``padding`` is the string to use for missing fields.
"""
if len(name) >= 3:
return (tuple(name)[:2] + (joiner.join(name[2:]),))
else:
... |
def count_None(seq):
"""Returns the number of `None` in a list or tuple
Parameters
----------
seq : list or tuple
input sequence
Returns
-------
num : integer
number of `None` in the sequence
"""
return sum(i is None for i in seq) |
def clean_value(v, debug=False):
"""
Strip bad characters off of values
"""
if debug:
print("clean_value '%s'" % v)
if type(v) == type("") or type(v) == type(u""):
v = v.strip('"\\')
return v |
def to_path(path):
"""
Helper function, converting path strings into path lists.
>>> to_path('foo')
['foo']
>>> to_path('foo.bar')
['foo', 'bar']
>>> to_path('foo.bar[]')
['foo', 'bar', []]
"""
if isinstance(path, list):
return path # already in l... |
def slices_to_sched(sl):
"""Create a concrete schedule from a list of slices
returned by `psched`.
"""
sch = []
for s in sl:
step = s.step // 2
sch.extend([(i,i+step) for i in range(s.start, s.stop, s.step)])
return sch |
def permission_denied_page(error):
"""Show a personalized error message."""
return "Not Permitted", 403 |
def fib_up_to(n):
"""Return Fibonacci sequence up to "n".
Args:
n: An integer up to wich calculate Fibonacci sequence.
Returns:
A list containing the Fibonacci sequence.
"""
result = []
a, b = 0, 1
while b <= n:
result.append(b)
a, b = b, a + b
retur... |
def is_short(item: str) -> bool:
"""Return true if the length of string is less than 4 characters long."""
return len(item) < 4 |
def convert_type(dtype):
""" Converts a datatype to its pure python equivalent """
val = dtype(0)
if hasattr(val, "item"):
return type(val.item())
else:
return dtype |
def conditionString(cond,string = None, parenthesis = False):
"""If the condition cond holds: return the string if it's not None, else the cond.
If its not empty, add parenthesis around them
"""
if not cond:
return ""
if string is not None:
ret = str(string)
else:
ret = s... |
def _GetCountDict(arr):
""" *Internal Use Only*
"""
res = {}
for v in arr:
res[v] = res.get(v, 0) + 1
return res |
def rtrunc(string, width, marker='...'):
"""Truncates a string from the right to be at most 'width' wide.
Args:
string: String to truncate.
width: Width to make the string at most. May be 0 to not truncate.
marker: String to use in place of any truncated text.
Returns:
Tru... |
def first_occurrence(array, query):
"""
Returns the index of the first occurance of the given element in an array.
The array has to be sorted in increasing order.
"""
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
#print("lo: ", lo, " hi: ", hi, " mid: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.