content stringlengths 42 6.51k |
|---|
def round_float_to_str(val):
"""Function to round a float to our set number of sigificant digits
Args:
val (float): input value
Returns:
float: rounded float value
"""
return "{:.4f}".format(val) |
def linearInterpolation(x1, x2, y1, y2, x):
"""
A default linear interpolation functions for the value x between two points
p1 = (x1,y1) and p2 = (x2,y2).
Parameters
----------
x : float
The input x value
Returns
-------
y : float
the output y value.
"""
... |
def is_empty(val):
"""Check if a variable is an empty string or an empty list."""
return val == "" or val == [] |
def extract_arxiv_links(urls):
"""
Try to find an arXiv link from a given list of URLs.
:param urls: A list of URLs.
:returns: First matching arXiv URL, or ``None``.
"""
arxiv_urls = [url for url in urls if "://arxiv.org" in url]
if len(arxiv_urls) > 0:
return arxiv_urls[0]
else... |
def alignment_error_rate(reference, hypothesis, possible=None):
"""
Return the Alignment Error Rate (AER) of an alignment
with respect to a "gold standard" reference alignment.
Return an error rate between 0.0 (perfect alignment) and 1.0 (no
alignment).
>>> from nltk.translate import Alignm... |
def get_source_path(project_name):
""" each project contains differents java_path """
paths = {
"Chart": "source",
"Closure": "src",
"Lang": "src/java",
"Lang2": "src/main/java",
"Math": "src/main/java",
"Math2": "src/java",
"Mockito": "src",
"Time... |
def append(base_url, *args):
"""Append paths together."""
extension = '/'.join([u.strip('/') for u in args])
if extension:
url = base_url.rstrip('/')+'/'+extension
else:
url = base_url
return url |
def is_palindrome(n):
"""
Fill in the blanks '_____' to check if a number
is a palindrome.
>>> is_palindrome(12321)
True
>>> is_palindrome(42)
False
>>> is_palindrome(2015)
False
>>> is_palindrome(55)
True
"""
x, y = n, 0
f = lambda: y * 10 + x % 10
while x >... |
def sanitise(string, replacements={'_' : '-'}):
"""
Substitute characters that are used as separators in the pathname and other
special characters if required
"""
for c in replacements:
string = string.replace(c, replacements[c])
return string |
def getRowValList(CSVList):
"""
Expected Input: List of all rows within CSV file.
Expected Output: List of columns within CSVList.
"""
valList = []
for row in CSVList:
valList.append(row)
valList.pop(0)
return(valList) |
def make_dict(title, quantity, percent):
"""
Small utility to create dictionary with title, quantity and percent
Args:
title: The title
quantity: quantity
percent: percent
Returns:
dict(dict): Dictionary
"""
return {"title": title,
"quantity": quantity,
... |
def from_task_key(key):
"""
Retrieves the coordinates of a tasks given its corresponding key
:param key: the key to use
:return: x and y coordinates of the task
"""
return key[0], key[1] |
def replace_grid(old_grid, new_grid, topology_grid):
"""Replaces old hyperparameter search grid with one supplied by YAML."""
#print(old_grid,new_grid)
for k in new_grid.keys():
if k != 'topology_grid':
old_grid["--{}".format(k)] = new_grid[k]
if 'topology_grid' in new_grid:
topology_grid = new_grid.pop('top... |
def is_leaf(node_value):
"""This function checks whether a validation node is a leaf or not.
Args:
node_value(dict): The value of the node you want to check.
Returns:
: bool.
"""
return isinstance(node_value, dict) and 'required' in node_value |
def find_lcs(strings):
""" Find longest common substring of all strings in list """
num_strings = len(strings)
# Take first word from array as reference
len_0 = len(strings[0])
results = set()
for i in range(len_0):
for j in range(i + 1, len_0 + 1):
# generating all possi... |
def double_digit(num):
""" This returns two string digits """
if num > 9:
return str(num)
else:
return "0" + str(num) |
def incb(sstr: str):
""" in_curly_braces """
return '{' + sstr + '}' |
def shorten_message(message, max_length, ellipsis):
"""Shortens the message to at most max_length characters by using the given
ellipsis.
"""
if max_length <= 0 or len(message) <= max_length:
# Nothing to shorten.
return message
if len(ellipsis) >= max_length:
# We cannot in... |
def format_list(record_list):
"""Format a list into a string to increase readability in CSV"""
# record_list should only be a list, not an integer, None, or
# anything else. Thus this if clause handles only empty
# lists. This makes a "null" appear in the JSON output for
# empty lists, as expected... |
def get_pairs(word):
"""
Args:
word (tuple): tuple of symbols (symbols being variable-length strings).
Returns:
set: symbol pairs in a word.
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return p... |
def fany(func, iterable):
"""
fany(func: function, iter: iterable)
return true if any element x make func(x) == True
args:
func = x > 0, iter = [-1,0,1]
return:
True
"""
for x in iterable:
if func(x): return True
return False |
def cell_empty(value) -> bool:
"""Checks if a cell is empty. Cells contain True or False return False"""
if isinstance(value, bool):
return False
if not value:
return True
return False |
def all_uppercase(title_words):
"""
if the words are all in uppercase
>>> all_uppercase(["A", "B", "C"])
True
>>> all_uppercase(["A", "12B", "C12"])
True
>>> all_uppercase(["A", "12B", "c12"])
False
"""
concat_str = ''.join(title_words)
return concat_str.upper() == concat_st... |
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
if s.strip() == '':
return 0
list_ = s.strip().split(" ")
for i in range(list_.count('')):
list_.remove('')
return len(list_[-1]) |
def disjoint2(a, b, c):
"""Return True if there is no element common to all three lists."""
for i in a:
for j in b:
if i == j: # only check c if we found match from a and b.
return False
for k in c:
if i == k: # (and thus i == j == k)
... |
def _node_create_dict(nodes):
""" Convert a set of :class:`.Node` objects into a dictionary of
:class:`.Node` lists, keyed by frozenset(labels).
:param nodes:
:return: dict of frozenset(labels) to list(nodes)
"""
d = {}
for node in nodes:
key = frozenset(node.labels)
d.setde... |
def qualified_column(column_name: str, alias: str="") -> str:
"""
Returns a column in the form "table.column" if the table is not
empty. If the table is empty it returns the column itself.
"""
return column_name if not alias else f"{alias}.{column_name}" |
def eccentricity_earth_orbit(julian_century):
"""Returns the Eccentricity or Earth Orbit with Julian Century, julian_century."""
ecc_earth_orb = 0.016708634 - julian_century * (
0.000042037 + 0.0000001267 * julian_century
)
return ecc_earth_orb |
def float2Fixed(value):
"""The float2Fixed method translates a float into a 1/64 pixel
unit-value."""
return int(round(value * 64)) |
def db_list_maker(info):
"""
Creates a list from a tuple of lists.
:param info: Tuple of Lists
:return: List
"""
answer = []
for i in info:
answer.append(i[0])
return answer |
def get_max_len(api_table_database):
"""
Return the max text length for Prototype, Description and Parameters field of API table
"""
pro_len = 0
des_len = 0
par_len = 0
for idx, details in api_table_database.items():
pro_idx = 5 + details[2] - 1
if pro_len < len(details[pro_idx]):
pro_len = len(details[p... |
def parse_number(x):
"""
Parse argument as int or float.
"""
try:
return int(x)
except ValueError:
return float(x) |
def exponential_scaling(base, exponent):
"""Behold, exponents that don't die with negative values."""
if base>0:
return abs(base)**exponent
else:
return -(abs(base)**exponent) |
def _uniq(iterable):
"""Returns a list of unique elements in `iterable`.
Requires all the elements to be hashable.
Args:
iterable: An iterable to filter.
Returns:
A new list with all unique elements from `iterable`.
"""
unique_elements = {element: None for element in iterable}
... |
def get_keypress_event_trigger_key(event: str) -> int:
"""Find the key number which triggers particular keypress event."""
comparison_str = "e.which == "
if comparison_str not in event:
return -1
comparison_start = event.index(comparison_str) + len(comparison_str)
comparison_end = event.find... |
def UpdateGuessWord(Input, alphabet_guess_already):
"""update new Input to alphabet_guess_already"""
alphabet_guess_already.append(Input)
return alphabet_guess_already |
def get_order_update_critical_section_key(order_id):
"""
:param order_id: the pk of the order
:return: the key to be used with CriticalSection for preventing multiple
threads from updating the same order at the same time
"""
return 'zipline-updating-order-id-{}'.format(order_id) |
def craft_invalidator_key(prefix: str, db_table: str, conj: dict) -> str:
"""
this function will generate the invalidator key
from the invalidator key, we can invalidate old data
invalidate_key -> data_key -> data
the invalidator key will have the following format
[prefix]conj:db_name:field1=v... |
def list_to_tuples(list_to_pair, pair_length):
"""Pairs elements of list into tuples of pair_length
Args:
list_to_pair (List)
pair_length (int)
Returns:
List of tuples
"""
# Create N copies of the same iterator
it = [iter(list_to_pair)] * pair_length
# Unpack the co... |
def parse_coeff_line(coeff_str):
"""
split str coef to float list
:param coeff_str : line coef
:type coeff_str : str
:return coeff list
:rtype list()
"""
return [float(el) for el in coeff_str.split()] |
def format_name(name):
"""
Format parameter names for output
Parameters
----------
name: str
Name to be formatted
Returns
-------
str: Formatted name
"""
name = name.replace("_", " ")
return name |
def _to_base(n, base):
"""Transforms an integer to another defined base."""
len_base = len(base)
if n < len_base:
return base[n]
else:
return _to_base(n // len_base, base) + base[n % len_base] |
def next_p2 (num):
""" If num isn't a power of 2, will return the next higher power of two """
rval = 1
while (rval<num):
rval <<= 1
return rval |
def _concat(left: str, right: str) -> str:
"""Convenience function
Takes two string representations of regular expressions, where the empty
string is considered as matching the empty langage, and returns a string
representation of their concatenation.
"""
if len(left) > 0 and len(right) > 0:
... |
def npasser(inbox, n=None):
"""
Passes "n" first inputs from inbox. By default passes the whole inbox.
Arguments:
- n(``int``) [default: ``None``]
"""
return inbox[:n] |
def drop(i_list: list,n:int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert(n>0)
_shallow_list = []
k=1
for element in i_list:
if k % n != 0:
... |
def hexify(number):
"""Produce hex string of the given number with leading '0x' removed."""
return hex(number)[2:] |
def is_truthy(candidate_value):
"""
Converts many representations of "True" into a boolean True
@param: candidate_value - the value to be evaluated. Any of the following will be considered True
"true", "TRUE", "True", "1", any number except zero, True
"""
if isinstance(candidate_value, str):
... |
def is_rule(fun):
""" Returns whether something is a rule or not """
is_callable = hasattr(fun, '__call__')
return is_callable and hasattr(fun, "is_rule") and fun.is_rule |
def out_of_bounds(cell_size, pos) -> bool:
"""
Checks whether a position is out of the game board.
:param cell_size: Board size as array
:param pos: tuple (x, y)
:return: bool
"""
x, y = pos
return x < 0 or x >= cell_size[1] or y < 0 or y >= cell_size[0] |
def list_is_flat(l):
"""Determine if the given list is flat (only check for other lists,
not other iterables).
"""
for x in l:
if isinstance(x, list):
return False
return True |
def get_api_url_from_base(base_url):
"""Get the full URL given a base URL"""
if base_url.endswith("/") != True:
base_url += "/"
base_url += "api/workflows/"
return base_url |
def t_ana(i, j, k, dz, dx, dy, zsa, xsa, ysa, vzero):
"""Calculate analytical times in homogeneous model."""
return (
vzero
* ((dz * (i - zsa)) ** 2.0 + (dx * (j - xsa)) ** 2.0 + (dy * (k - ysa)) ** 2.0)
** 0.5
) |
def process_template(pairs, rules):
"""
process dict of pairs with list of rules
"""
new_pairs = {}
for pair in pairs:
if pair in rules:
cnt = pairs[pair]
new_pairs[pair[0] + rules[pair]] = (
new_pairs.get(pair[0] + rules[pair], 0) + cnt
)
... |
def _get_prog_path(env, key, name):
"""Try to find the executable 'name' and store its location in env[key]."""
# check if the user already specified the location
try:
return env[key]
except KeyError:
pass
# asciidoc and a2x may be installed with a '.py' suffix
prog_path = env.... |
def connack_string(connack_code):
"""Return the string associated with a CONNACK result."""
if connack_code == 0:
return "Connection Accepted."
elif connack_code == 1:
return "Connection Refused: unacceptable protocol version."
elif connack_code == 2:
return "Connection Refused: ... |
def basic(x_old, r=3.9):
"""Logmap update dynamics (1 step)
:param float x_old: current value
:param float r: parameter
:return: next value
"""
x_new = r * x_old * (1.0 - x_old)
return x_new |
def quantile(values, q):
"""
Returns q-th quantile.
"""
values = sorted(values)
size = len(values)
idx = int(round(size * q)) - 1
if idx == 0:
raise ValueError("Sample size too small: %s" % len(values))
return values[idx] |
def lai(params: dict, states: dict) -> float:
"""
Calculates leaf area index
Parameters
----------
params: dict
sla: float
Specific leaf area. [m2 {leaf} mg-1 {CH2O}]
states: dict
CLeaf: float
Carbohydrates stored in the leaves [mg m-2]
Returns
... |
def coord_while(n, a=0, b=1):
"""Function does the same thing as coord_for but uses a while loop instead of for."""
a=float(a)
b=float(b)
coords=[]
num=a
while num!=(n+1):
coords.append((b-a)*num/n)
num=len(coords)
return coords |
def getColumnLocations(columnNumber):
"""
Return a list of all nine locations in a column.
:param int rowNumber: Column
:return: List of tuples
:rtype: list
"""
return [(row, columnNumber) for row in range(9)] |
def crf_kernel_config(defn):
"""Creates a default kernel configuration for sampling the dish assignment
using the "Posterior sampling in the Chinese restaurant franchise" Gibbs
sampler from Teh et al (2005)
Parameters
----------
defn : LDA model definition
"""
return ['crf'] |
def is_boc(lbl, iob, prev_lbl, prev_iob, otag='O'):
"""
is beginning of a chunk
supports: IOB, IOBE, BILOU schemes
- {E,L} --> last
- {S,U} --> unit
:param lbl: current label
:param iob: current iob
:param prev_lbl: previous label
:param prev_iob: previous iob
:... |
def ReadFile(filename):
"""Reads a list of numbers from a file.
filename: string
returns: list of float
"""
fp = open(filename)
data = []
for line in fp:
x = float(line.strip())
data.append(x)
return data |
def argmin(arr, f):
"""Return the index, i, in arr that minimizes f(arr[i])"""
m = None
i = None
for idx, item in enumerate(arr):
if item is not None:
if m is None or f(item) < m:
m = f(item)
i = idx
return i |
def merge(tree1, tree2):
"""Merges two Splay trees, tree1 and tree2, using the last element (of highest rank) in tree1 (left string) as the node for merging, into a new Splay tree.
CONSTRAINTS: None.
INPUTS: tree1, tree2.
OUTPUT (the return value of this function) is tree1, with all the elements of ... |
def parse_remote(path,loopback=False,login_flag=False):
"""parse remote connection string of the form ``[[user@]host:]path``
Args:
path (str): remote connection string.
loopback (bool, default=False): if True, ensure *host* is used.
login_flag (bool, default=False): if True, prepend use... |
def build_tree(list_of_strings):
"""Function takes a list of strings, ie:
user.address.city
user.address.postcode
user.name.first
user.name.last
user.age
And builds a tree of nested dictionaries.
"""
tree = {}
node = tree
for key in list_of_strings:
if '.' in key:
... |
def parse_error(bad_token):
"""Returns an error message and the token causing it
"""
return {"error": f"parsing error, invalid token [{bad_token}] found"} |
def epsilon_tensor(i, j, k):
"""Rank-3 epsilon tensor
Based on https://codegolf.stackexchange.com/a/160375
"""
test_set = set((i, j, k))
if not (test_set <= set((1, 2, 3)) or test_set <= set((0, 1, 2))):
raise Exception("Unexpected input", i, j, k)
return (i - j) * (j - k) * (k - i) / ... |
def prone_rewards(rewards):
"""Prone reward to be between 0 to 1s
"""
if isinstance(rewards, list):
return [max(min(r, 1), 0) for r in rewards]
return max(min(rewards, 1), 0) |
def square_rect_deindex(index, rect_x, rect_y, width, height):
"""Performs the inverse of square_rect_index
Equivalent to list(square_rect(...))[index]"""
dx = index % width
dy = index // width
assert dx >= 0 and dy < height
return (rect_x + dx, rect_y + dy) |
def get_handedness(sys):
"""Return the handedness of the coordinate system sys, as seen from inside
the celestial sphere, in the standard IAU convention."""
if sys in ["altaz","tele","bore"]: return 'R'
else: return 'L' |
def pyramid_steps_concat(n):
"""Return a list of "n" progression pyramid steps, concatenating the parts."""
result = []
for i in range(1, n + 1):
result.append((" " * (n - i)) + ("#" * (i * 2 - 1)) + (" " * (n - i)))
return result |
def assemble_transcripts(run_parallel, samples):
"""
assembly strategy rationale implemented as suggested in
http://www.nature.com/nprot/journal/v7/n3/full/nprot.2012.016.html
run Cufflinks in without a reference GTF for each individual sample
merge the assemblies with Cuffmerge using a reference G... |
def get_peer_name(cert):
"""Extract the client name from an SSL certificate
Parameters:
cert (dict): SSL certificate
Returns:
str: Client name
"""
subject = cert['subject']
for x in subject:
if x[0][0] == 'commonName':
return x[0][1] |
def clean_line(url):
"""Clean input line"""
return url.rstrip('\n') |
def curvatures_bending_plate(m1, m2, m12, D, poisson):
"""
Calculates the curvature values on a plate caused by bi-directional bending.
"""
k1 = (1 / (D * (1 - poisson ** 2))) * (m1 - poisson * m2)
k2 = (1 / (D * (1 - poisson ** 2))) * (m2 - poisson * m1)
k12 = (1 / (D * (1 - poisson))) * m12
... |
def _interval_to_seconds(interval, valid_units='smhdw'):
"""Convert the timeout duration to seconds.
The value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
interval: A "<integer><unit>" string.
valid_units: A list of suppor... |
def Soluvw(u, v, w):
""" Given positive numbers u and v, gives one solution to the equation x*u + y*v = w
where x and y are numbers in the interval [0,1].
If there is no solution, gives False, if solution exists, gives the 'average' solution
x = (x_min+x_max)/2 or y = (y_min+y_max)/2.
"""
if (w<... |
def ap(helplist, format_, sep=', '):
"""Little helper to enforce consistency"""
if helplist == '-':
return helplist
ls = [format_ % x for x in helplist]
return sep.join(ls) |
def minValue(inputArray):
"""
minValue
Function used to calculate the minimum value of an array
@param inputArray Array passed for calculation
@return minValueReturn The integer value returned by the calculation
"""
minValueReturn = min(inputArray)
return minValueReturn |
def get_time(start_time, end_time):
"""Get ellapsed time in minutes and seconds.
Args:
start_time (float): strarting time
end_time (float): ending time
Returns:
elapsed_mins (float): elapsed time in minutes
elapsed_secs (float): elapsed time in seconds.
"""
elapsed_... |
def auto_converter(s):
"""automaticaly convert string to the int or float"""
for fn in int, float:
try:
return fn(s)
except ValueError:
pass
return s |
def parse_accept_language(accept_header):
"""
Taken from:
https://siongui.github.io/2012/10/11/python-parse-accept-language-in-http-request-header/
"""
languages = accept_header.split(",")
locale_q_pairs = []
for language in languages:
if language.split(";")[0] == language:
... |
def color(r, g, b):
"""Convert an RGB triplet of 0-255 values to a 24 bit representation."""
if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
raise ValueError('Color values must be 0 to 255.')
return (r << 16) | (g << 8) | b |
def func_extract_all_version_ids(project_version_mapping):
"""
:param project_version_mapping:
:return: version id list
"""
ids = []
for tmp in project_version_mapping.values():
ids.extend([_.id for _ in tmp])
return ids |
def EnumCrossRefLabel(enum_name):
"""Enum cross reference label."""
return 'envoy_api_enum_%s' % enum_name |
def codacy_result(hit, path):
"""Convert a hit to the Codacy result format
:param hit : a cfn-lint hit in json format
:param path: the path of the file where the hit occured
:return : dictionary conforming to the Codacy format
"""
return dict(filename=path,
message=hit["Message... |
def accuracy(results):
"""
Evaluate the accuracy of results, considering victories and defeats.
Args:
results: List of 2 elements representing the number of victories and defeats
Returns:
results accuracy
"""
return results[1] / (results[0] + results[1]) * 100 |
def get_reviewer_type(level):
"""
Creates the type of reviewer based on the level
returns: type string
"""
if level == 'lvl1' or level == 'lvl2':
return 'contractor'
else:
return 'federal employee' |
def values_in_multilevel_dct(dct, key1, key2, fill_val=None):
""" Obtain a dictionary value where
dct[key1][key2]
"""
dct2 = dct.get(key1, None)
if dct2 is not None:
val = dct2.get(key2, fill_val)
else:
val = fill_val
return val |
def multi_find(input_string, substring, start, end):
"""
Describe your function
:param :
:return:
:raises:
"""
result = ""
return result |
def snapshots_to_send(source_snaps, dest_snaps):
"""return pair of snapshots"""
if len(source_snaps) == 0:
raise AssertionError("No snapshots exist locally!")
if len(dest_snaps) == 0:
# nothing on the remote side, send everything
return None, source_snaps[-1]
last_remote = dest_s... |
def produce_tel_list(tel_config):
"""Convert the list of telescopes into a string for FITS header"""
tel_list = "".join("T" + str(tel) + "," for tel in tel_config["TelType"])
return tel_list[:-1] |
def strictly_increasing(L):
"""https://stackoverflow.com/a/4983359"""
return all(x<=y for x, y in zip(L, L[1:])) |
def normalize_interval(interval: int) -> int:
"""Return a normalized interval.
Normalized intervals:
1: Monthly (every month)
3: Quarterly (every three months)
6: Biannual (two times a year)
12: Annual (once a year)
"""
if interval < 1 or interval > 12:
raise V... |
def _make_dense_feature_vector(instance, transformers):
"""Make dense feature vector with value as elements."""
if len(transformers) == 1:
# The feature has only one source column.
transformer = transformers[0]
return transformer.get_value_and_transform(instance)
else:
feature_vector = []
for ... |
def clientlogin(token):
"""
Authorization: header to pass to self.client.{get,post}() calls::
self.client.post(url, data, **clientlogin(token))
"""
return {'HTTP_AUTHORIZATION': 'GoogleLogin auth={0}'.format(token)} |
def compute_distance(point1, point2):
"""
Computes distance between 2 points in a 2D space
:param point1:
:param point2:
:return: distance
"""
import math
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.