content stringlengths 42 6.51k |
|---|
def wrap_text(text, max_length):
"""
Wrap text at the max line length
Source: http://stackoverflow.com/a/32122312/499631
:param text: String of text
:param max_length: Maximum characters on a line
:return:
"""
words = iter(text.split())
lines, current = [], next(words)
for word in words:
if len(current) + 1 + len(word) > max_length:
lines.append(current)
current = word
else:
current += ' ' + word
lines.append(current)
return '\n'.join(lines) |
def rev(arr):
"""Reverse array-like if not None"""
if arr is None:
return None
else:
return arr[::-1] |
def subdif_gap_1d(w, x):
"""
Horrible code, but otherwise does not work with numba
"""
eps = 1e-10
if x < 0 - eps:
d = w + 1
elif x > 0 + eps:
d = w - 1
else:
if -1 <= w <= 1:
d = 0
elif w > 1:
d = w - 1
else:
d = -w - 1
return d |
def evaluate(labels, predictions):
"""
Given a list of actual labels and a list of predicted labels,
return a tuple (sensitivity, specificty).
Assume each label is either a 1 (positive) or 0 (negative).
`sensitivity` should be a floating-point value from 0 to 1
representing the "true positive rate": the proportion of
actual positive labels that were accurately identified.
`specificity` should be a floating-point value from 0 to 1
representing the "true negative rate": the proportion of
actual negative labels that were accurately identified.
"""
all_true = labels.count(1)
all_false = labels.count(0)
sensitivity=0
specificity=0
for lab, pre in zip(labels,predictions):
if lab ==1:
if lab==pre:
sensitivity+=1
else:
if lab==pre:
specificity+=1
return (sensitivity/all_true , specificity/all_false) |
def mixfiles(d1, d2, cuts):
"""mixing data with exclusive parts of each data"""
assert len(d1) == len(d2)
d = b""
start = 0
keep = d1
skip = d2
for end in cuts:
d += keep[start:end]
start = end
keep, skip = skip, keep
d += keep[start:]
return d |
def prepend_chr(chr):
"""Prepends chromosome with 'chr' if not present.
Users are strongly discouraged from using this function. Adding a
'chr' prefix results in a name that is not consistent
with authoritative assembly records.
Args:
chr (str): The chromosome.
Returns:
str: The chromosome with 'chr' prepended.
Examples:
>>> prepend_chr('22')
'chr22'
>>> prepend_chr('chr22')
'chr22'
"""
return chr if chr[0:3] == 'chr' else 'chr' + chr |
def filter_packets_by_filter_list(packets, filter_list):
"""
:param packets: Packet list
:param filter_list: Filters with respect to packet field
:type filter_list: list of pyshark_filter_util.PySharkFilter
:return: Filtered packets as list
"""
filtered_packets = [packet for packet in packets
if all(single_filter.apply_filter_to_packet(packet) for single_filter in filter_list)]
return filtered_packets |
def find_selected(nodes):
"""
Finds a selected nav_extender node
"""
for node in nodes:
if hasattr(node, "selected"):
return node
if hasattr(node, "ancestor"):
result = find_selected(node.childrens)
if result:
return result |
def filter_out_installed_pkgs(event_out_pkgs, installed_pkgs):
"""Do not install those packages that are already installed."""
return {p for p in event_out_pkgs if (p.name, p.modulestream) not in installed_pkgs} |
def insertDateRangeFilter(query):
"""
Add a date range filter on the '@timestamp' field either as
a 'filter' or 'post_filter'. If both 'filter' and 'post_filter'
are already defined then an RuntimeError is raised as the
date filter cannot be inserted into the query.
The date range filter will look like either
"filter" : {"range" : { "@timestamp" : { "gte" : "start-date",
"lt" : "end-date"} } }
or
"post_filter" : {"range" : { "@timestamp" : { "gte" : "start-date",
"lt" : "end-date"} } }
where 'start-date' and 'end-date' literals will be replaced by
the actual timestamps in the query.
"""
dates = {'gte' : 'start-date', 'lt' : 'end-date'}
timestamp = {'@timestamp' : dates}
range_ = {'range' : timestamp}
if not 'filter' in query:
query['filter'] = range_
elif not 'post_filter' in query:
query['post_filter'] = range_
else:
raise RuntimeError("Cannot add a 'filter' or 'post_filter' \
date range to the query")
return query |
def _collect_scalars(values):
"""Given a list containing scalars (float or int) collect scalars
into a single prefactor. Input list is modified."""
prefactor = 1.0
for i in range(len(values)-1, -1, -1):
if isinstance(values[i], (int, float)):
prefactor *= values.pop(i)
return prefactor |
def get_provenance_record(caption):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption': caption,
'statistics': ['diff'],
'domains': ['user'],
'plot_type': 'lineplot',
'authors': [
'mueller_benjamin',
'crezee_bas',
'hassler_birgit',
],
'projects': ['cmug'],
'references': [
'acknow_project',
],
}
return record |
def group_ngrams(p_words, window, fill_value):
"""
:param p_words:
:param window:
:param fill_value: Index for retrieving all zeros for padded regions. When loading the pre-trained
embedding matrix, this row is filled with zeros. This is set as an additional row (last row) of the matrix.
:return:
"""
w = []
start = 0
for i in range(len(p_words) // window + 1):
grouped_words = p_words[start:start + window]
grouped_words = grouped_words + [fill_value] * (window - len(grouped_words))
w.append(grouped_words)
start += window
return w |
def first_non_repeating_letter(str):
"""
This function returns the first non repeating letter in a string. This method does not use Counter function.
Input: string
Output: string of first non repeating letter. If all repeating, return empty string
"""
#Convert string to lower-case string
str_lower = str.lower()
#create a list with character and index for each character in string
#enumerate returns a tuple for each letter format
list_str_lower = enumerate(str_lower)
#traverse through dictionary
for i, letter in list_str_lower:
if str_lower.count(letter) == 1:
return str[i]
#return empty string if all are repeating letters
return "" |
def _relu_not_vect(x, derivative=False):
"""Non vectorized ReLU activation function.
Args:
x (list): Vector with input values.
derivative (bool, optional): Whether the derivative should be returned instead. Defaults to False.
"""
if x > 0:
if derivative:
return 1
else: return x
else:
return 0 |
def freeParameters(self):
"""
Roadrunner models do not have a concept of "free" or "fixed"
parameters (maybe it should?). Either way, we add a cheeky method
to the tellurium interface to roadrunner to return the names
of the parameters we want to fit
"""
return ['ki', 'kr', 'k_T1R', 'k_T2R',
'kdeg_T1R', 'kdeg_T2R', 'kdeg_LRC', 'kdeg_TGF_beta', 'klid', 'ka_LRC', 'kdiss_LRC', 'kimp_Smad2',
'kexp_Smad2', 'kimp_Smad4', 'kexp_Smad4', 'kpho_Smad2', 'kon_Smads', 'koff_Smads', 'kimp_Smads',
'kdepho_Smad2', 'kon_ns', 'KD_ns'] |
def get_location(location_strategy, dwell_location):
"""Determines if the vehicle can be charged given location strategy and dwelling location
:param int location_strategy: where the vehicle can charge-1, 2, 3, 4, or 5; 1-home only, 2-home and work related, 3-anywhere if possibile, 4-home and school only, 5-home and work and school.
:param int dwell_location: location the vehicle dwells
:return: (*bool*) -- a boolean that represents whether or not the vehicle can charge
"""
#only home
if location_strategy == 1:
return dwell_location == 1
#home and go to work related
elif location_strategy == 2:
#13 is to 'attend business meeting', 14 is 'other work related'.
#here only consider the regular work, which are 11 and 12, 'go to work' and 'return to work'
return dwell_location < 13
#anywhere if possible
elif location_strategy == 3:
return True
#home and school only
elif location_strategy == 4:
#21 is 'go to school as student'
return dwell_location in {1, 21}
#home and work and school
elif location_strategy == 5:
if dwell_location in {1, 11, 12, 21}:
return True
else:
return False |
def read_reader(source, new_format=False):
"""
Read from EmotivReader only. Return data for decryption.
:param source: Emotiv data reader
:return: Next row in Emotiv data file.
"""
value = next(source)
value = value.split(',')
return value |
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri |
def check_central_position(m, n, i, j, width):
"""
checking if the distribution given by the `i,j` and `width` will be inside the grid
defined by the `n` and `m`.
:math:`i\in[1..m]`, :math:`j\in[1..n]`, where `m` -- number of cells along latitude and
`n` is the number of cells along longitude.
:param m: number of cells along latitude
:param n: number of cells along longitude
:param i: current position along latitude
:param j: current position along longitude
:param width: width of the distribution of state
:return: True or False
"""
result = (i + width < m) & (i - width >= 0) & (j + width < n) & (j - width >= 0)
return result |
def get_nodes_ids(ipfs_diag_net_out):
"""
Parsing nodes IDs
"""
node_ids_set = set()
for line in ipfs_diag_net_out.split("\n"):
line = line.strip()
if line.startswith("ID"):
line = line.strip().split(" ")[1]
node_ids_set.add(line)
return node_ids_set |
def cond_swap_bit(x,y, b):
""" swap if b == 1 """
if x is None:
return y, None
elif y is None:
return x, None
if isinstance(x, list):
t = [(xi - yi) * b for xi,yi in zip(x, y)]
return [xi - ti for xi,ti in zip(x, t)], \
[yi + ti for yi,ti in zip(y, t)]
else:
t = (x - y) * b
return x - t, y + t |
def coerce_to_list(data, key):
"""
Returns the value of the ``key`` key in the ``data`` mapping. If the value is a string, wraps it in an array.
"""
item = data.get(key, [])
if isinstance(item, str):
return [item]
return item |
def get_IGV_header(samples):
"""get header for IGV output file"""
header = '#type=DNA_METHYLATION\nChromosome\tStart\tEnd\tFeature'
for sample in samples[9:]:
header += '\t%s' % sample
return header + '\n' |
def lift(lst):
"""Lift from 2D to 3D, with z=0."""
return [(x, y, 0) for (x,y) in lst] |
def get_delta_from_interval(data_interval):
"""Convert interval name to number of seconds
Parameters
----------
interval : str
interval length {day, hour, minute, second, tenhertz}
Returns
-------
int
number of seconds for interval, or None if unknown
"""
if data_interval == "tenhertz":
delta = 0.1
elif data_interval == "second":
delta = 1.0
elif data_interval == "minute":
delta = 60.0
elif data_interval == "hour":
delta = 3600.0
elif data_interval == "day":
delta = 86400.0
else:
delta = None
return delta |
def sec_to_min_pretty(time_secs: int) -> str:
"""
Returns formatted string for converting secs to mins.
"""
if time_secs % 60 == 0:
return f'{time_secs // 60}'
m = time_secs / 60
return f'{m:.2g}' |
def compute_phase_error(res, obs):
"""compute error in phase between 0 and 360"""
if res < 0:
res += 360
if obs < 0:
obs += 360
if res >= obs:
mu = res - obs
return mu
else:
mu = res - obs
mu += 360
return mu |
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i + 2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode() |
def count_bcd_digits(bcd):
""" Count the number of digits in a bcd value
:param bcd: The bcd number to count the digits of
:returns: The number of digits in the bcd string
"""
count = 0
while bcd > 0:
count += 1
bcd >>= 4
return count |
def _HPERM_OP(a):
"""Clever bit manipulation."""
t = ((a << 18) ^ a) & 0xcccc0000
return a ^ t ^ ((t >> 18) & 0x3fff) |
def lev(str1, str2):
"""Make a Levenshtein Distances Matrix"""
n1, n2 = len(str1), len(str2)
lev_matrix = [ [ 0 for i1 in range(n1 + 1) ] for i2 in range(n2 + 1) ]
for i1 in range(1, n1 + 1):
lev_matrix[0][i1] = i1
for i2 in range(1, n2 + 1):
lev_matrix[i2][0] = i2
for i2 in range(1, n2 + 1):
for i1 in range(1, n1 + 1):
cost = 0 if str1[i1-1] == str2[i2-1] else 1
elem = min( lev_matrix[i2-1][i1] + 1,
lev_matrix[i2][i1-1] + 1,
lev_matrix[i2-1][i1-1] + cost )
lev_matrix[i2][i1] = elem
return lev_matrix[-1][-1] |
def triangleArea(a, b, c):
"""Calculates the area of a triangle spanned by three points.
Note that the area will be negative if the points are not given in counter-clockwise order.
Keyword arguments:
a -- First point
b -- Second point
c -- Third point
Returns:
Area of triangle
"""
return ((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])) |
def interval_converter(z, a, b):
""" convert from [-1, 1] (the integration range of Gauss-Legendre)
to [a, b] (our general range) through a change of variables z -> x """
z1 = 0.5*(b + a) + 0.5*(b - a)*z
return z1 |
def collate_fn(batch):
"""Function that organizes the batch
Keyword arguments:
- batch
"""
return list(zip(*batch)) |
def validate_output(output_path):
"""
Converts 'default_loc' to './out.csv' and makes sure any passed in argument
has a .csv file extension
"""
if output_path == 'default_loc' or not output_path:
output_path = './out.csv'
if output_path[-4:] != '.csv':
output_path += '.csv'
return output_path |
def grad_desc(value, grad):
""" Simple gradient descent function """
eta = 0.1
return (value - eta*grad) |
def mergeWithLabels(json, firstField, firstFieldLabel, secondField, secondFieldLabel):
"""
merge two fields of a json into an array of { firstFieldLabel : firstFieldLabel, secondFieldLabel : secondField }
"""
merged = []
for i in range(0, len(json[firstField])):
merged.append({ firstFieldLabel : json[firstField][i],
secondFieldLabel : json[secondField][i] })
return merged |
def in_list(ldict, key, value):
""" Find whether a key/value pair is inside of a list of dictionaries.
@param ldict: List of dictionaries
@param key: The key to use for comparision
@param value: The value to look for
"""
for l in ldict:
if l[key] == value:
return True
return False |
def soft_equals(a, b):
"""Implements the '==' operator, which does type JS-style coertion."""
if isinstance(a, str) or isinstance(b, str):
return str(a) == str(b)
if isinstance(a, bool) or isinstance(b, bool):
return bool(a) is bool(b)
return a == b |
def categorizeTypeOfDay(x):
"""
This function returns either the day provided is a week day or a weekend.
:param x: string value of day
:return: string
"""
if x == 'Monday':
return 'Week Day'
elif x == 'Tuesday':
return 'Week Day'
elif x == 'Wednesday':
return 'Week Day'
elif x == 'Thursday':
return 'Week Day'
elif x == 'Friday':
return 'Week Day'
else:
return 'Weekend' |
def get_root_url(url_path):
"""Split by forward-slash; Keep everything except image filename."""
return "/".join(url_path.split(r"/")[:-1]) |
def _clean_url(url: str) -> str:
"""..."""
return '{}{}{}'.format(
'' if url.startswith('http') else 'http://',
'127.0.0.1' if url.startswith(':') else '',
url.strip().rstrip('/')
) |
def _lambdas_to_sklearn_inputs(lambda1, lambda2):
"""Converts lambdas to input arguments for scikit-learn.
:param lambda1: L1-regularization weight.
:param lambda2: L2-regularization weight.
:return: alpha: Input arg for scikit-learn model.
:return: l1_ratio: Input arg for scikit-learn model.
"""
return lambda1 + lambda2, lambda1 / (lambda1 + lambda2) |
def get_die_base_hazard_rate(type_id: int) -> float:
"""Retrieve the base hazard rate for a VHISC/VLSI die.
:param type_id: the VHISC/VLSI type identifier.
:return: _lambda_bd; the base die hazard rate.
:rtype: float
"""
return 0.16 if type_id == 1 else 0.24 |
def purge_log_day(args_array, server):
"""Function: purge_log_day
Description: purge_log_day function.
Arguments:
(input) args_array
(input) server
"""
status = True
if args_array and server:
status = True
return status |
def size_of_window_vector(number_of_freq_estimations):
"""size of the window vector"""
return 4*number_of_freq_estimations + 1 |
def minHour(rows, columns, grid):
"""
This function calculates the minimum hours to infect all humans.
Args:
rows: number of rows of the grid
columns: number of columns of the grid
grid: a 2D grid, each cell is either a zombie 1 or a human 0
Returns:
minimum hours to infect all humans
To use:
grid=[[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0]]
minHour(4,5,grid)
Output: 2
Explanation:
At the end of the 1st hour, the status of the grid:
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 0, 1, 1],
[1, 1, 1, 0, 1]]
At the end of the 2nd hour, the status of the grid:
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]
"""
# return 0 hour as there is no zombie
if not rows or not columns:
return 0
# Create a queue and collect all positions of the zombies into a queue
q = [[i,j] for i in range(rows) for j in range(columns) if grid[i][j]==1]
print("Original q:",q)
# zombies can move to down, up, right, left
directions = [[1,0],[-1,0],[0,1],[0,-1]]
time = 0
while True:
new = []
# Turn human into zombies every hour
for [i,j] in q:
for d in directions:
ni = i + d[0]
nj = j + d[1]
# Find adjacent humans around each enqueued position
if 0 <= ni < rows and 0 <= nj < columns and grid[ni][nj] == 0:
# Convert them into zombies
grid[ni][nj] = 1
# Add their positions into a new queue of zombies
new.append([ni,nj])
print("\nAt the end of the ",time+1," hour, the status of the grid:")
print(grid)
q = new
print("q:",q)
# Repeat until all humans on the matrix will be found and processed
# Empty queue, already turn all humans into zombies
if not q:
break
#Increase number of the hours
time += 1
return time |
def cut(value, arg):
"""Removes all values of arg from the given string"""
return value.replace(arg, "") |
def rating_label(rating, cfg):
"""Convert a credibility rating into a label
:param rating: a credibility rating. We assume it has
`reviewAspect == credibility` and float `confidence` and
`ratingValue`s
:param cfg: configuration options
:returns: a short string to summarise the credibility rating
:rtype: str
"""
if 'reviewAspect' in rating:
assert rating['reviewAspect'] == 'credibility', '%s' % (rating)
conf_threshold = float(cfg.get('cred_conf_threshold', 0.7))
if 'confidence' in rating and rating['confidence'] < conf_threshold:
return 'not verifiable'
assert 'ratingValue' in rating, '%s' % (rating)
val = rating['ratingValue']
assert val <= 1.0 and val >= -1.0, '%s' % (rating)
if val >= 0.5:
return 'credible'
if val >= 0.25:
return 'mostly credible'
if val >= -0.25:
return 'uncertain'
if val >= -0.5:
return 'mostly not credible'
return 'not credible' |
def calculateAltitude(P, P0):
"""
Calculate altitude from barometric pressure readings
Formula from:
http://www.mide.com/products/slamstick/air-pressure-altitude-calculator.php
"""
return 44330.0 * (1 - (P / P0) ** (1 / 5.255)) |
def add_all(tap_stream_id):
"""
Adds all to the generic term e.g. groups_all for groups
"""
return tap_stream_id.split('-')[0] + '_all' |
def is_palindrome(word_3):
"""
To check whether the word is the "Palindrome".
"""
for i in range(len(word_3)):
if(word_3[i]==word_3[len(word_3)-1-i]):
return(True)
else:
return(False) |
def union_of_intervals(intervals):
"""
Takes an iterable of intervals and finds the union of them. Will fail if they are not on the same chromosome
:param intervals: Iterable of ChromosomeIntervals
:return: List of new ChromosomeIntervals
"""
new_intervals = []
for interval in sorted(intervals):
if not new_intervals:
new_intervals.append(interval)
continue
u = new_intervals[-1].union(interval)
if u is not None:
new_intervals[-1] = u
else:
new_intervals.append(interval)
return new_intervals |
def range_union(ranges):
"""Take a list of (H, M) tuples and merge any overlapping intervals."""
results = []
# tuples are sorted in increasing order, so we are sure we always have
# the "latest" end time at the back of the list
for start, end in sorted(ranges):
last_end_time = results[-1] if results else None
# if the next start time is earlier than the latest end time, then
# we can merge the intervals
if last_end_time and start <= last_end_time[1]:
results[-1] = (last_end_time[0], max(last_end_time[1], end))
else:
results.append((start, end))
return results |
def filter_groups_by_members(groups, quantity=1):
"""
Take groups list and return empty groups
:param groups:
:param quantity:
:return:
"""
return [x for x in groups if int(x["total"]) < quantity] |
def get_translated_text(basisObj):
"""
return the concatenated string of translated Named Entities if present
"""
concatenated_text = []
for e in basisObj.get('entities', []):
if 'translation' in e:
concatenated_text.append(e['translation'])
return " ".join(concatenated_text) |
def normalize_spec_version(version):
"""Return the spec version, normalized."""
# XXX finish!
return version |
def MissingNumber2(array, n) :
""" In case we get a very large integer in the summation process """
summ = 0
for i in range(n-1) :
summ += array[i] - (i+1)
return n - summ |
def find_even_index(arr):
"""
Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the
sum of the integers to the right of N. If there is no index that would make this happen, return -1.
:param arr: Array of integers.
:return: The lowest index N where the side to the left of N is equal to the side to the right of N. If you do
not find an index that fits these rules, then you will return -1.
"""
for x in range(len(arr)):
if sum(arr[0:x]) == sum(arr[x+1:len(arr)]):
return x
return -1 |
def insert_right(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(2)
if len(t) > 1:
root.insert(2, [new_branch, [], t])
else:
root.insert(2, [new_branch, [], []])
return root |
def factorial(n):
# n! can also be defined as n * (n-1)!
""" calculates n! recursively """
if n <= 1:
return 1
else:
return n * factorial(n-1) |
def silent_write_text_file(filename, contents=''):
"""
Create a new text file and writes contents into it (do not raise exceptions).
If file with specified name already exists, it will be overwritten.
:return: Dict - 'error': empty string if success, or error message otherwise.
"""
result = {'error': ''}
try:
f = open(filename, 'w')
f.write(contents)
f.close()
return result
except Exception as e:
result['error'] = str(e)
return result |
def delete_invalid_values(dct):
""" Deletes entries that are dictionaries or sets """
for k, v in list(dct.items()):
if isinstance(v, dict) or isinstance(v, set):
del dct[k]
return dct |
def get_float_cell_value(cell_value) -> float:
"""Returns the value of an openpyxl cell value.
This function is used in oder to operate with spreadsheets
which use the comma as the decimal mark instead of a period.
Arguments
----------
* cell_value ~ The openpyxl cell value
"""
if type(cell_value) not in (int, float):
cell_value = cell_value.replace(",", ".")
cell_value = float(cell_value)
return cell_value |
def timefmt(t, fmt):
"""
Format a timestamp in the correct way for subtitles. This is the only
reason we need a programming language and can't do this in bash easily.
"""
seconds = t % (24 * 3600)
hours = int(seconds // 3600)
seconds %= 3600
minutes = int(seconds // 60)
seconds %= 60
(seconds, ms) = divmod(seconds, 1)
seconds = int(seconds)
ms = int(1000 * ms)
if fmt == "webvtt":
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{ms:03d}"
else:
return f"{hours:02d}:{minutes:02d}:{seconds:02d},{ms:03d}" |
def _is_chief(task_type, task_id):
"""Determines if the replica is the Chief."""
return task_type is None or task_type == 'chief' or (
task_type == 'worker' and task_id == 0) |
def get_fib(position):
""" Algorithm:
1. If position matches with base cases(0 and 1) then
return the position. i.e.
1.1 If position == 0
return 0
1.2 If position == 1
return 1
2. Else return addition of previous two values
"""
if position == 0 or position == 1:
return position
else:
return get_fib(position - 1) + get_fib(position - 2)
return -1 |
def _f_p_r_lcs(llcs, m, n):
"""
Computes the LCS-based F-measure score.
Source: https://www.microsoft.com/en-us/research/publication/
researchouge-a-package-for-automatic-evaluation-of-summaries/
Args:
llcs: Length of LCS
m: number of words in (truncated) candidate summary
n: number of words in (truncated) reference summary
Returns:
Float. LCS-based F-measure score
"""
r_lcs = llcs / m
p_lcs = llcs / n
beta = p_lcs / (r_lcs + 1e-12)
num = (1 + (beta**2)) * r_lcs * p_lcs
denom = r_lcs + ((beta**2) * p_lcs)
f_lcs = num / (denom + 1e-12)
return f_lcs, p_lcs, r_lcs |
def findMin(nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
min_number = nums[0]
for i in range(len(nums) - 1):
if nums[i + 1] < nums[i]:
return nums[i + 1]
return min_number |
def replace_ip_in_string(ip, string):
"""
Description
-----------
Use to change the ip in a packet
Parameters:
string:
Represent the ip that are overwrite
string:
Represent the string that have the uncorrect ip
Return
------
string
The correct message whit correct ip
"""
string = string.replace(string.split()[0], ip)
return string |
def find_next_empty(puzzle):
"""
Takes a puzzle as parameter
Finds the next row, col on the puzzle
that's not filled yet (with a value of -1)
Returns (row, col) tuple
or (None, None) if there is none
"""
for row in range(9):
for col in range(9):
if puzzle[row][col] == -1:
return row, col
return None, None |
def xor(stream: bytes, key: int) -> bytes:
"""Apply XOR cipher to ``stream`` with ``key``.
Applying this operation twice decodes ``stream`` back to the initial state.
Parameters
----------
stream: :class:`bytes`
Data to apply XOR on.
key: :class:`int`
Key to use. Type ``u8`` (or ``byte``) should be used, in ``[0; 255]`` range.
Returns
-------
:class:`bytes`
Data after XOR applied.
"""
return bytes(byte ^ key for byte in stream) |
def test(test_names):
""" Run unit tests """
import unittest
if test_names:
""" Run specific unit tests.
Example:
$ flask test tests.test_auth_api tests.test_user_model ...
"""
tests = unittest.TestLoader().loadTestsFromNames(test_names)
else:
tests = unittest.TestLoader().discover("tests", pattern="test*.py")
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
# Return 1 if tests failed, won't reach here if succeeded.
return 1 |
def unwrap(value):
""" Unwrap a quoted string """
return value[1:-1] |
def getfloat(value, default=None):
"""getfloat(value[, default]) -> float(value) if possible, else default."""
try:
return float(value)
except Exception:
return default |
def prob2odds(p):
""" Return the odds for a given probability p """
# Note: in the case of the usual game, we do not have to handle impossible events (e.g if a horse cannot win), and so this equation will never result in
# divion by zero.
return (1-p) / p |
def total_others_income(responses, derived):
""" Return the total of other incomes """
total = 0.0
for income in derived['others_income']:
try:
total += float(income['income_others_amount'])
except ValueError:
pass
return total |
def equal(iterator):
"""
Checks whether all elements of ``iterator`` are equal.
INPUT:
- ``iterator`` -- an iterator of the elements to check
OUTPUT:
``True`` or ``False``.
This implements `<http://stackoverflow.com/a/3844832/1052778>`_.
EXAMPLES::
sage: from sage.combinat.finite_state_machine import equal
sage: equal([0, 0, 0])
True
sage: equal([0, 1, 0])
False
sage: equal([])
True
sage: equal(iter([None, None]))
True
We can test other properties of the elements than the elements
themselves. In the following example, we check whether all tuples
have the same lengths::
sage: equal(len(x) for x in [(1, 2), (2, 3), (3, 1)])
True
sage: equal(len(x) for x in [(1, 2), (1, 2, 3), (3, 1)])
False
"""
try:
iterator = iter(iterator)
first = next(iterator)
return all(first == rest for rest in iterator)
except StopIteration:
return True |
def sendmsg(msg, value1=None, value2=None):
"""
Purpose :
send the same message to the screen
Passed :
msg - the string
value - the number associated with the string
Returns
-------
return
"""
print('*******************************************************************')
if value1 is None:
print(msg)
elif value2 is None:
print((msg, value1))
else:
print((msg, value1, value2))
print('*******************************************************************')
return None |
def divND(v1, v2):
"""Returns divisor of two nD vectors
(same as itemwise multiplication)
Note that this does not catch cases
where an element of the divisor is zero."""
return [vv1 / vv2 for vv1, vv2 in zip(v1, v2)] |
def first_bad_version(last_version, is_bad_version):
"""
Finds the first bad version.
Runtime: O(n), I should have thought this function as if
find the min number in the sorted list.
"""
for version in range(last_version, -1, -1):
print(f"version: {version}")
if not is_bad_version(version):
return version + 1 |
def id18to15(id18):
"""
Truncate an 18 char sObject ID to the case-sensitive 15 char variety.
"""
return id18[:15] |
def compute_increment(draw, a, b):
"""
From a list of event timestamps in a counting process, count the number of events
between a and b.
:param list[float] draw: A list of timestamps drawn from a counting process
:param float a: The left endpoint
:param float b: The right endpoint
:return: The increment between a and b
:rtype: int
"""
return sum(1 for d in draw if a < d < b) |
def adjust_key(key, shape):
"""Prepare a slicing tuple (key) for slicing an array of specific shape."""
if type(key) is not tuple:
key = (key,)
if Ellipsis in key:
if key.count(Ellipsis) > 1:
raise IndexError("an index can only have a single ellipsis ('...')")
ellipsis_pos = key.index(Ellipsis)
missing = (slice(None),) * (len(shape) - len(key) + 1)
key = key[:ellipsis_pos] + missing + key[ellipsis_pos + 1:]
if len(key) > len(shape):
raise IndexError('too many indices for array')
if len(key) < len(shape):
missing = (slice(None),) * (len(shape) - len(key))
key += missing
return key |
def convert(args_list):
"""Convert a list of arguments from string to whatever type it can be converted.
Args:
args_list: A list of string arguments.
Returns:
A list of arguments, each of the type that could be converted.
"""
result = []
for item in args_list:
try:
result.append(int(item))
continue
except ValueError:
pass
try:
result.append(float(item))
continue
except ValueError:
pass
result.append(str(item))
return result |
def initCtrl(size):
"""Init array usefull to check the diagionales and the lines
Args:
size (int): size of the board
Returns:
[array]: ctrl_line
[array]: ctrl_oblique
[array]: ctrl_obliqueinv
"""
x = 2 * size - 1
ctrl_oblique = [False] * x
ctrl_obliqueinv = [False] * x
ctrl_line = [False] * size
return ctrl_line, ctrl_oblique, ctrl_obliqueinv |
def strify(iterable_struct, delimiter=','):
""" Convert an iterable structure to comma separated string.
:param iterable_struct: an iterable structure
:param delimiter: separated character, default comma
:return: a string with delimiter separated
"""
return delimiter.join(map(str, iterable_struct)) |
def constraints_check(constraints=None):
"""Check constraints list for consistency and return the list with basic problems corrected.
A valid constraints list is a list of constraint dictionaries. --> [{const_dict}, ... ,{const_dict}]
A constraint dictionary specifies individual constraint functions, arguments (args and kwargs), and constraint
types. The value corresponding the 'func' key is a callable function which defines the constraint. Traditional
functions ('def func(x): ...') and lambda functions ('func = lambda x: ...') both work. The function signature
must be of the form 'func(x, *args, **kwargs)' where 'x' is a float or a list of floats representing a vector.
The return value from 'func' must be a float. Values corresponding to the 'args' and 'kwargs' keys are any
additional arguments to be passed to 'func' (both are optional). Positional arguments (args) are specified as
a tuple and keyword arguments (kwargs) are specified as a dictionary. The 'type' key specifies the inequality
that the value returned from 'func' must obey for the constraint to be satisfied. Values for the inequality
specification may be '>0', '>=0', '<0', '<=0'.
const_dict --> {'type': ineq_spec_string, 'func': callable_func, 'args': (args_tuple), 'kwargs': {kwargs_dict}}
Args:
constraints (list): List of constraint dictionaries.
Returns:
list: Validated list of constraint dictionaries.
Raises:
TypeError: constraints must be a list of dictionaries
TypeError: constraint is not a dictionary
TypeError: constraint dictionary does not have required "type" key
ValueError: constraint["type"] must be >0, >=0, <0, or <=0
TypeError: constraint dictionary does not have required "func" key
ValueError: constraint["func"] must be callable
TypeError: constraint["args"] must be a tuple
TypeError: constraint["kwargs"] must be a dictionary
"""
if constraints is not None:
if not isinstance(constraints, list):
raise TypeError('constraints must be a list of dictionaries')
for i, const in enumerate(constraints):
if not isinstance(const, dict):
raise TypeError('constraint[%d] is not a dictionary' % i)
if 'type' not in const.keys():
raise TypeError('constraint[%d] dictionary does not have required "type" key' % i)
if const['type'] not in ['>0', '>=0', '<0', '<=0']:
raise ValueError('constraint[%d]["type"] must be >0, >=0, <0, or <=0' % i)
if 'func' not in const.keys():
raise TypeError('constraint[%d] dictionary does not have required "func" key' % i)
if not callable(const['func']):
raise TypeError('constraint[%d]["func"] must be callable' % i)
if 'args' not in const.keys():
const['args'] = ()
if not isinstance(const['args'], tuple):
raise TypeError('constraint[%d]["args"] must be a tuple' % i)
if 'kwargs' not in const.keys():
const['kwargs'] = {}
if not isinstance(const['kwargs'], dict):
raise TypeError('constraint[%d]["kwargs"] must be a dictionary' % i)
return constraints |
def find_target_dict(scene_data):
"""Find and return the target dict from the scene data."""
return scene_data['objects'][0] |
def flatten(lists):
"""
Singly flattens nested list
"""
return [item for sublist in lists for item in sublist] |
def validate_brackets(code_to_validate):
"""
You're working with an intern that keeps coming to you with JavaScript code that won't run because
the braces, brackets, and parentheses are off.
To save you both some time, you decide to write a braces/brackets/parentheses validator.
"""
if not code_to_validate:
raise ValueError('Cannot validate an empty string')
counter = {
'{': 0,
'[': 0,
'(': 0,
'}': 0,
']': 0,
')': 0
}
# What cannot be inmediately after a given symbol
rules = {
'{': '])',
'[': '})',
'(': '}]',
'}': '',
']': '',
')': ''
}
i = 0
while i < len(code_to_validate) - 1:
if code_to_validate[i+1] in rules[code_to_validate[i]]:
return False
counter[code_to_validate[i]] += 1
i += 1
counter[code_to_validate[i]] += 1
return counter['{'] == counter['}'] and \
counter['['] == counter[']'] and \
counter['('] == counter[')'] |
def bytes_startswith_range(x: bytes, prefix: bytes, start: int, end: int) -> bool:
"""Does specified slice of given bytes object start with the subsequence prefix?
Compiling bytes.startswith with range arguments compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
prefix: The subsequence to look for.
start: Beginning of slice of x. Interpreted as slice notation.
end: End of slice of x. Interpreted as slice notation.
Returns:
Result of check.
"""
if start < 0:
start += len(x)
if start < 0:
start = 0
if end < 0:
end += len(x)
if end < 0:
end = 0
elif end > len(x):
end = len(x)
if end - start < len(prefix):
return False
index = start
for i in prefix:
if x[index] != i:
return False
index += 1
return True |
def define_format_dict():
"""Define FORMAT field
Args:
None
Returns:
d (dict): see define_info_dict
"""
d = {
"AD": {
"COLUMN": ["ref_count", "alt_count"],
"Number": "R",
"Type": "Integer",
"Description": "Allelic depths by fragment (not read) "
"for the ref and alt alleles in the order listed",
}
}
return d |
def IoU(bbox1, bbox2):
"""Compute IoU of two bounding boxes
Args:
bbox1 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bounding box, and (w, h) are width and height of the box.
bbox2 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bounding box, and (w, h) are width and height of the box.
Returns:
score - IoU score
"""
x1, y1, w1, h1 = bbox1
x2, y2, w2, h2 = bbox2
xs = sorted([x1, x1 + w1, x2, x2 + w2])
ys = sorted([y1, y1 + h1, y2, y2 + h2])
if xs[1] == x2 or xs[1] == x1:
x_lens = xs[2] - xs[1]
y_lens = ys[2] - ys[1]
intersection_area = x_lens * y_lens
union_area = w1 * h1 + w2 * h2 - intersection_area
score = intersection_area / union_area
else:
score = 0
return score |
def split(l, c=0):
"""Split the given list in two."""
return (l[: int(len(l)/2)], l[int(len(l)/2) : None if c == 0 else c]) |
def computeDeviation(pDetect, pGener, tol_limit):
""" per class deviation measurer"""
expectedToleranceplus = pDetect+tol_limit*0.01*pDetect
expectedToleranceminus = pDetect-tol_limit*0.01*pDetect
if (pGener <= expectedToleranceplus and pGener >= expectedToleranceminus):
deviation = 0
print('within tolerance range, not penalized')
else:
deviation = abs(expectedToleranceminus-pGener)
return deviation |
def leapdays(y1, y2):
"""Return number of leap years in range [y1, y2).
Assume y1 <= y2."""
y1 -= 1
y2 -= 1
return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) |
def obj(X):
"""
Objective function: Rosenbrock function with n variables
Minimum for obj(1.0,...,1.0) = 0.0
"""
res = 0.0
for i_param in range(len(X)-1):
res += 100.0*(X[i_param+1]-X[i_param]**2)**2 + (X[i_param]-1.0)**2
return res |
def get_prob_from_odds( odds, outcome ):
""" Get the probability of `outcome` given the `odds` """
oddFor = odds[ outcome ]
oddAgn = odds[ 1-outcome ]
return oddFor / (oddFor + oddAgn) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.