content stringlengths 42 6.51k |
|---|
def eng_to_i18n(string, mapping):
"""Convert English to i18n."""
i18n = None
for k, v in mapping.items():
if v == string:
i18n = k
break
return i18n |
def _escape_specification(specification):
# type: (str) -> str
"""
Escapes the interface string: replaces slashes '/' by '%2F'
:param specification: Specification name
:return: The escaped name
"""
return specification.replace("/", "%2F") |
def main1(nums, k):
""" Find compliment of each number in the remaining list.
Time: O(n^2)
Space: O(1)
"""
for i, num in enumerate(nums):
compliment = k - num
if compliment in nums[i + 1:]:
return True
return False |
def n(src):
"""
Normalize the link. Very basic implementation
:param src:
:return:
"""
if src.startswith('//'):
src = 'http:' + src
return src |
def _build_line(entry):
"""
Create a define statement in a single line.
Args:
- entry(Dictionary(String:String)): Dictionary containing a description
of the target define statement using the Keys: 'Module',
'Address/Value', 'Function', 'Submodule' (opt), 'Comment' (opt)
Retur... |
def decode_base64(data):
"""Decodes a base64 string to binary."""
import base64
data = data.replace("\n", "")
data = data.replace(" ", "")
data = base64.b64decode(data)
return data |
def char_contains(str1, str2):
"""
check whether str2 cotains all characters of str1
"""
if set(str1).issubset(set(str2)):
return True
return False |
def axial_dispersion_coeff(Dm, dp, ui):
"""
Estimate the axial dispersion coefficient using Edwards and Richardson
correlation.
.. math:: D_{ax} = 0.73 D_m + 0.5 d_p u_i
Parameters
----------
Dm : float
Molecular diffusion coefficient [m^2/s]
dp : float
Particle diamete... |
def is_command_yes(cmd: str):
"""Check if user agree with current command.
Args:
cmd (str): Command input value.
Returns:
bool: True if command value is match "yes" or "y" (case insensitive.).
"""
lower_cmd = cmd.lower()
return lower_cmd == "yes" or lower_cmd == "y" |
def vector_subtract(u, v):
"""returns the difference (vector) of vectors u and v"""
return (u[0]-v[0], u[1]-v[1], u[2]-v[2]) |
def dict_of_integrals_until(num):
"""
Question3:
print dict of integrals from 0 to 'num' containing pairs {num: num*num}
"""
return {i : i*i for i in range(1,num+1)} |
def optiWage(A,k,alpha):
"""Compute the optimal wage
Args:
A (float): technology level
k (float): capital level
alpha (float): Cobb Douglas parameter
Returns:
(float): optimal wage
"""
return A*(1-alpha)*k**alpha |
def parse_youtube_time(yt_time: str) -> str:
"""
Parse the Youtube time format to the hh:mm:ss format
params :
- yt_time: str = The youtube time string
return -> str = The youtube time formatted in a cooler format
"""
# Remove the PT at the start
yt_time = yt_time[2:len(yt_time)]
... |
def _transpose_list_of_lists(lol):
"""Transpose a list of equally-sized python lists.
Args:
lol: a list of lists
Returns:
a list of lists
"""
assert lol, "cannot pass the empty list"
return [list(x) for x in zip(*lol)] |
def is_float(value):
"""
Checks value if it can be converted to float.
Args:
value (string): value to check if can be converted to float
Returns:
bool: True if float, False if not
"""
try:
float(value)
return True
except ValueError:
return False |
def check_separation(values, distance_threshold):
"""Checks that the separation among the values is close enough about distance_threshold.
:param values: array of values to check, assumed to be sorted from low to high
:param distance_threshold: threshold
:returns: success
:rtype: bool
"""
... |
def _matches2str(matches):
"""
Get matches into a multi-line string
:param matches: matches to convert
:return: multi-line string containing matches
"""
output_text = ''
for match in matches:
output_text += f"{match[0]} - {match[1]}\n"
return output_text |
def rule_to_expression(filtering_rule):
"""
Single filtering rule to expression
:param filtering_rule:
:return: expression
"""
column = filtering_rule["column"]
filter_type = filtering_rule["type"]
filter_params = filtering_rule["value"]
if filter_type == "range":
sdt = "to_t... |
def move_player_backward(player_pos, current_move):
"""
move pos by current move in circular field from 1 to 10 backward
"""
player_pos = (player_pos - current_move) % 10
if player_pos == 0:
return 10
return player_pos |
def mean_(data):
"""Mean of the values"""
return sum(data) / len(data) |
def InducedSubgraph(V, G, adjacency_list_type=set):
"""
The subgraph consisting of all edges between pairs of vertices in V.
"""
return {x: adjacency_list_type(y for y in G[x] if y in V) for x in G if x in V} |
def make_video_spec_dict(video_specs):
"""
convert video_specs from list to dictionary, key is thee video name w/o extentions
"""
video_specs_dict = {}
for v_spec in video_specs:
video_specs_dict[''.join(v_spec['filename'].split('.')[:-1])] = v_spec
return video_specs_dict |
def rpmul(a,b):
"""Russian peasant multiplication.
Simple multiplication on shifters, taken from "Ten Little Algorithms" by
Jason Sachs.
Args:
a (int): the first variable,
b (int): the second vairable.
Returns:
x (int): result of multiplication a*b.
"""
result... |
def filter(p, xs):
"""Takes a predicate and a Filterable, and returns a new filterable of the
same type containing the members of the given filterable which satisfy the
given predicate. Filterable objects include plain objects or any object
that has a filter method such as Array.
Dispatches to the f... |
def foo_3(x, y, z):
""" test
>>> foo_3(1,2,3)
[1, 2, 3]
>>> foo_3(2,1,3)
[1, 2, 3]
>>> foo_3(3,1,2)
[1, 2, 3]
>>> foo_3(3,2,1)
[1, 2, 3]
"""
if x > y:
tmp=y
y=x
x=tmp
if y > z:
tmp=z
z=y
y=tmp
return [x, y, z] |
def find_integer(array, target):
"""
:params array: [[]]
:params target: int
:return bool
"""
if not array:
return False
for i in array:
if i[0] <= target <= i[len(i)-1]:
if target in i:
return True
else:
if i[0] > target:
... |
def code(doc: str) -> str:
"""Escape Markdown charters from inline code."""
doc = doc.replace('|', '|')
if '&' in doc:
return f"<code>{doc}</code>"
elif doc:
return f"`{doc}`"
else:
return " " |
def add_ap_record(aps, classes, record=None, mean=True):
"""
ap values in aps
and there must be the same length of classes
and same order
"""
if record is None:
record = {}
sum_ap = 0
for cid, c in enumerate(classes):
ap = aps[cid]
name_ap = 'ap_' + c.lower()
... |
def get_app_module_name_list(modules):
"""
Returns the list of module name from a Ghost App
>>> modules = [{
... "name" : "symfony2",
... "post_deploy" : "Y29tcG9zZXIgaW5zdGFsbCAtLW5vLWludGVyYWN0aW9u",
... "pre_deploy" : "ZXhpdCAx",
... "scope" : "code",
... "initialized"... |
def format_dword(i):
"""Format an integer to 32-bit hex."""
return '{0:#010x}'.format(i) |
def generate_sql_q1(sql_i1, tb1):
"""
sql = {'sel': 5, 'agg': 4, 'conds': [[3, 0, '59']]}
agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg']
cond_ops = ['=', '>', '<', 'OP']
Temporal as it can show only one-time conditioned case.
sql_query: real sql_query
sql_... |
def _extract_format(fmt):
"""
Returns:
a list of tuples: each tuple is a
ex: [('H', 6)]
"""
correspond_fmt = []
start = 0
for i, ch in enumerate(fmt):
if not ch.isdigit():
end = i
times = int(fmt[start:end]) if start != end else 1
corre... |
def get_bucket_name_from_path(path_input):
"""
>>> get_bucket_name_from_path('gs://my-bucket/path')
'my-bucket'
"""
path = str(path_input)
if not path.startswith('gs://'):
raise ValueError(f'path does not start with gs://: {path}')
return path[len('gs://') :].split('/', maxsplit=1... |
def diff_flair(left, right):
"""returns: (modifications, deletions)"""
left_users = frozenset(left)
right_users = frozenset(right)
common_users = left_users & right_users
added_users = right_users - left_users
removed_users = left_users - right_users
modifications = [(u, right[u][0], right[u... |
def extract_kwargs(kwargs_tuple):
""" Converts a tuple of kwarg tokens to a dictionary. Expects in format
(--key1, value1, --key2, value2)
Args:
kwargs_tuple (tuple(str)) tuple of list
"""
if len(kwargs_tuple) == 0:
return {}
assert kwargs_tuple[0][:2] == "--", f"No key for fi... |
def ABS(expression):
"""
Returns the absolute value of a number.
See https://docs.mongodb.com/manual/reference/operator/aggregation/abs/
for more details
:param expression: The number or field of number
:return: Aggregation operator
"""
return {'$abs': expression} |
def db_error_needs_new_session(driver, code):
"""some errors justify a new database connection. In that case return true"""
if code in ("1001", "57P01"):
return True
return False |
def dict_is_all_none(dict_item: dict) -> bool:
"""
Tests if all dictionary items are None.
:param dict_item: A dictionary object to be testes.
:return bool: True if all keys have None as value, False otherwise
"""
for _key, _value in dict_item.items():
if _value is not None:
... |
def positives(nums):
"""Positives:
Given a list of numbers, write a list comprehension that produces a list of only the positive numbers in that list.
>>> positives([-2, -1, 0, 1, 2])
[1, 2]
"""
lst = [a for a in nums if a > 0]
return lst
pass |
def _remove_trailing_nones(array):
""" Trim any trailing Nones from a list """
while array and array[-1] is None:
array.pop()
return array |
def _getLogHandlers(logToFile=True, logToStderr=True):
"""Get the appropriate list of log handlers.
:param bool logToFile: If ``True``, add a logfile handler.
:param bool logToStderr: If ``True``, add a stream handler to stderr.
:rtype: list
:returns: A list containing the appropriate log handler n... |
def sformat(text, args):
"""
sformat
"""
for key in args:
text = text.replace("{%s}" % key, "%s" % (args[key]))
return text |
def size_to_bytes(size):
"""
Returns a number of bytes if given a reasonably formatted string with the size
"""
# Assume input in bytes if we can convert directly to an int
try:
return int(size)
except Exception:
return -1
# Otherwise it must have non-numeric characters
s... |
def find(s, sub, i = 0, last=None):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
Slen = len(s) # cache this val... |
def build_increments(start, stop, increment):
""" Build a range of years from start to stop, given a specific increment
Args:
start (int): starting year
stop (int): ending year
increment (int): number of years in one time series
Returns:
year_increments (list): list of tupl... |
def stripquotes(s):
"""Replace explicit quotes in a string.
>>> from sympy.physics.quantum.qasm import stripquotes
>>> stripquotes("'S'") == 'S'
True
>>> stripquotes('"S"') == 'S'
True
>>> stripquotes('S') == 'S'
True
"""
s = s.replace('"', '') # Remove second set of quotes?
... |
def searchers_start_together(m: int, v):
"""Place all searchers are one vertex
:param m : number of searchers
:param v : integer or list"""
if isinstance(v, int):
my_v = v
else:
my_v = v[0]
v_searchers = []
for i in range(m):
v_searchers.append(my_v)
return v_s... |
def nfc_normalize(iri):
"""
Normalizes the given unicode string according to Unicode Normalization Form C (NFC)
so that it can be used as an IRI or IRI reference.
"""
from unicodedata import normalize
return normalize('NFC', iri) |
def constrain_rgb(r, g, b):
"""
If the requested RGB shade contains a negative weight for
one of the primaries, it lies outside the colour gamut
accessible from the given triple of primaries. Desaturate
it by adding white, equal quantities of R, G, and B, enough
to make RGB all positive. The f... |
def turn_weight_function_distance(v, u, e, pred_node):
"""
Weight function used in modified version of Dijkstra path algorithm.
Weight is calculated as the sum of edge length weight and turn length weight (turn length weight keyed by predecessor node)
This version of the function takes edge lengths keye... |
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None):
"""Generate a horizontal line.
Args:
lineLength (int): The length of the line or how many characters the line will have.
lineWidth (int, optional): The width of the line or how many lines of text the line will take spa... |
def type_getattr_construct(ls, **kwargs):
"""Utility to build a type_getattr_table entry. Used only at module
load time.
"""
map = dict.fromkeys(ls, True)
map.update(kwargs)
return map |
def computeRatio(indicator1, indicator2):
"""Computation of ratio of 2 inidcators.
Parameters:
-----------
indicator1 : float
indicator1 : float
Returns:
--------
Either None (division by zero)
Or the computed ratio (float)
"""
try:
ratio = indic... |
def arePermsEqualParity(perm0, perm1):
"""Check if 2 permutations are of equal parity.
Assume that both permutation lists are of equal length
and have the same elements. No need to check for these
conditions.
:param perm0: A list.
:param perm1: Another list with same elements.
:return: Tr... |
def name_value(name):
"""
Compute name value for a name
"""
return sum([ord(c) - ord('A') + 1 for c in name]) |
def convert_pos(pos):
"""
Method to convert part of speech from nltk form to WordNet form
"""
# dictionary of pos tags (keys are in nltk form, values are wordnet form)
pos_conversions = dict.fromkeys(['NN', 'NNS'], 'n')
pos_conversions.update(dict.fromkeys(['VB', 'VBD', 'VBN', 'VBP', 'VBZ'], 'v'))
pos_conversion... |
def _retrieve_yearly_data(yearly_data):
"""Auxiliary function to collect yearly data.
Returns list of lists in the form [mergedstatname, stat], where
mergedstatname - dictionary key joined with associated period.
"""
out = []
for t in yearly_data:
for key in t:
if key not in... |
def gcd(a, b):
"""Returns the greatest common divisor of a and b.
Should be implemented using recursion.
>>> gcd(34, 19)
1
>>> gcd(39, 91)
13
>>> gcd(20, 30)
10
>>> gcd(40, 40)
40
"""
# new strat: since Euclid's algorithm swaps the numbers' places for every call to gcd,... |
def data_corners(data, data_filter = None):
"""!
@brief Finds maximum and minimum corner in each dimension of the specified data.
@param[in] data (list): List of points that should be analysed.
@param[in] data_filter (list): List of indexes of the data that should be analysed,
... |
def line(x1, y1, x2, y2):
"""Returns a list of points in a line between the given points.
Uses the Bresenham line algorithm. More info at:
https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm"""
points = []
isSteep = abs(y2-y1) > abs(x2-x1)
if isSteep:
x1, y1 = y1, x1
x2, ... |
def _GenerateDeviceHVInfoStr(hvinfo):
"""Construct the -device option string for hvinfo dict
PV disk: virtio-blk-pci,id=disk-1234,bus=pci.0,addr=0x9
PV NIC: virtio-net-pci,id=nic-1234,bus=pci.0,addr=0x9
SG disk: scsi-generic,id=disk-1234,bus=scsi.0,channel=0,scsi-id=1,lun=0
@type hvinfo: dict
@param hvin... |
def hasNumbers(inputString):
"""
Returns True if the string contains a number, False otherwise
:param inputString: String to check for number
:return: Boolean: whether string contains a number
"""
return any(char.isdigit() for char in inputString) |
def replace_duplicate_words(word_list):
"""
input: list of words
output: new list where words that appear more than once in the input are replaced by 'word '
used due to react-autoselect UI of the app
"""
new_list = []
for word in word_list:
occurences = word_list.cou... |
def dict_or_list_2_tuple_2_str(inp):
"""
dict_or_list_2_tuple_2_str
Args:
inp: dict or list of 2-tuple
Returns:
formatted string
"""
if isinstance(inp, dict):
inp = sorted(list(inp.items()), key=lambda x: x[0])
else:
inp = sorted(inp, key=lambda x: x[0])
... |
def default_entry_point(name):
"""Generate a default entry point for package `name`."""
return "{name}.__main__:main".format(name=name) |
def upper_diag_self_prodx(list_):
"""
upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> fr... |
def _getfield(history, field):
"""
Return the last value in the trace, or None if there is no
last value or no trace.
"""
trace = getattr(history, field, [])
try:
return trace[0]
except IndexError:
return None |
def _get_single_wdr_with_qw_sel(asm_str):
"""returns a single register from string with quad word select and check proper formatting (e.g "w5.2")"""
if len(asm_str.split()) > 1:
raise SyntaxError('Unexpected separator in reg reference')
if not asm_str.lower().startswith('w'):
raise SyntaxErr... |
def text2idx(text, max_seq_length, word2idx):
"""
Converts a single text into a list of ids with mask.
This function consider annotaiton of z1, z2, z3 are provided
"""
input_ids = []
text_ = text.strip().split(" ")
if len(text_) > max_seq_length:
text_ = text_[0:max_seq_length]
... |
def digitsaverage(d):
"""Return the average of the digits until number is one digit.
input = integer
output = integer, single digit
ex. 246 = 4 i.e. avg of 2 and 4 is 3, average of 4 and 6 is 5
so after first iteration 246 => 35
avg of 3 and 5 is 4 so digitsAverage(246) returns 4
""... |
def _validate_window_size(k):
"""
Check if k is a positive integer
"""
if not isinstance(k, int):
raise TypeError(
"window_size must be integer type, got {}".format(type(k).__name__)
)
if k <= 0:
raise ValueError("window_size must be positive")
return k |
def no_bracketed(st):
"""
Remove bracketed substrings from a string -- used to convert to a
one letter sequence:
acgu[URA:VirtualPhosphate]acgu ==> acguacgu
"""
ret = ""
incl = True
for c in st:
if incl:
if c == '[': incl = False
else: ret += c
e... |
def temperature_rise(H, Eff, U):
"""
Func to provide temperature rise versus pump capacity.
TR (deg F) = H(1.0-E)/(778.0*U*E)
Where:
-TR is temp rise
-H is total head in ft.
-E efficiency as a decimal
-U specific heat ( BTU/lb/Deg F)
"""
TR = (H*(1.0-Eff))/(778.0*U*Eff)
prin... |
def is_in_pi(param_name, pi_exp):
"""
Parameters
----------
param_name Name of a particular physical parameter
pi_exp Pi expression
Returns True if the parameter is in pi_exp
-------
"""
_vars = pi_exp.split('*')
raw_vars = []
for _var in _vars:
raw_va... |
def max_sum(triangle_matrix):
"""Finds maximum sum of path from top of triangle down to bottom.
Input: Matrix of triangle e.g.
1
3 5
7 8 4
becomes [[1], [3, 5], [7, 8, 4]]
Uses memoization from the bottom layer up to work quickly
Output: maximum value
"""
max_depth = len(tria... |
def _nval(val):
"""convert value to byte array"""
if val < 0:
raise ValueError
buf = b''
while val >> 7:
m = val & 0xFF | 0x80
buf += m.to_bytes(1, 'big')
val >>= 7
buf += val.to_bytes(1, 'big')
return buf |
def align_cells(lines):
"""
Correct the problem of some cells not being aligned in successive columns, when belonging to the same fragment
sequence
"""
previous_line, output_lines = None, ['molecule,nres,mod,mod_ext,matches\n']
for line in lines:
output_nts = []
if previous_li... |
def cobs_encode(data):
"""
COBS-encode DATA.
"""
output = bytearray()
curr_block = bytearray()
for byte in data:
if byte:
curr_block.append(byte)
if len(curr_block) == 254:
output.append(1 + len(curr_block))
output.extend(curr_block... |
def get_next(currentHead, nextMove):
"""
return the coordinate of the head if our snake goes that way
"""
futureHead = currentHead.copy()
if nextMove == 'left':
futureHead['x'] = currentHead['x'] - 1
if nextMove == 'right':
futureHead['x'] = currentHead['x'] + 1
if nextMove =... |
def calculate(triangle):
"""Returns the maximum total from top to bottom by starting at the top
of the specified triangle and moving to adjacent numbers on the row below"""
def calculate_helper(row, col):
"""Returns the maximum path value of a specified cell in the triangle"""
if row == len... |
def cross_map(iter_mapper, iterable):
"""Maps each map in iter_mapper on each iterable"""
return [list(map(im, iterable)) for im in iter_mapper] |
def getmodestring_( I, callingRoutine ) :
"""For internal use only."""
if ( I in [ 0, 7, 9, 10, 11, 12, 13, 30, 32, 80, 89, 90, 91, 92, 941, 942, 951 ] ) :
s = "2"
elif ( I in [ 1, 21, 22, 81, 84, 952 ] ) :
s = "3"
elif ( I in [ 3, 4, 20 ] ) :
s = "4"
else :
raise Ex... |
def _normalize_percent_rgb(value):
"""
Normalize ``value`` for use in a percentage ``rgb()`` triplet, as
follows:
* If ``value`` is less than 0%, convert to 0%.
* If ``value`` is greater than 100%, convert to 100%.
Examples:
>>> _normalize_percent_rgb('0%')
'0%'
>>> _normalize_pe... |
def extend_matches(value, choices, direction):
"""
Extends the value by anything in choices the
1) ends in the same 2 digits that value begins with
2) has remaining digit(s) unique from those in value
"""
value_digits = set(value)
if direction == 'right':
first_two_match = [choice fo... |
def polynomiale_2(a: float, b: float, c: float, d: float, x: float) -> float:
"""Retourne la valeur de a*x^3 + b*x^2 + c*x + d
"""
return ((((a*x + b) * x) + c) * x) + d |
def TSKVsPartGetNumberOfSectors(tsk_vs_part):
"""Retrieves the number of sectors of a TSK volume system part object.
Args:
tsk_vs_part (pytsk3.TSK_VS_PART_INFO): TSK volume system part information.
Returns:
int: number of sectors or None.
"""
# Note that because pytsk3.TSK_VS_PART_INFO does not expl... |
def subset_to_str_list(subset_sol):
"""From a subset solution (e.g.: [[0,1],[0,0]]) returns a list with the rows string and the columns string (e.g.: ['0 1', '0 0']) or NO_SOL"""
return [' '.join([str(e) for e in subset_sol[0]]), \
' '.join([str(e) for e in subset_sol[1]])] |
def cut_strokes(strokes, n_points):
"""
Reduce a drawing to its n first points.
"""
result_strokes = []
current_n_points = 0
for xs, ys in strokes:
stroke_size = len(xs)
n_points_remaining = max(0, n_points - current_n_points)
result_strokes.append((xs[:n_points_remaini... |
def computescale(population):
"""
Computes appropriate scale to show locations with specific population
"""
if population == '': population = 0
population = int(population)
if population < 20000: return 15
if population < 40000: return 14.5
if population < 60000: return 14
if popul... |
def _starsToPercentage (numStars):
"""
Converts a given number of stars to its percentage
:param numStars: teh number of stars as an integer or float
:return: the percentage is the number is valid or None if it's not.
"""
if numStars == 0:
return 1
elif numStars == 1:
return... |
def find_stop(seq):
"""
:param seq: a translated amino acid sequence
:return: the position of the first stop codon (*) inside - if none, return length of whole sequence
"""
if '*' in seq:
return seq.index('*')
else:
return len(seq) |
def dict_repr_html(dictionary):
"""
Jupyter Notebook magic repr function.
"""
rows = ''
s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'
for k, v in dictionary.items():
rows += s.format(k=k, v=v)
html = '<table>{}</table>'.format(rows)
return html |
def get_token_update(count, token):
"""
Estrae i token uno alla volta dal dizionario di count
"""
old_value = count[token]
count[token] -= min(count[token], 1)
return min(old_value, 1) |
def parse_fsx_backups(backups, tag_key, tag_val):
"""Parse backups by tag."""
tmp_backups = []
for bkup in backups:
for tag in bkup['Tags']:
if ((tag['Key'] == tag_key) and (tag['Value'] == tag_val)):
tmp_backups.append(bkup)
break
return tmp_b... |
def paired(coords):
"""Return a list of pairs from a flat list of coordinates."""
assert len(coords) % 2 == 0, 'Coordinates are not paired.'
points = []
x = None
for elem in coords:
if x is None:
x = elem
else:
points.append((x, elem))
x = None
... |
def return_(value = None):
"""Create a return statement."""
if value is not None:
return [['return', value]]
else:
return [['return']] |
def multisigfig(X, sigfigs=5):
""" Return a string representation of variable x with sigfigs number of significant figures """
from numpy import log10, floor
output = []
try:
n=len(X)
islist = True
except:
X = [X]
n = 1
islist = False
for i in range(... |
def st_rowfreq(row,srate,length):
"""
for a row in a stockwell transform, give what frequency (Hz)
it corresponds to, given the sampling rate srate and the length of the original
array
"""
return row*srate/length |
def listify(*args):
"""
Given a set of parameters where some of them are given as lists and the
others as values, put brackets around the values to make lists of 1 element
so that we can use a for loop on all parameters in run_synthetic_exps.
For instance, the tuple of parameters
(n=500, k=[10,... |
def get_input(fn_str):
"""
Get input var to `fn_str`
"""
# parse to innermost inputs
if "(" not in fn_str:
return {fn_str}
else:
inner_fns = []
parens_stack = []
for c, char in enumerate(fn_str):
if char == '(':
parens_stack.append(c)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.