content stringlengths 42 6.51k |
|---|
def convert_to_bool(x) -> bool:
"""Convert string 'true' to bool."""
return x == "true" |
def dot(a, b):
"""Compute the dot product between the two vectors a and b."""
return sum(i * j for i, j in zip(a, b)) |
def is_set(parameter: str):
"""
Checks if a given parameter exists and is not empty.
:param parameter: param to check for
:return: if param is not None and not empty
"""
return parameter and parameter != "" |
def linear_system_example(x):
"""A simple linear system of equations."""
n = len(x)
res = [0] * n
for i in range(n):
for j in range(n):
res[i] += (1 + i * j) * x[j]
return res |
def fill_zeros(coords):
"""
fill with zeros, if coord is missing seconds
:param coords:
:return:
"""
if len(coords) == 2:
if "." in coords[1]:
coords = [coords[0], "00", coords[1]]
else:
coords = [coords[0], coords[1], "00"]
return coords |
def get_trans_freq_color(trans_count, min_trans_count, max_trans_count):
"""
Gets transition frequency color
Parameters
----------
trans_count
Current transition count
min_trans_count
Minimum transition count
max_trans_count
Maximum transition count
Returns
... |
def __remove_empty(j):
"""Remove the empty fields in the Json."""
if isinstance(j, list):
res = []
for i in j:
# Don't remove empty primitive types. Only remove other empty types.
if isinstance(i, int) or isinstance(i, float) or isinstance(
i, str) or isinstance(i, bool):
res.a... |
def deletedup(xs):
"""Delete duplicates in a playlist."""
result = []
for x in xs:
if x not in result:
result.append(x)
return result |
def _inputs_swap_needed(mode, shape1, shape2):
"""
If in 'valid' mode, returns whether or not the input arrays need to be
swapped depending on whether `shape1` is at least as large as `shape2` in
every dimension.
This is important for some of the correlation and convolution
implementations in th... |
def trunc(text, max_length: int = 2000):
"""Truncates output if it is too long."""
if len(text) <= max_length:
return text
else:
return text[0 : max_length - 3] + "..." |
def balance_formatter(asset_info):
"""
Returns the formatted units for a given asset and amount.
"""
decimals = asset_info.get("decimals")
unit = asset_info.get("unitname")
total = asset_info.get("total")
formatted_amount = total/10**decimals
return "{} {}".format(formatted_amount, uni... |
def bin_to_hex(binary_string, min_width=0):
"""
Convert binary string into hex string
:param binary_string: binary string
:param min_width: width of hex string
:return:
"""
return '{0:0{width}x}'.format(int(binary_string, 2), width=min_width) |
def _compute_temp_terminus(temp, temp_grad, ref_hgt,
terminus_hgt, temp_anomaly=0):
"""Computes the (monthly) mean temperature at the glacier terminus,
following section 2.1.2 of Marzeion et. al., 2012. The input temperature
is scaled by the given temperature gradient and the elev... |
def sanitize_list(mylist):
""" Helper function to objectify items """
if mylist is not None:
return mylist.split(',')
else:
return None |
def state_string_from_int(i, N):
"""translates an integer i into a state string by using the binary
representation of the integer"""
return bin(i)[2:].zfill(N) |
def isMatch(s, p):
""" Perform regular simple expression matching
Given an input string s and a pattern p, run regular expression
matching with support for '.' and '*'.
Parameters
----------
s : str
The string to match.
p : str
The pattern to match.
Returns
-------... |
def check_help_flag(addons: list) -> bool:
"""Checks to see if a help message needs to be printed for an addon.
Not all addons check for help flags themselves. Until they do, intercept
calls to print help text and print out a generic message to that effect.
"""
addon = addons[0]
if any(help_arg... |
def _indent(text, amount):
"""Indent a multiline string by some number of spaces.
Parameters
----------
text: str
The text to be indented
amount: int
The number of spaces to indent the text
Returns
-------
indented_text
"""
indentation = amount * ' '
return... |
def _generate_overlap_table(prefix):
"""
Generate an overlap table for the following prefix.
An overlap table is a table of the same size as the prefix which
informs about the potential self-overlap for each index in the prefix:
- if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...]
- if o... |
def skip_14(labels):
"""Customised label skipping for 14 quantiles."""
return (
labels[0],
labels[2],
labels[4],
labels[6],
labels[8],
labels[10],
labels[13],
) |
def _llvm_get_rule_name(
prefix_dict,
name):
"""Returns a customized name of a rule. When the prefix matches a key
from 'prefix_dict', the prefix will be replaced with the
'prefix_dict[key]' value.
Args:
prefix_dict: the dictionary of library name prefixes.
name: r... |
def average_contour(cnt):
"""
This function smooths out the contours created by the model
"""
result = [cnt[0]]
n = len(cnt)
for i in range(1, n):
px = (cnt[(i-1)%n][0] + 2*cnt[i%n][0] + cnt[(i+1)%n][0])/4
py = (cnt[(i-1)%n][1] + 2*cnt[i%n][1] + cnt[(i+1)%n][1])/4
result.... |
def findNext ( v, pos, pattern, bodyFlag = 1 ):
"""
findNext: use string.find() to find a pattern in a Leo outline.
v the vnode to start the search.
pos the position within the body text of v to start the search.
pattern the search string.
bodyFlag true: search body text. false: search headline te... |
def find_comment(s):
""" Finds the first comment character in the line that isn't in quotes."""
quote_single, quote_double, was_backslash = False, False, False
for i, ch in enumerate(s):
if was_backslash:
was_backslash = False
elif ch == '\\':
was_backslash = True
... |
def split_cols_with_dot(column: str) -> str:
"""Split column name in data frame columns whenever there is a dot between 2 words.
E.g. price.availableSupply -> priceAvailableSupply.
Parameters
----------
column: str
Pandas dataframe column value
Returns
-------
str:
Valu... |
def snake_to_kebab(text: str) -> str:
"""
Examples
--------
>>> snake_to_kebab('donut_eat_animals')
'donut-eat-animals'
"""
return text.replace("_", "-") |
def exponential_decay_fn(t, t0, t1, eps0, factor):
"""Exponentially decays.
Args:
t: Current step, starting from 0
t0: Decay start
t1: Decay end
factor: Decay factor
eps0: start learning rate
"""
if t < t0:
return eps0
lr = eps0 * pow(factor, (t - t0)... |
def process_line(line: str) -> dict:
"""Assign values from lines of a data file to keys in a dictionary."""
name, age, state = line.strip().split(",")
result = {"name": name, "age": int(age), "state": state}
return result |
def data_transformer(x, y, xfactor, yfactor, **kwargs):
"""Multiplies x or y data by their corresponding factor."""
return {"x": x * xfactor, "y": y * yfactor} |
def isglobalelement (domains):
""" Check whether all domains are negations."""
for domain in domains.split(","):
if domain and not domain.startswith("~"):
return False
return True |
def scaleRect(rect, x, y):
"""Scale the rectangle by x, y."""
(xMin, yMin, xMax, yMax) = rect
return xMin * x, yMin * y, xMax * x, yMax * y |
def CleanStrForFilenames(filename):
"""Sanitize a string to be used as a filename"""
keepcharacters = (' ', '.', '_')
FILEOUT = "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip()
return FILEOUT |
def _to_int(x):
"""convert to integers"""
return int(x[0]), int(x[1]) |
def count_true(seq, pred=lambda x: x):
"""How many elements is ``pred(elm)`` true for?
With the default predicate, this counts the number of true elements.
>>> count_true([1, 2, 0, "A", ""])
3
>>> count_true([1, "A", 2], lambda x: isinstance(x, int))
2
This is equivalent to the ``itertool... |
def five(ls):
"""
returns first five of list
"""
return ls[:5] |
def get_time_in_seconds(time, time_units):
"""This method get time is seconds"""
min_in_sec = 60
hour_in_sec = 60 * 60
day_in_sec = 24 * 60 * 60
if time is not None and time > 0:
if time_units in 'minutes':
return time * min_in_sec
elif time_units in 'hours':
... |
def bytes_isupper(x: bytes) -> bool:
"""Checks if given bytes object contains only uppercase elements.
Compiling bytes.isupper compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of chec... |
def packHeader(name, *values):
"""
Format and return a header line.
For example: h.packHeader('Accept', 'text/html')
"""
if isinstance(name, str): # not bytes
name = name.encode('ascii')
name = name.title() # make title case
values = list(values) # make copy
for i, value in e... |
def _clear_bits(basis_state, apply_qubits):
""" Set bits specified in apply_qubits to zero in the int basis_state.
Example:
basis_state = 6, apply_qubits = [0, 1]
6 == 0b0110 # number in binary representation
calling this method returns sets the two right-most bits to zero:
retu... |
def get_bool(bytearray_: bytearray, byte_index: int, bool_index: int) -> bool:
"""Get the boolean value from location in bytearray
Args:
bytearray_: buffer data.
byte_index: byte index to read from.
bool_index: bit index to read from.
Returns:
True if the bit is 1, else 0.
... |
def _yes_format(user, keys):
"""Changes all dictionary values to yes whose keys are in the list. """
for key in keys:
if user.get(key):
user[key] = 'yes'
return user |
def get_coordinates(threshold, value, step, direction, current_x, current_y):
"""Function for looping until correct coordinate is found"""
while value <= threshold:
for _ in range(0, 2):
for _ in range(0, step):
value += 1
# Step
if direction =... |
def get_filename_stem(filename):
"""
A filename should have the following format:
/path/to/file/filename_stem.jpg
This function extracts filename_stem from the input filename string.
"""
filename_stem = filename.split("/")
filename_stem = filename_stem[-1].split(".")
filename_stem... |
def compatiblify_phenotype_id(phenotype_id):
"""RHEmc throws errors on reading weird phenotype
headers. This function resolves these characters.
"""
to_replace = [' ', '|', '>', '<', '/', '\\']
for i in to_replace:
phenotype_id = phenotype_id.replace(i, '_')
return phenotype_id |
def _descExc(reprOfWhat, err):
"""Return a description of an exception.
This is a private function for use by safeDescription().
"""
try:
return '(exception from repr(%s): %s: %s)' % (
reprOfWhat, err.__class__.__name__, err)
except Exception:
return '(exception from rep... |
def app_create(app, request):
"""
Create a copy of welcome.w2p (scaffolding) app
Parameters
----------
app:
application name
request:
the global request object
"""
did_mkdir = False
try:
path = apath(app, request)
os.mkdir(path)
did_mkdir = T... |
def func_create_file(path_to_file):
"""
Function description
Example/s of use (and excutable test/s via doctest):
>>> func_create_file("file.txt")
'line in file'
:param path_to_file: set a path to file
:return: string with first line in file
"""
with open(path_to_file, "w") as f:
... |
def tagToByte(value):
"""
Converts an ASN1 Tag into the corresponding byte representation
:param value: The tag to convert
:return: The integer array
"""
if value <= 0xff:
return [value]
elif value <= 0xffff:
return [(value >> 8), (value & 0xff)]
elif value <= 0xffffff... |
def progress_reporting_sum(numbers, progress):
"""
Sum a list of numbers, reporting progress at each step.
"""
count = len(numbers)
total = 0
for i, number in enumerate(numbers):
progress((i, count))
total += number
progress((count, count))
return total |
def _pipe_separated(val):
"""
Returns *val* split on the ``'|'`` character.
>>> _pipe_separated("a|b|c")
['a', 'b', 'c]
"""
return [s.strip() for s in val.split('|') if s.strip()] |
def ternary_search(array):
"""
Ternary Search
Complexity: O(log3(N))
Requires a unimodal array. That means
that the array has to be increasing and then
decreasing (or the opposite). The point is to
find the maximum (or minimum) element. Small
modifications needed to work with d... |
def period_to_date(period):
""" Convert a period (in AAAAMM form) to a date (in MM/AAAA form). """
month = period[4:6]
year = period[0:4]
return month + '/' + year |
def palindrome(number):
""" Returns True if number is palindrome """
number = str(number)
for idx in range(len(number)//2):
if number[idx] != number[len(number)-idx-1]:
return False
return True |
def istruthy(val) -> bool or str or int or dict or list or None:
""" Returns True if the passed val is T, True, Y, Yes, 1, or boolean True.
Returns False if the passed val is boolean False or a string that is not T, True, Y, Yes, or 1, or an integer that is not 1.
Returns the passed val otherwise. Ignores c... |
def cross(a, b):
"""Cross Product.
Given vectors a and b, calculate the cross product.
Parameters
----------
a : list
First 3D vector.
b : list
Second 3D vector.
Returns
-------
c : list
The cross product of vector a and vector b.
Examples
--------... |
def is_defined(s, table):
"""
Test if a symbol or label is defined.
:param s: The symbol to look up.
:param table: A dictionary containing the labels and symbols.
:return: True if defined, False otherwise.
"""
try:
table[s] # Exploiting possible KeyError
return True
ex... |
def str_to_orientation(value, reversed_horizontal=False, reversed_vertical=False):
"""Tries to interpret a string as an orientation value.
The following basic values are understood: ``left-right``, ``bottom-top``,
``right-left``, ``top-bottom``. Possible aliases are:
- ``horizontal``, ``horiz``, ``h... |
def _value_error_on_false(ok, *args):
"""Returns None / args[0] / args if ok."""
if not isinstance(ok, bool):
raise TypeError("first argument should be a bool")
if not ok:
raise ValueError("call failed")
if args:
return args if len(args) > 1 else args[0]
return None |
def nested_list_elements_to_int(mask):
"""Recursively convert list of nested lists/tuples to list of nested lists with elements coerced to integers
Args:
mask (list): List with nested lists/tuples containing start, end positions
Returns:
(list): List of nested lists containing start, end p... |
def hash_s(_s):
"""
Hash and sum each charater from string
"""
s_hashed = 0
for _char in _s:
s_hashed += hash(_char)
return s_hashed |
def truncate_string(string: str, max_length: int) -> str:
"""
Truncate a string to a specified maximum length.
:param string: String to truncate.
:param max_length: Maximum length of the output string.
:return: Possibly shortened string.
"""
if len(string) <= max_length:
return strin... |
def transform_boolean(value):
"""
Transform boolean values that are blank into NULL so that they are not
imported as empty strings.
"""
if value.lower() in ("true", "t", "1"):
return True
elif value.lower() in ("false", "f", "0"):
return False
else:
return None |
def RPL_TRACESERVICE(sender, receipient, message):
""" Reply Code 207 """
return "<" + sender + ">: " + message |
def validateRange(rangeStr : str) -> bool:
"""Validates the range argument"""
# type cast and compare
try:
# get range indices
ranges = rangeStr.split(",", 1)
rangeFrom = 0 if ranges[0] == "" else int(ranges[0])
rangeTo = 0 if ranges[1] == "" else int(ranges[1])
# ... |
def compare_floats(float1, float2, f_error=0.01, zero_tolerance=1e-8, inf_tolerance=1e80):
"""
Compare two numeric objects according to the following algorithm:
1. If float1 < zero_tolerance and float2 < zero_tolerance, then returns True.
2. If abs(float1) > inf_tolerance and abs(float2) > inf_toleranc... |
def exp_str(dictionary, key):
"""Return exponent string. An empty string if exponent is 1.
"""
if dictionary[key] == 1:
return ''
else:
return '**' + str(dictionary[key]) |
def fix_aspect_providers(lib_providers):
"""Change a list of providers to be returnable from an aspect.
Args:
lib_providers: A list of providers, e.g., as returned from forward_deps().
Returns:
A list of providers which is valid to return from an aspect.
"""
# The DefaultInfo provider... |
def to_cuda(data):
"""
Move an object to CUDA.
This function works recursively on lists and dicts, moving the values
inside to cuda.
Args:
data (list, tuple, dict, torch.Tensor, torch.nn.Module):
The data you'd like to move to the GPU. If there's a pytorch tensor or
... |
def station_geojson(stations):
"""Process station data into GeoJSON
"""
result = []
for data in stations:
result.append(
{"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [data['x'], data['y']]
},
... |
def suffix_length(needle, p):
"""
Returns the maximum length of the substring ending at p that is a suffix.
"""
length = 0;
j = len(needle) - 1
for i in reversed(range(p + 1)):
if needle[i] == needle[j]:
length += 1
else:
break
j -= 1
return le... |
def update_with(left, right, default_value, upd_fn):
"""
unionWith for Python, but modifying first dictionary instead of returning result
"""
for k, val in right.items():
if k not in left:
left[k] = default_value[:]
left[k] = upd_fn(left[k], val)
return left |
def make_slist(l, t_sizes):
"""
Create a list of tuples of given sizes from a list
Parameters
----------
l : list or ndarray
List or array to pack into shaped list.
t_sizes : list of ints
List of tuple sizes.
Returns
-------
slist : list of tuples
List of tu... |
def _unflatten_dims(dims):
""" ['a','b,c','d'] ==> ['a','b','c','d']
"""
flatdims = []
for d in dims:
flatdims.extend(d.split(','))
return flatdims |
def codestr2rst(codestr):
"""Return reStructuredText code block from code string"""
code_directive = ".. code-block:: python\n\n"
indented_block = '\t' + codestr.replace('\n', '\n\t')
return code_directive + indented_block |
def _arg_names(f):
"""Return the argument names of a function."""
return f.__code__.co_varnames[:f.__code__.co_argcount] |
def _Error(message, code=400):
"""
Create an Error framework
:param message:
:param code:
:return:
"""
return {
"error" : message,
"code" : code
} |
def clean_bibitem_string(string):
"""Removes surrounding whitespace, surrounding \\emph brackets etc."""
out = string
out = out.strip()
if out[:6] == "\\emph{" and out[-1] == "}":
out = out[6:-1]
if out[:8] == "\\textsc{" and out[-1] == "}":
out = out[8:-1]
return out |
def calc_center(eye):
"""
Using for further cropping eyes from images with faces
:param eye:
:return: x, y, of center of eye
"""
center_x = (eye[0][0] + eye[3][0]) // 2
center_y = (eye[0][1] + eye[3][1]) // 2
return int(center_x), int(center_y) |
def single_number(nums):
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Args:
nums: list[int]
Returns:
int
"... |
def tanh_to_sig_scale(tanh_input,scale_multiplier=1.):
"""For image data scaled between [-1,1],
rescale to [0,1] * scale_multiplier (e.g. 255 for RGB images)
"""
#Due to operator overloading, this also works with tensors
return ((tanh_input+1.)/2.)*scale_multiplier |
def check_equal(val1, val2):
""" Check two values are equal and exit with message if not
Args:
val1: the first value to compare
val2: the second value to compare
"""
return abs(val1 - val2) < 0.0000000001 |
def mod_exponent(base, power, mod):
"""
Modular exponential of a number
:param base : number which is going to be raised
:param power : power to which the number is raised
:param mod : number by modulo has to be performed
:return : number raised to power and modulo by mod [(base ^ power) % mod... |
def create_object_detected_msg(position):
"""creates an xyz message of target location"""
return {'coords':position} |
def distance_squared(a, b):
"""The square of the distance between two (x, y) points."""
return (a[0] - b[0])**2 + (a[1] - b[1])**2 |
def import_function(function):
"""L{import_function} is a shortcut that will import and return L{function}
if it is a I{str}. If not, then it is assumed that L{function} is callable,
and is returned."""
if isinstance(function, str):
m, f = function.rsplit('.', 1)
return getattr(__import... |
def best3av(a, b, c, d):
""" (number, number, numbern number) -> number
Precondition: 100 > Numbers > 0.
Returns the average of the highest three numbers.
>>>average(40, 99, 87, 0)
75.33
>>>average(80, 10, 100, 40)
73.33
"""
One = min(a, b, c, d)
Two = (a + b + c + d - One)
... |
def compute_power(rawvolts, rawamps):
"""
Compute the power. Looks trivial, but I'm gonna implement
smoothing later.
"""
power = rawvolts * 1.58
power_low = rawvolts * 1.51
power_high = rawvolts * 1.648
return power, power_low, power_high |
def condense_repeats(ll, use_is=True):
"""
Count the number of consecutive repeats in a list.
Essentially, a way of doing `uniq -c`
Parameters
----------
ll : list
a list
Returns
-------
list of tuples
list of 2-tuples in the format (element, repeats) where element... |
def ordinal_number(n: int):
"""
Returns a string representation of the ordinal number for `n`
e.g.,
>>> ordinal_number(1)
'1st'
>>> ordinal_number(4)
'4th'
>>> ordinal_number(21)
'21st'
"""
# from https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1... |
def compareKeys(zotkeys, notkeys):
"""
Compares the Zotero and Notion keys
"""
keys = []
for zkey in zotkeys:
if zkey in notkeys:
pass
else:
keys.append(zkey)
return keys |
def ordered(obj):
"""Ordering a dict object
:param obj: Can be list or dict
:return obj:
"""
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj |
def processFirstLine(x):
"""work on the values of x """
numbers = (x.split(' '))
return numbers |
def _return_parameter_names(num_pars):
"""
Function that returns the names of the parameters for writing to the dataframe after the fit.
num_pars is the number of parameters in the fit. 1,3,5,7,9 are the num_params that constrain the fit.
while the even numbers are the parameters for the functions that ... |
def validate_heart_rate_timestamp(in_heart_rate, heart_rate_expected_keys):
"""Validate inputted json data
This function tests 3 criteria for the inputted json file.
1. It must be a dictionary
2. It must contain all of the expected_keys: "patient_id" and
"heart_rate"
3. It must contain the corr... |
def _insert_breaks(s, min_length, max_length):
"""Inserts line breaks to try to get line lengths within the given range.
This tries to minimize raggedness and to break lines at punctuation
(periods and commas). It never splits words or numbers. Multiple spaces
may be converted into single spaces.
... |
def win_concat_quote(command_line: str, argument: str) -> str:
"""
appends the given argument to a command line such that CommandLineToArgvW will return
the argument string unchanged.
"""
# from https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-lin... |
def return_real_remote_addr(env):
"""Returns the remote ip-address,
if there is a proxy involved it will take the last IP addres from the HTTP_X_FORWARDED_FOR list
"""
try:
return env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
except KeyError:
return env['REMOTE_ADDR'] |
def bonenamematch(name1, name2):
"""Heuristic bone name matching algorithm."""
if name1 == name2:
return True
if name1.startswith("Bip01 L "):
name1 = "Bip01 " + name1[8:] + ".L"
elif name1.startswith("Bip01 R "):
name1 = "Bip01 " + name1[8:] + ".R"
if name2.startswith("Bip01... |
def _convert_space_to_shape_index(space):
"""Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing).
Parameters
----------
space : str, values=('feature', 'sample')
Feature or sample space.
Returns
-------
return : int, values=(0, 1)
Index location of th... |
def show_database_like(db_name):
"""Rerurns the command
Arguments:
db_name {string} -- [description]
Returns:
string -- [description]
"""
return "SHOW DATABASES LIKE '" + db_name+ "'" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.