content stringlengths 42 6.51k |
|---|
def thresholding(x):
"""Thresholding function."""
if x > 0.:
y = 1
else:
y = 0.
return y |
def nearest_band(wavelengths, target):
"""Get index of band nearest to a target wavelength."""
idx = 0
minimum = float('inf')
for (i, wl) in enumerate(wavelengths):
if abs(target - wl) < minimum:
minimum = abs(target - wl)
idx = i
return idx |
def get_social_discount(t, r=0.01):
"""
Calaculate social discount rate.
"""
return 1 / (1 + r) ** t |
def path2handle(path):
""" Translates a full path to a handle. """
return path.split('/')[-1] |
def popular_articles_query(limit=None):
"""Return an SQL string to query for popular articles.
Args:
limit (int): The maximum number of results to query for. If
ommited, query for all matching results.
Returns:
str: An SQL string. When used in a query, the result wil... |
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
result = []
for p in paragraphs:
... |
def col_length(headline, content, dict_key=None):
"""
calculate the max needed length for a output col by getting the headline, the content of the rows
(different data types) and in some cases a specific key
:param headline: Column headline
:param content: A list of column contents
:param dict_k... |
def robustlog(x):
"""Returns log(x) if x > 0, the complex log cmath.log(x) if x < 0,
or float('-inf') if x == 0.
"""
if x == 0.:
return float('-inf')
elif type(x) is complex or (type(x) is float and x < 0):
return cmath.log(x)
else:
return math.log(x) |
def insert_relationships(datapoints):
"""Inserts an empty relationship at index 4"""
new_datapoints = set()
for dp in datapoints:
cast_dp = list(dp)
cast_dp.insert(4, "")
new_datapoints.add(tuple(cast_dp))
return new_datapoints |
def d_phi_dy(x, y):
"""
angular derivative in respect to y when phi = arctan2(y, x)
:param x:
:param y:
:return:
"""
return x / (x**2 + y**2) |
def convert_size(size):
"""Convert bytes to mb or kb depending on scale"""
kb = size // 1000
mb = round(kb / 1000, 1)
if kb > 1000:
return f'{mb:,.1f} MB'
else:
return f'{kb:,d} KB' |
def average_above_zero(tab):
"""
brief: computes ten average of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the computed average
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstance(tab, list)):
raise Value... |
def match_users(users):
"""Returns a tuple: a list of pairs of users and a list of unmatched users."""
user_list = users.copy()
matched = []
# print(user_list)
while len(user_list) > 1:
matched.append(
(user_list.pop(), user_list.pop())
)
return matched, user_list |
def get_true_url(url):
"""
get the true URL of an otherwise messy URL
"""
data = url.split("/")
return "{}//{}".format(data[0], data[2]) |
def onehot_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return [x == s for s in allowable_set] |
def hb_energy_times_to_power(es, ee, ts, te):
"""Compute power from start and end energy and times.
Return: power values
"""
return (ee - es) / ((te - ts) / 1000.0) |
def pretty_time_delta(seconds):
"""Prints a number of seconds in a terse, human-readable format.
Adapted from: https://gist.github.com/thatalextaylor/7408395
"""
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(se... |
def split_message(data, boundary):
""" Split the message into it separate parts based on the boundary.
:param data: raw message data
:param boundary: boundary used in message
:return: message parts, that were separated by boundary
"""
# Split the data into message parts using the boundar... |
def format_filename(string):
"""
Converts a string to an acceptable filename
e.g. "Go! series - F1" into "Go_series_-_F1"
Parameters:
string (str): raw filename
Returns:
formatted_filename (str): formatted filename
Raises:
"""
# NOTE: Periods (.) and dashes (-) are a... |
def _ToLocalPath(toplevel_dir, path):
"""Converts |path| to a path relative to |toplevel_dir|."""
if path == toplevel_dir:
return ''
if path.startswith(toplevel_dir + '/'):
return path[len(toplevel_dir) + len('/'):]
return path |
def index_requests(reqs):
"""adds an index key for each dict entry in the array
Args:
requests_set (list): Array of requests to send:
request(dict): required to have
- method(string): http method to use
- url(string): url of the requested resource
... |
def get_matrix41():
"""
Return the matrix with ID 41.
"""
return [
[0.000, 0.000, 0.333],
[0.033, 0.050, 0.267],
[0.067, 0.100, 0.200],
[0.100, 0.175, 0.100],
[0.200, 0.200, 0.067],
[0.267, 0.225, 0.033],
[0.333, 0.250, 0.000],
] |
def compute_chi_eff(m1,m2,s1,s2):
""" Compute chi effective spin parameter (for a given component)
--------
m1 = primary mass component [solar masses]
m2 = secondary mass component [solar masses]
s1 = primary spin z-component [dimensionless]
s2 = secondary spin z-component [d... |
def nearly_equal(a,b,sig_fig=5):
"""
Returns it two numbers are nearly equal within sig_fig decimal places
http://stackoverflow.com/questions/558216/function-to-determine-if-two-numbers-are-nearly-equal-when-rounded-to-n-signific
:param flt a: number 1
:param flt b: number 2
:param int sig_fig: nu... |
def span(data, **kwargs):
"""
Compute the difference of largest and smallest data point.
"""
return max(data) - min(data) |
def _evalfact(lcs, c):
"""Input: a list of variable-bracketed strings, the known LCS
Output: number of variables needed and the variables themselves in a list."""
allbreaks = []
for w in c:
breaks = [0] * len(lcs)
p = 0
inside = 0
for pos in w:
if pos == "[":
... |
def align(num, exp):
"""Round up to multiple of 2**exp."""
mask = 2**exp - 1
return (num + mask) & ~mask |
def summ_nsqr(i1, i2):
"""Return the summation from i1 to i2 of n^2"""
return ((i2 * (i2+1) * (2*i2 + 1)) / 6) - (((i1-1) * i1 * (2*(i1-1) + 1)) / 6) |
def tokens(_s, _separator=' '):
"""Returns all the tokens from a string, separated by a given separator, default ' '"""
return _s.strip().split(_separator) |
def isSea(obj):
"""
Detect whether obj is a SEA object.
:param obj: Object
"""
return True if hasattr(obj, 'SeaObject') else False |
def getElectronDensityLink(pdb_code, diff=False):
"""Returns the html path to the 2FoFc electron density file on the ebi server
:param diff: Optionaly, defaults to False, if true gets the Fo-Fc, if Flase gets the 2Fo-Fc
"""
file_name = pdb_code + '.ccp4'
if diff:
file_name = pdb_code + '_di... |
def e_palavra_potencial(arg):
"""
Reconhecedor do TAD palavra_potencial
Verifica se o arg e palavra_potencial e devolve valor booleano
Argumentos:
arg -- argumento a verificar
"""
return isinstance(arg, str) and all(l.isupper() for l in arg) |
def not_lane(b, n):
"""
Bitwise NOT in Python for n bits by default.
"""
return (1 << n) - 1 - b |
def replace_celltypes(celldict,row,label):
""" Replaces cell type with max celltype in anndata object, but preserves original call if no max cell type is found. """
if row['leiden'] in celldict:
return(celldict[row['leiden']])
else:
return(row[label]) |
def read_key_value(line, separator='='):
"""
Read a key and value from a line.
Only splits on first instance of separator.
:param line: string of text to read.
:param separator: key-value separator
"""
key, value = line.split(separator, 1)
return key.strip(), value.strip() |
def isfloat(element):
"""
This function check if a string is convertable to float
"""
try:
float(element)
return True
except ValueError:
return False |
def _public_coverage_ht_path(data_type: str, version: str) -> str:
"""
Get public coverage hail table
:param data_type: One of "exomes" or "genomes"
:param version: One of the release versions of gnomAD on GRCh38
:return: path to coverage Table
"""
return f"gs://gnomad-public-requester-pays... |
def order_to_process(a, b):
"""
Takes two sorted lists of tuples and returns a
combined list sorted by lowest first element
Paramters:
a, b - a sorted list of tuples
"""
ret_l = []
while a and b:
ret_l.append(a.pop(0) if a <= b else b.pop(0))
ret_l.extend(a)
ret_l.exten... |
def first_item(l):
"""Returns first item in the list or None if empty."""
return l[0] if len(l) > 0 else None |
def power_set(values):
"""Return all the set of all subsets of a set."""
# A: init the set for the return value
subsets = list()
def size_subsets(size, current, values):
"""Finds all subsets of a given size in a set."""
# Base Case: the current subset is full
if len(current) == ... |
def signed_to_unsigned_8bit(data):
"""
Converts 8-bit signed data initally read as unsigned data back to its
original relative position.
"""
# Python reads bytes as unsigned chars (0 to 255).
# For example: Byte "FF" in a signed file is -1, but Python will read it
# as the unsigned value 255... |
def ordered_binary_search(ordered_list, item):
"""Binary search in an ordered list
Complexity: O(log n)
Args:
ordered_list (list): An ordered list.
item (int): The item to search.
Returns:
bool: Boolean with the answer of the search.
Examples:
>>> alist... |
def create_dict(items):
"""
creates a dict with each key and value set to an item of given list.
:param list items: items to create a dict from them.
:rtype: dict
"""
result = {name: name for name in items}
return result |
def _ReportFileAndLine(filename, line_num):
"""Default error formatter for _FindNewViolationsOfRule."""
return '%s (line %s)' % (filename, line_num) |
def has_spaces(txt:str) -> bool:
"""Determine if txt has spaces."""
return len(txt.split(" ")) > 1 |
def forge_nat(value) -> bytes:
"""
Encode a number using LEB128 encoding (Zarith)
:param int value: the value to encode
:return: encoded value
:rtype: bytes
"""
if value < 0:
raise ValueError('Value cannot be negative.')
buf = bytearray()
more = True
while more:
... |
def mc_pow(data):
"""
Modulus calculation. Squared version.
Calculated real^2+imag^2
"""
return data.real ** 2 + data.imag ** 2 |
def to_px8(p):
"""Convenience method to convert pymunk coordinates to px8
"""
return int(p[0]), 128 - int(p[1]) |
def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
"""Replace the Python tag in a wheel file name with a new value.
"""
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts) |
def clean_question_mark(content):
"""Removes question mark strings, turning them to nulls.
Parameters
----------
content: :class:`str`
A string to clean.
Returns
-------
:class:`str`
The string, or None if it was a question mark.
"""
if not content:
return N... |
def tag_clean(n):
"""Get tagname without prefix"""
if n[0] in u"-~!": return n[1:]
return n |
def _create_sanic_web_config():
"""
Sanic log configuration to avoid duplicate messages
Default log configuration Sanic uses has handlers set up that causes
messages to be logged twice, so pass in a minimal config of our own to
avoid those handlers being created / used
"""
return dict(
... |
def transpose_tabular(rows):
"""
Takes a list of lists, all of which must be the same length,
and returns their transpose.
:param rows: List of lists, all must be the same length
:returns: Transposed list of lists.
"""
return list(map(list, zip(*rows))) |
def get_detailtrans_21cn(data_base, type):
"""
get 21 detail trans dict
:param data_base:
:param type:
:return:
"""
data21cn = data_base.get("ec21") if type == 'en' else data_base.get("ce_new")
if not data21cn:
return None
# -----source
# source21cn = data21cn.get("sourc... |
def find_filename(path_to_file):
"""
extract filename given path
@param path_to_file - relative path to file
"""
return path_to_file.split('/')[-1] |
def beaufort(n):
"""Converts windspeed in m/s into Beaufort Scale descriptor."""
s = ''
if n < 0.3:
s = 'calm'
elif n < 1.6:
s = 'light air'
elif n < 3.4:
s = 'light breeze'
elif n < 5.5:
s = 'gentle breeze'
elif n < 8.0:
s = 'moderate breeze'
elif... |
def test_sub_grids(board: list) -> bool:
"""
test each of the nine 3x3 sub-grids
(also known as blocks)
"""
sub_grids = [
board[0][0:3] + board[1][0:3] + board[2][0:3],
board[0][3:6] + board[1][3:6] + board[2][3:6],
board[0][6:] + board[1][6:] + board[2][6:],
board[3][0:3] + board[4][0:3] + board[5][0:3]... |
def manhatten_distance(point):
"""Manhatten distance between point and the origin."""
return int(abs(point.real) + abs(point.imag)) |
def timedur(x):
"""
Print consistent string format of seconds passed.
Example: 300 = '5 mins'
Example: 86400 = '1 day'
Example: 86705 = '1 day, 5 mins, 5 sec'
"""
divs = [('days', 86400), ('hours', 3600), ('mins', 60)]
x = float(x)
res = []
for lbl, sec in divs:
... |
def fix_star(word):
""" Replace ``*`` with ``\*`` so that is will be parsed properly by
docutils.
"""
return word.replace('*', '\*') |
def mention_user(user):
"""
Helper function to make it easier to mention users
:Args:
`user` the ID of the user
:Returns:
A string formatted in a way that will mention the user on Slack
"""
return "<@" + user + ">" |
def assemble_message_from_columns(columns_to_build_from):
"""Reacrete message from N columns (N = columns_to_build_from)"""
#initialize the text structure
max_column_len = max([len(c) for c in columns_to_build_from])
text = ""
for i in range(0, max_column_len):
for c in columns_to_build_from... |
def _rn_daily(rs, rnl):
"""Daily net radiation (Eqs. 15 & 16)
Parameters
----------
rs : scalar or array_like of shape(M, )
Incoming solar radiation [MJ m-2 d-1].
rnl : scalar or array_like of shape(M, )
Net long-wave radiation [MJ m-2 d-1].
Returns
-------
ndarray
... |
def _myDet(p, q, r):
"""Calc. determinant of a special matrix with three 2D points.
The sign, "-" or "+", determines the side, right or left,
respectivly, on which the point r lies, when measured against
a directed vector from p to q.
"""
# We use Sarrus' Rule to calculate the determinant.
# (could also use th... |
def get_failing_item(state):
"""Return name of failing item or None if none are failing"""
for key, value in state.items():
if not value:
return key
return None |
def echo(obj):
"""
Prints the value to the console.
"""
print(obj)
return obj |
def merge_partial(a, b):
"""
:return: Merged value containing the partial combined calculation
"""
if hasattr(a, '__add__'):
return a + b
for key, val in b.items():
if key not in a:
a[key] = val
else:
a[key] = merge_partial(a[key], val)
return a |
def schema_decorator(decorators_state, cls):
"""Adds cls to decorator_state"""
decorators_state['schema'] = cls()
return cls |
def _edge_is_between_selections(edge, selection_a, selection_b):
"""
Returns ``True`` is the edge has one end in each selection.
Parameters
----------
edge: tuple[int, int]
selection_a: collections.abc.Container[collections.abc.Hashable]
selection_b: collections.abc.Container[collections.ab... |
def is_prime(number: int):
"""
This function finds if the number is prime
Returns:
True if prime false otherwise
"""
for index in range(2, (number//2) + 1):
if number%index == 0:
return False
return True |
def my_confusion_matrix(rater_a, rater_b, sample_weight, min_rating=None, max_rating=None):
"""
Returns the (weighted) confusion matrix between rater's ratings
"""
assert (len(rater_a) == len(rater_b))
if min_rating is None:
min_rating = min(rater_a + rater_b)
if max_rating is None:
... |
def remove_sql_comment_from_string(string):
""" takes a string of the form : part of query -- comment and returns only the former.
:string: part of sql query -- comment type strings
:returns: the part of the sql query
"""
query_part = string.strip().split('--')[0].strip()
return query_part |
def parameters_analyser(string_instruction):
""" Return a list with the parameters of the instruction.
A post treatment may be required for some instruction """
return string_instruction.split(', ') |
def is_input_valid(char: str) -> bool:
"""
Helper that checks if input is valid
"""
# is there a char at all?
if char is None:
return False
# check for embedded 0 byte
if char == "\0":
return False
return True |
def scale(points, scalar):
"""Try really hard to scale 'points' by 'scalar'.
@type points: mixed
@param points: Points can either be:
- a sequence of pairs, in which case the second item will be scaled,
- a list, or
- a number
@type scalar: number
@param scalar: the amou... |
def compare_version_part(a_part, b_part):
"""Compare two parts of a version number and return the difference (taking into account
versions like 7.0.0-M1)."""
try:
a_bits = a_part.split('-')
b_bits = b_part.split('-')
version_difference = int(a_bits[0]) - int(b_bits[0])
if ver... |
def prime_sieve(upper, lower=2):
"""Returns a list of primes from 2 to 'upper'"""
if lower < 2:
raise ValueError("Lower bound cannot be lower than 2")
prime_list = list(range(lower, upper))
index = 0
while True:
try:
prime = prime_list[index]
for i in prime_l... |
def websocketize(value):
"""Convert a HTTP(S) URL into a WS(S) URL."""
if not (value.startswith('http://') or value.startswith('https://')):
raise ValueError('cannot websocketize non-HTTP URL')
return 'ws' + value[len('http'):] |
def magnitude_relative_error(estimate, actual, balanced=False):
"""
Normalizes the difference between actual and predicted values.
:param estimate:Estimated by the model.
:param actual: Real value in data.
:return: MRE
"""
if not balanced:
denominator = actual
else:
deno... |
def get_lattice_points(tup1, tup2, check_diagonals = True):
"""Returns a list of points which lie in a line defined by two endpoints"""
x1, y1 = tup1[0], tup1[1]
x2, y2 = tup2[0], tup2[1]
# for horizontal lines, y values are same
if y1 == y2:
if x1 <= x2:
points = [(i, y1)... |
def is_wildcard_allowed(san_regexes):
"""
:param list[str] san_regexes:
:rtype: bool
"""
if not san_regexes:
return False
for val in san_regexes:
if not val.startswith('[*a'):
return False
return True |
def get_empty_preference_message(preference_key):
"""
Returns the validation message shown for an empty preference.
"""
return f"Preference '{preference_key}' cannot be set to an empty value." |
def reverse_table(tab):
"""
This function reverse the table
Parameters :
tab: the list
Returns :
return the reverse table
"""
for i in range(len(tab)//2):
tmp = tab[i]
endVal = len(tab)-i-1
tab[i] = tab[endVal]
tab[endVal] = tmp
return tab |
def _Spaced(lines):
"""Adds a line of space between the passed in lines."""
spaced_lines = []
for line in lines:
if spaced_lines:
spaced_lines.append(' ')
spaced_lines.append(line)
return spaced_lines |
def orm_coerce_row(row, extra_columns, result_type):
"""Trim off the extra columns."""
# orm_get_page might have added some extra columns to the query in order
# to get the keys for the bookmark. Here, we split the rows back to the
# requested data and the ordering keys.
N = len(row) - len(extra_col... |
def cube(x):
"""Cube of x."""
return x * x * x |
def submit_url(url):
"""Returns the submission url."""
return 'https://class.coursera.org/' + url + '/assignment/submit' |
def add_up_errors(list_keyerror):
"""
#################################################################################
Description:
Adds in one string the given keyerrors from the list of keyerrors
#################################################################################
:param list_ke... |
def getChanprofIndex(chanprof, profile, chanList):
""" List of indices into the RTTOV chanprof(:) array corresponding to the chanlist.
NB This assumes you've checked the chanlist against chanprof already.
"""
ilo = sum(map(len, chanprof[:profile-1]))
ichanprof = []
for c in chanList:
... |
def _gr_ymax_ ( graph ) :
""" Get maximal x for the points
>>> graph = ...
>>> ymax = graph.ymax ()
"""
ymx = None
np = len ( graph )
for ip in range ( np ) :
x , y = graph[ip]
if None == ymx or y >= ymx : ymx = y
return ymx |
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the accelerat... |
def _find_imports(*args):
"""
Helper sorting the named modules into existing and not existing.
"""
import importlib
exists = {
True: [],
False: [],
}
for name in args:
try:
importlib.import_module(name)
exists[True].append(name)
except ImportError:
exists[False].append(n... |
def extract_port_num(arg):
"""Extract port number from command line argument."""
port = 0
try:
port = int(arg)
except ValueError:
print("Invalid port number\n")
return port |
def _get_reputation(followers, following):
"""Get reputation of user."""
try:
return followers / (followers + following)
except ZeroDivisionError:
return 0.0 |
def cli_err_msg(cmd, err):
""" get cli exception message"""
if not err:
return "Error: Fail to get cli exception message."
msg = list()
err_list = str(err).split("\r\n")
for err in err_list:
err = err.strip('.,\r\n\t ')
if not err:
continue
if cmd and cm... |
def tupleRemoveByIndex(initTuple, indexList):
"""
Remove the elements of given indices from a tuple.
Parameters
----------
initTuple : tuple of any
The given tuple from which we will remove elements.
indexList : list of ints
The indices of elements that we want to remove.
R... |
def make_full_size_url(image_name):
"""Return the URL to the full size of the file."""
base_url = "http://commons.wikimedia.org/w/index.php?title=Special:FilePath&file=%s"
return base_url % (image_name) |
def words_are_alphabetic(word_list, debug):
"""Return whether words in list are sorted alphabetically."""
return sorted(word_list) == word_list |
def break_words(stuff):
"""This fuction will break up words for us."""
words = stuff.split(' ')
return words |
def fib(number):
"""Get the Nth Fibonacci number, cache intermediate results in Redis."""
if number < 0:
raise ValueError
if number in (0, 1):
return number
return fib(number - 1) + fib(number - 2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.