content stringlengths 42 6.51k |
|---|
def startWebPage(myTitle):
"""
Returns a string with the head element for a web page
with title myTitle.
Example: webPageHeader("Temperatures") returns the
header for a web page with temperatures on it, i.e.
<head>
<title>Temperatures</title>
</head>
"""
return ("<html>\n... |
def constr_leaf_value(xml_str, leafName, leafValue):
"""construct the leaf update string"""
if leafValue is not None:
xml_str += "<" + leafName + ">"
xml_str += "%s" % leafValue
xml_str += "</" + leafName + ">\r\n"
return xml_str |
def sortedDictLists(d, byvalue=True, onlykeys=None, reverse=False):
"""Return (key list, value list) pair from a dictionary,
sorted by value (default) or key.
Adapted from an original function by Duncan Booth.
"""
if onlykeys is None:
onlykeys = list(d.keys())
if byvalue:
... |
def video(data_type, stream_id, data, control, timestamp):
"""
Construct a video message to send video data to the server.
:param data_type: int the RTMP datatype.
:param stream_id: int the stream which the message will be sent on (same as the publish StreamID).
:param data: bytes the raw video data... |
def convert_args_to_str(args, max_len=None):
""" Convert args to a string, allowing for some arguments to raise
exceptions during conversion and ignoring them.
"""
length = 0
strs = ["" for i in range(len(args))]
for i, arg in enumerate(args):
try:
sarg = repr(arg)
ex... |
def escape(s, quote=True):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
s = s.replace("&", "&") # Mus... |
def get_db_engine(snapshot_response):
"""Function to parse snapshot response from AWS for DB engine.
Args:
snapshot_response (str): The snapshot identifier to parse.
Returns:
:obj:`str`: The DB engine of the snapshot.
"""
db_source_snapshot = snapshot_response['DBSnapshots'][0]['DBSn... |
def turn(p, q, r):
"""Returns -1, 0, 1 if p,q,r forms a right, straight, or left turn."""
t = (q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1])
# Update to make jarvis run with Python 3.3:
if t < 0: return -1
if t == 0: return 0
if t > 0: return 1 |
def stripExtension(path):
"""Return the part of the path before the extension.
@param path: The path to split.
@type path: string
@return: The part of the path before the extension.
@rtype: string
"""
end = path.rfind("\\")
end = max(path.rfind("/", end + 1), end) + 1
# We search in the substrin... |
def rle_decode(data):
"""Decodes PackBits encoded data."""
i = 0
output = bytearray()
while i < len(data):
val = data[i]
i += 1
if val == 0x80:
continue
if val > 0x80:
repeats = 0x101 - val
output += data[i:i + 1] * repeats
... |
def Col_to_row(m):
"""Column-To-Row Transposition : moves the nibble in the position ( i , j ) to the
position ( j , i )"""
n = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(4):
for j in range(4):
try:
n[j][i] = m[i][j]
except IndexEr... |
def check_for_ticket_quantity_error(quantity):
"""
Returns any error message if the ticket's quantity is not between 1 and 100 else if
there is no errors it returns false.
:param quantity: the ticket's quantity as a string
:return: false if no error, else returns the error as a string message
"... |
def digits(n,B=10):
"""
Number of digits of n in base B
"""
n = abs(n)
ctr = 0
while n != 0:
n //= B
ctr += 1
return ctr |
def get_rank(target, ranks):
"""
Get rank of a target entity within all ranked entities.
Args:
target (str): Target entity which rank should be determined.
ranks (list): List of tuples of an entity and its rank.
Returns:
int: Rank of entity or -1 if entity is not present in ranks.
"""
for i in range(len(r... |
def check_password_vs_blacklist(current_string, blacklist):
"""Checks a string to determine whether it is contained within a blacklist
Arguments:
current_string {string} -- the string to be checked against blacklist
blacklist {list} -- list of words defined within a given
... |
def month_name_to_number_string(string):
"""
:param string:
:return:
"""
m = {
'jan': '01',
'feb': '02',
'mar': '03',
'apr': '04',
'may': '05',
'jun': '06',
'jul': '07',
'aug': '08',
'sep': '09',
'oct': '10',
'... |
def api_command_wrapper(api_command_result):
"""Prints the result of the command and raises RuntimeError to interrupt command sequence if there is an error.
Args:
api_command_result: result of the api command
"""
print(api_command_result)
if not api_command_result["status"] == "SUCCESS":
... |
def example_combi(pos, a=None, b=1, c='test'):
"""
I'm a harder case:
a slice is indicated by :
Args:
pos:
a: value
b: test
returns:
a list separated by colon (:)
"""
return pos, a, b, c |
def dead_zone(controller_input, dead_zone):
"""This is the dead zone code, essential for any 4009 'bot."""
if controller_input <= dead_zone and controller_input >= -dead_zone:
return 0
elif controller_input > 0:
return ((controller_input-dead_zone)/(1-dead_zone))
else:
return ((-... |
def decode_bytes(data: bytes) -> str:
"""
Decodes provided bytes using `utf-8` decoding, ignoring potential decoding errors.
"""
return data.decode('utf-8', 'ignore') |
def slice_as_int(s: slice, l: int):
"""Converts slices of length 1 to the integer index they'll access."""
out = list(range(*s.indices(l)))
assert len(out) == 1
return out[0] |
def isGitUrl(Url):
""" this function returns true, if the Url given as parameter is a git url:
it either starts with git:// or the first part before the first '|' ends with .git
or if the url starts with the token [git] """
if Url.startswith('git://'):
return True
# split away branch... |
def formatDirPath(path):
"""Appends trailing separator to non-empty path if it is missing.
Args:
path: path string, which may be with or without a trailing separator,
or even empty or None
Returns:
path unchanged if path evaluates to False or already ends with a trailing
separator; otherwise,... |
def prepend_protocol(url: str) -> str:
"""Prefix a URL with a protocol schema if not present
Args:
url (str)
Returns:
str
"""
if '://' not in url:
url = 'https://' + url
return url |
def ring_idxs(gra_rings):
""" Get idxs for rings
"""
_ring_idxs = tuple()
for ring in gra_rings:
idxs = tuple(ring[0].keys())
if idxs:
_ring_idxs += (idxs,)
return _ring_idxs |
def bin2dec(string_num):
"""Turn binary into decimal."""
return str(int(string_num, 2)) |
def parse_game_type(data: dict) -> str:
"""Parse and format a game's type."""
is_rated = data.get('rated')
speed = data.get('speed')
variant = data.get('variant')
game_type = 'unknown'
if speed:
game_type = '%s (%s)' % (speed, variant or 'standard')
if is_rated:
game_type ... |
def validate_move(move):
"""
Takes user input and validates it, returning the result if valid.
"""
try:
move = int(move)
assert move in [1, 2, 3, 4, 5, 6]
except (ValueError, AssertionError):
raise ValueError("Choose a value in [1-6]. Please try again.")
return move |
def horizontal_index(ncols, row, col):
""" Compute the array index using horizontal-display logic """
# lambda ncols, row, col: ncols * (row - 1) + col
return ncols * (row - 1) + col |
def remove_whitespace(html):
"""Removes whitespace from an HTML buffer"""
return ''.join([line.strip() for line in html.split('\n')]) |
def even(arg: int) -> bool:
"""
Tells if the given arg number is even.
"""
return arg % 2 == 0 |
def convert_custom_objects(obj, custom_objects={}):
"""Handles custom object lookup.
# Arguments
obj: object, dict, or list.
# Returns
The same structure, where occurences
of a custom object name have been replaced
with the custom object.... |
def check_valid_password_2(minimum, maximum, letter, password):
"""PART TWO
Checks if a password is valid based on the criteria.
The min/max in this example are actually the indexes
(no index 0 here) of where the letter should occur.
Only one occurence of the letter is acceptable (an "a")
at bo... |
def make_sub_rst(id_, x):
"""Turn (id, original) into valid RST which can be inserted in a document for parsing."""
return ":sub:`(%s)%s`"%(id_, x.replace("`", r"\`").strip()) |
def valid_parentheses(string):
"""."""
stack = []
for i in string:
if i == '(':
stack.append(0)
elif i == ')':
if stack == []:
return False
else:
stack.pop()
return stack == [] |
def replace_with_ids(tokens, vocab):
"""Takes in a list of tokens and returns a list of word ids. <unk> must be included in vocabulary!
Args:
tokens: List of tokens.
vocab: A dictionary from word -> word_id. MUST INCLUDE THE TERM <unk>.
Returns:
List of word ids.
"""
return ... |
def compute_start_points(shapes, margin):
"""
tiling features in horizontal direction with a given margin
shapes: list, in NCHW format
margin: int, margin to tiling features of different levels
"""
N, C, H0, W0 = shapes[0]
x0 = 0
start_points = []
ranges = []
for shape in shapes:... |
def generate_matrix(dim):
"""Generate the matrix with enumarated elements.
Args:
dim: Dimension of the matrix.
Returns:
Generated matrix as a nested list.
"""
matr = []
for i in range(dim):
# Start by 1 and increase the number for each new element by one.
matr.a... |
def sequence_del(my_str):
"""
:param my_str:
:return: List made of the received string of all the products the user entered
"""
List = list(my_str.split(','))
print(List)
return List |
def _data_not_in_spec(spec):
""" check to see if the data element is defined for this spec """
if isinstance(spec, dict):
return 'data' not in spec
return True |
def get_localizable_attributes(obj):
"""Returns a dictionary with localizable attributes of `obj`."""
# FIXME: use some kind of class attribute to get list of localizable attributes
locale = {}
try:
if obj.label:
locale["label"] = obj.label
except:
pass
try:
... |
def lasso_and_ridge_from_enet(pen_val, l1_ratio):
"""
Returns the lasso and L2 penalties from the elastic net parameterization
Parameters
----------
pen_val: float
l1_ratio: float, None
Output
------
lasso_pen, ridge_pen
"""
if l1_ratio is None or l1_ratio == 0:
l... |
def calc_stats(total_unique_molecular_bases, total_bases, output_bases, genome_size, coverage):
"""
>>> calc_stats(0, 0, 0, 0, 0) == \
{'genome_size': 0, 'coverage': 0, 'total_bases': 0, 'total_unique_molecular_bases': 0, \
'output_bases': 0, 'unique_molecular_avg_cov': 0.0, 'output_avg_cov': 0.0, 'tota... |
def translate_tuple_to_basemask(tup, demux_tool):
"""Return illumina or picard-style base mask string"""
picard_to_illumina = {"T": "y", "S": "n", "B": "I"}
if demux_tool == "bcl2fastq":
return picard_to_illumina[tup[0]] + str(tup[1])
else:
return str(tup[1]) + tup[0] |
def is_var_desc(p, pltype):
"""
The variable description will either follow a Var Name or be a
continuation of a Var Desc line
Note: This test is dependent on other identifications before it.
"""
import re
if pltype in ['Var Name', 'Var Desc']:
pparser = re.compile(r"[\t ]+\.")
... |
def has_method(o, name):
""" Verifies whether an object has a specific method """
return callable(getattr(o, name, None)) |
def show_best_slave(slaves, args_array):
"""Method: show_best_slave
Description: Stub holder for mysql_rep_failover.show_best_slave function.
Arguments:
(input) slaves
(input) args_array
"""
status = False
if slaves and args_array:
status = False
return statu... |
def jacobi(a, b):
"""Calculates the value of the Jacobi symbol (a/b)
where both a and b are positive integers, and b is odd
"""
if a == 0: return 0
result = 1
while a > 1:
if a & 1:
if ((a-1)*(b-1) >> 2) & 1:
result = -result
a, b = b % a, a
... |
def text_type(s):
"""
Given an unnamed piece of data, try to guess its content type.
Detects HTML, XML, and plain text.
:return: A MIME type string such as 'text/html'.
:rtype: str
:param bytes s: The binary data to examine.
"""
# at least the maximum length of any tags we look for
... |
def get_ring(gossip):
""" Return the ring status in a structured way.
Args:
gossip: A list of gossip info for each node.
Returns:
A list of nodes represented by dictionaries.
"""
nodes = sorted(gossip, key=lambda node: node['token'])
for index, node in enumerate(nodes):
node['index'] = index
... |
def create_annotationlist_id(manifest_info, canvas_id, annolist_idx, opts):
"""
Return (uri, filename) for annotation list
"""
prefix = opts['url_prefix']
if not prefix:
# use manifest id as prefix
prefix = manifest_info['id']
scheme = opts['annolist_name_scheme']
if scheme ... |
def is_prime(n):
"""Returns True if n is a prime number.
:param n: The nummer to test
"""
if n == 2 or n == 3: return True
if n < 2 or n % 2 == 0: return False
if n < 9: return True
if n % 3 == 0: return False
r = int(n ** 0.5)
f = 5
while f <= r:
if n % f == 0: return F... |
def reverse_bisect_left(a, x, lo=0, hi=None):
"""\
Similar to ``bisect.bisect_left``, but expects the data in the array ``a``
to be provided in descending order, rather than the ascending order assumed
by ``bisect_left``.
The returned index ``i`` partitions the array ``a`` into two halves so that:
... |
def End_Path(path):
"""
Split the path at every '/' and return the final file/folder name.
If your path uses backslashes rather than forward slashes it will use
that as the separator.
CODE: End_Path(path)
AVAILABLE PARAMS:
path - This is the path where you want to grab the end item name.
EXAMPLE CODE:
ad... |
def mw_sigma_leonard(rake):
"""
sigma values are determined from the Leonard 2014 paper, based on Table 3 - S(a) passing it through the equation
rake: to determine if DS or SS
returns sigma value for mean Mw
"""
if round(rake % 360 / 90.0) % 2:
sigma = 0.3
else:
sigma = 0.26... |
def get_aws_connection_data(assumed_account_id, assumed_role_name, assumed_region_name=""):
"""
Build a key-value dictionnatiory args for aws cross connections
"""
if assumed_account_id and assumed_role_name:
aws_connection_data = dict(
[("assumed_account_id", assumed_account_id), (... |
def _shortnameByCaps(name):
"""
uses hungarian notation (aka camelCaps) to generate a shortname, with a maximum of 3 letters
ex.
myProc --> mp
fooBar --> fb
superCrazyLongProc --> scl
"""
shortname = name[0]
count = 1
for each in name[1:]:
if... |
def create_file_name(scale=1, invert=False, flip=False):
"""Helper function to dynamically create a file name
Keyword arguments:
scale -- scale of the printed icon
invert -- boolean to invert the binary symbols
flip -- boolean to flip icon 180 degrees
"""
return ('icon_scaled_x'
... |
def unbox(boxed_pixels):
""" assumes the pixels came from box
and unboxes them!
"""
flat_pixels = []
for boxed_row in boxed_pixels:
flat_row = []
for pixel in boxed_row:
flat_row.extend(pixel)
flat_pixels.append(flat_row)
return flat_pixels |
def phaseY(father, child):
"""Phase Y chromosome genotype of a male child given the genotype of the
father. This function only checks that the genotype of the child
could have been inherited from the father.
Arguments:
mother (string): genotype of father expressed in the form 0/1, 0/0 etc
... |
def unquote(s):
"""unquote('abc%20def') -> 'abc def'."""
mychr = chr
myatoi = int
list = s.split('%')
res = [list[0]]
myappend = res.append
del list[0]
for item in list:
if item[1:2]:
try:
myappend(mychr(myatoi(item[:2], 16))
... |
def check_has_backup_this_year(year, existing_backups):
"""
Check if any backup in existing_backups matches year.
"""
for backup in existing_backups:
if backup.createdYear == year:
return True
return False |
def has_doc(obj):
"""
Return whether an object has a docstring
:param obj: Object to check for docstring on
:return: Whether the object has a docstring
"""
return hasattr(obj, "__doc__") and isinstance(obj.__doc__, str) |
def _check_noise_dict(noise_dict, component):
"""Ensure noise compatibility for the noises of the components
provided when building a state space model.
Returns
-------
noise_dict : dict
Checked input.
"""
sub_component = component.split('_')
if isinstance(noise_dict, dict):
... |
def get_set_from_annotation(annotation_list, key):
"""
Takes list of annotation dicts and a key.
Returns a set of all values of that key
"""
return set([x[key] for x in annotation_list]) |
def tof_cm(time_of_flight):
"""
EZ1 ultrasonic sensor is measuring "time of flight"
Converts time of flight into distance in centimeters
"""
convert_to_cm = 58
cm = time_of_flight / convert_to_cm
return cm |
def constrain(x, min_=0, max_=255):
""" constrain a number between two values """
return min(max_, max(min_, x)); |
def counter(alist, func=None):
"""
- counts the number of things in a list
- can apply a function (func) to item
"""
adict = {}
for item in alist:
if func is not None:
item = func(item)
if item is not None:
adict[item] = adict.get(item, 0) + 1
return a... |
def getCharacterFromGame(gtitle: str) -> str:
"""Return a query to get characters with lower Ryu Number to a game.
The query will retrieve the name and Ryu Number of a character whose Ryu
Number is exactly one less than the Ryu Number of the game whose title
is passed. This is used primarily ... |
def new_dict_trie(lines):
"""
`new_dict_trie` returns a new trie, encoded as a dictionary, containing
`lines`.
"""
trie = {}
for line in lines:
node = trie
for char in line:
if char not in node:
node[char] = {}
node = node[char]
nod... |
def filter_bolts(table, header):
""" filter to keep bolts """
bolts_info = []
for row in table:
if row[0] == 'bolt':
bolts_info.append(row)
return bolts_info, header |
def decode_dec_ttl(value):
"""Decodes dec_ttl and dec_ttl(id, id[2], ...) actions"""
if not value:
return True
return [int(idx) for idx in value.split(",")] |
def get_fieldnames(records):
"""
Extract fieldnames for CSV headers from list of results
:param records: list
:return: list
"""
fieldnames = []
ordered_fieldname = (
"time_last",
"time_first",
"source",
"count",
"bailiwick",
"rrname",
... |
def _linear_decay(value, origin, offset, scale, decay):
"""
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html
"""
s = scale / (1 - decay)
return max(0, (s - max(0, abs(value - origin) - offset)) / s) |
def get_text(boxes):
"""
Merge text from boxes (Textblock)
Parameters::
(TextBlock[]): boxes -- OCR boundingbox grouping to retreive test from
Returns:
TextS (String): concat textblock text
"""
text = ""
for b in boxes:
text = text + " " + b.text
r... |
def filter_disabled(s):
"""
Filter out all disabled items.
:param s:
:return:
"""
return list(filter(lambda x: "is_disabled" not in x or not x["is_disabled"], s)) |
def get_int(value, allow_sign=False) -> int:
"""Convert a value to an integer.
Args:
value: String value to convert.
allow_sign: If True, negative values are allowed.
Return:
int(value) if possible.
"""
try:
# rstrip needed when 0. is passed via [count]
int_v... |
def stars_amount_counter(board: list) -> int:
"""Counts amount of stars in the given board.
>>> stars_amount_counter(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
"7 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 9****"])
36
"""
stars = 0
for i in range(9):
for j in... |
def price_data(sp_available=False, sp_traded=False, ex_best_offers=False, ex_all_offers=False, ex_traded=False):
"""
Create PriceData filter list from all args passed as True.
:param bool sp_available: Amount available for the BSP auction.
:param bool sp_traded: Amount traded in the BSP auction.
:pa... |
def generate_tokens_map_by_flatten_pqa_data(flatten_data_list):
"""
flatten_data_list: List[(paragraph, question, answer)]
"""
token_map = {}
for (paragraph_text, question_text, answer_text) in flatten_data_list:
paragraph_tokens = paragraph_text.split(" ")
question_tokens = question... |
def eh_celula(cell):
"""
eh_celula: universal >>> logico
- Determina se o valor dado e do tipo celula ou nao
"""
if not isinstance(cell, dict):
return False
elif "valor" not in cell or len(cell.keys()) != 1:
return False
return cell["valor"] in (-1, 0, 1) |
def drop_fst_arg(args_dict):
"""
Convinient function to drop the first argument, for example when applying
a contract to class methods and you don't need the ``self`` argument.
"""
if "arg__0" in args_dict:
del args_dict["arg__0"]
return args_dict |
def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool:
"""Returns True if bothe token sequences contain the same tokens,
no matter in what order::
>>> eq_tokens('red thin stroked', 'stroked red thin')
True
>>> eq_tokens('red thin', 'thin blue')
False
"""
retu... |
def compare_samples(s1, s2):
"""
s1, s2 - samples with the following fields:
'node_tree', 'name'
"""
if s1 is None or s2 is None:
return False
else:
def remove_field(node, field):
if field in node:
node.pop(field)
return node
# ... |
def dummy_list_of_objects(dummy_dict):
"""Return a list of objects"""
return [
{
1: {1.1: "1.1.1", 1.2: ["1.2.1", "1.2.2"]},
},
[4, 5],
{2: {2.1: "2.1.1", 2.2: {}}, 3: {}},
] |
def add_something(num1, num2):
"""This function adds two numbers and returns the result
>>> add_something(2,3)
5
>>> add_something(-4, 4)
0
>>> add_something(-3, -5)
-8
"""
return(num1 + num2) |
def is_pythonfile(file):
"""Returns True if file extension is py and if not then false."""
if file.endswith('py'):
return True
else:
return False |
def _binary_search(array, elt):
"""Modified binary search on an array."""
start = 0
end = len(array) - 1
while start <= end:
mid = (start + end) // 2
if elt == array[mid]:
return mid + 1
if elt < array[mid]:
end = mid - 1
else:
start =... |
def experience_converting(current_exp: int):
"""Return tuple(level, gained_after_lvl_up, left_before_lvl_up)"""
a1 = 100
q = 1.1
current_lvl = 0
Sn = 100
prevSn = 0
while Sn <= current_exp:
prevSn = Sn
Sn = int(a1 * (q**(current_lvl + 2) - 1) / (q - 1))
current_lvl +=... |
def SortCrescent(li, index):
"""
Argument:
- li a list of lists.
- index an integer
Return:
- A sorted list of lists in a crescent order by the elements located at the index position of each list contained in li.
"""
#ex :[
""""""
return(sorted(li, key = lambda x: x[ind... |
def __has_value(cell):
"""Checks if a cell value from a Pandas dataframe is a valid string
The following are treated as invalid:
* empty cell (None)
* empty string ('')
* zero (0)
* type = nan OR type = None
* 'null' OR 'NULL'
* 'none' OR 'NONE'
Args:
cell (Any): Value of a... |
def get_fp_color(n, col_set=1):
"""
Get the color of a fixed point given
the number of unstable modes
Arguments:
n (int): number of unstable modes
col_set (int): which colors set to use
Returns:
color (str)
"""
if n == 0:
color = "seagreen" if col_set == 1 e... |
def map_platforms(platforms):
""" Takes in a list of platforms and translates Grinder platorms to corresponding GitHub-hosted runners.
This function both modifies and returns the 'platforms' argument.
"""
platform_map = {
'x86-64_windows': 'windows-latest',
'x86-64_mac': 'mac-la... |
def default(value: object):
"""Formatter functions handle Knack values by returning a formatted
(aka, humanized) value.
The `default()` formatter handles any field type for which another formatter
function has not been defined. If the input value is a list, it returns a comma
separated string of li... |
def replace_stuff(url):
""" Remove common domain suffixes and prefixes """
stuff = ['www.', 'm.', 'blog.', 'help.', 'blogs.',
'gist.', 'en.', '.co', 'www2.', '.wordpress']
for item in stuff:
url = url.replace(item, '')
return url |
def atoi(text):
"""
Based on a stackoverflow post:
https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
"""
return int(text) if text.isdigit() else text |
def part_1(commands):
"""
Calculate the horizontal position and depth you would have after following the planned course.
What do you get if you multiply your final horizontal position by your final depth?
:param commands: the list of commands
:return: product of final horizontal position and depth
... |
def _get_value(entry_quals, key, cb=lambda x: x):
"""Get the value from the entry and apply the callback
"""
return list(map(lambda v: cb(v), entry_quals.get(key, []))) |
def maxValue(inputArray):
"""
maxValue
Function used to calculate the maximum value of an array
@param inputArray Array passed for calculation
@return maxValueReturn The integer value returned by the calculation
"""
maxValueReturn = max(inputArray)
return maxValueReturn |
def to_binary(val, expected_length=8):
"""Converts decimal value to binary
:param val: decimal
:param expected_length: length of data
:return: binary value
"""
val = bin(val)[2:] # to binary
while len(val) < expected_length:
val = "0" + val
return val |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.