content stringlengths 42 6.51k |
|---|
def binarySearch(lower, upper, alist):
"""
take in a lower bound, upper bound, and a list as input.
then you have the range of numbers to search for.
binary search after but the search element is a range of numbers.
"""
bounds = range(lower, upper + 1)
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if alist[midpoint] in bounds:
found = True
else:
if bounds[0] > alist[midpoint]:
first = midpoint + 1
else:
last = midpoint - 1
return found |
def assign_scores(game):
"""Cleanup games without linescores to include team score
based on team totals."""
for team in game['team'].values():
if 'score' not in team and 'totals' in team:
team['score'] = team['totals']['source__B_R']
return game |
def songs_or_artists(search_type):
"""[summary]
Ask user to input whether search is based on songs or artists.
[description]
"""
while search_type != "a" and search_type != "s":
search_type = input("Do you want to search for playlists containing artists or specific songs? (a or s) \n").lower()
return search_type |
def dist(t1,t2):
""" Euclidean distance between two lists """
return sum([(t1[i]-t2[i])**2 for i in range(len(t1))]) |
def get_key(key, config, msg=None, delete=False):
"""Returns a value given a dictionary key, throwing if not available."""
if isinstance(key, list):
if len(key) <= 1:
if msg is not None:
raise AssertionError(msg)
else:
raise AssertionError("must provide at least two valid keys to test")
for k in key:
if k in config:
val = config[k]
if delete:
del config[k]
return val
if msg is not None:
raise AssertionError(msg)
else:
raise AssertionError("config dictionary missing a field named as one of '%s'" % str(key))
else:
if key not in config:
if msg is not None:
raise AssertionError(msg)
else:
raise AssertionError("config dictionary missing '%s' field" % key)
else:
val = config[key]
if delete:
del config[key]
return val |
def subs_str_finder(control_s, sub_str):
"""
Finds indexes of all sub_str occurences in control_s.
"""
sub_len = len(sub_str)
while sub_str in control_s:
first_index = control_s.find(sub_str)
second_index = first_index + sub_len
return first_index, second_index |
def _get_dir_list(obj=None):
"""
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
"""
list_attributes = dir(obj)
return list_attributes |
def clean_args(hargs, iterarg, iteridx):
"""
Filters arguments for batch submission.
Parameters
----------
hargs: list
Command-line arguments
iterarg: str
Multi-argument to index (`subjects` OR `files`)
iteridx: int
`iterarg` index to submit
Returns
-------
cmdargs : list
Filtered arguments for batch submission
Example
--------
>>> from heudiconv.queue import clean_args
>>> cmd = ['heudiconv', '-d', '/some/{subject}/path',
... '-q', 'SLURM',
... '-s', 'sub-1', 'sub-2', 'sub-3', 'sub-4']
>>> clean_args(cmd, 'subjects', 0)
['heudiconv', '-d', '/some/{subject}/path', '-s', 'sub-1']
"""
if iterarg == "subjects":
iterarg = ['-s', '--subjects']
elif iterarg == "files":
iterarg = ['--files']
else:
raise ValueError("Cannot index %s" % iterarg)
# remove these or cause an infinite loop
queue_args = ['-q', '--queue', '--queue-args']
# control variables for multi-argument parsing
is_iterarg = False
itercount = 0
indicies = []
cmdargs = hargs[:]
for i, arg in enumerate(hargs):
if arg.startswith('-') and is_iterarg:
# moving on to another argument
is_iterarg = False
if is_iterarg:
if iteridx != itercount:
indicies.append(i)
itercount += 1
if arg in iterarg:
is_iterarg = True
if arg in queue_args:
indicies.extend([i, i+1])
for j in sorted(indicies, reverse=True):
del cmdargs[j]
return cmdargs |
def ReadFileAsLines(filename):
"""Reads a file, removing blank lines and lines that start with #"""
file = open(filename, "r")
raw_lines = file.readlines()
file.close()
lines = []
for line in raw_lines:
line = line.strip()
if len(line) > 0 and not line.startswith("#"):
lines.append(line)
return lines |
def get_parent_path(path, split_symbol):
"""get parent path
Args:
path (string): raw path
split_symbol (string): path separator
Returns:
string: the parent path
"""
reversed_path = ''
times = 0
for ch in reversed(path):
if(times >= 2):
reversed_path = reversed_path + ch
else:
if(ch == split_symbol):
times = times + 1
return reversed_path[::-1] |
def disable() -> dict:
"""Disables headless events for the target."""
return {"method": "HeadlessExperimental.disable", "params": {}} |
def popCount(v):
"""Return number of 1 bits in an integer."""
if v > 0xFFFFFFFF:
return popCount(v >> 32) + popCount(v & 0xFFFFFFFF)
# HACKMEM 169
y = (v >> 1) & 0xDB6DB6DB
y = v - y - ((y >> 1) & 0xDB6DB6DB)
return (((y + (y >> 3)) & 0xC71C71C7) % 0x3F) |
def jaccard_similarity(str_1, str_2):
""" compute of intersection to get similraity score between words """
str_1 = set(str_1.split())
str_2 = set(str_2.split())
intersect = str_1.intersection(str_2)
return float(len(intersect)) / (len(str_1) + len(str_2) - len(intersect)) |
def message_relative_index(messages, message_id):
"""
Searches the relative index of the given message's id in a channel's message history. The returned index is
relative, because if the message with the given is not found, it should be at that specific index, if it would be
inside of the respective channel's message history.
Parameters
----------
messages : `deque` of ``Message``
The message history of a channel.
message_id : `int`
A messages's id to search.
Returns
-------
index : `int`
"""
bot = 0
top = len(messages)
while True:
if bot < top:
half = (bot + top) >> 1
if messages[half].id > message_id:
bot = half + 1
else:
top = half
continue
break
return bot |
def heur(p1, p2):
"""
Heuristic function, gets a prediction for the distance from the
given node to the end node, which is used to guide the a*
algorithm on which node to search next.
Uses Manhattan distance, which simply draws an L to the end node.
"""
x1, y1 = p1
x2, y2 = p2
return abs(x1 - x2) + abs(y1 - y2) |
def _osi(preferred_responses, ortho_responses):
"""This is the hard-coded osi function."""
return ((preferred_responses - ortho_responses)
/ (preferred_responses + ortho_responses)) |
def swllegend(cur):
"""
Example of a hardcoded legend, does not use the legend database.
"""
d = {'linecolor' : '#0505ff',
'linethick' : 2,
'linestyle': '-'}
return d |
def increment(value, list_):
"""
This updates the value according to the list. Since we seek 4
consecutive numbers with exactly 4 prime factors, we can jump
4 numbers if the last doesn't have 4 factors, can jump 3 if
the second to last doesn't have 4 factors, and so on
"""
if list_[-1] != 4:
return value + 4
# We can assume the last element is a 4
if list_[-2:] != [4, 4]:
return value + 3
# We can assume the last 2 elements are [4,4]
if list_[-3:] != [4, 4, 4]:
return value + 2
# We can assume the last 3 elements are [4,4,4]
return value + 1 |
def url_join(*args):
"""Join combine URL parts to get the full endpoint address."""
return '/'.join(arg.strip('/') for arg in args) |
def calc_factorial(x: int) -> int:
"""Calculate factorial."""
if x < 2:
return 1
return x * calc_factorial(x=x - 1) |
def _get_resource_info(args):
"""Get the target resource information.
Args:
args (object): The args.
Returns:
list: The list of args to use with gcloud.
str: The resource id.
"""
resource_args = None
resource_id = None
if args.org_id:
resource_args = ['organizations']
resource_id = args.org_id
elif args.folder_id:
resource_args = ['alpha', 'resource-manager', 'folders']
resource_id = args.folder_id
elif args.project_id:
resource_args = ['projects']
resource_id = args.project_id
return resource_args, resource_id |
def sys_model(t, x, u):
"""Function modelling the dynamic behaviour of the system in question with a control term u.
Returns the state of the ODE at a given point in time"""
dx1dt = 2*x[0] + x[1] + 2*u[0] - u[1]
dx2dt = x[0] + 2*x[1] - 2*u[0] + 2*u[1]
return [dx1dt, dx2dt] |
def _get_aea_logger_name_prefix(module_name: str, agent_name: str) -> str:
"""
Get the logger name prefix.
It consists of a dotted save_path with:
- the name of the package, 'aea';
- the agent name;
- the rest of the dotted save_path.
>>> _get_aea_logger_name_prefix("aea.save_path.to.package", "myagent")
'aea.myagent.save_path.to.package'
:param module_name: the module name.
:param agent_name: the agent name.
:return: the logger name prefix.
"""
module_name_parts = module_name.split(".")
root = module_name_parts[0]
postfix = module_name_parts[1:]
return ".".join([root, agent_name, *postfix]) |
def _parse_selections(dpkgselection):
"""
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
"""
ret = {}
if isinstance(dpkgselection, str):
dpkgselection = dpkgselection.split("\n")
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret |
def length(iterable):
"""
Return number of elements in iterable. Consumes iterable!
>>> length(range(10))
10
:param iterable iterable: Any iterable, e.g. list, range, ...
:return: Length of iterable.
:rtype: int
"""
return sum(1 for _ in iterable) |
def flatten_list_of_lists(list_of_lists):
"""Convert a list os lists to a single list
Args:
list_of_lists (list of lists): A list of lists.
Returns:
result_list (list): A list
Examples:
>>> list_of_lists = [[1,2,3],[0,3,9]]
>>> flatten_list_of_lists(list_of_lists)
[1, 2, 3, 0, 3, 9]
"""
result_list = [item for sublist in list_of_lists for item in sublist]
return result_list |
def compute_grid_growth(n_para, n_approx_points):
"""
"""
grid_growth = [n_approx_points ** power for power in range(1, n_para)]
return grid_growth |
def mtime(filename):
"""When was the file modified the last time?
Return value: seconds since 1970-01-01 00:00:00 UTC as floating point number
0 if the file does not exists"""
from os.path import getmtime
try: return getmtime(filename)
except: return 0 |
def max_scaling(x):
""" Scaling the values of an array x
with respect to the maximum value of x.
"""
return [i/max(x) for i in x] |
def convertToInts(problem):
"""
Given a two-dimensional list of sets return a new two-dimensional list
of integers.
:param list problem: Two-dimensional list of sets
:return: Two-dimensional list of integer
:rtype: list
"""
return [[next(iter(loc)) if len(loc) == 1 else 0 for loc in row]
for row in problem] |
def look_up_words(input_text):
"""Replacing social media slangs with more standarized words.
:param input_text: Slanged social media text.
:return: Standarized text.
"""
# look-up dictionary
social_media_look_up = {
'rt':'Retweet',
'dm':'direct message',
"awsm" : "awesome",
"luv" :"love"
}
# words in sentence
words = input_text.split()
# standarize each word using look-up table
return " ".join([social_media_look_up.get(word.lower(),word) for word in words]) |
def error(geometry):
"""
returns the max expected error (based on past runs)
"""
return {"slice": 7e-2,
"sphere": 2.5e-2}[geometry] |
def convert_quarter_to_date(time):
"""
Reformats dates given with quarters to month-day format.
Args:
time: String representing time in the format year-quarter(e.g. Q1, Q2, ...)
Returns:
String representing time in the format year-month-day.
"""
date = time
if "Q1" in date:
date = str(date[:5]) + "01-01"
elif "Q2" in date:
date = str(date[:5]) + "04-01"
elif "Q3" in date:
date = str(date[:5]) + "07-01"
else:
date = str(date[:5]) + "10-01"
return date |
def mappingSightingOpenIOC(etype):
"""
Map the openioc types to threat sightings
"""
mapping = {
"sha256": "FileItem/Sha256sum",
"ipv4": "DnsEntryItem/RecordData/IPv4Address",
"domain": "Network/URI",
"url": "UrlHistoryItem/URL",
"dstHost": "Network/URI",
"md5": "FileItem/Md5sum",
"sha1": "FileItem/Sha1sum",
"ipv6": "DnsEntryItem/RecordData/IPv6Address",
"file": "FileItem/FileName",
"name": "FileItem/FileName",
"path": "FileItem/FilePath",
"key": "RegistryItem/KeyPath"
}
return mapping[etype] |
def __splitTime(sec):
"""Takes an amount of seconds and returns a tuple for hours, minutes and seconds.
@rtype: tuple(int, int, int)
@return: A tuple that contains hours, minutes and seconds"""
minutes, sec = divmod(sec, 60)
hour, minutes = divmod(minutes, 60)
return (hour, minutes, sec) |
def filter_ReceptPolys(recept_polys,bna_polys):
"""
checks if a receptor poly is wholly within a bna poly. If it is, it isn't kept.
"""
recept_polys_new = []
recept_index = []
for kk in range(len(recept_polys)):
keep = True
bb = 0
bna = []
for bpoly in bna_polys[1:]:
#print('bb: ',bb)
bb += 1
if recept_polys[kk].within(bpoly):
keep = False
break
if keep:
# print('kk:: ',kk)
recept_polys_new.append(recept_polys[kk])
recept_index.append(kk)
return recept_polys_new,recept_index |
def rebuild_cmd(i):
"""
Input: {
choices - dict of choices
choices_order - choices order
choices_desc - dict of choices desc
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
cmd - compiler command line
pruned_choices - leave only compiler flags
}
"""
cmd=''
choices=i.get('choices',{})
corder=i.get('choices_order',[])
cdesc=i.get('choices_desc',{})
for q in sorted(corder):
v=choices.get(q, None)
d=cdesc.get(q, None)
if v!=None:
if cmd!='': cmd+=' '
cmd+=v
return {'return':0, 'cmd':cmd} |
def find_first(sack):
""" Find the ID of the first kid who gets allocated a present from the supplied sack. """
return 1 if sack == 1 else sack ** 2 // 2 |
def collapse_stmts(stmts):
"""
Returns a flat list containing every statement in the tree
stmts.
"""
rv = [ ]
for i in stmts:
i.get_children(rv.append)
return rv |
def escape_windows_title_string(s):
"""Returns a string that is usable by the Windows cmd.exe title
builtin. The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
"""
for c in '^&<>|':
s = s.replace(c, '^' + c)
s = s.replace('/?', '/.')
return s |
def chain_apply(funcs, var):
"""apply func from funcs[0] to funcs[-1]"""
for func in funcs:
var = func(var)
return var |
def bresenhams(start, end):
"""Bresenham's Line Algo -- returns list of tuples from start and end"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
# Determine how steep the line is
is_steep = abs(dy) > abs(dx)
# Rotate line
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
# Swap start and end points if necessary and store swap state
swapped = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
swapped = True
# Recalculate differentials
dx = x2 - x1
dy = y2 - y1
# Calculate error
error = int(dx / 2.0)
ystep = 1 if y1 < y2 else -1
# Iterate over bounding box generating points between start and end
y = y1
points = []
for x in range(x1, x2 + 1):
coord = (y, x) if is_steep else (x, y)
points.append(coord)
error -= abs(dy)
if error < 0:
y += ystep
error += dx
# Reverse the list if the coordinates were swapped
if swapped:
points.reverse()
return points |
def convert_lowercase(in_str):
""" Convert a given string to lowercase
:param in_str: input text
:return: string
"""
return str(in_str).lower() |
def find_total_bag_colors(rules, color, level=0):
"""Find all colors which can contain a bag of the given color"""
found = []
def mapper(rule, times):
ret = []
for bag in rules[rule]:
for _ in range(bag.count):
ret.append(bag)
for bag in tuple(ret):
ret.extend(mapper(bag.color, bag.count))
return ret
found = mapper(color, 1)
print(f"{len(found)} bags needed within a {color} bag")
return found |
def bubble_sort(array):
"""This function takes a list as input and sorts it by bubblegit sort algorithm"""
for i in range(len(array)):
for j in range(len(array)-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array |
def _encodeList(l):
"""Check for binary arrays in list and tries to decode to string
Args:
l ([]): list to seach
Returns:
:[]: original list with any byte array entries replaced with strings
"""
for i in range(len(l)):
if type(l[i]) is bytes:
l[i] = l[i].decode()
return l |
def is_asm(l):
"""Returns whether a line should be considered to be an instruction."""
l = l.strip()
# Empty lines
if l == '':
return False
# Comments
if l.startswith('#'):
return False
# Assembly Macros
if l.startswith('.'):
return False
# Label
if l.endswith(':'):
return False
return True |
def sorted_dict(item, key=None, reverse=False):
"""Return a new sorted dictionary from the `item`."""
if not isinstance(item, dict):
return item
return {k: sorted_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items(), key=key, reverse=reverse)} |
def main(name="Valdis", count=3):
"""
Printing a greeting message
For our friends
"""
for _ in range(count):
print(f'Hello {name}')
return None |
def str_goal(goal, indent=4):
"""Print each variable in goal, indented by indent spaces."""
result = ""
if goal != False:
for (name,val) in vars(goal).items():
if name != '__name__':
for x in range(indent): result = result + " "
result = result + goal.__name__ + "." + name
result = result + "= " + val
else: result = result + "False"
return result |
def flatten_in_place(orig):
"""flattens a given list in place"""
is_flattened = False
while not is_flattened: # iterating until no more lists are found
is_flattened = True
for i, item in enumerate(orig):
if isinstance(item, list):
is_flattened = False
orig = orig[:i] + item + orig[i + 1:]
return orig |
def convertSize(size):
"""
The convertSize function converts an integer representing bytes into a human-readable format.
:param size: The size in bytes of a file
:return: The human-readable size.
"""
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
index = 0
while size > 1024:
size /= 1024.
index += 1
return '{:.2f} {}'.format(size, sizes[index]) |
def _clean_kwargs(kwargs):
""" Do some sanity checks on kwargs
>>> _clean_kwargs({'parse_dates': ['a', 'b'], 'usecols': ['b', 'c']})
{'parse_dates': ['b'], 'usecols': ['b', 'c']}
>>> _clean_kwargs({'names': ['a', 'b'], 'usecols': [1]})
{'parse_dates': [], 'names': ['a', 'b'], 'usecols': ['b']}
"""
kwargs = kwargs.copy()
if kwargs.get('usecols') and 'names' in kwargs:
kwargs['usecols'] = [kwargs['names'][c]
if isinstance(c, int) and c not in kwargs['names']
else c
for c in kwargs['usecols']]
kwargs['parse_dates'] = [col for col in kwargs.get('parse_dates', ())
if kwargs.get('usecols') is None
or isinstance(col, (tuple, list)) and all(c in kwargs['usecols']
for c in col)
or col in kwargs['usecols']]
return kwargs |
def is_source(f):
"""Returns true iff the input file name is considered a source file."""
return not f.endswith('_test.go') and (
f.endswith('.go') or f.endswith('.s')) |
def format_hours(date, **kwargs):
"""Format hours"""
date_list = date.split('T')
date_hour = date_list[1][:5]
return date_hour |
def string_similarity(string1: str, string2: str) -> float:
"""
Compare the characters of two strings.
Parameters
----------
string1: str
The first string.
string2: str
The second string.
Returns
-------
: float
Similarity of strings expressed as fraction of matching characters.
"""
common = len([x for x, y in zip(string1, string2) if x == y])
return common / max([len(string1), len(string2)]) |
def check_pseudo_overlap(x1, x2, y1, y2):
"""
check for overlaps [x1, x2] and [y1, y2]
should only be true if these overlap
"""
return max(x1, y1) <= min(x2, y2) |
def get_index_bounds(indexes):
"""Returns the bounds (first and last element) of consecutive numbers.
Example:
[1 , 3, 4, 5, 7, 8, 9, 10] -> [1, 3, 5, 7, 10]
Args:
indexes (list of int): integers in an ascending order.
Returns:
list of int: the bounds (first and last element) of consecutive numbers.
"""
index_bounds = [indexes[0]]
for i, v in enumerate(indexes):
if i == len(indexes)-1:
index_bounds.append(v)
break
if v+1 == indexes[i+1]:
continue
else:
index_bounds.append(v)
index_bounds.append(indexes[i+1])
return index_bounds |
def mod97(digit_string):
"""Modulo 97 for huge numbers given as digit strings.
This function is a prototype for a JavaScript implementation.
In Python this can be done much easier: long(digit_string) % 97.
"""
m = 0
for d in digit_string:
m = (m * 10 + int(d)) % 97
return m |
def get_taurus_options(artifacts_dir, jmeter_path=None):
"""The options for Taurus BZT command"""
options = []
if jmeter_path:
options.append('-o modules.jmeter.path={}'.format(jmeter_path))
options.append('-o settings.artifacts-dir={}'.format(artifacts_dir))
options.append('-o modules.console.disable=true')
options.append('-o settings.env.BASEDIR={}'.format(artifacts_dir))
options_str = ' '.join(options)
return options_str |
def isdistinct(seq):
""" All values in sequence are distinct
>>> isdistinct([1, 2, 3])
True
>>> isdistinct([1, 2, 1])
False
>>> isdistinct("Hello")
False
>>> isdistinct("World")
True
"""
if iter(seq) is seq:
seen = set()
for item in seq:
if item in seen:
return False
seen.add(item)
return True
else:
return len(seq) == len(set(seq)) |
def mergeDicts(dictOfDicts, keysOfDicts):
"""Function merge dicts in dict. Current dicts are given by its key.
Args:
dictOfDicts (dict): Dictionary of dictionaries to merge.
keysOfDicts (set): Keys of current dictionaries to merge.
Returns:
dict: Merged dictionary.
"""
mergedDict = dict()
for currentDictKey in keysOfDicts:
# Check if asked dictionary exists.
if currentDictKey in dictOfDicts:
for key in dictOfDicts[currentDictKey]:
if key not in mergedDict:
mergedDict[key] = set()
mergedDict[key].update(dictOfDicts[currentDictKey][key])
return mergedDict |
def latin1_encode(obj):
"""
Encodes a string using LATIN-1 encoding.
:param obj:
String to encode.
:returns:
LATIN-1 encoded bytes.
"""
return obj.encode("latin1") |
def crossref_title_parser(title):
"""Function to parse title.
Returns:
str"""
return " ".join(title[0].split()) |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, Nothing at this URL.', 404 |
def style(style_def):
"""Convert a console style definition in to dictionary
>>> style("bold red on yellow")
{fg="red", bg="yellow", bold=True}
"""
if not style_def:
return {}
if isinstance(style_def, dict):
return style_def
colors = {"yellow", "magenta", "green", "cyan", "blue", "red", "black", "white"}
text_styles = {"bold", "underline", "dim", "reverse", "italic"}
style = {}
foreground = True
style_set = True
for s in style_def.split(" "):
if s == "on":
foreground = False
elif s == "not":
style_set = False
elif s in colors:
style["fg" if foreground else "bg"] = s
elif s in text_styles:
style[s] = style_set
else:
raise ValueError("unknown style '{}'".format(s))
return style |
def sort_by_relevance(repo_list):
"""
Build display order.
As of 2020-01-14 it sorts by number of forks and stars combined
:param repo_list: repolist to sort
:return: sorted repolist
"""
repo_list.sort(key=lambda repo: repo['repo_forks'] + repo['repo_stars'], reverse=True)
return repo_list |
def preprocess(line):
"""
Preprocess a line of Jane Austen text.
* insert spaces around double dashes --
:param line:
:return:
"""
return line.replace("--", " -- ") |
def isUrl(image):
"""Checks if a string is an URL link.
Args:
image (string): The string to be checked.
Returns:
bool: True if it is a valid URL link, False if otherwise.
"""
try:
if image.startswith('https') or image.startswith('http'):
return True
return False
except:
return False |
def end() -> dict:
"""Stop trace events collection."""
return {"method": "Tracing.end", "params": {}} |
def is_set(check, bits):
"""Return True if all bits are set."""
return check & bits == bits |
def _read_if_html_path(txt: str) -> str:
"""Open HTML file if path provided
If the input is a path to a valid HTML file, read it.
Otherwise return the input
"""
if txt and txt.endswith(".html"):
with open(txt, "rt") as fh:
txt = fh.read()
return txt |
def select_k_best_regions(regions, k=16):
"""
Args:
regions -- list list of 2-component tuples first component the region,
second component the ratio of white pixels
k -- int -- number of regions to select
"""
regions = [x for x in regions if x[3] > 180 and x[4] > 180]
k_best_regions = sorted(regions, key=lambda tup: tup[2])[:k]
return k_best_regions |
def time_to_min(in_time: str) -> int:
"""
Turns human given string to time in minutes
e.g. 10h 15m -> 615
"""
times = [int(x.strip()) for x in in_time.strip("m").split("h")]
assert len(times) <= 2
if len(times) == 1:
return times[0]
else:
return times[0] * 60 + times[1] |
def ensure_ends_with_slash(string):
"""Returns string with a trailing slash"""
return (
string
if string.endswith('/')
else '{}/'.format(string)
) |
def file_as_byte(file):
"""
This function is used to return the content of a file as byte. Used for the MD5 hash of the file in main.py
"""
with file:
return file.read() |
def list_to_str(list_name):
"""
Formats a list into a string.
:param list_name: (List of String) List to be formatted
:return: (String) String representation of list
"""
final_str = ''
for string in list_name:
final_str += string + '\n'
return final_str |
def empty_or_matching_label(prediction: dict, labels: list) -> bool:
"""
Returns:
bool: if labels list is empty or prediction label matches a label in the list
"""
if len(labels) == 0 or prediction["label"] in labels:
return True
else:
return False |
def parsemem(value, unit):
"""Parse a memory size value and unit to int."""
e = {"B": 0, "K": 1, "M": 2, "G": 3, "T": 4}[unit]
return int(float(value) * 1024 ** e) |
def parse_csv(csv, as_ints=False):
"""
Parses a comma separated list of values as strings or integers
"""
items = []
for val in csv.split(','):
val = val.strip()
if val:
items.append(int(val) if as_ints else val)
return items |
def _pythonize_cmdstan_type(type_name: str) -> type:
"""Turn CmdStan C++ type name into Python type.
For example, "double" becomes ``float`` (the type).
"""
if type_name == "double":
return float
if type_name in {"int", "unsigned int"}:
return int
if type_name.startswith("bool"):
return bool
if type_name == "list element":
raise NotImplementedError(f"Cannot convert CmdStan `{type_name}` to Python type.")
if type_name == "string":
return str
raise ValueError(f"Cannot convert CmdStan `{type_name}` to Python type.") |
def IsInClosurizedNamespace(symbol, closurized_namespaces):
"""Match a goog.scope alias.
Args:
symbol: An identifier like 'goog.events.Event'.
closurized_namespaces: Iterable of valid Closurized namespaces (strings).
Returns:
True if symbol is an identifier in a Closurized namespace, otherwise False.
"""
for ns in closurized_namespaces:
if symbol.startswith(ns + '.'):
return True
return False |
def cardValue(card):
"""Returns the value of a given card."""
if card[0] >= '2' and card[0] <= '9':
return int(card[0])
elif card[0] == 'T':
return 10
elif card[0] == 'J':
return 11
elif card[0] == 'Q':
return 12
elif card[0] == 'K':
return 13
elif card[0] == 'A':
return 14 |
def _formatOptions(kargs):
"""Returns a string: "key1=val1,key2=val2,..."
(where keyx and valx are string representations)
"""
arglist = ["%s=%s" % keyVal for keyVal in kargs.items()]
return "%s" % (",".join(arglist)) |
def _read_marker_mapping_from_ini(string: str) -> dict:
"""Read marker descriptions from configuration file."""
# Split by newlines and remove empty strings.
lines = filter(lambda x: bool(x), string.split("\n"))
mapping = {}
for line in lines:
try:
key, value = line.split(":")
except ValueError as e:
key = line
value = ""
if not key.isidentifier():
raise ValueError(
f"{key} is not a valid Python name and cannot be used as a marker."
) from e
mapping[key] = value
return mapping |
def path_exists(fpath):
"""
determine whether a file or directory exists
workaround for os.stat, which doesn't properly allow Unicode filenames
"""
try:
with open(fpath, "rb") as f:
f.close()
return True
except IOError as e:
if e.errno == 21:
# Is a directory
return True
else:
return False |
def triangle_area(base, height):
"""Returns the area of a triangle"""
# You have to code here
# REMEMBER: Tests first!!!
area = (base * height) / 2
return area |
def filename_to_varname(filename):
"""Converts a template file-name to a python variable name"""
return (filename.lower()
.replace('-', '_')
.replace('.txt', '')) |
def split_tuple(s):
"""Split a string of comma-separated expressions at the top level,
respecting parentheses and brackets:
e.g. 'a, b, c(d, e), f' -> ['a', 'b', 'c(d, e)', 'f']
Args:
s (string): a string of comma-separated expressions which may themselves contain commas
Returns:
list(str): a list of top-level expressions
"""
bl = 0 # Bracketing level
ls = []
w = ""
for i, c in enumerate(s):
if c in "[(":
bl += 1
elif c in ")]":
bl -= 1
if c == "," and not bl: # Add running word to the list as long as we're outside of brackets
ls.append(w.strip())
w = ""
else:
w += c # Add character to running string
ls.append(w.strip())
return ls |
def make_matrix(num_rows, num_cols, entry_fn):
""" returns a num_rows by num_cols matrix
whose (i,j)th entry is entry_fn(i,j) """
# Example: identity_matrix = make_matrix(5, 5, is_diagonal)
return [[entry_fn(i, j) # given i, create a list
for j in range(num_cols)] # [entry_fn(i, 0), ...]
for i in range(num_rows)] |
def get_trajectory_len(trajectory):
"""Get the total number of actions in the trajectory."""
return len(trajectory["action"]) |
def plain_text(*rtf):
"""Return the combined plain text from the list of RichText objects."""
return ("".join(text.plain_text for text in rtf if text)).strip() |
def _basename_in_ignore_list_re(base_name, ignore_list_re):
"""Determines if the basename is matched in a regex ignorelist
:param str base_name: The basename of the file
:param list ignore_list_re: A collection of regex patterns to match against.
Successful matches are ignored.
:returns: `True` if the basename is ignored, `False` otherwise.
:rtype: bool
"""
for file_pattern in ignore_list_re:
if file_pattern.match(base_name):
return True
return False |
def scaled_image(width, height):
"""face_recognition face detection slow AF compare to MTCNN
scaling the image as per resolution to process fast"""
total = width*height
scale_dict = {0.2: 6500000, 0.3: 4000000, 0.4: 2250000, 0.5: 1000000, 0.8: 500000, 1: 0}
for k, v in scale_dict.items():
if total > v:
return k |
def solve(num_a, num_b, num_c, num_d, num_e):
"""Sums a bunch of numbers."""
return num_a + num_b + num_c + num_d + num_e |
def toUnicode(input):
"""
Convert bytes string to string
"""
return str(input, 'utf-8') |
def optimal_threshold(payoffs):
"""
>>> optimal_threshold([2,0,1,0.5])
0.5
>>> optimal_threshold([1.1,0,1,0.4])
0.9090909090909091
"""
return (payoffs[2] - payoffs[1]) / float(payoffs[0] - payoffs[1]) |
def expand_number_range(num_string):
"""
A function that will accept a text number range (such as 1,3,5-7) and convert it into a list of integers such as
[1, 3, 5, 6, 7]
:param num_string: <str> A string that is in the format of a number range (e.g. 1,3,5-7)
:return: <list> A list of all integers in that range (e.g. [1,3,5,6,7])
"""
output_list = []
for item in num_string.split(','):
if "-" in item:
if item.count('-') != 1:
raise ValueError("Invalid range: '{0]'".format(item))
else:
start, end = map(int, item.split('-'))
output_list.extend(range(start, end+1))
else:
output_list.append(int(item))
return output_list |
def inverse_brzycki(one_rm, r):
"""
Realistic for low reps. Conservative for high reps.
r-RM estimate based on 1RM.
"""
return (37 - r) / 36 * one_rm |
def format_helptext(value):
"""Handle formatting for HELPTEXT field.
Apply formatting only for token with value otherwise supply with newline"""
if not value:
return "\n"
return "\t {}\n".format(value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.