content stringlengths 42 6.51k |
|---|
def to_hex(number, width):
"""Convert number to hex value with specified width. Will be padded by zero
to fill the width.
"""
format_string = '{{0:0{0}X}}'.format(width)
return format_string.format(number) |
def green(text):
"""Returns a string with ANSI codes for green color and reset color
wrapping the provided text.
"""
return '\033[32m%s\033[39m' % text |
def log_file_path(log_path, date_string, suffix):
"""
Create log file path. The arg date_string must be in the form: yyyymmdd
Inputs:
log_path: directory string
date_string: date string in the form yyyymmdd
suffix: suffix string
"""
return("%s.%s%s" % (log_path, date_string, suff... |
def precision(tp, fp):
"""
:param tp:
:param fp:
:return:
"""
return tp/(tp+fp) |
def column_filter(column):
"""standardize column names"""
return column.replace(' ', '_').replace('-', '_').lower().strip() |
def to_decimal(number: str) -> int:
"""Convert other bases to decimal"""
if number[0:2] == "0b": # binary
return int(number[2:], 2)
if number[0:2] == "0x": # hex
return int(number[2:], 16)
if number[0:2] == "0o": # octal
return int(number[2:], 8)
if number[0:2] == "0d": #... |
def bytedivider(nbytes):
"""
Given an integer (probably a long integer returned by os.getsize() )
it returns a tuple of (megabytes, kilobytes, bytes).
This can be more easily converted into a formatted string to display the
size of the file.
"""
mb, remainder = divmod(nbytes, 1048576)
... |
def split_string_by_n(bitstring: str, n: int) -> list:
"""
Split a string every n number of characters
(or less if the 'remaining characters' < n ) this way we can sperate the
data for an etire video into a list based on the resolution of a frame.
bitstring -- a string containing bits
n -- spli... |
def quick_find_max_sum_interval(a_list):
"""
Prac 3 Hall of Fame
@purpose variant of Kadane's Algorithm for maximum subarray problems,
to find the max sum interval in this case, using dynamic programming
@param
a_list: The list to be passed to find max sum interval indices
@Complexit... |
def _get_decoded_dict(the_dict: dict) -> dict:
"""This method might be over kill, but redis appears to be sending back non ASCII data, so this
method prunes all possible non usable data, to something that's usable.
@note: This should be revisited!
"""
new_dict = {}
for key, value in the_d... |
def cql_type_to_gemini(cql_type, is_frozen=False):
"""
Convert a cql type representation to the gemini json one.
Limitations:
* no support for udt
* limited nested complex types support
"""
if isinstance(cql_type, str):
return cql_type
elif len(cql_type) == 1:
return... |
def str_binary_or(s1, s2):
"""
returns a string of 1 and 0 specifying if letters are the same or not
test1,test2 ==> 11110
use .find('0') to determine the first diff character.
"""
return ''.join(str(int(a == b)) for a, b in zip(s1, s2)) |
def verifyIsCloseEnough(number1, number2, margin = 0.05):
"""
Return true if number1 is within margin of number 2.
"""
max_diff = number2 * margin
return (abs(number1 - number2) < max_diff) |
def is_valid_instant(x):
"""
Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position).
"""
try:
return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \
len(x.inTimePosition[0].numericPosition) > 0
except TypeError:
return ... |
def str_or_list_like(x):
"""Determine if x is list-list (list, tuple) using duck-typing.
Here is a set of Attributes for different classes
| x | type(x) | x.strip | x.__getitem__ | x.__iter__ |
| aa | <class 'str'> | True | True ... |
def stripColours(msg):
"""Strip colours (and other formatting) from the given string"""
while chr(3) in msg:
color_pos = msg.index(chr(3))
strip_length = 1
color_f = 0
color_b = 0
comma = False
for i in range(color_pos + 1, len(msg) if len(msg) < color_pos + 6 els... |
def get_next_page(resp_json):
"""Description."""
if "navigationLinks" in resp_json:
if "next" in resp_json["navigationLinks"][0]["ref"]:
return resp_json["navigationLinks"][0]["href"]
else:
if len(resp_json["navigationLinks"]) == 2:
if "next" in resp_json[... |
def extract_keywords(lst_dict, kw):
"""Extract the value associated to a specific keyword in a list of
dictionaries. Returns the list of values extracted from the keywords.
Parameters
----------
lst_dict : python list of dictionaries
list to extract keywords from
kw : string
keywo... |
def prompt_dependent(independent: str) -> str:
"""Prompt the user for the dependent variable to use for calculation
>>> prompt_dependent('Annual CO2 emissions of Brazil')
'Amazon Precipitation'
>>> prompt_dependent('Estimated Natural Forest Cover')
Would you like to calculate for CO2 or precipitati... |
def is_prima_facie(c_and_e, c_true, e_true, events):
"""
Determines whether c is a prima facie cause of e.
Parameters:
c_and_e: number of times both events were true in a time window
c_true: number of times the cause was true in a time window
e_true: number of times the e... |
def _is_int(v):
"""int testing"""
return isinstance(v, int) |
def get_intersection_point_yaxis(y):
"""
Get the intersection point between a line and x axis
"""
if str(y) == '-0.0':
y = 0.0
if 0.0 <= y <= 1.0:
return (0.0, y)
return None |
def check_rms_edf(task_list):
"""Parse the YAML for the required field for RMS and EDF algorithms.
.. literalinclude:: ../../wikipedia.yaml
:language: yaml
:linenos:
:param task_list: List of task descriptors, as in the example above.
:type task_list: List of dictionaries.
:return... |
def concat_to_address(ip, port):
"""
ip: str for address to concat, like "127.0.0.1"
port: str for port, like "2379"
return: str like "127.0.0.1:2379"
return None if ip or port is None
"""
if ip is None or port is None:
return None
return ip.strip() + ":" + port.strip() |
def counting_sort(num_arr, cur, base):
"""
Modified counting sort
:param num_arr: array of Number-s
:param cur: current index of numeral
:param base: base of radix sort
:return: sorted array of Number-s
"""
count_arr = [0 for _ in range(base + 1)]
res = [None] * len(num_arr)
fo... |
def list_to_string(inlist, endsep="and", addquote=False):
"""
This pretty-formats a list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
is `True`, the outgoing strings will be surrounded by quotes.
Args:
inlist (list): The list to prin... |
def preprocess_call_name(name):
""" map an event name to a preprocess call name """
return 'preprocess_{}'.format(name) |
def tokendict_to_list(input_dict):
""" converts dict (loaded jason) in message format
to lists in message format
"""
# outs each sentence str in body in a temp list
message_list = []
body_list = []
for item in input_dict['body']:
body_list.append(input_dict['body'][item])... |
def to_float(s):
"""Convert a column to floats
usage: new_var = data.apply(lambda f : to_int(f['COLNAME']) , axis = 1)
"""
try:
s1 = float(s)
return s1
except ValueError:
return s |
def make_link_list(linklist):
"""Turn linklist into string."""
l = ""
for u in linklist:
l = l + " " + u
# check size isn't bigger than 255
o = l[1:len(l)]
if len(o) > 255:
o = o[:254]
return o |
def log_level_int(log_level):
"""
This function returns the integer log level from a string. Used for compatibility across HELICS and FNCS
Inputs
log_level - Log level string
Outputs
log level integer
"""
logLevels = {'ERROR': 0,'WARNING': 1,'INFO': 2,'DEBUG': 3,'DEBUG1':... |
def counter(i=0, f=10, p=1):
"""
:param i: Beggining of the counter
:param f: End of the counter
:param p: Distance between consecutive numbers in the sequece
:return: List with the entire sequence
"""
p = abs(p)
if p == 0:
p = 1
if f < i:
p = p * -1
contagem = []... |
def extract(a,b):
"""Find common string in two separate strings"""
m = min(len(a),len(b))
for i in range(m):
if a[i] != b[i]:
return a[:i]
return a[:m] |
def _removeDuplicatesOneLevel(aList):
""" Remove first level duplicates. """
result = []
if aList == []: return
if type(aList) != type([]): return aList
for elem in aList:
if elem not in result: result.append(elem)
return result |
def add_intstr(istr):
"""Takes a positive number as a string, returns the integer sum of its
digits.
"""
sum = 0
for i in istr:
sum += int(i)
return sum |
def product(A):
"""
Return the accumulated product of an array.
"""
def prod(a, b):
n = b - a
if n < 24:
p = 1
for k in range(a, b + 1):
p *= A[k]
return p
m = (a + b) // 2
return prod(a, m) * prod(m + 1, b)
return p... |
def zero2none(v):
"""Zero -> None."""
if v == 0:
return None
return v |
def _dot(fqdn):
"""
Append a dot to a fully qualified domain name.
DNS and Designate expect FQDNs to end with a dot, but human's conventionally don't do that.
"""
return '{0}.'.format(fqdn) |
def starlist_line(tokens):
"""Starlist token lines."""
return "".join(tokens) |
def report(config_id=1, name='mock', state='Completed',
start='/Date(1351118760000)/',
end='/Date(1351118760001)/',
duration='00:00:00', errors=None,
outcome='OK', diagnostics='OK'):
"""Base mock report."""
return {
'BackupConfigurationId': config_id,
... |
def format_bytes(input_bytes, precision=2):
"""
Format an integer number of input_bytes to a human
readable string.
If input_bytes is negative, this method raises ArithmeticError
"""
import math
if input_bytes < 0:
raise ArithmeticError("Only Positive Integers Allowed")
if inp... |
def decode_bs_word(word: int):
"""
decode word in the bistream file
:param word: word
:return: meaning
"""
# 001 xx RRRRRRRRRxxxxx RR xxxxxxxxxxx
# 111
# 000 11
# 000 00 11111111111111 0
# 000 00 00000000000000 11 00000000000
# 000 00 00000000000000 00 11111111111
header_... |
def merge(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def str_set_of_candidates(candset, cand_names=None):
"""
Nicely format a set of candidates.
.. doctest::
>>> print(str_set_of_candidates({0, 1, 3, 2}))
{0, 1, 2, 3}
>>> print(str_set_of_candidates({0, 3, 1}, cand_names="abcde"))
{a, b, d}
Parameters
----------
... |
def ranges(nums):
"""
input : a set of numbers (floats or ints)
output : list of tuples, one tuple for each string of consecutively increasing numbers in nums
each tuple contains two numbers: the first and last values from each consecutively incresing string
"""
nums = sorted(set(nums)... |
def class_indices(classes_arr):
"""Returns a dict with classes mapped to indices"""
size = len(classes_arr)
return {classes_arr[i]: i for i in range(size)} |
def getVec3(default_value, init_value = [0.0, 0.0, 0.0]):
"""
Return vec3 with a given default/fallback value.
"""
return_value = init_value.copy()
if default_value is None or len(default_value) < 3:
return return_value
index = 0
for number in default_value:
return_value[i... |
def linear_conv(value, old_min, old_max, new_min, new_max):
"""
A simple linear conversion of one value from one scale to another
Returns:
Value in the new scale
"""
return ((value - old_min) / (old_max - old_min)) * ((new_max - new_min) + new_min) |
def _quote(expr: str) -> str:
"""Quote a string, if not already quoted."""
if expr.startswith("'") and expr.endswith("'"):
return expr
return f"'{expr}'" |
def parse_links(s):
"""
Parse URLs from Link header
>>> links = parse_links(
... '<https://api.github.com/repos?page=2>; rel="next", '
... '<https://api.github.com/repos?page=5>; rel="last"')
>>> list(links.keys())
['next', 'last']
>>> links['next']
'https://api.github.com/r... |
def decode_ber(ber):
"""
Decodes an array of bytes to an integer value
If the first byte in the BER length field does not have the high bit set (0x80),
then that single byte represents an integer between 0 and 127 and indicates
the number of Value bytes that immediately follows. If the high bit is ... |
def localisation_formatting(localisation):
"""
This function takes a localisation and format it to be used with google API.
param: company localisation
return: formatted company localisation
"""
localisation = localisation.replace(' ', '+')
return localisation |
def bitwise_dot(x, y):
"""Compute the dot product of two integers bitwise."""
def bit_parity(i):
n = bin(i).count("1")
return int(n % 2)
return bit_parity(x & y) |
def parse_single_assignment(assignment):
"""
Parse the useful information from a single assignment.
:param assignment: All information of a single assignment.
:type assignment: dict(str, str)
:return: The id, due_date and name of an assignment.
:rtype: tuple(int, int, str)
"""
assignmen... |
def midpoint(pair1, pair2):
"""find and return the midpoint between the two given points"""
x = (pair1[0] + pair2[0])/2
y = (pair1[1] + pair2[1])/2
return x, y |
def escapeBelString(belstring):
"""Escape double quotes in BEL string"""
return belstring.replace('"', '\\"') |
def sizeof_fmt(num, suffix='B'):
"""
Returns human-readable version of file size
Source: https://stackoverflow.com/a/1094933
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%... |
def find_average_score(generation):
"""
Generation is a dictionary with the subjects and score.
Returns the average score of that generation
"""
sum = 0
for score in generation.values():
sum += score
return sum/len(generation.values()) |
def contains(query, include, exclude=None):
"""
Is anything from `include` in `query` that doesn't include anything from `exclude`
`query` can be any iterator that is not a generator
"""
if isinstance(include, str):
include = [include]
condition_A = any(x in query for x in include)
i... |
def descendants(cls: type) -> list:
"""
Return a list of all descendant classes of a class
Arguments:
cls (type): Class from which to identify descendants
Returns:
subclasses (list): List of all descendant classes
"""
subclasses = cls.__subclasses__()
for subclass in subclasses:
subclasses.extend(descend... |
def validate_office_types(office_type):
"""
Method to validate office types
:params: office type
:response: boolean
"""
office_types = ["local","federal","state", "legistlative"]
if office_type not in office_types:
return False
return True |
def transpose_table(table):
"""Transpose the table for further adaptation"""
new_table = []
for row in table:
for i, value in enumerate(row):
if i != 0:
new_row = [row[0], i, value]
new_table.append(new_row)
return new_table |
def normalize_unique_together(unique_together):
"""
unique_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
"""
if unique_together and not isinstance(unique_together[0], (tuple, list)):
... |
def parenthesise(s, parens = True):
"""
Put parentheses around a string if requested.
"""
if parens:
return '(%s)' % s
else:
return s |
def jinja2_targetpage(env, target):
"""Returns the page basename (without ".html") of a link target.
E.g. "authors.html#Shakespeare" yields "authors"
"""
return (target.split("#")[0]).split(".")[0] |
def check_element_equal(lst):
"""
Check that all elements in an
iterable are the same.
:params lst: iterable object to be checked
:type lst: np.array, list, tuple
:return: result of element equality check
:rtype: bool
"""
return lst[1:] == lst[:-1] |
def cleanup_wiki_string(line):
"""Helper for :meth:`_cleanup_wikisaurus`
Args:
line (str): line to be cleaned up from wiki markup
Returns:
(str): cleaned up string
"""
line = line.strip("=")
line = line.lower()
if line:
if not "beginlist" in line and not "endlist"... |
def get_mac_a(output: bytes) -> bytes:
"""Support function to get the 64-bit network authentication code (MAC-A)
from OUT1, the output of 3GPP f1 function.
:param output: OUT1
:returns: OUT1[0] .. OUT1[63]
"""
edge = 8 # = ceil(63/8)
return output[:edge] |
def numbers_to_strings(argument):
"""allocator mode num to str."""
switcher = {
0: "direct",
1: "cycle",
2: "unified",
3: "je_direct",
4: "je_cycle",
5: "je_unified",
}
return switcher.get(argument, "cycle") |
def int_hex(data_in, mode=0):
"""
converts list elements from int to hex and back
mode : int to hex (0) , hex to int (1)
"""
data_out = []
if mode == 0:
for i in range(len(data_in)):
data_out.append(format(data_in[i], '02x'))
return data_out
for i in range(len(dat... |
def time_in_range(start, end, x_time):
""" See if a time falls within range """
if start <= end:
return start <= x_time <= end
return end <= x_time <= start |
def round_filters(filters, width_coefficient, depth_divisor=8):
"""Round number of filters based on depth multiplier."""
min_depth = depth_divisor
filters *= width_coefficient
new_filters = max(min_depth, int(filters + depth_divisor / 2) // depth_divisor * depth_divisor)
# Make sure that round down... |
def is_permutation(a: str, b: str) -> bool:
"""Check if a is a permutation of b
Args:
a: a string
b: another string
Returns:
True if a is a permutation of b, False otherwise
"""
counter = {}
for char in a:
counter[char] = counter.get(char, 0) + 1
for char in... |
def LineColour(argument):
"""Dictionary for switching line colours where appropriate"""
switcher = {
'Black': 'k',
'Red': 'r',
'Green': 'g',
'Blue': 'b'
}
return switcher.get(argument, argument) |
def _parse_wamd_gps(gpsfirst):
"""WAMD "GPS First" waypoints are in one of these two formats:
SM3, SM4, (the correct format):
WGS..., LAT, N|S, LON, E|W [, alt...]
EMTouch:
WGS..., [-]LAT, [-]LON[,alt...]
Produces (lat, lon, altitude) float tuple.
"""
if not gpsfirst:
ret... |
def result_table_to_string(table):
"""Converts a resulting SQL table to a human-readable string."""
string_val = (
"\t" + "\n\t".join([str(row) for row in table[: min(len(table), 5)]]) + "\n"
)
if len(table) > 5:
string_val += "... and %d more rows.\n" % (len(table) - 5)
return strin... |
def teardown(message):
"""Finalize the processing pipeline and return the errors list.
"""
et, err_list = message
return err_list |
def cat_id_to_real_id(catId):
"""
Note coco has 80 classes, but the catId ranges from 1 to 90!
Args:
realId: id in coco datasets.
Returns:
id for our training set.
"""
cat_id_to_real_id = \
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 13: 12, 14: 13,... |
def _pkornone(account):
""" Devuelve clave primaria de un objeto Account.
Si account es None, devuelve None """
if account is None:
return None
return account.pk |
def fis_trimf(x:float, a:float, b:float, c:float):
"""Triangular Member Function"""
t1 = (x - a) / (b - a)
t2 = (c - x) / (c - b)
if (a == b) and (b == c):
return float(x == a)
if (a == b):
return (t2 * float(b <= x) * float(x <= c))
if (b == c):
return (t1 * float(a <= x... |
def keyword(text):
"""
Formats keywords by
-lowercasing all letters
-replacing ' ' with '_'
-replacing '-' with '_'
"""
text = str(text).lower()
text = text.replace("-", " ")
return text |
def parse_name(ldap_entry):
"""Return the user's first and last name as a 2-tuple.
This is messy because there's apparently no canonical field to pull
the user's first and last name from and also because the user's
surname field (for example) may contain a title at the end (like
"Bob Smith, Assista... |
def hex_to_rgb(hex):
""" Returns RGB values for a hex color string.
"""
hex = hex.lstrip("#")
if len(hex) < 6:
hex += hex[-1] * (6-len(hex))
r, g, b = hex[0:2], hex[2:4], hex[4:]
r, g, b = [int(n, 16)/255.0 for n in (r, g, b)]
return r, g, b |
def setValue(size=0, value=0.0):
"""
Return a python list with every value initialised to value.
"""
lst = []
i = 0
while i < size:
lst.append(value)
i += 1
return lst |
def validate_num(n):
"""Attempt to typecast n as an integer."""
try:
n = int(n)
except:
print('Error validating number. Please only use positive integers.')
return 0
else:
return n |
def geterr(obj):
"""
Returns false if there are no errors in a network response,
else a tuple of (code integer, description string)
"""
error = obj.get("error")
if not error:
return False
return (error["code"], error["description"]) |
def _is_mgmt_url(path):
"""
small helper to test if URL is for management API.
"""
return path.startswith("/mgmt/") |
def bracket(a, f, s=0.001, m=2):
""" Finds an interval [a,b] where the function f is unimodal
Args:
a: Starting point
f: Objective function
s: Initial step size
m: scaling factor for the step size
Returns:
A list with the lower and upper bounds of the interval
i... |
def move_item_to_front(lst, item):
""" Move an item to the front of a list.
:param lst: the list
:type lst: list or tuple
:param item: the item, which must be in `lst`
:returns: the list, with the item moved to front
:rtype: tuple
"""
lst = list(lst)
lst.insert(0... |
def list_diff(l1,l2):
""" Return set difference l1\l2. Assumes l1 and l2 are generators
of hashable things """
sl2 = set(l2)
return [s for s in l1 if s not in sl2] |
def switchUser(username, password, event, hideError=False):
"""Attempts to switch the current user on the fly.
If the given username and password fail, this function will return
False. If it succeeds, then all currently opened windows are closed,
the user is switched, and windows are then re-opened in ... |
def __renumber(dictionary) :
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys() :
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1 :
new... |
def transposta_matriz(M):
"""Calcula a transposta de uma matriz."""
lin = len(M[0])
col = len(M)
MT = []
for l in range(lin):
linha = []
for c in range(col):
linha.append(M[c][l])
MT.append(linha)
return MT |
def from_digit(n):
"""
0 <= n < 16
"""
return '0123456789ABCDEF'[n] |
def list_removeDuplicates(alist):
"""
Removes duplicates from an input list
"""
#d = {}
#print alist
#for x in alist:
#d[x] = x
#alist = d.values()
alist = list(set(alist))
return alist |
def createGrid(nx, ny):
"""
Create a grid position array.
"""
direction = 0
positions = []
if (nx > 1) or (ny > 1):
half_x = int(nx/2)
half_y = int(ny/2)
for i in range(-half_y, half_y+1):
for j in range(-half_x, half_x+1):
if not ((i==0) and (... |
def strip_leading_dashdash(name):
"""Remove leading ``'--'`` if present."""
if name.startswith('--'):
return name[2:]
else:
return name |
def get_mapping(d):
"""
Reports fields and types of a dictionary recursively
:param object: dictionary to search
:type object:dict
"""
mapp=dict()
for x in d:
if type(d[x])==list:
mapp[x]=str(type(d[x][0]).__name__)
elif type(d[x])==dict:
ma... |
def filter_bcg_candidate_peaks(bcg_indices, bcg_peak_values, ecg_indices):
"""
get corrent bcg peaks by choose closest peaks at ecg_indices
"""
peak_indices = []
peak_values = []
num_bcg_indices = len(bcg_indices)
num_ecg_indices = len(ecg_indices)
bcg_id = 0
ecg_id = 0
while (ec... |
def get_namespace(type_or_context):
"""
Utility function to extract the namespace from a type (@odata.type) or context (@odata.context)
:param type_or_context: the type or context value
:type type_or_context: str
:return: the namespace
"""
if '#' in type_or_context:
type_or_context =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.