content stringlengths 42 6.51k |
|---|
def _inter_pos_list(obs, target):
"""
Get the list of positions of obs in target
ex:
_inter_pos_list([1,2,3,4,5,6,9,1,1,1,1,1,1], [1])
= [1, 8, 9, 10, 11, 12, 13]
"""
pos_list = [0]
if len(obs) != 0:
pos_list = [i for i,o in enumerate(obs, start=1) if o in targe... |
def split_repo_name(repository):
"""Take a string of the form user/repo, and return the tuple
(user, repo). If the string does not contain the username, then just
return None for the user."""
nameparts = repository.split('/', 1)
if len(nameparts) == 1:
return (None, nameparts[0])
else:
... |
def _update_render_options(
render_options, show_col_names, show_col_groups, show_index_names
):
"""Update default render_options of df.to_html() and df.to_latex()"""
if not render_options:
if not (show_col_names or show_col_groups):
render_options = {"header": False}
if show_ind... |
def _check(value,x,y):
"""
Check if a value is between x and y
Parameters
----------
value : float
Value of interest.
x : float
Limit x.
y : float
Limit y.
Returns
-------
int
Numerical bool if value is between limits x and y.
"""
if x <... |
def __rating_to_prob(rating):
"""Transform a rating of 1 to 5 to a non-negatie number proportational to
its probability of being sampled.
"""
# Exponential scale: one step higher in rating results in twice as much as
# likely to be sampled.
return float(2 ** rating) |
def greedy_algo_expected_remaining(n, p):
"""List of expected remaining nodes of G(n, p) at stage 1,2,3... of greedy clique finding algorithm"""
results = [n-1]
j = 1
while results[-1] > 0:
results.append(int(results[-1] - 1/p**j))
j += 1
return results |
def _find_headers_from_data(data):
"""Return the header names from the data."""
if isinstance(data, list):
first_row = data[0] if len(data) else {}
else:
first_row = data
return list(first_row.keys()) |
def convList(string):
"""
Input: String of a list of integers
Output: List of integers
"""
toList = string[1:-1].split(', ')
toInts = [int(i) for i in toList]
return(toInts) |
def streq_const_time(s1, s2):
"""Constant-time string comparison.
:params s1: the first string
:params s2: the second string
:return: True if the strings are equal.
This function takes two strings and compares them. It is intended to be
used when doing a comparison for authentication purpose... |
def roi(capital, duration, percent):
"""
roi() calculates the cumulative return on investment of a certain amount for a given time at a given interest rate.
parameters:
capital: amount to be invested
duration: how long one is investing in months
percent: the interest rate per month
... |
def mean_longitude(t: float) -> float:
"""
Calculate the sun's mean longitude in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The sun's mean longitude at the given time
"""
# t must be in the range fro... |
def find_odd_integer(integers):
"""The time complexity of this algorithm is
O(N), where N is the number of integers in
`integers`."""
odds = set()
for i in integers: # O(N)
if i in odds:
odds.remove(i) # O(1)
else:
odds.add(i) # O(1)
return odds.pop() i... |
def extended_euclidean(a, b):
"""
Extended Euclidean algorithm
Complexity: O(log(min(A, B))
Find x and y in the problem a*x + b*y = GCD(a, b).
The above equation is based in the property
GCD(a, b) = GCD(b, a%b).
"""
if b == 0:
return a, 1, 0
gcd, x1, y1 = extended_euclidean... |
def gamma_to_tau_half_threshold(gamma):
"""Converts gamma to tau for half thresholding
"""
return (4. / 54 ** (1. / 3.) * gamma) ** 1.5 |
def fix_style(s):
"""Minor, general style fixes for questions."""
s = s.replace('?', '')
s = s.strip(' .')
if s[0] == s[0].lower():
s = s[0].upper() + s[1:]
return s + '.' |
def encode_matrix_parameters(parameters):
"""
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
"""
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):... |
def _make_dictnames(tmp_arr, offset=0):
"""
Helper function to create a dictionary mapping a column number
to the name in tmp_arr.
"""
col_map = {}
for i,col_name in enumerate(tmp_arr):
col_map.update({i+offset : col_name})
return col_map |
def _RaiseOnFalse(caller_name, error_class, ok, *args):
"""Returns None / arg / (args,...) if ok, otherwise raises error_class."""
if not isinstance(ok, bool):
raise TypeError('Use %s only on bool return value' % caller_name)
if not ok and error_class is not None:
raise error_class('CLIF wrapped call retu... |
def deserialise_csw_row(row):
"""
de-serialises a backend csv string into a dict
@see serialisers.c
"""
line = row.strip('\r\n').replace('\:', '[[D]]')
sline = line.split(':')
res = []
for val in sline:
val = val.replace('[[D]]', ':')
res.append(val)
return res |
def seqify(flowgram, floworder):
"""
Turns the flowgram into a string of bases.
@param flowgram: an iterable container of integer flow values
@param floworder: the flow order
@return: a string representing the call
"""
nflows = len(floworder)
ret = []
for ndx, ext in enumerate(flowgr... |
def basename(path):
"""
Returns the last component of path, like base name of a filesystem path.
"""
return path[-1] if path else None |
def beta_mode(a, b):
"""Mode of a beta-distributed random variable
:param a: the alpha parameter, number of prior successes
:param b: the beta parameter, number of prior failures
:return: the mean of the distribution(s)
"""
return (a - 1) / (a + b - 2) |
def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop'])
return status.split(None, 1)[0].lower() in mutating |
def _extrapolate(x1, y1, slope, x0, x2):
"""
Extrapolate from pivot point to the ends
:param x1:
:param y1:
:param slope:
:param x0:
:param x2:
:return: tuple containing low and high end points
"""
y0 = int(slope * (x0 - x1) + y1)
y2 = int(slope * (x2 - x1) + y1)
return (... |
def IsEven(v):
""" function to find even numbers"""
if (v % 2 == 0):
return "Even"
else:
return "Not Even" |
def rescale(value, curr_min, curr_max, new_min, new_max):
"""Convert the value from one scale to a new scale.
Args:
value (int/float/object): Value to convert to the new scale
curr_max (int/float): Current maximum value for the current scale.
curr_min (int/float): Current minimum va... |
def get_file_type(url):
"""Do a best effort to guess the file type from the URL
return unknown if it cannot be guessed
"""
if '.css' in url:
return "CSS"
if '.html' in url or '.php' in url:
return "HTML/PAGE"
if '.js' in url:
return "JS"
if '.png' in url or '.jpeg'... |
def extractBnFIdentifier(uri):
"""This function extracts the numerical identifier of a BnF URI.
>>> extractBnFIdentifier("http://data.bnf.fr/ark:/12148/cb39863687h#Expression")
'cb39863687h'
>>> extractBnFIdentifier("http://data.bnf.fr/ark:/12148/cb39863687h#about")
'cb39863687h'
>>> extractBnFIdentifier(... |
def _split_entries_by_variants(entries):
"""Split entries by their variants."""
human_entries = []
noop_entries = []
unspecified_entries = []
for entry in entries:
if 'env-variant' not in entry:
unspecified_entries.append(entry)
elif entry['env-variant'] == 'Human start':... |
def to_unit_vector(vector):
"""
Convert a vector to a unit vector.
Parameter
---------
vector: vector to convert (tuple(float, float)).
Return
------
unit_vector: a unit vector between 1 and -1 (tuple(int, int)).
Version
-------
Specification: Nicolas Van Bossuyt (v1. 10/... |
def func_slack(k):
"""Computes the expected value of the slack random variable K.
Computes the expressions (29c) in Theorem 11. Remember that r.v. $K:= k-\sum_{j=1}^{S-1}W_j$
Args:
k: Int. The capacity of the Knapsack Problem instance.
Returns:
slack_closed: float. The expected value ... |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words uncahanged: compile_word('+') => '+'"""
if word.isupper():
terms = [('%s*%s' % (10**i, d))
for (i, d) in enumerate(word[::-1])]
... |
def cross_full_overlap(dep_t, dep_h):
"""Checks whether the dependent and head in the hypthesis triplet respectively
matches the head and dependent in the text triplet."""
return (dep_h[2] in dep_t[0]) and (dep_h[0] in dep_t[2]) |
def classify_triangle(side1: int, side2: int, side3: int) -> str:
"""
Your correct code goes here... Fix the faulty logic below until the
code passes all of you test cases.
This function returns side1 string with the type of triangle from three integer
values corresponding to the lengths of the t... |
def check_bingo(matrix) -> bool:
"""
Check if any row or column is completely marked
Returns:
bool: True if any row or column is completely marked
"""
for i in range(len(matrix)):
if matrix[i][0] == matrix[i][1] == matrix[i][2] == matrix[i][3] == matrix[i][4] == True:
... |
def parse_abbrs(abbrs):
"""
Parse comma-delimited abbreviations.
Args:
abbrs (str): The raw abbreviations.
Returns:
list: The cleaned list.
"""
parsed = []
for abbr in abbrs.split(','):
if abbr.strip():
parsed.append(abbr.strip())
return parsed if... |
def subscript(text: str) -> str:
"""
Return the *text* surrounded by subscript HTML tags.
Subscript text appears half a character below the normal line,
and is sometimes rendered in a smaller font.
Subscript text can be used for chemical formulas.
>>> subscript("foo")
'<sub>foo</su... |
def pick_fill(_key_background):
"""pick rgba colour"""
white = (255, 255, 255, 255)
black = (0, 0, 0, 255)
return black if _key_background in ['white', 'lightgray', 'lightskyblue'] else white |
def modularExponentiation(a, b, n):
"""
See Introduction to Algorithm 560
d = a^b(mod n)
"""
d = 1
b = bin(b)[2:][::-1]
print("Binary representation of b: ", b)
lens = len(b)
for i in b:
d = (d * d) % n
if i == '1':
d = (d * a) % n
return d |
def dim_unit_scaling(in_unit, out_unit):
"""
Calculate the scaling factor to convert from the input unit (in_unit) to
the output unit (out_unit). in_unit and out_unit must be a string and one
of ['nm', 'um', 'mm', 'cm', 'm', 'km'].
inputs
======
in_unit : str
Input unit
out_uni... |
def _is_divisible_by(num: int, divisor: int) -> bool:
"""Return true if [num] is evenly divisible by [divisor]."""
return num % divisor == 0 |
def hexagon_number(n):
"""Get the nth hexagon number
Hn=n(2n-1)
Test cases:
- 045
"""
hexagon = n * (2 * n - 1)
return hexagon |
def is_int(check: int):
"""
Check if value is int
Args:
check (int): value to be checked
Returns:
Bool: If value is int true, else false.
"""
try:
int(check)
return True
except ValueError:
return False |
def to_bool(value):
"""Converts 'something' to boolean. Raises exception for invalid formats"""
if str(value).lower() in ("on", "yes", "y", "true", "t", "1"):
return True
if str(value).lower() in ("off", "no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"):
return False
raise Exc... |
def get_box(prediction: dict, img_width: int, img_height: int):
"""
Return the relative bounxing box coordinates.
Defined by the tuple (y_min, x_min, y_max, x_max)
where the coordinates are floats in the range [0.0, 1.0] and
relative to the width and height of the image.
"""
box = [
... |
def flatten_args(args):
"""! @brief Converts a list of lists to a single list."""
return [item for sublist in args for item in sublist] |
def get_row_col_array(array, rows_skipped):
"""Get col array from grid."""
ver_hor_array = []
total_rows = len(array)
for row in range(rows_skipped, total_rows):
individual_row_array = []
for cell in enumerate(array[row]):
if array[row][cell] != '':
individual... |
def is_condition(cfg):
"""
Check if the given configuration object specifies a
:py:class:`~enrich2.condition.Condition`.
Args:
cfg (dict): decoded JSON object
Returns:
bool: True if `cfg` if specifies a
:py:class:`~enrich2.condition.Condition`, else False.
"""
if... |
def frohner_cor_3rd_order(sig1,sig2,sig3,n1,n2,n3):
"""
Takes cross-sections [barns] and atom densities [atoms/barn] for
three thicknesses of the same sample, and returns extrapolated
cross section according to Frohner.
Parameters
----------
sig1 : array_like
Cross section of the ... |
def repeater(string, repetitions):
"""Return a string that contains given string, repeated repetitions
times"""
# nb: you must use a "for loop"
repeating_word = ""
for repetition in range(repetitions):
repeating_word += string
return repeating_word |
def hexagonalNum(n):
"""Returns the nth hexagonal number."""
return int(n * (2*n - 1)) |
def flatten(array):
"""
Returns a list o flatten elements of every inner lists (or tuples)
****RECURSIVE****
"""
res = []
for el in array:
if isinstance(el, (list, tuple)):
res.extend(flatten(el))
continue
res.append(el)
return res |
def _needs_scope_expansion(filter_, filter_value, sub_scope):
"""
Check if there is a requirements to expand the `group` scope to individual `user` scopes.
Assumptions:
filter_ != Scope.ALL
"""
if not (filter_ == 'user' and 'group' in sub_scope):
return False
if 'user' in sub_scope:
... |
def normalize_tuple(value, n, name):
"""Transforms a single int or iterable of ints into an int tuple.
# Arguments
value: The value to validate and convert. Could be an int, or any iterable
of ints.
n: The size of the tuple to be returned.
name: The name of the argument being v... |
def argmax(_list):
"""
Compute argmax of a list
Previous maximum is not overwrited
Parameters
----------
_list : array-like
list to find argmax
Returns
-------
_max
maximum value
argmax
maximum index
"""
_max = _list[0]
argmax = 0
for i... |
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = word + '!!!'
# Replace print with return
return shout_word |
def del_constant_start_stop(x):
"""
>>> l = [1,2,3,4]
>>> del_constant_start_stop(l)
[1, 2]
>>> l = [1,2,3,4,5,6,7]
>>> del_constant_start_stop(l)
[1, 2, 7]
"""
del x[2:6]
return x |
def _get_friendly_name(xml):
""" Extract device name from description xml
xml -- device description xml
return -- device name
"""
try:
return xml['root']['device']['friendlyName']
except Exception as e:
return 'Unknown' |
def chunk_indices(l, chunk_size):
"""Returns the indices of the beginning of each chunk"""
return range(0, len(l), chunk_size) |
def is_xml_article_set(filename: str) -> bool:
"""
Check if input file is pubmed xml compressed archive from name.
Arguments:
filename {str} -- the name of the file
Returns:
bool -- true if file is compressed pubmed article set
"""
if filename.endswith(".xml.gz"):
retur... |
def chunk_list(input_list, chunksize):
""" Helped function to chunk a list
>>> lst = [1,2,3,4,5,6]
>>> chunk_list(lst)
[[1,2],[3,4],[5,6]]
"""
return [input_list[start : end] for start, end
in zip(range(0, len(input_list), chunksize),
range(chunksize, len(... |
def WEEK(expression):
"""
Returns the week of the year for a date as a number between 0 and 53.
See https://docs.mongodb.com/manual/reference/operator/aggregation/week/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggregation operator... |
def _get_unique_crs_vertref(fqpr_instances: list):
"""
Pull the CRS and vertical reference from each FQPR instance, check to make sure there aren't differences. We cant
add points from different FQPR instances if the CRS or vertical reference is different. The grid itself will check
to make sure that ... |
def bar_sequence(n):
"""
Create the pattern for left-right side of a grid
n: int -> the number of times the pattern will be repeated
"""
pattern = ' ' * 8
return ('| ' + pattern) * n + '|' |
def num_switch_trials(eventcode):
"""
:param eventcode: list of event codes from operant conditioning file
:return: number of large and small rewards in the switch task
"""
return eventcode.count('LargeReward'), eventcode.count('SmallReward') |
def test_hof(a, b):
"""Test higher order functions."""
def f(g, x):
return g(x) * g(x + 10.0)
def g(x):
return x * b
return f(g, a) + f(g, b) |
def get_line(pt1, pt2):
"""get line slope and bias from two points
y = slope * x + bias
"""
slope, bias = None, None
if pt1[0] != pt2[0]:
slope = (pt1[1] - pt2[1]) / (pt1[0] - pt2[0])
bias = pt1[1] - slope * pt1[0]
return slope, bias |
def get_unique_list(input_list):
"""
Return a new list of unique elemets only while preserving original order
"""
new_list = []
for element in input_list:
if element not in new_list:
new_list.append(element)
return new_list |
def emquote_string(string):
"""
Return a string escape into single or double quotes accordingly to its contents.
"""
string = str( string )
is_single = "'" in string
is_double = '"' in string
if is_single and is_double:
return '"{}"'.format( string.replace( "'", "\\'" ) )
i... |
def aux_stopwords(row, stopwords):
"""Remueve las stopwords de una fila.
Args:
row (pandas row): Fila a la cual se le remueven las stopwords.
stopwords (list): Lista con las stopwords.
Returns:
pandas row: Fila modificada.
"""
row = ' ' + row + ' '
for word in stopwords... |
def find_kmers(seq, k):
"""Find kmers in a string"""
n = len(seq) - k + 1
return [] if n < 1 else [seq[i:i + k] for i in range(n)] |
def fib(n):
"""
O(2**n) time and space
"""
if n < 2:
return n
return fib(n-1) + fib(n-2) |
def build_power_state_payload(device_id, device_type, valid_option):
"""Build the payload for requested device."""
payload = {
"Id": 0,
"JobName": "DeviceAction_Task_PowerState",
"JobDescription": "DeviceAction_Task",
"Schedule": "startnow",
"State": "Enabled",
"J... |
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str:
"""Strips the suffix from a string if present.
https://stackoverflow.com/a/1038999
:param text: String to check for suffix
:param suffix: Suffix to look for.
:param case_insensitive: Do a case insensitive match. Defaults... |
def contains_tr(list, item):
"""
Return whether the list contains the given item. (Naturally
tail-recursive.)
"""
if list == ():
return False
else:
head, tail = list
if head == item:
return True
else:
return contains_tr(tail, item) |
def padded(l, n=4):
"""Return the size to pad a thing to.
- `l` being the current size of the thing.
- `n` being the desired divisor of the thing's padded size.
"""
return n * (min(1, divmod(l, n)[1]) + l // n) |
def format_sla_results(host_groups, unsafe_only=False):
"""Formats SLA check result output.
:param host_groups: SLA check result groups (grouped by external grouping criteria, e.g. by_host)
:type host_groups: list of (defaultdict(list))
:param unsafe_only: If True, includes only SLA-"unsafe" hosts from the res... |
def GenZeroStr(n):
"""Generate a bunch of zeroes.
Arguments:
n -- Number of zeroes
Returns: string
"""
return "".join(["0"] * n) |
def system_user_exists(username):
""" Check if username exists
"""
import pwd
try:
pwd.getpwnam(username)
except KeyError:
return False
return True |
def unwrap_function(fn):
"""
Given a function, returns its undecorated original.
"""
while hasattr(fn, '__wrapped__'):
fn = fn.__wrapped__
return fn |
def func_getattr(val, attr):
"""
Return attribute if it exists; otherwise treat attribute as a dict key.
:param Any val: an object that either has attribute ``attr`` or is a dict
and has a key named ``attr``
:param str attr: name of the attribute/dict key.
"""
try:
r... |
def interestPaidPerMonth(annualPercent,currentBalance):
"""Function that takes in the annual interest rate percentage and the
current principle balance and calualates how much interest must be
paid in that month. Returns that interest amount."""
annualPercent = float(annualPercent) #convert argument to float
cur... |
def roll_min_edge_info(var):
"""Rolls core JSON (specifying minimal info about an edge.
var: the variable name for the edge within this cypher clause."""
return "{ label: %s.label, " \
"iri: %s.iri, type: type(%s) } " % (var, var, var) |
def speak_next(most_recent: int, turn_num: int, nums_spoken: dict):
"""
If you want to optimize something in Python,
it probably involves dictionaries or tuples.
~ My friend Miles
"""
if most_recent not in nums_spoken:
saying = 0
else:
saying = turn_num - nu... |
def get_inc_methods(browser):
"""Return all inclusion methods applicable for a given browser."""
return ["script", "link-stylesheet", "link-prefetch", "img", "iframe", "video", "audio", "object", "embed", "embed-img", "window.open", "iframe-csp"] |
def calc_node_coords(tiling_edge_list, first_node_offset=0):
"""
For a single tiling path (tiling_edge_list is a list
of edges for a particular contig) calculates the
genomic coordinate of every node in the path.
In case there are cycles in the tiling path,
the existing node's coordinate will be... |
def indent(num_spaces):
"""Gets spaces.
Args:
num_spaces: An int describes number of spaces.
Returns:
A string contains num_spaces spaces.
"""
num = num_spaces
spaces = ''
while num > 0:
spaces += ' '
num -= 1
return spaces |
def is_hello_message(message: str) -> bool:
"""Checks if a message is a hello message."""
if "Hello" in message:
return True
return False |
def chunk(seq, n):
"""
divide a sequence into equal sized chunks
(the last chunk may be smaller, but won't be empty)
"""
chunks = []
some = []
for element in seq:
if len(some) == n:
chunks.append(some)
some = []
some.append(element)
if len(some) > ... |
def _affine(mat, W_std, b_std):
"""Get covariances of affine outputs if inputs have covariances `nngp`.
The output is assumed to be `xW + b`, where `x` is the input, `W` is a matrix
of i.i.d. Gaussian weights with std `W_std`, `b` is a vector of i.i.d.
Gaussian biases with std `b_std`.
Args:
mat: a `np.... |
def proto_name(s):
"""Return the name of the proto file
>>> proto_name('foo.proto')
'foo'
:param s:
:return:
"""
return s.split('.')[0] |
def is_json(input_file):
"""
Check if the file is in JSON format.
The function reads the first character of the file, and if it is "{" then returns True.
:param input_file: file name (string)
:return: Boolean.
"""
with open(input_file) as unknown_file:
c = unknown_file.read(1)
... |
def comment_out_details(source):
"""
Given the source of a cell, comment out any lines that contain <details>
"""
filtered=[]
for line in source.splitlines():
if "details>" in line:
filtered.append('<!-- UNCOMMENT DETAILS AFTER RENDERING ' + line + ' END OF LINE TO UNCOMMENT -->... |
def get_test_case_class(test):
"""
Returns the test class name, if it can be determined.
e.g. if test.id() == "smoketests.test_smoke_001.TestCase.test_smoke_001",
this would return "TestCase".
Parameter:
test (unittest.TestCase)
"""
if hasattr(test, 'id'):
testcasename = test.i... |
def is_valid_password_1(password):
"""
>>> is_valid_password_1("111111")
True
>>> is_valid_password_1("223450")
False
>>> is_valid_password_1("123789")
False
"""
has_double = any(password[c] == password[c+1] for c in range(len(password)-1))
is_ascending = all(password[c] <= passw... |
def get_all_unique_system_ids(market_datas):
"""
Get all unique system ids from the market data
:param market_datas: the market data dictionary
:return: list of system ids
"""
system_ids = []
for _, market_data in market_datas.items():
for order in market_data:
system_id ... |
def tts_version(version):
"""Convert a version string to something the TTS will pronounce correctly.
Args:
version (str): The version string, e.g. '1.1.2'
Returns:
str: A pronounceable version string, e.g. '1 point 1 point 2'
"""
return version.replace('.', ' Punkt ') |
def concat(*args):
"""
Return a concatenated string.
"""
return ''.join(args) |
def estimate_infectious_rate_constant(events, t_start, t_end, kernel_integral, count_events=None):
"""
Returns estimation of infectious rate for given events on defined interval.
The infectious is expected to be constant on given interval.
:param events: array of event tuples containing (event_time, fo... |
def replace_none(iterable, replacement=0):
"""
replaces None in the iterable with replacement 0
:param iterable:
:param replacement:
:return:
"""
return [x if x is not None else replacement for x in iterable] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.