content stringlengths 42 6.51k |
|---|
def _line_is_hyphens(line):
"""Returns whether the line is entirely hyphens (and not blank)."""
return line and not line.strip('-') |
def get_filename(abs_path):
"""Returns the basename of the given absolute path."""
return abs_path.rsplit("/", 1)[-1].rsplit("\\", 1)[-1] |
def format_orbit_notes(text: str) -> str:
"""Given orbit notes returns them as HTML"""
template = '<div class="orbit-notes"><p>{}</p></div>'
html_text = text.replace("\n", "</p><p>")
return template.format(html_text) |
def strip_id_from_matrix(mat):
"""
Remove the ID (1st row element) form a matrix
:param mat: a 2D list
:rtype: a 2D list with the 1st row elelemnt (ID) removed
"""
new_mat = []
for i in range(0, len(mat)):
new_mat.append(mat[i][1:])
return new_mat |
def get_status_code_value(status_code):
"""function to return appropriate status code value from the dictionary"""
status_code_dict = {
"100": "Continue", "101": "Switching Protocols", "200": "OK", "201": "Created",
"202": "Accepted", "203": "Non-authoritative Information", "204": "No Conten... |
def bench5(x):
"""A benchmark function for test purposes.
f(x) = float(x[0]) ** 2 + x[1] ** 2
where x is a string. It has a single minima with f(x) = 0 at x[0] = "0"
and x[1] = "0"
This benchmark is used for checking support of mixed spaces.
"""
return float(x[0]) ** 2 + x[1] ** 2 |
def split_url(url):
"""
Split the given URL ``base#anchor`` into ``(base, anchor)``,
or ``(base, None)`` if no anchor is present.
In case there are two or more ``#`` characters,
return only the first two tokens: ``a#b#c => (a, b)``.
:param string url: the url
:rtype: list of str
"""
... |
def int_to_string(integer, keyspace_chars):
""" Turn a positive integer into a string. """
if not integer > 0:
raise ValueError('integer must be > 0')
output = ""
while integer > 0:
integer, digit = divmod(integer, len(keyspace_chars))
output += keyspace_chars[digit]
return o... |
def runlength2(blk, p0, p1, bsf):
""" p0 is the source position, p1 is the dest position
Return the length of run of common chars
"""
if blk[p0:p0+bsf+1] != blk[p1:p1+bsf+1]:
return 0
for i in range(bsf + 1, len(blk) - p1):
if blk[p0:p0+i] != blk[p1:p1+i]:
return i - 1
... |
def get_binary_representation(n, num_digits):
"""
Helper function to get a binary representation of items to add to a subset,
which combinations() uses to construct and append another item to the powerset.
Parameters:
n and num_digits are non-negative ints
Returns:
a num_digit... |
def origin(current, start, end, cum_extents, screen, moving):
"""Determine new origin for screen view if necessary.
The part of the DataFrame displayed on screen is conceptually a box which
has the same dimensions as the screen and hovers over the contents of the
DataFrame. The origin of the relative... |
def _amplify_qm(text):
"""
check for added emphasis resulting from question marks (2 or 3+)
"""
qm_count = text.count("?")
qm_amplifier = 0
if qm_count > 1:
if qm_count <= 3:
# (empirically derived mean sentiment intensity rating increase for
# question marks)
... |
def VOLTStoHEX(volts):
""" DAC: 1000.0 volts full scale (FFFF).
(for setting DAC output)
VOLTStoHEX(1000.0) => 'FFFF'
VOLTStoHEX( 900.0) => 'E665' """
return hex(int(volts * 65.535))[2:].upper() |
def pad_pokemon_id(pokemon_id: int) -> str:
"""Pads a pokemon's id with 0's.
Examples:
1 -> 001
23 -> 023
144 -> 144
Args:
pokemon_id: The pokemon's id
Returns:
A string with padded 0's in front.
"""
return f"{pokemon_id:03}" |
def get_commit_merge_message(
head_commit_id: str, user_commit_id: str, user_input: str
) -> str:
"""Shortens the commit ids and adds them to a commit message;
if user used a branch name, the latter will appear next to the id.
Example: `Merged 123456 (HEAD) with 654321 (<branch_name>)`.
"""
shor... |
def isnumeric(value):
"""
"0.2355" would return True.
A little auxiliary function for command line parsing.
"""
return str(value).replace(".", "").replace("-", "").isdigit() |
def _decode_node(s):
"""Map string `s` to node-like integer."""
if s == 'F':
return -1
elif s == 'T':
return 1
else:
return int(s) |
def to_tuple(expression):
""" Convert nested list to nested tuple """
my_tup=tuple()
for elem in expression:
if type(elem)!=list:
my_tup=my_tup+tuple([elem])
else:
my_tup=my_tup+tuple([to_tuple(elem)])
return (my_tup) |
def get_dependencies(key, mapping, recurse=True):
"""
Get the full set of dependencies required by an extension
:param key: extension base name or skin as 'skin/BASENAME'
:param mapping: mapping of repositories to their dependencies
:param recurse: Whether to recursively process dependencies
:r... |
def matSub(mat1, mat2):
"""Return matrix - matrix."""
dim = len(mat1)
return tuple( tuple( mat1[i][j] - mat2[i][j]
for j in range(dim) )
for i in range(dim) ) |
def generate_nodes_binary_status(nodes_status, number_cascades):
"""
Parameters
----------
nodes_status: list
The status for each node (if number_cascades = 3): [(1, 1),(2, 3),...,(n, 0)]
number_cascades: int
The number of competitive c... |
def to_matrix(graph):
"""Function for convert graph to matrix
This function is getting the json-data
and return list of lists like:
[
[0, 1, 1],
[0, 0, 1],
[0, 1, 0],
].
"""
graph_names = [node["name"] for node in graph["nodes"]]
numb_of_nodes = len(graph_names)
... |
def bubble(sortlist):
"""checks for adjacent values and swaps them on the spot"""
for i in range(0,len(sortlist)):
for j in range(0,len(sortlist)-1):
if sortlist[j] > sortlist[j+1]:
sortlist[j],sortlist[j+1] = sortlist[j+1],sortlist[j]
return sortlist |
def findIsolatedNodes (graph):
""" Returns a list of isolated nodes. """
isolated = []
for node in graph:
if not graph[node]:
isolated += node
return isolated |
def full_name(app):
"""Builds App full_name, prepending the App with the name
of the parent App.
:param app: App as returned by queries.get_apps()
:type app: dict
:return: full name of the app
:rtype: string
"""
name = app['name']
if app.get('parentApp'):
parent_app = app['p... |
def _deal_with_update(template: str) -> str:
"""
For the patch of UPDATE statement, avoid redundant commas in update set
:param template: Template
:return: Results after treatment
"""
up_template = template.upper()
index_update = up_template.find("UPDATE")
index_where = up_template.find(... |
def check_blank_row(person_row: list):
""" This function takes a name row and sees if theres enough information
to determine if the row has no information in it.\n
@param personRow the row to be determined whether or not its blank.\n
@return True if the row is blank and can be removed, False otherwise.
... |
def retrieve_task_id(context):
"""Helper to retrieve the `Task` identifier from the message `body`.
This helper supports Protocol Version 1 and 2. The Protocol is well
detailed in the official documentation:
http://docs.celeryproject.org/en/latest/internals/protocol.html
"""
headers = context.ge... |
def flatten_voting_method(method):
"""Flatten a voting method data structure.
The incoming ``method`` data structure is as follows. At the time of
writing, all elections have an identical structure. In practice. the None
values could be different scalars. ::
{
"instructions": {
... |
def drop_non_lower(X):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_non_lower([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui', 'dono', 'lepidum', 'novum', 'libellum', 'arida', ... |
def union_dicts(dicts: list) -> dict:
"""
:param dicts:
:return:
"""
merged = {}
for dic in dicts:
try:
for key in dic.keys():
merged[key] = dic[key]
except Exception:
raise TypeError("Dicts are as input required.")
return merged |
def time_formatter(seconds: float) -> str:
""" humanize time """
minutes, seconds = divmod(int(seconds), 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + "d, ") if days else "") + \
((str(hours) + "h, ") if hours else "") + \
((str(minutes)... |
def concatenate(token_1, token_2):
"""
:param token_1:
:param token_2:
:return:
"""
if not token_2 or len(token_2) == 0:
return token_1
return '%s%s%s' % (token_1, ' ' if len(token_1) > 0 else '', token_2) |
def valFallingSlopes(Frames):
"""Computes values of FALLING slopes.Returns a list of
all values of FALLING slopes in the signal."""
previous, slopes = Frames[0], []
for i in range(len(Frames)):
if Frames[i] < previous:
slopes.append(previous - Frames[i])
previous = Frames[i]
... |
def get_city_from_team(cityteam):
"""Returns a city and teamname from teamname in lower case.
It should return the contents of class wide-matchup from the NHL schedule
For historical reasons:
This function used to return a city from a team name, citydict1 had entries like:
"Washington" : "Washin... |
def colorize(string, color, bold=False, highlight=False):
"""
Colorize a string.
This function was originally written by John Schulman.
"""
color2num = dict(
gray=30,
red=31,
green=32,
yellow=33,
blue=34,
magenta=35,
cyan=36,
white=37,... |
def serialise(entry):
"""Serialise an entry."""
if not entry:
return None
ret = entry._asdict()
ret['type'] = entry.__class__.__name__
if ret['type'] == 'Transaction':
if entry.tags:
ret['narration'] += ' ' + ' '.join(['#' + t for t in entry.tags])
if entry.links:... |
def parse_cookie(cookie):
""" Parse cookie string and return a dictionary
where key is a name of the cookie and value
is cookie value.
"""
return cookie and dict([pair.split('=', 1)
for pair in cookie.split('; ')]) or {} |
def simplify(num, denom):
"""Given a numerator and denominator for a fraction, reduce it to lowest terms"""
while num % 2 == 0 and denom % 2 == 0:
num = num >> 1
denom = denom >> 1
factor = 3
while factor <= num:
while num % factor == 0 and denom % factor == 0:
n... |
def _iterate_over_nested_obj(obj, key):
"""It iterates over the nested dict object.
It iterates over two types of data
* list
* dict
for the rest data type it returns the value
Args:
obj (any type): object to process
key (str, int): key to find in object
"""
if isinsta... |
def dictFromList(data_list):
"""Returns a dict given a list.
- Dict created from a list where list contains alternating key, value
pairs.
- ex: [key1, value1, key2, value2] returns: {key1:value1, key2:value2}
"""
data_dict = {}
for i in range(0,len(data_list)-1,2):
#If t... |
def function_04(parameter_01, parameter_02, parameter_03):
"""
Function description.
Parameters
----------
parameter_01 : type
Description.
parameter_02 : type
Description.
parameter_03 : type
Description.
Returns
-------
return_01
Description.... |
def _get_class_category_href(c_name: str) -> str:
"""Return a href for linking to the specified class category."""
return 'class_category_' + c_name.replace('.', '_').replace(' ', '_') |
def get_potential(q):
"""Return potential energy on scaled oscillator displacement grid q."""
return q ** 2 / 2 |
def dfs(grid, row, col):
"""
:type grid: List[List[str]]
:type row : int
:type col : int
:rtype : int
"""
# Checking for Out of Bounds
if (row < 0 or col < 0 or row > len(grid)-1 or col > len(grid[row])-1 or grid[row][col] == '0'):
return 0
# Assigning the traversed the ... |
def _match_field(line, field):
"""
Return the remaining part of the line in case of matching field,
otherwise it returns None.
"""
if line is None or len(line) < 2:
return None
if line[0] == '*' and line[1] == ':':
# Match (star).
return line[2:]
escaped = False
... |
def ShouldCheckFile(file_name):
"""Returns True if the given file is a type we want to check."""
if len(file_name) < 2:
return False
return file_name.endswith(".cc") or file_name.endswith(".h") |
def binary_search_recursive(array, elem, offset=0):
"""
Binary search algorithm.
Complexity of algorithm is log(n).
:param array: should be sorted list of elements
:param elem: element to find in array
:param offset: default is 0, used for recursive call
:return: index of element in array if... |
def hello(name="World"):
"""
python3 all.py hello
> Hello World
python3 all.py hello --name Yazid
> Hello Yazid
"""
return "Hello %s" % name |
def script_run_DB2Falcon(config, preads4falcon_fn, preads_db):
"""Run in pread_dir.
"""
params = dict(config)
params.update(locals())
script = """\
# Given preads.db,
# write preads4falcon.fasta (implicitly) in CWD.
time DB2Falcon -U {preads_db}
[ -f preads4falcon.fasta ] || exit 1
""".format(**para... |
def _from_file(filename):
"""Open a file and read its first line.
:param filename: the name of the file to be read
:returns: string -- the first line of filename, stripped of the final '\n'
:raises: IOError
"""
with open(filename) as f:
value = f.readline().rstrip('\n')
return valu... |
def quicksort(arr, pivi=0):
"""Return a sorted 2D numerical array smallest -> largest."""
if len(arr) < 2:
return arr
else:
piv = arr[pivi]
lower = [v for v in arr[1:] if v <= piv]
higher = [v for v in arr[1:] if v > piv]
return quicksort(lower) + [piv] + quicksort(h... |
def agent_alive_id_list(agent_list, agent_type):
"""Return a list of agents that are alive from an API list of agents
:param agent_list: API response for list_agents()
"""
return [agent['id'] for agent in agent_list
if agent['agent_type'] == agent_type and agent['alive'] is True] |
def merge(A, p, q, r):
"""Assumes A to be an array of numbers, p, q, and r are indices of the array A such that that
p <= q < r. The process also assumes that the subarrays A[p, q] and A[q+1, r] are sorted."""
n1 = q-p+1
n2 = r-q
L, R = [], []
for i in range(n1):
L.append(A[p+i... |
def ignore_urls(searchurls, ignoreurls):
"""Removes URLs that are common to both lists,
given a list of URLs and another list of URLs to ignore.
Args:
searchurls (list): initial list of URLs to remove from.
ignoreurls (list): a list of URLs to remove from searchurls.
Returns:
... |
def whitespace_tokenize(text):
"""
Desc:
runs basic whitespace cleaning and splitting on a piece of text
"""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens |
def merge_result(docker_list: dict, result_dict: dict = {}, max_entries_per_docker: int = 5) -> dict:
"""Returns a python dict of the merge result
:type docker_list: ``dict``
:param docker_list: dictionary representation for the docker image used by integration or script
:type result_dict: ``dict``
... |
def __to_camel(method_name: str) -> str:
"""
Function converts to camel
case specific method name.
First version of naming:
<get|set>_your_action -> getYourAction
Second version of naming:
_<get|set> -> get
:param method_name: As is
:return: str
"""
tmp... |
def getOrElseUpdate(dictionary, key, opr):
"""If given key is already in the dictionary, returns associated value.
Otherwise compute the value with opr, update the dictionary and return it.
None dictionary are ignored.
>>> d = dict()
>>> getOrElseUpdate(d, 1, lambda _: _ + 1)
2
>>> print(d)
{... |
def penn_to_wordnet(tag):
"""
Convert a Penn Treebank PoS tag to WordNet PoS tag.
"""
if tag in ['NN', 'NNS', 'NNP', 'NNPS']:
return 'n' #wordnet.NOUN
elif tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
return 'v' #wordnet.VERB
elif tag in ['RB', 'RBR', 'RBS']:
return ... |
def get_fixed_length_string(string: str, length=20) -> str:
"""
Add spacing to the end of the string so it's a fixed length.
"""
if len(string) > length:
return f"{string[: length - 3]}..."
spacing = "".join(" " for _ in range(length - len(string)))
return f"{string}{spacing}" |
def binary_search(a_list, item):
"""
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> print(binary_search(test_list, 3))
False
>>> print(binary_search(test_list, 13))
True
"""
if len(a_list) == 0:
return False
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
... |
def ver_tuple_to_str(req_ver):
"""Converts a requirement version tuple into a version string."""
return ".".join(str(x) for x in req_ver) |
def get_repository_name(url):
""" This function returns the name of the repository for splitting the
url of the repository.
:Arguments:
1. url (str) = url of the repository as stated by the user in
the xml file
:Returns:
string = name of the repository
"""
li_temp_1 = url.rsplit('/',... |
def decimal_to_hex(number):
"""
This function calculates the hex of the given decimal number
:param number: decimal number in string or integer format
:return : string of the equivalent hex number
Algo:
1. Divide the decimal number by 16. Treat the division as an integer div... |
def scheduler(epoch):
"""
Learning rate scheduler
"""
lr = 0.0001
if epoch > 25:
lr = 0.00001
elif epoch > 60:
lr = 0.000001
print('Using learning rate', lr)
return lr |
def transform_pesq_range(pesq_score):
"""transform PESQ metric range from [-0.5 ~ 4.5] to [0 ~ 1]
Args:
pesq_score (float): pesq score
Returns:
pesq_score: transformed pesq score
"""
return (pesq_score + 0.5) / 5 |
def isglob(path):
"""
Checks if *path* is a glob pattern. Returns #True if it is, #False if not.
"""
return '*' in path or '?' in path |
def split_decimal(flt):
"""
split decimal
params:
flt : <float> float to convert
returns: <tuple> ( whole number, decimal part)
"""
whole, dec = str(flt).split('.')
# dec = int(dec)
# if dec >= 5:
# return int(whole) + 1, dec
return [int(whole), int(dec)] |
def hk_sp_errors(bits: list) -> bytes:
"""
First bit should be on the left, bitfield is read from left to right
"""
error_bits = 0
bits.reverse()
for i in range(len(bits)):
error_bits |= bits[i] << i
return error_bits.to_bytes(2, byteorder='big') |
def _mapfuns(d1, d2):
"""
Given two dicts, d1 (k1 -> v1) and d2 (k2 -> v2), returns a dict which has
the mapping (k1 -> k2) such that _name(k1) == _name(k2).
"""
def _name(fn):
"""
Strips the line number at the end if any.
Eg. 'foo.py:23' -> 'foo.py', 'foo:bar.py' -> 'foo:bar... |
def good_fft_number(goal):
"""pick a number >= goal that has only factors of 2,3,5. FFT will be much
faster if I use such a number"""
assert goal < 1e5
choices = [2**a * 3**b * 5**c for a in range(17) for b in range(11)
for c in range(8)]
return min(x for x in choic... |
def evaluate_status2led(elm):
"""
adapter between color rendered by `led.css` and
statuses returned by `guestoo`
color-space: ['red', 'orange', 'yellow', 'green', 'blue']
status-space: ['INVITED', 'OPEN', 'DECLINED', 'CONFIRMED', 'APPEARED']
"""
guest_status = elm['events'][0]['status']
... |
def get_leader(tokens, token_index, size):
"""
Create a tuple out of the tokens that precede the token at the given index.
If the leader would extend beyond the begging of tokens None will be used.
:param tokens: the tokens to create the leader from
:param token_indiex: the index of the token ot g... |
def extract_vars(l):
"""
Extracts variables from lines, looking for lines
containing an equals, and splitting into key=value.
"""
data = {}
for s in l.splitlines():
if '=' in s:
name, value = s.split('=')
data[name] = value
return data |
def ifan03to02(state) -> dict:
"""Convert incoming from iFan03."""
return {'switches': [
{'outlet': 0, 'switch': state['light']},
{'outlet': 1, 'switch': state['fan']},
{'outlet': 2, 'switch': 'on' if state['speed'] == 2 else 'off'},
{'outlet': 3, 'switch': 'on' if state['speed']... |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB', 'XB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def replace_multiple(text, dic):
"""replace multiple text fragments in a string"""
for i, j in dic.items():
text = text.replace(i, j)
return text |
def generate_scenarios(key, test_cases):
"""
This function generates the test case scenarios according to key given
to it, e.g. key=ADD, key=update etc.
:param key: for which operation generate the test scenario
:type key: str
:param test_cases
:type test_cases: list
:return: scenarios
... |
def _parameters_link(args, parameters):
"""Build arguments based on the arguments and parameters provided."""
args_ = {}
for index, arg in enumerate(args):
args_.setdefault(arg, []).append(index)
args_ = {key: iter(value) for key, value in args_.items()}
return [next(args_.get(p, iter([p])))... |
def filterString(text):
"""
Replace/Remove invalid file characters
text : The text to search in
Returns:
A filtered version of the given string
"""
# Remove invalid chars
text = text.strip()
text = text.replace(':', ';')
text = text.replace('?', '')
text = text.replace('"'... |
def add_suffix(signals, suffix):
"""Add `suffix` to every element of `signals`."""
return [s + suffix for s in signals] |
def temp_depression(ua_per_ft2,
balance_point,
outdoor_temp,
doors_open):
"""Function returns the number of degrees F cooler that the bedrooms are
relative to the main space, assuming no heating system heat is directly
provided to bedrooms. Bedr... |
def _B_at_h(h1, h2):
"""Evaluates B auxiliary variable at given h coefficients.
Parameters
----------
h1: float
The first of the h coefficients.
h2: float
The second of the h coefficients.
Returns
-------
B: float
Auxiliary variable.
Notes
-----
Thi... |
def parse_repository_tag(repo_path):
"""Splits image identification into base image path, tag/digest
and it's separator.
Example:
>>> parse_repository_tag('user/repo@sha256:digest')
('user/repo', 'sha256:digest', '@')
>>> parse_repository_tag('user/repo:v1')
('user/repo', 'v1', ':')
""... |
def align(n, a):
"""Align @n to @a bytes.
Examples:
align(4, 4) = 4
align(3, 4) = 4
align(0, 4) = 0
align(5, 4) = 8
Args:
n (numbers.Integral): Virtual address to align
a (numbers.Integral): Alignment
Returns:
New, aligned address, or @n if alre... |
def circle_area(radius: float) -> float:
"""
>>> circle_area(10)
314.1592653589793
>>> circle_area(0)
0.0
"""
import math
return math.pi * radius * radius |
def is_number(s):
""" checks if passed in variable is a float """
try:
float(s)
return True
except:
pass
return False |
def remove_intro(l):
""" Remove the marker that indicates this is a change to introductory
text. """
return l.replace('[text]', '') |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL. (' + str(e) + ')', 404 |
def _is_caching_needed(m):
"""Check if image should be cached or not
:param m: the meta-data dictionary of an image
:return: False if it's not ok to cache or already cached
True if is good to cache or previous caching failed
"""
# Check main status and format
if m['status'] != 'act... |
def GetAccelIndex(label):
"""
Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic
(e.g. 'lab&el' ==> will result in 3 and labelOnly = label).
:param `label`: a string containining an ampersand.
"""
indexAccel = 0
while True:
indexAccel =... |
def format_filesize(value):
""" Return a human readable filesize for a given byte count """
if not value:
return ""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB']:
if value < 1024.0:
return "%3.1f %s" % (value, x)
value /= 1024.0
return value |
def _compare_across(collections, key):
"""Return whether all the collections return equal values when called with
`key`."""
if len(collections) < 2:
return True
c0 = key(collections[0])
return all(c0 == key(c) for c in collections[1:]) |
def isValid(s):
"""
:type s: str
:rtype: bool
"""
## given a string of just parentheses
## go through the string
## keep track if something is the correct closing parentheses
## O(N) where n is length of the string
## {[]}
stack = []
par_mapping = {"}" : "{", "]" : "[", ")" :... |
def isalpha(obj):
"""
Test if the argument is a string representing a number.
:param obj: Object
:type obj: any
:rtype: boolean
For example:
>>> import pmisc
>>> pmisc.isalpha('1.5')
True
>>> pmisc.isalpha('1E-20')
True
>>> pmisc.isalpha('1EA-... |
def pid_controller(proportional_value, integral_value, derivative_value):
"""Docstring here (what does the function do)"""
return derivative_value + (proportional_value + integral_value) |
def decode(line):
"""Make treatment of stdout Python 2/3 compatible"""
if isinstance(line, bytes):
return line.decode('utf-8')
return line |
def add_layer(a_binary, C, ori_tile, gg_tile):
"""
add layer for building complexity fractiles
"""
for i in range(C-1):
extend_tile = ()
for tt in a_binary:
if tt == 0: # G(gold exist)
extend_tile += gg_tile
elif tt == 1: # L(gold not exist)
... |
def latex_name(model_name):
"""
Replaces model names with latex-friendly names.
E.g. "avg_br" becomes "$E_{avg}|D_{br}$".
Args:
model_name (str): original name of the model
Returns:
latex_name (str): latex-friendly translation of the model name
"""
if model_name == "enc_de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.