content stringlengths 42 6.51k |
|---|
def range_sum(lower, upper):
"""Find the sum of a range of numbers
"""
# sum(range(lower, upper + 1))
total = (upper + lower) * (upper - lower + 1) / 2
return total |
def convert_base_list(lst, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
"""Converts a "base-list" (something like what ```from_decimal``` would output) to a number (in string form)."""
res = ''
for i in lst:
res += alphabet[i]
return res |
def _expand_global_features(B, T, g, bct=True):
"""Expand global conditioning features to all time steps
Args:
B (int): Batch size.
T (int): Time length.
g (Tensor): Global features, (B x C) or (B x C x 1).
bct (bool) : returns (B x C x T) if True, otherwise (B x T x C)
Returns:
Tensor: B x C x T or B x T x C or None
"""
if g is None:
return None
g = g.unsqueeze(-1) if g.dim() == 2 else g
if bct:
g_bct = g.expand(B, -1, T)
return g_bct.contiguous()
else:
g_btc = g.expand(B, -1, T).transpose(1, 2)
return g_btc.contiguous() |
def put_number(line_number, line):
"""
Return a string. The `line_number` is formatted as 3 digits
number with a dot and a space preceding the `line`. The empty
space before line number will be replaced by '0's.
Example:
>>> put_number(1, "Hello World!")
'001. Hello World'
"""
return "{:03d}. {}".format(line_number, line) |
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
dic = {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
out = ''
for char in seq:
out += dic[char]
return out |
def clean_completion_name(name: str, char_before_cursor: str) -> str:
"""Clean the completion name, stripping bad surroundings.
Currently, removes surrounding " and '.
"""
if char_before_cursor in {"'", '"'}:
return name.lstrip(char_before_cursor)
return name |
def lists_from_options(poss, size, repetitions=True):
"""Returns a list of all possible lists of size ```size``` that
consist only of items from ```poss```, a set."""
if not size:
return [[]]
res = []
prev = lists_from_options(poss, size-1)
for lst in prev:
if repetitions:
for ele in poss:
res.append(lst+[ele])
else:
assert size <= len(poss)
for ele in poss - set(lst):
res.append(lst+[ele])
return res |
def Mean(values):
"""Returns the arithmetic mean, or NaN if the input is empty."""
if not values:
return float('nan')
return sum(values) / float(len(values)) |
def filter_by_dislikes(client_list: list, dislikes: list) -> list:
"""Receives a list of clients and returns a list of clients that have the specified dislikes D.
Args:
client_list (list): List of clients that has the form [[L,D,N]*].
dislikes (list): A list of dislikes in the form of a sorted list of strings.
Returns:
list: Returns a list of clients C in [[L,D,N]*] all for which the condition D == dislikes holds.
"""
clients_sharing_dislikes = list(filter(lambda client: client[1] == dislikes, client_list))
return clients_sharing_dislikes |
def CompareLists(gyp, gn, name, dont_care=None):
"""Return a report of any differences between two lists, ignoring anything
in |dont_care|."""
if not dont_care:
dont_care = []
output = ''
if gyp[name] != gn[name]:
output += ' %s differ:\n' % name
gyp_set = set(gyp[name]) - set(dont_care)
gn_set = set(gn[name]) - set(dont_care)
output += ' In gyp, but not in GN:\n %s' % '\n '.join(
sorted(gyp_set - gn_set)) + '\n'
output += ' In GN, but not in gyp:\n %s' % '\n '.join(
sorted(gn_set - gyp_set)) + '\n\n'
return output |
def precision_and_recall_at_k(ground_truth, prediction, k=-1):
"""
:param ground_truth:
:param prediction:
:param k: how far down the ranked list we look, set to -1 (default) for all of the predictions
:return:
"""
if k == -1:
k = len(prediction)
prediction = prediction[0:k]
numer = len(set(ground_truth).intersection(set(prediction)))
prec = numer / k
recall = numer / len(ground_truth)
return prec, recall |
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.
o(n) runtime, based off the length of the text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# Implement find_all_indexes here (iteratively and/or recursively)
text_i = 0
pattern_i = 0
indexes = []
if pattern == "":
return [x for x in range(len(text))]
elif len(pattern) == 1:
return [i for i, x in enumerate(text) if pattern == x]
elif len(pattern) > len(text):
return []
elif text == pattern:
return [0]
while text_i < len(text) and pattern_i < len(pattern):
if pattern[pattern_i] == text[text_i]:
if pattern_i == len(pattern) - 1:
indexes.append(text_i - pattern_i)
text_i -= pattern_i - 1
pattern_i = 0
text_i += 1
pattern_i += 1
elif pattern[pattern_i] != text[text_i]:
if pattern_i != 0:
text_i -= pattern_i - 1
pattern_i = 0
else:
text_i += 1
return indexes |
def cantor(a, b):
"""Cantor pairing function, used to give unique int name to each observation"""
a = int(a)
b = int(b)
return (a + b) * (a + b + 1) / 2 + b |
def read_paralogs(paralogs_file):
"""Read list of paralogs."""
if paralogs_file is None:
# then nothing to return
return set()
f = open(paralogs_file, "r")
paralogs = set(x.rstrip() for x in f.readlines())
f.close()
return paralogs |
def get_name(mode):
"""
Returns name of given observation mode
"""
names = {}
names['ANT'] = "Alpha-numeric Text"
names['GWW3F'] = "Global Wave Model"
names['RWW3A'] = "Regional Wave Analysis"
names['SICEA'] = "Sea Ice"
names['SSTA'] = "Sea Surface Temperature Analysis"
names['SSTF24'] = "Sea Surface Temperature Forecast 24hrs"
names['SSTF48'] = "Sea Surface Temperature Forecast 48hrs"
names['SSTF72'] = "Sea Surface Temperature Forecast 72hrs"
names['SUFA03'] = "Regional Synoptic"
names['UP50A'] = "Synoptic"
names['UP50F24'] = "Synoptic Forecast 24hrs"
try:
return names[mode]
except KeyError:
return "UNKNOWN" |
def check_iterable_1_not_smaller(iterable_1, iterable_2):
"""Checks two iterables of the same length for whether each element in 1
is at least as big as the corresponding element of 2
Inputs:
iterable_1 - an iterable of arbitary length n
iterable_2 - an iterable of length n which is ordered to correspond
to iterable_1
Returns:
bool reflecting whether all elements are not smaller
"""
if len(iterable_1) == len(iterable_2):
bool_list = map(lambda x,y: x>=y, iterable_1, iterable_2)
else:
raise ValueError('the iterables must be the same length')
return all(list(bool_list)) |
def validate_default_value(handler, default, norm, param="value"):
"""
assert helper that quickly validates default value.
designed to get out of the way and reduce overhead when asserts are stripped.
"""
assert default is not None, "%s lacks default %s" % (handler.name, param)
assert norm(default) == default, "%s: invalid default %s: %r" % (handler.name, param, default)
return True |
def RGB(nRed, nGreen, nBlue):
"""Return an integer which repsents a color.
The color is specified in RGB notation.
Each of nRed, nGreen and nBlue must be a number from 0 to 255.
"""
return (int( nRed ) & 255) << 16 | (int( nGreen ) & 255) << 8 | (int( nBlue ) & 255) |
def say_gday(name, age):
"""
Gday!
"""
# your code here
return "Gday. My name is Alex and I'm 32 years old" |
def conv_packed_binary_string_to_1_0_string(s):
"""
'\xAF' --> '10101111'
"""
r = []
for ch in s:
x = ord(ch)
for i in range(7,-1,-1):
t = (x >> i) & 0x1
r.append(t)
return ''.join(map(lambda x: chr(x + ord('0')), r)) |
def decode_string(data):
""" Decode string and strip NULL-bytes from end."""
return data.decode('utf-8').rstrip('\0') |
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4)
10
>>> g_iter(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
True
"""
"*** YOUR CODE HERE ***"
val = []
for i in range(4):
val.append(i)
for i in range(4, n + 1):
val.append(val[i - 1] + 2 * val[i - 2] + 3 * val[i - 3])
return val[n] |
def get_window_args(wid):
"""wmctrl arguments that choose `wid` for further processing.
"""
return ["wmctrl","-i","-r",wid] |
def MergeIndexRanges(section_list):
"""Given a list of (begin, end) ranges, return the merged ranges.
Args:
range_list: a list of index ranges as (begin, end)
Return:
a list of merged index ranges.
"""
actions = []
for section in section_list:
if section[0] >= section[1]:
raise ValueError('Invalid range: (%d, %d)', section[0], section[1])
actions.append((section[0], 1))
actions.append((section[1], -1))
actions.sort(key=lambda x: (x[0], -x[1]))
merged_indexes = []
status = 0
start = -1
for action in actions:
if start == -1:
start = action[0]
status += action[1]
if status == 0:
merged_indexes.append((start, action[0]))
start = -1
return merged_indexes |
def swap_32b(val):
""" Swap 32b val
:param val: 32b value
:return: swapped 32b """
tmp = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF)
tmp = (tmp << 16) | (tmp >> 16)
return tmp & 0xFFFFFFFF |
def tolerance(condition, sampling_rate=0):
"""Absolute tolerance for different condition."""
tol = 0
if condition == 8:
tol = 2 ** -7
elif condition == 16:
tol = 2 ** -11 # half precision
elif condition == 24:
tol = 2 ** -17 # to be checked
elif condition == 32:
tol = 2 ** -24 # single precision
elif condition == 'duration':
tol = 1 / sampling_rate
return tol |
def state(row, i):
"""This function takes in the current row and the index of the item,
and returns its state as and 0 =< integer =< 7 """
length = len(row)
return row[i - 1] * 4 + row[i] * 2 + row[(i + 1) % length] |
def rgb_to_int(red, green, blue):
"""
Given RGB components of a color, covnert this to an integer
which is in the range of 0 (#000000) to 16777215 (#FFFFFF)
>>> rgb_to_int(0, 0, 0)
0
>>> rgb_to_int(255, 0, 0)
16711680
>>> rgb_to_int(0, 255, 0)
65280
>>> rgb_to_int(0, 0, 255)
255
>>> rgb_to_int(255, 255, 255)
16777215
"""
return (red << 16) + (green << 8) + blue |
def reject_filter(record):
""" A filter function to reject records.
"""
return record if record["int"] != 789 else None |
def get_first(d, key):
"""Return value for d[key][0] if d[key] is a list with elements, else return d[key].
Useful to retrieve values from solr index (e.g. `title` and `text` fields),
which are stored as lists.
"""
v = d.get(key)
if isinstance(v, list):
return v[0] if len(v) > 0 else None
return v |
def list_hasnext(xs):
"""Whether the list is empty or not."""
return len(xs) > 0 |
def indexToCoordinate(index):
"""Return a board coordinate (e.g. e4) from index (e.g. [4, 4])"""
return ("a", "b", "c", "d", "e", "f", "g", "h")[index[1]] + str(abs(index[0] - 8)) |
def check_kwargs(kwargs, default_kw):
"""
Check user-provided kwargs against defaults, and if some defaults aren't
provided by user make sure they are provided to the function regardless.
"""
for key in default_kw:
if key not in kwargs:
kwargs[key] = default_kw[key]
return kwargs |
def calc_rns(rs, albedo):
"""
Total incoming shortwave radiation.
Parameters
----------
rs : numpy ndarray
Total incoming shortwave solar radiation, in MegaJoules per square meter per day
albedo : numpy ndarray
Shortwave blue-sky albedo, unitless
"""
return (1. - albedo) * rs |
def fmt_time(ts, msp=False):
"""Converts nanosecond timestamps to timecodes.
msp = Set timecodes for millisecond precision if True
"""
s = ts / 10 ** 9
m = s // 60
s = s % 60
h = m // 60
m = m % 60
if msp:
return '{:02.0f}:{:02.0f}:{:06.3f}'.format(h, m, s)
else:
return '{:02.0f}:{:02.0f}:{:012.9f}'.format(h, m, s) |
def box(points):
"""Obtain a tight fitting axis-aligned box around point set"""
xmin = min(points, key=lambda x: x[0])[0]
ymin = min(points, key=lambda x: x[1])[1]
xmax = max(points, key=lambda x: x[0])[0]
ymax = max(points, key=lambda x: x[1])[1]
return (xmin, ymin), (xmax, ymax) |
def max_luck_balance(contests, num_can_lose):
"""
Returns a single integer denoting the maximum amount of luck Lena can have
after all the contests.
"""
balance = 0
# We can lose all unimportant contests.
unimportant_contests = [contest for contest in contests if contest[1] == 0]
for contest_luck, _is_important in unimportant_contests:
balance += contest_luck
# Sort the important contests in descending order of luck balance.
important_contests = sorted(
[contest for contest in contests if contest[1] == 1], reverse=True)
# We want to lose as many of the high balance contests as possible.
contests_to_lose = (important_contests)[:num_can_lose]
# We must win the remaining contests.
contests_to_win = (important_contests)[num_can_lose:]
for contest_luck, _is_important in contests_to_lose:
balance += contest_luck
for contest_luck, _is_important in contests_to_win:
balance -= contest_luck
return balance |
def urljoin(*args):
"""A custom version of urljoin that simply joins strings into a path.
The real urljoin takes into account web semantics like when joining a url
like /path this should be joined to http://host/path as it is an anchored
link. We generally won't care about that in client.
"""
return '/'.join(str(a or '').strip('/') for a in args) |
def realord(s, pos=0):
"""
Returns the unicode of a character in a unicode string, taking surrogate pairs into account
"""
if s is None:
return None
code = ord(s[pos])
if code >= 0xD800 and code < 0xDC00:
if len(s) <= pos + 1:
print("realord warning: missing surrogate character")
return 0
code2 = ord(s[pos + 1])
if code2 >= 0xDC00 and code < 0xE000:
code = 0x10000 + ((code - 0xD800) << 10) + (code2 - 0xDC00)
return hex(code).replace("x", "") |
def set_dict_indices(my_array):
"""
Creates a dictionary based on values in my_array, and links each of them to an indice.
:param my_array: An array (e.g. [a,b,c])
:return: A dictionary (e.g. {a:0, b:1, c:2})
"""
my_dict = {}
i = 0
for value in my_array:
my_dict[value] = i
i += 1
return my_dict |
def compute_avg_wmd_distance(contexts1, contexts2, gensim_obj):
"""
Compute an average word metric distance
:param contexts1: List of ContextAndEntities objects extracted from Document 1
:param contexts2: List of ContextAndEntities objects extracted from Document 2
:param gensim_obj: a Gensim object initialized with a word2vec model
e.g. gensim_obj = api.load('word2vec-google-news-300')
:return: Dictionary with keys for the 'max' WMD, 'min' WMD, and 'avg' WMD for all
combinations of contexts. Returns None if the average WMD cannot be calculated
"""
distances = list()
context_combinations = 0
if len(contexts1) == 0:
return None
if len(contexts2) == 0:
return None
# Calculate the distance for every combination of contexts we have been passed
for c1 in contexts1:
for c2 in contexts2:
sc1 = c1.sentence_as_string
sc2 = c2.sentence_as_string
context_combinations += 1
distances.append(gensim_obj.wmdistance(sc1, sc2))
if len(distances) > 0:
avg_distance = sum(distances) / len(distances)
else:
return None
max_distance = max(distances)
min_distance = min(distances)
return {'max': max_distance, 'min': min_distance, 'avg': avg_distance,
'number_of_combinations': context_combinations} |
def greeting(greeting, name):
""" Returns a greeting to a person.
Args:
greeting (str): A greeting.
name (str): A person's name.
Returns (str):
A greeting to a person.
"""
# NOTES:
# 1. String technique #3: %-interpolation
# 2. Built-in function 'title()' capitalizes only the first letter of a string.
return "%s, %s!" % (greeting.title(), name) |
def to_int(num):
"""Convert decimal to integer for storage in DB"""
return int(num * 100) |
def contains(text: str, pattern: str) -> bool:
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# ! Runtime = O(n), have to use contains
# check if pattern is smaller than text
if len(pattern) > len(text):
return False
# case: pattern is empty
if len(pattern) == '':
return True
text_length = len(text)
pattern_length = len(pattern)
counter = 0
# loop over text
for index in range(0, text_length):
if counter == pattern_length:
return True
if text[index] == pattern[0] or text[index] == pattern[counter]:
counter += 1
else:
counter = 0
if counter == pattern_length:
return True
else:
return False |
def _clean(v):
"""Convert parameters into an acceptable format for the API."""
if isinstance(v, (list, set, tuple)):
return ",".join(str(i) for i in v)
else:
return str(v) |
def fib(n):
"""Return the nth fibonacci number."""
a = 0
b = 1
for _ in range(n):
a, b = b, a + b
return a |
def _text(e):
""" Try to get the text content of this element """
try:
text = e.text_content()
except AttributeError:
text = e
return text.strip() |
def is_valid_sudoku(sudokuBoard):
"""
:type sudokuBoard: list
:rtype: bool
"""
seen = []
for i, row in enumerate(sudokuBoard):
for j, c in enumerate(row):
if c != '.':
seen += [(c, j), (i, c), (i // 3, j // 3, c)]
return len(seen) == len(set(seen)) |
def num_to_words(num, join=True):
"""
words = {} convert an integer number into words
:param num:
:param join:
:return:
"""
units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
teens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
thousands = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion',
'nonillion', 'decillion', 'undecillion', 'duodecillion',
'tredecillion', 'quattuordecillion', 'sexdecillion',
'septendecillion', 'octodecillion', 'novemdecillion',
'vigintillion']
words = []
if num == 0:
words.append('zero')
else:
num_str = '%d' % num
num_str_len = len(num_str)
groups = (num_str_len + 2) / 3
print(groups)
num_str = num_str.zfill(int(groups) * 3)
for i in range(0, int(groups) * 3, 3):
h, t, u = int(num_str[i]), int(num_str[i + 1]), int(num_str[i + 2])
g = groups - (i / 3 + 1)
if h >= 1:
words.append(units[h])
words.append('hundred')
if t > 1:
words.append(tens[t])
if u >= 1:
words.append(units[u])
elif t == 1:
if u >= 1:
words.append(teens[u])
else:
words.append(tens[t])
else:
if u >= 1:
words.append(units[u])
if (g >= 1) and ((h + t + u) > 0):
words.append(thousands[int(g)] + ',')
if join:
return ' '.join(words)
return words |
def is_valid_password_v1(password):
"""
Checks if a password is valid, with scheme 1
"""
letter_count = sum([x == password["letter"] for x in list(password["password"])])
return password["low"] <= letter_count <= password["high"] |
def iob1_to_iob2(tags):
"""
checked
Check that tags have a valid IOB or IOB2/BIO format.
Tags in IOB1 format are converted to IOB2.
"""
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return tags
if split[0] == 'B':
continue
elif i == 0 or tags[i - 1] == 'O': # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
elif tags[i - 1][1:] == tag[1:]:
continue
else: # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
return tags |
def from_cycle_notation(permutation, n):
"""
Convert a permutation from cycle notation to one-line notation.
:param permutation: Permutation in cycle notation (list of tuples fo cycles in the permutation).
:param n: Length of the permutation (needed since length 1 cycles are omitted in the cycle notation).
:return: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1).
.. rubric:: Examples
>>> from_cycle_notation([(0, 1, 4), (2, 3)], 6)
(1, 4, 3, 2, 0, 5)
"""
image = [-1] * n
# Record image of all cycles
for perm_cycle in permutation:
for i in range(len(perm_cycle) - 1):
image[perm_cycle[i]] = perm_cycle[i + 1]
image[perm_cycle[len(perm_cycle) - 1]] = perm_cycle[0]
# Handle elements mapping to them selves (length one cycles)
for i in range(len(image)):
if image[i] == -1:
image[i] = i
return tuple(image) |
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg) |
def mm2pt(mm=1):
"""25.4mm -> 72pt (1 inch)"""
return float(mm) * 72.0 / 25.4 |
def find_level_columns(columns):
"""This method finds level columns."""
return [e for e in columns if 'level' in e] |
def string_or_default(message, default_message):
"""
Returns a given string, or a default message if the string is empty or invalid
"""
if (message is None or (not isinstance(message, str)) or len(message) < 1):
return default_message
else:
return message |
def sort_by_price_descending(res):
"""
res should be the return value of search (a list of Products as dictionaries)
returns res as a sorted list of dicts by descending by price
"""
return sorted(res, key = lambda i: i["PriceInEuros"], reverse=True) |
def rotate_point(xpoint, ypoint, angle, xcenter = 0, ycenter = 0, integer = False):
"""
Introduction
------------
This function will rotate a point in respect of another point (optionally
given) by a certain angle.
The outputs are the coordinates of the new point rotated
Information
-----------
Author: Gaetano Camarda, Ph.D. Student in Structural Engineer
Affiliation: University of Palermo
e-mail: gaetano.camarda@unipa.it
V1.0 2020
Package needed
--------------
- numpy
Input:
------
xpoint, x coordinate of point to rotate
ypoint, y coordinate of point to rotate
angle, angle of rotation (in degree, it will be converted in rad)
Optional input:
---------------
xcenter, x coordinate of point as reference for rotation
ycenter, y coordinate of point as reference for rotation
integer, if "True" return the output as integer value
"""
from numpy import cos
from numpy import sin
from numpy import round_
x1 = xpoint - xcenter
y1 = ypoint - ycenter
x2 = x1 * cos(angle) - y1 * sin(angle)
y2 = x1 * sin(angle) + y1 * cos(angle)
newx = round_(x2 + xcenter,decimals = 3)
newy = round_(y2 + ycenter,decimals = 3)
if integer == True:
return int(newx), int(newy)
else:
return newx, newy |
def int_to_string(x, byte=False):
"""Convert integer to string
Parameters
----------
x: int
Integer
byte: bool
Keep it bytes or not
Returns
-------
str (or bytes)
Result
Examples
--------
>>> int_to_string(8387236825053623156)
'testtest'
>>> int_to_string(8387236825053623156, byte=True)
b'testtest'
"""
res = bytes.fromhex(format(x, "x"))
if not byte:
res = res.decode()
return res |
def _check_pronominal(infinitive):
""" check if the infinitive is pronominal verb """
return infinitive.split()[0] == 'se' or infinitive.split("'")[0] == "s" |
def polarization_to_success_probability(p, n):
"""
Inverse of success_probability_to_polarization.
"""
return p * (1 - 1 / 2**n) + 1 / 2**n |
def auto_capitalize(text, state = None):
"""
Auto-capitalizes text. `state` argument means:
- None: Don't capitalize initial word.
- "sentence start": Capitalize initial word.
- "after newline": Don't capitalize initial word, but we're after a newline.
Used for double-newline detection.
Returns (capitalized text, updated state).
"""
output = ""
# Imagine a metaphorical "capitalization charge" travelling through the
# string left-to-right.
charge = state == "sentence start"
newline = state == "after newline"
for c in text:
# Sentence endings & double newlines create a charge.
if c in ".!?" or (newline and c == "\n"):
charge = True
# Alphanumeric characters and commas/colons absorb charge & try to
# capitalize (for numbers & punctuation this does nothing, which is what
# we want).
elif charge and (c.isalnum() or c in ",:"):
charge = False
c = c.capitalize()
# Otherwise the charge just passes through.
output += c
newline = c == "\n"
return output, ("sentence start" if charge else
"after newline" if newline else None) |
def make_safe_name(name: str) -> str:
"""Return a name safe for usage in sql."""
return name.lower().replace(' ', '_') |
def convert_mem(kmem, unit=None):
"""Returns an amount of memory in a human-readable string.
:type kmem: int
:param kmem: amount of memory in kB
:rtype: str
:return: same amount of memory formatted into a human-readable string
"""
k = 1024
if unit == 'K' or (unit is None and kmem < k):
return '%dK' % kmem
if unit == 'M' or (unit is None and kmem < pow(k, 2)):
return '%dM' % (kmem / k)
if unit == 'G' or (unit is None and kmem < pow(k, 3)):
return '%.01fG' % (float(kmem) / pow(k, 2))
return str(kmem) |
def prepare_template(temp):
"""Prepare template by reading the TEMPLATE and converting it to markdown
Parameters
----------
temp : dict
TEMPLATE (or its subfields)
Returns
-------
dict
with default values and necessary
"""
out = {}
for k, v in temp.items():
if 'type' in v:
if not v['necessary']:
out[k] = None
elif v['type'] == 'int':
out[k] = v.get('default', 0)
elif v['type'] == 'float':
out[k] = v.get('default', 0.0)
elif v['type'] == 'str':
out[k] = v.get('default', '')
elif v['type'] == 'list':
out[k] = v.get('default', [])
else:
out[k] = prepare_template(v)
return out |
def get_from_classad(name, class_ad, default=None):
"""
Get the value of the specified item from a job ClassAd
"""
value = default
if name in class_ad:
value = class_ad[name]
return value |
def _merge(listA, listB):
""" Merges two list of objects removing
repetitions.
"""
listA = [x.id for x in listA]
listB = [x.id for x in listB]
listA.extend(listB)
set_ = set(listA)
return list(set_) |
def task_url_from_task_id(task_id: str) -> str:
"""
Transforms an Asana Task's object-id into an url referring to the task in the Asana app
"""
if not task_id:
raise ValueError("task_url_from_task_id requires a task_id")
return f"https://app.asana.com/0/0/{task_id}" |
def is_valid_file_name_length(file_name, length):
"""
Check the file name length is valid
:param file_name: The file name to be checked
:param length: The length of file name which is valid
:return: boolean
"""
return len(file_name) <= int(length) |
def is_float(value: str) -> bool:
"""
Utility function to know whether or not a given string
contains a valid float
Args:
value: string to check
Returns:
Boolean:
True if string can be converted to float
False otherwise
"""
try:
float(value)
return True
except ValueError:
return False |
def _clear_empties(cleaned_data):
"""
FIXME: this is a work around because for some reason Django is seeing
the new (empty) forms in the formsets as stuff that is to be
stored when it really should be discarded.
"""
return [cd for cd in cleaned_data if cd.get('copy')] |
def make_file_name(s):
# adapted from
# https://docs.djangoproject.com/en/2.1/_modules/django/utils/text/#slugify
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata, re
s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
s = s.decode()
s = re.sub(r'[^\w\s-]', '', s).strip().lower()
s = re.sub(r'[-\s]+', '-', s)
return s |
def strip_prefix(name, split='_'):
"""
Strips prefix
:param name: str, name to strip prefix of
:param split: str, split character
:return: str
"""
if not name.count(split):
return name
return split.join(name.split(split)[1:]) |
def swapNibbles(s):
""" Swap nibbles of string s. """
# return ''.join([chr((ord(x) >> 4) | ((ord(x) & 0x0F) << 4)) for x in s])
sb = bytes.fromhex(s)
return bytes([(x >> 4) | ((x & 0x0F) << 4) for x in sb]) |
def convCoord(v):
"""swizzle, the quake order is wacky. also scale by an arbitrary amount."""
scale = 1.0/15.0
return (v[1]*scale, v[2]*scale, v[0]*scale) |
def id_from_url(url):
"""Get player id from URL."""
return url.strip("/").split("/")[-1] |
def clean_line(str, delimiter):
"""Split a string into 'clean' fields.
str the string to process
delimiter the delimiter string to split 'line' with
Returns a list of 'cleaned' field strings.
Any fields that were initially zero length will be removed.
If a field contains '\n' it isn't zero length.
"""
return [x.strip() for x in str.strip().split(delimiter) if x != ''] |
def _make_args_nokwargs(arg1, arg2, arg3):
"""Test utility for args no kwargs case"""
return arg1 + arg2 + arg3 |
def new_chr(pos):
"""
Turn a number to the letter in that position in the alphabet
"""
return chr(pos + 96) |
def alignTo(alignmentValue, bitPosition):
"""
Aligns the bit size to the given alignment value.
:param alignmentValue: Value to align.
:param bitPosition: Current bit position where to apply alignment.
:returns: Aligned bit position.
"""
if bitPosition <= 0 or alignmentValue == 0:
return bitPosition
return (((bitPosition - 1) // alignmentValue) + 1) * alignmentValue |
def calc_process_time(t1, t2):
"""Calculates difference between times
Args:
t1 (float): initial time
t2 (float): end time
Returns:
str: difference in times
"""
return str(t2 - t1) |
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = [
't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt',
'sneaker', 'bag', 'ankle boot']
return [text_labels[int(idx)] for idx in labels] |
def not_found(environ, start_response):
"""Called if no URL matches."""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return [environ.get('PATH_INFO', '').lstrip('/')] |
def add_outgrads(prev_g, g):
"""Add gradient contributions together."""
if prev_g is None:
return g
return prev_g + g |
def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) |
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
try:
color = 'red' if val < 0 else 'black'
except TypeError:
color = 'black'
return 'color: %s' % color |
def sum_of_sequence(n):
"""
Using N(N+1)/ 2
"""
if not input:
return 0
else:
return (n*(n+1))/2 |
def remove_stopwords(annotations, stop_words=[]):
"""
Recibe una lista de textos y stopwords, luego elimina las stopwords para cada elemento de la lista de textos
"""
return [' '.join([word for word in ann.split() if word not in stop_words]) for ann in annotations] |
def capitalize(arg):
"""Capitalize or upper depending on length.
>>> capitalize('telia')
'Telia'
>>> capitalize('free peering')
'Free peering'
>>> capitalize('ix')
'IX'
>>> capitalize('man')
'MAN'
"""
if len(arg) <= 3:
return arg.upper()
return arg.capitalize() |
def diff_last_filter(trail, key=lambda x: x['pid']):
""" Filter out trails with last two key different
"""
return trail if key(trail[-1]) != key(trail[-2]) else None |
def tuples_to_dict(kvw_tuples, colnums=(0, 1)):
"""Given a list of k,v tuples, get a dictionary of the form k -> v
:param kvw_tuples: list of k,v,w tuples (e.g. [(k1,v1,a1), (k2,v2,a2), (k3,v3,a3), (k1,v4,a4)]
:param colnums: column numbers
:return: a dict; something like {k1: v4, k2: v2, k3: v3} (note, k1 is repeated, so last val is retained)
"""
return dict((x[colnums[0]], x[colnums[1]]) for x in kvw_tuples) |
def validate_nodes_number(nodes_number: int) -> int:
"""
Check whether a number of nodes is sufficient to detrend the data.
Parameters
----------
nodes_number : int
The number of nodes.
Returns
-------
int
The number of nodes.
Raises
------
ValueError
Raise when the number of nodes is not sufficient.
"""
min_nodes_number = 2
if nodes_number < min_nodes_number:
raise ValueError(f"At least {min_nodes_number} nodes are required to detrend data")
else:
return nodes_number |
def labels_after_1(circle):
"""
>>> labels_after_1({8: 3, 3: 7, 7: 4, 4: 1, 1: 9, 9: 2, 2: 6, 6: 5, 5: 8})
'92658374'
>>> circ = meh(EXAMPLE_INPUT)
>>> cur = int(EXAMPLE_INPUT[0])
>>> for m in range(100):
... cur = make_move(circ, cur)
...
>>> labels_after_1(circ)
'67384529'
>>> circ = meh(REAL_INPUT)
>>> cur = int(REAL_INPUT[0])
>>> for m in range(100):
... cur = make_move(circ, cur)
...
>>> labels_after_1(circ)
'69852437'
"""
labels = ""
nxt = circle[1]
while nxt != 1:
labels += str(nxt)
nxt = circle[nxt]
return labels |
def escape_trailing__(string: str) -> str:
"""
Returns the given string with trailing underscores escaped to prevent Sphinx treating them as references.
.. versionadded:: 0.8.0
:param string:
"""
if string.endswith('_'):
return f"{string[:-1]}\\_"
return string |
def str_or_na(string):
"""Return the string or "na". """
try:
return string
except:
return "na" |
def equivalent_viscous_damping(mu, mtype="concrete", btype="frame"):
"""
Calculate the equivalent viscous damping based on the ductility and structural type.
:param mu: Displacement ductility
:param mtype: material type
:param btype: building type (e.g. frame or wall)
:return:
"""
pie = 3.141
if mu < 1:
return 0.05
if mtype == "concrete":
if btype == "frame":
# Equivalent viscous damping for concrete frame
return 0.05 + 0.565 * (mu - 1) / (mu * pie)
if btype == "wall":
# Equivalent viscous damping for concrete wall (Sullivan et al., 2010)
return 0.05 + 0.444 * (mu - 1) / (mu * pie) |
def _match_cookie(flow_to_install, stored_flow_dict):
"""Check if a the cookie and its mask matches between the flows."""
cookie = flow_to_install.get("cookie", 0) & flow_to_install.get("cookie_mask", 0)
cookie_stored = stored_flow_dict.get("cookie", 0) & flow_to_install.get(
"cookie_mask", 0
)
if cookie and cookie != cookie_stored:
return False
return True |
def quote_list(the_list):
"""Jinja helper to quote list items"""
return ["'%s'" % element for element in the_list] |
def type_boost(doctype, boost_factor):
"""Helper function to boost results from particular data stores"""
return { "boost_factor": boost_factor, "filter": { "type": { "value": doctype } } } |
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy.
http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
"""
z = x.copy()
z.update(y)
return z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.