content stringlengths 42 6.51k |
|---|
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true):
"""
Use the derivative of the binary cross entropy (BCE) loss function.
Parameters
----------
y_predicted : ndarray
The predicted output of the model.
y_true : ndarray
The actual output value.
Return... |
def alwayslist(value):
"""If input value if not a list/tuple type, return it as a single value list."""
if value is None:
return []
if isinstance(value, (list, tuple)):
return value
else:
return [value] |
def quote_arg(arg):
"""Return the quoted version of the given argument.
Returns a human-friendly representation of the given argument, but with all
extra quoting done if necessary. The intent is to produce an argument
image that can be copy/pasted on a POSIX shell command (at a shell prompt).
:par... |
def check_filename(filename):
""" checks if the filename is correct and adapts it if necessary
Parameters:
filename - media filename
return:
string: updated filename
"""
# delete all invaild characters from filename
filename = filename.strip() # rem... |
def pull_all_metrics(email):
"""Obtains list of timestamps/corresponding
processes for a user
Args:
email (str): user email (primary key)
Returns:
all_metrics
"""
# check database
# print list of timestamps/actions
all_metrics = []
return all_metrics |
def minmax(array):
"""Find both min and max value of arr in one pass"""
minval = maxval = array[0]
for e in array[1:]:
if e < minval:
minval = e
if e > maxval:
maxval = e
return minval, maxval |
def list_remove(list_a, list_b):
"""
Fine all elements of a list A that does not exist in list B.
Args
list_a: list A
list_b: list B
Returns
list_c: result
"""
list_c = []
for item in list_a:
if item not in list_b:
list_c.append(item)
return l... |
def nearest_larger(arr, i):
"""Finds the nearest item in `arr` which is larger than arr[i]"""
distance = 1
while True:
left = i - distance
right = i + distance
if (left < 0) and (right >= len(arr)):
return None
if (left >= 0) and (arr[left] > arr[i]):
... |
def ratio(value, count):
"""compute ratio but ignore count=0"""
if count == 0:
return 0.0
return value / count |
def parse_mitie_output(raw_json):
"""
:param dict raw_json: dict of JSON values
:returns list: List of entities
"""
if 'entities' not in raw_json:
return list()
return list(set([elem['text'] for elem in raw_json['entities'] if 'text' in elem])) |
def human_size(size: int) -> str:
"""Converts size in bytes to a human-friendly format."""
if size > 1_000_000_000:
return f"{size / 1_000_000_000:.1f} GB"
if size > 1_000_000:
return f"{size // 1_000_000} MB"
if size > 1_000:
return f"{size // 1_000} KB"
return f"{size} B" |
def fabclass_2_umax(fab_class=None):
# Docstring
"""
Max dimple displacement.
Returns the maximum displacement for a dimple imperfection on a cylindrical shell. The values are taken from table
8.4 of EN1993-1-6[1] for a given fabrication quality class, A, B or C.
Parameters
----------
... |
def update_name(name, mapping):
""" Update the street name using the mapping dictionary. """
for target_name in mapping:
if name.find(target_name) != -1:
a = name[:name.find(target_name)]
b = mapping[target_name]
c = name[name.find(target_name)+len(target_name):]
... |
def depends_on_unbuilt(item, deps, built):
""" See if item depends on any item not built """
if not item in deps:
return False
return any(d not in built for d in deps[item]) |
def str_reindent(s, num_spaces): # change indentation of multine string
"""
if args:
aux= name1+'.'+obj.__name__ +'('+ str(args) +') \n' + str(inspect.getdoc(obj))
aux= aux.replace('\n', '\n ')
aux= aux.rstrip()
aux= aux + ' \n'
wi( aux)
"""
s = s.split("\n")
... |
def output(s: str) -> str:
"""Returns the string output cyan"""
return '\033[96m' + s + '\033[0m' |
def root(num,pow):
"""
Do the roots
"""
return 1.0*num**(1.0/pow) |
def mirror_letter(letter):
""" Returns the letter in the same position on the other
side of the alphabet.
>>> mirror_letter('a')
'z'
>>> mirror_letter('z')
'a'
>>> mirror_letter('B')
'Y'
>>> mirror_letter('C')
'X'
"""
if letter.isupper():
return chr(155 - ord(l... |
def base36encode(num):
"""Converts a positive integer into a base36 string."""
if not isinstance(num, int):
raise TypeError("Positive integer must be provided for base36encode. " + repr(num) + " provided instead.")
if not num >= 0:
raise ValueError('Negative integers are not permitted for ... |
def partition_at_level(dendrogram, level):
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest communities,
and the best is len(dendrogram) - 1.
The higher the le... |
def sign(a, b):
"""Return a with the algebraic sign of b"""
return (b/abs(b)) * a |
def command_friendly_kv_pair(dict):
"""Converts a dictionary into a list of key=value pairs for use in subprocess run"""
# subprocess.run expects parameters to be in the foo=bar format. We build this format here and return a list
output = []
for key, value in dict.items():
output.append('%s=%s' ... |
def optimize_distance_with_mistake(distance: float, mistake: float) -> float:
""" Using mistake to optimize the walk during runtime
Using mistake to shorten or lengthen the walk, but never more then a single hop
"""
distance_diff = (min(mistake, 1) - 0.5) / 0.5
return distance + distance_diff |
def merge(json, firstField, secondField):
"""
merge two fields of a json into an array of { firstField : secondField }
"""
merged = []
for i in range(0, len(json[firstField])):
merged.append({ json[firstField][i] : json[secondField][i] })
return merged |
def hex_to_rgb(col_hex):
"""Convert a hex colour to an RGB tuple."""
col_hex = col_hex.lstrip('#')
return bytearray.fromhex(col_hex) |
def up_diagonal_contains_only_os(board):
"""Check whether the going up diagonal contains only os"""
i = len(board) - 1
j = 0
while i >= 0 and j < len(board):
if board[i][j] != "O":
return False
i -= 1
j += 1
return True |
def iterative_binary_search(data: list, left: int, right: int, key: str) -> int:
"""Iterative Binary Search Implementation"""
while right >= left:
mid = (left + right) // 2
if data[mid] == key:
return mid
elif key < data[mid]:
right = mid - 1
else:
... |
def strip_version(r: str) -> str:
"""
:param r: required package name and required version matcher
:return: just the package name
"""
for symbol in [" ", "~", "<", ">", "="]:
i = r.find(symbol)
if i != -1:
return r[:i].rstrip()
return r |
def lenient_lowercase(lst):
"""Lowercase elements of a list.
If an element is not a string, pass it through untouched.
"""
lowered = []
for value in lst:
try:
lowered.append(value.lower())
except AttributeError:
lowered.append(value)
return lowered |
def concat_classnames(classes):
"""Concatenate a list of classname strings (without failing on None)"""
# SEE: https://stackoverflow.com/a/20271297/11817077
return ' '.join(_class for _class in classes if _class) |
def is_a(cls, x): # noqa: F811
"""
Check if x is an instance of cls.
Equivalent to isinstance, but auto-curried and with the order or arguments
flipped.
Args:
cls:
Type or tuple of types to test for.
x:
Instance.
Examples:
>>> is_int = sk.is_a(... |
def split_pkg(pkg):
"""nice little code snippet from isuru and CJ"""
if not pkg.endswith(".tar.bz2"):
raise RuntimeError("Can only process packages that end in .tar.bz2")
pkg = pkg[:-8]
plat, pkg_name = pkg.split("/")
name_ver, build = pkg_name.rsplit("-", 1)
name, ver = name_ver.rsplit(... |
def calcular_tiempo_recorrido(distancias, velocidad):
"""
Definicion de la funcion calcular_tiempo_recorrido:
Funcion de calculo del tiempo de recorrido
Parametros
----------
distancias: Pandas Dataframe
Dataframe que contiene las distancias entre nodos
... |
def get_starting_datetime_of_timetable(timetable):
"""
Get the starting_datetime of a timetable, which corresponds to
the departure_datetime of the first timetable entry.
:param timetable: timetable_document
:return: starting_datetime_of_timetable: datetime
"""
timetable_entries = timetable... |
def get_lines(filename):
""" return list of lines read from filename
"""
with open(filename) as infile:
return infile.readlines() |
def count_positives_sum_negatives(arr):
"""Return count of postive and sum of negatives"""
return [len([elem for elem in arr if elem > 0]), \
sum([elem for elem in arr if elem < 0])] if arr!=[] else arr |
def html_escape(text):
"""Escape text so that it will be displayed safely within HTML"""
text = text.replace('&','&')
text = text.replace('<','<')
text = text.replace('>','>')
return text |
def smart_pop(word, greek_text):
"""refactor: this used to have some hackish logic to deal with text nodes with no text,
it still prevents a fatal error if something goes wrong and we run out of greeked words
"""
# if we run out of words, just keep going...
if len(greek_text) == 0:
return "E... |
def same_type(t1, t2):
"""
:return bool: True if 't1' and 't2' are of equivalent types
"""
if t1 is None or t2 is None:
return t1 is t2
if not isinstance(t1, type):
t1 = t1.__class__
if not isinstance(t2, type):
t2 = t2.__class__
if issubclass(t1, str) and issubcla... |
def sumList(alist):
"""
To calcualte the sum of a list of numbers.
"""
sum = 0
for value in alist:
sum += value
return sum |
def calcSquaredError(actualResult, forecastResult):
"""
Calculate squared error.
returns float
"""
return (actualResult - forecastResult)**2 |
def _get_rows_helper(iterableObj, key=None):
""" Takes an object and returns a list of rows to use for appending.
:param iterableObj: Iterable
:param key: If iterableObj had a key to assigned it it's given here """
row = [key] if key else []
if isinstance(iterableObj, (list, tuple)):
... |
def get_dict_keys(data, files):
"""
filters all the keys out of data
Args:
data: (list of lists of dictionaries)
files: (list)
Returns:
keys: (list) set of keys contained in data
"""
key_list = []
for i in range(len(data)):
data_file = data[i] # iterating o... |
def round_of_rating(number):
"""Round a number to the closest half integer.
1.5
2.5
3.0
4.0"""
return round(number * 2) / 2 |
def string_validation(state_input, county_input):
"""
WHAT IT DOES: Processes the State and County variables to ensure that they are strings
PARAMETERS: Two strings representing a state and county in the US
RETURNS: A boolean
"""
has_errors = False
try:
int_variable = int(state_in... |
def rx_mix(rx_tuple, value):
"""Build up the regular expression string for the XML
When the value has a % in the lead, we need to build
a tuple and prepare the string for use in building
an XML template for NetLogo invocation.
Otherwise, we are reading the .nlogo file in and just
adding ... |
def getFileDialogTitle(msg
,title):
"""
Create nicely-formatted string based on arguments msg and title
:param msg: the msg to be displayed
:param title: the window title
:return: None
"""
if msg and title:
return "%s - %s" % (title, msg)
if msg and not tit... |
def pad_int_str(int_to_pad: int, n: int = 2) -> str:
"""Converts an integer to a string, padding with leading zeros
to get n characters. Intended for date and time formatting.
"""
base = str(int_to_pad)
for k in range(n - 1):
if int_to_pad < 10 ** (k + 1):
base = "0" + base
r... |
def generate_positionnal_changes_indicator(string1, string2):
""" Generate a string showing the differences between two strings
"""
changes = ""
if len(string1) < len(string2):
string_iteration = string1
string_to_compare = string2
else:
string_iteration = string2
str... |
def bitVector2num(bitVec: list):
"""Convert a bit list to a number.
The list is assumed to be in "MSB-at-index-0" ordering.
Args:
bitVec (list): The bit list that we want to convert to a number.
Returns:
Integer value of input bit vector.
"""
bitStr = ''.join(str(b) for b... |
def group_property_types(row : str) -> str:
"""
This functions changes each row in the dataframe to have the one
of five options for building type:
- Residential
- Storage
- Retail
- Office
- Other
this was done to reduce the dimensionality down to the top building
types.
... |
def get_precision_recall(confusion_table):
"""
Get precision and recall for each class according to confusion table.
:param confusion_table:
:return: {class1: (precision, recall), class2, ...}
"""
precision_recall = {}
relations = confusion_table.keys()
for target_relation in relations:
... |
def air_density(virtual_temperature_k, pressure_hPa):
"""
Calculate the density of air based on the ideal gas law, virtual temperature, and pressure.
Args:
virtual_temperature_k: The virtual temperature in units K.
pressure_hPa: The pressure in units hPa.
Returns:
The density o... |
def to_unit_memory(number):
"""Creates a string representation of memory size given `number`."""
kb = 1024
number /= kb
if number < 100:
return '{} Kb'.format(round(number, 2))
number /= kb
if number < 300:
return '{} Mb'.format(round(number, 2))
number /= kb
return ... |
def edit_distance(word_one, word_two):
"""
Find the edit distance between two words
"""
# short-circuit conditions
if word_one == word_two:
return 0
shorter = min(word_one, word_two, key=len)
longer = max(word_one, word_two, key=len)
if not shorter and longer:
return l... |
def calculate_chunk_slices(items_per_chunk, num_items):
"""Calculate slices for indexing an adapter.
Parameters
----------
items_per_chunk: (int)
Approximate number of items per chunk.
num_items: (int)
Total number of items.
Returns
-------
list of slices
"""
a... |
def sizeof_fmt(num, suffix='B'):
"""
Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection
"""
precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15}
for unit in ['', 'Ki', ... |
def cal_rmse(actual_readings, predicted_readings):
"""Calculating the root mean square error"""
square_error_total = 0.0
total_readings = len(actual_readings)
for i in range(0, total_readings):
error = predicted_readings[i] - actual_readings[i]
square_error_total += pow(error, 2)
rms... |
def get_choice(text = None):
""" gets users choice from a numbered list """
try:
choice = int(input(text if text else "Choose something...\n"))
return choice
except Exception as error:
print("Please don't be a douche, input a valid number.")
return 0 |
def convert(text):
"""Convert digits to alphanumeric text"""
if text.isdigit():
return int(text)
else:
return text |
def sanitize_device(device):
"""returns device id if device can be converted to an integer"""
try:
return int(device)
except (TypeError, ValueError):
return device |
def render_tile(tile):
"""
For a given tile, render its character
:param tile:
:returns str value of tile
"""
# each tile list has the meaning: [Visible (bool), Mine (bool), Adjacent Mines (int)]
# visible, mine, adjacent_mines = tile
if tile[0]:
# if the tile is visible
... |
def _pkg_curated_namespace(package):
"""
Strips out the package name and returns its curated namespace.
"""
return f"curated-{package.split('/', 1)[0]}" |
def _check_if_position_on_board(coord: tuple, board_size: int):
"""
checks whether coordinates are inside of board
:param coord:
:param board_size:
:return:
"""
in_row = coord[0] in range(board_size)
in_col = coord[1] in range(board_size)
return in_row and in_col |
def param_to_string(param):
"""
Helper function for random_generator, creates a string from the param dict
:param param_dict: param_dict from random_generator
:return: string of params
"""
string = "<p>Search results for these parameters: </p>"
if param == {}:
return "<p></p>"
fo... |
def get_spline_knot_values(order):
"""Knot values to the right of a B-spline's center."""
knot_values = {0: [1],
1: [1],
2: [6, 1],
3: [4, 1],
4: [230, 76, 1],
5: [66, 26, 1]}
return knot_values[order] |
def strlen(s):
"""
Returns the length of string s using recursion.
Examples:
>>> strlen("input")
5
>>> strlen("")
0
>>> strlen('123456789')
9
>>> strlen("I love software engineering")
27
>>> strlen('a'*527)
527
... |
def to_from(arr):
"""Convert two elements list into dictionary 'to-from'.
"""
try:
return {'from':arr[0], 'to':arr[1]}
except IndexError:
return None |
def score_sentences(sen1, sen2):
"""
Compares two sentences, find intersection and scores them
:param sen1: (str) sentence
:param sen2: (str) sentence
:returns: score
"""
s1 = set(sen1.lower().split())
s2 = set(sen2.lower().split())
score = 0
if s1 and s2:
avg = len(s1) ... |
def process_data(data):
""" Pre-process the given data to make textual string searches easier. """
return (
data
.lower() # Force lowercase
.replace('/', '\\') # Force backslashes
) |
def assert_lrp_epsilon_param(epsilon, caller):
"""
Function for asserting epsilon parameter choice
passed to constructors inheriting from EpsilonRule
and LRPEpsilon.
The following conditions can not be met:
epsilon > 1
:param epsilon: the epsilon parameter.
... |
def pretty_print_dict(dtmp):
"""Pretty prints an un-nested dictionary
Parameters
----------
dtmp : dict
Returns
-------
str
pretty-printed dictionary
"""
ltmp = []
keys = dtmp.keys()
maxlen = 2 + max([len(K) for K in keys])
for k, v in sorted(dtmp.items(), ... |
def bytes_filesize_to_readable_str(bytes_filesize: int) -> str:
"""Convert bytes integer to kilobyte/megabyte/gigabyte/terabyte equivalent string"""
if bytes_filesize < 1024:
return "{} B"
num = float(bytes_filesize)
for unit in ["B", "KB", "MB", "GB"]:
if abs(num) < 1024.0:
... |
def create_context(machine, arch, scripts_path):
"""
Create a context object for use in deferred function invocation.
"""
context = {}
context["machine"] = machine
context["arch"] = arch
context["scripts_path"] = scripts_path
return context |
def AB2Jy(ABmag):
"""Convert AB magnitudes to Jansky"""
return 10.**(-0.4*(ABmag+48.60))/1e-23 |
def IncludeCompareKey(line):
"""Sorting comparator key used for comparing two #include lines.
Returns the filename without the #include/#import prefix.
"""
for prefix in ('#include ', '#import '):
if line.startswith(prefix):
return line[len(prefix):]
return line |
def format_call(__name, *args, **kw_args):
"""
Formats a function call as a string. (Does not call any function.)
>>> import math
>>> format_call(math.hypot, 3, 4)
'hypot(3, 4)'
>>> format_call("myfunc", "arg", foo=42, bar=None)
"myfunc('arg', foo=42, bar=None)"
@param __na... |
def parse_path_expr(expr):
"""
parses the path expresssion passed, expects path to be separated via forward slashes like
directory traversing i.e. '1/4/10'
"""
if expr is not None:
return [segment for segment in expr.split("/") if segment != ""]
return None |
def delta(vec, elem):
"""
:param vec: list of values
:param elem: value being measured between
:return: list of delta and index pairs
"""
return [(abs(elem-item), i) for i, item in enumerate(vec)] |
def get_new_size(original_size):
"""
Returns each width and height plus 2px.
:param original_size: Original image's size
:return: Width / height after calculation
:rtype: tuple
"""
return tuple(x + 2 for x in original_size) |
def exception_exists(results):
"""Calculate the number of exceptions in the argument 'results'
Args:
results (list)
Retuns:
the number of exceptions in results
"""
if not isinstance(results, list):
raise TypeError(
f'Expected type is list, but the argument type... |
def get_prefixed(strs, prefix):
"""Get all string values with a prefix applied to them.
:param strs: a sequence of strings to be given a prefix.
:param prefix: a prefix to be added to the strings
:returns: a list of prefixed strings
"""
return [prefix + n for n in strs] |
def bezout(a, b):
"""
:return s and t st. sa + tb = (a,b)
"""
s, t, sn, tn, r = 1, 0, 0, 1, 1
while r != 0:
q, r = divmod(a, b)
st, tt = sn * (-q) + s, tn * (-q) + t
s, t = sn, tn
sn, tn = st, tt
a, b = b, r
return s, t |
def dict2list(thedict, parmnames, default=None):
"""
Convert the values in thedict for the given list of parmnames to a list of values.
"""
return [thedict.get(n, default) for n in parmnames] |
def get_pv_status(pv_obj):
"""
Get the status of the pv object
Args:
pv_obj (dict): A dictionary that represent the pv object
Returns:
str: The status of the pv object
"""
return pv_obj.get("status").get("phase") |
def _str2float(s):
"""Cast string to float if it is not None. Otherwise return None.
Args:
s (str): String to convert or None.
Returns:
str or NoneType: The converted string or None.
"""
return float(s) if s is not None else None |
def value_if_found_else_key(some_dict, key):
"""Lookup a value in some_dict and use the key itself as fallback"""
return some_dict.get(key, key) |
def mac_addr_reverse_byte_order(mac_addr):
"""Reverse the byte order of a 48 bit MAC address."""
mac_addr_reversed = 0
for i in range(6):
mac_addr_reversed |= ((mac_addr >> 8*i) & 0xFF) << 8*(5-i)
return mac_addr_reversed |
def get_attr_count(ent, attr_dict, dataset):
"""
calculate count of attributes of given entity
"""
if ent not in attr_dict:
return 0
return len(attr_dict[ent]) |
def wrap_traj(traj, start, length):
"""Wraps the traj such that the original traj starts at frame `start`
and is of length `length` by padding beginning with traj[0] and end with
traj[-1]. Used to test the slice restricted trajectories."""
if (start < 0) or (length < len(traj)+start):
raise Valu... |
def reverse(string):
"""
Reverse the order of the characters in a string.
"""
return string[::-1] |
def spc_queue(runlst, fml):
""" Build spc queue from the reaction lst for the drivers.
Use the formula to discern if run_lst is SPC or PES
:return spc_queue: all the species and corresponding models in rxn
:rtype: list[(species, model),...]
"""
if fml == 'SPC':
_queue = run... |
def is_in_coverage(unixtime, weathers_list):
"""
Checks if the supplied UNIX time is contained into the time range
(coverage) defined by the most ancient and most recent *Weather* objects
in the supplied list
:param unixtime: the UNIX time to be searched in the time range
:type unixtime: int
... |
def filter_keys(item):
"""
Returns first element of the tuple or ``item`` itself.
:param object item: It can be tuple, list or just an object.
>>> filter_keys(1)
... 1
>>> filter_keys((1, 2))
... 1
"""
if isinstance(item, tuple):
return item[0]
return item |
def convert_ds_name(ds):
"""Convert from dataset ID to more easily understood string."""
ref_name = ['T','C','V','L']
if isinstance(ds, str):
ds = ds[-4:]
else:
ds = f'{int(ds):04d}'
for c_idx, c in enumerate(ds):
if c == '0':
ref_name[c_idx] = '-'
return ''.join(ref_name) |
def merge(a, b, path=None):
"""
Merges b into a,
mainly: https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107
"""
path = [] if path is None else path
for key in b:
if key in a:
if isinstance(a[key], list) and isinstance(b[key]... |
def removeDuplicates(nums):
"""
TimeComplexity: O(n)
SpaceComplexity: O(1)
"""
i = 0
for j in range(len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i], nums[j] = nums[j], nums[i]
return nums[0 : i + 1] |
def IsNumber(value):
"""
Return True if value is float or integer number.
"""
return bool(not isinstance(value, bool) and (isinstance(value, int) or isinstance(value, float))) |
def _prepare_json(paths):
"""Prepare json."""
return {
index: [
cosa
for cosa in path
]
for index, path in enumerate(paths)
} |
def keys_from_bucket_objects(objects):
"""Extract keys from a list of S3 bucket objects."""
return [x["Key"] for x in objects if not x["Key"].endswith("/")] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.