content stringlengths 42 6.51k |
|---|
def readable_size(n):
"""Return a readable size string."""
sizes = ['K', 'M', 'G']
fmt = ''
size = n
for i, s in enumerate(sizes):
nn = n / (1000 ** (i + 1))
if nn >= 1:
size = nn
fmt = sizes[i]
else:
break
return '%.2f%s' % (size, fmt) |
def custom_func_quotify(populator, value, **kwargs):
"""Add quotes to the value.
"""
value = value if value is None else str(value)
value = value.replace('"', '""')
return f'"{value}"' |
def num2bits(num, length=0):
"""
Convert a number to an array of bits of the give length
"""
if length and num.bit_length() > length:
raise ValueError('Number does not fit in bits')
bits = []
while num:
bits.insert(0, num & 1)
num = num >> 1
return [0] * (length - len... |
def md_getAccuracy(field):
"""Get accuracy"""
return field.split(',')[2].strip() |
def factorial(n):
"""
factorial
@param n:
@return:
"""
return 1 if n < 2 else n * factorial(n-1) |
def orthogonal(a):
"""Return an arbitrary vector orthogonal to the input vector.
:type a: tuple of floats.
:return b: tuple of floats.
"""
if len(a) == 1:
return None
# Handle the vector generation one way if any elements
# of the input vector are zero.
if not all(a):
re... |
def linear_search_iterative(elements, key):
"""
An index, i, where A[i] = k.
If there is no such i, then
NOT_FOUND.
"""
for idx, value in enumerate(elements):
if key == value:
return idx
return "Not Found" |
def get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic):
"""
Get site ID - transcript ID combination score, based on selected
transcripts for each of the 10 different filter settings.
10 transcript quality filter settings:
EIR
EXB
TSC
ISRN
ISR
ISRFC
S... |
def white_listed(url, white_listed_urls, white_listed_patterns):
"""
check if link is in the white listed URLs or patterns to ignore.
"""
# check white listed urls
if url in white_listed_urls:
return True
# check white listed patterns
i = 0
while i < len(white_listed_patterns):
... |
def pt(n):
"""
Return list of pythagorean triples as non-descending tuples
of ints from 1 to n.
Assume n is positive.
@param int n: upper bound of pythagorean triples
"""
# helper to check whether a triple is pythagorean and non_descending
# you could also use a lambda instea... |
def trapped_water(heights):
"""
Question 18.8: Compute the maximum water
trapped by a pair of vertical lines
"""
max_water = 0
left = 0
right = len(heights) - 1
while left < right:
max_water = max(
max_water,
(right - left) * min(heights[left], heights[r... |
def gitlab_build_params_pagination(page, per_page):
"""https://docs.gitlab.com/ce/api/README.html#pagination"""
return {
'page': str(page),
'per_page': str(per_page)
} |
def is_file_like(obj):
"""
Check if the object is a file-like object.
For objects to be considered file-like, they must
be an iterator AND have either a `read` and/or `write`
method as an attribute.
Note: file-like objects must be iterable, but
iterable objects need not be file-like.
... |
def breadcrumb_trail(context):
"""
Renders a two-tuple of page URLs and titles (see the
:ref:`breadcrumb_trail <context_breadcrumb_trail>` context variable for more information)
"""
return {
'breadcrumb_trail': context.get('breadcrumb_trail')
} |
def spasser(inbox, s=None):
"""
Passes inputs with indecies in s. By default passes the whole inbox.
Arguments:
- s(sequence) [default: ``None``] The default translates to a range for
all inputs of the "inbox" i.e. ``range(len(inbox))``
"""
seq = (s or range(len(inbox)))
ret... |
def prefix(values, content):
"""
Discover start and separate from content.
Will raise ValueError if none of the starts match.
"""
for value in values:
if content.startswith(value):
break
else:
raise ValueError('invalid starts')
content = content[len(value):... |
def symbol_converted(symbol):
"""
Input: symbol in the form '0005.HK' (from Alpha Vantange data)
Output: symbol in the form '5' (for TWS)
"""
slice_index = 0
for i in range(0,4):
if symbol[i]=='0':
slice_index = i+1
else:
break
return symbol[slice_inde... |
def is_comment(s):
""" function to check if a line
starts with some character.
Here # for comment
"""
# return true if a line starts with #
return s.startswith('#') |
def format_data(account):
"""Takes the account data and returns the printable format."""
account_name = account["name"]
account_descr = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_descr}, from {account_country}" |
def is_web_safe(r: int, g: int, b: int, a: int):
"""
True if the rgba value is websafe.
Cite: https://www.rapidtables.com/web/color/Web_Safe.html
"""
if a != 255:
return False
else:
return all(x in (0, 0x33, 0x66, 0x99, 0xCC, 0xFF) for x in (r, g, b)) |
def chan_id(access_address):
"""
Compute channel identifier based on access address
"""
return ((access_address&0xffff0000)>>16) ^(access_address&0x0000ffff) |
def order(x):
"""
Determine sort order of char (x)
:param x: character to test
:return: order value
char class order value
---------- -----------
'~' -1
digits 0
empty 0
letters ascii x
non-letters ascii x + 256
"""
return \
... |
def Re_intube_waste(W_mass, z_way_waste, d_inner_waste, n_pipe_waste, mu_waste_avrg):
"""
Calculates the Reynold criterion.
Parameters
----------
F_mass : float
The mass flow rate of feed [kg/s]
z_way_waste : float
The number of ways in heat exchanger [dimensionless]
d_inner_... |
def pack_rle(data):
"""Use run-length encoding to pack the bytes"""
rle = []
value = data[0]
count = 0
for i in data:
if i != value or count == 255:
rle.append(count)
rle.append(value)
value = i
count = 1
else:
count += 1
rle.append(count)
rle.append(value)
return r... |
def num_desc_seq_given_total_and_head(total, head):
"""
Subproblem in dynamic programming.
Count the number of descending sequences given a total and the head.
Note that a one-term sequence is also considered a sequence.
"""
if total < 1 or head < 1:
return 0
# base case: sequence h... |
def fs15f16(x):
"""Convert float to ICC s15Fixed16Number (as a Python ``int``)."""
return int(round(x * 2 ** 16)) |
def Wday(month, day):
"""
Function that yields the weekday given the month and the day
Works for the year 2013, months 11 and 12
"""
out=["Mo","Tu","We","Th","Fr","Sa","Su"]
if(month==11):
return out[(4+day)%7]
if(month==12):
return out[(6+day)%7] |
def sort_dictionary_lists(dictionary):
"""
Give a dictionary, call `sorted` on all its elements.
"""
for key, value in dictionary.items():
dictionary[key] = sorted( value )
return dictionary |
def multiplicative_inverse(e, phi):
"""
Euclid's extended algorithm for finding the multiplicative inverse of two numbers
"""
d, next_d, temp_phi = 0, 1, phi
while e > 0:
quotient = temp_phi // e
d, next_d = next_d, d - quotient * next_d
temp_phi, e = e, temp_phi - quotient *... |
def attribute(
name, anchor_id, attribute_type, desc=None, options=None, default_option_id=None
):
"""
Create VIA attribute.
:param name: str, attribute name
:param anchor_id:
'FILE1_Z0_XY0':'Attribute of a File (e.g. image caption)',
'FILE1_Z0_XY1':'Spatial Region in an Image (e.g. bou... |
def get_dict(
date: str,
time: str,
sender: str,
message: str,
weekday: str,
hour_of_day: str,
) -> dict:
"""Return dictionary to build DF."""
return dict(
date=date,
time=time,
sender=sender,
message=message,
weekday=weekday,
hour_of_day=h... |
def format_sequence(sequence):
"""Convert a binary sequence of 16 bits into an int.
:param sequence: String composed of 16 zeroes or ones.
:return: int value of the binary sequence, or -1 if the sequence is not 16
characters long or contains characters others than 0 or 1.
"""
is_binary ... |
def is_index_out(index, arr):
"""
:param index: looping index
:param arr: array / list
:return: bool -> if index out of range
"""
return index < len(arr)-1 |
def wavelength_to_rgb(wavelength, gamma=0.8):
"""
This converts a given wavelength of light to an
approximate RGB color value. The wavelength must be given
in nanometers in the range from 380 nm through 750 nm
(789 THz through 400 THz).
Based on code by Dan Bruton
http://www.physics.sfasu.e... |
def quadinout(x):
"""Return the value at x of the 'quadratic in out' easing function between 0 and 1."""
if x < 0.5:
return 2*x**2
else:
return 1/2 - x*(2*x-2) |
def format_mask(bitmask):
"""
Formats a numerical bitmask into a binary string.
:Parameters:
bitmask: integer
A bit mask (e.g. 145)
:Returns:
bitstring: str
A string displaying the bitmask in binary
(e.g. '10010001')
"""
assert is... |
def armenian_date(year, month, day):
"""Return the Armenian date data structure."""
return [year, month, day] |
def _expand_ranges(ranges_text, delimiter=',', indicator='-'):
""" Expands a range text to a list of integers.
For example:
.. code-block:: python
range_text = '1,2-4,7'
print(_expand_ranges(range_text)) # [1, 2, 3, 4, 7]
:param str ranges_text: The text of ranges to expand
:retu... |
def getdeepattr(d, keys, default_value=None):
"""
Similar to the built-in `getattr`, this function accepts a list/tuple of keys to get a value deep in a `dict`
Given the following dict structure
.. code-block:: python
d = {
'A': {
'0': {
'a': 1,
... |
def are_overlapping_edges(
source_minimum, source_maximum, filter_minimum, filter_maximum
):
"""Verifies if two edges are overlapping in one dimension.
:param source_minimum: The minimum coordinate of the source edge.
:param source_maximum: The maximum coordinate of the source edge.
:param filter_mi... |
def clean_key(key):
"""
Unescapes and removes trailing characters on strings
"""
return key.replace("''", "'").strip().rstrip(":") |
def extract_model_name_and_run(model_string):
"""
`model_string` is a string in the format "model_name/run_id[ft]". Returns the name as a string and the run as an id.
"""
sp = model_string.split('/')
assert len(sp) == 2 or len(sp) == 3
name = sp[0] if len(sp) == 2 else '{}/{}'.format(sp[0], sp[1... |
def pad(s1):
"""
Pad a string to make it a multiple of blocksize.
If the string is already a multiple of blocksize, then simply return the string
"""
if len(s1) % 16 == 0:
return s1
else:
return s1 + "\x00"*(16 - len(s1) % 16) |
def get_rc(re):
"""
Return the reverse complement of a DNA/RNA RE.
"""
return re.translate(str.maketrans('ACGTURYKMBVDHSWN', 'TGCAAYRMKVBHDSWN'))[::-1] |
def star_generator(individual_rating, star_rating=5):
"""Generates rating stars when rating is passed through"""
output_html = ''
star = 1
# html output strings
checked_star = '<i class="fas fa-star checked" aria-hidden="true"></i>'
unchecked_star = '<i class="fas fa-star unchecked" aria-hidden... |
def dict_update(base_dict, update_dict):
"""Return an updated dictionary.
If ``update_dict`` is a dictionary it will be used to update the `
`base_dict`` which is then returned.
:param request_kwargs: ``dict``
:param kwargs: ``dict``
:return: ``dict``
"""
if isinstance(update_dict, dict... |
def split_data(data, num_part):
"""
Split data for each device.
"""
if len(data) == num_part:
return data
data = data[0]
inst_num_per_part = len(data) // num_part
return [
data[inst_num_per_part * i:inst_num_per_part * (i + 1)]
for i in range(num_part)
] |
def RPL_ISON(sender, receipient, message):
""" Reply Code 303 """
return "<" + sender + ">: " + message |
def format_chrom(chrom, want_chr):
""" Pass in a chromosome (unknown format), return in your format
@param chrom: chromosome ID (eg 1 or 'chr1')
@param want_chr: Boolean - whether you want "chr" at the beginning of chrom
@return: "chr1" or "1" (for want_chr True/False)
"""
if want_c... |
def show_bits(string: int, nbits: int = 16) -> str:
"""Return a string showing the occupations of the bitstring
Args:
string (int): bit string
nbits (int): the number of bits to show
Returns:
str: string representation of the bit string
"""
return str(bin(int(string))[2:].... |
def format_host_address(value):
"""format ipv4 vs ipv6 address to string"""
return value if ':' not in value else '[%s]' % value |
def isnumber(s):
"""
General Boolean test for for a floating point value
"""
try:
float(s)
return True
except ValueError:
return False
except TypeError:
return False |
def quick_sort(array):
"""
Sort function using quick sort algorithm.
array - unsorted array
"""
if len(array) <= 1:
return array
pivot = array[0]
# Separation element on less, equal, greater than pivot
less = [i for i in array if i < pivot]
equal = [i for i in array if i ==... |
def derive_ppop_state(obj, state_dict):
""" Deriving ppop code and ppop state name
Args:
obj: a dictionary containing the details we need to derive from and to
state_dict: a dictionary containing all the data for State objects keyed by state code
Returns:
Place ... |
def how_many (aDict):
"""
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
"""
key = aDict.keys()
val = []
for key in aDict:
aDict[key]
val = val + aDict[key]
return len(val) |
def digit_sum(n):
"""Calculating with integer arithmetic instead of char/int/list method
doubles the speed.
"""
result = 0
while n:
result += n % 10
n = n // 10
return result |
def expand_default_args(methods):
"""This function takes a collection of method tuples and expands all of
the default arguments, returning a set of all methods possible."""
methitems = set()
for mkey, mrtn in methods:
mname, margs = mkey[0], mkey[1:]
havedefaults = [3 == len(arg) for arg... |
def cost(actions):
"""A cost function"""
return len([x for x in actions if x.islower()]) |
def is_prime(integer: int) -> bool:
"""Function to check if an integer is a prime"""
if integer < 1:
return False
for i in range(2, integer):
if integer % i == 0:
return False
return True |
def get_tokens_from_line(line):
"""
Given a line split it into tokens and return them.
Tokens are runs of characters separated by spaces. If there are no
tokens return an empty list.
Args:
line (str): line to convert to tokens
Returns:
list(str): The tokens
"""
# Does ... |
def _toks2feats(a_tweet_toks):
"""Convert set of tweet's tokens to a dictionary of features.
@param a_tweet_toks - set of tweet's uni- and bigrams
@return feature dictionary with tweet's tokens as keys and values 1
"""
return {w: 1. for w in a_tweet_toks} |
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n # in Python 2 use sum(data)/float(n) |
def left_rotate(value, shift):
"""Returns value left-rotated by shift bits. In other words, performs a circular shift to the left."""
return ((value << shift) & 0xffffffff) | (value >> (32 - shift)) |
def mean(values):
"""Calculate the mean.
Parameters
----------
values : list
Values to find the mean of
Returns
-------
out : float
The mean
"""
return sum(values)/float(len(values)) if len(values) > 0 else 0.0 |
def extract_data(page_data):
"""
extract file data from page json
:param page_data: page data in json
:return: extracted data in dic
"""
extracted_data = {}
# loop through all cid in this page
for file in page_data['hits']:
cid = file['hash']
first_seen = file['first-seen... |
def clear(tupleo):
"""
clear(...) method of tupleo.tuple instance
T.clear(tupleo) -> None -- Remove all elements from tuple, tupleo
"""
if type(tupleo) != tuple:
raise TypeError("{} is not tuple".format(tupleo))
convertlist = list(tupleo)
convertlist.clear()
return tuple(convertl... |
def max_length(position, active_segments):
"""
Returns the maximum length of any segment overlapping ``position``
"""
if not active_segments:
return None
return max(s.length for s in active_segments) |
def parse_dec_or_hex(string):
"""Parses a string as either decimal or hexidecimal"""
base = 16 if string.startswith('0x') else 10
return int(string, base) |
def join(left, right):
"""
Join two dag paths together
:param str left: A node dagpath or name.
:param str right: A node name.
:return: A dagpath combining the left and right operant.
:rtype:str
"""
dagpath = "%s|%s" % (left.strip("|"), right.strip("|"))
if left.startswith("|"):
... |
def ccw(A, B, C):
"""Tests whether the turn
formed by A, B, and C is ccw"""
return (B[0] - A[0]) * (C[1] - A[1]) > (B[1] - A[1]) * (C[0] - A[0]) |
def reset_bits(value: int, pos: int) -> int:
""" Resets bits higher than the given pos. """
reset_bits_mask = ~(255 << pos)
value &= reset_bits_mask
return value |
def _search_to_regex(search):
""" """
return f'.*{search}' |
def display_mal_graph(value):
"""
Function that either displays the graph of the top 20 malicious domains or
hides them depending on the position of the toggle switch.
Args:
value: Contains the value of the toggle switch.
Returns:
A dictionary that communicates with the Dash inter... |
def is_valid_action(action):
"""Return whether or not the action function is a valid
detcord action
Args:
action (function): the function to check
Returns:
bool: Whether or not the action is valid
"""
return getattr(action, 'detcord_action', False) != False |
def json_value(obj):
"""Format obj in the JSON style for a value"""
if type(obj) is bool:
if obj:
return '*true*'
return '*false*'
if type(obj) is str:
return '"' + obj + '"'
if obj is None:
return '*null*'
assert False |
def mid_price(book):
""" ratio of top bid to top ask """
bids,asks = book['bids'],book['asks']
#asks.reverse()
level = 0
bp = bids[level]['price']
ap = asks[level]['price']
mid = (bp+ap)/2
return mid |
def max(x, y):
"""``max :: a -> a -> a``
Maximum function.
"""
return x if x >= y else y |
def ancestor_width(circ, supp, verbose=False):
"""
Args:
circ(list(list(tuple))): Circuit
supp(list): List of integers
Returns:
int: Width of the past causal cone of supp
"""
circ_rev= circ[::-1]
supp_coded = 0
for s in supp:
supp_coded |= (1<<s)
for uni... |
def parsepath(path):
"""internal use only: parsepath(path) - transform path like 'node/subnode(attr1=value,attr2=value2)[2]/subsubnode' into processible structure"""
# remove first and last '/'
if path[0] == '/': path=path[1:]
if path[-1] == '/': path=path[:-1]
el = path.split('/')
elements=[]
for e in el:
whe... |
def better_bottom_up_mscs(seq: list) -> tuple:
"""Returns a tuple of three elements (sum, start, end), where sum is the sum
of the maximum contiguous subsequence, and start and end are respectively
the starting and ending indices of the subsequence.
Let sum[k] denote the max contiguous sequence ending ... |
def split_transactions(transactions):
"""
Split transactions into 80% to learn and 20% to test
:param transactions: The whole transactions list
:return: The transactions list to be learnt, the transactions list to be tested
"""
i = int(len(transactions) * 0.8)
transactions_to_learn = transac... |
def empty(list):
""" Checks whether the `list` is empty. Returns `true` or `false` accordingly."""
return len(list) == 0 |
def mod360_distance(a, b):
"""distance between a and b in mod(360)"""
# Surprisingly enough there doesn't seem to be a more elegant way.
# Check http://stackoverflow.com/questions/6192825/
a %= 360
b %= 360
if a < b:
return mod360_distance(b, a)
else:
return min(a-b, b-a+360... |
def normalise_U(U):
"""
This de-fuzzifies the U, at the end of the clustering. It would assume that the point is a member of the cluster whose membership is maximum.
"""
for i in range(0,len(U)):
maximum = max(U[i])
for j in range(0,len(U[0])):
if U[i][j] != maximum:
U[i][j] = 0
else:
U[i][j] = 1
... |
def flatten(nav):
"""
Flattens mkdocs navigation to list of markdown files
See tests/test_flatten.py for example
Args:
nav (list): nested list with dicts
Returns:
list: list of markdown pages
"""
pages = []
for i in nav:
# file
if type(i) =... |
def get_three_level_class(value, red_thresh, yellow_thresh):
"""
Map a continuous value to a three level (green, yellow, red) classification in which intermediate ("yellow")
values are tagged with class -1. The idea is that these values will be removed from the data set.
"""
if value >= red_thresh:
... |
def _safe_read(filepath):
"""Returns the content of the file if possible, None otherwise."""
try:
with open(filepath, 'rb') as f:
return f.read()
except (IOError, OSError):
return None |
def get_process_name(proc_name):
"""
Get the exe process.
@param proc_name: Sanitized name of the process.
"""
indexOfExe = proc_name.lower().find(".exe")
if indexOfExe != -1:
return proc_name[:indexOfExe + 4]
else:
return "{0} not an exe process.".format(proc_name) |
def detect_cycle(variable, substitutions):
"""check whether variable has been substituted before"""
# cycle detection
if not isinstance(variable, list) and variable in substitutions:
return True
elif tuple(variable) in substitutions:
return True
else:
has_cycle = False
... |
def analyse_sample_attributes_extended(sample):
""" To find sample attributes
Attributes:
min_position_value - [index, value]
max_position_value - [index, value]
status - up, up_variates, down, down_variates, same, same_variates # noqa
"""
attributes = {
"min_position_v... |
def limit(string, print_length=58):
"""Limit the length of a string to print_length characters
Replaces the middle with ...
"""
if len(string) > print_length:
trim = int((print_length-3)/2)
return string[:trim] + '...' + string[-trim:]
else:
return string |
def spatial_scale_conv_3x3_stride_1(s, p):
"""
This method computes the spatial scale of 3x3 convolutional layer with stride 1 in terms of its input feature map's
spatial scale value (s) and spatial overal value (p).
"""
return s + 4 * (1-p) * s + 4 * (1-p) ** 2 * s |
def round_to_nearest(x, base=5):
"""Round to nearest base.
Parameters
----------
x : float
Input
Returns
-------
v : int
Output
"""
return int(base * round(float(x) / base)) |
def _normalise(s):
"""
Normalise the supplied string in the following ways:
1. String excess whitespace
2. cast to lower case
3. Normalise all internal spacing
:param s: string to be normalised
:return: normalised string
"""
if s is None:
return ""
s = s.strip().lower()... |
def camelcase(a):
"""Convert string to camelcase."""
return a.title().replace('_', '') |
def with_trailing_slash(p):
"""Returns a path with a single trailing slash or None if not a path"""
if not p:
return p
return type(p)(p.rstrip('/') + '/') |
def get_giturl_from_url(url) :
"""extracts the actual git url from an url string
(splits off the branch name after the optional '#')
:param url: an url string, with optional '#' branch name appended
:returns: the actual git url
"""
return url.split('#')[0] |
def span_cover(sa,sb):
"""return smallest span covering both sa and sb; if either is None other is returned; 0-length spans aren't allowed - use None instead"""
if sa is None:
return sb
if sb is None:
return sa
return (min(sa[0],sb[0]),max(sa[1],sb[1])) |
def is_password_valid_with_old_rules(dataset):
""" Validate password according to the old rules """
letter_count = dataset['password'].count(dataset['letter'])
return int(dataset['first']) <= letter_count and letter_count <= int(dataset['last']) |
def sarsa(currQ, alpha, gamma, reward, nextQ):
""" nextQ = Q(curr, nextAction)
where nextAction is selected according to policy - eGreedy or softmax
"""
newQ = currQ + alpha * (reward + gamma * nextQ - currQ)
# update currQ to newQ in DB
return newQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.