content stringlengths 42 6.51k |
|---|
def find_frame(buffer):
"""
Finds the next MP3 frame header.
@param bytearray buffer
Bytes from an MP3 file.
@return int
The index in the buffer where the frame was found, or -1 if not found.
"""
try:
synchs = [buffer.find(b'\xFF\xFA'), buffer.find(b'\xFF\xFB')]
return min(x for x in synch... |
def mac_str_to_tuple(mac):
"""
Convert 'xx:xx:xx:xx:xx:xx' MAC address string to a tuple of integers.
Example: mac_str_to_tuple('00:01:02:03:04:05') == (0, 1, 2, 3, 4, 5)
"""
return tuple(int(d, 16) for d in mac.split(':')) |
def sub_base(k,base):
"""
If base is a list of sorted integers [i_1,...,i_R] then sub_base returns
a list with the k^th element removed. Note that k=0 removes the first
element. There is no test to see if k is in the range of the list.
"""
n = len(base)
if n == 1:
return([])
if ... |
def logical_xor(a, b, unsafe=False):
"""logical xor without the bloat of numpy.logical_xor
could be substituted with numpy.logical_xor
!important: if unsafe is set to True, a and b are not checked. This improves speed but is risky.
expects integers [0,1] or bools
"""
if not unsafe:
... |
def bytes2human(n, format="%(value)i%(symbol)s"):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i+1)*10
for symbol in reversed(... |
def simple_chewrec_func(data, rec, arg):
"""
Callback for record chewing.
"""
if rec is None:
return 1
return 0 |
def area_triangle(base, height):
"""
.. math::
area = \\frac{base * height}{2.0}
Parameters
----------
base: float
length of the base of the triangle
height: float
height of the triangle
Returns
-------
area: float
area of the triangle
"""
... |
def find_word_in_turn(dialogue, turn_id, value, start_idx, end_idx):
"""
find non-cat slot value in turn.
return List[(turn_id, frame_id, key)]
"""
assert isinstance(value, str)
frames = dialogue["turns"][turn_id]["frames"]
res = []
for frame_id, frame in enumerate(frames):
for ... |
def fibonacci(n):
"""Return a list with the first `n` fibonacci numbers"""
if n == 1:
return 1
elif n == 2:
return 2
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def separa_palavras(frase):
"""[A funcao recebe uma frase e devolve uma lista das palavras dentro da frase]
Arguments:
frase {[str]} -- [Uma frase]
Returns:
[lista] -- [Retorna uma lista de palavras dentro da frase recebida]
"""
return frase.split() |
def get_model_var_scope(module_scope, model_name):
""" Assembly Module Scope Name and model scope name
"""
model_var_scope = module_scope + "_" + model_name
return model_var_scope |
def name_from_url(url):
""" Parses a URL in REST format where the last component is the object name"""
return url.split('/')[-1] |
def dictToHashTuple(baseDict):
"""super inefficient and explicit for now"""
return tuple( (k, str(baseDict[k]), str(id((baseDict[k])))) for k in sorted(baseDict.keys()))
# return ", ".join(tuple(k + "=" + str(baseDict[k]) for k in sorted(baseDict.keys()))) |
def thankyou(contributor):
"""End"""
#form = ReusableForm(request.form)
#print(form.errors)
#if request.method == 'POST':
# expertiseLevel = request.form['expertiseLevel']
#if form.validate():
# return redirect(url_for('description', contributor=name))
return("THANK YOU, ... |
def g_speed(parameters, actual_speed):
"""returns a speed from a g-code"""
# default values
speed = actual_speed
# parse text
params = parameters.split(' ')
for param in pa... |
def clean(string_value):
"""Standardizes string values for lookup by removing case and special characters and spaces.
Args:
string_value (str): The lookup key to be transformed.
Returns:
str: The original value, but lowercase and without spaces, underscores or dashes.
"""
return st... |
def reached_minimum_node_size(data, min_node_size):
"""
Purpose: Determine if the node contains at most the minimum
number of data points
Input : Data array and minimum node size
Output : True if minimum size has been reached, else False
"""
if len(data) <= min_node_size:
... |
def ParseKey(algorithm, key_length, key_type, messages):
"""Generate a keyspec from the given (unparsed) command line arguments.
Args:
algorithm: (str) String mnemonic for the DNSSEC algorithm to be specified in
the keyspec; must be a value from AlgorithmValueValuesEnum.
key_length: (int) The key l... |
def limpiar_extremos(texto):
"""Quita los espacios presentes al inicio y al final de una cadena de texto.
:param texto: (str) Cadena de texto de entrada.
:return: (str) Cadena de texto sin espacios en el inicio y en el final.
"""
return texto[::-1].rstrip()[::-1].rstrip() |
def partition(pred, iterable):
""" Returns tuple of allocated and unallocated systems
:param pred: status predicate
:type pred: function
:param iterable: machine data
:type iterable: list
:returns: ([allocated], [unallocated])
:rtype: tuple
.. code::
def is_allocated(d):
... |
def has_loops(path):
"""Returns True if this path has a loop in it, i.e. if it
visits a node more than once. Returns False otherwise."""
visited = {}
for node in path:
if node not in visited:
visited[node] = 0
else:
return True
return False |
def eps(i, N):
"""Dispersion."""
i=i+1 #THIS IS SO THE DISPERSION IS THE SAME AS IN mathematica
return -1 + (2/(N+1) * i) |
def resolve_multi_input_change_ranges(input_change_ranges_list):
"""For AGGREGATE_LAYERS such as Add, the different inputs have different
change ranges. For the change ranges, take the largest range over all
input ranges:
e.g. [ [(1,3), (4,6)], [(2,4), (4,5)] ] -> [(1,4), (3,6)]
input1 -^ ... |
def col_to_str(agg, col, tab, table_names, N=1):
""" transform Agg Column Table to str
Args:
agg(str):
col(str):
tab(str):
table_names(dict):
N(int): Default is 1
Returns: str
Rsises: NULL
"""
_col = col.replace(' ', '_')
tab = ''.join(tab)
if agg... |
def get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce):
"""
Extracts encrypted payment id from extra
:param extra_nonce:
:return:
"""
if 9 != len(extra_nonce):
raise ValueError("Nonce size mismatch")
if 0x1 != extra_nonce[0]:
raise ValueError("Nonce payment type invali... |
def function_merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return(z) |
def check_puppet_class(rec):
"""
Checks if the given file is a puppet class
:param rec: file path
:return: check result
"""
return rec.lower().endswith(".pp") |
def pad_locs(book,loc_length):
"""
Pad location keys as necessary
"""
book_new = {}
for key,value in book.items():
pad = loc_length - len(key) # how much we need to pad
newkey=key
while pad > 0:
newkey = newkey[0] + "0" + newkey[1:]
pad-=1
... |
def remove_quantopian_imports(code: str) -> str:
"""
we implement the algorithm api inside pylivetrader.
the quantopian api is removed.
:param code:
:return:
"""
result = []
skip_next_line = False
for line in code.splitlines():
if "import" in line and "\\" in line:
... |
def filt_by_filetype(filetypes, value):
"""
filt the urls of filetypes
"""
for ftype in filetypes:
if value.endswith(ftype):
return True
return False |
def get_bytes(count, ignore):
"""
unittest patch for get_rnd_bytes (ID2TLib.Utility.py)
:param count: count of requested bytes
:param ignore: <not used>
:return: a count of As
"""
return b'A' * count |
def key_exists(dictionary, key):
"""Tests if a key exists in a dictionary
Arguments:
dictionary {dict} -- The dictionary to test
key {str} -- The key to test
Returns:
bool -- `True` if the key exists in the dictionary
"""
exists = dictionary.get(key, None)
retu... |
def unbox_usecase2(x):
"""
Expect a list of tuples
"""
res = 0
for v in x:
res += len(v)
return res |
def recall(cm):
"""The ratio of correct positive predictions to the total positives examples.
This is also called the true positive rate."""
return cm[1][1]/(cm[1][1] + cm[1][0]) |
def get_lr(lr, total_epochs, steps_per_epoch, lr_step, gamma):
"""get_lr"""
lr_each_step = []
total_steps = steps_per_epoch * total_epochs
lr_step = [i * steps_per_epoch for i in lr_step]
for i in range(total_steps):
if i < lr_step[0]:
lr_each_step.append(lr)
elif i < lr... |
def result(result):
""" Prints results in a specific color
"""
if result == "conditional":
return "[ " + "(!) WARNING (!)" + " ]"
else:
if result:
return "[ " + "(#) PASS (#)" + " ]"
else:
return "[ " + "<!!> FAILURE <!!>" + " ]" |
def get_api_name(intfspec):
"""Given an interface specification return an API name for it"""
if len(intfspec) > 3:
name = intfspec[3]
else:
name = intfspec[0].split('.')[-1]
return name |
def map_reputation_to_score(reputation: str) -> int:
"""Map reputation as string to it's score as integer representation
:param reputation: The reputation as str
:type reputation: ``str``
:return: the score integer value
:rtype: ``int``
"""
reputation_map = {
'unknown': 0,
... |
def getGuids(fileList):
""" extracts the guids from the file list """
guids = []
# loop over all files
for thisfile in fileList:
guids.append(str(thisfile.getAttribute("ID")))
return guids |
def list2map(listoffilenames, delimiter):
"""
convert a list to a map
:param listoffilenames: list of filenames
:param delimiter: common separator used in filenames
:return: map/dictionary of list with key of filename before delimiter and value of complete filename
"""
return dict(map(lambd... |
def asciify(string):
"""Returns a string encoded as ascii"""
return string.encode('ascii') |
def time_periods_in_epoch(epoch):
"""
Args:
epoch (int): the Unix-time epoch to extract time periods from.
Returns:
tuple: A tuple of ints (days, hours, mins) in the epoch.
"""
epoch = epoch // 60
mins = epoch % 60
epoch = epoch // 60
hours = epoch % 24
epoch = epoch... |
def find_letter_grade(grade: float) -> str:
"""
Grading Scale -
89.50 - 100 = A \n
88.50 - 89.49 = B+ \n
79.50 - 88.49 = B \n
78.50 - 79.49 = C+ \n
69.50 - 78.49 = C \n
68.50 - 69.49 = D+ \n
59.50 - 68.49 = D \n
00.00 - 59.50 = F ... |
def calculate_uncertainty(terms, rho=0.):
"""
Generically calculates the uncertainty of a quantity that depends on multiple *terms*. Each term
is expected to be a 2-tuple containing the derivative and the uncertainty of the term.
Correlations can be defined via *rho*. When *rho* is a numner, all correla... |
def ema(values, n):
"""Calculates actual value of exponential moving average of given series with certain length.
:param values: list of floats
:param n: int ema length
:return: float actual ema value
"""
ema_list = []
sma = sum(values) / n
multiplier = 2 / (n + 1)
# EMA(current) =... |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
... |
def is_payload_list_pages(payload: bytes) -> bool:
"""Checks if payload is a list of UsmPage which has a signature of '@UTF' at the beginning."""
if len(payload) < 4:
return False
return payload[:4] == bytes("@UTF", "UTF-8") |
def exchangeRows(M, r1, r2):
"""Intercambia las filas r1 y r2 de M"""
M[r1], M[r2] = M[r2], M[r1]
return M |
def suggested_filter(sensor: str) -> str:
"""Suggested sensors."""
filt = {
"serial": "last",
"overall_state": "last",
"batter_soc": "last",
"total_load": "step",
}.get(sensor)
if filt:
return filt
if sensor.startswith("total_"):
return "last"
if s... |
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
i... |
def crawl_dictionary(dictionary, parent, parameter, inserted=False):
""" Recursively look for a given parent within a potential dictionary of
dictionaries. If the parent is found, insert the new parameter and update
the 'inserted' flag. Return both the updated dictionary and inserted flag.
:param dic... |
def _word_badness(word):
"""
Assign a heuristic to possible outputs from Morphy. Minimizing this
heuristic avoids incorrect stems.
"""
if word.endswith('e'):
return len(word) - 2
elif word.endswith('ess'):
return len(word) - 10
elif word.endswith('ss'):
return len(wor... |
def check_set_number(value, typ, default=None, minimum=None, maximum=None):
""" Checks if a value is instance of type and lies within permissive_range if given. """
if value is None:
return default
if not isinstance(value, typ):
try:
value = typ(value)
except:
... |
def get_pathname_from_url(url):
"""Get the pathname from a URL.
Args:
url (str): URL.
Returns:
str: Pathname of the URL.
"""
return url[:url.rfind('/') + 1:] |
def sizify(value):
"""
Simple kb/mb/gb size snippet for templates:
{{ product.file.size|sizify }}
"""
if value < 512000:
value = value / 1024.0
ext = 'kb'
elif value < 4194304000:
value = value / 1048576.0
ext = 'mb'
else:
value = value / 1073741824.0... |
def corrected_components(x):
"""
:return: the components x, negated if both components are negative
"""
if x[0] < 0 and x[1] < 0:
return -x
return x |
def select_keys(d, keys):
"""
>>> d = {'foo': 52, 'bar': 12, 'baz': 98}
>>> select_keys(d, ['foo'])
{'foo': 52}
"""
return {k:d[k] for k in keys} |
def subnet4(ip_addresses, max_address_bits=32):
"""
Takes an iterable sequence of positive integers.
Returns a tuple consisting of the minimum subnet address and netmask.
The subnet is calculated based on the received set of IP addresses.
Examples of usage:
# 10.0.0.0/21
>>> subnet4(range... |
def mean(l):
"""
Returns the mean value of the given list
"""
sum = 0
for x in l:
sum = sum + x
return sum / float(len(l)) |
def get_version(diff_file, ix=True):
"""Determine the product version from the diff file name.
param ix denotes if the diff file was generated by APIx or CLIx
"""
split_ver = diff_file.split("/")[-1].split("-")
if "-comp.yaml" in diff_file:
return split_ver[0]
else:
return f"{spl... |
def get_row_sql(row):
"""Function to get SQL to create column from row in PROC CONTENTS."""
postgres_type = row['postgres_type']
if postgres_type == 'timestamp':
postgres_type = 'text'
return row['name'].lower() + ' ' + postgres_type |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True |
def alpha_adj(color, alpha=0.25):
"""
Adjust alpha of color.
"""
return [color[0], color[1], color[2], alpha] |
def discounted_columns_pairs(cashflow_columns, prefix, suffix):
"""
Computes a dictionary with the undiscounted version of columns as keys and the discounted version as values
:param cashflow_columns: list
undiscounted cashflow columns
:param prefix: str
prefix used to mark discounted columns
... |
def rescale_to_max_value(max_value, input_list):
""" Rescale each value inside input_list into a target range of 0 to max_value """
scale_factor = max_value / float(max(input_list))
# Multiply each item by the scale_factor
input_list_rescaled = [int(x * scale_factor) for x in input_list]
return inpu... |
def binary_search(items, target):
"""O(log n)."""
low = 0
high = len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
elif items[mid] > target:
high = mi... |
def auto_id(index: int, total: int) -> str:
"""Generate ID property for sentence
Arguments:
index {int} -- sentence index in content
total {int} -- total number of sentences in content
Returns:
str -- sentence id
"""
pad = len(str(total))
template = '{{0:{0}d}} of {{1}}... |
def trailing_stop_loss(last, higher, percentage=3):
"""
Trailing stop loss function.
Receives structure with:
- Last price.
- Entry point x.
- Exit percentage [0.1-99.9]
Returns true when triggered.
"""
if last <= higher * (1 - (percentage * 0.01)):
ret... |
def match(v1, v2, nomatch=-1, incomparables=None, start=0):
"""
Return a vector of the positions of (first)
matches of its first argument in its second.
Parameters
----------
v1: array_like
Values to be matched
v2: array_like
Values to be matched against
nomatch: int
... |
def reverse_only_alnum(s):
"""reverse only alnums leaving special charactes in place"""
return len(s) != 0 and reverse_only_alnum(s[1:]) + s[0] or s |
def _im_func(f):
"""Wrapper to get at the underlying function belonging to a method.
Python 2 is slightly different because classes have "unbound methods"
which wrap the underlying function, whereas on Python 3 they're just
functions. (Methods work the same way on both versions.)
"""
# "im_func... |
def pvr(green, red):
"""Normalized Difference 550/650 Photosynthetic vigour ratio boosted with Numba
See:
https://www.indexdatabase.de/db/i-single.php?id=484
"""
return (green - red) / (green + red) |
def _class_hasattr(instance, attr):
"""
Helper function for checking if `instance.__class__` has an attribute
Parameters
----------
instance : obj
instance to check
attr : str
attribute name
Returns
-------
bool
"""
return hasattr(instance.__class__, attr) |
def readable_mem(mem):
"""
:param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number.
"""
for suffix in ["", "K", "M", "G", "T"]:
if mem < 10000:
return "{}{}".format(int(mem), suffix)
mem /= 10... |
def cipher(text, shift, encrypt=True):
"""
This function applies the Caesar cipher, which is a simple and well-known encryption technique, on text input. Each letter in the text is replaced by a letter some fixed number of positions down the alphabet.
Parameters
----------
text:
Th... |
def sequential_search(a, value):
"""
Searches a value in a list. Return the index if found, otherwise returns
<None>.
"""
for i in range(len(a)):
# If found the value
if (a[i] == value):
return i
return None |
def type_to_str(type_object) -> str:
"""convert a type object to class path in str format
Args:
type_object: type
Returns:
class path
"""
cls_name = str(type_object)
assert cls_name.startswith("<class '"), 'illegal input'
cls_name = cls_name[len("<class '"):]
assert cls_na... |
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str:
"""Pack data in Server-Sent Events (SSE) format"""
return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n" |
def _list_frame(value):
"""
Returns:
list: Value converted to a list.
"""
try:
return [value] if isinstance(value, (str, bytes)) else list(value)
except TypeError:
return [value] |
def trapezint(f, a, b, n) :
"""
Just for testing - uses trapazoidal approximation from on f from a to b with
n trapazoids
"""
output = 0.0
for i in range(int(n)):
f_output_lower = f( a + i * (b - a) / n )
f_output_upper = f( a + (i + 1) * (b - a) / n )
output += (f_output... |
def _to_time(integ, frac, n=32):
"""Return a timestamp from an integral and fractional part.
Parameters:
integ -- integral part
frac -- fractional part
n -- number of bits of the fractional part
Retuns:
timestamp
"""
return integ + float(frac)/2**n |
def _find_header(md):
"""Find header markers
"""
mark = '<!-- end header -->'
lines = md.splitlines()
for n, line in enumerate(lines):
if mark == line:
return n
return None |
def percent_change(starting_point, current_point):
"""
Computes the percentage difference between two points
:return: The percentage change between starting_point and current_point
"""
default_change = 0.00001
try:
change = ((float(current_point) - starting_point) / abs(starting_point)) ... |
def get_value(json_dict, key, default=""):
"""Try to fetch optional parameters from input json dict."""
try:
return json_dict[key]
except KeyError: return default |
def _reg_str_comp(str1, str2):
"""Compare the float values in str1 and str2 and determine if they
are equal. Returns True if they are the "same", False if different"""
aux1 = str1.split()
aux2 = str2.split()
if not aux1[0] == aux2[0] == "@value":
# This line does not need to be compared
... |
def af_rotation(xfm90, xf0, xf90, xf180):
"""
takes the fiducial centers measured in the x direction at -90, 0, 90, and 180 degrees
and returns the offset in x and z from the center of rotation, as well as the
unrotated x positon of the fiducial marker.
the x offset is not expected to vary between ... |
def normalize(val, minval, maxval):
"""Scale a value between 0 and 1."""
if val >= maxval:
return 1
elif val <= minval:
return 0
normed = float(val - minval) / float(maxval - minval)
return normed |
def get_supported_os(scheduler):
"""
Return a tuple of the os supported by parallelcluster for the specific scheduler.
:param scheduler: the scheduler for which we want to know the supported os
:return: a tuple of strings of the supported os
"""
return ("alinux" if scheduler == "awsbatch" else ... |
def build_dict(key_list, value):
"""
Build a hierarchical dictionary with a single element from the list of keys and a value.
:param key_list: List of dictionary element keys.
:param value: Key value.
:return: dictionary
"""
temp_dict = {}
if key_list:
key = key_list.pop()
... |
def map_items_to_parent(items, parents):
"""Groups all items into a list based on thier respective parent
ex: pages have request, runs have pages
"""
item_lists = {}
if len(parents) > 0:
pk = parents.values()[0].pk
for p_id in parents:
item_lists[p_id] = []
for i... |
def scaleMatrix(x, y, z):
"""Generate scale matrix
x,y,z -- scale vector
"""
S = [ [x,0.,0.,0.], [0.,y,0.,0.], [0.,0.,z,0.], [0.,0.,0.,1.] ]
return S |
def flatten(l, ltypes=(list, tuple)):
""" Flattens an arbitrarily large list or tuple
Apparently very fast
Pulled from online >> https://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
Author: Mike C. Fletcher, Distribution: BasicTypes library.
"""
ltype = type(l)
l ... |
def _annotate_bookmark(label, bookmark=None):
"""
Annotate a bookmark indicator onto the type indicator of a bucket or prefix
"""
if not bookmark:
return label
return '\x1b[33m${}\x1b[0m {}'.format(bookmark, label) |
def _transform(command, *args):
"""Apply command's transformation function (if any) to given arguments.
Arguments:
command -- the command description dict
*args -- command arguments
"""
if "value_transform" in command:
return command["value_transform"](*args)
return args if len(args... |
def path(y):
"""Equation: x = a(y-h)^2 + k"""
a = 110.0 / 160.0 ** 2
x = a * y ** 2 + 0.0
return x, y |
def array_index_to_idx(i: int, idxpos0: int):
"""
Converts a nucleotide index to an 0-included array index
:param i: The array index
:param idxpos0: The start index
:return: The index of the element in the array
>>> array_index_to_idx(5, 5)
10
>>> array_index_to_idx(209, -200)
10
... |
def lowercase_first_string_letter(v:str):
"""Transform a string to lowercase first letter.
Args:
v (str): String value to convert
Returns:
str: Lowercase first letter of v
"""
return v[0].lower() + v[1:] |
def whitespace_tokenize(text):
"""Basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
return text.split() if text else [] |
def serialize_mc(analysis, type):
"""serialised function for the Monte Carlo Analysis"""
return {
'id': None,
'type': type,
'attributes': {
'window': analysis.get('window', None),
'mc_number': analysis.get('mc_number', None),
'bin_number': analysis.get... |
def get_docker_networks(data, state, labels=None):
"""Get list of docker networks."""
network_list = []
network_names = []
if not labels:
labels = {}
for platform in data:
if "docker_networks" in platform:
for docker_network in platform["docker_networks"]:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.