content stringlengths 42 6.51k |
|---|
def normalize_set(set_id, conversion={}):
"""Convert set id readable by goldfish/deckstats"""
conversion.update({'DAR': 'DOM'})
return conversion.get(set_id.upper(), set_id.upper()) |
def generate_integers(m, n):
"""
Accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive.
:param m: an integer value of starting index.
:param n: an integer value of ending index.
:return: the values in the range between m and n.
"""... |
def hide_helpers(content):
"""prevent helper requests from being filled"""
return content.replace('{{', '[[raw!').replace('}}', '-raw]]') |
def parallel_circuit_UA(*args):
"""
Calculates the total U*A-value for a parallel circuit of two or more U*A
values.
Parameters:
-----------
UA : float, int, np.ndarray
U*A value (heat conductivity) in [W/K] for each part of the parallel
circuit. If given as np.ndarray, all arra... |
def toggle_modal(n1, n2, is_open):
"""Open and close info-box."""
if n1 or n2:
return not is_open
return is_open |
def calc_area(l,w):
"""
Params l and w are both real positive numbers representing the length and width of a rectangle
"""
if l <=0 or w <=0:
raise ValueError
return l*w |
def __split_flavor(flavor):
"""
Split a flavor into type and subtype.
:param flavor: The flavor to split
:type flavor: str
:return: type, subtype
:rtype: str, str
:raise: ValueError
"""
flavor_types = flavor.split("/")
if len(flavor_types) != 2:
raise ValueError("Invalid... |
def _read_value(cell):
"""Read the value from the given cell.
"""
if type(cell) != str:
# We're dealing with a cell from either openpyxl or xlrd.
if cell.value:
return str(cell.value)
return ""
return cell |
def transforms(subject_number: int, target_pk) -> int:
"""For the parm subject number. Transform the subject number several times until it matches the target public key.
Return the number of iterations needed"""
# "To transform a subject number, start with the value 1."
result = 1
loop = 0
... |
def parse_labels(labels_fh):
"""Read seq label IDs into dictionary.
Incase label line has other text slice first item"""
labels = [line.split()[0] for line in labels_fh]
return set(labels) |
def tresca(sigma):
"""
Computes the Tresca equivalent stress
:param sigma:
:return:
"""
size = len(sigma)
if size == 1:
return (sigma[0] - 0.0)/(2.0)
elif size == 2:
return (sigma[0] - sigma[1]) / (2.0) |
def str_for_latex(string):
"""
Helper method to convert some strings that are problematic for latex.
"""
string = string.replace('_', '\\_')
string = string.replace('$', '\\$')
string = string.replace('&', '\\&')
string = string.replace('%', '\\%')
string = string.replace('#', '\\#')
... |
def xor(item1, item2):
"""
Implementation of xor
"""
if not item1 and not item2:
return False
if item1 and item2:
return False
return True |
def is_list(value, by_instance=False):
"""
Check whether the value is list object
:param value:
:param by_instance:
:return:
"""
if by_instance is True:
return isinstance(value, list)
return type(value) == list |
def set_value(dictionary, value, *keys):
"""Modify the value the keys point to in a nested dictionary.
The dictionary can be a nested dictionary containing lists, these lists can
also contain nested dictionaries, and so on. The keys list can contain
strings (which refer dictionary keys) and integers (w... |
def rev_cohort_interleave(inner, cohort_size):
"""
Inverse of `cohort_interleave`.
"""
if inner % 2:
return cohort_size - 1 - inner // 2
else:
return inner // 2 |
def indented(text, level, indent=2):
"""Take a multiline text and indent it as a block"""
return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines()) |
def get_node_ids(iface_list):
""" Returns a list of unique node_ids from the master list of
interface dicts returned by get_iface_list()
"""
# Casting as a set() removes duplicates
# Casting back as list() for further use
return list(set([i["node_id"] for i in iface_list])) |
def valid_post_data(post_data):
"""
loosely validate block data
Valid post data =
[
{
"transaction": {
"from": "alice", -+
"to": "bob", |-> mandatory fields
"amount": 113 -+
}
},
[...]
]... |
def _unique_metric_name(name, existing_metrics):
"""Returns a unique name given the existing metric names."""
existing_names = set([metric.name for metric in existing_metrics])
proposed_name = name
cnt = 1 # Start incrementing with 1.
# Increment name suffix until the name is unique.
while proposed_name i... |
def load_episodes(path):
"""Load shows' episodes,
Return episode list
"""
# gather all episodes of all shows together
all_episodes_series = ""
# shows' names
all_series = ['TheBigBangTheory']
# final list of all episodes (season x)
episodes_list = ['TheBigBangTheory.Sea... |
def set_or_label(termtype):
""" Sets OR Label only if the clusters radio button is selected"""
if termtype == 'Clusters':
return 'Or' |
def func_xy_ab_pq_kwargs(x, y, a=2, b=3, *, p="p", q="q", **kwargs):
"""func.
Parameters
----------
x, y: float
a, b: int
p, q: str
kwargs: dict
Returns
-------
x, y: float
a, b: int
p, q: str
kwargs: dict
"""
return x, y, a, b, None, p, q, kwargs |
def count_bits(s):
"""
Count the number of bit 1 in the binary representation of non-negative number s
"""
cnt = 0
while s > 0:
s -= s & (-s) # (s & (-s)) = 2^k, where k is the index of least significant bit 1 of s.
cnt += 1
return cnt |
def _zig_zag_encode(value: int) -> int:
"""Encodes signed integers to give a compact varint encoding."""
return value << 1 if value >= 0 else (value << 1) ^ (~0) |
def make_summary(results):
"""returns records from analyses as list"""
rows = []
for position_set in results:
if type(position_set) != str:
position = ":".join(position_set)
else:
position = position_set
re = results[position_set]["rel_entropy"]
dev =... |
def auc(curve=[]):
""" Returns the area under the curve for the given list of (x, y)-points.
The area is calculated using the trapezoidal rule.
For the area under the ROC-curve,
the return value is the probability (0.0-1.0) that a classifier will rank
a random positive document (Tr... |
def _parse_int_set(nputstr=""):
"""Return list of numbers given a string of ranges
http://thoughtsbyclayg.blogspot.com/2008/10/
parsing-list-of-numbers-in-python.html
"""
selection = set()
invalid = set()
# tokens are comma separated values
tokens = [x.strip() for x in nputstr.split(','... |
def _all_contained_in(inner, outer):
"""
Return True iff all items in ``inner`` are also in ``outer``.
"""
for v in inner:
if v not in outer:
return False
return True |
def alias_diff(refcounts_before, refcounts_after):
"""
Given the before and after copies of refcounts works out which aliases
have been added to the after copy.
"""
return set(t for t in refcounts_after
if refcounts_after[t] > refcounts_before.get(t, 0)) |
def add_events(base, new):
"""Add newly declared events to a base set of events. New
declarations replace old ones."""
for (event, callback) in new:
if event in base:
del base[event]
base[event] = [callback]
else:
callbacks = base[event]
if c... |
def underline(text: str) -> str:
"""Get the given text with an underline.
Parameters
----------
text : str
The text to be marked up.
Returns
-------
str
The marked up text.
"""
return "__{}__".format(text) |
def normalize_name(name):
"""
normalize the name to use as a key in the donors dict
"""
name = " ".join(name.strip().split()).lower()
return name |
def BuildSvd(svd_json):
"""Create a list out of a single SVD object's dictionary.
Args:
svd_json: The dictionary of a single SVD object info.
Returns:
An 8-bit integer representing a single SVD object.
"""
svd = svd_json["VIC"]
if svd_json["Nativity"] == "Native":
svd += 0x... |
def _is_array_type(column_type: str) -> bool:
"""
Given column_type string returns boolean value
if given string is for ArrayType.
:param column_type: string description of
column type
:return: boolean - ArrayTaype or not.
"""
if column_type.find("array<") == -1:
return Fals... |
def mapping_completeness_frequency(x, volatiliyTime, performanceSample):
"""
Mapping Function for completeness_frequency, it returns the new line containing the found value of the Completeness_Frequency dimension, or a fake line that will be eliminated if there is only 1 record for the considered grouping value... |
def select_test_metrics(metrics, data):
"""
Util function to check which subset of the provided test metrics is available in the current data dictionary
"""
found = False
eval_metrics = []
for metric in metrics:
if metric in data.keys():
eval_metrics.append(metric)
... |
def getChannelsFromProductPlists(products):
"""Takes a list of product plist objects and returns a dict of
channels and what each is an update_for."""
channels = {}
for product in products:
for channel in product['channels']:
if not channel in channels.keys():
channel... |
def sum_abs_of_all(sequence):
"""
What comes in:
-- A sequence of numbers.
What goes out:
Returns the sum of the absolute values of the numbers.
Side effects: None.
Examples:
sum_all([5, -1, 10, 4, -33])
would return 5 + 1 + 10 + 4 + 33, which is 53
sum_all([10, -... |
def version_bumped(prev_version, new_version):
"""Check version in master branch."""
x0, y0, z0 = map(int, prev_version.split("."))
x, y, z = map(int, new_version.split("."))
return z0 != z |
def clean_string(string, remove_parenthesis=False, remove_brackets=False):
"""
Return given string that is strip, uppercase without multiple whitespaces. Optionally, remove parenthesis and brackets. Note that "\t\n\s" will be removed
Parameters
----------
string : str
String to clean
re... |
def get_n_grams(text, n):
"""
Computes the n-grams of a given text
:rtype : list
:param text: The text provided
:param n: The n of n-grams
:return: List of all the word's n-grams
"""
# returning the list of n-grams
return [text[i:i+n] for i in range(len(text) - n + 1)] |
def byte_str(object):
"""bytes to str, str to bytes"""
if isinstance(object, str):
return object.encode(encoding="utf-8")
elif isinstance(object, bytes):
return bytes.decode(object)
else:
print(type(object)) |
def present_query(*args, **kwags):
"""
A query returning something that is in the DB
"""
response = {
'responseHeader': {'params': {'rows': 1}},
'response': {
'numFound': 1,
'docs': [{
'id': 'abcde',
'checks... |
def weight(alpha, beta, x):
"""The weight function of the jacobi polynomials for a given alpha, beta value."""
one_minus_x = 1 - x
return (one_minus_x ** alpha) * (one_minus_x ** beta) |
def stiefel_params(n_samples):
"""Generate stiefel benchmarking parameters.
Parameters
----------
n_samples : int
Number of samples to be used.
Returns
-------
_ : list.
List of params.
"""
manifold = "Stiefel"
manifold_args = [(3, 2), (4, 3)]
module = "geom... |
def get_lw_grism_tso_intermeidate_aperture(aperture):
"""Grism time series observations use an intermediate aperture in
order to place the undispersed target at the correct location such
that, once the grism is in the beam, the trace lands at row 34 on
the detector. In the APT pointing file, the request... |
def error(message, code=-1):
"""Return an error with the specified message and code."""
err = {'Error': message, 'Code': code}
return err |
def flatten_gear(gear_array):
"""the shape of the request data from the project wizard that
corresponds to the gears and process types are too deeply nested
and need to be flattened to match the other data elements. This
function takes the deeply nested dict and flattens each one into a
dictionary ... |
def _update_atomic_actions(atomic_actions, started_at):
"""Convert atomic actions in old format to latest one."""
new = []
for name, duration in atomic_actions.items():
finished_at = started_at + duration
new.append({
"name": name,
"started_at": started_at,
... |
def bits_to_array(num, output_size):
""" Converts a number from an integer to an array of bits
"""
##list(map(int,bin(mushroom)[2:].zfill(output_size)))
bit_array = []
for i in range(output_size - 1, -1, -1):
bit_array.append((num & (1 << i)) >> i)
return bit_array |
def format_evaluation(results, separator=" | ", float_format="{:.5f}"):
"""Construct a string to neatly display the results of a model evaluation
Parameters
----------
results: Dict
The results of a model evaluation, in which keys represent the dataset type evaluated, and
values are d... |
def validate_bool_arg(args, name):
"""Validate a boolean argument."""
value = args.get(name) if isinstance(args, dict) else args
if not value:
return False
if value.lower() in ('n', 'no', '0', 'off', 'disabled'):
return False
elif value.lower() in ('y', 'yes', '1', 'on', 'enabled'):
... |
def isoperator(x):
"""
Returns `True` if the given object implements the required attributes for
an operator.
Returns:
bool
"""
return all(
hasattr(x, name) for name in ('run', 'operators', 'kind', '__class__')
) |
def wkt2json(wktGeometryList):
"""converts a list of WKT-Geometrys (Boudingbox) to a list of GeoJSON geometries
:param wktGeometryList List containing WKT-Geometry boundingboxes and their ID
:returns: list of GeoJSON boudingboxes with their HTML ID as property and an empty color property
"""
# first... |
def _parse_query_string(query):
"""Used for replacing cgi.parse_qsl.
The cgi version returns the same pair for query 'key'
and query 'key=', so reconstruction
maps to the same string. But some sites does not handle both versions
in the same way.
This version returns (key, None) in the first case... |
def diff(a, b):
"""Get a diff -object of 'a' to 'b'
Given, the a and b..
a = { "id": 1, name:"My name", args: [ 1, 2 ] }
b = { "id": 2, name:"Your name", args: [ 2, 3 ] }
.. the diff is:
diff(a, b) = {
"name": [ "My Name", "Your name" ],
"args": [ [ 1, 2... |
def flatten_lists(lists):
"""
flatten lists to 1d
"""
flatten_list = []
for temp in lists:
if type(temp) == list:
flatten_list += temp
else:
flatten_list.append(temp)
return flatten_list |
def str_to_disp(s):
"""Convert a string to a user-friendly, displayable string by replacing
underscores with spaces and trimming outer whitespace.
Args:
s: String to make displayable.
Returns:
New, converted string.
"""
return s.replace("_", " ").strip() |
def base64_len(s):
"""Return the length of s when it is encoded with base64."""
groups_of_3, leftover = divmod(len(s), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
# Thanks, Tim!
n = groups_of_3 * 4
if leftover:
n += 4
return n |
def phase1(l, sum):
"""
instead of jumping from start to end, since this is an ordered list
we place a pointer to the beginning of the list and another one to the end
then, if the sum of both numbers is higher than "sum" we decrease the higher index by one
if the sum is lower than "sum" we increase ... |
def wrdvi(nir, red, alpha=0.1):
"""
Compute Wide Dynamic Range Vegetation Index from red and NIR bands
WRDVI = \\frac { \\alpha NIR - RED } {\\alpha NIR + RED }
:param nir: Near-Infrared band
:param red: Red band
:param alpha: Weighting coefficient, usually in [0.1-0.2]
:ret... |
def _get_ipv4_from_dnsrecords(dnsrecords):
"""
Find the A record in dns records, and return tuple (id, address).
"""
for rec in dnsrecords:
if 'type' in rec:
if rec['type'] == 'A':
return (rec['id'], rec['content'])
return (None, None) |
def find_changelogs(session, name, candidates):
"""
Tries to find changelogs on the given URL candidates
:param session: requests Session instance
:param name: str, project name
:param candidates: list, URL candidates
:return: tuple, (set(changelog URLs), set(repo URLs))
"""
return set()... |
def removeprefix(string: str, prefix: str) -> str:
"""Remove prefix from string, if present."""
return string[len(prefix) :] if string.startswith(prefix) else string |
def bubblesort(x, count = False):
"""
For each element e in x, compare it to its right neighbor. If e is larger,
switch them. Continue until you reach the end of the array or a larger value.
"""
assignments = 0
conditionals = 0
for i in range(len(x)-1):
for j in range(len(x)-1):
... |
def to_camel(string: str):
"""Schema helper function to export models with camelCase properties."""
pascal_cased = ''.join(word.capitalize() for word in string.split('_'))
return f'{pascal_cased[0].lower()}{pascal_cased[1:]}' |
def generate_desc(joinf, result):
"""
Generates the text description of the test represented by result
"""
if type(result) is frozenset:
ret = sorted([generate_desc(joinf, i) for i in result])
return '{' + ' '.join(ret) + '}'
elif type(result) is tuple:
(item, children) = res... |
def merge(a, b):
"""
@param a: a list
@param b: a list
@return: a and b list merged
"""
return list(a) + list (b) |
def rivers_with_station(stations):
"""input of list of monitoring station type. Output a set of rivers which have stations."""
riverstation = set() #initialise set
for i in stations:
riverstation.add(i.river) #adds river name to set for every station
return riverstation |
def compute_percent_id(seq_1, seq_2):
"""Return % identity for two sequences."""
assert len(seq_1) == len(seq_2) # otherwise it is a bug
matches = sum([1 for i in range(len(seq_1))
if seq_1[i] == seq_2[i]
and seq_1[i] != "N"
and seq_2[i] != "N"
... |
def generate_initials(name, max_initials=2):
"""
Generates initials for a person's or organization's name.
Name can be a string or list. If inputted as a list, input names in desired order of
initials, such as [first, last]. If an element of that list has multiple names
(e.g. a middle name or multi... |
def bubble_sort(arrayParam):
"""
Sort a list using bubble sort algorithm. Run time: O(n**2)
"""
done = True
array = arrayParam[:]
for l in range(1, len(array)):
if array[l] < array[l - 1]:
done = False
if done == True:
return array
while done ... |
def count_collisions(point_vector, n, k, t, s):
"""
As the name says, count the number of wall collisions of n ball in t seconds in the box of dimensions
2s x 2s. To avoid division by zero, vx and vy should be checked if they are zero.
Function basically counts the collisions for vx and vy separately, a... |
def truncate(phrase, n):
"""Return truncated-at-n-chars version of phrase.
If the phrase is longer than, or the same size as, n make sure it ends with '...' and is no
longer than n.
>>> truncate("Hello World", 6)
'Hel...'
>>> truncate("Problem solving is the best!", 10)
'... |
def doc_view(request):
"""View for documentation route."""
return {
'page': 'Documentation'
} |
def decode_list_index(list_index: bytes) -> int:
"""Decode an index for lists in a key path from bytes."""
return int.from_bytes(list_index, byteorder='big') |
def format_filename(prefix, suffix, seq_len, uncased):
"""Format the name of the tfrecord/meta file."""
seq_str = "seq-{}".format(seq_len)
if uncased:
case_str = "uncased"
else:
case_str = "cased"
file_name = "{}.{}.{}.{}".format(prefix, seq_str, case_str, suffix)
return file_name |
def find_first(combination, idx):
"""finds the next non null element in the combination sequence whose first
element matches the index"""
for fc_idx, fc_set in enumerate(combination):
if fc_set is None:
continue
if idx == fc_set[0]:
return fc_idx
elif idx in f... |
def batch_files(pool_size, limit):
""" Create batches of files to process by a multiprocessing Pool """
batch_size = limit // pool_size
filenames = []
for i in range(pool_size):
batch = []
for j in range(i*batch_size, (i+1)*batch_size):
filename = 'numbers/numbers_%d.t... |
def get_phase_left_without_stop_codon(dct):
""" get the phase on the left with correct frame """
correct_ones = list()
for phase_left in range(0,3):
pep_phased, dna_leftover_left, dna_leftover_right = dct[phase_left]
if not "*" in pep_phased:
correct_ones.append(phase_left)
r... |
def is_factor(i, x):
""" returns True if i is a factor or x """
return x % i == 0 |
def trapezoid_area(base_minor, base_major, height):
"""Returns the area of a trapezoid"""
area = ((base_minor + base_major) / 2) * height
return area |
def DeepSupervision(criterion, xs, y):
"""DeepSupervision
Applies criterion to each element in a list.
Args:
criterion: loss function
xs: tuple of inputs
y: ground truth
"""
loss = 0.
for i in range(len(xs)):
loss += criterion(xs[i], y)
# loss = 0.
# ... |
def _is_a_vertex_of_polygon(x, y, polygon):
"""
Check if the `x`/`y` coordinate is a vertex of the `polygon`.
>>> polygon = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0))
>>> _is_a_vertex_of_polygon(0.0, 0.0, polygon)
True
>>> _is_a_vertex_of_polygon(0.5, 0.5, polygon)
... |
def search_value(array, origin_key, origin_value, dest_key):
""" given origin key and value,search dest_value form array by dest_key
>>> d = [{"UHostId": "foo", "Name": "testing"}]
>>> search_value(d, "Name", "testing", "UHostId")
'foo'
"""
arr = [i.get(dest_key, "") for i in array if i[origin_... |
def _MakeDispatchListIntoYaml(application, dispatch_list):
"""Converts list of DispatchEntry objects into a YAML string."""
statements = []
if application:
statements.append('application: %s' % application)
statements.append('dispatch:')
for entry in dispatch_list:
statements += entry.ToYaml()
retur... |
def is_string_or_null(val):
"""Checks if value is string or empty
Args:
val (str)
Returns:
bool: True if successful, False otherwise
"""
if val is None:
return True
return isinstance(val, str) |
def re_word_boundary(r: str) -> str:
"""
Adds word boundary characters to the start and end of an
expression to require that the match occur as a whole word,
but do so respecting the fact that strings starting or ending
with non-word characters will change word boundaries.
"""
# we can't use... |
def bCallbackEvent(dataset, colors):
"""Callback to set initial value of blue slider from dict.
Positional arguments:
dataset -- Currently selected dataset.
colors -- Dictionary containing the color values.
"""
colorsDict = colors
try:
colorVal = colorsDict[dataset][4:-1].split(',')... |
def rgbToHex(rgb_color):
"""Converts a RGB tuple to a hex color string"""
r, g, b = rgb_color
return '#{:02x}{:02x}{:02x}'.format(r, g, b) |
def clean_string(s: str, extra_chars: str = ""):
"""Method to replace various chars with an underscore and remove leading and trailing whitespace
Parameters
----------
s : str
string to clean
extra_chars : str, optional
additional characrters to be replaced by an underscore
Ret... |
def _pretty_hex(value, width=None):
"""
Return a value of width bits as a pretty hexadecimal formatted string.
"""
if value is None:
return 'Undefined'
if width is None:
return '{0:#x}'.format(value)
width = (width + 3) // 4
hex_str = "{{0:#0{0:d}x}}".format(width + 2)
re... |
def capitalize(name):
""" Return a capitalized version of name for use in ifndef/define
"""
return name.replace(':', '_') |
def print_write(string: str, file):
"""
Write text in a text file with printing in the console.
:param string: string to write
:param file: text file
:return: True
"""
print(string, file=file)
print(string)
return True |
def clear_ui_items(*items):
"""Attempts to call 'deleteMe()' on every item provided. Returns True if all deletions are a success"""
return all([item.deleteMe() for item in items if item is not None]) |
def get_model_name(npz_path):
"""Get the victim model name from npz file path."""
if 'dgcnn' in npz_path.lower():
return 'dgcnn'
if 'pointconv' in npz_path.lower():
return 'pointconv'
if 'pointnet2' in npz_path.lower():
return 'pointnet2'
if 'pointnet' in npz_path.lower():
... |
def execute_walk_callback(count, filepath, callback, *kargs, **kwargs):
"""
Execute the callback function adding the file path to its argument list.
Increments the file counter and returns it.
NB: the callback function must be defined with the filepath argument.
"""
kwargs["filepath"] = filepath... |
def tokenize(text):
"""this function is to tokenize the headline into a list of individual words"""
return text.split(" ") |
def csv_path(name):
"""
Shortcut function to get the relative path to the directory
which contains the CSV data.
"""
return "./data/%s" % name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.