content stringlengths 42 6.51k |
|---|
def clean_age(x):
"""Return the clean age
"""
stripped = x.strip().lower()
# take only first value of any range
stripped = stripped.split('-')[0].strip()
try:
age = int(stripped)
if age<1 or age>99:
return None
except:
return None
return age |
def marvin_in_good_direction(elevator_pos: int, clone_pos: int, direction: str) -> bool:
"""
Is the clone going in the good direction?
Args:
elevator_pos (int) - The position of the elevator.
clone_pos (int) - The position of Marvin's clone.
direction (str) - RIGHT or LEFT.
"""
... |
def get_leading_spaces(input_string):
"""
Returns the leading spaces from a string and the length of that string.
(string, length).
"""
justified = input_string.lstrip()
length = len(input_string) - len(justified)
string = ' ' * length
return string, length |
def summation(n, term):
"""Return the sum of the first n terms in the sequence defined by term.
Implement using recursion!
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
>>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
54
>>> summation(5, lamb... |
def calc_prob_sr(pt, sl, freq, tgt_sr, rf=0.):
"""Calculate required probability wrt target SR
Paramters
---------
pt: float
Profit Take
sl: float
Stop Loss
freq: float
Frequency of trading
tgt_sr: float
Target Sharpe Ratio
rf: float, (default 0)
... |
def format_size(nbytes):
"""Formats a size as a human-readable string like "123.4k".
Units are in powers of 1024, so "k" is technically "kiB", etc.
Values smaller than "k" have the suffix "B".
Exact multiples of a unit are displayed without a decimal;
e.g., "17k" means the value is exactly 17 * 10... |
def from_ell_to_index(ell):
"""
Returns the range of column values assuming a matrix with columns ordered
with the m multipole , m ranging from -ell to +ell
"""
return ell ** 2, ell ** 2 + 2 * ell + 1 |
def removeSpacesAndTabs(data):
"""
Remove all tabs and spaces.
>>> removeSpacesAndTabs("a Sting With Spaces")
'aStingWithSpaces'
>>> removeSpacesAndTabs("a\tSting\tWith\tTabs")
'aStingWithTabs'
"""
return data.replace(" ", "").replace("\t", "") |
def user_commented(user_id, comments):
"""Check for a comment from a user given a list of comments"""
user_comments = []
media = []
for medium in comments:
media_comments = comments[medium]
for comment in media_comments:
if comment.user.id == user_id:
user_com... |
def make_reduction_plots(initial_expids_and_image_ranges, expids_and_image_ranges):
"""Make a chart showing excluded image ranges."""
x = list(range(len(initial_expids_and_image_ranges)))
initial_n_images = []
initial_expids = []
for expid_and_img in initial_expids_and_image_ranges:
initial_... |
def get_factor_names(factor_count):
"""Returns a list of factor variable names up to the count.
Example:
>>> get_factor_names(3)
["X1", "X2", "X3"]
"""
# Design-Expert uses A/B/C for variable names, switching to A'/B'/C'
# and A"/B"/C" after 25 or 50 variables (I is not used)
# ... |
def _detect_nonce_too_low_geth(message):
"""source:
https://github.com/ethereum/go-ethereum/blob/60516c83b011998e20d52e2ff23b5c89527faf83/core/tx_pool.go#L51
"""
return message.startswith("nonce too low") |
def polygon_centroid(*points):
"""
Calculates center point of given polygon.
Args:
points: ((float, float),)
Collection of points as (x, y) coordinates.
Returns:
(float, float)
Center point as (x, y) coordinates.
"""
x = sum(p[0] for p in po... |
def unsafe_version(version):
"""Undoes what safe_version() does.
See safe_version() for the details.
Args:
version: string, The safe version string.
Returns:
The string with '_' replaced with '.'.
"""
return version.replace('_', '.') |
def gs_to_public_url(gs_url):
"""Converts a gs:// URI to a HTTP URL."""
assert gs_url.startswith('gs://')
return gs_url.replace('gs://', 'https://storage.googleapis.com/', 1) |
def validate_max_step(max_step):
"""Assert that max_Step is valid and return it."""
if max_step <= 0:
raise ValueError("`max_step` must be positive.")
return max_step |
def get_random_set( num_of_leds, total_num_leds ):
""" Returns a set (no duplicates) of LED index numbers.
"""
known_led_indexes = range(total_num_leds)
new_sequence = []
while len(new_sequence) < num_of_leds:
i = rnd.randint(0,len(known_led_indexes)-1)
led = known_led_indexes[i]
new_sequence.append(... |
def parse_owner(URL):
"""
There are two common ways to specify a submolde URL, either with the git@
syntax, or the http/git syntax. Examples:
git@github.com:zfsonlinux/zfs.git
https://github.com/zfsonlinux/zfs.git
git://github.com/zfsonlinux/zfs.git
one trick is that the owner and repo have ... |
def get_hashtag_positions(text):
"""
e.g. "#tbt kind! #summer" -> [0, 11]
"""
positions = [pos for pos, char in enumerate(text) if char == '#']
if len(positions) == 0:
return None
else:
return positions |
def _check_bounding_box(lat_min: float,
lat_max: float,
lon_min: float,
lon_max: float) -> bool:
"""
Check if the provided [lat_min, lat_max, lon_min, lon_max] extents
are sane.
"""
if lat_min >= lat_max:
return False
... |
def get_hms(t_sec):
"""
Convert a time given in seconds to hours, minutes, and seconds
Parameters
----------
t_sec : int
Time in seconds.
Returns
-------
h : int
The hours portion of the time.
m : int
The minutes portion of the time.
s : int
The ... |
def linear_decay(x0, alpha, T, t):
"""Compute the linear decay rate of quantity x at time t.
x(t) = x0 - (1-alpha) * x0 * t / T if t <= T
x(t) = alpha * x0 if t > T
Args:
x0: Initial value
alpha: Linear decay coefficient (alpha > 0)
T: Time at which to stop decay... |
def set_key(key):
"""
Instantiates an API key object to pull from the SimFin API.
"""
api_key = key
return api_key |
def line_line_intersect(x1, y1, x2, y2, x3, y3, x4, y4, line_segment = False, half_segment = False):
"""Returns the intersection x',y' of two lines x,y 1 to 2 and x,y 3 to 4.
arguments:
x1, y1, x2, y2: coordinates of two points defining first line
x3, y3, x4, y4: coordinates of two points defining se... |
def quantile(l, p):
"""Return p quantile of list l. E.g. p=0.25 for q1.
See:
http://rweb.stat.umn.edu/R/library/base/html/quantile.html
"""
l_sort = l[:]
l_sort.sort()
n = len(l)
r = 1 + ((n - 1) * p)
i = int(r)
f = r - i
if i < n:
result = (1-f)*l_sort[i-1] + f*l_... |
def naive_with_counts(p, t):
"""Return the naive match.
Also return the number of alignments
and the total number of character comparisons.
"""
occurrences = []
alignments = 0
comparisons = 0
for i in range(len(t) - len(p) + 1): # loop over alignments
alignments += 1
ma... |
def power_set(elements):
"""
recursive version
"""
if not elements:
return [[]]
else:
result= []
first = elements[0]
subsets = power_set(elements[1:])
for subset in subsets:
result.append(subset)
new = [first] + subset
... |
def isolate_glossary(word, glossary):
"""
Isolate a glossary present inside a word.
Returns a list of subwords. In which all 'glossary' glossaries are isolated
For example, if 'USA' is the glossary and '1934USABUSA' the word, the return value is:
['1934', 'USA', 'B', 'USA']
"""
if word... |
def is_leapyear(year):
"""Returns true if year was a leapyear."""
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False |
def create_response(data, status_code, detail):
"""
Create a standardised response
[
status: 'message',
code: 'number',
data: '{}|[]',
detail: 'message',
]
"""
response = {
'status': 'success',
'code': status_code,
'data': data,
'de... |
def prod_boiler(info):
"""
Boiler plate text for On-Demand Info for products breakdown
:param info: values to insert into the boiler plate
:param info: dict
:return: formatted string
"""
boiler = ('\n==========================================\n'
' {title}\n'
'===... |
def clean(in_str:str)->str:
"""
Remove or replace characters that may not tweet well.
See: https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin
"""
replacements = [
{"search": u'\u2018', "replace": "'"},
{"search": u'\u2019', "replace": "'"},
{"search": u'\u... |
def warn(expression, message_if_true):
""" Display the given warning message if 'expression' is True. """
if expression:
print(message_if_true)
return expression |
def justify_indel(start, end, indel, seq, justify):
"""
Justify an indel to the left or right along a sequence 'seq'.
start, end: 0-based, end-exclusive coordinates of 'indel' within the
sequence 'seq'. Inserts denote the insertion point using start=end
and deletions indicate the deleted re... |
def validate_zoom(zoom):
"""
Return validated zoom.
Assert zoom value is positive integer.
Returns
-------
zoom
Raises
------
TypeError if type is invalid.
"""
if any([not isinstance(zoom, int), zoom < 0]):
raise TypeError("zoom must be a positive integer: %s" % zo... |
def process_chunk(chunk, func, olddf, newdf, sourcexinter, destxinter, metric_name, interpolate):
""" Process each chunk. """
results = [func(olddf, newdf, e, sourcexinter, destxinter, metric_name, interpolate)
for e in chunk]
return results |
def _parse_categories(categories, sep=' '):
""" Parses the string containing categories separated by sep.
Internal method, used in case we want to change split strategy later. """
categories = categories.replace(',', ' ') # drop commas
categories = categories.replace(';', ' ') # drop semi-colons
# R... |
def pad_matrix(M):
"""
Pad the matrix's dimensions to the smallest
power of 2 greater than or equal to the number
of rows and columns in the matrix.
This eliminates edge cases for this example.
"""
m, n = len(M), len(M[0])
b = 1
while b < max(m, n):
b <<= 1
M += [[0] * n for _ in range(b - m)]... |
def _list2str(array):
"""
Join a list with spaces between elements.
"""
return ' '.join(str(a) for a in array) |
def check_initializers(initializers, keys):
"""Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to module... |
def lens(lists):
"""Returns the sizes of lists in a list."""
return list(map(len, lists)) |
def find_sentence(sentence_list, taggedspan, filename):
"""
Find the sentence index that corresponds with the span.
Keyword arguments:
sentence_list: list -- list of all sentences in the note (list)
taggedspan: the span of the annotation (list)
filename: the name of the file (string)
"""
... |
def stringIncrement(serial_string):
"""
string incrementer
:param serial_string:
:return:
"""
init_ser = serial_string
carry = 0
let = 65
for letS in serial_string[::-1]:
let = ord(letS)
let = let + 1
if let > 122 or let < 65:
carry = carry + 1
... |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
"""
def change_with_maxcoin(total, maxcoin):
if total == 0:
return 1
... |
def validateFilenamePset(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Filename for LaGriT pset file not specified.")
return value |
def initialize_skill_state(name, origin, beta, skill_gid) -> dict:
"""Create a new skill entry
Arguments:
name: skill name
origin: the source of the installation
beta: Boolean indicating wether the skill is in beta
skill_gid: skill global id
Returns:
populated skills... |
def expTaylor(n, x):
"""Calculate exp(x) with n terms.
10.3us <- Run `%timeit expTaylor(100, 5)` in iPython
Rationale
---------
Term 1. x**1 / fact(1) = x / 1
Term 2. x**2 / fact(2) = x*x / (1*2) = Term 1 * x/2
Term 3. x**3 / fact(3) = x*x*x / (1*2*3) = Term 2 * x/3
Term 4. x**4 / fact... |
def length(iterable):
"""
Return number of items in the iterable.
Attention: this function consumes the whole iterable and
can never return if iterable has infinite number of items.
:Example:
>>> length(iter([0, 1]))
2
>>> length([0, 1, 2])
3
"""
try:
return len(itera... |
def positive_id(obj):
"""Return id(obj) as a non-negative integer."""
import struct
_ADDRESS_MASK = 256 ** struct.calcsize('P')
result = id(obj)
if result < 0:
result += _ADDRESS_MASK
assert result > 0
return result |
def _get_url(document):
"""Return the URL for the given JSON-LD document."""
return document['@id'] |
def _recipient(recipient):
"""
Returns a query item matching "to".
Args:
recipient (str): The recipient of the message.
Returns:
The query string.
"""
return f"to:{recipient}" |
def solve(s):
"""
Returns capitalized first alphabets only.
"""
stripped = s.strip().split(' ')
caps = [x.capitalize() for x in stripped]
return str(' '.join(caps)) |
def egcd(a, b):
"""Extended gcd of a and b. Returns (d, x, y) such that d = a*x + b*y where d is the greatest common divisor of a and b."""
x0, x1, y0, y1 = 1, 0, 0, 1
while b != 0:
q, a, b = a // b, b, a % b
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return a, x0, y0 |
def get_article_templates(article, user):
"""
example of functions to get custom templates
It may depend on article or user
"""
return (
('standard.html', 'Standard'),
('homepage.html', 'Homepage'),
('blog.html', 'Blog'),
('standard_en.html', 'English'),
) |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
i... |
def compatibility_g_a(gen, anot):
"""Check compatibility with annotations."""
print("Checking compatibility of genome with annotation file")
r_code = 0
for seq in gen:
if seq not in anot:
print("WARN\t{} sequence not found in annotaion file".format(seq))
r_code = 1
fo... |
def div_mod(a, b, mod):
"""
(a // b) % mod
:param int a:
:param int b:
:param int mod:
"""
return a * pow(b, mod - 2, mod) % mod |
def get_text(element):
"""
Extract text contents of `element`, normalizing newlines to spaces and stripping.
"""
if element is None:
return ''
else:
return element.get_text().replace('\r', '').replace('\n', ' ').strip() |
def is_within_distance(number, target_number, distance):
""" returns true if the number is within 'distance' from the 'target_number' """
actual_distance = abs(target_number - number)
return actual_distance <= distance |
def _process_chunk(fn, chunk):
""" Processes a chunk of an iterable passed to map.
Runs the function passed to map() on a chunk of the
iterable passed to map.
This function is run in a separate process.
"""
return [fn(*args) for args in chunk] |
def getAllListings(command):
""" Check if command is to get all listings (l | list). """
return (command.strip().lower() == "l" or command.strip().lower() == "list") |
def decrypt_ascii(k: int, ciphertext: str) -> str:
"""Return the decrypted message using the Caesar cipher with key k.
Preconditions:
- all({ord(c) < 128 for c in ciphertext})
- 1 <= k <= 127
>>> decrypt_ascii(4, 'Kssh$qsvrmrk%')
'Good morning!'
"""
plaintext = ''
for lett... |
def delete_empty_data(data):
""" Deletes any items with the value `NA` or '' a dictionary """
keys = list(data.keys())
for key in keys:
if data[key] == '' or data[key] == ' ':
del data[key]
return data |
def _lerp(percent, bounds):
"""
Return a linearly interpreted value given a percentage and a range
:param percent: The percentage
:param bounds: The range
:return: A linearly interpreted value given a percentage and a range
"""
assert len(bounds) == 2
lower, upper = bounds
return ((u... |
def split_pair(pair_string):
"""given an option of the form "(val1, val2)", split it into val1 and
val2"""
return pair_string.replace("(", "").replace(")", "").replace(" ", "").split(",") |
def str_digit_to_int(chr):
"""
Converts a string character to a decimal number.
Where "A"->10, "B"->11, "C"->12, ...etc
Args:
chr(str): A single character in the form of a string.
Returns:
The integer value of the input string digit.
"""
# 0 - 9
if chr in ("... |
def create_7z(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a 7z archive."""
cmdlist = [cmd, 'a']
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-t7z', '-mx=9', '--', archive])
cmdlist.extend(filenames)
return cmdlist |
def realword(sym):
"""
Test if a word is a real word (not silence or filler)
"""
if sym.lower() in ('<s>','<sil>','</s>'):
return False
if sym.startswith("++"):
return False
return True |
def expected_os2_weight(style):
"""The weight name and the expected OS/2 usWeightClass value inferred from
the style part of the font name
The Google Font's API which serves the fonts can only serve
the following weights values with the corresponding subfamily styles:
250, Thin
275, ExtraLight
300, Ligh... |
def escape_latex(text):
"""Escape a string for matplotlib latex processing.
Run this function on any FSPS parameter names before passing to the
plotting functions in this module as axis labels.
Parameters
----------
text : str
String to escape.
"""
return text.replace("... |
def str2int(string):
""" Safely convert string to int or return None. """
return int(string) if string else None |
def solution(S):
"""Check that a string is properly nested.
A string is considered properly nested if one of the following is true:
(1) S is empty
(2) S has the form "(U)" or "[U]" or "{U}" where U is properly nested
(3) S has the form "VW" where V and W are properly nested
Args:
... |
def remove_marc_files(filenames):
"""Marc files are not supported"""
filenames2 = []
for filename in filenames:
if 'marc' not in filename:
filenames2.append(filename)
return filenames2 |
def unscented_default_params(n=None):
""" """
if n is None:
n = 0
return {'alpha': 1., 'beta' : 0., 'kappa': 3. - n} |
def chunk_string(input_str, length):
"""
Splits a string in to smaller chunks.
NOTE: http://stackoverflow.com/questions/18854620/
:param input_str: str the input string to chunk.
:param length: int the length of each chunk.
:return: list of input str chunks.
"""
return list((input_str[... |
def get_boolean(value):
"""Convert a value to a boolean.
Args:
value: String value to convert.
Return:
bool: True if string.lower() in ["yes", "true"]. False otherwise.
"""
return True if value.lower() in ["yes", "true"] else False |
def lcsubstring_length(a, b):
"""Find the length of the longuest contiguous subsequence of subwords.
The name is a bit of a misnomer.
"""
table = {}
l = 0
for i, ca in enumerate(a, 1):
for j, cb in enumerate(b, 1):
if ca == cb:
table[i, j] = table.get((i - 1... |
def get_field_reference(path):
"""Get a field indicator from the received path."""
if isinstance(path[-1], int):
field = ".".join(list(path)[:-1])
ref = "item {} in '{}' field".format(path[-1], field)
else:
field = ".".join(path)
ref = "'{}' field".format(field)
return re... |
def call_activation(x, foo=None):
""" return result of an activation function `foo` on the input `x`, return `x` if `foo is None` """
if foo is None:
return x
return foo(x) |
def name(link:str):
"""Will name a file based on the link given"""
# If the link is empty, raise an error
if link == "":
raise ValueError("Link is empty")
else:
return link.split('/')[-1] |
def format_symbolic_duration(symbolic_dur):
"""
Create a string representation of the symbolic duration encoded in the
dictionary `symbolic_dur`.
Examples
--------
>>> format_symbolic_duration({'type': 'q', 'dots': 2})
'q..'
>>> format_symbolic_duration({'type': '16th'})
'16th'
... |
def first_recurring_character2(array):
"""
- Create a dictionary
- Loop through the list
- At each item
- check if item in dictionary
- if present => return true
- else dictionary[item] = True
O(n) - worst case will check each element once
"""
items_already_seen = {}
for... |
def yp_raw_businesses(yelp_username):
"""
Competitors file of the given yelp_username.
File Type: CSV
"""
return '../data/raw/{}_competitors.csv'.format(yelp_username) |
def insertion_sort(arr):
"""Performs an Insertion Sort on the array arr."""
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j>= 0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr |
def rolling_hashes(string: str) -> str:
"""Construct a palindrome with rolling hashes"""
p = 23
P = 666013
str_rev = string[::-1]
f_foward = 0
f_backward = 0
p_power = 1
max_suffix_palindrome = 0
for index, char in enumerate(str_rev):
char_idx = ord(char) - ord("a")
f... |
def filter_user_info(user_info):
"""Filter the user info dictionary for a Bountysource account.
This is so that the Bountysource access token doesn't float around in a
user_info hash (considering nothing else does that).
"""
whitelist = ['id', 'display_name', 'first_name', 'last_name', 'email', \
... |
def is_overlapping(bbox1, bbox2):
"""
Checks if the bounding boxes given overlap.
Copied from https://www.geeksforgeeks.org/find-two-rectangles-overlap/
"""
rmin1, cmin1, rmax1, cmax1 = bbox1
rmin2, cmin2, rmax2, cmax2 = bbox2
# To check if either rectangle is actually a line
# For exa... |
def has_consecutive_ranges(ranges):
"""Check that a set of ranges is non-consecutive"""
total_entries = sum(h - l + 1 + 1 for l, h in ranges)
union = set().union(*[set(range(l, h + 2)) for l, h in ranges])
return len(union) < total_entries |
def _make_pretty_arguments(arguments):
"""
Makes the arguments description pretty and returns a formatted string if `arguments`
starts with the argument prefix. Otherwise, returns None.
Expected input:
Arguments:
* arg0 - ...
...
* arg0 - ...
...... |
def _merge_small_dims(shape_to_merge, max_dim):
"""Merge small dimensions.
If there are some small dimensions, we collapse them:
e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024
[1, 2, 768, 1, 2048] --> [2, 768, 2048]
Args:
shape_to_merge: Shape to merge small dimensions.
... |
def DecodeEncode(tRaw, filetype):
"""return the decoded string or False
copy from readwritefile, in order to prevent another import statement.
used by readAnything, also see testreadanything in miscqh/test scripts
"""
try:
tDecoded = tRaw.decode(filetype)
except UnicodeDecod... |
def layer_add(x):
"""Compute Q given Advantage and V."""
return x[0] + x[1] |
def reverse_complement(table, seq):
"""Return the reverse complement of a DNA sequence."""
return seq.translate(str.maketrans("ATGC","TACG"))[::-1] |
def detect_orm(input_text_data: str,):
"""Simple detecting ORM by text sample."""
if 'django' in input_text_data:
return 'django'
if 'sqlalchemy' in input_text_data:
return 'sa'
raise Exception("Unknown ORM") |
def from_str(string):
""" Convert string to number
This function takes a string and converts it into a number or a list.
Args:
string (str): The string.
Returns:
The value in the string.
"""
beg_delims = ('(', '[', '{', '<')
end_delims = (')', ']', '}', '>')
string =... |
def islice(vals, inds):
"""Returns a list of values from `vals` at the indices in `inds`."""
sliced = []
for (i, v) in enumerate(vals):
if i in inds:
sliced.append(v)
return sliced |
def pad_oid(oid, size):
"""If oid is short, pad right with 0s."""
result = list(oid)
while len(result) < size:
result.append(0)
return result |
def calculate_refresh_commands(rm_exe, config, fil, activate, is_ini):
"""Detect if an activate config flag is required or not."""
if activate:
cmds = [rm_exe, "!ActivateConfig", config]
if is_ini:
cmds.append(fil)
return cmds
else:
return None |
def escape_path(path):
"""
Adds " if the path contains whitespaces
Parameters
----------
path: str
A path to a file.
Returns
-------
an escaped path
"""
if ' ' in path and not (path.startswith('"') and path.endswith('"')):
return '"' + path + '"'
... |
def truncate_text(text, maxlen=128, suffix="..."):
"""Truncates text to a maximum number of characters."""
if len(text) >= maxlen:
return text[:maxlen].rsplit(" ", 1)[0] + suffix
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.