content stringlengths 42 6.51k |
|---|
def rec_copy(d: dict) -> dict:
"""Local replacement for copy.deepcopy(), as transcrypt cannot import the copy module.
We recursively make a copy of a dict.
This code can only handle values that are dicts or scaler types
"""
newdct = dict()
for k, v in d.items():
if isinstance(v, dict):
... |
def is_prime(n):
"""Checks if a number is a prime number."""
if n <= 2: return False
if n % 2 == 0: return False
i = 3
while i < n**0.5+1:
if n % i == 0: return False
i += 2
return True |
def to_bool(bool_str):
"""Parse a boolean environment variable."""
return bool_str.lower() in ("yes", "true", "1") |
def letters_count(value):
"""Count the number of letters in the string representation of a scalar
value.
Parameters
----------
value: scalar
Scalar value in a data stream.
Returns
-------
int
"""
return sum(c.isalpha() for c in str(value)) |
def s2tc(secs: float, base: float=25) -> str:
"""Convert seconds to an SMPTE timecode
Args:
secs (float):
Number of seconds
base (float):
Frame rate (default: 25)
Returns:
str:
SMPTE timecode (`HH:MM:SS:FF`)
"""
try:
f = max(0, i... |
def combi_to_int(s):
"""
use integer as index of a set
"""
i = 0
for x in s: i += 2 ** x
return i |
def store_times(xdata, ydata, x, r, yfirst, rtimes):
""" Helper function that stores the times. """
xdata.append(x)
if rtimes:
ydata.append(r)
else:
if ydata:
ydata.append(float(yfirst)/float(r))
else:
ydata.append(1.0)
yfirst = r
return yf... |
def hex_to_RGB(hex):
""" "#FFFFFF" -> [255,255,255] """
# Pass 16 to the integer function for change of base
return [int(hex[i:i+2], 16) for i in range(1, 6, 2)] |
def nestEggVariable(salary, save, growthRates):
"""
- salary: the amount of money you make each year.
- save: the percent of your salary to save in the investment account each
year (an integer between 0 and 100).
- growthRate: a list of the annual percent increases in your investment
account... |
def unlock_params(lock_handle):
"""Returns parameters for Action Unlock"""
return {'_action': 'UNLOCK', 'lockHandle': lock_handle} |
def myfunc(s):
"""Convert strings to mixed caps."""
ret_val = ''
index = 0
for letter in s:
if index % 2 == 0:
ret_val = ret_val + letter.upper()
else:
ret_val = ret_val + letter.lower()
index = index+1
return ret_val |
def scale(val, minx, maxx, minscale, maxscale):
""" Scales a value in one range to another. """
# https://stackoverflow.com/a/5295202
return (maxscale - minscale) * (val - minx) / maxx - minx + minscale |
def direction_leaf(forw):
""" direction leaf directory name
"""
return 'F' if forw else 'B' |
def song_ids(songs):
"""
returns list of ids of songs in a given list,
song ids are needed to get the audio features
"""
ids = []
for song in songs:
ids.append(song['track']['id'])
return ids |
def get_comma_separated(codes):
"""Takes list of codes, returns comma separated string."""
return ", ".join(codes) |
def model_submodule(model):
"""Get submodule of the model in the case of DataParallel, otherwise return
the model itself. """
return model.module if hasattr(model, 'module') else model |
def _CreateLookupCacheKey(func, prefix, args, unused_kwargs=None):
"""Generate a unique key from the Lookup function and its arguments."""
prefix = prefix or func.__name__
binary_hash = args[0] or ''
return '%s|%s' % (prefix, binary_hash) |
def serialize_parentesco_relacion(parentezco):
"""
# $ref : '#/components/schemas/parentescoRelacion'
"""
if parentezco:
return {
"clave": parentezco.codigo,
"valor": parentezco.tipo_relacion
}
return {"clave":"OTRO", "valor": "Otro"} |
def xor_strs(s1, s2):
"""
Helper used for encryption, xors given strs
"""
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) |
def conv_out_shp(IR, IC, KR, KC, border_mode, subsample):
"""
.. todo::
WRITEME
"""
ssR, ssC = subsample
def ceildiv(x, y):
r = x // y
if r * y < x:
return r + 1
return r
if border_mode == 'valid':
OR, OC = ceildiv(IR - KR + 1,ssR), ceildiv(IC... |
def expo2(n: int):
"""
Returns the exponent of a power of two
Using bit manipulation
Parameters
----------
n : int
Returns
-------
p : int,
such as n = 2 ** p
"""
pow2 = (n & (n - 1) == 0)
if not pow2:
return "not a power of tow"
return n.bit_length() - 1 |
def is_number(s):
"""simple helper to test if value is number as requests with numbers don't
need quote marks
"""
try:
float(s)
return True
except ValueError:
return False |
def weekday_to_str(weekday, *, inverse=False):
"""
Given a weekday number (integer in the range 0, 1, ..., 6),
return its corresponding weekday name as a lowercase string.
Here 0 -> 'monday', 1 -> 'tuesday', and so on.
If ``inverse``, then perform the inverse operation.
"""
s = [
"mo... |
def CalculateThroughput(total_bytes_transferred, total_elapsed_time):
"""Calculates throughput and checks for a small total_elapsed_time.
Args:
total_bytes_transferred: Total bytes transferred in a period of time.
total_elapsed_time: The amount of time elapsed in seconds.
Returns:
The throughput as ... |
def ExtractVarFromTupleList(tupleList, n):
"""
Method to extract from a list of tuples, one variable in the tuple and return the
values in a list
:param tupleList:
:param n:
:return:
"""
varList = list()
N = len(tupleList)
for ii in range(N):
varList.append(tup... |
def pop(tpl, index):
"""removes element at `index` and returns a new tuple"""
return tpl[:index] + tpl[index+1:] |
def get_codebook(feature):
"""
feature1 = feature_extract(feature)
shapely = filter_shapely(feature1)
codebook_index = get_codebook(shapely)
"""
codebook =[]
for i in range(len(feature)):
if feature[i]<0:
codebook.append(i)
return codebook |
def _get_options_group(group=None):
"""Get a specific group of options which are allowed."""
#: These expect a hexidecimal keyid as their argument, and can be parsed
#: with :func:`_is_hex`.
hex_options = frozenset(['--check-sigs',
'--default-key',
... |
def create_library_task_payload(name, task_type, attrs, description, out_vars=None):
"""Create Task Library payload"""
task_resources = {
"type": task_type,
"variable_list": [],
}
if task_type == "HTTP":
task_resources["attrs"] = attrs
else:
script_type = attrs.get(... |
def str_to_bin(s: str) -> str:
"""
'Hello' => '01001000 01100101 01101100 01101100 01101111'
"""
b = s.encode()
str_bytes = ["{:08b}".format(n) for n in b]
return " ".join(str_bytes) |
def _SectionDictFromConfigList(boto_config_list):
"""Converts the input config list to a dict that is easy to write to a file.
This is used to reset the boto config contents for a test instead of
preserving the existing values.
Args:
boto_config_list: list of tuples of:
(boto config section to set... |
def _make_ssa_name(name):
"""Converts a symbol name (string) into an SSA name, by prepending '%'.
Only used for pretty printing the graph.
"""
return "%" + name |
def is_puny(fqdn):
"""
returns true if any 'section' of a url (split by '.') begins with xn--
"""
sections = fqdn.split('.')
for section in sections:
if section[:4] == 'xn--':
return True
else:
return False |
def decorate_chat_msg(username, message):
""" Decorate the message sent by a user by adding the sender's name
and a colon at the front
"""
return username + ": " + message |
def first(iterable, pred, default=None):
"""Returns the first item for which pred(item) is true.
If no true value is found, returns *default*
"""
return next(filter(pred, iterable), default) |
def regional_indicator(c: str) -> str:
"""Returns a regional indicator emoji given a character."""
return chr(0x1F1E6 - ord("A") + ord(c.upper())) |
def replace_newlines(s, replacement=' / ', newlines=(u"\n", u"\r")):
"""
Used by the status message display on the buddy list to replace newline
characters.
"""
# turn all carraige returns to newlines
for newline in newlines[1:]:
s = s.replace(newline, newlines[0])
# while ... |
def parse_pattern(seq: str):
"""
A function to substitute RegEx in the sequence string
sequence: A string that contains a comma seperated numbers and patterns
returns: A string after replacing the patterns with a specific regex
"""
_RE1 = r'(\+|-)?\d+'
_RE2 = '.+'
# Clear seq from space... |
def clean_up_tokenization_spaces(out_string):
"""Converts an output string (de-BPE-ed) using de-tokenization algorithm from OpenAI GPT."""
out_string = out_string.replace('<unk>', '')
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ','
).replace(" '... |
def check_for_bypass_url(raw_creds, nova_args):
"""
Return a list of extra args that need to be passed on cmdline to nova.
"""
if 'BYPASS_URL' in raw_creds.keys():
bypass_args = ['--bypass-url', raw_creds['BYPASS_URL']]
nova_args = bypass_args + nova_args
return nova_args |
def elements_to_str(l):
""" Convert each element in an iterator to a string representation
Args:
l (:obj:`list`): an iterator
Returns:
:obj:`list`: a list containing each element of the iterator converted to a string
"""
return [str(e) for e in l] |
def round_channels(channels, multiplier=None, divisor=8, min_depth=None):
"""Round number of filters based on depth multiplier."""
if not multiplier:
return channels
channels *= multiplier
min_depth = min_depth or divisor
new_channels = max(min_depth, int(channels + divisor / 2) // divisor... |
def case_name_func(func_name, kwargs):
"""Function to return a customized name for parameterized testcase."""
return "{} ({}+{}={})".format(
func_name, kwargs["a"], kwargs["b"], kwargs["expected"]
) |
def dedent(string, ts=4):
"""
Removes common leading whitespace from the given string. Each tab counts as
the given number of spaces.
"""
lines = string.split("\n")
common = None
for l in lines:
here = 0
for c in l:
if c not in " \t":
break
elif c == " ":
here += 1
... |
def sub(value, arg):
"""Subtract the arg from the value."""
try:
return int(value) - int(arg)
except (ValueError, TypeError):
return value |
def count_vowels(string):
"""
Returns the number of vowels in a given string.
"""
count = 0
for character in string.lower():
if character in "aeiou":
count += 1
return count |
def content_type_from_filename(filename):
"""Determined content type from 'filename'"""
if filename:
if filename.endswith(".rst"):
return "text/x-rst"
if filename.endswith(".md"):
return "text/markdown"
return None |
def enumerate_ids(locationlist):
"""For a given list of locations, give them all an ID"""
counter = 1
for location in locationlist:
location.insert(0,"LOCID%s" % (counter))
counter+=1
return locationlist |
def swapcase(strn: str) -> str:
"""Swapcase of strn, except for items that are inside braces."""
output = []
brackets = 0
for letter in strn:
output.append(letter if brackets else letter.swapcase())
if letter == "{":
brackets += 1
elif letter == "}":
brac... |
def function_with_three_parameters(input_value_tbd1: int,
input_value_tbd2: int,
input_value_tbd3: int,
static_value: int) -> int:
"""function_with_multiple_inputs called using {input_value_tbd1} and {input_valu... |
def return_tuple_item(item):
"""tuple of statements, next statement"""
return " {0},".format(item) |
def colorAsFloatValues(color):
""" convert color values """
return color[0] / 255., color[1] / 255., color[2] / 255. |
def like_prefix(value, start='%'):
"""
gets a copy of string with `%` or couple of `_` values attached to beginning.
it is to be used in like operator.
:param str value: value to be processed.
:param str start: start place holder to be prefixed.
it could be `%` or couple of ... |
def remove_repeated_first_names(names):
"""
Question 14.4: Remove duplicate first names
from input array
"""
seen = set()
output = []
for name in names:
if name[0] not in seen:
output.append(name)
seen.add(name[0])
return output |
def rivers_with_station(stations):
"""Takes a list of stations and returns a set of all the rivers
in alphabetic order upon which those stations are located"""
rivers = set()
for station in stations:
rivers.add(station.river)
rivers = sorted(rivers)
return rivers |
def sanitizeIOC(ioc):
"""
Method to sanitize IOCs
"""
newIOC = ioc.replace("[.]", ".").replace("hxxp", "http")
return newIOC |
def get_package_json_dict(project: str, score_class: str) -> dict:
"""Returns the template of package.json
:param project: SCORE's name.
:param score_class: SCORE's main class name.
:return: package.json's contents.(dict)
"""
package_json_dict = {
"version": "0.0.1",
"main_modu... |
def vector_subtract(vect1, vect2):
""" Subtracts corresponding elements of 2 vectors """
return [v1_i - v2_i for v1_i, v2_i in zip(vect1, vect2)] |
def replace_check(c):
"""
Replace non-ASCII chars with their code point
"""
if ord(c) <= ord('~'):
return c
return '<%(orig)c:U+%(point)04X>' % {
'orig': c,
'point': ord(c)
} |
def colour(text, colour):
"""
Colours text.
Requires markup=pango
"""
if colour == "default":
return text
if colour == "empty":
return ""
if colour == "blank":
return " " * len(text)
return f"<span color='{colour}'>{text}</span>" |
def mask_to_dict(bits_def, mask_value):
"""
Describes which flags are set for a mask value
:param bits_def:
:param mask_value:
:return: Mapping of flag_name -> set_value
:rtype: dict
"""
return_dict = {}
for flag_name, flag_defn in bits_def.items():
# Make bits a list, even... |
def ptest_add_ingredients(ingredients):
"""Here the caller expects us to return a list"""
if "egg" in ingredients:
spam = ["lovely spam", "wonderous spam"]
else:
spam = ["spendiferous spam", "magnificent spam"]
return spam |
def deep_merge(source: dict, destination) -> dict:
"""Deep merge for dictionaries
Args:
source (dict): Dict to merge
destination (Any): hm...
Returns:
dict: hm...
"""
for key, value in source.items():
if isinstance(value, dict):
node = destin... |
def truncate(string, continuation="...", limit=30):
"""Get a truncated version of a string if if over the limit.
:param string: The string to be truncated.
:type string: str | None
:param limit: The maximum number of characters.
:type limit: int
:param continuation: The string to add to the t... |
def split_pdb_atom_lines(lines):
"""
Extract PDB atom properties
for a list of strings and
return a list of dictionaries.
Parameters
----------
lines : list of str
list of PDB atom strings
Returns
-------
list of dict
list of PDB atom properties
"""
retu... |
def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
return isinstance(obj, DataFrame)
except ImportError:
# Pandas is not a dependency, so this is scary
... |
def mass(plates, materials):
""" compute mass of each plate based on material data """
totalmass = 0
matl_data = dict([(row[0], row[1:]) for row in materials])
for plate in plates:
matl = plate.get("material", "MIL_DTL_12560")
this_matl_data = matl_data.get(matl, [-1, "x", "x", 0... |
def lst2tup(data):
"""Converts output of json.loads to have tuples, not lists.
"""
if isinstance(data, list):
return tuple(lst2tup(e) for e in data)
if isinstance(data, dict):
return {k: lst2tup(v) for k, v in data.items()}
return data |
def remove_deprecated(stix_objects):
"""Will remove any revoked or deprecated objects from queries made to the data source"""
# Note we use .get() because the property may not be present in the JSON data. The default is False
# if the property is not set.
return list(
filter(
lambda ... |
def get_p_at_n_in_m(data, n, m, ind):
"""Former n recall rate"""
pos_score = data[ind][0]
curr = data[ind:ind + m]
curr = sorted(curr, key=lambda x: x[0], reverse=True)
if curr[n - 1][0] <= pos_score:
return 1
return 0 |
def IsTarball(path):
"""Guess if this is a tarball based on the filename."""
parts = path.split('.')
if len(parts) <= 1:
return False
if parts[-1] == 'tar':
return True
if parts[-2] == 'tar':
return parts[-1] in ('bz2', 'gz', 'xz')
return parts[-1] in ('tbz2', 'tbz', 'tgz', 'txz') |
def recast_string(value):
"""Converts a string to some type of number or True/False if possible
Args:
value (str): A string that may represent an int or float
Returns:
int, float, bool, str, or None: The most precise numerical or boolean
representation of ``value`` if ``value`` is ... |
def validate_ticket_price(price):
"""
validate that the ticket price is between $10 and $100 (inclusive)
:param price: price of the ticket
:return: an error message (if any) or nothing if the price is valid
"""
errors = []
if int(price) < 10:
errors.append("Ticket price must be at least $10")
if int(price) >... |
def factorial(n):
"""Returns the factorial of n."""
if n == 0:
return 1
else:
return n * factorial(n - 1) |
def generate_paragraph(parsed_dict):
"""Return a formatted paragraph from a dictionary parsed by
run.py.parse_file (with False passed to weight_int param)."""
paragraph = "Name: {}<br/> Weight: {} <br/><br/>".format(parsed_dict["name"], parsed_dict["weight"])
return paragraph |
def fast_exponentiation(a, p, n):
"""A fast way to calculate a**p % n"""
result = a%n
remainders = []
while p != 1:
remainders.append(p & 1)
p = p >> 1
while remainders:
rem = remainders.pop()
result = ((a ** rem) * result ** 2) % n
return result |
def _iterative_levenshtein(source, targ):
"""
iterative_levenshtein(source, targ) -> ldist
ldist is the Levenshtein distance between the strings
source and targ.
For all i and j, dist[i,j] will contain the Levenshtein
distance between the first i characters of source and the
... |
def dict_merge(base_dct, merge_dct, add_keys=True):
"""
Recursively merge dict from
https://gist.github.com/CMeza99/5eae3af0776bef32f945f34428669437
"""
rtn_dct = base_dct.copy()
if add_keys is False:
merge_dct = {key: merge_dct[key] for key in set(rtn_dct).intersection(set(merge_dct))}
... |
def _parse_list_of_strings(input_str):
"""
Parse a text string as a list of strings.
Parameters
----------
input_str : str
The input string to be processed.
Returns
-------
files : list of str
The list of strings representing input files.
"""
# use basic string... |
def _select_points(a, list_like):
"""
returns one above a, one below a, and the third
closest point to a sorted in ascending order
for quadratic interpolation. Assumes that points
above and below a exist.
"""
foo = [x for x in list(list_like) if x-a <= 0]
z = [min(foo, key=lambda x : abs... |
def parse_coords(string):
"""
Retrieve coordinates from the string.
Parameters
----------
string : str
the string to parse
Returns
-------
coords : list(float, float, str)
list containing RA, Dec, and coordinate system description
"""
ra = float(string.split()[0... |
def test_if_empty_string_in_line_items_contents(lst):
"""Takes components and amounts as a list of strings and floats (origninating in line items), and returns true if there is at least one empty string."""
empty_comps = [x for x in lst if x == ""]
return bool(empty_comps) |
def _remove_invalid_filename_characters(basename):
"""
Helper method for exporting cases of 12*I/t^3.csv,
which have invalid characters.
Invalid for Windows
< (less than)
> (greater than)
: (colon - sometimes works, but is actually NTFS Alternate Data Streams)
" (double quote)
... |
def keep_going(steps, num_steps, episodes, num_episodes):
"""Determine whether we've collected enough data"""
# If num_episodes is set, stop if limit reached.
if num_episodes and episodes >= num_episodes:
return False
# If num_steps is set, stop if limit reached.
elif num_steps and steps >= ... |
def value_to_number(name):
"""Given the "value" part of a card, returns its numeric value"""
values = [None, 'A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'J', 'Q', 'K']
return values.index(name) |
def api_json_format(timestamp, temperature):
"""
Imitate API json format.
Parameters
----------
timestamp : str
Event UTC timestamp.
temperature : float
Event temperature value.
Returns
-------
json : dict
API json format.
"""
json = {
'... |
def int_div_test(equation, val):
"""
Comparison for the integer division binary search.
:equation: Equation to test
:val: Input to the division
"""
r1 = equation(val)
if r1 == None:
return None
r2 = equation(val - 1)
if r2 == None:
return None
if r1 == 1 and r2 ... |
def get_meridiem(hour):
"""
Returns if the hour corresponds to a.m. or p.m.
it's incomplete as it don't check the range of the value
Keywords:
Hour: integer,
Returns:
a string : "a.m."/"p.m."
>>> for x in range(24):
... get_meridiem(x)
...
'a.m.'
'a.m.'
'a.m.'... |
def _pcolor(text, color, indent=0):
""" Colorized print to standard output """
esc_dict = {
'black':30, 'red':31, 'green':32, 'yellow':33, 'blue':34, 'magenta':35,
'cyan':36, 'white':37, 'none':-1
}
if esc_dict[color] != -1:
return (
'\033[{color_code}m{indent}{text}\... |
def convert_continuous_to_categorical(categories, orig_col, imputed_col):
""""Takes a set of categories, the original column, and a column
that has been imputed using the mean value of the KNN.
Returns a new column where the imputed values are transformed to the
nearest numeric category.
Note: Thi... |
def _argstrip(arglist):
"""Some options might be best removed before resubmission."""
to_remove = ['-i', '--interactive', '-m', '--import']
newargs = list(arglist)
for item in to_remove:
while item in newargs:
newargs.remove(item)
return newargs |
def precision(tp, fp, eps: float = 1e-5) -> float:
"""
Calculates precision (a.k.a. positive predictive value) for binary
classification and segmentation.
Args:
tp: number of true positives
fp: number of false positives
eps: epsilon to use
Returns:
precision value (... |
def seconds_for_one_day(time_s):
"""
strips away all seconds not in one day
:param time_s:
:return:
"""
return time_s % (60 * 60 * 24) |
def affine_encrypt(plaintext, key):
"""
C = (a * P + b) % 26
"""
return "".join(
[
chr(((key[0] * (ord(t) - ord("A")) + key[1]) % 26) + ord("A"))
for t in plaintext.upper().replace(" ", "")
]
) |
def problem_1(a, b):
""" Write a function of two arguments that returns `True` if adding both of its
arguments would result in an `int`. Otherwise `false`.
"""
return type(a + b) == int |
def scaling_round(val, factor=16, max_value=0):
"""
Round the given value to the nearest multiple of `factor`.
If the optional `max_value` is given, the nearest multiple
not above that `max_value` is returned.
:param val: The value to round.
:param factor: Rounding multiple.
:param max_val... |
def sort_string(s):
"""
:param s: string, ex: 'apple'
:return: string, sorted by a,b,c,d,e... ex: 'aelpp'
"""
sort_s = ''
for ch in sorted(list(s)):
sort_s += ch
return sort_s |
def dict_to_list(my_dict, mapping):
"""
having a dictionary, it returns a list
:param my_dict: dictionary to be mapped
:param mapping: alphabet for mapping
:return: list of ints
"""
my_list = [0] * len(mapping.keys())
for key in my_dict:
my_list[mapping[key]] = my_dict[key]
r... |
def res_spec2chain_id(res_spec):
"""simple extraction function"""
if not res_spec:
return False
if (len(res_spec) == 4):
return res_spec[1]
if (len(res_spec) == 3):
return res_spec[0]
return False |
def strip_namespace(name, content, namespace, logger=None):
""" Given a namespace, strips 'namespace__' from file name and content
"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
orig_content = content
new_content = orig_content.replace(namespace_pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.