content stringlengths 42 6.51k |
|---|
def _create_path(directory, filename):
"""
Returns the full path for the given directory and filename.
"""
return f'{directory}/{filename}' |
def get_only_updated_values(instance, data):
"""
"""
new_data = dict()
for key, value in data.items():
current_value = instance.__getattribute__(key)
if value != current_value:
new_data[key] = value
return new_data |
def check_data(data):
"""
Check the *data* argument and make sure it's a tuple.
If the data is a single array, return it as a tuple with a single element.
This is the default format accepted and used by all gridders and processing
functions.
Examples
--------
>>> check_data([1, 2, 3])... |
def recall(TP, FN):
"""Sensitivity, hit rate, recall, or true positive rate"""
return (TP) / (TP + FN) |
def swap_column(content, col_index, col_info=[]):
"""
Swap column position into the table
Arguments:
- the table content, a list of list of strings:
- First dimension: the columns
- Second dimensions: the column's content
- cursor index for col
- optional i... |
def custom_dict_chunking(basedict, field, how_many):
"""
splits a dict value based on comma x amount of times
:param basedict: a dict with keys and messy values
:param field: what key to split in the dict
:param how_many: how many fields should remain after splitting
:return: clean dict (hopefu... |
def modulus(intf, ints):
"""
overpython.modulus(intf, ints)
Calculate the modulus of intf and ints. Raises ValueError if intf/ints is a string.
"""
try:
return float(intf) % float(ints)
except ValueError:
raise ValueError("%s/%s is not a number" % (intf, ints)) |
def orfs(dna,frame=0) :
"""
This function outputs a list of all ORFs found in string 'dna', using
triplet boundaries defined by frame position 'frame'
dna is the dna sequence to be analysed
frame is the offset (0,1 or 2) from start of the sequence to scan triplets
"""
orfs=[]
orf=''
... |
def isUnmarked(s):
"""If string s is unmarked returns True otherwise False.
"""
if len(s) > 0: return s[0] != '*'
else: return False |
def fibonacci(n):
"""
assumes n an int != 0
returns Fibonacci of n
"""
assert type(n) == int and n >= 0
if n == 0 or n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def split_line_num(line):
"""Split each line into line number and remaining line text
Args:
line (str): Text of each line to split
Returns:
tuple consisting of:
line number (int): Line number split from the beginning of line
remaining text (str): Text for remainder ... |
def pv_f(fv,r,n):
"""Objective: estimate present value
fv: fture value
r : discount period rate
n : number of periods
formula : fv/(1+r)**n
e.g.,
>>>pv_f(100,0.1,1)
90.9090909090909
>>>pv_f(r=0.1,fv=100,n=1)
... |
def decompress(x, slen, n):
"""
Take as input an encoding x, a bytelength slen and a length n, and
return a list of integers v of length n such that x encode v.
If such a list does not exist, the encoding is invalid and we output False.
"""
if (len(x) > slen):
print("Too long")
r... |
def _is_acyclic(edges: set):
"""
Use the number of nodes (NN) and the number of edges (NE) to determine
whether an undirected graph has a ring:
NE >= NN: has a ring
NE < NN: does not have a ring
Args:
edges: a set of Edge.
"""
NE = len(edges)
nodes = set()
for ... |
def parse_boundary(text):
"""Parse a string which represents the boundary of a value.
:param str text: the input string.
:return tuple: (lower boundary, upper boundary).
Examples:
parse_boundary("1, 2") == (1, 2)
"""
msg = "Input lower and upper boundaries separated by comma."
try:
... |
def assert_repr_reproduces(object_):
""" The second assertion assumes that __eq__ checks actual equality. In fact - it skips docstring. """
assert repr(eval(repr(object_))) == repr(object_)
assert eval(repr(object_)) == object_
return True |
def cur_mkt_score(ds, fs):
"""
Given a bunch of participants' open-interests and fees,
calculate the total current market score.
"""
total = 0
for d, f in zip(ds, fs):
total += (d**.3) * (f**.7)
return total |
def get_word2vector(wordsense, word2vecDic = dict()):
"""
:param wordsense:
:param word2vecDic:
:return:
"""
wd = wordsense.split('.')[0]
if wd in word2vecDic:
return word2vecDic[wd]
elif wordsense.split('.')[0] in word2vecDic:
return word2vecDic[wordsense.split('.')[0]] |
def difference_of(lhs, rhs):
"""
Computes the difference of two posting lists, that is, the elements
in the first list which are not elements in the second list.
"""
i = 0
j = 0
answer = []
while (i < len(lhs)):
if (j == len(rhs) or lhs[i] < rhs[j]):
answer.append(lh... |
def fermat_test(n):
"""Statistically test the primality of a number using the Fermat
algorithm.
"""
return (2**(n - 1) % n) == 1 |
def dimensions(data, array=False):
"""Takes in a string map and returns a 2D list map and map dimensions"""
if not array:
data = [[col for col in row] for row in data.split('\n')]
height = len(data)
width = max(len(col) for col in data)
return data, height, width |
def binary_search_recursive(arr, val, start, end):
"""searches arr for val between and including the indices start and end.
Parameters:
arr (array): array to search.
val (type used in array): value to search for in arr.
start (int): start index to search for val in arr.
end (int... |
def convert_to_float(string):
"""Convert a string to a float, if possible
"""
return float(string) if string else 0.0 |
def _check_weights(weights):
"""Check to make sure weights are valid"""
if weights not in (None, "uniform", "distance") and not callable(weights):
raise ValueError(
"weights not recognized: should be 'uniform', "
"'distance', or a callable function"
)
return weights |
def getinfo(segment, spec):
""" Method to get basic information about a spectral line that was only
detected by segment detection. Calculates the peak intensity, the
sigma of the peak, and the very rough FWHM of the line.
Parameters
----------
segment : list
List... |
def remove_dir_from_path(path: str, directory: str):
"""Remove a directory form a string representing a path
Args:
path: String resembling path
directory: String resembling directory to be removed from path
Returns:
String resembling input path with directory removed
"""
re... |
def getSymbols(equation):
"""Return a set of symbols present in the equation"""
stopchars=['(',')','*','/','+','-',',']
symbols=set()
pos=0
symbol=""
for i, c in enumerate(equation,1):
if c in stopchars:
pos=i
if(len(symbol)!=0):
if not all(i.isdig... |
def runge_kutta(y, x, dx, f):
""" y is the initial value for y
x is the initial value for x
dx is the time step in x
f is derivative of function y(t)
"""
k1 = dx * f(y, x)
k2 = dx * f(y + 0.5 * k1, x + 0.5 * dx)
k3 = dx * f(y + 0.5 * k2, x + 0.5 * dx)
k4 = dx * f... |
def as_valid_fraction(x):
"""Ensure that x is between 0 and 1."""
if x < 0.:
x = 0.
elif x > 1.:
x = 1.
return x |
def _find_minimum_alignment(offset: int, base_alignment: int, prev_end: int) -> int:
"""
Returns the minimum alignment that must be set for a field with
``base_alignment`` (the one inherent to the type),
so that the compiler positioned it at ``offset`` given that the previous field
ends at the posit... |
def magnitude(vector_1, vector_2):
""" This just-in-time compiled CUDA kernel is a device
function for calculating the distance between vectors.
"""
total = 0
for i in range(0, 3):
total += (vector_1[i] - vector_2[i]) ** 2
return total ** 0.5 |
def is_function(func_var):
"""
Check if a variable is a callable function object.
"""
import inspect
import types
if not func_var:
return False
can_call = callable(func_var)
chk_type = isinstance(func_var, (
types.FunctionType, types.BuiltinFunctionType,
types.Met... |
def convert_masks(seq):
"""Converts # masking to the [MASK] symbol used by BERT."""
seq = list(seq)
for i, c in enumerate(seq):
if c == "#":
seq[i] = "[MASK]"
return "".join(seq) |
def kernel_primitive_zhao(x, s0=0.08333, theta=0.242):
"""
Calculates the primitive of the Zhao kernel for given values.
:param x: point to evaluate
:param s0: initial reaction time
:param theta: empirically determined constant
:return: primitive evaluated at x
"""
c0 = 1.0 / s0 / (1 - ... |
def naka_rushton_allow_decreasing(c, a, b, c50, n):
"""
Naka-Rushton equation for modeling contrast-response functions. Taken from Dan to allow for
decreasing contrast responses (eg. VIP cells). If bounded, returns the same as naka_rushton. (?)
Where:
c = contrast
a = Rmax (max f... |
def weighted_precision(relationships, run_rules, run_confidences, threshold=0.0, allow_reverse=False):
"""
From a list of rules and confidences, calculates the proportion of those rules that match relationships injected into the data, weighted by confidence.
"""
wrong_relationship_weight = 0
total_r... |
def split_string0(buf):
"""split a list of zero-terminated strings into python not-zero-terminated bytes"""
if isinstance(buf, bytearray):
buf = bytes(buf) # use a bytes object, so we return a list of bytes objects
return buf.split(b'\0')[:-1] |
def calculate_appointments(new_set, old_set):
"""
Calculate different appointment types.
Used for making useful distinctions in the email message.
new_set will be the fresh set of all available appointments at a given interval
old_set will the previous appointments variable getting passed i... |
def numtomaxn2(n):
"""This function rearranges the digits of a number to
its maximum value possible
"""
if type(n) is not int:
raise TypeError("Input an integer only")
digits = list(str(n))
digits.sort(reverse=True)
return int(''.join(digits)) |
def extract_data_from_str_lst(str_lst, tag, num_args=1):
"""
General purpose routine to extract any static from a log (text) file
Args:
file_name (str): file name or path to the file, can either be absolute or relative
tag (str): string at the beginning of the line
num_args (int): n... |
def keep_numeric(s: str) -> str:
"""
Keeps only numeric characters in a string
------
PARAMS
------
1. 's' -> input string
"""
return "".join(c for c in list(s) if c.isnumeric()) |
def fast_sum_ternary(J, s):
"""Helper function for calculating energy in calc_e(). Iterates couplings J."""
assert len(J)==(len(s)*(len(s)-1)//2)
e = 0
k = 0
for i in range(len(s)-1):
for j in range(i+1,len(s)):
if s[i]==s[j]:
e += J[k]
k += 1
ret... |
def wheel(pos):
"""
Helper to create a colorwheel.
:param pos: int 0-255 of color value to return
:return: tuple of RGB values
"""
# Input a value 0 to 255 to get a color value.
# The colours are a transition r - g - b - back to r.
if pos < 0 or pos > 255:
return 0, 0, 0
if ... |
def GetDimensions(line):
"""
Parse and extract X, Y and Z dimensions from string
Parameters
----------
line: string
Line containing x, y, z dimensions
Returns
-------
(nx,ny,nz): (int,int,int)
The dimensions on x, y, and z coordinate respectively
... |
def _conditional_links(assembled_specs, app_name):
""" Given the assembled specs and app_name, this function will return all apps and services specified in
'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that
some other part of the system has declared them as... |
def atom_dict_to_atom_dict(d, aniso_dict):
"""Turns an .mmcif atom dictionary into an atomium atom data dictionary.
:param dict d: the .mmcif atom dictionary.
:param dict d: the mapping of atom IDs to anisotropy.
:rtype: ``dict``"""
charge = "pdbx_formal_charge"
atom = {
"x": d["Cartn_x"]... |
def _ragged_eof(exc):
"""Return True if the OpenSSL.SSL.SysCallError is a ragged EOF."""
return exc.args == (-1, 'Unexpected EOF') |
def checksum16(payload):
"""
Calculates checksum of packet.
:param payload: Bytearray, data to which the checksum is going
to be applied.
:return: Int, checksum result given as a number.
"""
chk_32b = 0 # accumulates short integers to calculate checksum
j = 1 # iterates through p... |
def full_path(csv):
"""Path to the csv_files. Used mainly for raw data."""
# Make sure we have the file ending
if csv[-4:] != '.csv':
csv = csv + '.csv'
return f'csv_files\\{csv}' |
def calculate_accuracy(test_tags, model_tags):
""" Function to calculate the accuracy of the Viterbi algorithm by comparing the output of the POS tagger to the actual tags
provided in the test set. """
num_correct = 0
total = 0
for test_taglist, model_taglist in zip(test_tags, model_tags):
... |
def map_range_constrained(x, in_min, in_max, out_min, out_max):
"""Map value from one range to another - constrain input range."""
if x < in_min:
x = in_min
elif x > in_max:
x = in_max
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def mock_run_applescript(script):
"""Don't actually run any applescript in the unit tests, ya dingbat.
This function should return whatever type of object
dialogs._run_applescript returns.
Returns:
tuple
"""
return (1, "", "") |
def greet(person):
"""
Return a greeting, given a person.
Args:
person (str): The person's name.
Returns:
str. The greeting.
Example:
>>> greet('Matt')
Hello Matt!
"""
return "Hello {}!".format(person) |
def count_set_bits(n):
""" Returns the number of set bits in the input. """
count = 0
while n != 0:
last_bit = n & 1
if last_bit == 1:
count += 1
n = n >> 1
return count |
def is_libris_edition_id(identifier):
"""
Check if identifier is old-format Libris ID.
@param identifier: ID to check
@type identifier: string
"""
if len(identifier) <= 9 and identifier.isdigit():
return True
return False |
def InStrRev(text, subtext, start=None, compare=None):
"""Return the location of one string in another starting from the end"""
assert compare is None, "Compare modes not allowed for InStrRev"
if start is None:
start = len(text)
if subtext == "":
return len(text)
elif start > len(tex... |
def parseName(lines):
"""
Args:
lines: all information on all identified molecular lines. nested list
Returns:
list of names of identified elements. Str list
"""
result = []
for line in lines:
name = line["name"]
result.append(name)
return result |
def listify_dict(dict_):
"""
turn each element that is not a list into a one-element list
"""
if not isinstance(dict_, dict):
return dict_
def listify_sub(key):
"""
actual worker
"""
value = dict_[key]
if isinstance(value, dict):
return [l... |
def is_crack(x, y):
"""Determine whether a pair of particles define the crack."""
output = 0
crack_length = 0.3
p1 = x
p2 = y
if x[0] > y[0]:
p2 = x
p1 = y
# 1e-6 makes it fall one side of central line of particles
if p1[0] < 0.5 + 1e-6 and p2[0] > 0.5 + 1e-6:
# d... |
def get_product_linear_fair(sets, bound):
""" Return the product of the input sets (1-D combinatorial) in
breadth-first order.
@param sets: Input sets
@type sets: List
@param bound: Max number of the product
@type bound: Int
@return: Product (partial) of the input sets
@rtype: List
... |
def mod_inverse(X, MOD):
"""
return X^-1 mod MOD
"""
return pow(X, MOD - 2, MOD) |
def smartsplit(t, s, e):
"""
smartsplit(text, start_position, end_position)
Splits a string into parts according to the number of characters.
If there is a space between the start and end positions, split before a space, the word will not end in the middle.
If there are no spaces in the specified range, divide as ... |
def ensure_evidence(badge_data: dict) -> dict:
"""Given badge_data, ensure 'evidence' key exists with list value"""
if 'evidence' not in badge_data:
badge_data['evidence'] = [{}]
return badge_data |
def fitness_function(items, m):
"""Return sum of cost for child if weight < m otherwise return 0."""
cost = 0
weight = 0
for key, is_selected in items.items():
if is_selected:
weight += key[1]
cost += key[0]
res = cost if weight <= m else 0
return res |
def cloudfront_origin_request_query_string_behavior(query_string_behavior):
"""
Property: OriginRequestQueryStringsConfig.QueryStringBehavior
"""
valid_values = ["none", "whitelist", "all"]
if query_string_behavior not in valid_values:
raise ValueError(
'QueryStringBehavior must ... |
def get_bit(value, n):
"""
:param value:
:param n:
:return:
"""
if value & (1 << n):
return 1
else:
return 0 |
def remove_or_ingredients(string: str) -> str:
"""Removes any 'or' ingredients.
Example:
>>> 1/2 small eggplant or a few mushrooms or half a small zucchini or half a pepper
1/2 small eggplant
"""
or_index = string.find(" or ")
if or_index != -1:
return string[:or_index]
return s... |
def topleft2corner(topleft):
""" convert (x, y, w, h) to (x1, y1, x2, y2)
Args:
center: np.array (4 * N)
Return:
np.array (4 * N)
"""
x, y, w, h = topleft[0], topleft[1], topleft[2], topleft[3]
x1 = x
y1 = y
x2 = x + w
y2 = y + h
return x1, y1, x2, y2 |
def text_to_markdownv2(text: str) -> str:
"""Helper function to convert plaintext into MarkdownV2-friendly plaintext.
This method is based on the fastest method available in:
https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string
:param text: The text to conver... |
def isPrime(n):
"""Returns True if n is prime."""
if n == 2:return True
if n == 3:return True
if n % 2 == 0:return False
if n % 3 == 0:return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True |
def convert_lx_to_qx(lx_list: list):
""" Converts a list of lx values to a qx list. """
q_values = []
for i, l in enumerate(lx_list[:-1]):
q_values.append(1 - lx_list[i + 1] / l)
return q_values |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = [list(map(int, ln.split(" "))) for ln in lines]
return res |
def int2str(val, max_dec=1024):
"""Make string from int. Hexademical representaion will be used if input value greater that 'max_dec'."""
if val > max_dec:
return "0x%x" % val
else:
return "%d" % val |
def decreasing_strict(args):
"""
Ensure that the values in args are strict decreasing.
"""
return [args[i-1] >= args[i] for i in range(1,len(args))] |
def normalize_wiki_text(text):
"""
Normalizes a text such as a wikipedia title.
@param text text to normalize
@return normalized text
"""
return text.replace("_", " ").replace("''", '"') |
def solve(string):
"""
Capitalizing function
"""
list_strings = string.rstrip().split(" ")
result = ""
for item in list_strings:
if item[0].isalpha():
item = item.title()
result += item + " "
return result.strip() |
def next_permutation(a):
"""Generate the lexicographically next permutation inplace.
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
Return false if there is no next permutation.
"""
# Find the largest index i such that a[i] < a[i + 1]. If no such
# index exists, the... |
def is_digit(s):
"""
Return True if given str is a digit or a dot(in float),
which means it is in `0,1,2,3,4,5,6,7,8,9,.`, False otherwise.
@param
---
`s` A symbol in string
"""
return s in "1234567890." |
def guess_platform(product_id):
"""Guess platform of a product according to its identifier."""
if len(product_id) == 40 and product_id.startswith('L'):
return 'Landsat'
if product_id.startswith('ASA'):
return 'Envisat'
if product_id.startswith('SAR'):
return 'ERS'
if product_... |
def scorefun(x, threshold=70):
"""
Score function used by `finalgrade`
"""
if x['total'] >= threshold:
return 100
else:
return x['total'] |
def moveTime(time, start):
"""
Move the given time to the given start time.
Example:
print moveTime((15, 35), 5)
# 5, 20
:type time: (int, int)
:type start: int
:rtype: (int, int)
"""
srcStartTime, srcEndTime = time
duration = srcEndTime - srcStartTime
if start... |
def implyGate(argumentValues):
"""
Method that evaluates the IMPLY gate
Note that this gate requires a specific definition of the two inputs. This definition is specifed in the order of the events provided in the input file
As an example, BE1->BE2 is translated as:
<define-gate name="TOP">
... |
def plur(word, n, plural=lambda n: n != 1,
convert=lambda w, p: w + 's' if p else w):
"""
Pluralize word based on number of items. This function provides rudimentary
pluralization support. It is quite flexible, but not a replacement for
functions like ``ngettext``.
This function takes two ... |
def is_valid_payload(payload):
"""Validates search query size"""
if (
len(payload["cards"]) < 1
or len(payload["cards"]) > 15
or any(not card.strip() or len(card) < 3 for card in payload["cards"])
):
return False
return True |
def get_serialized_obj_from_param(page, param):
"""
Get content of a param that contains a java serialized object (base64 gziped or only base64 of raw)
:param page: The page source code for search in it
:param param: The param that will be searched
:return: Param content with java serialized object ... |
def find_f_index(x, col):
"""find feature index giving matrix index"""
return x[0] * col + x[1] + 1 |
def __assign_if_set(old_val, json, key):
"""
Helper method for returning the value of a dictionary entry if it exists,
and returning a default value if not
:param old_val: The default to return if key is not found in json.
Typically the current assignment of the variable this
... |
def reorder_acq_dict(acq_dict):
""" Re-order the dictionary of files associated with an acquisition to a format
that is better suited for multi-raft outputs.
"""
d_out = {}
for raft, v in acq_dict.items():
for sensor, vv in v.items():
for image_type, fits_file in vv.items():
... |
def get_fpn_config(base_reduction=8):
"""BiFPN config with sum."""
p = {
'nodes': [
{'reduction': base_reduction << 3, 'inputs_offsets': [3, 4]},
{'reduction': base_reduction << 2, 'inputs_offsets': [2, 5]},
{'reduction': base_reduction << 1, 'inputs_offsets': [1, 6]},
{'reduction': base_reduction, 'inp... |
def process_wav(wav_rxfilename, process):
"""Return preprocessed wav_rxfilename.
Args:
wav_rxfilename: input
process: command which can be connected via pipe,
use stdin and stdout
Returns:
wav_rxfilename: output piped command
"""
if wav_rxfilename.endswith("|... |
def stdr_val(val_freqv, mean, std):
"""Make data zero mean and with unit variance with given mean and standard deviation."""
return (val_freqv - mean) / std |
def pack_address(value, *, is_reg=False, is_deref=False):
"""Pack an address into an integer."""
return value | is_reg << 15 | is_deref << 14 |
def get_string_event_attribute_succession_rep(event1, event2, event_attribute):
"""
Get a representation of the feature name associated to a string event attribute value
Parameters
------------
event1
First event of the succession
event2
Second event of the succession
event_... |
def map_recommendations(recommendations,
inv_user_index,
inv_doc_index,
mode='usr2doc'):
"""
Map internal IDs to real IDs. Supports three modes depending on the
recommendations shape.
Args:
recommendations: A list of tuples to be mapped fr... |
def get_fil_int(col) -> str:
"""
Integer based filter conditions
:param col:
:return:
"""
return """
if %s is not None:
data = data[data["%s"] == int(%s)]
""" % (col, col, col) |
def argdef(*args):
"""Return the first non-None value from a list of arguments.
Parameters
----------
value0
First potential value. If None, try value 1
value1
Second potential value. If None, try value 2
...
valueN
Last potential value
Returns
-------
v... |
def scope_vars(var_list, scope):
"""
Args:
var_list: list of `tf.Variable`s. Contains all variables that should be searched
scope: str. Scope of the variables that should be selected
"""
return [v for v in var_list if scope in v.name] |
def interseccion(m1,b1,m2,b2):
"""Da la interseccion entre dos rectas"""
if m1 != m2:
return False
x = (b2-b1) / (m1 - m2)
y = m1* x + b1
return (x,y) |
def get_diagnosis(case):
"""Returns site and diagnosis."""
site = 'unknown'
diagnosis = 'unknown'
if 'diagnoses' in case:
for d in case['diagnoses']:
_site = d.get('site', None)
if _site:
site = _site
_diagnosis = d.get('diagnosis', None)
... |
def erb_bandwidth(fc):
"""Bandwitdh of an Equivalent Rectangular Bandwidth (ERB).
Parameters
----------
fc : ndarray
Center frequency, or center frequencies, of the filter.
Returns
-------
ndarray or float
Equivalent rectangular bandwidth of the filter(s).
"""
# In ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.