content
stringlengths 42
6.51k
|
|---|
def apply_changes(block, changes):
"""Apply a set of changes to a block."""
for (x, y, c) in changes:
block[y][x] = c
return block
|
def is_increasing(arr):
""" Returns true if the sequence is increasing. """
return all([x < y for x, y in zip(arr, arr[1:])])
|
def MaybeAddColor(s, color):
"""Wrap the input string to the xterm green color, if color is set.
"""
if color:
return '\033[92m{0}\033[0m'.format(s)
else:
return s
|
def num_nodes_balanced_tree(r,h):
"""
Returns the number of nodes in a balanced tree, with branching factor R and height H.
"""
total = 0
for i in range(0,h+1):
total += r ** i
#log.debug("total: %s", total)
return total
|
def chaddr_to_mac(chaddr):
"""Convert the chaddr data from a DhcpPacket Option to a hex string
of the form '12:34:56:ab:cd:ef'"""
return ":".join(hex(i)[2:] for i in chaddr[0:6])
|
def map_profile_fields(data, fields):
"""Copy profile data from site-specific to standard field names.
Standard keys will only be set if the site data for that key is not
``None`` and not empty string.
:param data: Profile data from the site, to be modified in place.
:param fields: Map of ``{destination: source}``. Destination is the
standard name. Source source is the site-specific name, or
a callable taking ``data`` and returning the value.
:return: UserInfo fields
"""
profile = {}
for dst, src in fields.items():
if callable(src):
value = src(data)
else:
value = data.get(src)
if value is not None and value != '':
profile[dst] = value
return profile
|
def safe_unicode_str(text):
"""Trys to decode a byte stream as UTF-8 with a safe fallback to raw ascii."""
try:
sn = bytes(text).decode("utf-8")
except UnicodeDecodeError:
sn = []
for b in text:
if b >= 0x20 and b <= 127:
sn.append(str(b))
sn = "".join(sn)
sn = sn.rstrip("\0")
return sn
|
def lrotate(key, steps):
"""Returns the left rotation of the provided permuted choice key.
Used as part of the key schedule to select each round key. The key is
treated as two separate parts, each containing 28 bits and receiving its
own bit rotation. Since these operations should be fast, the resulting keys
are not cached. Instead, each step is performed for each round in which it
is required.
Keyword: arguments
key -- 56 bits of a DES encryption key stored in a 7-byte array.
steps -- The number of places to rotate the bits; usually either 1 or 2.
"""
keyp = key[:]
fmask = 0
hmask = 255
# Left boundary masks to avoid losing bits during rotation
for i in range(steps):
fmask = fmask ^ (2**(7 - i))
hmask = hmask ^ (2**(4 + i))
# First six bytes can be shifted and right-fill in one step
for k in range(6):
keyp[k] = key[k] << steps
keyp[k] = keyp[k] ^ ((key[k + 1] & fmask) >> (8 - steps))
# Last byte needs to be right-fill from the middle (beginning of right key)
keyp[6] = key[6] << steps
keyp[6] = keyp[6] ^ ((key[3] & (fmask >> 4)) >> (4 - steps))
# Middle byte needs to be middle-filled from the left
keyp[3] = keyp[3] & hmask
keyp[3] = keyp[3] ^ ((key[0] & fmask) >> (4 - steps))
return keyp
|
def get_fqdn(hostname):
""" Reimplemented to be cached for continuous tango host parsing """
import socket
return socket.getfqdn(hostname)
|
def is_itits(node):
"""
Searches for pronouns "it", and "its", returning True if found.
"""
if len(node) != 1:
return False
target = node[0].lower()
pos = node.label()
return ((pos == 'PRP') and (target == 'it')) or \
((pos == 'PRP$') and (target == 'its'))
|
def value_to_zero_or_one(s):
"""Convert value to 1 or 0 string."""
if isinstance(s, str):
if s.lower() in ('true', 't', 'yes', 'y', '1'):
return '1'
if s.lower() in ('false', 'f', 'no', 'n', '0'):
return '0'
if isinstance(s, bool):
if s:
return '1'
return '0'
raise ValueError("Cannot covert {} to a 1 or 0".format(s))
|
def safe_int(val, allow_zero=True):
"""
This function converts the six.moves.input values to integers. It handles
invalid entries, and optionally forbids values of zero.
"""
try:
ret = int(val)
except ValueError:
print("Sorry, '%s' is not a valid integer." % val)
return False
if not allow_zero and ret == 0:
print("Please enter a non-zero integer.")
return False
return ret
|
def flatten(l):
"""Flatten nested lists into a single-level list"""
if l and type(l[0]) == list:
rv = []
for e in l:
if type(e) == list:
rv.extend(e)
else:
rv.append(e)
return rv
else:
return l
|
def _query_worrying_level(time_elapsed, state):
"""
Gives a "worriness" level to a query
For instance, long times waiting for something to happen is bad
Very long times sending is bad too
Return a value between 0 and 1 rating the "worrying level"
See http://dev.mysql.com/doc/refman/5.7/en/general-thread-states.html
"""
state_lower = state.lower()
if state in ('creating sort index', 'sorting result'):
max_time = 60
elif state in ('creating table', 'creating tmp table', 'removing tmp table'):
max_time = 180
elif state == 'copying to tmp table on disk':
max_time = 60
elif state in ('executing', 'preparing'):
max_time = 300
elif state == 'logging slow query':
return 0.5
elif state_lower == 'sending data':
max_time = 600
elif state_lower in ('sorting for group', 'sorting for order'):
max_time = 60
elif state_lower.startswith('waiting'):
max_time = 600
else:
return 0
if time_elapsed > max_time:
return 1
else:
return float(time_elapsed) / max_time
|
def setdefaultattr(obj, name, value):
"""Set attribute with *name* on *obj* with *value* if it doesn't exist yet
Analogous to dict.setdefault
"""
if not hasattr(obj, name):
setattr(obj, name, value)
return getattr(obj, name)
|
def humio_headers(args):
"""Humio structured api endpoint"""
return {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + args['humio-token']}
|
def func1(arg1, arg2):
"""
This function take two arguments, sets the first to equal the second, then returns the new first argument. Pointless.
This is my personal edit. Let's see if this works.
:param arg1: Some value
:param arg2: Another value
:return: arg1
"""
arg1 = arg2
return arg1
|
def _get_redshift_cluster_arn(event: dict) -> str:
""" Get ARN of Redshift cluster """
account_id = event['userIdentity']['accountId']
region = event['awsRegion']
cluster_identifier = event['responseElements']['clusterIdentifier']
return f"arn:aws:redshift:{region}:{account_id}:cluster:{cluster_identifier}"
|
def get_bit(val: int, bitNo: int) -> int:
"""
Get bit from int
"""
return (val >> bitNo) & 1
|
def camel_case_convert(item: str) -> str:
"""Converts strings that look_like_this to
strings that lookLikeThis"""
item = (
item.title().replace(" ", "").replace("_", "").replace("-", "")
) # removing all '_', '-', and spaces
item = item[0].lower() + item[1:] if item else ""
return item
|
def generate_realtime_processed_dto_to_build_dataframe(data_object: dict) -> dict:
"""
Get a dictionary, remove the unnecessary part then return the dictionary to add this data on a dataframe
:param data_object: dictionary representing the processed
:return: a dictionary which is compatible /w dataframe schema.
"""
keys_to_keep = ['timestamp', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count']
# Generate needed keys
for item in range(len(keys_to_keep)):
try:
print(keys_to_keep[item], data_object[keys_to_keep[item]])
except KeyError:
data_object[keys_to_keep[item]] = 0.
# Remove unneeded keys
for key in list(data_object.keys()):
if key not in keys_to_keep:
del data_object[key]
return data_object
|
def cls_name(cls):
"""Return the full name of a class (including the it's module name)."""
return "{}.{}".format(cls.__module__, cls.__name__)
|
def has_attrs(obj, attrs):
"""Check that an object has specific attributes"""
assert type(attrs) in {list, set}, "Second argument must be list/set of attributes"
for attr in attrs:
if not hasattr(obj, attr):
raise ValueError("Required metadata attribute '{0}' is missing, "
"check data object metadata".format(attr))
if not getattr(obj, attr):
raise ValueError("Required metadata attribute '{0}' does not have a "
"value, check data object metadata".format( attr))
return True
|
def __get_correction_factor(temperature, humidity):
"""Calculates the correction factor for ambient air temperature and relative humidity
Based on the linearization of the temperature dependency curve
under and above 20 degrees Celsius, assuming a linear dependency on humidity,
provided by Balk77 https://github.com/GeorgK/MQ135/pull/6/files
0.00035 - 'CORA' Parameters to model temperature and humidity dependence
0.02718 - 'CORB'
1.39538 - 'CORC'
0.0018 - 'CORD'
-0.003333333 - 'CORE'
-0.001923077 - 'CORF'
1.130128205 - 'CORG'
"""
if temperature < 20:
return 0.00035 * temperature * temperature - 0.02718 \
* temperature + 1.39538 - (humidity - 33.) * 0.0018
return -0.003333333 * temperature + -0.001923077 * humidity + 1.130128205
|
def clean_data(data):
"""Clean data tuples returned from api"""
return list(map(lambda entry: [str(entry[0]), str(entry[1])], data))
|
def sum_digit(number):
"""
Calculate the sum of a number's digits
"""
assert type(number) == int
number_str = str(number)
number_list = [int(i) for i in list(number_str)]
return sum(number_list)
|
def temporal_iou(span_A, span_B):
"""
Calculates the intersection over union of two temporal "bounding boxes"
span_A: (start, end)
span_B: (start, end)
"""
union = min(span_A[0], span_B[0]), max(span_A[1], span_B[1])
inter = max(span_A[0], span_B[0]), min(span_A[1], span_B[1])
if inter[0] >= inter[1]:
return 0
else:
return float(inter[1] - inter[0]) / float(union[1] - union[0])
|
def _contains_sample(pairs_list, sample):
"""Returns pairs_list that contains the sample"""
pairs_list_f = [x for x in pairs_list
if sample in [x[0][0], x[1][0]]]
return pairs_list_f
|
def UsedFramework(module):
"""
Tells which framework module is based on.
Arguments:
-module:
The object to test
Returns:
-'keras' if module is a keras object
-'torch' if module is a pyTorch object
-None if none of them
"""
moduleClass = str(module.__class__)[8:-2]
IsKeras = 'keras' in moduleClass
IsTorch = 'torch' in moduleClass
if '_backend' in dir(module):
IsTorch = IsTorch or 'torch' in str(module._backend)
if IsKeras:
return 'keras'
if IsTorch:
return 'torch'
return None
|
def postprocess_int(field, value, **options):
"""Convert a string to an integer."""
try:
return int(value)
except (ValueError, TypeError):
return value
|
def int_to_sequence(integer):
"""Return a list of each digit in integer
For example:
1111 -> [1, 1, 1, 1]
451 -> [4, 5, 1]
"""
return [int(n) for n in str(integer)]
|
def _get_item(node):
"""
Returns the item element of the specified node if [the node] is not null.
:param node: The node to extract the item from.
:return: A node's item.
"""
return node.item if node is not None else None
|
def mult_table(size):
"""
Build Multiplication table given an integer value.
:param size: an interger value.
:return: NxN multiplication table, of size provided in parameter.
"""
return [[i * j for i in range(1, size + 1)] for j in range(1, size + 1)]
|
def num_matches(list1, list2):
"""returns the number of elements that the
2 lists have in common"""
#sorted already?
#list1.sort()
#list2.sort()
matches = i = j = 0
lenLst1 = len(list1)
lenLst2 = len(list2)
while i < lenLst1 and j < lenLst2:
if list1[i] < list2[j]:
i+=1
elif list1[i] > list2[j]:
j+=1
else: #they are the same
matches+=1
i+=1
j+=1
return matches
|
def flatten(list_like, recursive=True):
""" Flattens a list-like datastructure (returning a new list). """
retval = []
for element in list_like:
if isinstance(element, list):
if recursive:
retval += flatten(element, recursive=True)
else:
retval += element
else:
retval.append(element)
return retval
|
def _find_contiguous_colors(colors):
"""
Helper function that finds the continuous segments of colors
and returns those segments
Code adapted from:
http://abhay.harpale.net/blog/python/how-to-plot-multicolored-lines-in-matplotlib/
"""
segs = []
curr_seg = []
prev_color = ''
for c in colors:
if c == prev_color or prev_color == '':
curr_seg.append(c)
else:
segs.append(curr_seg)
curr_seg = []
curr_seg.append(c)
prev_color = c
segs.append(curr_seg) # the final one
return segs
|
def bigrams(text):
"""Return a list of pairs in text (a sequence of letters or words).
>>> bigrams('this')
['th', 'hi', 'is']
>>> bigrams(['this', 'is', 'a', 'test'])
[['this', 'is'], ['is', 'a'], ['a', 'test']]
"""
return [text[i:i+2] for i in range(len(text) - 1)]
|
def GetGuestPolicyUriPath(parent_type, parent_name, policy_id):
"""Returns the URI path of an osconfig guest policy."""
return '/'.join([parent_type, parent_name, 'guestPolicies', policy_id])
|
def all_equal(iterable):
"""
Check all elements of an iterable (e.g., list) are identical
"""
return len(set(iterable)) <= 1
|
def cv_tiered_list(list):
"""The tag is hiding recursive loop for generation tiered list of CV options,
it makes template code more readable."""
answer = ""
for item in list:
point = item['text']
if item['href']:
point = '<a href="{0}">{1}<span class="bx bx-link"/></a>'.format(item['href'], point)
if len(item['subdetails']) > 0:
point += cv_tiered_list(item['subdetails'])
answer += "<li>{}</li>".format(point)
if answer:
answer = '<ul>{}</ul>'.format(answer)
return answer
|
def rename_name(points, linestrings):
"""Rename the 'name' property to 'trip' on linestrings and 'city' on points."""
for point in points:
name = point['properties']['name']
point['properties']['city'] = name
del point['properties']['name']
for linestring in linestrings:
name = linestring['properties']['name']
linestring['properties']['trip'] = name
del linestring['properties']['name']
return points, linestrings
|
def test_function_with_fixed_args(meta, name):
"""This form is ok, but will fail if `name` is not provided."""
return f"hello {name}"
|
def get_operand_expression(nvols):
"""
Generates operand string
Parameters
----------
nvols : int
Returns
-------
expr : string
"""
expr = None
vol = int(nvols)
expr = ('a*sqrt(%d-3)' % vol)
return expr
|
def filter_func(bigrams):
"""
Given a list of bigrams from a review's text, returns true if the review is
incentivized by using a lookup list
:param bigrams: Bigrams from the review's text, lemmatized for better matching
:return: True if the review is incentivized, False otherwise
"""
# Tuples are saved as lists in Spark dataframes, convert them back to tuples
# and use set for faster searching
bg = set([tuple(b) for b in bigrams])
# Look for specific bigrams in the list
return (('complimentary', 'copy') in bg) or \
(('discount', 'exchange') in bg) or \
(('exchange', 'product') in bg) or \
(('exchange', 'review') in bg) or \
(('exchange', 'unbiased') in bg) or \
(('exchange', 'free') in bg) or \
(('exchange', 'honest') in bg) or \
(('exchange', 'true') in bg) or \
(('exchange', 'truth') in bg) or \
(('fair', 'review') in bg) or \
(('free', 'discount') in bg) or \
(('free', 'exchange') in bg) or \
(('free', 'sample') in bg) or \
(('free', 'unbiased') in bg) or \
(('honest', 'feedback') in bg) or \
(('honest', 'unbiased') in bg) or \
(('opinion', 'state') in bg) or \
(('opinion', 'own') in bg) or \
(('provide', 'exchange') in bg) or \
(('provide', 'sample') in bg) or \
(('provided', 'sample') in bg) or \
(('provided', 'exchange') in bg) or \
(('receive', 'free') in bg) or \
(('receive', 'free') in bg) or \
(('received', 'free') in bg) or \
(('received', 'sample') in bg) or \
(('return', 'unbiased') in bg) or \
(('review', 'sample') in bg) or \
(('sample', 'product') in bg) or \
(('sample', 'unbiased') in bg) or \
(('sample', 'free') in bg) or \
(('send', 'sample') in bg) or \
(('unbiased', 'review') in bg) or \
(('unbiased', 'opinion') in bg) or \
(('unbiased', 'view') in bg)
|
def _get_latest_checkpoint_number(latest_checkpoint):
"""Get latest checkpoint number from latest_checkpoint.
Return None if latest_checkpoint is None or failed to get number
"""
checkpoint_number = None
if latest_checkpoint and isinstance(latest_checkpoint, str):
if '-' in latest_checkpoint:
number_str = latest_checkpoint.rsplit('-', 1)[1]
if number_str.isdigit():
checkpoint_number = int(number_str)
return checkpoint_number
|
def modular_inverse(a, n):
"""
Used for division in elliptic curves. Very important in RSA/ECDSA algorithms.
It uses EGCD.
Extended Euclidean Algorithm:
- http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
- http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
"""
lm, hm = 1,0
low, high = a%n,n
while low > 1:
ratio = high/low
nm, new = hm-lm*ratio, high-low*ratio
lm, low, hm, high = nm, new, lm, low
return lm % n
|
def collatz_sequence_length(starting_value: int) -> int:
"""
Given solution relies on just calculating the length, which takes out the longer and more
expensive collatz calculation that requires storing the sequence. Passing the integer parameter
is cheaper than storing, appending, and passing a list data structure.
:param starting_value: the integer in the collatz
:return: returns the length
"""
if starting_value < 2:
return 1
if not starting_value % 2:
return 1 + collatz_sequence_length(starting_value // 2)
return 1 + collatz_sequence_length(3 * starting_value + 1)
|
def update_eta(gamma,sigmax):
"""
Args: gamma and sigmax: scalar
Return: scalar
"""
r = -1/sigmax
return 1/(1+gamma*r)
|
def flip_vert_tile(s):
"""Flip a tile vertically, return str repr."""
return str.join("\n", list(reversed(s.split("\n"))))
|
def get_bound_indices(str1, str2):
"""Returns the aligned and not bound indices of str1, str2
:param str str1: the first string to align
:param str str2: the second string to align
Caution: order matters, a lot! --> str1 is going to be traversed the other way around # noqa
:return: the free along with the bound indices
:rtype: tuple(list, list), tuple(list, list)
"""
free_str1_indices = []
free_str2_indices = []
bound_str1_indices = []
bound_str2_indices = []
# we need to traverse str1 reversed and use the reversed indices
for i in range(0, len(str1)):
if str1[i] != "-":
bound_str1_indices.append(i)
else:
free_str1_indices.append(i)
for i in range(0, len(str2)):
if str2[i] != "-":
bound_str2_indices.append(i)
else:
free_str2_indices.append(i)
return (
free_str1_indices,
free_str2_indices,
bound_str1_indices,
bound_str2_indices,
)
|
def schedule_confirm(message, description, bus_stop_code, selected_buses):
"""
Message that will be sent to user once they confirm their schedule
:param message: Time
:param description: Bus Stop Name
:param bus_stop_code: Bus Stop Code
:param selected_buses: Bus selected for scheduling message
:return:
"""
return 'You will receive message at {}H for <b>{} (/{})</b>.\n\nBus: <b>{}</b>\n\n' \
'You can view all your schedules at /settings and clicking the "View Scheduled Message" button'.\
format(message, description, bus_stop_code, selected_buses)
|
def parse_num(s):
""" parse a string into either int or float.
"""
try:
return int(s)
except ValueError:
return float(s)
|
def to_lbs(amount):
"""Converts an amount from grams to lbs rounded to two decimal places"""
return round(amount*.0022, 2)
|
def get_excel_column_index(column: str) -> int:
"""
This function converts an excel column to its respective column index as used by pyexcel package.
viz. 'A' to 0
'AZ' to 51
:param column:
:return: column index of type int
"""
index = 0
column = column.upper()
column = column[::-1]
for i in range(len(column)):
index += ((ord(column[i]) % 65 + 1)*(26**i))
return index-1
|
def errToLogX(x, y=None, dx=None, dy=None):
"""
calculate error of Log(x)
:param x: float value
:param dx: float value
"""
if dx is None:
dx = 0
# Check that the x point on the graph is zero
if x != 0:
dx = dx / x
else:
raise ValueError("errToLogX: divide by zero")
return dx
|
def dict_slice(dictionary,start=None,end=None,step=None):
"""
Slice a dictionary based on the (possibly arbitrary) order in which the keys are delivered
:param dictionary:
:param start:
:param end:
:param step:
:returns:
"""
return {k:dictionary.get(k) for k in list(dictionary.keys())[start:end:step]}
|
def hsva_to_rgba(h, s, v, alpha=1.0):
"""Converts a color given by its HSVA coordinates (hue, saturation,
value, alpha) to RGB coordinates.
Each of the HSVA coordinates must be in the range [0, 1].
"""
# This is based on the formulae found at:
# http://en.wikipedia.org/wiki/HSL_and_HSV
c = v * s
h1 = (h * 6) % 6
x = c * (1 - abs(h1 % 2 - 1))
m = v - c
h1 = int(h1)
if h1 < 3:
if h1 < 1:
return (c + m, x + m, m, alpha)
elif h1 < 2:
return (x + m, c + m, m, alpha)
else:
return (m, c + m, x + m, alpha)
else:
if h1 < 4:
return (m, x + m, c + m, alpha)
elif h1 < 5:
return (x + m, m, c + m, alpha)
else:
return (c + m, m, x + m, alpha)
|
def pressure_to_kpa(pressure):
""" convert 1000 Pa to kpi """
kpa = pressure / 10.0
return kpa
|
def get_unique_item(items: set, item: str) -> str:
"""
Returns an item which is not in the set. The basic item name is sent as a parameter and
the returned item may be of the form 'item_#', where number is the first available.
The new item is added to the set to ensure two subsequent calls return different items.
Args:
items: the current set of items
item: the item to add
Returns:
The first item available, possibly in the form of 'item_#'.
"""
sequence = 1
compound_item = item
while compound_item in items:
sequence += 1
compound_item = item + f'_{sequence}'
items.add(compound_item)
return compound_item
|
def CMP(x=None, y=None):
"""
Compares two values and returns:
-1 if the first value is less than the second.
1 if the first value is greater than the second.
0 if the two values are equivalent.
See https://docs.mongodb.com/manual/reference/operator/aggregation/cmp/
for more details
:param x: first value or expression
:param y: second value or expression
:return: Aggregation operator
"""
if x is None and y is None:
return {'$cmp': []}
return {'$cmp': [x, y]}
|
def parse_error(error):
"""Return the error name."""
if error.endswith("genome-size-error.txt"):
return ["genome-size-error", "Poor estimate of genome size"]
elif error.endswith("low-read-count-error.txt"):
return ["low-read-count-error", "Low number of reads"]
elif error.endswith("low-sequence-depth-error.txt"):
return ["low-sequence-depth-error", "Low depth of sequencing"]
elif error.endswith("paired-end-error.txt"):
return ["paired-end-error", "Paired-end read count mismatch"]
return ["unknown-error", "Unknown Error"]
|
def get_email_domain_from_username(username):
"""
A quick utility for getting an Email Domain from a username
(the last part of the email after the '@' sign)
:param username: String
:return: Domain name string. `None` if there is no domain name.
"""
split_username = username.split('@')
if len(split_username) < 2:
# Not a real email address with an expected email domain.
return None
# we take the last split because `@` is technically an allowed character if
# inside a quoted string.
# See https://en.wikipedia.org/wiki/Email_address#Local-part
return split_username[-1]
|
def get_path_details(formatted, original, file=None):
"""
Return original path information in a consistent format.
"""
if formatted == original:
if file is None:
message = ""
else:
message = " (in '{}')".format(file)
else:
if file is None:
message = " (specified as '{}')".format(original)
else:
message = " (specified as '{}' in '{}')".format(original, file)
return message
|
def calc_scale(src_width, src_height, dst_width, dst_height):
"""scale into max size but do not upscale"""
scale = min(dst_width / src_width, dst_height / src_height)
return min(scale, 1)
|
def divisibleby(value, arg):
"""Returns True if the value is devisible by the argument."""
return int(value) % int(arg) == 0
|
def to_snake_case(name):
"""Convert a name from camelCase to snake_case. Names that already are
snake_case remain the same.
"""
name2 = ""
for c in name:
c2 = c.lower()
if c2 != c and len(name2) > 0 and name2[-1] not in "_123":
name2 += "_"
name2 += c2
return name2
|
def lines_get_first_line(lines: str) -> str:
"""Return the first non-empty line in lines."""
return lines.strip().splitlines()[0]
|
def insertion_sort(arr: list, increment=1) -> list:
"""Sorts arr in-place in by implementing
https://en.wikipedia.org/wiki/Insertion_sort
"""
for i in range(increment, len(arr)):
for j in range(i - increment, -1, -increment):
if arr[j] > arr[j+increment]:
arr[j+increment], arr[j] = arr[j], arr[j+increment]
else:
break
return arr
|
def removed(letters, remove):
"""Return a string of letters, but with each letter in remove removed once."""
for L in remove:
letters = letters.replace(L, '', 1)
return letters
|
def test_function_with_single_kwarg(name=None):
"""This cannot be called because meta is always passed."""
return f"hello {name}"
|
def sizeof_fmt(num, suffix='B'):
""" Format sizes """
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
|
def move_consonant_right(letters: list, positions: list) -> list:
"""Given a list of letters, and a list of consonant positions, move the consonant positions to
the right, merging strings as necessary.
>>> move_consonant_right(list("abbra"), [ 2, 3])
['a', 'b', '', '', 'bra']
"""
for pos in positions:
letters[pos + 1] = letters[pos] + letters[pos + 1]
letters[pos] = ""
return letters
|
def letter_check(word,check_ord):
"""
Checks for a letter with the ordval stored in check_ord within word.
Returns false if word contains that letter.
Returns true if word doesn't contain that letter.
"""
for letter in range(0,len(word)):
ordval = ord(word[letter])
if ordval == check_ord:
return False
return True
|
def sub_poly(p, g):
"""Returns a difference of two polynomials"""
result = [m.copy() for m in p]
for m in g:
k = m.copy()
k.c = -k.c
result.append(k)
return result
|
def fibSumThreeTracker(n0):
"""
Created on Mon Aug 23 07:40:53 2021
@author: Ezra
fibSumThree(n0) function to find the sum of all the terms in the
Fibonacci sequence divisible by three whih do not exceed n0.
Input: n0 is the largest natural number considered
Output: fibSumThreeTracker-
x: Fibonacci numbers taht are divisible by 3
y: The sum of the Fibonacci terms divisible by 3
that do not exceed n0
the sum of the Fibonacci terms divisible by 3 that do
not exceed n0. keeps track of intermeiate values.
"""
a=0
b=1
fibSum3 = 0
x=[]
y=[]
while b < n0:
if b % 3 == 0 :
fibSum3 = fibSum3 + b
x.append(b)
y.append(fibSum3)
c =a+b
a=b
b=c
return x,y
print("b=", "fibSum3",fibSum3)
return fibSum3
|
def ucfirst(value: str):
"""Uppercase first letter in sentence and leaves rest alone"""
return value[0].upper() + value[1:]
|
def field_2_factory_func(field):
"""Convert a sqlalchemy field into a corresponding factory boy function.
These functions are used as LazyAttribute functions that are
pre-defined in `factories.py`
"""
field = repr(field)
return ''
if 'sql.sqltypes.Text' in field or 'sql.sqltypes.String' in field:
return 'rand_str'
elif 'sql.sqltypes.Date' in field:
return 'new_date'
elif 'sql.sqltypes.BigInteger' in field:
return 'rand_int'
elif 'sql.sqltypes.SmallInteger' in field:
return 'rand_int'
elif 'sql.sqltypes.Integer' in field:
return 'rand_int'
else:
print('COULD NOT FIND MAPPING!')
return ''
|
def translator(string):
"""
string = list(string)
pig = string[0]
del string[0]
string.append(pig)
string.append("ay")
string = str(string)
return string
# will get the result "['w', 'o']" . don't use this way
"""
# the right way is to use slice to cut user input into different sections.
pig = string[0:1]
string = string[1:]
string = string + pig + 'ay'
return string
|
def separate_substructures(tokenized_commands):
"""Returns a list of SVG substructures."""
# every moveTo command starts a new substructure
# an SVG substructure is a subpath that closes on itself
# such as the outter and the inner edge of the character `o`
substructures = []
curr = []
for cmd in tokenized_commands:
if cmd[0] in 'mM' and len(curr) > 0:
substructures.append(curr)
curr = []
curr.append(cmd)
if len(curr) > 0:
substructures.append(curr)
return substructures
|
def error_to_string(error):
""" Helper to derive information from an error even if blank """
return getattr(error, 'message', str(error) or type(error).__name__)
|
def fp(i, n):
"""Calculates the compound amount factor.
:param i: The interest rate.
:param n: The number of periods.
:return: The calculated factor.
"""
return (1 + i) ** n
|
def split_arguments(s):
"""
split command line input and extract arguments
:param s: command line input
:return: (command, arguments)
"""
# split with "'"
parts_quote = s.split("'")
parts_final = []
for i in range(len(parts_quote)):
if i == "":
# skip empty parts
continue
elif i % 2 == 1:
# parts surrounded by quotation marks (eg: "word documents.doc")
# do not need further splittings
parts_final.append(parts_quote[i])
else:
# other parts do need further splittings
# split and add non empty parts
parts_final = parts_final + [x for x in parts_quote[i].split(" ") if not x == ""]
command = parts_final[0]
arguments = []
if len(parts_final) > 1:
arguments = parts_final[1:]
return command, arguments
|
def argsort(seq):
""" The numpy sort is inconistent with the matlab version for values that are the same """
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__)
|
def nSquaredSum(X, Y):
"""Returns negative squared sum of X and Y"""
return -(X**2 + Y**2)
|
def bitsize(x):
"""Return size of long in bits."""
return len(bin(x)) - 2
|
def encode(array, encoding):
"""Encodes 'array' with the encoding specified in encoding.
This value must be a dictionary"""
encoded = []
for i in array:
encoded.append(encoding[i])
return encoded
|
def col255_from_RGB(red,green,blue):
""" returns a term256 colour index from RGB value
found at :
https://unix.stackexchange.com/questions/269077/
"""
if red > 255:
red = 255
if green > 255:
green = 255
if blue > 255:
blue = 255
if red < 75:
red = 0
else:
red = ((red -35)/40)
red = red*6*6
if green < 75:
green = 0
else:
green = ((green - 35)/40)
green = green*6
if blue<75:
blue = 0
else:
blue = ((blue -35)/40)
j = int(red+green+blue+16)
if j>255:
j=255
return j
|
def avg_value(avg: float) -> str:
"""
"""
return "Average Value : {:.2f}".format(avg)
|
def compute_precision_recall(correct_chunk_cnt, found_pred_cnt, found_correct_cnt):
"""Computes and returns the precision and recall.
Args:
correct_chunk_cnt: The count of correctly predicted chunks.
found_pred_cnt: The count of predicted chunks.
found_correct_cnt : The actual count of chunks.
Returns:
The slot precision and recall
"""
if found_pred_cnt > 0:
precision = 100 * correct_chunk_cnt / found_pred_cnt
else:
precision = 0
if found_correct_cnt > 0:
recall = 100 * correct_chunk_cnt / found_correct_cnt
else:
recall = 0
return precision, recall
|
def _dict_compare(d1, d2):
"""
We care if one of two things happens:
* d2 has added a new key
* a (value for the same key) in d2 has a different value than d1
We don't care if this stuff happens:
* A key is deleted from the dict
Should return a list of keys that either have been added or have a different value than they used to
"""
keys_added = set(d2.keys()) - set(d1.keys())
keys_changed = [k for k in d1.keys() if k in d2.keys() and d1[k] != d2[k]]
return list(keys_added) + keys_changed
|
def _get_coord_shift(ndim):
"""Compute target coordinate based on a shift.
Notes
-----
Assumes the following variables have been initialized on the device::
in_coord[ndim]: array containing the source coordinate
shift[ndim]: array containing the zoom for each axis
computes::
c_j = in_coord[j] - shift[j]
"""
ops = []
for j in range(ndim):
ops.append(
"""
W c_{j} = (W)in_coord[{j}] - shift[{j}];""".format(j=j))
return ops
|
def e_oeste(arg):
"""
e_oeste: direcao --> logico
e_oeste(arg) tem o valor verdadeiro se arg for o elemento 'W' e falso caso
contrario.
"""
return arg == 'W'
|
def document(populated):
"""second document, containing three pages"""
next(populated)
return next(populated)
|
def isPerfectSquare_v2(num: int) -> bool:
"""
This O(1) solution were contributed to LeetCode by another user.
Way faster than my first solution!
A good example why you should always: 'Know your standard API!'
But there is so much much python magic in it, that it almost feels like cheating.
"""
return (num ** 0.5).is_integer()
|
def _bin_to_dec(num):
"""
Converts a binary vector to a decimal number.
"""
return sum([num[i]*2**i for i in range(len(num))])
|
def GetSegmentOfUrl(url: str, prefix: str) -> str:
"""
Get the next segment from url following prefix. The return value is a segment without slash.
For example, url = "projects/test-project/global/networks/n1",
and prefix = "networks/", then the return value is "n1".
"""
if not url: return ""
if not prefix: return ""
if not prefix.endswith("/"): prefix += "/"
offset = url.find(prefix)
if offset == -1: return ""
offset += len(prefix)
end = url.find("/", offset)
if end == -1: end = len(url)
return url[offset:end]
|
def fix_trailing_slashes(s):
""" remove abritrary number of trailing slashes"""
s = s.strip() # first remove spaces
while s[-1] == '/':
s = s.strip('/')
return(s)
|
def shorten_to_63_chars(string):
"""
Trims the middle out of a string until it's <= 63 characters.
Useful because postgres limits column names to 63 chars.
"""
string = str(string)
if len(string) > 63:
out = '%s...%s'%(string[:30], string[-30:])
print(out)
return out
return string
|
def encode_maybe(encode_func, value):
"""Encode the value."""
if value is None:
return 'Nothing'
else:
return '(Just $ ' + encode_func(value) + ')'
|
def convert_to_minotl(outline, indent = 4, curr_indent = 0):
"""Converts to a standard minotl format"""
lines = []
for i in outline:
if type(i) == str:
lines.append("%s%s" % (curr_indent * " ", i))
else:
lines.append("%s%s" % (curr_indent * " ", i[0]))
lines.append(convert_to_minotl(i[1], indent, indent +
curr_indent))
return '\n'.join(lines)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.