response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Version from vmaf __init__ | def get_version():
"""Version from vmaf __init__"""
try:
with open(os.path.join(PYTHON_PROJECT, "vmaf", "__init__.py")) as fh:
for line in fh:
if line.startswith("__version__"):
return line.strip().rpartition(" ")[2].replace('"', "")
except Exception... |
Dynamically mark tests based on their file name:
- *_test.py: main test (always exercise)
- *_extratest.py: exercised only when testing with ffmpeg
- *_libtest.py: exercised only to test testlib | def pytest_collection_modifyitems(items):
"""
Dynamically mark tests based on their file name:
- *_test.py: main test (always exercise)
- *_extratest.py: exercised only when testing with ffmpeg
- *_libtest.py: exercised only to test testlib
"""
for item in items:
item.add_marker(pyte... |
Convert FFmpeg-style pixel format (pix_fmt) to vmaf style.
:param ffmpeg_pix_fmt: FFmpeg-style pixel format, for example: yuv420p, yuv420p10le
:return: (pixel_format: str, bitdepth: int), for example: (420, 8), (420, 10) | def convert_pixel_format_ffmpeg2vmafexec(ffmpeg_pix_fmt):
"""
Convert FFmpeg-style pixel format (pix_fmt) to vmaf style.
:param ffmpeg_pix_fmt: FFmpeg-style pixel format, for example: yuv420p, yuv420p10le
:return: (pixel_format: str, bitdepth: int), for example: (420, 8), (420, 10)
"""
assert f... |
# ((x) + ((x) % MAX_ALIGN ? MAX_ALIGN - (x) % MAX_ALIGN : 0))
>>> ALIGN_CEIL(3)
32
>>> ALIGN_CEIL(32)
32
>>> ALIGN_CEIL(33)
64 | def ALIGN_CEIL(x):
"""
# ((x) + ((x) % MAX_ALIGN ? MAX_ALIGN - (x) % MAX_ALIGN : 0))
>>> ALIGN_CEIL(3)
32
>>> ALIGN_CEIL(32)
32
>>> ALIGN_CEIL(33)
64
"""
if x % MAX_ALIGN != 0:
y = MAX_ALIGN - x % MAX_ALIGN
else:
y = 0
return x + y |
Run multiple Executors in parallel. | def run_executors_in_parallel(executor_class,
assets,
fifo_mode=True,
delete_workdir=True,
parallelize=True,
logger=None,
result_store=None,... |
Mark a function as deprecated.
It will result in a warning being emitted when the function is used. | def deprecated(func):
"""
Mark a function as deprecated.
It will result in a warning being emitted when the function is used.
"""
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn("Call to deprecated function {}.".form... |
Cache returned value of function in a function. Useful when calling functions
recursively, especially in dynamic programming where lots of returned values
can be reused. | def persist(original_func):
"""
Cache returned value of function in a function. Useful when calling functions
recursively, especially in dynamic programming where lots of returned values
can be reused.
"""
cache = {}
def new_func(*args):
h = hashlib.sha1(str(original_func.__name__)... |
Dummy decorator. | def dummy(func):
""" Dummy decorator. """
return func |
Cache (or persist) returned value of function in a json file . | def persist_to_file(file_name):
"""
Cache (or persist) returned value of function in a json file .
"""
def decorator(original_func):
if not os.path.exists(file_name):
cache = {}
else:
try:
cache = json.load(open(file_name, 'rt'))
exc... |
Cache (or persist) returned value of function in a directory of files. | def persist_to_dir(dir_name):
"""
Cache (or persist) returned value of function in a directory of files.
"""
def decorator(original_func):
def new_func(*args):
h = hashlib.sha1(str(original_func.__name__) + str(args)).hexdigest()
file_name = os.path.join(dir_name, h)
... |
Convert a Python 2 pickle to Python 3 | def convert(old_pkl):
"""
Convert a Python 2 pickle to Python 3
"""
# Make a name for the new pickle
new_pkl = os.path.splitext(os.path.basename(old_pkl))[0]+"_p3.pkl"
# Convert Python 2 "ObjectType" to Python 3 object
dill._dill._reverse_typemap["ObjectType"] = object
# Open the pickl... |
>>> get_file_name_without_extension('yuv/src01_hrc01.yuv')
'src01_hrc01'
>>> get_file_name_without_extension('yuv/src01_hrc01')
'src01_hrc01'
>>> get_file_name_without_extension('abc/xyz/src01_hrc01.yuv')
'src01_hrc01'
>>> get_file_name_without_extension('abc/xyz/src01_hrc01.sdr.yuv')
'src01_hrc01.sdr'
>>> get_file_nam... | def get_file_name_without_extension(path):
"""
>>> get_file_name_without_extension('yuv/src01_hrc01.yuv')
'src01_hrc01'
>>> get_file_name_without_extension('yuv/src01_hrc01')
'src01_hrc01'
>>> get_file_name_without_extension('abc/xyz/src01_hrc01.yuv')
'src01_hrc01'
>>> get_file_name_wit... |
>>> get_file_name_with_extension('yuv/src01_hrc01.yuv')
'src01_hrc01.yuv'
>>> get_file_name_with_extension('src01_hrc01.yuv')
'src01_hrc01.yuv'
>>> get_file_name_with_extension('abc/xyz/src01_hrc01.yuv')
'src01_hrc01.yuv' | def get_file_name_with_extension(path):
"""
>>> get_file_name_with_extension('yuv/src01_hrc01.yuv')
'src01_hrc01.yuv'
>>> get_file_name_with_extension('src01_hrc01.yuv')
'src01_hrc01.yuv'
>>> get_file_name_with_extension('abc/xyz/src01_hrc01.yuv')
'src01_hrc01.yuv'
"""
return Path(... |
>>> get_file_name_extension("file:///mnt/zli/test.txt")
'txt'
>>> get_file_name_extension("test.txt")
'txt'
>>> get_file_name_extension("abc")
''
>>> get_file_name_extension("test.265")
'265' | def get_file_name_extension(path):
"""
>>> get_file_name_extension("file:///mnt/zli/test.txt")
'txt'
>>> get_file_name_extension("test.txt")
'txt'
>>> get_file_name_extension("abc")
''
>>> get_file_name_extension("test.265")
'265'
"""
return Path(path).suffix[1:] |
>>> get_dir_without_last_slash('abc/src01_hrc01.yuv')
'abc'
>>> get_dir_without_last_slash('src01_hrc01.yuv')
''
>>> get_dir_without_last_slash('abc/xyz/src01_hrc01.yuv')
'abc/xyz'
>>> get_dir_without_last_slash('abc/xyz/')
'abc/xyz' | def get_dir_without_last_slash(path: str) -> str:
"""
>>> get_dir_without_last_slash('abc/src01_hrc01.yuv')
'abc'
>>> get_dir_without_last_slash('src01_hrc01.yuv')
''
>>> get_dir_without_last_slash('abc/xyz/src01_hrc01.yuv')
'abc/xyz'
>>> get_dir_without_last_slash('abc/xyz/')
'abc/... |
Normalized string representation with sorted keys.
>>> get_normalized_string_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, })
'bitrate_kbps_45_max_buffer_sec_5.0' | def get_normalized_string_from_dict(d):
""" Normalized string representation with sorted keys.
>>> get_normalized_string_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, })
'bitrate_kbps_45_max_buffer_sec_5.0'
"""
return '_'.join(map(lambda k: '{k}_{v}'.format(k=k,v=d[k]), sorted(d.keys()))) |
Hashable tuple of values with sorted keys.
>>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, })
(45, 5.0)
>>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, "resolutions": [(740, 480), (1920, 1080), ]})
(45, 5.0, ((740, 480), (1920, 1080))) | def get_hashable_value_tuple_from_dict(d):
""" Hashable tuple of values with sorted keys.
>>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, })
(45, 5.0)
>>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, "resolutions": [(740, 480), (1920,... |
String representation with sorted keys and values for recursive dict.
>>> get_unique_str_from_recursive_dict({'a':1, 'b':2, 'c':{'x':'0', 'y':'1'}})
'{"a": 1, "b": 2, "c": {"x": "0", "y": "1"}}'
>>> get_unique_str_from_recursive_dict({'a':1, 'c':2, 'b':{'y':'1', 'x':'0', }})
'{"a": 1, "b": {"x": "0", "y": "1"}, "c": 2... | def get_unique_str_from_recursive_dict(d):
""" String representation with sorted keys and values for recursive dict.
>>> get_unique_str_from_recursive_dict({'a':1, 'b':2, 'c':{'x':'0', 'y':'1'}})
'{"a": 1, "b": 2, "c": {"x": "0", "y": "1"}}'
>>> get_unique_str_from_recursive_dict({'a':1, 'c':2, 'b':{'y... |
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: 1 < x <= 3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
[1, 3]
>>> indices([1,2,3,1,2,3,1,2,3], lambda x: x > 2)
[2, 5, ... | def indices(a, func):
"""
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: 1 < x <= 3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
... |
Import a python file as a module, allowing overriding some of the variables.
Assumption: in the original python file, variables to be overridden get assigned once only, in a single line. | def import_python_file(filepath : str, override : dict = None):
"""
Import a python file as a module, allowing overriding some of the variables.
Assumption: in the original python file, variables to be overridden get assigned once only, in a single line.
"""
if override is None:
filename = g... |
>>> make_absolute_path('abc/cde.fg', '/xyz/')
'/xyz/abc/cde.fg'
>>> make_absolute_path('/abc/cde.fg', '/xyz/')
'/abc/cde.fg' | def make_absolute_path(path: str, current_dir: str) -> str:
"""
>>> make_absolute_path('abc/cde.fg', '/xyz/')
'/xyz/abc/cde.fg'
>>> make_absolute_path('/abc/cde.fg', '/xyz/')
'/abc/cde.fg'
"""
assert current_dir.endswith('/'), f"expect current_dir ends with '/', but is: {current_dir}"
if... |
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 3, 5, '--xyz')
'123'
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 0, 5, '--xyz')
'123'
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 4, 5, '--xyz')
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 5, 5, '--xyz')
>>> get_cmd_option(['a', 'b', 'c', '--xy... | def get_cmd_option(argv, begin, end, option):
"""
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 3, 5, '--xyz')
'123'
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 0, 5, '--xyz')
'123'
>>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 4, 5, '--xyz')
>>> get_cmd_option(['a', 'b'... |
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'c')
True
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'c')
False
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'd')
True
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'a')
False
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'b')
False | def cmd_option_exists(argv, begin, end, option):
"""
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'c')
True
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'c')
False
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'd')
True
>>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'a'... |
>>> index_and_value_of_min([2, 0, 3])
(1, 0) | def index_and_value_of_min(l):
"""
>>> index_and_value_of_min([2, 0, 3])
(1, 0)
"""
return min(enumerate(l), key=lambda x: x[1]) |
Build my own parallelized map function since multiprocessing's Process(),
or Pool.map() cannot meet my both needs:
1) be able to control the maximum number of processes in parallel
2) be able to take in non-picklable objects as arguments | def parallel_map(func, list_args, processes=None, sleep_sec=0.01):
"""
Build my own parallelized map function since multiprocessing's Process(),
or Pool.map() cannot meet my both needs:
1) be able to control the maximum number of processes in parallel
2) be able to take in non-picklable objects as a... |
>>> check_program_exist("xxxafasd34df")
False
>>> check_program_exist("xxxafasd34df f899")
False
>>> check_program_exist("ls")
True
>>> check_program_exist("ls -all")
True
>>> check_program_exist("pwd")
True | def check_program_exist(program):
"""
>>> check_program_exist("xxxafasd34df")
False
>>> check_program_exist("xxxafasd34df f899")
False
>>> check_program_exist("ls")
True
>>> check_program_exist("ls -all")
True
>>> check_program_exist("pwd")
True
"""
try:
wit... |
>>> check_scanf_match('frame00000000.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame00000003.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame0000001.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame00000001.icpff', 'frame%08d.icpf')
True
>>> check_scanf_match('gframe00000001.icpff', 'frame... | def check_scanf_match(string, template):
"""
>>> check_scanf_match('frame00000000.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame00000003.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame0000001.icpf', 'frame%08d.icpf')
True
>>> check_scanf_match('frame00000001.icpff'... |
Unfold a dictionary of lists into a list of dictionaries.
>>> dict_of_lists = {'norm_type':['normalize'], 'n_estimators':[10, 50], 'random_state': [0]}
>>> expected = [{'n_estimators': 10, 'norm_type': 'normalize', 'random_state': 0}, {'n_estimators': 50, 'norm_type': 'normalize', 'random_state': 0}]
>>> unroll_dict_o... | def unroll_dict_of_lists(dict_of_lists):
""" Unfold a dictionary of lists into a list of dictionaries.
>>> dict_of_lists = {'norm_type':['normalize'], 'n_estimators':[10, 50], 'random_state': [0]}
>>> expected = [{'n_estimators': 10, 'norm_type': 'normalize', 'random_state': 0}, {'n_estimators': 50, 'norm_... |
>>> neg_if_even(2)
-1
>>> neg_if_even(1)
1
>>> neg_if_even(0)
-1
>>> neg_if_even(-1)
1
>>> neg_if_even(-2)
-1 | def neg_if_even(x):
"""
>>> neg_if_even(2)
-1
>>> neg_if_even(1)
1
>>> neg_if_even(0)
-1
>>> neg_if_even(-1)
1
>>> neg_if_even(-2)
-1
"""
return 1 - (x % 2 == 0) * 2 |
>>> get_unique_sorted_list([3, 4, 4, 1])
[1, 3, 4]
>>> get_unique_sorted_list([])
[] | def get_unique_sorted_list(l):
"""
>>> get_unique_sorted_list([3, 4, 4, 1])
[1, 3, 4]
>>> get_unique_sorted_list([])
[]
"""
return sorted(list(set(l))) |
>>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) == {'a': 1, 'c': 2}
True | def dedup_value_in_dict(d):
"""
>>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) == {'a': 1, 'c': 2}
True
"""
reversed_d = dict()
keys = sorted(d.keys())
for key in keys:
value = d[key]
if value not in reversed_d:
reversed_d[value] = key
d_ = dict()
fo... |
Find parameters of a linear function connecting first_point and second_point
>>> find_linear_function_parameters((1, 1), (0, 0))
Traceback (most recent call last):
...
AssertionError: first_point coordinates need to be smaller or equal to second_point coordinates
>>> find_linear_function_parameters((0, 1), (0, 0))
Tra... | def find_linear_function_parameters(p1, p2):
"""
Find parameters of a linear function connecting first_point and second_point
>>> find_linear_function_parameters((1, 1), (0, 0))
Traceback (most recent call last):
...
AssertionError: first_point coordinates need to be smaller or equal to second_... |
A piecewise linear mapping function, defined by the boundary points of each segment. For example,
a function consisting of 3 segments is defined by 4 points. The x-coordinate of each point need to be
greater that the x-coordinate of the previous point, the y-coordinate needs to be greater or equal.
The function continu... | def piecewise_linear_mapping(x, knots):
"""
A piecewise linear mapping function, defined by the boundary points of each segment. For example,
a function consisting of 3 segments is defined by 4 points. The x-coordinate of each point need to be
greater that the x-coordinate of the previous point, the y-c... |
>>> round_up_to_odd(32.6)
33
>>> round_up_to_odd(33.1)
35 | def round_up_to_odd(f):
"""
>>> round_up_to_odd(32.6)
33
>>> round_up_to_odd(33.1)
35
"""
return int(np.ceil(f) // 2 * 2 + 1) |
>>> fit = linear_fit([0, 1], [0, 1])
>>> (fit[0][0], fit[0][1])
(1.0, 0.0) | def linear_fit(x, y):
"""
>>> fit = linear_fit([0, 1], [0, 1])
>>> (fit[0][0], fit[0][1])
(1.0, 0.0)
"""
assert isinstance(x, (list, tuple, np.ndarray)), 'x must be a list, tuple, or a numpy array'
assert len(x) == np.size(x) and len(x) > 0, 'x must be one-dimensional with non-zero length'
... |
>>> map_yuv_type_to_bitdepth('yuv420p')
8
>>> map_yuv_type_to_bitdepth('yuv422p')
8
>>> map_yuv_type_to_bitdepth('yuv444p')
8
>>> map_yuv_type_to_bitdepth('yuv420p10le')
10
>>> map_yuv_type_to_bitdepth('yuv422p10le')
10
>>> map_yuv_type_to_bitdepth('yuv444p10le')
10
>>> map_yuv_type_to_bitdepth('yuv420p12le')
12
>>> ma... | def map_yuv_type_to_bitdepth(yuv_type):
"""
>>> map_yuv_type_to_bitdepth('yuv420p')
8
>>> map_yuv_type_to_bitdepth('yuv422p')
8
>>> map_yuv_type_to_bitdepth('yuv444p')
8
>>> map_yuv_type_to_bitdepth('yuv420p10le')
10
>>> map_yuv_type_to_bitdepth('yuv422p10le')
10
>>> map_... |
Returns an iterator that calls read(*args) on the inputFile. | def readiter(inputFile, *args):
"""Returns an iterator that calls read(*args) on the inputFile."""
while True:
ch = inputFile.read(*args)
if ch:
yield ch
else:
raise StopIteration |
Returns true if 'thing' looks iterable. | def isIterable(thing):
"""Returns true if 'thing' looks iterable."""
try:
iter(thing)
except TypeError:
return False
return True |
Returns true if thing looks like a file. | def isFileLike(thing):
"""Returns true if thing looks like a file."""
if hasattr(thing, "read") and hasattr(thing, "seek"):
try:
thing.seek(1, 1)
thing.seek(-1, 1)
return True
except IOError:
pass
return False |
Try to coerse 'thing' into a CharacterBuffer. 'thing' can be
an instance of:
1. CharacterBuffer
2. A file-like object,
3. An iterable.
makeCharBuffer() will make guesses in that order. | def makeCharBuffer(thing):
"""Try to coerse 'thing' into a CharacterBuffer. 'thing' can be
an instance of:
1. CharacterBuffer
2. A file-like object,
3. An iterable.
makeCharBuffer() will make guesses in that order.
"""
if isinstance(thing, CharacterBuffer):
retu... |
scanf(formatString) -> tuple
Scans standard input for formats specified in the formatString. See
module's docs for list of supported format characters. | def scanf(formatString):
"""scanf(formatString) -> tuple
Scans standard input for formats specified in the formatString. See
module's docs for list of supported format characters."""
return bscanf(_STDIN, formatString) |
sscanf(inputString, formatString) -> tuple
Scans inputString for formats specified in the formatString. See
module's docs for list of supported format characters. | def sscanf(inputString, formatString):
"""sscanf(inputString, formatString) -> tuple
Scans inputString for formats specified in the formatString. See
module's docs for list of supported format characters."""
return bscanf(CharacterBufferFromIterable(inputString), formatString) |
fscanf(inputFile, formatString) -> tuple
Scans inputFile for formats specified in the formatString. See
module's docs for list of supported format characters. | def fscanf(inputFile, formatString):
"""fscanf(inputFile, formatString) -> tuple
Scans inputFile for formats specified in the formatString. See
module's docs for list of supported format characters."""
buffer = CharacterBufferFromFile(inputFile)
return bscanf(buffer, formatString) |
fscanf(buffer, formatString) -> tuple
Scans a CharacterBuffer 'buffer' for formats specified in the
formatString. See scanf module's docs for list of supported format
characters. | def bscanf(buffer, formatString):
"""fscanf(buffer, formatString) -> tuple
Scans a CharacterBuffer 'buffer' for formats specified in the
formatString. See scanf module's docs for list of supported format
characters."""
# TODO: we may want to do some caching here of compiled formatStrings,
# similar to tha... |
Returns true if the charcter looks like whitespace.
We follow the definition of C's isspace() function. | def isWhitespaceChar(ch, _set=_WHITESPACE_SET):
"""Returns true if the charcter looks like whitespace.
We follow the definition of C's isspace() function.
"""
return ch in _set |
Scans for whitespace. Returns all the whitespace it collects. | def handleWhitespace(buffer):
"""Scans for whitespace. Returns all the whitespace it collects."""
chars = []
while True:
ch = buffer.getch()
if isWhitespaceChar(ch):
chars.append(ch)
else:
buffer.ungetch(ch)
break
return ''.join(chars) |
Tries to scan for an integer. If 'optional' is set to False,
returns None if an integer can't be successfully scanned. | def handleDecimalInt(buffer, optional=False, allowLeadingWhitespace=True):
"""Tries to scan for an integer. If 'optional' is set to False,
returns None if an integer can't be successfully scanned."""
if allowLeadingWhitespace:
handleWhitespace(buffer) # eat leading spaces
chars = []
chars ... |
Read as many characters are there are in the buffer. | def handleChars(buffer,
allowLeadingWhitespace=False,
isBadCharacter=lambda ch: False,
optional=False):
"""Read as many characters are there are in the buffer."""
if allowLeadingWhitespace:
handleWhitespace(buffer)
chars = []
chars += buffer.scanPr... |
Reading a string format is just an application of reading
characters (skipping leading spaces, and reading up to space). | def handleString(buffer, allowLeadingWhitespace=True):
"""Reading a string format is just an application of reading
characters (skipping leading spaces, and reading up to space)."""
return handleChars(buffer,
allowLeadingWhitespace=allowLeadingWhitespace,
isBadC... |
Constructs a Handler that caps the number of bytes that can be read
from the byte buffer. | def makeWidthLimitedHandler(handler, width, ignoreWhitespace=False):
"""Constructs a Handler that caps the number of bytes that can be read
from the byte buffer."""
def f(buffer):
return handler(CappedBuffer(buffer, width, ignoreWhitespace))
return f |
Given a format string, emits a new CompiledPattern that eats
CharacterBuffers and returns captured values as a tuple.
If there's a failure during scanning, raises IncompleteCaptureError,
with args being a two-tuple of the FormatError, and the results that
were captured before the error occurred. | def compile(formatString):
"""Given a format string, emits a new CompiledPattern that eats
CharacterBuffers and returns captured values as a tuple.
If there's a failure during scanning, raises IncompleteCaptureError,
with args being a two-tuple of the FormatError, and the results that
were captured... |
Given suppression, width, and a formatType, returns a function
that eats a buffer and returns that thing. | def makeFormattedHandler(suppression, width, formatCh):
"""Given suppression, width, and a formatType, returns a function
that eats a buffer and returns that thing."""
def applySuppression(handler):
if suppression:
return makeIgnoredHandler(handler)
return handler
def applyW... |
x: rows - observation vector 0, 1, 2, ...
return a covariance matrix based on kendall correlation | def _cov_kendall(x):
"""
x: rows - observation vector 0, 1, 2, ...
return a covariance matrix based on kendall correlation
"""
m, n = x.shape
cov_ = np.zeros([m, m])
for i in range(m):
for j in range(i, m):
# scipy 1.2.0 kendalltau() has an issue with the p-value of two ... |
Replace UUIDs in a command line with pattern [UUID]
>>> replace_uuid('/tmp/72b3a7af-204c-4455-afe5-be2d536f2fdd/dv_el_out_1.h265')
'/tmp/[UUID]/dv_el_out_1.h265' | def replace_uuid(command_line: str) -> str:
"""
Replace UUIDs in a command line with pattern [UUID]
>>> replace_uuid('/tmp/72b3a7af-204c-4455-afe5-be2d536f2fdd/dv_el_out_1.h265')
'/tmp/[UUID]/dv_el_out_1.h265'
"""
uuid_pattern = r'\b[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}\b'
return re.sub(... |
Replace root directory specified in input with pattern [ROOT]
>>> replace_root('/opt/project/vmaf/libvmaf/build/tools/vmaf', root='/opt/project')
'[ROOT]/vmaf/libvmaf/build/tools/vmaf'
>>> replace_root('/tmp/72b3a7af-204c-4455-afe5-be2d536f2fdd', root='/opt/project')
'/tmp/72b3a7af-204c-4455-afe5-be2d536f2fdd' | def replace_root(command_line: str, root: str) -> str:
"""
Replace root directory specified in input with pattern [ROOT]
>>> replace_root('/opt/project/vmaf/libvmaf/build/tools/vmaf', root='/opt/project')
'[ROOT]/vmaf/libvmaf/build/tools/vmaf'
>>> replace_root('/tmp/72b3a7af-204c-4455-afe5-be2d536f... |
Replaces multiple whitespace between words with a single one, and removes redundant whitespace at the start and end
>>> remove_redundant_whitespace(' a b c d e f ')
'a b c d e f'
>>> remove_redundant_whitespace('cat /opt/project/vmaf/workspace/workdir/9e693ccc-7706-49c5-8c8e-40f5242e81a6/dis_test_0_0_seeking_10... | def remove_redundant_whitespace(command_line: str) -> str:
"""
Replaces multiple whitespace between words with a single one, and removes redundant whitespace at the start and end
>>> remove_redundant_whitespace(' a b c d e f ')
'a b c d e f'
>>> remove_redundant_whitespace('cat /opt/project/... |
Removes a whitespace-separated option that is prefixed by two dashes, e.g., --option_name.
>>> remove_option('vmaf --reference REFERENCE --model MODEL', 'model')
'vmaf --reference REFERENCE'
>>> remove_option('vmaf --model MODEL --reference REFERENCE', 'model')
'vmaf --reference REFERENCE'
>>> remove_option(remove_opti... | def remove_option(command_line: str, option: str) -> str:
"""
Removes a whitespace-separated option that is prefixed by two dashes, e.g., --option_name.
>>> remove_option('vmaf --reference REFERENCE --model MODEL', 'model')
'vmaf --reference REFERENCE'
>>> remove_option('vmaf --model MODEL --referen... |
Removes strings from the command line that contain a specific substring
>>> remove_elements_containing_substring('cat /opt/project/vmaf/workspace/workdir/9e693ccc-7706-49c5-8c8e-40f5242e81a6/dis_test_0_0_seeking_10_288_375_notyuv_lanczos_accurate_rnd_10to14_prece_FFmpegDecoder_postunsharpunsharp_q_480x360_PostDecode_tm... | def remove_elements_containing_substring(command_line: str, sub_str: str) -> str:
"""
Removes strings from the command line that contain a specific substring
>>> remove_elements_containing_substring('cat /opt/project/vmaf/workspace/workdir/9e693ccc-7706-49c5-8c8e-40f5242e81a6/dis_test_0_0_seeking_10_288_375... |
>>> self = MyTestCase()
>>> self.setUp()
>>> assert_equivalent_commands(self, cmds=["/opt/project/vmaf/libvmaf/build/tools/vmaf /tmp/72b3a7af-204c-4455-afe5-be2d536f2fdd/dv_el_out_1.h265"], cmds_expected=["/opt/project/vmaf/libvmaf/build/tools/vmaf /tmp/82b3a7af-304c-5455-afe5-be2d536f2fdd/dv_el_out_1.h265"], root="/op... | def assert_equivalent_commands(self, cmds: List[str], cmds_expected: List[str], root: str, root_expected: str, do_replace_uuid: bool = True,
options_to_remove: Optional[List[str]] = None, substrings_to_remove: Optional[List[str]] = None):
"""
>>> self = MyTestCase()
>>> self.s... |
Load pretrained model from file | def LoadModel(path, dbtype='minidb'):
'''
Load pretrained model from file
'''
log.info("Loading path: {}".format(path))
meta_net_def = pred_exp.load_from_db(path, dbtype)
init_net = core.Net(pred_utils.GetNet(
meta_net_def, predictor_constants.GLOBAL_INIT_NET_TYPE))
predict_init_net ... |
function that returns all the model weights in a dict | def GetModelWeights(model, gpu_id=0):
'''
function that returns all the model weights in a dict
'''
model_ops = model.net.Proto().op
master_gpu = 'gpu_{}'.format(gpu_id)
param_ops = []
for idx in range(len(model_ops)):
op_type = model.net.Proto().op[idx].type
op_input = model... |
well, turns out that SaveModel savs the vars with the gpu_X/ prefix...
this function returns the GPUs used during training. | def getTrainingGPUs(path, dbtype):
'''
well, turns out that SaveModel savs the vars with the gpu_X/ prefix...
this function returns the GPUs used during training.
'''
meta_net_def = pred_exp.load_from_db(path, dbtype)
gpus = set()
def is_number(s):
try:
float(s)
... |
Add the momentum-SGD update. | def AddMomentumParameterUpdate(train_model, LR):
'''
Add the momentum-SGD update.
'''
params = train_model.GetParams()
assert(len(params) > 0)
for param in params:
param_grad = train_model.param_to_grad[param]
param_momentum = train_model.param_init_net.ConstantFill(
... |
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) | def crop(clip, i, j, h, w):
"""
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
"""
assert len(clip.size()) == 4, "clip should be a 4D tensor"
return clip[..., i : i + h, j : j + w] |
Args:
clip (torch.tensor): Video clip to be
cropped along the temporal axis. Size is (C, T, H, W) | def temporal_center_crop(clip, clip_len):
"""
Args:
clip (torch.tensor): Video clip to be
cropped along the temporal axis. Size is (C, T, H, W)
"""
assert len(clip.size()) == 4, "clip should be a 4D tensor"
assert clip.size(1) >= clip_len, "clip is shorter than the proposed lenght"
... |
Do spatial cropping and resizing to the video clip
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped region.
w (int): Wid... | def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"):
"""
Do spatial cropping and resizing to the video clip
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) ... |
Convert tensor data type from uint8 to float, divide value by 255.0 and
permute the dimenions of clip tensor
Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) | def to_tensor(clip):
"""
Convert tensor data type from uint8 to float, divide value by 255.0 and
permute the dimenions of clip tensor
Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W)
"""
_i... |
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
mean (tuple): pixel RGB mean. Size is (3)
std (tuple): pixel standard deviation. Size is (3)
Returns:
normalized clip (torch.tensor): Size is (C, T, H, W) | def normalize(clip, mean, std, inplace=False):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
mean (tuple): pixel RGB mean. Size is (3)
std (tuple): pixel standard deviation. Size is (3)
Returns:
normalized clip (torch.tensor): Size is (C, T,... |
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W) | def hflip(clip):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
return clip.flip((-1)) |
Computes the accuracy over the k top predictions
for the specified values of k | def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions
for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.... |
This function disables printing when not in master process | def setup_for_distributed(is_master):
"""
This function disables printing when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_pri... |
Get the vocab file and casing info from the Hub module. | def create_tokenizer_from_hub_module(bert_path, sess):
"""Get the vocab file and casing info from the Hub module."""
bert_module = hub.Module(bert_path)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
vocab_file, do_lower_case = tf.print(
[tokenization_info["vocab_fi... |
Converts a single `InputExample` into a single `InputFeatures`. | def convert_single_example(tokenizer, example, max_seq_length=256):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
input_ids = [0] * max_seq_length
input_mask = [0] * max_seq_length
segment_ids = [0] * max_seq_length
... |
Convert a set of `InputExample`s to a list of `InputFeatures`. | def convert_examples_to_features(tokenizer, examples, max_seq_length=256):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
input_ids, input_masks, segment_ids, labels = [], [], [], []
# for example in tqdm(examples, desc="Converting examples to features"):
for example in examples:
... |
Create InputExamples | def convert_text_to_examples(texts, labels):
"""Create InputExamples"""
InputExamples = []
for text, label in zip(texts, labels):
InputExamples.append(
InputExample(guid=None, text_a=" ".join(text), text_b=None, label=label)
)
return InputExamples |
Tokenize text and stem words removing punctuation | def process_text(text, stem=True):
""" Tokenize text and stem words removing punctuation """
text = text.translate(str.maketrans('','', string.punctuation))
# text = text.translate(str.maketrans('', '', '1234567890'))
tokens = word_tokenize(text)
if stem:
stemmer = PorterStemmer()
... |
Transform texts to Tf-Idf coordinates and cluster texts using K-Means | def cluster_texts(texts, clusters):
""" Transform texts to Tf-Idf coordinates and cluster texts using K-Means """
stop_words = stopwords.words('english') #+ list(string.punctuation)
# print('Stop word')
logger.debug('Initializing tfidf model')
vectorizer = TfidfVectorizer(tokenizer=process_text,
... |
This module is used in a Lambda layer with our keras model. The model is not performing well. One hypothesis is lambda layers don't train.
Replacing with above Class works but there are some import statement issues.
:param inp:
:return: | def ELMoEmbedding(inp):
"""
This module is used in a Lambda layer with our keras model. The model is not performing well. One hypothesis is lambda layers don't train.
Replacing with above Class works but there are some import statement issues.
:param inp:
:return:
"""
trainable = True
po... |
Defines parser arguments
:return: parser arguments | def parse_arguments():
"""
Defines parser arguments
:return: parser arguments
"""
parser = argparse.ArgumentParser(
description='Run modeling tasks on visual question geenration task')
parser.add_argument('-model_dir', type=str, default='model',
help='Directory to... |
Provides logging functionality
:param log_level: describes log level of logger functionality
:return: logger | def get_logger(log_level):
"""
Provides logging functionality
:param log_level: describes log level of logger functionality
:return: logger
"""
file_handler = logging.FileHandler(filename='run.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [stdout_handler, file_handl... |
Load model
:param question_generator: Class containing all question generator modules. Defined in question_generator_model.py
:return: model defition file | def load_model(question_generator):
"""
Load model
:param question_generator: Class containing all question generator modules. Defined in question_generator_model.py
:return: model defition file
"""
# Build the model
if question_generator.datasets.use_keyword:
model = question_genera... |
This module saves obj into a pkl file
:param obj: pickle object to be saved
:param name: Name of file
:return: None | def save_obj(obj, name):
"""
This module saves obj into a pkl file
:param obj: pickle object to be saved
:param name: Name of file
:return: None
"""
print('Saving', name)
with open(name, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) |
This module loads the objects defined under name
:param name: Name of pickle object to be loaded
:return: Pickle object | def load_obj(name):
"""
This module loads the objects defined under name
:param name: Name of pickle object to be loaded
:return: Pickle object
"""
print('Loading', name)
with open(name, 'rb') as f:
return pickle.load(f) |
Installs the libraries that will be bundled with the extension. | def install_bundled_libs(session):
"""Installs the libraries that will be bundled with the extension."""
session.install("wheel")
_install_bundle(session) |
Sets up the extension for development. | def setup(session: nox.Session) -> None:
"""Sets up the extension for development."""
_setup_template_environment(session) |
Runs all the tests for the extension. | def tests(session: nox.Session) -> None:
"""Runs all the tests for the extension."""
session.install("-r", "src/test/python_tests/requirements.txt")
session.run("pytest", "src/test/python_tests")
session.install("freezegun")
session.run("pytest", "build") |
Runs linter and formatter checks on python files. | def lint(session: nox.Session) -> None:
"""Runs linter and formatter checks on python files."""
session.install("-r", "src/test/python_tests/requirements.txt")
session.install("flake8")
session.run("flake8", "./bundled/tool")
session.run(
"flake8",
"--extend-exclude",
"./src... |
Builds VSIX package for publishing. | def build_package(session: nox.Session) -> None:
"""Builds VSIX package for publishing."""
_check_files(["README.md", "LICENSE", "SECURITY.md", "SUPPORT.md"])
_setup_template_environment(session)
session.run("npm", "install", external=True)
session.run("npm", "run", "vsce-package", external=True) |
Updates build number for the extension. | def update_build_number(session: nox.Session) -> None:
"""Updates build number for the extension."""
if len(session.posargs) == 0:
session.log("No updates to package version")
return
package_json_path = pathlib.Path(__file__).parent / "package.json"
session.log(f"Reading package.json at... |
Ensures the formatter version in 'requirements.txt' matches 'readme.md'. | def validate_readme(session: nox.Session) -> None:
"""Ensures the formatter version in 'requirements.txt' matches 'readme.md'."""
readme_file = pathlib.Path(__file__).parent / "README.md"
name = _get_module_name()
version = _get_version(name)
session.log(f"Looking for {name}={version} in README.m... |
Update pip and npm packages. | def update_packages(session: nox.Session) -> None:
"""Update pip and npm packages."""
session.install("wheel", "pip-tools")
_update_pip_packages(session)
_update_npm_packages(session)
_update_readme() |
Returns True if there are changes in the working tree. | def has_changes() -> bool:
"""Returns True if there are changes in the working tree."""
print("Detecting changes")
result = subprocess.run(["git", "diff", "--exit-code"], check=False)
return result.returncode != 0 |
Returns the next odd number. | def get_next_odd_number(number: int) -> int:
"""Returns the next odd number."""
return number + 1 if number % 2 == 0 else number + 2 |
Returns the next even number. | def get_next_even_number(number: int) -> int:
"""Returns the next even number."""
return number if number % 2 == 0 else number + 1 |
Create `package.json` in `directory` with a specified version of `version`. | def create_package_json(directory, version):
"""Create `package.json` in `directory` with a specified version of `version`."""
package_json = directory / "package.json"
package_json.write_text(json.dumps({"version": version}), encoding="utf-8")
return package_json |
Builds the arguments parser. | def build_arg_parse() -> argparse.ArgumentParser:
"""Builds the arguments parser."""
parser = argparse.ArgumentParser(
description="This script updates the python extension micro version based on the release or pre-release channel."
)
parser.add_argument(
"--release",
action="sto... |
Returns True if `v` is even. | def is_even(v: Union[int, str]) -> bool:
"""Returns True if `v` is even."""
return not int(v) % 2 |
Generates the micro build number.
The format is `1<Julian day><hour><minute>`. | def micro_build_number() -> str:
"""Generates the micro build number.
The format is `1<Julian day><hour><minute>`.
"""
return f"1{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%j%H%M')}" |
Parse a version string into a tuple of version parts. | def parse_version(version: str) -> Tuple[str, str, str, str]:
"""Parse a version string into a tuple of version parts."""
major, minor, parts = version.split(".", maxsplit=2)
try:
micro, suffix = parts.split("-", maxsplit=1)
except ValueError:
micro = parts
suffix = ""
return... |
Return a list of text edits to transform old_text into new_text. | def get_text_edits(
old_text: str,
new_text: str,
position_encoding: lsp.PositionEncodingKind,
timeout: Optional[int] = None,
) -> List[lsp.TextEdit]:
"""Return a list of text edits to transform old_text into new_text."""
lines = old_text.splitlines(True)
codec = PositionCodec(position_enco... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.