content stringlengths 42 6.51k |
|---|
def flatten(lst):
"""Flat list out of list of lists."""
return [item for sublist in lst for item in sublist] |
def col(dict_2d, col_key):
""" returns a dict of the contents of column **col_key** of dict_2d """
column = {}
row_keys = dict_2d.keys()
for r in row_keys:
column[r] = dict_2d[r][col_key]
return column |
def jaccard(a, b):
"""
Calculate the jaccard coefficient of two sets.
"""
(a, b) = (set(a), set(b))
n = len(a & b) # intersection
d = len(a | b) # union
if d == 0:
return 1
return n / d |
def normalize_dataset(performance: list, variance: float, median: float):
"""Normalizes the performance obtain in a given dataset"""
return [(p - median) / variance for p in performance] |
def trunc(s, length):
"""Truncate a string to a given length.
The string is truncated by cutting off the last (length-4) characters
and replacing them with ' ...'
"""
if s and len(s) > length:
return s[:length - 4] + ' ...'
return s or '' |
def run_maze(maze, i, j, solutions):
"""
This method is recursive method which starts from i and j
and goes with 4 direction option up, down, left, right
if path found to destination it breaks and return True
otherwise False
Parameters:
maze(2D matrix) : maze
i, j : coordinates o... |
def _tags_arg(string):
"""Pulls out primary tag (first tag) from the others"""
tags = string.split(',')
return (tags[0], set(tags[1:])) |
def _any_none(*args):
"""Returns a boolean indicating if any argument is None"""
for arg in args:
if arg is None:
return True
return False |
def clean_sequence(seq):
"""Clean up provided sequence by removing whitespace."""
return seq.replace(' ', '') |
def convert_column_to_stat_var(column, features):
"""Converts input CSV column name to Statistical Variable DCID."""
s = column.split('!!')
sv = []
base = False
for p in s:
# Set base SV for special cases
if not base and 'base' in features:
if p in features['base']:
... |
def one_hot_encoding(x, allowable_set, encode_unknown=False):
"""One-hot encoding.
Parameters
----------
x
Value to encode.
allowable_set : list
The elements of the allowable_set should be of the
same type as x.
encode_unknown : bool
If True, map inputs not in th... |
def convertOnOffStatement(v):
"""
Receive the value about average on/off
and return "ON" or "OFF"
Args:
v: returned integer 0 or 1
"""
if int(v)==0:
return "OFF"
elif int(v)==1:
return "ON" |
def check_keys_in_dict(keys, map):
""" Check if all keys are present in a dictionary.
"""
return all([key in map for key in keys]) |
def cmd_with_properties(commandline):
"""Add extra arguments that use `trial` and `exp` properties"""
cmd_args = commandline
cmd_args.extend(["--trial-name", "{trial.hash_name}", "--exp-name", "{exp.name}"])
return cmd_args |
def time_format(num, digits=1, align_unit=False):
# type: (float, int, bool) -> str
"""Format and scale output according to standard time
units.
Example
-------
>>> time_format(0)
'0.0 s'
>>> time_format(0, align_unit=True)
'0.0 s '
>>> time_format(0.002)
'2.0 ms'
>>> t... |
def indent(code, level):
"""
indent code to the given level
"""
return code.replace("\n", "\n" + (" "*level)) |
def is_eresource_callno(callno: str) -> bool:
"""
Checks if call number is for electronic resource
Args:
callno: call number string
Returns:
bool
"""
try:
norm_callno = callno.lower()
except AttributeError:
return False
if norm_c... |
def float_from_str(string):
"""
Extract a float from a given String. Decimal is ',' and Thousand
seperator is ".".
:returns: float -- The extracted number
>>> extract_float("The number is 12.567,57.")
12567.57
"""
import re
pattern = re.compile(r"\b[0-9]{1,3}(\.[0-9]{3})*(,[0-9]+)... |
def connect_the_dots(pts):
"""given a list of tag pts, convert the point observations to
poly-lines. If there is only one pt, return None, otherwise connect
the dots by copying the points and offseting by 1, producing N-1 line
segments.
Arguments: - `pts`: a list of point observations of the
f... |
def _is_dunder(name):
"""
A copy of enum._is_dunder from Python 3.6.
Returns True if a __dunder__ (double underscore) name, False otherwise.
"""
return (len(name) > 4 and
name[:2] == name[-2:] == '__' and
name[2] != '_' and
name[-3] != '_') |
def pretty_time(dt):
"""
Returns a human readable string for a time duration in seconds.
:param dt: duration in seconds
"""
if dt > 3600:
hours = dt / 3600.
if hours > 9:
return '%dh' % (int(hours))
minutes = 60 * (hours - int(hours))
return '%dh%2dm' % (i... |
def encased(message, marker):
"""Return string 'message' encased in specified marker at both ends.
>>> encased("hello", "**")
'**hello**'
:message: the string to be encased
:marker: the string to encase with
:returns: 'message' encased in markers
"""
return marker + message + marker |
def extractFolders(folders):
"""
convert a string of folders to a list of tuples (db , schema, node)
:param folders: a string containing folders db-schema-node seperated by ,
:return: a list of tuples (db , schema, node)
"""
output = []
folderList = folders.split('-')
for folde... |
def adjust_size(back_height):
"""
adjust scale(version) for QR code to 1-40.
Parameters
------
back_height: int
height of background wallpaper
"""
ver = int(back_height/300+0.5)
if ver == 0:
ver += 1
elif ver > 39:
ver = 39
return ver |
def fcur(input):
"""
Format CURrency
"""
if int(input) == input:
value = str(int(input))
else:
value = r"{:20,.2f}".format(input)
return rf"${value.strip()}" |
def hexbyte_2integer_normalizer(first_int_byte, second_int_btye):
"""Function to normalize integer bytes to a single byte
Transform two integer bytes to their hex byte values and normalize
their values to a single integer
Parameters
__________
first_int_byte, second_int_byte : int
inte... |
def remove_empty_arrays(movies_names_wl):
"""
This function takes movies_names_wl and removes empty arrays.
"""
for movie in movies_names_wl:
if(movie == []):
movies_names_wl.remove(movie)
return movies_names_wl |
def _get_gcs_path(base_path, content_type, root_id, timestamp):
"""Generate a GCS object path for CAI dump.
Args:
base_path (str): The GCS bucket, starting with 'gs://'.
content_type (str): The Cloud Asset content type for this export.
root_id (str): The root resource ID for this export... |
def compute_frequencies(words):
"""
Args:
words: list of words (or n-grams), all are made of lowercase characters
Returns:
dictionary that maps string:int where each string
is a word (or n-gram) in words and the corresponding int
is the frequency of the word (or n-gram... |
def _mode(basemode, label):
"""Return the trace mode given a base mode and label bool.
"""
if label:
return basemode + "+text"
else:
return basemode |
def is_cjk(character):
""""
Checks whether character is CJK.
>>> is_cjk(u'\u33fe')
True
>>> is_cjk(u'\uFE5F')
False
:param character: The character that needs to be checked.
:type character: char
:return: bool
"""
return any([start <= ord(character) <= end for start, end in
[(4352, 4607), (11904, ... |
def query_tw_field_exists(field):
"""ES query within documents pulled from Twitter API v2
Args:
field (str)
Returns:
ES query (JSON)
"""
return {
"query": {
"bool": {
"filter": [
{"term": {"doctype": "tweets2"}},
... |
def named_capture(pattern, name):
""" generate a named capturing pattern
:param pattern: an `re` pattern
:type pattern: str
:param name: a group name for the capture
:type name: str
:rtype: str
"""
return r'(?P<{:s}>{:s})'.format(name, pattern) |
def valid_model_name(name, opt, step=0):
"""
chcek if a sting is valid checkpoint name.
naming pattern: $NAME_acc_XX.YY_ppl_XX.YY_eZZ.pt
:param name: name of the checkpoint
:param opt: parser
:return: return True if the name if valid else False.
"""
parts = name.strip().split('_')
if... |
def num_shifts_in_stack(params):
"""Calculate how many time points (shifts) will be used in loss functions.
Arguments:
params -- dictionary of parameters for experiment
Returns:
max_shifts_to_stack -- max number of shifts to use in loss functions
Side effects:
None
... |
def escape_split(sep, argstr):
"""
Allows for escaping of the separator: e.g. task:arg='foo\, bar'
It should be noted that the way bash et. al. do command line parsing, those
single quotes are required.
Copy from fabric 1.14
"""
escaped_sep = r"\%s" % sep
if escaped_sep not in argstr:... |
def _schema_to_keys(s):
"""Return the entry keys for schema of dict type."""
def _get_d(s):
d = s
while hasattr(d, 'schema'):
d = s.schema
return d
d = _get_d(s)
if not isinstance(d, dict):
return None
return (_get_d(ss) for ss in d.keys()) |
def quotestr(v):
"""Quote a string value to be output."""
if not v:
v = '""'
elif " " in v or "\t" in v or '"' in v or "=" in v:
v = '"%s"' % v.replace(r'"', r"\"")
return v |
def _convert_y(latitude):
""" convert latitude to y """
return -68.75659401 * latitude + 2782.239846283 |
def compute_avg_over_multiple_runs(number_episodes, number_runs, y_all_reward, y_all_cum_reward, y_all_timesteps):
"""
Compute average of reward and timesteps over multiple runs (different dates)
"""
y_final_reward = []
y_final_cum_reward = []
y_final_timesteps = []
for array_index in range(... |
def is_blank_or_comment(x):
"""Checks if x is blank or a FASTA comment line."""
return (not x) or x.startswith("#") or x.isspace() |
def find_empty(board):
"""Function to find empty cells in game board.
Args:
board (list): the current game board.
Returns:
(i, j) (tuple): empty position (row, column) if found, otherwise None.
"""
for i in range(len(board)):
for j in range(len(board[0])):
... |
def format_message(
text: str,
*args, no_arg_phrase: str = "None",
enclosing_char: str = "`") -> str:
"""Construct message from given text with inserting given args to it and
return resulting message.
Args:
text:
Main message text with formatting brackets `{... |
def format_subpattern(subpattern: dict) -> list:
"""Sort layers of each subpattern and convert to tuple"""
formatted = list()
for _, color_layers in subpattern.items():
formatted.append(tuple(sorted(color_layers)))
return formatted |
def gff3_attributes(att):
"""
Process the attributes column into a dict of key - list(values) pairs
:param att: str
:return attribute_dict: dict
"""
att_arr = att.split(";") # Break K=V;K=V;K=V into key-value pairs
if len(att_arr) == 0:
return None
attribute_dict = dict()
fo... |
def parse(tokens):
"""
Parses a list of tokens, constructing a representation where:
* symbols are represented as Python strings
* numbers are represented as Python ints or floats
* S-expressions are represented as Python lists
Arguments:
tokens (list): a list of strings rep... |
def isSubListInListWithIndex(sublist, alist):
"""
Predicates that checks if a list is included in another one
Args:
sublist (list): a (sub)-list of elements.
alist (list): a list in which to look if the sublist is included in.
Result:
(True, Index) if the sublist is included in the l... |
def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... |
def path(keys, dict):
"""Retrieve the value at a given path"""
if not keys:
raise ValueError("Expected at least one key, got {0}".format(keys))
current_value = dict
for key in keys:
current_value = current_value[key]
return current_value |
def recursive_binary_search(l:list, item):
"""Use binary search with recursion."""
if len(l) < 2:
return 0 if len(l) == 1 and item == l[0] else None
else:
mid = len(l) // 2
if item == l[mid]:
return mid
elif item > l[mid]:
return recursive_binary_searc... |
def encode(number, base):
"""
Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)
NOTE: For the purpose of this function we keep remaind... |
def addFloat2String(value, val_len, decimal_len, front):
"""
Function for parsing a float into a correct string format. Front works as the parser character which tells the program how the string has to be formatted.
**Examples**::
>> addFloat2String(0.71, 6, 3, '>')
" 0.710"
:para... |
def convert_to_base(num, base):
"""
Converts integer num into base b format
ie number to configuration
Args:
num - intger to be converted
base - base to be converted into
Returns:
base b representation of num
"""
convStr = "0123"
if num < base:
return str(... |
def _merge_dicts(a, b, path=None, overwrite=True):
"""
like _join_dicts, but works for any nested levels
copied from: https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge
"""
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key],... |
def get_xp(lvl):
"""
Returns total XP according to gain level
"""
total_xp = int((lvl * 10) ** 1.1)
return total_xp * lvl |
def selfDescriptiveNumber(num):
"""
-- Self-Descriptive Number
-- See: http://en.wikipedia.org/wiki/Self-descriptive_number
-- Checks if the given number is self-descriptive
-- num : a number, in base 10
-- returns : true if the number is self-descriptive, false otherwise
"""
sdNum=0 #create self-des... |
def master_func(x, m, p):
"""
master function to be fit
refer to the Supplementary Note for a justification
"""
return m * (1 - ((m - p) / m) ** x) |
def normalize_memory_value(mem_string):
"""
Returns memory value in Gigabyte
"""
if mem_string[-1] == 'G':
return float(mem_string[:-1])
elif mem_string[-1] == 'M':
return float(mem_string[:-1])/1024.0
elif mem_string[-1] == 'K':
return float(mem_string[:-1])/(1024*1024.0... |
def float_input(input_str):
"""
Parse passed text string input to float
Return None if input contains characters apart from digits
"""
try:
input_val = float(input_str)
except ValueError:
input_val = None
return input_val |
def isfloat(instr):
""" Reports whether a string is floatable """
try:
_ = float(instr)
return(True)
except:
return(False) |
def where2(value1, value2, ls, interval):
"""Find where the value1 and value2 are located in ls, where the interval between neighboring elements are given.
This function may be faster than where, but might be slower in case that the interval is irregular.
This function returns the slice of ls betw... |
def mirror_distance_object(focal_point,distance_image):
"""Usage: Find distance of object with focal point and distance of image"""
numerator = focal_point * distance_image
denominator = distance_image - focal_point
return numerator / denominator |
def transpose(matrix):
"""Takes a 2D matrix (as nested list) and returns the transposed version.
Parameters
----------
matrix :
Returns
-------
"""
return [list(val) for val in zip(*matrix)] |
def build_trigram(words):
"""
build up the trigrams dict from the list of words
:param words: a list of individual words in order
:returns: a dict with:
keys: word pairs in tuples
values: list of the words that follow the pain in the key
"""
# Dictionary for trigram results:
... |
def bound_between(min_val, val, max_val):
"""Bound value between min and max."""
return min(max(val, min_val), max_val) |
def getCall(row):
"""
Return a call dictionary representing the call.
Assuming that row is an array having 4 elements
"""
return (row[0], row[1], row[2], row[3]) |
def results_basename(search_id):
""" Generate the base name for the download file """
basename = 'results-{}.csv'.format(search_id)
return basename |
def make_polymer(starting_dict, reference_dict_, n):
"""Creates the polymer by doing n steps"""
if n == 0:
return starting_dict
else:
#print(starting_dict)
n_dict = starting_dict.copy()
for key in starting_dict.keys():
val = starting_dict[key]
... |
def one_hand_hash(x, y):
"""
Use hash; more space; Bad solution since hashing is order invariant 'pale' and 'elap' will returned the same
:param x: string
:param y: string
:return:
"""
if x == y:
return True
# Fill dict of chars from the first string
cnt = {}
for ch in x... |
def as_float(value):
""" Converts a value to a float if possible
On success, it returns (converted_value, True)
On failure, it returns (None, False)
"""
try:
return float(value), True
except Exception as exception: # Catch all exception including ValueError
return No... |
def is_numeric(s):
"""Returns true if a value can be converted to a floating point number"""
try:
float(s)
return True
except ValueError:
return False
except TypeError:
print('ERROR: Must have null value in working dictionary')
return False |
def _LeftMostFace(holes, points):
"""Return (hole,index of hole in holes) where hole has
the leftmost first vertex. To be able to handle empty
holes gracefully, call an empty hole 'leftmost'.
Assumes holes are sorted by softface."""
assert(len(holes) > 0)
lefti = 0
lefthole = holes[0]
... |
def _ExtractPatternsFromFiletypeTriggerDict( triggerDict ):
"""Returns a copy of the dictionary with the _sre.SRE_Pattern instances in
each set value replaced with the pattern strings. Needed for equality test of
two filetype trigger dictionaries."""
copy = triggerDict.copy()
for key, values in triggerDict.i... |
def b2h(num, suffix='B'):
"""Format file sizes as human readable.
https://stackoverflow.com/a/1094933
Parameters
----------
num : int
The number of bytes.
suffix : str, optional
(default: 'B')
Returns
-------
str
The human readable file size string.
Ex... |
def verif_checksum(line_str, checksum):
"""Check data checksum."""
data_unicode = 0
data = line_str[0:-2] #chaine sans checksum de fin
for caractere in data:
data_unicode += ord(caractere)
sum_unicode = (data_unicode & 63) + 32
sum_chain = chr(sum_unicode)
return bool(checksum == sum... |
def split_basename(basename):
"""
Splits a base name into schema and table names.
"""
parts = basename.split(".")
db_name = parts[0]
python_path_name = parts[1]
schema_name = parts[2]
table_name = parts[3]
return db_name, python_path_name, schema_name, table_name |
def GetRegionFromZone(gce_zone):
"""Parses and returns the region string from the gce_zone string."""
zone_components = gce_zone.split('-')
# The region is the first two components of the zone.
return '-'.join(zone_components[:2]) |
def algP(m,s,b,n):
"""
based on Algorithm P in Donald Knuth's 'Art of
Computer Programming' v.2 pg. 395
"""
result = 0
y = pow(b,m,n)
for j in range(s):
if (y==1 and j==0) or (y==n-1):
result = 1
break
y = pow(y,2,n)
return result |
def reverse(head):
# Write your code here
""" head Node
return Node
"""
node = head
evens = []
while node is not None:
isEven = node.data % 2 == 0
# push node to evens
if isEven:
# print(" push:",node.data)
evens.append(node)
# not... |
def findFirstRepeater(data: list) -> int:
"""
Loops over puzzleArray adding each value to
frequency as with part 1, but loops over entire
array until it adds the same number twice. Once
found, returns that integer to submission.
Args:
data: puzzleArray from AOC
Returns:... |
def parse_to_sacred_experiment_args(arguments: list, _seed: int,
log_dir: str) -> list:
"""Add seed to sys args if not already defined.
This brings arguments into the expected structure of the sacred framework.
Remind: arguments is a list, so this is a call by reference
... |
def build_isolation_parameters(
technique,
threshold_type,
threshold_const,
threshold_min=0,
window_size=1.0,
chunk_size=2.0):
"""
Wrapper function for all of the audio isolation techniques (Steinberg,
Simple, Stack, Chunk). Will call the respective function o... |
def wait_timer(index: int, time: int):
"""Wait for timer."""
return f'B;WaitTimer("{index}","{time}");'.encode() |
def as_flag(b):
"""Return bool b as a shell script flag '1' or '0'"""
if b:
return '1'
return '0' |
def convert_chrome_cookie(cookie):
"""Convert a cookie from Chrome to a CookieJar format type"""
return {
'name': cookie['name'],
'value': cookie['value'],
'domain': cookie['domain'],
'path': cookie['path'],
'secure': cookie['secure'],
'expires': int(cookie['expir... |
def compute_returns(rewards, gamma=1.0):
"""
Compute returns for each time step, given the rewards
@param rewards: list of floats, where rewards[t] is the reward
obtained at time step t
@param gamma: the discount factor
@returns list of floats representing the episode's r... |
def elematypecolor2string(elem, atype, color):
"""
return formatted string from element, atomtype, and color
"""
return "%s_%s/%s" % (elem, atype, color) |
def format(time):
"""
Converts time in tenths of seconds to formatted string A:BC.D
"""
A = time // 600
B = ((time // 10) % 60) // 10
C = ((time // 10) % 60) % 10
D = time % 10
return str(A) + ":" + str(B) + str(C) + "." + str(D) |
def split_obj_identifier(obj_identifier):
"""
Break down the identifier representing the instance.
Converts 'notes.note.23' into ('notes.note', 23).
"""
bits = obj_identifier.split('.')
if len(bits) < 2:
return (None, None)
pk = '.'.join(bits[2:])
# In case Django ever handles... |
def ProcCSV(lst):
"""
Processes lst for delimiters and sorts them into a multi-dimensional array
"""
OutList = []
MegaList = []
for element in lst:
for item in element.split(",,"):
OutList.append(item.strip("\n"))
for item in OutList:
MegaList.append(item.split(",... |
def count_column_freqs(columns_list):
"""return the frequency of columns"""
col_freq_dict = {}
for column in columns_list:
column = ' '.join(column)
col_freq_dict[column] = col_freq_dict.get(column, 0) + 1
return col_freq_dict |
def iterative_len(x):
"""Return the len of an iterator without using len
Example:
>>> a = "hola"
>>> iterative_len(a)
>>> 4
"""
return sum(1 for i in x) |
def _qualified_type_name(class_):
"""
Compute a descriptive string representing a class, including
a module name where relevant.
Example outputs are "RuntimeError" for the built-in RuntimeError
exception, or "struct.error" for the struct module exception class.
Parameters
----------
cl... |
def getDataNodeUrls(app):
""" Return list of all urls to the set of datanodes """
dn_url_map = app["dn_urls"]
dn_urls = []
for id in dn_url_map:
dn_urls.append(dn_url_map[id])
return dn_urls |
def has_duplicates(array):
"""Write a function called has_duplicates that takes a list and returns True if there is any
element that appears more than once. It should not modify the original list."""
copy_array = array[:]
copy_array.sort()
val = copy_array[0]
for i in range (1, len(array)):
... |
def aggregation_count(list_, primary_key, count_key):
"""
params
list_ : [{},{}]
"""
return list(
map(
lambda x: {
primary_key: x[primary_key],
'count': len(x[count_key])
}, list_)) |
def convert_phred(letter):
"""Converts a single character into a phred score"""
QScore = ord(letter) - 33
return QScore |
def strip_package_from_class(base_package: str, class_name: str) -> str:
"""
Strips base package name from the class (if it starts with the package name).
"""
if class_name.startswith(base_package):
return class_name[len(base_package) + 1 :]
else:
return class_name |
def get_text(*args, sep=' '):
"""
Use this function for join some data with a separator
Args:
*args: all arguments
sep (str): text separator
Returns:
(str) : result text
"""
text = ""
for i in range(len(args)):
text += str(args[i])
if i != len(ar... |
def use_mem(numbers):
"""Different ways to use up memory.
"""
a = sum([x * x for x in numbers])
b = sum(x * x for x in numbers)
c = sum(x * x for x in numbers)
squares = [x * x for x in numbers]
d = sum(squares)
del squares
x = 'a' * int(1e6)
del x
return 42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.