content stringlengths 42 6.51k |
|---|
def process_enclitics(word):
"""
Input: Word with dash and enclitic - only handles enclitics, not i-ii or a-ang
Output: Concatenated word with enclitic and removal of dash
"""
items = word.split('-')
if len(items) > 2:
raise ValueError('not yet able to process more than one dash')
if items[1] == '2u':
word =... |
def get_data(wavs, id_to_text, maxlen=50):
"""returns mapping of audio paths and transcription texts"""
data = []
for w in wavs:
id = w.split("/")[-1].split(".")[0]
if len(id_to_text[id]) < maxlen:
data.append({"audio": w, "text": id_to_text[id]})
return data |
def temp_to_hex(value: int) -> str:
"""Convert an int to a 2-byte hex string."""
if value is None:
return "7FFF" # or: "31FF"?
if value is False:
return "7EFF"
temp = int(value * 100)
if temp < 0:
temp += 2 ** 16
return f"{temp:04X}" |
def controlcharacter_check(glyph: str):
"""
Checks if glyph is controlcharacter (unicodedata cant handle CC as input)
:param glyph: unicode glyph
:return:
"""
if len(glyph) == 1 and (ord(glyph) < int(0x001F) or int(0x007F) <= ord(glyph) <= int(0x009F)):
return True
else:
retu... |
def toggle_modal(n1, n2, is_open):
""" Callback for the modal (open/close)
"""
if n1 or n2:
return not is_open
return is_open |
def rescale(X, lo, hi, new_lo, new_hi):
"""
>>> rescale(0, 0, 1, 0, 1)
0.0
>>> rescale(1, 0, 1, 0, 1)
1.0
>>> rescale(0, -.5, .5, 0, 1)
0.5
>>> rescale(0.0, -1, 1, 1, 10)
5.5
"""
return (X-lo) / (hi-lo) * (new_hi - new_lo) + new_lo |
def decorate(rvecs):
"""Output range vectors into some desired string format"""
return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs]) |
def get_officer_uid(in_data):
"""
Extracts an officer's unique identifier from an officer record.
Unfortunately, lots of officers have lots of these, but the function is
occasionally useful all the same.
"""
if 'self' in in_data['links']:
uid = in_data['links']['self'].split("/")[... |
def has_prefix(sub_s, word_d):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:param word_d: the dictionary
:return: (bool) If there is any words with prefix stored in sub_s
"""
for word in word_d:
if word.startswith(sub_s):
return True
return False |
def classify_variant(variant):
""" does what it says on the tin """
var_size = abs(len(variant['ALT']) - len(variant['REF']))
alt_len = len(variant['ALT'])
ref_len = len(variant['REF'])
# SNPs are size zero
if var_size == 0:
return 'snp', var_size
# An ALT smaller than REF is a de... |
def unit_form(disc):
"""
Return generated quadratic form with the given discriminant.
"""
if disc & 3 == 0:
a = 1
b = 0
c = disc // -4
elif disc & 3 == 1:
a = 1
b = 1
c = (disc - 1) // -4
else:
raise ValueError("discriminant is not 0 or 1 m... |
def _args_from_exception(exception):
"""In Python 3 we can't guarantee that an exception will have a `message`
property. This function ensures that we can extract *args and have it
include at least one argument, regardless of the exception type passed-in.
"""
if exception.args:
return except... |
def bytes2str(bstr):
"""Convert a bytes into string."""
if type(bstr) is bytes:
return bstr.decode('utf-8')
elif type(bstr) is str:
return bstr
else:
raise TypeError(
bstr, ' should be a bytes or str but got ', type(bstr), ' instead') |
def _recover_uid(good_id) -> int:
"""
Get the uid part of the good id.
:param int good_id: the good id
:return: the uid
"""
uid = int(good_id.split("_")[-2])
return uid |
def set_dont_care(key, parkeys, dont_care):
"""Set the values of `key` named in `dont_care` to 'N/A'."""
key = list(key)
for i, name in enumerate(parkeys):
if name in dont_care:
key[i] = 'N/A'
return tuple(key) |
def mix(x, y, a):
"""Performs a linear interpolation between `x` and `y` using
`a` to weight between them. The return value is computed as
:math:`x\times a + (1-a)\times y`.
The arguments can be scalars or :class:`~taichi.Matrix`,
as long as the operation can be performed.
This function is sim... |
def get_enum_name_from_repr_str(s):
"""
when read from config, enums are converted to repr(Enum)
:param s:
:return:
"""
ename = s.split('.')[-1].split(':')[0]
if ename == 'None':
ename = None
return ename |
def syncsort(a_arr, b_arr):
"""
sorts a in ascending order (and b will tag along, so each element of b is still associated with the right element in a)
"""
a_arr, b_arr = (list(t) for t in zip(*sorted(zip(a_arr, b_arr))))
return a_arr, b_arr |
def dedup_list(lst):
"""Remove duplicate items from a list.
:param lst: List.
:returns: List with duplicate items removed from lst.
"""
return list(set(lst)) |
def get_hyperleda_radius(bmag):
"""
Get the hyperleda radius in degrees
Parameters
----------
bmag: float
The magnitude in B
Returns
-------
radius in degrees
"""
slope = -0.00824
offset = 0.147
return offset + slope * bmag |
def int_to_little_endian_bytes(integer):
"""Converts a two-bytes integer into a pair of one-byte integers using
the little-endian notation (i.e. the less significant byte first).
The `integer` input must be a 2 bytes integer, i.e. `integer` must be
greater or equal to 0 and less or equal to 65535 (0xff... |
def wavelength_to_rgb(wavelength, gamma=0.8):
"""Convert a given wavelength of light to an approximate RGB color value.
The wavelength must be given in nanometers in the range from 380 nm through 750 nm (789 THz through 400 THz).
Based on code by Dan Bruton
http://www.physics.sfasu.edu/astro/color... |
def hamming_distance(x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
n = 0
while x != 0 and y != 0:
if x % 2 != y % 2:
n += 1
x /= 2
y /= 2
m = x if x != 0 else y
if m != 0:
while m != 0:
if m % 2 == 1:
n +=... |
def removeDuplicates(objectList):
"""
Method to efficiently remove duplicates from a list and maintain their
order based on first appearance. See the url below for a description of why
this is optimal:
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-... |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
Time Complexity: O(n) where n is the number of characters between index 0 and our max_index
Space Complexity: O(n) where n is the number of items in the array h... |
def label_intersects_tags(label, tags):
"""
Primarily for use in force of infection calculation to determine whether a compartment is infectious.
Args:
label: Generally a compartment label.
tags: Tag for whether label is to be counted.
Returns:
Boolean for whether any of the tag... |
def construct_webserver_rules(entries, webserver):
"""Construct webserver redirect rules based on webserver."""
lst = []
if webserver == 'nginx':
prefix = ""
for row in entries:
lst.append(f"rewrite /{row['docType']}/{row['pid']}$ {row['url']} redirect")
else:
prefix ... |
def less_than(data: list, i: int, j: int) -> bool:
"""Check if data[i] is greater than data[j]."""
return data[i] < data[j] |
def poly_learning_rate(base_lr, curr_iter, max_iter, power=0.9):
"""poly learning rate policy"""
lr = base_lr * (1 - float(curr_iter) / max_iter)**power
return lr |
def capitalize_title(title):
"""
:param title: str title string that needs title casing
:return: str title string in title case (first letters capitalized)
"""
return title.title() |
def infer_channels_from_layout(layout, channels):
"""Extract the number of channels from the layout."""
if layout in ("TBD", "BTD"):
if channels is not None and channels != 1:
raise ValueError(
"Expected channels ({}) to be 1 for layout = {}".format(
chann... |
def reprEnum(e, typ):
""" this is a port of the nim runtime function `reprEnum` to python """
e = int(e)
n = typ["node"]
flags = int(typ["flags"])
# 1 << 2 is {ntfEnumHole}
if ((1 << 2) & flags) == 0:
o = e - int(n["sons"][0]["offset"])
if o >= 0 and 0 < int(n["len"]):
return n["sons"][o]["nam... |
def pep423_name(name):
"""Normalize package name to PEP 423 style standard."""
return name.lower().replace('_', '-') |
def insert_text(text: str) -> dict:
"""This method emulates inserting text that doesn't come from a key press,
for example an emoji keyboard or an IME.
Parameters
----------
text: str
The text to insert.
**Experimental**
"""
return {"method": "Input.insertText", "params": {... |
def labels_after_1(circle):
"""
>>> labels_after_1([8, 3, 7, 4, 1, 9, 2, 6, 5])
'92658374'
>>> circ = meh(EXAMPLE_INPUT)
>>> for m in range(100):
... circ = make_move(circ)
...
>>> labels_after_1(circ)
'67384529'
"""
n = circle.index(1)
res = circle[n+1:] + circle[:n]... |
def slistFloat(slist):
""" Converts signed list to float. """
values = [v / 60**(i) for (i,v) in enumerate(slist[1:])]
value = sum(values)
return -value if slist[0] == '-' else value |
def celsius_to_fahrenheit(celsius):
"""Convert a Celsius temperature to Fahrenheit."""
return celsius * 1.8 + 32.0 |
def rank(X):
"""
Return the rank of each element in X
"""
sorted_X = sorted(X)
rank = [0]*len(X)
for i in range(len(X)):
# since index is zero-based, plus 1 to get the rank
rank[i] = sorted_X.index(X[i]) + 1
return rank |
def _merge_tables(d1, d2):
"""
Merge dictionaries
Args:
d1 (dict): first dict to merge
d2 (dict): second dict to merge
"""
for key, l in d2.items():
if key in d1:
for item in l:
if item not in d1[key]:
d1[key].append(item)
... |
def get_vacant_groups(groups)-> dict:
"""
retrieves group numbers with vacant spots
"""
vacant_groups = {}
for group_number in groups.keys():
if len(groups[group_number]) < 6:
vacant_groups[group_number] = len(groups[group_number])
return vacant_groups |
def get_digits_matching_next(captcha, step_size=1):
"""Get digits from captcha that are matching next step_size digit."""
matching_digits = []
for index, digit in enumerate(captcha):
next_index = (index + step_size) % len(captcha)
if digit == captcha[next_index]:
matching_digits.... |
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
"""
Defines an elicit slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "ElicitSlot",
"intentName": intent_name,
... |
def poly_np(x, *coefs):
"""
f(x) = a * x + b * x**2 + c * x**3 + ...
*args = (x, a, b, ...)
"""
# Add a warning for something potentially incorrect
if len(coefs) == 0:
raise Exception("You have not provided any polynomial coefficients.")
# Calculate using a loop
result = x * 0... |
def w(b,s):
"""
Given a tic tac toe board b of arbitrary size s, determine if 1 won.
This is a helper function for e. If I wasn't trying to reduce the
character count, this function's name would begin with an
underscore, and would be called _one_won.
Board must be specified as an integer, the ... |
def quad(x):
"""
Represents the mathematical quadratic function f(x) = ((1/2)x^2) + 3.
(Quadratic function parabola)
A caller can pass this to plot() for rendering.
"""
return 1/2 * x ** 2 + 3 |
def parse_show_qos_trust(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos trust' command in a \
dictionary:
::
{
'trust': 'none'
}
"""
resu... |
def levelOrderCheck(root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = []
result = []
queueFront = queueBack = 0
if root:
queue.append(root)
queueFront += 1
result.append([root.val])
... |
def _get_grid_limits(headers):
"""
Return a two-length tuple that contains the lower limits of the grid and the upper limits of the grid.
:param headers:
The primary headers from a FERRE grid file.
"""
return (
headers["LLIMITS"],
headers["LLIMITS"] + headers["STEPS"] * (hea... |
def findSubsetTranscripts( eachinput ):
"""
"""
gene_to_transcripts, gene, transcripts_fasta = eachinput
redundant_transcripts = []
i = 0
while i < len( gene_to_transcripts[gene] ):
transcript_i = gene_to_transcripts[gene][i]
j = i + 1
while j < len( gene_to_transcripts[g... |
def parse_size(size):
"""
Converts a size specified as '800x600-fit' to a list like [800, 600]
and a string 'fit'. The strings in the error messages are really for the
developer so they don't need to be translated.
"""
first_split = size.split('-')
if len(first_split) != 2:
raise Att... |
def levenshtein(s1, s2):
"""Returns the Levenshtein distance of S1 and S2.
>>> levenshtein('aabcadcdbaba', 'aabacbaaadb')
6
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
... |
def create(width, height, fill=0):
"""Create a matrix in list format."""
return [
[fill for _ in range(width)]
for _ in range(height)
] |
def str2bool(v):
"""
Convert strings (and bytearrays) to boolean values
>>> all([str2bool(v) for v in (True, "yes", "true",
... "y", "t", "Yes", "True", "1", "on", "On")])
True
>>> all([str2bool(v.encode('utf-8'))
... for v in ("yes", "true", "y", "t", "1", "Yes", "on", "On")])
... |
def oligo_dilution_table(conc=None, sc=None):
"""Return dilution table
Determine the amount of diluent to add to an oligo based on
concentration wanted and scale ordered. This function can return the
entire dilution table or slices and values as needd
Parameters
----------
conc : str, opti... |
def exclude(list, value=["-v", "-vv", "-vvv"]):
"""
remove value from the list
"""
new = []
for item in list:
if not item in value:
new.append(item)
return new |
def get_relevant_dates(year):
""" Gets the relevant dates for the given year """
if year == 2003:
return [
"20030102", "20030203", "20030303", "20030401", "20030502", "20030603", "20030701", "20030801", "20030902",
"20031001", "20031103", "20031201",
]
# you can add ... |
def cls_2_dot_pattern(cls_name):
""" Transform all class names to the dot seperated form.
"""
if isinstance(cls_name, str):
cls_name = cls_name.replace('/', '.')
return cls_name |
def get_threads(cluster_config, rule_name='__default__'):
"""
To retrieve threads from cluster config or return default value of 8
"""
return cluster_config[rule_name]['n'] if rule_name in cluster_config else 8 |
def convert_ptb_token(token: str) -> str:
"""Convert PTB tokens to normal tokens"""
return {
"-lrb-": "(",
"-rrb-": ")",
"-lsb-": "[",
"-rsb-": "]",
"-lcb-": "{",
"-rcb-": "}",
}.get(token.lower(), token) |
def to_celsius(temp):
"""Converts temperature in Kelvin to Celsius"""
temp_in_c = round(temp-273.15)
return temp_in_c |
def gaussian(feval=False, vardict=None):
"""1D/2D Gaussian lineshape model. Returns numerical values if ``feval=True``.
**Parameters**
feval: bool | False
Option to evaluate function.
vardict: dict | None
Dictionary containing values for the variables named as follows (as dictionary ke... |
def evaluate_turns_to_wait(laid_card, turns_to_wait=0):
"""
Function used to evaluate number of turns to wait.
:param laid_card: tuple with last played card
:param turns_to_wait: integer value with earlier punishment
:return: integer value with punishment after card played
"""
value = laid_c... |
def round_to_multiple_of(val, divisor):
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
bias, will round up, i.e. (83, 8) -> 88, but (84, 8) -> 88. """
new_val = max(divisor, int(val + divisor / 2) // divisor * divisor)
return new_val if new_val >= val else new_val + divisor |
def transform_stats(values):
"""Transform the output of stats to something more manageable.
:param list values: The list of values from `SHOW STATS`
:rtype: dict
"""
output = {}
for row in values:
if row['database'] not in output:
output[row['database']] = {}
for k,... |
def isIrrelevantManualRules(s, cdoc):
"""
Hand-crafted rules to remove paragraphs or entire documents from job advertisements
:param s: String
:param cdoc: List of parts of document (String)
:returns: Boolean (ie. True if removal is needed), list of parts of documents (String), length of irrele... |
def replace_field(field, value):
""" if Retard field is not empty, replace content by retard: """
if field == 'retard':
if value is None or value == '':
return ''
else:
return 'retard :'
else:
return value |
def as_key(key):
""" Convert path to a string of of length 1 otherwise return it. """
if isinstance(key, tuple) and len(key) == 1:
return key[0]
return key |
def flatten_list(l):
""" Single-level flatten """
return [item for sublist in l for item in sublist] |
def num_events_in_event_dict(event_dict):
"""
Given an event dict, returns number of events
:param event_dict: Edge dictionary of events between all node pair. Output of the generative models.
:return: (int) number of events
"""
num_events = 0
for _, event_times in event_dict.items():
... |
def rd(v, n=100.0):
"""Round down, to the nearest even 100"""
import math
n = float(n)
return math.floor(v/n) * int(n) |
def _apply_pairwise_op_ml(op, tensor):
"""Applies the op on tensor in the pairwise manner."""
# _check_tensor_shapes([tensor])
rval = op(tensor, tensor)
return rval
# return op(tf.expand_dims(tensor, 2), tf.expand_dims(tensor, 1)) |
def _convert(s,t):
""" This helper routine does a hard type conversion to a boolean.
"""
try:
return s.astype('bool'), t.astype('bool')
except:
return s,t |
def rescale(maxabsval, strval):
"""Force labels to 1.0e-3 boundary which contains maxabsval
:param double maxabsval: absolute value on axis
:param str strval: units
:return (multiplier, strval): axis multiplier, axis label
"""
mult = 1
if maxabsval>=1.0e2 and maxabsval<1.0e5:
mult = ... |
def _ExtractDwValue(line):
"""Extract DW_AT_ value from dwarfdump stdout.
Examples:
DW_AT_name ("foo.cc")
DW_AT_decl_line (177)
DW_AT_low_pc (0x2)
"""
lparen_index = line.rfind('(')
if lparen_index < 0:
return None
rparen_index = line.find(')', lparen_index + 1)
if rparen_index < 0:
return ... |
def _empty_or_comment_(line):
"""helper method for extracting a line"""
return line is None or len(line.strip()) < 1 or line.strip().startswith("#") |
def twoNumberSum_2(array, targetSum):
"""
Space complexity: O(1) => using array in place
Time complexity: O(n log n) => due to array.sort
"""
# Sort array in-place
array.sort()
left, right = 0, len(array)-1
while left < right:
l, r = array[left], array[right]
current_sum... |
def gf_add_ground(f, a, p, K):
"""Returns `f + a` where `f` in `GF(p)[x]` and `a` in `GF(p)`. """
if not f:
a = a % p
else:
a = (f[-1] + a) % p
if len(f) > 1:
return f[:-1] + [a]
if not a:
return []
else:
return [a] |
def tree_map(f, tr) :
"""
apply f recursively to all the tree nodes
"""
return (f(tr[0]), tuple([tree_map(f, x) for x in tr[1]])) |
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
... |
def parse_adm1(feature):
"""
returns dict
'id', 'category' - required keys
'dist_meters' - distance from point in search
"""
res = {
'id' : feature['id'],
'category' : 'adm_level1',
'adm1_name' : feature['properties']['name'],
'admin_center_name' : featu... |
def label_seq(data):
"""
Input:
data: dictionary of text, begin_sentences, end_sentences
Output:
a sequence of labels where each token from the text is assiciated with a label:
regular token --> O
begin sentences token --> BS
end sentences token --> ES
... |
def gen_urdf_cylinder(length, radius):
"""
:param length: Length of the urdf cylinder (meters), ``float``
:param radius: Radius of the urdf cylinder (meters), ``float``
:returns: urdf element sequence for a cylinder geometry, ``str``
"""
return '<geometry><cylinder length="{0}" radius="{1}" /></... |
def makeUnique(list):
""" Removes duplicates from a list. """
u = []
for l in list:
if not l in u:
u.append(l)
return u |
def convert_distance_to_probability(distances, a=1.0, b=1.0):
"""
convert distance representation into probability,
as a function of a, b params
Parameters
----------
distances : array
euclidean distance between two points in embedding
a : float, optional
parameter base... |
def _split(text, sep=None):
"""Split a string by delimiter or into lines and return a list of parts."""
if sep is None:
return text.splitlines()
return text.split(sep) |
def generateStringPermutations(string, level=0):
"""Generate all possible permutations of the 'string'."""
if len(string) == 0:
return [""]
permutations = []
for c in string:
reduced = string.replace(c, "", 1)
reducedPermutations = generateStringPermutations(reduced, level + 1)
... |
def strip(l):
"""Strip strings from a list."""
return list(map(lambda x: x.strip(), l)) |
def is_float(string):
"""\
Check whether string is float.
See also
--------
http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
"""
try:
float(string)
return True
except ValueError:
return False |
def negfloat(x):
""" Helper function """
return -float(x) |
def levenshtein(s1, s2, cutoff=None):
"""Compute the Levenshtein edit distance between two strings. If the
minimum distance will be greater than cutoff, then quit early and return
at least cutoff.
"""
if len(s1) < len(s2):
return levenshtein(s2, s1, cutoff)
# len(s1) >= len(s2)
if l... |
def split_tree(tree):
""" Splits the dictionary of answers and corresponding branches
to the positive and the negative subtrees
Parameters
----------
tree : dict
answers and corresponding branches
Returns
-------
tuple
positive subtree, negative subtree
"""
ne... |
def is_etree_element(obj):
"""A checker for valid ElementTree elements that excludes XsdElement objects."""
return hasattr(obj, 'append') and hasattr(obj, 'tag') and hasattr(obj, 'attrib') |
def make_list(obj):
"""Gets the values of a list as an array"""
return [obj[x] for x in obj] |
def f(x, a=0., b=0., c=0.):
"""
Basic function representation: ax^2 + bx + c
Parameters
----------
x coordinate on the abscissa axis
a coefficient of x^2
b coefficient of x
c known term
Returns
-------
The function value at the given x coordinate
"""
return a * x ** ... |
def assign_skill_level(skill_level):
"""This function is used to define user's skill level"""
skill_level_list = [*range(0, 11, 1)]
if skill_level:
if skill_level in skill_level_list:
return skill_level
else:
return None
return None |
def massRatios(pairs, m_arr):
"""
Function calculates the mass ratio between the pairs
"""
m1, m2 = m_arr[int(pairs[0])], m_arr[int(pairs[1])]
return m1/m2 |
def _encode(x_raw, y_raw, feat_idx_dict, class_idx_dict):
"""Encode features and classes to integer indices using given dictionaries.
Arguments:
x_raw: [[string]
list of list of string features; outer list represents samples
e.g., [['age_8', 'gender_M', '31', 'V72.3'],
... |
def dedup_and_title_case_names(names):
"""Should return a list of names, each name appears only once"""
names = [name.title() for name in names]
names = list(set(names))
return names |
def from_args(args, key):
"""
Lazy look into args for key.
:param args:
:param key:
:return:
"""
return args[key] if args.__contains__(key) else f'ERROR' |
def run(arg):
"""
Repeatedly advance a single iterator until it returns a value.
Primarily useful in testing nested generators.
"""
try:
while 1: next(arg)
except StopIteration as si:
return si.value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.