content stringlengths 42 6.51k |
|---|
def to_camel(string: str) -> str:
"""Convert snake_case to camelCase."""
words = []
for num, word in enumerate(string.split("_")):
if num > 0:
word = word.capitalize()
words.append(word)
return "".join(words) |
def convert_postag(pos):
"""Convert NLTK POS tags to SWN's POS tags."""
if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
return 'v'
elif pos in ['JJ', 'JJR', 'JJS']:
return 'a'
elif pos in ['RB', 'RBR', 'RBS']:
return 'r'
elif pos in ['NNS', 'NN', 'NNP', 'NNPS']:
... |
def _project(doc, projection):
"""Return new doc with items filtered according to projection."""
def _include_key(key, projection):
for k, v in projection.items():
if key == k:
if v == 0:
return False
elif v == 1:
return... |
def maybe_na(val):
"""Return 'n/a' if non-None value represented as str is not empty
Primarily for the consistent use of lower case 'n/a' so 'N/A' and 'NA'
are also treated as 'n/a'
"""
if val is not None:
val = str(val)
val = val.strip()
return 'n/a' if (not val or val in ('N/A... |
def flatten(lst):
"""Returns a flattened version of lst.
>>> flatten([1, 2, 3]) # normal list
[1, 2, 3]
>>> x = [1, [2, 3], 4] # deep list
>>> flatten(x)
[1, 2, 3, 4]
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> flatten(x)
[1, 1, 1, 1, 1, 1]
"""
"*** YOUR CODE H... |
def new_result(ans, result, your_guess):
"""
The function shows the correct letters and their position after guess.
:param ans: str, the answer
:param result: str, the condition before guess
:param your_guess: str, the letter user guesses
:return: str, the result after guess
"""
n = 0 #... |
def sum_of_n(n):
"""Sum all numbers from 0 to N, recursively."""
if n == 0:
return 0
return n + sum_of_n(n - 1) |
def getWordFrequency(words: list) -> dict:
"""
:Return: dictionary with word and count
"""
dici = {}
for word in words:
if word in dici:
dici[word] += 1
else:
dici[word] = 1
return dici |
def make_unique(value, existing, suffix="_%s", counter=2, case=False):
"""
Returns a unique string, appending suffix % counter as necessary.
@param existing collection of existing strings to check
@oaram case whether uniqueness should be case-sensitive
"""
result, is_present = ... |
def flatten_data(data, *, fill=0x00):
"""
Flatten a list of ``(addr, chunk)`` pairs, such as that returned by :func:`input_data`,
to a flat byte array, such as that accepted by :func:`output_data`.
"""
data_flat = bytearray([fill]) * max([addr + len(chunk) for (addr, chunk) in data])
for (addr, ... |
def module_is_namespace(mod):
"""Is the module object `mod` a PEP420 namespace module?"""
return hasattr(mod, '__path__') and getattr(mod, '__file__', None) is None |
def nested_lookup(doc, field):
"""
Performs a nested lookup of doc using a period (.) delimited
list of fields. This is a nested dictionary lookup.
:param doc: document to perform lookup on
:param field: period delimited list of fields
:return:
"""
value = doc
keys = field.split('.'... |
def sym_pairwise(arg1, arg2):
"""Calculates the symmetric difference of two
sets.
Arguments:
arg1 -- the first set
arg2 -- the second set
Returns: the symmetric difference of two sets
"""
result = []
# Add each element in arg1 to result as long
# as the element is not ... |
def testfunc1(arg1, kwarg1=None):
"""custom docstring"""
return "testfunc1: %s, %s" % (arg1, kwarg1) |
def num_inside_limits(x, limits):
"""
Evaluates if x is inside the limits(min, max)
"""
if x >= limits[0] and x <= limits[1]:
return True
else:
return False |
def _latex_tabular(rows):
"""Creates a string of text that denotes a tabular entity in LaTeX
Parameters
----------
rows : list
Nested list, with each sublist containing elements of a single row
of the table.
Returns
-------
table : str
LaTeX-formated table
Exam... |
def chunk_list(list_to_chunk: list, chunk_size: int) -> list:
"""Chunk given list into chunks of a given size."""
return [
list_to_chunk[i : i + chunk_size]
for i in range(0, len(list_to_chunk), chunk_size)
] |
def galeshapley(suitor_pref_dict, reviewer_pref_dict, max_iteration):
""" The Gale-Shapley algorithm. This is known to provide a unique, stable
suitor-optimal matching. The algorithm is as follows:
(1) Assign all suitors and reviewers to be unmatched.
(2) Take any unmatched suitor, s, and their most p... |
def format_reponse_string(num_item, item):
"""
Hackathon level string formating.
"""
return (
str(int(num_item)) + (" " + item + "s" if num_item > 1 else " " + item)
if num_item > 0
else ""
) |
def num_there(s):
"""helper function for main()"""
return any(i.isdigit() for i in s) |
def padlist(container, size, default=None):
"""Pad list with default elements.
Example:
>>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3)
('George', 'Costanza', 'NYC')
>>> first, last, city = padlist(['George', 'Costanza'], 3)
('George', 'Costanza', None)
... |
def distinct_powers_brute(num):
"""Compute distinct power using brute force."""
total = set()
for a in range(num, 1, -1):
l0 = len(total)
p = a * a
for b in range(2, num+1):
if p not in total:
total.add(p)
p *= a
return len(total) |
def reverse_string(s: str) -> str:
"""Reverses s using recursion."""
assert type(s) == str, "Strings only."
if not s:
return ""
return s[-1] + reverse_string(s[:-1]) |
def get_from_list(x, ys: list, remove=False):
""" Returns value from list. Optionally removes.
Args:
x: item value
ys: list
remove: removes item from list
Returns:
item
"""
res = None
if x in ys:
res = x
if remove:
ys.remove(x)
return res |
def get_rounds(number):
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [n for n in range(number, number + 3, 1)] |
def write_file(filename="", text=""):
"""
write_file - write a string to a file and return the number of chars
"""
with open(filename, "w", encoding="utf-8") as f:
return f.write(text) |
def download_boiler(info):
"""
Boiler plate text for On-Demand Info for downloads
:param info: values to insert into the boiler plate
:param info: dict
:return: formatted string
"""
boiler = ('\n==========================================\n'
' {title}\n'
'========... |
def file_type(filename, param='rb'):
"""returns the type of file, e.g., gz, bz2, normal"""
magic_dict = {
b"\x1f\x8b\x08": "gz",
b"\x42\x5a\x68": "bz2",
b"\x50\x4b\x03\x04": "zip"
}
if param.startswith('w'):
return filename.split('.')[-1]
max_len = max(len(x) for x in... |
def fastaDecodeHeader(fastaHeader):
"""Decodes the fasta header
"""
return fastaHeader.split("|") |
def _get_arm64_macosx_deployment_target(macosx_deployment_target: str) -> str:
"""
The first version of macOS that supports arm is 11.0. So the wheel tag
cannot contain an earlier deployment target, even if
MACOSX_DEPLOYMENT_TARGET sets it.
"""
version_tuple = tuple(map(int, macosx_deployment_ta... |
def match(A, B, equivalence = lambda a,b: a is b):
"""
Returns all elements of A that are exactly the same as an element of B. ie. a is b for some b in B.
You can change the equivalence relation used.
"""
matches = []
for a in A:
for b in B:
if equivalence(a, b):
... |
def check_visibility(line: str) -> bool:
"""
Check visibility for a given line of houses from both sides.
>>> check_visibility('412354*')
True
>>> check_visibility('4123542')
True
>>> check_visibility('312354*')
False
>>> check_visibility('3123545')
False
>>> check_visibilit... |
def solution(socks):
"""Return an integer representing the number of pairs of matching socks."""
# build a histogram of the socks
sock_colors = {}
for sock in socks:
if sock not in sock_colors.keys():
sock_colors[sock] = 1
else:
sock_colors[sock] += 1
# count ... |
def linear_search_multiple(arr, target):
"""
Searches the provided target in the given array.
If target(s) found, then a list with index(es) will be returned.
else empty list will be returned.
Time Complexity = O(n)
Space Complexity = O(1)
"""
return [idx for idx in range(len(arr)) if ar... |
def get_gc(seq_str):
""" Return GC content from a sequence string. """
return float(seq_str.count('G') + seq_str.count('C')) / len(seq_str) |
def get_player_name(number, players, team, home_team):
"""
This function is used for the description field in the html. Given a last name and a number it return the player's
full name and id.
:param number: player's number
:param players: all players with info
:param team: team of player
:p... |
def get_sign(x):
"""
Returns the sign of x.
:param x: A scalar x.
:return: The sign of x.
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 |
def tri_n(n):
"""tri_n(n)
Numpy ufunc. Get the nth triangular number.
:param int n: Nonnegative integer.
:rtype: int
"""
return n * (n + 1) // 2 |
def dayfrac2tick(fd, nbTicks):
"""Conversion day fraction -> tick."""
return int( (fd % 1) * nbTicks) |
def is_palindrome(value):
"""
Check that given number is a palindrom like: 161, 2332.
:returns: true when given number is a palindrom
see http://en.wikipedia.org/wiki/Palindromic_number
>>> is_palindrome(123454321)
True
>>> is_palindrome(1231)
False
"""
value = abs(value)
d... |
def unlines(strings):
"""
``lines :: [String] -> String``
unlines is an inverse operation to lines. It joins lines, after appending a
terminating newline to each.
"""
return "\n".join(strings) |
def test(test_cases, function):
"""Given a dictionary of test_cases containing inputs and their expected results after a function has
been run on them, returns True if all passed, returns False if any fail with a print statement on
each failure."""
successful = True
for test_case in test_cases:
... |
def divide(x, y):
"""Divide Function"""
if y == 0:
raise ValueError('Can not divide by zero!')
return x / y |
def assemble_version_string(prefix, version_array, release, metadata):
"""
reconstruct version
:param prefix: boolean
:param version_array: list of ints
:param release: string
:param metadata: sting
:return: string
"""
result_string = ''
if prefix:
result_string = 'v'
... |
def _end_of_encoding(encoding, start):
"""Find the end index of the encoding starting at index start.
The encoding is not validated very extensively. There are no guarantees what happens for invalid encodings;
an error may be raised, or a bogus end index may be returned.
"""
if start < 0 or start >... |
def _tree_flatten(tree):
"""Flatten a tree into a list."""
if isinstance(tree, (list, tuple)):
# In python, sum of lists starting from [] is the concatenation.
return sum([_tree_flatten(t) for t in tree], [])
if isinstance(tree, dict):
# Only use the values in case of a dictionary node.
return sum... |
def sum_no_duplicates(l):
"""This will find the sum of non repeated ints."""
dup = list([x for x in l if l.count(x) < 2])
answer = sum(dup)
return answer |
def split_nums( text ):
"""
Splits a string into pieces of numbers and non-numbers, like 'abc23B3' --> [ 'abc', 23, 'B', 3 ]
"""
split_t = []
c = ''
n = ''
for ch in text:
try:
v = int( ch )
n += ch
if c:
split_t.append( ''.join( c ... |
def str_time(ltime):
"""return string format time.
The length of miliseconds is vary like '123.45678' or '123.456789'. So this
function generates string format time which is aligned with 6 bytes as the
following example of 'API Request Time':
+-----+------------------------+--------------------+---... |
def get_column_string(n):
"""Converts index n to a letter-based column index as is used in Google Sheets."""
chars = []
a = ord('A')
while n > 0:
n, offset = divmod(n-1, 26)
chars.append(chr(a + offset))
return "".join(reversed(chars)) |
def from_uint(uint):
"""Takes in uint256-ish tuple, returns value."""
return uint[0] + (uint[1] << 128) |
def pingpong(n):
"""Return the nth element of the ping-pong sequence.
>>> pingpong(7)
7
>>> pingpong(8)
6
>>> pingpong(15)
1
>>> pingpong(21)
-1
>>> pingpong(22)
0
>>> pingpong(30)
6
>>> pingpong(68)
2
>>> pingpong(69)
1
>>> pingpong(70)
0
... |
def calculate_score(imp: list, dats: list) -> float:
"""Calculates the score of a tweet
given the importance of each topic
and the topic distribution of that tweet
Args:
imp (list): importance of topic
dats (list): topic dictribution in a tweet
Returns:
float: score of the ... |
def input_test(a):
"""
Injected function for Get_Input testing.
:param a: input
:return: "1"
"""
_ = a
return "1" |
def flatten_dict(data):
"""
Format and return a comma-separated string of dict items.
:param data:
:return:
"""
return ', '.join(["{0}: {1}".format(x, y) for x, y in data.items()]) |
def folderNameCleaner(name):
"""cleans up the name for the folder that holds the file
:param name: The name of the folder to be rename
:type name: str
:returns: A str that will be the new name of the folder
:rtype: str
"""
resolutions = ['proper', '480p', '720p', '1080p', '4k']
afterReso... |
def _is_datadisk_exists(existing_disks, datadisk_name):
"""Helper to test if a datadisks exists among
existing disks.
:param existing_disks: A list that contains the existing
disks within a storage account.
:param datadisk_name: The name of the disk to test. You do not need ... |
def repr(object: object) -> str:
"""repr."""
return object.__repr__() |
def str_to_boolean(string):
"""
If the string is "True" or "False" it wil convert it to a Boolean type
Else it return what was given to it.
:param string: A input string
:return:IF that string is "True" or "False" Then return the boolean otherwise return the result.
"""
if string == "True":... |
def orange(text):
""" Return this text formatted orange (olive) """
return '\x0307%s\x03' % text |
def _test_if_all_vals_equal(vals1, vals2):
"""Checks if the union of two iterables is 1 and returns True if that is the case. Is used in test_num_feats to
check if two lists of values have only the same value and nothing else.
:param vals1:
:param vals2:
:return:
"""
# build union between v... |
def HHV_to_LHV(value, ref_HHV, ref_LHV, reverse=False):
"""
Transfrom values with fuel heat components, This is not a proper transformation ,
it assumes that the fuel that we are transforming has the properties of the reference fuel used
:param value: Heat value to be transformed
:param ref_HHV: HHV... |
def in_list(value, the_list):
"""Return the True or False
Example usage: {{ value|in:list }}
"""
if the_list is None or len(the_list) <=0:
return False
if isinstance(the_list,str):
the_list = the_list.split(',')
else:
the_list = list(the_list)
return value in the_lis... |
def decode(digits, base):
"""Decode given digits in given base to number in base 10.
digits: str -- string representation of number (in given base)
base: int -- base of given number
return: int -- integer representation of number (in base 10)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <... |
def permutate(seq):
"""permutate a sequence and return a list of the permutations"""
if not seq:
return [seq] # is an empty sequence
else:
temp = []
for k in range(len(seq)):
part = seq[:k] + seq[k+1:]
#print k, part # test
for m in permutate(par... |
def strip_js_imports(js_contents):
"""The input JS may use imports for Closure compilation. These must be
stripped from the output since the resulting data: URL cannot use imports
within its webview."""
def not_an_import(line):
return not line.startswith('import ')
return '\n'.join(filter(not_an_import, j... |
def binary_partition(n):
"""Get the powers of two that sum to an integer"""
if(n == 0):
return([0])
out = []
ctr = 0
while(n > 0):
if n % 2 == 1:
out.append(ctr)
ctr += 1
n //= 2
return(out) |
def mass_from_column_name(mass):
"""Return the PVMassSpec mass 'M<x>' given the column name '<x>_amu' as string"""
return f"M{mass[:-4]}" |
def _xpath(d, path):
""" Return value from xml dictionary at path.
d -- xml dictionary
path -- string path like root/device/serviceList/service@serviceType=URN_AVTransport/controlURL
return -- value at path or None if path not found
"""
for p in path.split('/'):
tag_attr = p.split('@')
t... |
def flatten_output_shape(input_shape, options=None):
"""Flatten operation input to output shape conversion"""
return (int(input_shape[0]), int(input_shape[1] * input_shape[2] * input_shape[3])) |
def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
"""
for rule in rules:
date_classes = rule.execute(date_classes)
return date_classes |
def _lon_to_x(lon, zoom):
"""
transform longitude to tile number
:type lon: float
:type zoom: int
:rtype: float
"""
if not (-180 <= lon <= 180):
lon = (lon + 180) % 360 - 180
return ((lon + 180.) / 360) * pow(2, zoom) |
def iteritems(kvlist):
"""
Iterate over (key, value) pairs in a sequence.
The sequence can be a list/tuple/iterator over (key, value) tuples,
or a dict over values.
"""
if isinstance(kvlist, dict):
return kvlist.items()
else:
return kvlist |
def validate_start_times(scene_list: list) -> list:
"""Checks if multiple scenes have the same start time
:param scene_list:
"""
errors = []
start_times = {}
for scene in scene_list:
for key, value in scene.items():
if key == "start":
scene_time = value["time... |
def between(x, y, z):
"""Is X >= Y AND X < Z?"""
return (x >= y and x < z) |
def draw_line(r, g, b, y1, x1, y2, x2, grid):
"""Draws a line on the ppm grid
Arguments
--------
r, g, b -- RGB values for line
m1, n1 -- start point of line
m2, n2 -- end point of line
grid -- ppm grid
"""
dx = x2 - x1
dy = y2 - y1
x = [x for x in range(x1, x2+1)]
for ... |
def tech(number) -> bool:
"""
Takes a number as input and checks whether the given number is Tech Number or not.
"""
if(len(str(number)) % 2 != 0):
return False
else:
return True if(((number % 100)+(number//100))**2 == number) else False |
def threesum_zero(A):
"""Given an array of unsorted numbers, find all unique triplets that
sum up to zero.
[LC-0015]
>>> threesum_zero([-3, 0, 1, 2, -1, 1, -2])
[[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
>>> threesum_zero([-5, 2, -1, -2, 3])
[[-5, 2, 3], [-2, -1, 3]]
>>> threes... |
def _old_node_test(node_info):
"""
Test the first entry of the first tuple in the tuple
"""
return node_info[0][0] |
def watch_pyramid_from_above(characters):
"""String pyramid implementation view from above."""
if not characters:
return characters
str_len = len(characters)
count = str_len + (str_len - 1)
container = []
max_count = count
min_count = 0
if count == 1:
print(characters)
... |
def spy(number) -> bool:
"""
Takes a number as input and checks whether the given number is Spy Number or not.
"""
sum, prod = 0, 1
while number > 0:
d = number % 10
sum += d
prod *= d
number //= 10
return True if(sum == prod) else False |
def scrub_tablename(tablename):
"""Removes whitespace characters from location so can save table name,
adds _ before name if all numbers
"""
table = ''.join(chr for chr in tablename if chr.isalnum())
if table[0].isdigit():
table = "_" + table
return table.upper() |
def parseIfcfg(ifconfig):
"""
Parses the ifconfig in an array if info
:param iostat
:return: array of dict
"""
data = []
for nic,stat in ifconfig.items():
data.append({
nic: {
"bytes_sent": stat.bytes_sent,
"bytes_recv": stat.bytes_recv,
... |
def _parse_namelist_val(val):
"""Parse a string and cast it in the appropriate python type."""
if "," in val: # It's a list, parse recursively
return [_parse_namelist_val(subval.strip()) for subval in val.split(",")]
elif val.startswith("'"): # It's a string, remove quotes.
return val[1:-1... |
def is_struct_seq(obj):
"""Returns whether obj is a structured sequence subclass: sys.float_info"""
return isinstance(obj, tuple) and hasattr(obj, 'n_fields') |
def required(flag=True):
"""When this flag is True, an exception should be issued if the related keyword/element is
not defined. Returns "R" or False.
>>> required(True)
'R'
>>> required(False)
False
"""
return "R" if flag else False |
def score_property(property_name, recipe, ingredients):
"""Score property_name according to spoons of ingredients in recipe."""
score = 0
for amount, properties in zip(recipe, ingredients.values()):
value = properties[property_name]
ingredient_value = amount * value
score += ingredie... |
def meters_to_user_units(meters: float, units: str) -> float:
"""Convert a meters value to user units"""
if units == 'english':
return meters * 3.2808
else:
return meters |
def validate_pin(pin):
"""
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly
6 digits. If the function is passed a valid PIN string, return true, else return false.
:param pin: a string input with either numbers or characters or both.
:re... |
def rr(y_true):
"""Return the reciprical rank of the first positive candidate."""
for index in range(0, len(y_true)):
if y_true[index]:
return 1.0 / (index + 1)
return 0.0 |
def sign(x):
""" :returns sign function (as float)
if x is complex then use numpy.sign()
"""
sgn_int = x and (1, -1)[x < 0]
return 1.0 * sgn_int |
def wavelength_RGB(wlen):
""" wlen: wavelength in nm
needs single value, np.array fails
returns: (R,G,B) triplet of integers (0-255)
Credits: Dan Bruton http://www.physics.sfasu.edu/astro/color.html"""
# first pass at an RGB mix
if 380 <= wlen and wlen < 440:
... |
def next_multiple(x: int, k: int = 512) -> int:
"""Calculate x's closest higher multiple of base k."""
if x % k:
x = x + (k - x % k)
return x |
def is_interpro_domain(domain):
"""
Function to check if the input domain is Interpro or GAP or unknown domain (unk)
Parameters
----------
domain : str
domain string name to check if it is Interpro or not
Returns
-------
bool
True if the domain is an Interpro domain or not
"""
if domain[0:3] == "IPR" or... |
def getNetFromGross(net_income, allowance):
"""Implements tax bands and rates corresponding to the tax year 2011-2012"""
if net_income <= allowance:
return net_income
else:
net_income_without_allowance = net_income - allowance
if net_income_without_allowance <= 35000:
ret... |
def get_path(data, path):
"""
Fetch a value in a nested dict/list using a path of keys/indexes
If it fails at any point in the path, None is returned
example: get_path({'x': [1, {'y': 'result'}]}, ['x', 1, 'y'])
"""
current = data
for p in path:
try:
current = data[p]
... |
def get_class_name(obj):
""" Returns full class name for given object"""
return str(obj.__class__).replace('<class \'', '').replace('\'>', '') |
def episode_player_url(episode):
"""Return the player URL for the given episode code"""
player_url = 'http://www.bbc.co.uk/radio/player/{}'
return player_url.format(episode) |
def combine(arr):
""" makes overlapping sequences 1 sequence """
def first(item):
return item[0]
def second(item):
return item[1]
if len(arr) == 0 or len(arr) == 1:
return arr
sarr = []
for c, val in enumerate(arr):
sarr.append((val[0], val[1], c))
... |
def curtail_string(s, length=20):
"""Trim a string nicely to length."""
if len(s) > length:
return s[:length] + "..."
else:
return s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.