content stringlengths 42 6.51k |
|---|
def header_level(line):
"""
Examples
--------
>>> header_level('# title')
1
>>> header_level('### title')
3
"""
i = 0
title = line + 'e'
while title[0] == "#":
i += 1
title = title[1:]
return i |
def ljust(value, arg):
"""
Left-aligns the value in a field of a given width
Argument: field size
"""
return value.ljust(int(arg)) |
def calc_labour(yield_required):
"""
Labour Costs Formaula
Notes
------
Direct farm labour cost = Number of staff working full-time x wages x 30 hours
Generalisation if statement on farm labour required if unknown
"""
farm_hours = yield_re... |
def _int(i, fallback=0):
""" int helper """
# pylint: disable=broad-except
try:
return int(i)
except BaseException:
return fallback |
def fibonacci(n: int) -> int:
"""Implement Fibonacci recursively
Raise:
- TypeError for given non integers
- ValueError for given negative integers
"""
if type(n) is not int:
raise TypeError("n isn't integer")
if n < 0:
raise ValueError("n is negative")
if n == 0:
... |
def _extract_name(line: str) -> str:
"""Accepts a UniProt DE line (string) as input. Returns the name with
evidence tags removed.
"""
tokens = line[19:-2].split(" {")
name = tokens[0]
return name |
def saponificationIndex (sample_weight, HCl_molarity, HCl_fc, HCl_spent, blank_volume):
"""
Function to calculate the saponification index in mg of KOH per grams
"""
V_HCl = blank_volume - HCl_spent
mols_KOH = HCl_molarity * HCl_fc * V_HCl
KOH_mass = mols_KOH * 56 # 56 is the molecular weight of... |
def _get_reduce_batch_axis(axis, x_dim, x_ndim):
"""get batch_axis for reduce* operation."""
if not isinstance(axis, tuple):
axis = (axis,)
batch_axis = ()
if axis:
for index in axis:
if index < x_dim:
batch_axis = batch_axis + (index,)
else:
... |
def get_font_color(average_color_metric):
"""Returns tuple of primary and secondary colors depending on average color metric"""
if average_color_metric[3] < 128:
return (255, 255, 255), average_color_metric[:3]
else:
return (0, 0, 0), average_color_metric[:3] |
def query_merge_rels_unwind(start_node_labels, end_node_labels, start_node_properties,
end_node_properties, rel_type, property_identifier=None):
"""
Merge relationship query with explicit arguments.
Note: The MERGE on relationships does not take relationship properties into acc... |
def str_visible_len(s):
"""
:param str s:
:return: len without escape chars
:rtype: int
"""
import re
# via: https://github.com/chalk/ansi-regex/blob/master/index.js
s = re.sub("[\x1b\x9b][\\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]", "", s)
return len(s) |
def getValue(struct, path, default=None):
"""
Read a value from the data structure.
Arguments:
struct can comprise one or more levels of dicts and lists.
path should be a string using dots to separate levels.
default will be returned if the path cannot be traced.
Example:
getValue({'a'... |
def pagealign(data, address, page_size, data_size=1):
"""
Aligns data to the start of a page
"""
# Pre-pad the data if it does not start at the start of a page
offset = address % page_size
for _ in range(offset):
data.insert(0, 0xFF)
# In case of other data sizes, post-pad the data
... |
def best_of_if(first, second):
"""
Tells which move is the best
Parameters
----------
first: dictionnary
The following required (string) keys are :
cleared: number of line cleared by the move
holes: number of hol... |
def unique_elements(values):
"""List the unique elements of a list."""
return list(set(values)) |
def UTCSecondToLocalDatetime(utcsec, timezone="Europe/Berlin"):
"""
Convert utc second to local datetime (specify correct local timezone with string).
Parameters
----------
utcsec: int
Time in utc seconds (unix time).
timezone: string
Time zone string compatible with pytz format
... |
def fnr_score(conf_mtx):
"""Computes FNR (false negative rate) given confusion matrix"""
[tp, fp], [fn, tn] = conf_mtx
a = tp + fn
return fn / a if a > 0 else 0 |
def get_label_name_from_dict(labels_dict_list):
"""
Parses the labels dict and returns just the names of the labels.
Args:
labels_dict_list (list): list of dictionaries
Returns:
str: name of each label separated by commas.
"""
label_names = [a_dict["name"] for a_dict in labels... |
def get_cal_total_info(data):
"""Get total information of calculation amount from origin data
Parameters
----------
data : list[dict[str, dict[str, object]]]
Original data
res : dict
Total information
"""
res = {
"fused_mul_add": 0,
"mul": 0,
"add": ... |
def average_precision(y_true, y_pred):
"""Calculate the mean average precision score
Args:
y_true (List(Permission)): A list of permissions used.
y_pred (List(Permission)): A Ranked list of permissions recommended
Returns:
ap: Average precision
"""
score = 0.0
n... |
def minima_in_list(lx, ly):
"""
in the list, it find points
that may be local minima
Returns the list of x-guesses
"""
np = len(lx)
# initialize guesses
guesses = []
# initial point
if ly[0] <= ly[1]:
guesses.append(lx[0])
# mid points
for idx in range(1, np - 1):... |
def GetChunks(data, size=None):
"""
Get chunks of the data.
"""
if size == None:
size = len(data)
start = 0
end = size
chunks = []
while start < len(data):
chunks.append(data[start:end])
start = end
end += size
if end > len(data):
en... |
def splitstring(data, maxlen):
""" Split string by length """
return "\n".join((data[i:maxlen + i] for i in range(0, len(data), maxlen))) |
def sanitize_title(title):
"""
Remove forbidden characters from title that will prevent Windows
from creating directory.
Also change ' ' to '_' to preserve previous behavior.
"""
forbidden_chars = ' *"/\<>:|(),'
replace_char = "_"
for ch in forbidden_chars:
title = title.replac... |
def RemoveExonPermutationsFromFront(segments):
"""remove exon permutations from the front.
Only permutations are removed, that are completely out of sync
with query. Overlapping segments are retained, as they might
correspond to conflicting starting points and both should be
checked by genewise.
... |
def edge(geom):
"""
return a polygon representing the edge of `geom`
"""
h = 1e-8
try:
geomext = geom.exterior
except:
try:
geomext = geom.buffer(h).exterior
except:
geomext = geom
return geomext |
def find_in_list(l, pred):
"""lamba function for finding item in a list
"""
for i in l:
if pred(i):
return i
return None |
def get_byte_order(ei_data):
"""Get the endian-ness of the header."""
if ei_data == b'\x01':
return 'little'
elif ei_data == b'\x02':
return 'big'
else:
raise ValueError |
def filter_common_words(tokens, word_list):
"""
Filter out words that appear in many of the documents
Args:
tokens: a list of word lemmas
word_list: a list of common words
Returns:
a set of word lemmas with the common words removed
"""
return list(set([word for word in to... |
def build_fib_iterative(n):
"""
n: number of elements in the sequence
Returns a Fibonacci sequence of n elements by iterative method
"""
if n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib = [0, 1]
count = 2
while count < n:
last_el... |
def get_file_offset(vfp: int) -> int:
"""Convert a block compressed virtual file pointer to a file offset."""
address_mask = 0xFFFFFFFFFFFF
return vfp >> 16 & address_mask |
def solve_by_dichotomy(f, objective, a, b, tolerance):
"""
Apply the dichotomy method to solve the equation f(x)=objective, x being the unknown variable.
a and b are initial x values satisfying the following inequation: (f(a) - objective) * (f(b) - objective) < 0.
The iterative method stops once f(x) is... |
def index_sets(items):
"""
Create a dictionary of sets from an iterable of `(key, value)` pairs.
Each item is stored in a set at `key`. More than one item with same key
means items get appended to same list.
This means items in indices are unique, but they must be hashable.
"""
index = {}
... |
def log_mean(T_hi, T_lo, exact=False):
"""
compute the logarithmic mean
"""
if exact:
from numpy import log
return (T_hi-T_lo)/log(T_hi/T_lo)
else:
d = T_hi - T_lo
return T_hi - d/2*(1 + d/6/T_hi*(1 + d/2/T_hi)) |
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
if k == 0 or k < 0:
return False
total = 0
# starting from 1 and until we reach k , we sum the numbers to get the triangular ones
# if we hit the number with this s... |
def coefficients(debug=False):
"""
Generate Ranking System Coefficients.
Parameters
----------
debug : bool, optional
What level of debugging/prints to do. The default is False.
Returns
-------
ratingCoeff : dict
DESCRIPTION.
"""
# Initiailize for All Ranking T... |
def getQueryString( bindings, variableName ):
""" Columns a bunch of data about the bindings. Will return properly formatted strings for
updating, inserting, and querying the SQLite table specified in the bindings dictionary. Will also
return the table name and a string that lists the columns (properly formatted... |
def double_factorial(k: int) -> int:
"""
Returns the double factorial of the number, the product of all positive integers of the same parity smaller or
equal to the number.
By convention an empty product is considered 1, meaning double_factorial(0) will return 1.
:param k: A positive integer
:r... |
def si_prefix(prefix=None):
"""
Return the SI-prefix for a unit
"""
if prefix is None:
prefix='none'
prefix=prefix.lower()
prefixes = {
'micro':'$\mu$',
'milli':'m',
'none':'',
'kilo':'k',
'mega':'M'
}
return prefixes[prefix] |
def unpad_list(listA, val=-1):
"""Unpad list of lists with which has values equal to 'val'.
Parameters
----------
listA : list
List of lists of equal sizes.
val : number, optional
Value to unpad the lists.
Returns
-------
list
A list of lists without the padding... |
def parse_color(color):
"""Take any css color definition and give back a tuple containing the
r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb,
#rrggbbaa, rgb, rgba
"""
r = g = b = a = type = None
if color.startswith('#'):
color = color[1:]
if len(color) == ... |
def grading(score) -> str:
"""
Converts percentage into letter grade.
"""
if score < 50:
grade = "F"
elif score >= 50 and score < 60:
grade = "D"
elif score >= 60 and score < 70:
grade = "C"
elif score >= 70 and score < 80:
grade = "B"
elif score >= 80 and... |
def henon_heiles_potential(x, y):
"""The values of henon heiles poptential (\lambda = 1) for given x/y."""
return (x**2 + y**2) / 2 + (x**2 * y - y**3 / 3) |
def clean_headers_client(header):
"""
Only allows through headers which are safe to pass to the server
"""
valid = ['user_agent', 'x-mining-extensions', 'x-mining-hashrate']
for name, value in header.items():
if name.lower() not in valid:
del header[name]
else:
... |
def calculateSimularity(data1, data2):
"""
On a scale of 0 to 1 returns how simular the two datasets are
INPUTS
-------
data1 : list of numbers - ranging from 0 - 1
data2 : list of numbers - ranging from 0 - 1
OUTPUTS
-------
simularity : how similar are the two ... |
def reverse_template(retro_template):
"""
Reverse the reaction template to swith product and reactants
:param retro_template: the reaction template
:type retro_template: str
:return: the reverse template
:rtype: str
"""
return ">>".join(retro_template.split(">>")[::-1]) |
def calculate_relative_metric(curr_score, best_score):
"""
Calculate the difference between the best score and the current score, as a percentage
relative to the best score.
A negative result indicates that the current score is higher than the best score
Parameters
----------
curr_score : ... |
def list2dict(
l=['A', 'B', 'C'],
keylist=['a', 'b', 'c']
):
"""
task 0.5.31 && task 0.6.3
implement one line procedure taking a list of letters and a keylist
output should be a dict. that maps them together
e.g. input l=['A', 'B', 'C'] keylist=['a', 'b', 'c'] output={'a':'A', '... |
def align_int_down(val, align):
"""Align a value down to the given alignment
Args:
val: Integer value to align
align: Integer alignment value (e.g. 4 to align to 4-byte boundary)
Returns:
integer value aligned to the required boundary, rounding down if
necessary
"""... |
def get_items(items_conf):
"""generic function creating a list of objects from a config specification
objects are: analyses, robots, worlds, tasks, losses, ...
"""
items = []
for i, item_conf in enumerate(items_conf):
# instantiate an item of class "class" with the given configuration
... |
def create_db_links(txt_tuple_iter, detail_page):
"""
From an iterable containing DB info for records in DB or 'not in DB' when no
instances were found, returns info formatted as url links to detail pages of
the records.
:param txt_tuple_iter: an iterable of strings and tuples where the 0 element
... |
def solr_field(name=None, type='string', multiValued=False, stored=True, docValues=False):
"""solr_field: convert python dict structure to Solr field structure"""
if not name:
raise TypeError('solar() missing 1 required positional \
argument: "name"')
lookup_bool = {True: 'true', False: 'fal... |
def splitFullFileName(fileName):
"""
split a full file name into path, fileName and suffix
@param fileName
@return a list containing the path (with a trailing slash added), the
file name (without the suffix) and the file suffix (without the
preceding dot)
"""
tmp = fileName.split('/')
path = '/'.join(tmp[:... |
def find_largest_digit(n):
"""
Do recursion to find max integer.
n: (int) input number.
return: max number in input number.
"""
n = str(n)
if len(n) == 1: # base point
return n
else:
if n[0] <= n[1]: # if head number is smaller than next number, trimming header.
retu... |
def xor(x, y):
"""Return truth value of ``x`` XOR ``y``."""
return bool(x) != bool(y) |
def _remove_filename_quotes(filename):
"""Removes the quotes from a filename returned by git status."""
if filename.startswith('"') and filename.endswith('"'):
return filename[1:-1]
return filename |
def has_recursive_magic(s):
"""
Return ``True`` if the given string (`str` or `bytes`) contains the ``**``
sequence
"""
if isinstance(s, bytes):
return b'**' in s
else:
return '**' in s |
def create_local_cluster_name(service: str, color: str, index: int) -> str:
"""Create the local service-color cluster name."""
return "local-{0}-{1}-{2}".format(service, color, index) |
def scale_l2_to_ip(l2_scores, max_norm=None, query_norm=None):
"""
sqrt(m^2 + q^2 - 2qx) -> m^2 + q^2 - 2qx -> qx - 0.5 (q^2 + m^2)
Note that faiss index returns squared euclidean distance, so no need to square it again.
"""
if max_norm is None:
return -0.5 * l2_scores
assert query_norm ... |
def line_from_2_points(x1, y1, x2, y2):
"""
Gets the coefficients of a line, given 2 points
:param x1:
:param y1:
:param x2:
:param y2:
:return:
"""
a = y1 - y2
b = x2 - x1
c = x1 * y2 - x2 * y1
return a, b, c |
def build_auth_url(url, token=None):
"""build_auth_url
Helper for constructing authenticated IEX urls
using an ``IEX Publishable Token`` with a valid
`IEX Account <https://iexcloud.io/cloud-login#/register/>`__
This will return a string with the token as a query
parameter on the HTTP url
... |
def stream_type_kwargs(stream_type_param):
"""The kwargs for stream_type to pass when invoking a method on `Events`.
:rtype:
`dict`
"""
if stream_type_param:
return {'stream_type': stream_type_param}
return {} |
def unpack_ushort(data: bytes) -> int:
"""Unpacks unsigned short number from bytes.
Keyword arguments:
data -- bytes to unpack number from
"""
return int.from_bytes(data, byteorder="little", signed=False) |
def list_2d(width, length, default=None):
""" Create a 2-dimensional list of width x length """
return [[default] * width for i in range(length)] |
def search(L, el):
"""
Returns the index of `el` in `L` if it exists, or `None` otherwise.
"""
# We're observing the part of the list between indices `left` and `right`.
# When we start, it's the whole list, so from `left=0` to `right=len(L)-1`.
left = 0
right = len(L)-1
# The length of... |
def rows_distributed(thelist, n):
"""
Break a list into ``n`` rows, distributing columns as evenly as possible
across the rows. For example::
>>> l = range(10)
>>> rows_distributed(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> rows_distributed(l, 3)
[[0, 1, 2, 3], [... |
def group_chains(chain_list):
"""
Group EPBC chains.
"""
chains = []
while len(chain_list):
chain = set(chain_list.pop(0))
## print ':', chain
ii = 0
while ii < len(chain_list):
c1 = sorted(chain_list[ii])
## print '--', ii, c1, chain
... |
def final_strategy(score, opponent_score):
"""Write a brief description of your final strategy.
*** YOUR DESCRIPTION HERE ***
"""
# BEGIN PROBLEM 11
"*** REPLACE THIS LINE ***"
return 4 # Replace this statement
# END PROBLEM 11 |
def extract_bindings(config_str):
"""Extracts bindings from a Gin config string.
Args:
config_str (str): Config string to parse.
Returns:
List of (name, value) pairs of the extracted Gin bindings.
"""
# Really crude parsing of gin configs.
# Remove line breaks preceded by '\'.
... |
def find_list_index(a_list, item):
"""
Finds the index of an item in a list.
:param a_list: A list to find the index in.
:type a_list: list
:param item: The item to find the index for.
:type item: str
:return: The index of the item, or None if not in the list.
:rtype: int | None
"""... |
def get_provenance_record(attributes, ancestor_files, plot_type):
"""Create a provenance record describing the diagnostic data and plot."""
caption = ("Correlation of {long_name} between {dataset} and "
"{reference_dataset}.".format(**attributes))
record = {
'caption': caption,
... |
def _process_for_bulk_op(raw_value):
"""
Converts a raw value into the accepted format for jsonb in PostgreSQL.
"""
if isinstance(raw_value, str):
raw_value = raw_value.replace("\\","\\\\")
raw_value = raw_value.replace("\n","\\n")
raw_value = raw_value.replace('\"','\\"')
... |
def max_height(v0):
"""
Compute maximum height reached, given the initial vertical
velocity v0. Assume negligible air resistance.
"""
g = 9.81
return v0**2/(2*g) |
def Average(lst):
"""
Compute the average of a data distribution
"""
return sum(lst) / len(lst) |
def string_to_points(s):
"""Convert a PageXml valid string to a list of (x,y) values."""
l_s = s.split(' ')
l_xy = list()
for s_pair in l_s: # s_pair = 'x,y'
try:
(sx, sy) = s_pair.split(',')
l_xy.append((int(sx), int(sy)))
except ValueError:
print("... |
def is_valid_classification(classification):
""" Check if the classification is a MISRA defined classification """
allowed_classifications = ['Rule']
return classification in allowed_classifications |
def getValAfterZero(stepLength: int, nStep: int = 50000000) -> int:
"""
The idea here is to just care about the value if it is inserted
after the position 0 which holds Zero, and not really constructing
the list itself
"""
currentPosition = 0
listLength = 1
valAfterZero = 0
for i i... |
def format_val(val):
""" format val (probably switch to one in ptt later)
"""
if val == 'True':
formtd_val = True
elif val == 'False':
formtd_val = False
elif val.isdigit():
formtd_val = int(val)
else:
formtd_val = val
return formtd_val |
def part1(data):
"""
>>> part1([
... '00100', '11110', '10110', '10111', '10101', '01111',
... '00111', '11100', '10000', '11001', '00010', '01010'
... ])
198
>>> part1(read_input())
2250414
"""
count = [0 for _ in range(len(data[0]))]
for string in data:
for ... |
def Dvalue2col(A, k, kout, Lmax=1):
""" Convert D-efficiency to equivalent value at another number of columns """
m = 1 + k + k * (k - 1) / 2
mout = 1 + kout + kout * (kout - 1) / 2
dc = kout - k
Aout = (A**(float(m)) * (Lmax**dc))**(1. / mout)
return Aout |
def encrypt(string):
"""Encrpts a string with a XOR cipher.
(assumes security is not necessarily required)
params:
string: A string to encrypt
return: A bytes object
"""
key = 175
string = map(ord, string)
result = []
for plain in string:
key ^= plain
resul... |
def sanitize_input ( s ):
"""Given an arbitrary string,
escape '/' characters
"""
return s.replace('/',r"%2F") |
def sort_annotations_by_offset(annotations):
"""
This function expects as input a list of dictionaries with this structure:
{'ann_id': u'T34',
'continuation': False,
'entity_type': u'Registry',
'positions': [{'end': 2465, 'start': 2448}],
'surface': u'reg 38 Padavinus,'},
And sorts... |
def unit_to_agg(row):
"""
args:
row - should look like (joinkey, (ten, hhgq, geo))
returns tuple with cnt appended
"""
assert len(row) == 2, f"Unit row tuple {row} is not of length 2"
_, (ten, hhgq, geo) = row
return ((geo, 8), 1) if hhgq == 0 and ten == 0 else ((geo, hhg... |
def square_matrix_sum(A, B):
"""
Sum two square matrices of equal
size.
"""
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
C[i][j] = A[i][j] + B[i][j]
return C |
def find_min(nums):
"""
Find minimum element in rotated sorted array
:param nums: given array
:type nums: list[int]
:return: minimum element
:rtype: int
"""
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] < nums[right]:
... |
def skyValue(value):
"""Method to return a simple scalar as a string with minor processing"""
try:
return str(int((value+5)/10.))
except:
return "999" |
def transpose(lists):
""" Transpose a list of lists. """
if not lists: return []
return map(lambda *row: list(row), *lists) |
def count_matching_pairs(arr, k):
"""
given a unique sorted list, count the pairs of elements which sum to equal k.
an element cannot pair with itself, and each pair counts as only one match.
:param arr: a unique sorted list
:param k: the target sum value
:return: the number of elements which su... |
def remove_dups(orig):
"""Remove duplicates from a list but maintain ordering"""
uniq = set(orig)
r = []
for o in orig:
if o in uniq:
r.append(o)
uniq.discard(o)
return r |
def lerp(point_a, point_b, fraction):
""" linear interpolation between two quantities with linear operators """
return point_a + fraction * (point_b - point_a) |
def underscored2camel_case(v):
"""converts ott_id to ottId."""
vlist = v.split('_')
c = []
for n, el in enumerate(vlist):
if el:
if n == 0:
c.append(el)
else:
c.extend([el[0].upper(), el[1:]])
return ''.join(c) |
def same_side(p1, p2, a, b):
"""
Checks whether two points are on the same side of a line segment.
:param p1: A point represented as a 2-element sequence of numbers
:type p1: ``list`` or ``tuple``
:param p2: A point represented as a 2-element sequence of numbers
:type p2: ``list`` or... |
def calc_lighting_radiation(ppfd):
"""Values taken from paper
# E = hf = hc/w
photon_energy = AVOGADRO_NUMBER * PLANK_CONSTANT * n * SPEED_OF_LIGHT / wavelength
PPFD measured in mol m-2 s-1
Flux density measured in W m-2
# https://www.researchgate.net/post/Can_I_convert_PAR_photo_active_r... |
def slug(value):
"""
Slugify (lower case, replace spaces with dashes) a given value.
:param value: value to be slugified
:return: slugified value
ex: {{ "Abc deF" | slug }} should generate abc-def
"""
return value.lower().replace(' ', '-') |
def convert_from_submodel_by_value_to_plain(key_value: list) -> dict:
"""
Convert from the structure where every key/value pair is a separate object
into a simpler, plain key/value structure
"""
result = {}
for item in key_value:
for key, value in item.items():
result[key] = ... |
def adapt_glob(regex):
"""
Supply legacy expectation on Python 3.5
"""
return regex
return regex.replace('(?s:', '').replace(r')\Z', r'\Z(?ms)') |
def grad_refactor_4(a):
""" if_test """
if a > 3:
return 3 * a
return 0 |
def loop_params(params: dict, stop: int) -> dict:
"""Loops through the parameters and deletes until stop index."""
print("params:", params)
for i, key in enumerate(params.copy()):
if i > stop:
break
del params[key]
print("params:", params)
return params |
def miller_rabin(n):
""" primality Test
if n < 3,825,123,056,546,413,051, it is enough to test
a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
Complexity: O(log^3 n)
"""
if n == 2:
return True
if n <= 1 or not n & 1:
return False
primes = [2, 3, 5, 7, 11, 13, 17, 19,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.