content stringlengths 42 6.51k |
|---|
def unique(l):
"""return unique values in a list"""
lu = []
for l1 in l:
if l1 not in lu:
lu.append(l1)
return lu |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*',\
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>... |
def FileName(dir,stat,alg,avg,min,max):
"""get svg graph file name from dimensions.
For stat use 'perf|size(min|avg|max)' used for the y axis.
Use 't' for the dimension used as the timeseries label.
Use 'x' for dimension used as x axis.
Use 'o' for the optimal value for the algorithm.
Use 's' for the stand... |
def hash_djb2(s, seed=5381):
"""
Hash string with djb2 hash function
:type s: ``str``
:param s: The input string to hash
:type seed: ``int``
:param seed: The seed for the hash function (default is 5381)
:return: The hashed value
:rtype: ``int``
"""
hash = seed
for x... |
def convert_ascii_to_alphabet(ascii_index: int):
"""function that converts ascii index to alphabet index"""
# take the index from ascii
# if its (upper/lower) case letter:
first_letter = ""
# upper
if ascii_index <= 90:
first_letter = "A"
else:
first_letter = "a"
# reduce... |
def decode_exit(exit_code):
"""Decodes the exit code returned by os.system() into a tuple
containing the exit status, the signal, and 1 if the core was dumped.
See os.wait() for the specification of exit_code"""
status = exit_code >> 8 # the high byte
signal = exit_code & 0x7f # the lowest ... |
def probability_to_red_green(probability, flip=False):
"""
Given a probability [0, 1], it returns the associated RGB value that corresponds to a
red -> green color scale. This
>>> probability_to_red_green(0)
(255, 0, 0)
>>> probability_to_red_green(1)
(0, 255, 0)
>>> probability_to_red_... |
def handle_error(e):
"""
Handle error message back to the FMU
"""
return 'ERROR: ' + str(e) |
def both_set_and_different(first, second):
"""
If any of both arguments are unset (=``None``), return ``False``. Otherwise
return result of unequality comparsion.
Returns:
bool: True if both arguments are set and different.
"""
if first is None:
return False
if second is No... |
def getUtility(time, informationGain):
"""Utility function which calgulates utility by dividing cost by variance with weight
Input arguments:
time = cost of node
informationGain = gain of node
"""
beta = 4
if informationGain < 1/beta:
informationGain = 1/beta
# return time/... |
def makeReadable(t):
"""squeeze text for readability"""
t = t.strip()
t = t.replace('\n', '\\\\')
if len(t) > 100:
return t[:50] + ' ... ' + t[-50:]
else:
return t |
def crit_gt(val, tol):
"""Greater than tolerance criterion."""
return val > 0 and val < tol |
def get_domain_from_weaviate_url(url: str) -> str:
"""
Get the domain from a weaviate URL.
Parameters
----------
url : str
The weaviate URL.
Of this form: 'weaviate://localhost/objects/28f3f61b-b524-45e0-9bbe-2c1550bf73d2'
Returns
-------
str
The domain.
"""... |
def get_session_logistic_regression(actions, outcomes, times):
"""
:param actions:
:param outcomes:
:param times:
:return:
"""
model = None
accuracy = {'train': 0, 'test': 0}
return model, accuracy |
def recursive_check(fcn, inp, ref, max_depth):
"""
The function to apply a custom function fcn (the 1st input) on each element of inp.
fcn should take two inputs: inp (the 2nd input) and ref (the 3rd input).
inp can be a scalar or a (nested with many nested levels) list or tuple or a range.
... |
def _fileobj_to_fd(fileobj):
"""Return a file descriptor from a file object.
Parameters:
fileobj -- file object or file descriptor
Returns:
corresponding file descriptor
"""
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = int(fileobj.fileno())
... |
def ranks_from_scores(scores):
"""Return the ordering of the scores"""
return sorted(range(len(scores)), key=lambda i: scores[i], reverse=True) |
def makeScanjob(sweepgates, values, sweepranges, resolution):
""" Create a scanjob from sweep ranges and a centre """
sj = {}
nx = len(sweepgates)
step = sweepranges[0] / resolution[0]
stepdata = {'gates': [sweepgates[0]], 'start': values[0] - sweepranges[0] / 2,
'end': values[0] + ... |
def OnlyTests(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles in order to remove
non-test sources."""
if is_dir:
return dent != 'test'
return '_test.' in dent |
def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print(row, end=' ')
else:
print(row)
return None |
def _default_to_dict(mappings):
"""
Convert a mapping collection from a defaultdict to a dict.
"""
if isinstance(mappings, dict):
return {
key: _default_to_dict(value)
for key, value in mappings.items()
}
else:
return mappings |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number < 0:
print(number, ' is invalid, must be greater than or equal to 0')
return None
... |
def line1(lines):
""" convert a string with newlines to a single line with ; separating lines
the double-quote needs to be removed...
"""
return lines.replace('\n',';').replace('"','') |
def list_difference (l, r) :
"""Compute difference of `l` and `r`.
>>> list (range (3)), list (range (2, 5))
([0, 1, 2], [2, 3, 4])
>>> list_difference (range (3), range (2, 5))
[0, 1]
>>> list_difference (range (10), range (3))
[3, 4, 5, 6, 7, 8, 9]
"""
rs = set (... |
def _build_snapshot_tree(snapshots):
"""
Builds a tree fro the given snapshot.
Parameters
----------
snapshots : `list` of ``BaseSnapshotType``
The snapshot to build tree from.
Returns
-------
snapshot_tree : `dict` of (``client``, `dict` of (`type`, ``BaseSnapshotType`... |
def calculate_rate_delay(rate_limit: float) -> float:
"""
Calculate the rate delay for each request given rate limit in request per minute
:param rate_limit: Rate limit in requests per minute
:return: Rate delay in seconds per request
"""
return 1 / rate_limit * 60 |
def get_buildings_with_sunset_view(buildings):
"""
Question 9.7: Design an algorithm that processes
buildings in east-to-west order and returns the
set of buildings which view the sunset. Each
building is specified by its height.
"""
building_stack = []
# when we get new building, we po... |
def check_pwd(password: str) -> bool :
"""Checks the passwords on certain stipulations and returns the boolean value"""
upper = [u_count for u_count in password if u_count.isupper()]
lower = [l_count for l_count in password if l_count.islower()]
if password[0].isdigit() and len(password) >= 4:
... |
def insertion_sort(lst):
"""Returns a sorted array.
A provided list will be sorted out of place. Returns a new list sorted smallest to largest."""
for i in range (1, len(lst)):
current_idx = i
temp_vlaue = lst[i]
while current_idx > 0 and lst[current_idx - 1] > temp_vlaue:
... |
def get_progress_for_repre(repre_doc, active_site, remote_site):
"""
Calculates average progress for representation.
If site has created_dt >> fully available >> progress == 1
Could be calculated in aggregate if it would be too slow
Args:
repre_doc(dict): representation... |
def build_full_pattern(global_pattern, value, to_record=False):
"""
Builds the pattern by merging the data type and field with the value dependig on the data.
Ex: if the data is xml and the field is Name the return will be <Name>value</Name>.
"""
data = global_pattern['data']
field = global_pa... |
def parse_arg_array(arguments):
"""
Parses array of arguments in key=value format into array
where keys and values are values of the resulting array
:param arguments: Arguments in key=value format
:type arguments: list(str)
:returns Arguments exploded by =
:rtype list(str)
"""
resu... |
def glob_to_regex(pattern):
"""Given a glob pattern, return an equivalent regex expression.
:param string glob: The glob pattern. "**" matches 0 or more dirs recursively.
"*" only matches patterns in a single dir.
:returns: A regex string that matches same paths as the input glob does.
"""... |
def is_superset(token, tokens):
"""If a token is a superset of another one, don't include it."""
for other in tokens:
if other == token:
continue
if other in token:
return True
return False |
def get_app_from_rq_name(name):
"""
Returns an app's env, name, role for a given RQ name
>>> sorted(get_app_from_rq_name('prod:App1:webfront').items())
[('env', 'prod'), ('name', 'App1'), ('role', 'webfront')]
"""
parts = name.split(':')
return {'env': parts[0], 'name': parts[1], 'role': pa... |
def reestructure_cameras(config_dict):
"""Ensure that all [Source_0, Source_1, ...] are consecutive"""
source_names = [x for x in config_dict.keys() if x.startswith("Source")]
source_names.sort()
for index, source_name in enumerate(source_names):
if f"Source_{index}" != source_name:
... |
def _get_resize(input_size, img_size):
"""Copies a resized and properly zero-padded image to a model's input tensor.
Args:
interpreter: The ``tf.lite.Interpreter`` to update.
size (tuple): The original image size as (width, height) tuple.
resize: A function that takes a (width, height) tuple, ... |
def containsExploit(text: str) -> bool:
""" Returns whether or not the given str contains evidence that it is an open redirect exploit """
return ('https://' in text.lower() or
'http://' in text.lower() or
'javascript:' in text.lower() or
'example.com' in text.lower()) |
def flatten_ds(ds_dict, schema):
"""
Flatten dialogue state from dict to sequence.
Args:
ds_dict(dcit): The dialogue state dict.
schema(dict): The schema of the current dataset.
Returns:
ds_seq(list): The sequence of dialogue state after flattening.
"""
ds_seq = []
... |
def _not_equal_goals(goals1, goals2):
"""Return true, if the goals are equal"""
for s in goals1:
if s not in goals2:
return True
return False |
def get_action_name_from_action(action):
"""
Returns the lowercase action name from a service:action combination
:param action: ec2:DescribeInstance
:return: describeinstance
"""
service, action_name = action.split(':')
return str.lower(action_name) |
def proper_path(path):
"""
Clean up the path specification so it looks like something I could use.
"./" <path> "/"
"""
if path.startswith("./"):
pass
elif path.startswith("/"):
path = ".%s" % path
elif path.startswith("."):
while path.startswith("."):
pat... |
def eqhash(o):
"""Call ``obj.__eqhash__``."""
try:
return o.__eqhash__()
except AttributeError:
return hash(o) |
def adjust_threshold(threshold: float,
flag_imp: bool,
flag_explore: bool,
n_accepted: int,
n_improved: int,
num_exchanges: int,
improving_params: list,
exploring_params: li... |
def bits_to_word(bits):
"""Convert a list or array of bits to an integer.
Parameters:
bits: List or array of bits, starting with least-significant bit.
Returns:
Unsigned integer value of the bits.
"""
v = 0
p = 1
for b in bits:
if b:
v += p
p *= ... |
def cross_multiply(x1:float, x2:float, y1:float):
"""
Given a fraction that looks like
a/b = c/d, returns d = bc/a, as shown below
x1 x2
y1 output
"""
return (y1 * x2) / x1 |
def index_by(f, xs):
"""Given a function that generates a key, turns a list of objects into an
object indexing the objects by the given key. Note that if multiple
objects generate the same value for the indexing key only the last value
will be included in the generated object.
Acts as a transducer i... |
def trapezoidal(f, a, b, n):
"""
Evaluates the integral of f, with endpoints a and b, using the trapezoidal
rule with n sample points.
@type f: function
@param f: function integrate
@type a: number
@param a: start of interval
@type b: number
@param b: end of interval
@type n... |
def hello ( name ):
""" Say hello ."""
return " hello " + name |
def weighted_average_cost_of_capital(cost_of_common, cost_of_debt, cost_of_preferred, weights_dict):
"""
Summary: Calculate a firm's wACC.
PARA cost_of_common: The firm's cost of common equity.
PARA type: float
PARA cost_of_debt: The firm's cost of debt.
PARA type: float
PARA ... |
def quote_etag(etag):
"""
Wraps a string in double quotes escaping contents as necesary.
"""
return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') |
def printHumanReadableSize(nbytes):
""" Prints the number of bytes in a human readable way.
parameter
nbytes : number of bytes
return
the size with respect to B, KB, MB, GB, TB and PB.
"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
if nbytes == 0: return '0 B'
i = 0
w... |
def _is_paired(fastq, fastq2, single_end):
"""Determines the workflow based on file inputs.
Args:
"""
if fastq and fastq2:
paired_end = True
interleaved = False
elif single_end:
paired_end = False
interleaved = False
else:
paired_end = True
inter... |
def _generate_string_to_sign(method, path, params):
"""
Generate a string that can be signed to produce an
authentication signature.
:param method: HTTP method
:param path: path part of HTTP request URI
:param params: querystring parameters
:return: string to sign
"""
return '{metho... |
def read_line2sample_list(header_line):
"""
Parse header of VCF file to return sample names found in file.
Args:
header_line (str): Header line from VCF file.
Returns:
vcf_samples (list of str): List of samples with data in VCF file.
Reference:previously: get_vcf_samples
"""
... |
def _householder_factor(newton, halley, hh3):
"""
:param newton:
:param halley:
:param hh3:
:return:
"""
return (1 + 0.5 * halley * newton) / (1 + newton * (halley + hh3 * newton / 6)) |
def end_record(line):
"""return CIF file end-of-file record"""
this_object = {'ID': line[0:2]}
return this_object |
def round(r, g, b):
"""
arrondit chaque couleur
"""
return (int(r), int(g), int(b)) |
def _rst_underline(text, markup):
"""Add and underline RsT string matching the length of the given string.
"""
return text + '\n' + markup * len(text) |
def freq_to_ppm(f, water_hz=0.0, water_ppm=4.7, hz_per_ppm=127.680):
"""
Convert a set of numbers from frequenxy in hertz to chemical shift in ppm
"""
return water_ppm - (f - water_hz)/hz_per_ppm |
def list_remove_duplicates(dup_list):
"""Remove duplicates from a list.
Args:
dup_list (list): List.
Returns:
list: Return a list of unique values.
"""
return list(set(dup_list)) |
def check_regular_intervals(date_str):
"""If a recurring task that repeats at regular intervals from the original task date is completed, it will not have an '!'"""
if '!' not in date_str:
return 1 |
def keep_only_digits(input_string: str) -> str:
"""This function takes as input a string and returns the same string but only containing digits
Args:
input_string (str): the input string from which we want to remove non-digit characters
Returns:
output_string (str): the output string that on... |
def only_ascii(string):
""" Returns only ASCII encoded characters """
return "".join([c for c in string if ord(c) < 127]) |
def crc16(s):
"""
Compute ITU-T CRC16
"""
crc = 0
for b in s:
b = ord(b)
crc = crc ^ (b << 8)
for i in range(0, 8):
if crc & 0x8000 == 0x8000:
crc = (crc << 1) ^ 0x1021
else:
crc = crc << 1
crc =... |
def dict_keys_to_str(dictionary):
""" Recursively converts dictionary keys to strings """
if not isinstance(dictionary, dict):
return dictionary
return dict((str(k), dict_keys_to_str(v))
for k, v in dictionary.items()) |
def avg_pressure(start, end):
"""returns average pressure from ATAstart to ATAend"""
return round((start + end) / 2, 2) |
def _split_ns_command(cmd_token):
"""
Extracts the name space and the command name of the given command token.
:param cmd_token: The command token
:return: The extracted (name space, command) tuple
"""
namespace = None
cmd_split = cmd_token.split('.', 1)
if len(cmd_split) == 1:
... |
def _attr(number):
"""Generates ARB assembly for a vertex attribute. """
return 'vertex.texcoord[{}]'.format(number) |
def toggle_sidebar(click, state):
"""Toggles sidebar based on click and the state of the sidebar
Args:
click (int): Click
state (str): Sidebar state
Returns:
str: Sidebar css className
str: Content css className
str: Sidebar state
str: Button text
"""
... |
def serial_escape(value):
"""Escape string values that are elements of a list, for serialization."""
return value.replace('\\', r'\\').replace(' ', r'\ ') |
def getROPFlux(spc_rop_dict, species_string, rxn_index):
"""
get the flux (numpy:array) for a given species and given rxn
"""
if species_string in spc_rop_dict:
flux_tup_list = spc_rop_dict[species_string]
for flux_tup in flux_tup_list:
header = flux_tup[0]
rxnNum... |
def reject_fairness(experiment):
"""using the 5% significance levels"""
num_heads = len([flip for flip in experiment if flip])
return num_heads < 469 or num_heads > 531 |
def get_mode_dict_from_list(modes_resouces):
"""
Takes in a list of modes and returns a dictionary of them indexed by their IDs
Parameters
----------
modes_resouces : list
a list of modes
"""
return {mode.id: mode for mode in modes_resouces} |
def lowercase_first(s: str):
"""Lowercase the first letter of a string"""
return s[0].lower() + s[1:] |
def calc_distance_lat(lat1, lat2):
"""Returns a distance between 2 latitudes"""
dlat = lat2 - lat1
dist = dlat * 60 * 1852
return dist |
def list_br_html_addition(l: list):
"""
Replace the /n by the <br> HTML tag throughout the list.
Argument:
:param l (list) List of compilation results
:return: updated list - <br> HTML tags added
"""
for sublist in l:
for i in range(len(sublist)):
if isinstance(su... |
def list_by_force(v):
"""Convert any non-iterable object into a list."""
try:
iter(v)
return v
except TypeError:
return [v] |
def generateIndices(elemList, elems):
"""
Generate the indices of label according to labelList. If some element appears more than once, then take indices in order
Parameters
----------
elemList : list of any
Index of which is asked.
elems : list of any
For each element in elems,... |
def f(xx, uu, uuref, t, pp):
""" Right hand side of the vectorfield defining the system dynamics
:param xx: state
:param uu: input
:param uuref: reference input (not used)
:param t: time (not used)
:param pp: additionial free parameters (not used)
:return: ... |
def clean_raw_telnet(telnet_output):
"""Clean raw telnet output from a brstest session
:param telnet_output: List of raw (decoded) telnet lines
:return: List of cleaned output lines, with empty lines removed
"""
split_str = "".join(telnet_output).split("\r\n")
while split_str.count("") > 0:
... |
def str2tuple(idx_str):
"""
Convert a miller index string to a tuple.
Arguments
---------
idx_str: str
String for miller index such as "1,1,1"
Returns
-------
tuple
Returns integer tuple such as (1,1,1)
"""
idx = []
temp_idx = ""
for ch... |
def cm2inch(*tupl):
"""
Specify figure size in centimeter in matplotlib.
Source: http://stackoverflow.com/a/22787457/395857
:param tupl:
:return:
"""
inch = 2.54
if type(tupl[0]) == tuple:
return tuple(i / inch for i in tupl[0])
else:
return tuple(i / inch for i in... |
def l2_loss(out, target):
""" computes loss = (x - y)^2 """
return (target - out) ** 2 |
def format_location(text):
"""Replace all the spaces with plus signs."""
return text.replace(' ', '+') |
def check_answer(guess, a_followers, b_followers):
"""Take the user guess and follower counts and returns if they got it right."""
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b" |
def _splice_s(array, *args):
"""Implementation of splice function in scalar context"""
offset = 0;
if len(args) >= 1:
offset = args[0]
length = len(array)
if len(args) >= 2:
length = args[1]
if offset < 0:
offset += len(array)
total = offset + length
if... |
def _format_erand(erand):
""" Reverse erang and return uppercase."""
erand = erand.replace('hex(b):', '')
erand_parts = erand.split(',')
erand_parts.reverse()
hex_str = ''.join(erand_parts)
dec = int(hex_str, 16)
return dec |
def protein_file_stats_filename(setname):
"""Return the name of the protein stat file."""
if setname is None:
return "protein_files.tsv"
return f"{setname}-protein_files.tsv" |
def result_to_tricks(result: int, level: int):
"""
Convert a result to tricks made, e.g. +1 in a
3 level contract becomes 10
"""
return 6 + level + result |
def reverse(lst):
"""
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
>>> reverse(reverse([1, 2, 3, 4]))
[1, 2, 3, 4]
"""
return lst[::-1] |
def format_coordinates(feature_collection):
"""
Format coordinates of feature to match ohsome requirements
:param feature:
:return:
"""
features = feature_collection["features"]
geometry_strings = []
for feature in features:
if feature["geometry"]["type"] == "Polygon":
... |
def reverse(seq):
"""Reverse the sequence of integers."""
next_int = seq.find(' ')
if next_int == -1:
return "0"
num = int(seq[0:next_int])
if num == 0:
return str(num)
return reverse(seq[next_int + 1:]) + " " + str(num) |
def get_uuids(things):
"""
Return an iterable of the 'uuid' attribute values of the things.
The things can be anything with a 'uuid' attribute.
"""
return [thing.uuid for thing in things] |
def anagrams(w):
"""group a list of words into anagrams
:param w: list of strings
:returns: list of lists
:complexity:
:math:`O(n k \log k)` in average, for n words of length at most k.
:math:`O(n^2 k \log k)` in worst case due to the usage of a dictionary.
"""
w = list(set(w))... |
def extract_single_worded_key(dictionary, key):
""" verify that key is in dictionary and its value is a single word """
if key in dictionary:
value = dictionary[key]
if not isinstance(value, str):
raise RuntimeError('\'{}\' of injected file must be a string, but got {}'
... |
def clean_and_split_input(input):
""" Removes carriage return and line feed characters and splits input on a single whitespace. """
input = input.strip()
input = input.split(' ')
return input |
def getMedian(alist):
"""get median value of list alist"""
tmp = list(alist)
tmp.sort()
alen = len(tmp)
if (alen % 2) == 1:
return tmp[alen // 2]
else:
return (tmp[alen // 2] + tmp[(alen // 2) - 1]) / 2 |
def has_documentation(dir_list):
"""
Checks for a directory specifically named 'docs'
"""
for d in dir_list:
if d == 'docs':
return True
return False |
def _min_orbitals(z):
"""Get the minimum number of harmonic oscillator orbitals for a given Z.
This is a port from the function Nmin_HO in it-code-111815.f.
:param z: proton or neutron number
:return: minimum number of harmonic oscillator orbitals
"""
z_rem = z
n_min = 0
n = 0
while ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.