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):
newdct[k] = rec_copy(v)
else:
newdct[k] = v
return newdct |
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, int(secs*base))
except ValueError:
return "--:--:--:--"
hh = int((f / base) / 3600)
hd = int((hh % 24))
mm = int(((f / base) / 60) - (hh*60))
ss = int((f/base) - (hh*3600) - (mm*60))
ff = int(f - (hh*3600*base) - (mm*60*base) - (ss*base))
return f"{hd:02d}:{mm:02d}:{ss:02d}:{ff:02d}" |
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 yfirst |
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 (integers between 0 and 100).
- return: a list of your retirement account value at the end of each year.
"""
F = []
F.append(salary*save*0.01)
i = 0
for growthRate in growthRates[1:]:
i += 1
F.append(F[i-1]*(1+0.01*growthRate) + salary*save*0.01)
return F |
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 - KC + 1,ssC)
elif border_mode == 'full':
OR, OC = ceildiv(IR + KR - 1,ssR), ceildiv(IC + KC - 1,ssC)
else:
raise NotImplementedError(border_mode)
return OR, OC |
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 = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
if not inverse:
try:
return s[weekday]
except:
return
else:
try:
return s.index(weekday)
except:
return |
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 a float.
"""
if total_elapsed_time < 0.01:
total_elapsed_time = 0.01
return float(total_bytes_transferred) / float(total_elapsed_time) |
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(tupleList[ii][n])
return varList |
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',
'--default-recipient',
'--delete-keys',
'--delete-secret-keys',
'--delete-secret-and-public-keys',
'--desig-revoke',
'--export',
'--export-secret-keys',
'--export-secret-subkeys',
'--fingerprint',
'--gen-revoke',
'--hidden-encrypt-to',
'--hidden-recipient',
'--list-key',
'--list-keys',
'--list-public-keys',
'--list-secret-keys',
'--list-sigs',
'--recipient',
'--recv-keys',
'--send-keys',
'--edit-key',
'--sign-key',
])
#: These options expect value which are left unchecked, though still run
#: through :func:`_fix_unsafe`.
unchecked_options = frozenset(['--list-options',
'--passphrase-fd',
'--status-fd',
'--verify-options',
'--command-fd',
])
#: These have their own parsers and don't really fit into a group
other_options = frozenset(['--debug-level',
'--keyserver',
])
#: These should have a directory for an argument
dir_options = frozenset(['--homedir',
])
#: These expect a keyring or keyfile as their argument
keyring_options = frozenset(['--keyring',
'--primary-keyring',
'--secret-keyring',
'--trustdb-name',
])
#: These expect a filename (or the contents of a file as a string) or None
#: (meaning that they read from stdin)
file_or_none_options = frozenset(['--decrypt',
'--decrypt-files',
'--encrypt',
'--encrypt-files',
'--import',
'--verify',
'--verify-files',
'--output',
])
#: These options expect a string. see :func:`_check_preferences`.
pref_options = frozenset(['--digest-algo',
'--cipher-algo',
'--compress-algo',
'--compression-algo',
'--cert-digest-algo',
'--personal-digest-prefs',
'--personal-digest-preferences',
'--personal-cipher-prefs',
'--personal-cipher-preferences',
'--personal-compress-prefs',
'--personal-compress-preferences',
'--pinentry-mode',
'--print-md',
'--trust-model',
])
#: These options expect no arguments
none_options = frozenset(['--allow-loopback-pinentry',
'--always-trust',
'--armor',
'--armour',
'--batch',
'--check-sigs',
'--check-trustdb',
'--clearsign',
'--debug-all',
'--default-recipient-self',
'--detach-sign',
'--export',
'--export-ownertrust',
'--export-secret-keys',
'--export-secret-subkeys',
'--fingerprint',
'--fixed-list-mode',
'--gen-key',
'--import-ownertrust',
'--list-config',
'--list-key',
'--list-keys',
'--list-packets',
'--list-public-keys',
'--list-secret-keys',
'--list-sigs',
'--lock-multiple',
'--lock-never',
'--lock-once',
'--no-default-keyring',
'--no-default-recipient',
'--no-emit-version',
'--no-options',
'--no-tty',
'--no-use-agent',
'--no-verbose',
'--print-mds',
'--quiet',
'--sign',
'--symmetric',
'--throw-keyids',
'--use-agent',
'--verbose',
'--version',
'--with-colons',
'--yes',
])
#: These options expect either None or a hex string
hex_or_none_options = hex_options.intersection(none_options)
allowed = hex_options.union(unchecked_options, other_options, dir_options,
keyring_options, file_or_none_options,
pref_options, none_options)
if group and group in locals().keys():
return locals()[group] |
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("script_type")
script = attrs.get("script")
if out_vars:
out_vars = out_vars.split(",")
else:
out_vars = attrs.get("eval_variables", None)
task_resources["attrs"] = {"script": script, "script_type": script_type}
if out_vars:
task_resources["attrs"]["eval_variables"] = out_vars
task_payload = {
"spec": {
"name": name,
"description": description or "",
"resources": task_resources,
},
"metadata": {"spec_version": 1, "name": name, "kind": "app_task"},
"api_version": "3.0",
}
return task_payload |
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, boto config name to set, value to set)
If value to set is None, no entry is created.
Returns:
Dictionary of {section: {keys: values}} for writing to the file.
"""
sections = {}
for config_entry in boto_config_list:
section, key, value = (config_entry[0], config_entry[1], config_entry[2])
if section not in sections:
sections[section] = {}
if value is not None:
sections[section][key] = value
return sections |
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 there are pairs of newlines, turn them into one
while s.find(newlines[0] * 2) != -1:
s = s.replace( newlines[0] * 2, newlines[0])
# replace newlines with the newline_replacement above
return s.strip().replace(newlines[0], replacement) |
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 spaces
seq = seq.replace(" ", "")
# Replace with Regex
terms = seq.split(",")
for idx in range(0, len(terms)):
if ":" in terms[idx]:
terms[idx] = _RE1
elif "?*" in terms[idx]:
terms[idx] = _RE2
elif "?" in terms[idx] and not ("?*" in terms[idx]):
num_terms = int(terms[idx].replace("?", ""))
terms[idx] = ""
for d in range(0, num_terms):
terms[idx] = terms[idx] + _RE1 + ","
terms[idx] = terms[idx][0:-1] # remove ',' from the last term
seq_returned = ""
for idx in range(0, len(terms)):
seq_returned += terms[idx] + ","
seq_returned = seq_returned[0:-1]
return seq_returned |
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(" ' ", "'").replace(" n't", "n't").replace(" 'm", "'m").replace(" do not", " don't"
).replace(" 's", "'s").replace(" 've", "'ve").replace(" 're", "'re")
return out_string |
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 * divisor)
# Make sure that round down does not go down by more than 10%.
if new_channels < 0.9 * channels:
new_channels += divisor
return int(new_channels) |
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
elif c == "\t":
here += ts
if here > 0 and (common == None or here < common):
common = here
if not common:
return string
result = None
for l in lines:
removed = 0
rest = l
while removed < common and rest:
c, rest = rest[0], rest[1:]
if c == " ":
removed += 1
elif c == " ":
removed += 4
else:
raise RuntimeWarning("Lost count while removing indentation.")
break
if result == None:
result = rest
else:
result += "\n" + rest
return result |
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 == "}":
brackets -= 1
if brackets < 0:
raise ValueError("Mismatched braces")
if brackets:
raise ValueError("Mismatched braces")
return "".join(output) |
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_value_tbd2} and {input_value_tbd3}
:param {input_value_tbd1}:
:param {input_value_tbd2}:
:param {input_value_tbd3}:
:param static_value:
:return: {output_name}
"""
return input_value_tbd1 + input_value_tbd2 + input_value_tbd3 + static_value |
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 `_` values
for exact matching.
defaults to `%` if not provided.
:rtype: str
"""
if value is None:
return None
return '{start}{value}'.format(start=start, value=value) |
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_module": f"{project}",
"main_score": f"{score_class}"
}
return package_json_dict |
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 if there is only one
flag_bits = flag_defn['bits']
if not isinstance(flag_defn['bits'], list):
flag_bits = [flag_bits]
# The amount to shift flag_value to line up with mask_value
flag_shift = min(flag_bits)
# Mask our mask_value, we are only interested in the bits for this flag
flag_mask = 0
for i in flag_bits:
flag_mask |= (1 << i)
masked_mask_value = mask_value & flag_mask
for flag_value, value in flag_defn['values'].items():
shifted_value = int(flag_value) << flag_shift
if shifted_value == masked_mask_value:
assert flag_name not in return_dict
return_dict[flag_name] = value
return return_dict |
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 = destination.setdefault(key, {})
deep_merge(value, node)
else:
destination[key] = value
return destination |
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 truncated title.
:type continuation: str | None
:rtype: str
.. code-block:: python
from superpython.utils import truncate
title = "This Title is Too Long to Be Displayed As Is"
print(truncate(title))
"""
# Make it safe to submit the string as None.
if string is None:
return ""
# There's nothing to do if the string is not over the limit.
if len(string) <= limit:
return string
# Adjust the limit according to the string length, otherwise we'll still be over.
if continuation:
limit -= len(continuation)
# Return the altered title.
if continuation:
return string[:limit] + continuation
else:
return string[:limit] |
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
"""
return [{"atype": line[:6].strip(),
"index": line[6:11].strip(),
"atom": line[12:16].strip(),
"resid": line[17:20].strip(),
"chain": line[21:22].strip(),
"resseq": int(line[22:26].strip()),
"icode": line[26:27].strip(),
"pos_x": line[30:38].strip(),
"pos_y": line[38:46].strip(),
"pos_z": line[46:54].strip(),
"occ": line[54:60].strip(),
"tfactor": line[60:66].strip(),
"symbol": line[76:78].strip(),
"charge": line[78:79].strip()}
for line in lines] |
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
return obj.__class__.__name__ == "DataFrame" |
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.0])
density = this_matl_data[-1] # per cubic inch
thickness = plate.get("thickness", 1.5)
area = plate.get("area", 0)
volume = thickness * area
plate["mass"] = volume * density
totalmass += plate["mass"]
return totalmass |
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 x: x.get("x_mitre_deprecated", False) is False and x.get("revoked", False) is False,
stix_objects
)
) |
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 a valid string-encoded
version of that type. Returns the unchanged string otherwise.
"""
### the order here is important, but hex that is not prefixed with
### 0x may be misinterpreted as integers.
new_value = value
for cast in (int, float, lambda x: int(x, 16)):
try:
new_value = cast(value)
break
except ValueError:
pass
if value == "True":
new_value = True
elif value == "False":
new_value = False
elif value == "null": # for mmperfmon
new_value = None
return new_value |
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) > 100:
errors.append("Maximum ticket price is $100")
return errors |
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
first j characters of targ
"""
rows = len(source)+1
cols = len(targ)+1
dist = [[0 for x in range(cols)] for x in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for i in range(1, rows):
dist[i][0] = i
# target prefixes can be created from an empty source string
# by inserting the characters
for i in range(1, cols):
dist[0][i] = i
row, col = None, None
for col in range(1, cols):
for row in range(1, rows):
if source[row-1] == targ[col-1]:
cost = 0
else:
cost = 1
dist[row][col] = min(dist[row-1][col] + 1, # deletion
dist[row][col-1] + 1, # insertion
dist[row-1][col-1] + cost) # substitution
assert row and col
return dist[row][col] |
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))}
rtn_dct.update({
key: dict_merge(rtn_dct[key], merge_dct[key], add_keys=add_keys)
if isinstance(rtn_dct.get(key), dict) and isinstance(merge_dct[key], dict)
else merge_dct[key]
for key in merge_dct.keys()
})
return rtn_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 processing to extract file paths
# remove brackets
files = input_str[1:-1]
# split on commas
files = files.split(',')
# strip surrounding spaces and quotes; cast as str type
files = [str(f.strip()[1:-1]) for f in files]
return files |
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(x-a))]
foo = [x for x in list(list_like) if x-a > 0]
z.append(min(foo, key=lambda x : abs(x-a)))
foo = [x for x in list(list_like) if x not in z]
z.append(min(foo, key=lambda x : abs(x-a)))
return sorted(z) |
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])
dec = float(string.split()[1])
coord_sys = string.split(None, 2)[2].strip()
coords = [ra, dec, coord_sys]
return coords |
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)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
Invalid for Linux
/ (forward slash)
.. todo:: do a check for linux
"""
invalid_chars = ':*?<>|/\\'
for char in invalid_chars:
basename = basename.replace(char, '')
return basename |
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 >= num_steps:
return False
# Otherwise, keep going.
return True |
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 = {
'targetName': 'local_file',
'data': {
'temperature': {
'value': temperature,
'updateTime': timestamp,
}
}
}
return 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 == 0:
return 0
elif r1 >= 1:
return 1
else:
return -1 |
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.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'a.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
'p.m.'
"""
if hour < 12:
return "a.m."
return "p.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}\033[0m'.format(
color_code=esc_dict[color],
indent=' '*indent,
text=text
)
)
return '{indent}{text}'.format(indent=' '*indent, text=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: This is quite a rough way to recover the imputed categories,
consider testing and potentially improving it."""
new_col = list(orig_col) # Take vals of orig col, including NAs
for i, j in enumerate(list(orig_col)): # iterate through them
if j != j: # if val is missing then get its imputed value
predicted = list(imputed_col)[i]
# Now distance of pred from all categories
diffs = []
for c in categories:
diffs.append(abs(predicted - c))
min_idx = diffs.index(min(diffs)) # get index of min distance
closest_cat = categories[min_idx] # find corresponding cat
new_col[i] = closest_cat # assign cat to value
return new_col |
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 (0-1)
"""
# originally precision is: ppv = tp / (tp + fp + eps)
# but when both masks are empty this gives: tp=0 and fp=0 => ppv=0
# so here precision is defined as ppv := 1 - fdr (false discovery rate)
return 1 - fp / (tp + fp + eps) |
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_value: Maximum return value.
:return: Rounded int
:rtype: int
"""
vsc = int(val / factor)
vmin = vsc * factor
vmax = (vsc + 1) * factor
if (max_value and vmax > max_value) or abs(val - vmin) < abs(val - vmax):
return vmin
return vmax |
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]
return my_list |
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_prefix, "")
new_content = new_content.replace(lightning_namespace, "c:")
name = name.replace(namespace_prefix, "")
if orig_content != new_content and logger:
logger.info(
" {file_name}: removed {namespace}".format(
file_name=name, namespace=namespace_prefix
)
)
return name, new_content |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.