content stringlengths 42 6.51k |
|---|
def myfloat(value, prec=1):
""" round and return float """
return round(float(value), prec) |
def rsquared_adj(r, nobs, df_res, has_constant=True):
"""
Compute the adjusted R^2, coefficient of determination.
Args:
r (float): rsquared value
nobs (int): number of observations the model was fit on
df_res (int): degrees of freedom of the residuals (nobs - number of model params... |
def path_cassette_dirname(vcr_path, cassettes_dirname="vcr_cassettes"):
"""Custom vcr path transformer to nest the cassette under a directory
/foo/cassette.yaml -> /foo/<cassettes_dirname>/cassette.yaml
"""
paths = vcr_path.split("/")
filename = paths.pop()
vcr_path = "/".join(paths + [cassettes... |
def _check_mod_11_2(numeric_string: str) -> bool:
"""
Validate numeric_string for its MOD-11-2 checksum.
Any "-" in the numeric_string are ignored.
The last digit of numeric_string is assumed to be the checksum, 0-9 or X.
See ISO/IEC 7064:2003 and
https://support.orcid.org/knowledgebase/artic... |
def sccs_from_string(s):
"""
Helper function to make it easy to write lists of scc vertices.
"""
return [
set(scc.split())
for scc in s.split(';')
] |
def _is_verbose(argv):
""" Doing this the low level way in order to init log as early as possible """
return '--verbose' in argv |
def get_page_url(skin_name, page_mappings, page_id):
""" Returns the page_url for the given page_id and skin_name """
fallback = '/'
if page_id is not None:
return page_mappings[page_id].get('path', '/')
return fallback |
def component_sequence_to_str(sequence):
"""
Transform a sequence of components (such as the one obtained from
get_sequence_cross_str) into an ASCII block which can be used either as
a cartoon or as an input for component_lattice(lattice = ...)
"""
component_txt_lattice = ""
M = len(sequence... |
def tricycle(tab,firstelt,sens):
"""
"""
result=[]
cptab=tab.copy()[::sens]
index=cptab.index(firstelt)
for i in range(index,len(cptab)):
result.append(cptab[i])
for i in range(0,index):
result.append(cptab[i])
return result |
def bfs(Adj, s):
"""
Adj: Adjacency list of graph
s: starting vertex
"""
parent = [None for v in Adj]
parent[s] = s
level = [[s]]
while 0 < len(level[-1]):
level.append([])
for u in level[-2]:
for v in Adj[u]:
if parent[v] is None:
... |
def instance_or_id_to_instance(obj, type_, name):
"""
Converts the given `obj` to it's `type_` representation.
Parameters
----------
obj : `int`, `str` or`type_` instance
The object to convert.
type_ : `type` or (`tuple` of `type`)
The type to convert.
name : `str`
... |
def contingency(set1,set2,all_genes):
"""Creates contingency table for gene enrichment
set1: Set of genes (e.g. regulon)
set2: Set of genes (e.g. i-modulon)
all_genes: Set of all genes
"""
tp = len(set1 & set2)
fp = len(set2 - set1)
tn = len(all_genes - set1 - set2)
... |
def get_exception_info(exception: BaseException) -> dict:
"""
Given an Exception object, retrieves some information about it: class and message.
:param exception: An exception which inherits from the BaseException class.
:return: A dict, containing two values:
- class: Th... |
def kTdiff(i, j, zs, kTs):
"""Compute the difference vector (kTi/zi - kTj/zj)."""
return kTs[i-1]/zs[i-1] - kTs[j-1]/zs[j-1] |
def recycle(words, func, times=2):
"""Run a set of words applied to a function repeatedly.
It will re-run with the last output as the new input.
`words` must be a list, and `func` must return a list.
:param words (list): The list of words.
:param func (function): A function to recycle.
... |
def distribute_tasks(n, memlim):
"""Util function for distribute tasks in matrix computation in order to
save memory or to parallelize computations."""
lims = []
inflim = 0
while True:
if inflim + memlim >= n:
lims.append([inflim, n])
break
else:
l... |
def file_from_path(path):
""" Extracts local filename from full path """
slashes = [pos for pos, char in enumerate(path) if char == '/']
return path[slashes[-1]+1:] |
def error(title, error_msg):
"""
Builds an error element. Provides a way to show errors or other
anomalous behavior in the web output.
Args:
title: The title to display
error_msg: A description of the error or other helpful message
Returns:
A dictionary with the metadata s... |
def set_navigator_overrides(platform: str) -> dict:
"""Overrides value returned by the javascript navigator object.
Parameters
----------
platform: str
The platform navigator.platform should return.
**Experimental**
"""
return {
"method": "Emulation.setNavigatorOverride... |
def binary_search(data, instructions, control):
""" day05 has a few binary search problems where the
search direction is a specific control character.
- `data` is a list to search
- `instructions` is a string with control characters
- `control` is two characters,
indicating which direction t... |
def _generic_assert_type(arg, arg_name, type_handle, type_name, type_casting_ok):
"""Assert if the arg is of type(s) type_handle or, if type_casting_ok is
True, assert if the arg can be cast to any of type_handle.
Parameters
----------
arg :
The variable being checked.
arg_name : stri... |
def DOT(L, X, Y):
"""
DOT: DOT product
p. 20
P: the dot product
"""
P = 0.0
if (L <= 0) :
return P
for I in range(L):
P += X[I] * Y[I]
return P |
def count_bits_set_to_one(n) -> int:
"""
x << y # Shift to left by y bits -- x * (2**y)
x >> y # Shift to right by y bits -- x // (2**y)
Args:
n: The I/P number
Returns:
Logic: And with 1 , and keep dividing n by powers of 2
"""
num_bits = 0
while n:
num_bits += n &... |
def class_name(cls):
"""Return a string representing the class"""
return cls.__name__.replace('.', '_') |
def joinargs(join_str, *args):
"""Joins given args (if valid) using join_str.
The result is stored in a context variable.
Example usage: {% join '/' str1 str2 str3 ... as var %}
"""
return join_str.join(["%s" % a for a in args if a]) |
def conv_transposed_output_dim(input_size,
kernel_size, stride=1, padding=0, dilation=1, **kwargs):
"""Calculate the output dimension of a transposed convolutional layer
"""
return (input_size-1)*stride - 2*padding + dilation*(kernel_size-1) + 1 |
def count_lines_with_blank_lines(file_to_read) -> int:
"""
Read the number of lines in the file
Args:
file_to_read : path + filename
Returns:
int: Returns the number of lines of which the file is composed (included blank lines)
"""
try:
lines = []
w... |
def cluster_prop_mentions(mention_list, score, argument_clusters, lexical_wt, argument_match_ratio):
"""
Cluster the predicate mentions in a greedy way: assign each predicate to the first
cluster with similarity score > 0.5. If no such cluster exists, start a new one.
:param mention_list: the mentions to clustert
... |
def deals_with_commodities(account_from, account_to = ''):
"""
Check if we are using commoditie-related text in
one of the account names.
"""
test1 = ':commodities'
test2 = ':cfd'
return ((test1 in account_from or test1 in account_to) or (test2 in account_from or test2 in account_t... |
def _remove_nulls(data, skip=None):
"""Remove all null/None/empty values from a dict or list, except those listed in skip."""
if isinstance(data, dict):
new_dict = {}
for key, val in data.items():
new_val = _remove_nulls(val, skip=skip)
if new_val is not None or (skip is ... |
def polynomial_selector(rate, constraint_length):
"""Returns generator polynomials for given code parameters. The
polynomials are chosen from [Moon] which are tabulated by searching
for polynomials with best free distances for a given rate and
constraint length.
Input
-----
rate: float
... |
def chunkify(inData, startIndex):
"""
:param list inData: the list of individual answers, split by newline
:param startIndex: where to start parsing from
:return int, str: the index we ended at, and the generated chunk string
"""
outValue = ''
end = False
index = startIndex
while n... |
def is_valid_value(val):
""" Validates if the value passed is a valid value,
note: None is a valid value
Args:
val (any type): value to be tested
Returns:
bool: True if not None and bool(val) is True else False
"""
return val is not None and bool(val) |
def euler_phi(*primes):
"""
Calculate Euler Totient-function
Args:
*primes: Prime-factored modulo e.g. n = \prod_{p\in *primes} p
Return: \phi(n)
"""
res = 1
for x in list(set(primes)):
k = primes.count(x)
res *= x ** k - x ** (k - 1)
return res |
def get_state_of_BP_FF(folder):
"""
This function return 2 flag for BP and FF according to the folder name given
"""
# Get the label of the state of BP and FF
if 'BP_on' in folder:
BP = True
elif 'BP_off' in folder:
BP = False
else:
print("Your folder name d... |
def hide_ip_address(ip_address):
"""
Template filter: <hide_ip_address>
Hide last sections of IP address
ex) 65.3.12.4 -> 65.3.*.*
"""
if not ip_address : return ""
else :
ipa = ip_address.split(".")
return "%s.%s.*.*" % (ipa[0], ipa[1]) |
def _default_key_function(*args, **kwargs):
"""
Return a string key, based on a given args and kwargs
"""
key = "|".join(map(str, args))
if kwargs:
key += "|" + "|".join(map(str, sorted(kwargs.items())))
return key |
def ith_bit(x: int, i: int) -> int:
"""
Return the i-th bit of the input parameter.
LSB has index 0, MSB has the greatest index (31 for a word).
:param x: A number.
:param i: The bit index.
:return: The ith-bit of x.
"""
assert i >= 0 # Do not support negative indexes, ATM
return (... |
def mark_coverage(percentage):
"""Return a mark from A to F based on the passed tests percentage.
:param percentage: Percentage of passed unit tests.
:type percentage: float
:return: Mark from A to F.
:rtype: str
"""
mark_table = {
"A": (90, 101),
"B": (80, 90),
"C":... |
def stringformat(value, arg):
"""
Formats the variable according to the argument, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
See http://docs.python.org/lib/typesseq-strings.html for documentation
of Pyth... |
def limit_stop_loss(entry_price: float, stop_price: float, trade_type: str, max_allowed_risk_percentage: int) -> float:
"""
Limits the stop-loss price according to the max allowed risk percentage.
(How many percent you're OK with the price going against your position)
:param entry_price:
:param sto... |
def compute(values):
"""Collapse a vector potentially consisting of 0, 1, -1 and None to a single value.
If a 1 or -1 is found they should always default to those values
There should not be opposing values in the same vector or the ontology may
need to be checked.
"""
if all(v is None for v in v... |
def strip(s: str):
"""strips outer html tags"""
start = s.find(">") + 1
end = len(s) - s[::-1].find("<") - 1
return s[start:end] |
def is_weight(w):
"""Whether w is a weight."""
return type(w) == list and len(w) == 2 and w[0] == 'weight' |
def filter_input(input_string, match=None, unmatch=None):
"""Filter input_string on a per-line basis
:param input_string: the input string to be filtered
:param match: a string required in one line
:param unmatch: a string should not exist in one line
"""
ret = []
for line in input_string.s... |
def entry_return_summary(video_entry):
"""
Returns the basic video information, good for a summary
Parameters
----------
video_entry
The full dict entry of the video that was retrieved from the database
Returns
-------
dict
Dict of just the summary data
"""
yout... |
def get_interface_type(interface):
"""Gets the type of interface
Args:
interface (str): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
type of interface: ethernet, svi, loopback, management, portchannel,
or unknown
"""
if... |
def coalesce(value, default_value):
"""https://en.wikipedia.org/wiki/Null_coalescing_operator
Can't use 'or' cuz of the RuntimeError thrown by pytorch"""
try:
if value:
return value
except RuntimeError: # bool(torch.tensor) throws RuntimeError for lists with len > 1
return v... |
def replace_single_pcoll_token(sql: str, pcoll_name: str) -> str:
"""Replaces the pcoll_name used in the sql with 'PCOLLECTION'.
For sql query using only a single PCollection, the PCollection needs to be
referred to as 'PCOLLECTION' instead of its variable/tag name.
"""
words = sql.split()
token_locations ... |
def prioritize_logos(logos):
""" Because only one logo is asked this
function prioritizes fetched logos
"""
d = {}
for logo in logos:
if "small" in logo.lower():
d[logo] = 10
elif "footer" in logo.lower():
d[logo] = 9
elif "header" in logo.lower():
... |
def find_identifier(qualifiers):
"""Finds an identifier from a dictionary of feature qualifiers.
This function selects for the following fields in decreasing order:
protein_id, locus_tag, ID and Gene. This should cover most cases where CDS
features do not have protein ID's.
Args:
qualifier... |
def mem_rm_payload(mem_default_payload):
"""Provide a membership payload for removing a member."""
rm_payload = mem_default_payload
rm_payload["action"] = "removed"
return rm_payload |
def _leftmost_descendants(node):
"""
Returns the set of all nodes descended in some way through
left branches from this node.
"""
try:
treepos = node.treepositions()
except AttributeError:
return []
return [node[x] for x in treepos[1:] if all(y == 0 for y in x)] |
def calc_checksum(data):
"""This function does not want the checksum byte in the input data.
jeep chrysler canbus checksum from http://illmatics.com/Remote%20Car%20Hacking.pdf
"""
checksum = 0xFF
for curr in data[:-1]:
shift = 0x80
for i in range(0, 8):
bit_sum = curr & shift
temp_chk = c... |
def get_proc_attr(process, processor_name, attribute_name):
"""Given an AutoPkg recipe processor array, extract the value of a specified
processor's attribute.
Args:
process ([dict]): List of dictionaries representing an AutoPkg recipe
process.
processor_name (str): Name of the ... |
def split_files(files, split_train, split_test, use_val):
"""Splits the files along with the provided indices
Returns a dict with the number of images in each folder
"""
files_train = files[:split_train]
files_test = files[split_train:split_test] if use_val else files[split_train:]
li = [(files... |
def next_name(names):
""" Determine the next numeric string name based on a list
Args:
names (list): list of current names (string)
"""
curr_ints = []
for name in names:
try:
curr_ints.append(int(name))
except ValueError:
continue
if len(curr_ints) == 0:
return str(0)
ret... |
def linear_model_flipper_mass(
flipper_length, weight_flipper_length, intercept_body_mass
):
"""Linear model of the form y = a * x + b"""
body_mass = weight_flipper_length * flipper_length + intercept_body_mass
return body_mass |
def get_inner_scope(scope_str):
"""Takes a tensorflow scope string and finds the inner scope.
Inner scope is one layer more internal.
Args:
scope_str: Tensorflow variable scope string.
Returns:
Scope string with outer scope stripped off.
"""
idx = scope_str.find('/')
return scope_str[idx + 1:] |
def unpack_arg(v):
"""Helper function for local methods"""
if isinstance(v,tuple):
return v[0],v[1]
else:
return v,{} |
def iob_ranges(tags):
"""
IOB -> Ranges
"""
ranges = []
def check_if_closing_range():
if i == len(tags) - 1 or tags[i + 1].split('-')[0] == 'O':
ranges.append((begin, i, type))
for i, tag in enumerate(tags):
if tag.split('-')[0] == 'O':
pass
elif... |
def is_ontology_file(file: str) -> bool:
"""
Checks whether the given filename is one of the RACK ontology files.
"""
return (
file.startswith("RACK-Ontology/ontology/")
and file.endswith(".sadl")
# don't care about this one
and file != "RACK-Ontology/ontology/GeneratePro... |
def modification_position(molecule, modification_short, modification_ext):
"""
Extract a list of the positions for the modified nucleotides inside a given match
"""
standard_bases = ['A', 'G', 'U', 'C']
modification_positions, output_strings = [], []
for index, nt in enumerate(modification_shor... |
def isPalindrome(s: str) -> bool:
"""
Return True if all letters in s produce a palindrome, False otherwise.
"""
def _toChars(s):
s = s.lower()
return "".join(c for c in s if c in "abcdefghijklmnopqrstuvwyxyz")
def _isPal(s):
if len(s) <= 1:
return True
... |
def row2string(row, sep=', '):
"""Converts a one-dimensional numpy.ndarray, list or tuple to string
Args:
row: one-dimensional list, tuple, numpy.ndarray or similar
sep: string separator between elements
Returns:
string representation of a row
"""
return sep.join("{0}".form... |
def merge_dict(primary, secondary):
""" Merge secondary into primary (maximum depth = 2).
If a key exists in secondary, overwrite the value of the same key in primary with the value in secondary.
:param primary: dictionary
:param secondary: dictionary
:return: None
"""
for k, v in secondary.... |
def create_ghost_points(pt_38_str, pt_82_str, pt_39_str, pt_83_str, pt_32_str, pt_76_str, pt_33_str, pt_77_str, pt_40_str, pt_84_str, pt_41_str, pt_85_str, pt_34_str, pt_78_str, pt_35_str, pt_79_str, pt_42_str, pt_86_str, pt_43_str, pt_87_str, pt_36_str, pt_80_str, pt_37_str, pt_81_str):
"""Create point on top of... |
def wrap_index(idx, dim):
"""
Helper function that wraps index when greater than maximum dimension.
Args:
idx (int): Unwrapped index
dim (int): Maximum dimension
Returns:
idx (int): idx if idx < dim or idx - dim
"""
if idx < dim:
return idx
else:
ret... |
def majorityElementB(nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
candidate = None
for i in nums:
if count == 0:
candidate = i
count += (1 if i == candidate else -1)
return candidate |
def power(a, n: int):
"""Return `a` to the n-th power, uses exponentiation by squaring i.e square and multiply
"""
# Shortcuts are evaluated here to avoid code duplication
if a == 0:
if n > 0:
return 0 # 0^n = 0 for n > 0
if n == 0:
return 1 # a^0 = 1 (0^0 = 1 is a co... |
def str_to_class(class_name):
"""
Returns a class based on class name
"""
mod_str, cls_str = class_name.rsplit('.', 1)
mod = __import__(mod_str, globals(), locals(), [''])
cls = getattr(mod, cls_str)
return cls |
def prefer_shallow_depths(solutions, weight=0.1):
"""Dock solutions which have a higher maximum depth"""
# Smallest maximum depth across solutions
try:
min_max_depth = min(max(p.depth for p in s.assignment) for s in solutions)
max_max_depth = max(p.depth for s in solutions for p in s.assignm... |
def mirror_pair(pair_list):
"""
double the data, generate pair2_pair1 from pair1_pair2 :param pair_list:
:return:
"""
return pair_list + [[pair[1],pair[0]] for pair in pair_list] |
def is_namedtuple(obj):
"""Check if `obj` is a namedtuple."""
return isinstance(obj, tuple) and hasattr(obj, "_fields") |
def is_vulnerable(myversion,minversion,maxversion):
"""
is_vulnerable(tuple,tuple,tuple) -> boolean
function checks whether a given kernel version is in a certain range of vulnerable kernel versions
"""
if ((minversion <= myversion) and (maxversion >= myversion)):
return True
else... |
def move_up_left(t):
""" A method that takes coordinates of the bomb and
returns coordinates of neighbour which is located at
the left-hand side and above the bomb. It returns
None if there isn't such a neighbour """
x, y = t
if x == 0 or y == 0:
return None
else:
return (x ... |
def parse_seat_to_binary(seat):
"""
Take a seat identifier BFFFBBFRRR and determine it's binary
number
"""
replaces = {
'B' : '1',
'F' : '0',
'R' : '1',
'L' : '0',
}
out_str = seat
for old, new in replaces.ite... |
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 bou... |
def open_file(path):
"""
Open file and read the contents.
Args:
path (str): Path to file.
Returns:
str: File contents.
"""
try:
with open(path, 'r') as f:
leads = f.read()
return leads
except OSError:
print('Cannot open file') |
def vhdl_fixed_start(address):
"""
Generate the start of a line in the VHDL ROM.
:param address: address of the ROM line.
:return: a string containg the start of the ROM line.
"""
rom_start = '\t\t%3d => "' % address
return rom_start |
def extract_alignment_keys(elements):
"""extract key features of an element list used for alignmetn checking"""
x_left_vals = [c["bounds"][0] for c in elements]
x_mid_vals = [(c["bounds"][0] + c["bounds"][2] / 2) for c in elements]
x_right_vals = [c["bounds"][2] for c in elements]
y_top_vals = [c["bounds"][1] fo... |
def undersampled(semibmaj, semibmin):
"""
We want more than 2 pixels across the beam major and minor axes.
:param Semibmaj/semibmin: describe the beam size in pixels
:returns: True if beam is undersampled, False otherwise
"""
return semibmaj * 2 <= 1 or semibmin * 2 <= 1 |
def _get_unique(node_list, key, mode=None):
"""
Returns number or names of unique nodes in a list of dictionaries.
:param node_list: List of dictionaries returned by Neo4j transactions.
:param key: Key accessing specific node in dictionary.
:param mode: If 'num', the number of unique nodes is return... |
def safe_len(x):
"""
safely returns the length of an object without throwing an exception
if the object is a number
"""
try:
ret = len(x)
except TypeError:
ret = False
return ret |
def get_next_item(iterable):
"""Gets the next item of an iterable.
If the iterable is exhausted, returns None."""
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x |
def temperature(fraction):
""" Example of temperature dicreasing as the process goes on."""
return max(0.01, min(1, 1 - fraction)) |
def calculate_loan_to_value_ratio(loan_amount, home_value):
"""
Calculates the loan to value ratio.
Converts the loan amount and home value parameters to
int values and divides the loan amount by the home value
to produce the loan to value ratio.
Parameters:
loan_amount (float): The lo... |
def slim(txt):
"""
Replaces any instances of multiple spaces with a single space
"""
return ' '.join(txt.split()) |
def ce(actual, predicted):
"""
Computes the classification error.
This function computes the classification error between two lists
:param actual : int, float, list of numbers, numpy array
The ground truth value
:param predicted : same type as actual
The pr... |
def calc_result(numbers):
""" Calculate average of numbers """
return sum(numbers) / len(numbers) |
def find_var_in_list(local_name, var_list):
###############################################################################
"""Find a variable, <local_name>, in <var_list>.
local name is used because Fortran metadata variables do not have
real standard names.
Note: The search is case insensitive.
Re... |
def mag_to_fno(mag, infinite_fno, pupil_mag=1):
"""Compute the working f/# from the magnification and infinite f/#.
Parameters
----------
mag : `float` or `numpy.ndarray`
linear or lateral magnification
infinite_fno : `float`
f/# as defined by EFL/EPD
pupil_mag : `float`
... |
def policy_compare(sen_a, sen_b, voting_dict):
"""
Input: last names of sen_a and sen_b, and a voting dictionary mapping senator
names to lists representing their voting records.
Output: the dot-product (as a number) representing the degree of similarity
between two senators' voting p... |
def compute_scale_factor(height, size):
"""
Compute gallery conversion scale factor as a percentage.
"""
landscape = True
source_width = size[0]
source_height = size[1]
if source_width < source_height:
landscape = False
if landscape:
return height/source_height * 100
... |
def _returnTimeVals(t=None, trackerdict=None):
"""
input: timeControlParamsDict, trackerdict (optional)
return timelist (list) in MM_DD_HH format.
startday (string), endday (string) are timelist[0] and [-1]
If timeControlParamsDict is None, default to full year
"""
if t is None: # full ye... |
def convert_padding(padding, expected_length=4):
"""Converts Python padding to C++ padding for ops which take EXPLICIT padding.
Args:
padding: the `padding` argument for a Python op which supports EXPLICIT
padding.
expected_length: Expected number of entries in the padding list when
explicit pa... |
def usage_ratio(usage: float, limit: float) -> float:
"""
Calculate the usage ratio
"""
return 0.0 if limit <= 0 else usage/limit |
def prepare_input(input_str, from_item):
"""
A function for preparing input for validation against a graph.
Parameters:
input_str: A string containing node or group identifiers.
from_item: Start processing only after this item.
Returns:
A list of node identifiers.
"""
... |
def convert_bool_to_char(value=False):
"""Convert boolean to SIP2 char representation."""
return 'Y' if value else 'N' |
def clean_lesson_content(content):
""" Remove items such as new lines and multiple spaces. """
content = content.replace("\n", " ")
while " " in content:
content = content.replace(" ", " ")
return content.strip() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.