content stringlengths 42 6.51k |
|---|
def should_print_row(i: int, max_entries: int, num_entries: int):
"""Make decision to print row or not based on max_rows.
:param i: index of row
:type i: int
:param max_entries: max number of entries for the table
:type max_entries: int
:param num_entries: number of possible entries (the full l... |
def normalize_extended_facility_id(facility_id):
"""
Manually confirmed matches are added to the list of canonical
facilities with a synthetic ID. This function converts one of these
extended IDs back to a plain Facility ID. A plain Facility ID will pass
through this function unc... |
def op_ifthenelse(x):
"""Returns branches depending on whether the first element of a vector is truthy."""
if isinstance(x, list) and len(x) == 3:
return x[1] if x[0] else x[2]
raise ArithmeticError("`ifthenelse` is only supported for 3-dimensional vectors") |
def sandhiSplit( x):
""" method sandhiSplit
'x' is a string
From a given input string, generate an array of strings.
The even elements (0,2,4...) of the array have value
"s" if the next array element is a string of Sanskrit characters
"o" if the next array element is a string of other non-Sanskrit character... |
def count_consonants(string):
""" Function which returns the count of
all consonants in the string \"string\" """
consonants = "bcdfghjklmnpqrstvwxz"
counter = 0
if string:
for ch in string.lower():
if ch in consonants:
counter += 1
return counter |
def merge_parser_lists(this, that, kind):
""" Merge two lists containing parsers. """
if isinstance(this, kind):
if isinstance(that, kind):
return this.parsers + that.parsers
else:
return this.parsers + [that]
else:
if isinstance(that, kind):
retur... |
def add(x, y):
"""Adds two vectors x and y.
Args:
x: The first summand.
y: The right summand.
Returns:
The result is the vector z for which z_i = x_i + y_i holds.
"""
result = []
for i, x_i in enumerate(x):
result.append(x_i + y[i])
return result |
def commaSplitNum(num: str) -> str:
"""Insert commas into every third position in a string.
For example: "3" -> "3", "30000" -> "30,000", and "561928301" -> "561,928,301"
:param str num: string to insert commas into. probably just containing digits
:return: num, but split with commas at every third dig... |
def get_state(person):
"""Feed a person dict return the state only"""
return person['state'] |
def not_null(value):
"""A validation function that checks that a value isn't None."""
return True if value is not None else False |
def clean_description(text: str) -> str:
"""Clean description of characters to improve tokenization.
:param text:
Description text to clean
:return:
Cleaned description text
"""
text = text.replace("\n", " ")
text = text.replace("\t", " ")
text = text.lower()
return tex... |
def len4bytes(v1, v2, v3, v4):
"""Return the packet body length when represented on 4 bytes"""
return (v1 << 24) | (v2 << 16) | (v3 << 8) | v4 |
def is_jquery_not_defined_error(msg):
"""
Check whether the JavaScript error message is due to jQuery not
being available.
"""
# Firefox: '$ is not defined'
# Chrome: 'unknown error: $ is not defined'
# PhantomJS: JSON with 'Can't find variable: $'
return any(txt in msg for txt in (
... |
def sum_of_squares(limit):
""" Returns the sum of all squares in the range 1 up to and including limit. """
return sum([i ** 2 for i in range(limit+1)]) |
def length(iterator):
"""A length function for iterators
Returns the number of items in the specified iterator. Note that this
function consumes the iterator in the process.
"""
return sum(1 for _item in iterator) |
def split(history: str) -> list:
"""
Splits history by specific keyword and removes leading '/'
:param history: String
:return: [String]
"""
return [his[1:] if his[0:1] == '/' else his for his in history.split('-')] |
def hop_to_str(offset):
"""
Formats a two-character string that uniquely identifies the hop offset.
>>> hop_to_str([-3, 0])
'L3'
>>> hop_to_str([1, 0])
'R1'
>>> hop_to_str([0, -2])
'T2'
>>> hop_to_str([0, +7])
'B7'
"""
# Zero offsets are not allowed
assert offset[0]... |
def get_sample_type(sample, bio_type):
"""
input: sample dictionary from BALSAMIC's config file
output: list of sample type id
"""
type_id = []
for sample_id in sample:
if sample[sample_id]["type"] == bio_type:
type_id.append(sample_id)
return type_id |
def intersect(range1, range2):
"""
Args:
range1(int, int): [begin, end)
range2(int, int): [begin, end)
"""
if range1[0] <= range2[0] < range1[1]:
return True
elif range1[0] < range2[1] <= range1[1]:
return True
elif range2[0] <= range1[0] < range2[1]:
retu... |
def calcOutputLen(outputFormat, article_len, wrd):
"""calc length of the summary. wrd is the user-specified output length or ratio"""
if outputFormat == "word_count":
return int(wrd)
else:
return article_len * float(wrd) |
def ap_at_k(preds, targets, k=10):
"""
Calculates the AP@K(Average Precision at K).
Parameters
-------------
preds : list
Predictions.
targets : list
Target (true) values.
k : int, optional
K in the MAP@K.
Returns
-------
float
AP@K.
"""
... |
def check_csv_row(data):
"""
check csv rows and add data to csv arrays.
Param post list data.
Return csv data array to download.
"""
arr_csv = []
for row in data:
if len(row) != 3:
return False
arr_csv.append(row)
return arr_csv |
def clip_count(cand_d, ref_ds):
"""Count the clip count for each ngram considering all references"""
count = 0
for m in list(cand_d.keys()):
m_w = cand_d[m]
m_max = 0
for ref in ref_ds:
if m in ref:
m_max = max(m_max, ref[m])
m_w = min(m_w, m_max)
... |
def _copy_shape_zero_rows(shape):
"""Return a copy of given shape with the number of rows zeroed out."""
temp = list(shape)
temp[0] = 0
return tuple(temp) |
def single_label_accuracies(gold, silver, test_tokens, known_tokens,
print_scores=True):
"""
Calculate accuracies for all, known and unknown tokens.
Uses index of items seen during training.
"""
kno_corr, unk_corr = 0.0, 0.0
nb_kno, nb_unk = 0.0, 0.0
for gold_pre... |
def signal_to_noise_limit_tag_from_signal_to_noise_limit(signal_to_noise_limit):
"""Generate a signal to noise limit tag, to customize phase names based on limiting the signal to noise ratio of
the dataset being fitted.
This changes the phase name 'phase_name' as follows:
signal_to_noise_limit = None ... |
def stripNamespace(nodeName):
"""Strip all the namespaces from a given name
Args:
nodeName (str): Node name to strip the namespaces
Returns:
str: Node name without namespace
"""
return nodeName.split(":")[-1] |
def build_group_clause(group_by):
"""Build group_by clause for a query."""
if not group_by:
return ''
if not isinstance(group_by, (tuple, list)):
group_by = (group_by,)
return 'GROUP BY %s' % ', '.join(group_by) |
def merge(a, b, path=None): # pylint: disable=invalid-name
"""Recursively merges dict b into dict a."""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
... |
def print_molecule_swap(swap):
"""Return a swap for DL CONTROL output"""
return "{} {}".format(swap["id1"], swap["id2"]) |
def is_inside_relative_range(value, ref_value, pct):
"""
Parameters
----------
value : numeric
ref_value : numeric
pct : numeric
pct should be smaller than 1.
Returns
-------
boolean
"""
if ref_value * (1 - pct) <= value <= ref_value * (1 + pct):
return True... |
def get_datatype(data):
"""
rules defining the sidtype, based on the data dict of the sid.
The keys are always given.
The values can be empty.
:param data:
:return:
"""
subtype = "project"
if "entity" in data.keys():
subtype = "entity"
if data.get("type"):
subt... |
def trimPerimeter(arr):
"""remove a 'border' of data from a 2d array"""
out = arr[1:-1]
for i in range(len(out) ):
out[i] = out[i][1:-1]
return out |
def insertion_sort(array):
"""[summary]
A simple sorting algorithm that works similar to the way you sort playing cards in your hands.
The array is virtually split into a sorted and an unsorted part.
Values from the unsorted part are picked and placed at the correct position in the sorted part.
Args... |
def make_c_string(string):
"""Render a Python string into C string literal format."""
if string == None:
return "NULL"
string = string.replace("\n", "\\n")
string = string.replace("\t", "\\t")
string = string.replace('"', '\\"')
string = string.replace("'", "\\'")
string = '"' + stri... |
def extract_fn(words):
""" Collects the trigger/action functions
from a string, by extracting the if/then phrase.
Templates:
(1) if <t>, (then) <a>
(2) <a> every time/year/month/week/day/hour <t>
(3) <a> when <t>
(4) if <t> then <a>
(5) <a> if <t>
(6) ... |
def _make_list(x):
"""Make list when it is necessary"""
if type(x) == list:
return x
return [x] |
def assert_type(value, class_or_type_or_tuple):
"""
Ensure the type of the value is as expected, then return the value.
:param value: value of any type
:param class_or_type_or_tuple: expected type
:return: value of expected type
"""
s = "%r must be %r, not %s."
if not isinstance(value, ... |
def get_year(year_string):
"""
return last 4 chars of string
"""
if year_string and len(year_string) > 3:
return year_string[:4]
else:
return "" |
def capitalize(string, Nfirst=1):
"""
Returns same string but with first Nfirst letters upper
Parameters
----------
string: (str)
Nfirst: (int)
Returns
-------
str
"""
return string[:Nfirst].upper() + string[Nfirst:] |
def get_test_result(nlu_result):
"""
get test elements from nlu result
"""
result = {}
result['entities'] = []
result['intent'] = nlu_result['intent']['name']
for d in nlu_result['entities']:
result['entities'].append({'entity':d['entity'], 'value':d['value']})
return re... |
def custom_sort(pseudo):
"""
Takes three lists and return three sorted list based on prediction confidence
"""
# Unpack
pred = pseudo["pred_list"]
lab = pseudo["lab_list"]
name = pseudo["name_list"]
# Sort
sorted_list = list(zip(pred, lab, name))
sorted_list.sort(key=lambda ... |
def prune_word_vectors(wv: dict, vocab: set):
"""
Remove vectors of the words which does not appear in vocab
Args:
wv: word vectors, mapping from a string to an array of floats
vocab: set of words
Returns:
Word vectors pruned from wv
"""
# Extend the vocab to set of all... |
def normalize_query_params(param_name, value, replacements=None):
"""Turns `True`->`true`, `False`->`false` and replaces param name if needed."""
if replacements and param_name in replacements.keys():
param_name = replacements[param_name]
return param_name, 'true' if value == True else 'false' if v... |
def align(value, m):
""" Increase value to a multiple of m """
while ((value % m) != 0):
value = value + 1
return value |
def pad_up(size, factor):
"""Pad size up to a multiple of a factor"""
x = size + factor - 1
return x - (x % factor) |
def find_escape_floor(pac_mine, pac_their, scene):
"""
Find an escape floor which will save our pac from being eaten.
"""
# Shortcuts
escapes = scene['escape']
my_x = pac_mine['position'][0]
my_y = pac_mine['position'][1]
their_x = pac_their['position'][0]
their_y = pac_th... |
def get_file_name_from_path(path):
"""
Given a file path, returns the file's name.
str -> str
"""
return path.split('\\')[-1].split('.')[0] |
def chainit(list_of_items):
"""Chains different hyperparameter settings."""
result = []
for items in list_of_items:
result.extend(items)
return result |
def vidgen_to_binary(label: str) -> str:
"""
Map Vidgen labels to multiclass.
:label (str): Raw label.
:return (str): Mapped label.
"""
positive = ['entity_directed_hostility', 'counter_speech', 'discussion_of_eastasian_prejudice',
'entity_directed_criticism']
if label in po... |
def _generate_tbl_filename(table_name, output_format):
"""Generate the filename fot the given table.
Generate the filename based on the specified table name and format to
export data.
table_name[in] Qualified table name (i.e., <db name>.<table name>).
output_format[in] Output format to expo... |
def findnextpointing(starttime, record, etime=None):
"""The next pointing occurs either when the next point to target
command happens
"""
for r in record:
if (r[0]==3 or r[0]==10) and r[1]>starttime: return r[1]
return etime |
def divrem(numerator, divisor):
"""Return the quotient and remainder of numerator / divisor"""
return (numerator // divisor, numerator % divisor) |
def parseSerialNumber(ManuDataHexStr):
"""
Parses the serial number from a hex string
"""
if (ManuDataHexStr == "None"):
SN = "Unknown"
else:
ManuData = bytearray.fromhex(ManuDataHexStr)
if (((ManuData[1] << 8) | ManuData[0]) == 0x0334):
SN = ManuData[2]
... |
def is_translator(permission):
"""
based on settings.CMS_CONTEXT_PERMISSIONS
given a permission code (int)
returns a dict{} with translator permission info
"""
if not permission > 0: return {}
allow_descendant = True if permission > 1 else False
return {'only_created_by': False,
... |
def union_intervals(intervals):
"""Size of the union of a set of intervals
:param intervals: list or set of integer pairs (left, right)
:returns: size of the union of those intervals
:complexity: :math:`O(n \\log n)`
"""
furthest = float('-inf') # furthest interval endpoint seen so far
len... |
def get_stride_sequence(stride_desc):
"""
Return the sequence of the secondary structure.
Parameters
----------
stride_desc : list of (str, str, float, float, float)
The Stride description.
Returns
-------
sequence : list of str
The secondary structure sequence.
"""... |
def flatten(l, types=None, base_type=None):
"""Given a list, return a recursively flattened version
Parameters
----------
l:
Iterable to flatten
types: type or tuple of types, optional
By default all non-list types are preserved as is, but you could specify
other iterable types (e... |
def _correct_phase_wrap(ha):
"""Ensure hour angle is between -180 and 180 degrees.
Parameters
----------
ha : np.ndarray or float
Hour angle in degrees.
Returns
-------
out : same as ha
Hour angle between -180 and 180 degrees.
"""
return ((ha + 180.0) % 360.0) - 180... |
def align_up(offset, align):
"""Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3
"""
remain = offset % align
if ... |
def flatlist(inlist):
"""Convert list of tuples into a list expanded by concatenating tuples"""
outlist = []
for r in inlist:
for x in r:
outlist.append(x)
return outlist |
def total_reliability(features):
"""
Calculates the total reliability of the features.
Parameters
----------
features : dictionary
a dictionary of features with keys as feature name and values as objects of
feature class.
Returns
-------
total_rel :... |
def SPUR(N, A):
"""
SPUR trac or spur of the diagonal elements of a matrix n x n
p. 49
SP = SPUR(N, A)
"""
SP = 0.0
for I in range(N):
II = I + I * N
SP += A[II]
return SP |
def create_weaviate_import_obj(line_obj):
"""
Creates an import objects that fits a Weaviatae
Returns
--------
dict
Object that fits the Weaviate import model
"""
weaviate_import_object = []
# check if entity, else it is a label
if "entity_url" in line_obj:
weaviate... |
def intersection(rect1, rect2):
"""
Calculates square of intersection of two rectangles
rect: list with coords of top-right and left-boom corners [x1,y1,x2,y2]
return: square of intersection
"""
x_overlap = max(0, min(rect1[2], rect2[2]) - max(rect1[0], rect2[0]));
y_overlap = max(0, min(rec... |
def username_cleaner(username: str) -> str:
"""Strips @ symbol from a username.
Example:
@dgnsrekt -> dgnsrekt
Args:
username: username with @ symbol to remove.
Returns:
Username with @ symbol stripped.
"""
return username.replace("@", "") |
def nextPermutation(array):
"""
Function for next Permutation
It rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it will rearrange it as the lowest possible order (i.e., sorted in ascending order).
""... |
def rol(byte, count):
"""
This method will left shift the byte left by count
Args:
byte: the byte to rol
count: The numerical amount to shift by. Needs to be an int
and greater or equal to 0
Return:
The byte shifted
"""
if count < 0:
raise ValueError('coun... |
def prettified_data(data, line_prefix='\t'):
"""Return the given data, formatted as string"""
data_prefix = '\n\t'+line_prefix
return data_prefix + data_prefix.join(str(l) for l in data) |
def day(string):
"""
converts day of week to number category
"""
string = string.lower()
days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
dayNumber = days.index(string) + 1
return dayNumber |
def log10(val):
"""
Equivalent to ceil(log(val) / log(10))
"""
result = 0
while val > 1:
result = result + 1
val = val / 10
if result:
return result
return 1 |
def memoize(f):
""" Memoization decorator for functions taking one or more arguments. """
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
... |
def validate(lat, lon):
"""Validate the lat and lon values,
return bool for validity
"""
try:
lat_in_ak_bbox = 51.229 <= float(lat) <= 71.3526
lon_in_ak_bbox = -179.1506 <= float(lon) <= -129.9795
valid = lat_in_ak_bbox and lon_in_ak_bbox
except ValueError:
valid = Fa... |
def removeDuplicatesFrom2DList(_list, column_no = 3):
"""
delete duplicates based on the column no
returns a list
deletes dupes in a 2D-csv like list;
"""
ulist = []
newlist = []
dupecount = 0
for line in _list:
if line[column_no] in ulist:
# don't write this ent... |
def handle_combined_input(args):
"""Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting.
"""
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
... |
def is_safe(func_str):
"""
Verifies that a string is safe to be passed to exec in the context of an
equation.
:param func_str: The function to be checked
:type func_str: string
:return: Whether the string is of the expected format for an equation
:rtype: bool
"""
# Remove whitespac... |
def map_graphql_args_to_api_filters(args):
"""
Maps the GraphQL query arguments to the corresponding
query string filters accepted by the Tenor API.
"""
mapped_filters = {}
# At the moment, only the 'query' parameter has to be mapped
# to the key 'q' which is acceptable by the Tenor API. N... |
def split_pem(s):
"""
Split PEM objects. Useful to process concatenated certificates.
"""
pem_strings = []
while s != b"":
start_idx = s.find(b"-----BEGIN")
if start_idx == -1:
break
end_idx = s.find(b"-----END")
end_idx = s.find(b"\n", end_idx) + 1
... |
def describe_humidity(humidity):
"""Convert relative humidity into good/bad description."""
# description str will be used to fetch the humidity's icon
if 40 < humidity < 60:
# description = "good"
description = "ok"
else:
# description = "bad"
description = "high"
re... |
def CalculateHeatFluxVector(c_v, lamb, rho, mom, e_tot, dim, dUdx):
"""Auxiliary function to calculate the heat flux vector with Fourier's law"""
# Calculate the heat flux vector (Fourier's law q = -lambda * grad(theta))
# Note that the temperature is expressed in terms of the total energy
heat_flux = ... |
def get_firstline(tokens):
"""Find first line."""
lines = ''.join(tokens).splitlines()
firstline = ''
for l in lines:
if l:
firstline = l
break
return firstline |
def skip_mul(n):
"""Return the product of n * (n - 2) * (n - 4) * ...
>>> skip_mul(5) # 5 * 3 * 1
15
>>> skip_mul(8) # 8 * 6 * 4 * 2
384
"""
if n == 1:
return 1
if n == 2:
return 2
else:
return n * skip_mul(n - 2) |
def katdal_ant_name(aips_ant_nr):
"""Return antenna name, given the AIPS antenna number"""
if aips_ant_nr < 65:
res = f'm{(aips_ant_nr-1):03d}'
else:
res = f's{(aips_ant_nr-65):04d}'
return res |
def change_dict(base, del_keys=(), **kwargs):
"""
returns the dictionary base less del_keys and with all kwargs
added.
This is a convenience function for the hypotheses that often have
to futz around with the criteria dicts. base itself is unchanged.
:param base:
:param del_keys:
:par... |
def nbits(val):
"""Return number of bits set to 1 in n"""
n = 0
while val:
if val & 1:
n += 1
val >>= 1
return n |
def is_linear(cigar_tuple):
"""
Whether end of alignment segment is a linear end
Parameters
-----
cigar_tuple : tuple of cigar
Returns
-----
int
1 for linear end, 0 for ambiguous end
"""
if cigar_tuple[0] == 0 and cigar_tuple[1] >= 5:
return 1
else:
... |
def centerpoint(geolocations):
"""
:param geolocations: array of arrays in the form of [[longitude, latitude],[longitude,latitude]]
:return: average latitude and longitude in the form [latitude, longitude]
"""
lats = []
lngs = []
for lon, lat in geolocations:
lats.append(lat)
... |
def to_name(value):
"""
Replace all underscores with space, and only take first path when with relationship
So first_name becomes first name
And company.name becomes company
"""
return value.split('.')[0].replace('_', ' ') |
def check_input_dir(indir):
"""
Check that the given indir doesn't have a trailing `/`.
Possibly useless if better way to handle this in Python.
Parameters
----------
indir: str or path
A string or path that might (or not) end with a `/`
Returns
-------
indir: str or path
... |
def set_count(items):
"""
This is similar to "set", but this just creates a list with values.
The list will be ordered from most frequent down.
Example:
>>> inventory = ['apple', 'lemon', 'apple', 'orange', 'lemon', 'lemon']
>>> set_count(inventory)
[('lemon', 3), ('apple', 2), ... |
def percentage_assembly_length(c_len, total_assembly_length):
"""
Returns the percentage of total assembly length
covered by this contig.
Args:
c_len:
total_assembly_length:
Returns:
"""
pct_of_total = c_len / total_assembly_length
return pct_of_total |
def get_int_from_str(string):
"""
get an integer from a given string. Return 0 if not found
"""
result = ''
for s in string:
if s.isdigit():
result += s
try:
ans = int(result)
return ans
except:
# print("no digit found in given string: %s" % string... |
def yahoo_ex_remove(yahoo_ex: str) -> str:
"""
convert yahoo exchange to exchange code
"""
# 1min, 5min, 15min, 30min, 60min, daily, weekly, monthly
# split content before and after the .
# for canadian stonks
# check if yahoo_ex has .
if yahoo_ex is None:
return yahoo_ex
... |
def ib64_patched(self, attrsD, contentparams):
""" Patch isBase64 to prevent Base64 encoding of JSON content
"""
if attrsD.get('mode', '') == 'base64':
return 0
if self.contentparams['type'].startswith('text/'):
return 0
if self.contentparams['type'].endswith('+xml'):
return ... |
def adelle_qnuc(xbar):
"""Returns Qnuc (MeV/nucleon) according to Adelle et al. (2018)
"""
return 1.305 + (6.9511 * xbar) - (1.9218 * xbar**2) |
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) // int(b) |
def isX( ch ):
""" Is the given character an x?"""
return ch == 'x' or ch == 'X' |
def three_list_to_string(three_list):
"""
Util: concatenates three lists into a single string
:param three_list:
:return:
"""
content = ''
for element in three_list:
for x in element:
for y in x:
content += str(y) + ','
content = content[:-1]
... |
def scale(val, old_scale, new_scale=100):
""" Change scale of a value
:param val: value
:param old_scale: current scale max value
:param new_scale: new scale max value
:return: value converted to new scale """
return float(val * new_scale) / old_scale |
def get_payment_id_from_tx_extra_nonce(extra_nonce):
"""
Extracts encrypted payment id from extra
:param extra_nonce:
:return:
"""
if 33 != len(extra_nonce):
raise ValueError("Nonce size mismatch")
if 0x0 != extra_nonce[0]:
raise ValueError("Nonce payment type invalid")
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.