content
stringlengths 42
6.51k
|
---|
def accuracy_score(data):
"""
Given a set of (predictions, truth labels), return the accuracy of the predictions.
:param data: [List[Tuple]] -- A list of predictions with truth labels
:returns: [Float] -- Accuracy metric of the prediction data
"""
return 100 * sum([1 if p == t else 0 for p, t in data]) / len(data)
|
def handle_pci_dev(line):
"""Handle if it is pci line"""
if "Region" in line and "Memory at" in line:
return True
if line != '\n':
if line.split()[0][2:3] == ':' and line.split()[0][5:6] == '.':
return True
return False
|
def rc_to_xy(track, r, c):
"""
Convert a track (row, col) location to (x, y)
(x, y) convention
* (0,0) in bottom left
* x +ve to the right
* y +ve up
(row,col) convention:
* (0,0) in top left
* row +ve down
* col +ve to the right
Args:
track (list): List of strings describing the track
r (int): row coordinate to be converted
c (int): col coordinate to be converted
Returns:
tuple: (x, y)
"""
x = c
y = (len(track) - 1) - r
return x, y
|
def get_out_direct_default(out_direct):
"""get default out direct"""
outdict = {"console": "1", "monitor": "2", "trapbuffer": "3",
"logbuffer": "4", "snmp": "5", "logfile": "6"}
channel_id_default = outdict.get(out_direct)
return channel_id_default
|
def only_even(arg1, arg2):
"""
Get even numbers between arg1 and arg2
:param arg1: Number
:param arg2: Number
:return: List of the even value between arg1 and arg2
"""
def even_filter(num):
"""
Function fo filter
:param num: Number
:return: True if even, else False
"""
return num % 2 == 0
return list(filter(even_filter, range(min(arg1, arg2), max(arg1, arg2))))
|
def duplicate_count(text):
"""Return duplicate count"""
unique = dict()
for elem in text.lower():
if elem in unique:
unique[elem] = unique[elem]+1
else:
unique[elem] = 1
return len([k for k,v in unique.items() if v >= 2])
|
def command_settings(body_max=102400000, time_max=0):
"""
Generates dictionary with command settings
"""
settings = {
"body_max": int(body_max),
"time_max": int(time_max)
}
return settings
|
def isPal(x):
"""Assumes x is a list
Returns True if the list is a palindrome; False otherwise"""
temp = x[:]
temp.reverse()
if temp == x:
return True
else:
return False
|
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
:param key:
:param values:
:return:
"""
return [max(values)-min(values), 0.5*(max(key)-min(key)), min(values)]
|
def _format_binary(num: int, padding: int) -> str:
"""Format a number in binary."""
return format(num, f'#0{padding + 2}b')[2:]
|
def check_format(filename):
"""
check the format of file
:param filename:
:return:
"""
allowed_format = [".fa", ".fasta", ".fa.gz", ".fasta.gz"]
if any([f for f in allowed_format if filename.endswith(f)]):
return 0
else:
msg = "file format is not in %s" % allowed_format
raise Exception(msg)
|
def get_counter(data, base):
"""
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
"""
b0 = data[base]
b1 = data[base + 1]
b2 = data[base + 2]
b3 = data[base + 3]
counter = b3
position = (b1 << 8) + b2
return counter, position
|
def calculate_avg_movie_score(movies):
"""Calculate average scores for each director"""
ratings = [
m.score for m in movies
] # make a list of all the movie scores of the specific director
average = sum(ratings) / max(
1, len(ratings)
) # add the list and divide by the number of items in the list. the max is to avoid divide by zeros
return round(average, 1)
|
def py_hash(key, num_buckets):
"""Generate a number in the range [0, num_buckets).
Args:
key (int): The key to hash.
num_buckets (int): Number of buckets to use.
Returns:
The bucket number `key` computes to.
Raises:
ValueError: If `num_buckets` is not a positive number.
"""
b, j = -1, 0.0
if num_buckets < 1:
raise ValueError(
f"'num_buckets' must be a positive number, got {num_buckets}"
)
while j < num_buckets:
b = int(j)
key = ((key * int(2862933555777941757)) + 1) & 0xFFFFFFFFFFFFFFFF
j = float(b + 1) * (float(1 << 31) / float((key >> 33) + 1))
return int(b)
|
def _filter_data_list(data: list, by_key, by_value, ignore_case: bool):
"""Parameter 'data':
- A list of entity dicts """
if data:
result = []
for entry in data:
entry_value = entry[by_key]
value = by_value
if ignore_case:
entry_value = str(entry_value).lower()
value = str(value).lower()
if isinstance(by_value, list):
if entry_value in value:
result.append(entry)
elif entry_value == value:
result.append(entry)
return result
else:
return data
|
def is_markdown_cell(cell):
"""Returns whether a cell is a Markdown cell
Args:
cell (``nbformat.NotebookNode``): the cell in question
Returns:
``bool``: whether a cell is a Markdown cell
"""
return cell["cell_type"] == "markdown"
|
def safe_float(string_, default=1.0):
"""Convert a string into a float.
If the conversion fails, return the default value.
"""
try:
ret = float(string_)
except ValueError:
return default
else:
return ret
|
def is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
import unicodedata
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
|
def find_encryption( public_key, loops ):
"""
Starting from the given public_key, this function applies the transformation
for loops times and returns the value
"""
value = 1
for _ in range(loops):
value *= public_key
value = value % 20201227
return value
|
def parse_iopub_for_reply(msgs, line_number):
"""Get kernel response from message pool (Async).
.. note:: some kernel (iperl) do not discriminate when client asks for
`user_expressions`. But still they give a printable output.
Parameters
----------
msgs : list
List of messages to parse.
line_number : int
The message number of the corresponding code.
Returns
-------
str
The kernel response to the messages.
"""
res = -1
# Parse all execute
for msg in msgs:
# Get the result of execution
content = msg.get('content', False)
if not content:
continue
ec = int(content.get('execution_count', 0))
if not ec:
continue
if line_number not in (-1, ec):
continue
msg_type = msg.get('header', {}).get('msg_type', '')
if msg_type not in ('execute_result', 'stream'):
continue
res = content.get('data', {}).get('text/plain', -1)
res = res if res != -1 else content.get('text', -1)
break
return res
|
def make_goal(s):
"""Generate a goal board with an given size
Args:
s (int, s>=3): The size of goal board to generate, i.e. the width of the board.
Returns:
goal (list): A 2D list representing tiles of the goal board,
e.g., if the size given is 3, the goal is [[1,2,3],[4,5,6],[7,8,9]].
"""
goal = []
arr = [i for i in range(1, s*s)]
arr.append(0)
for i in range(s):
tmp = []
for j in range(s):
tmp.append(arr[i*s + j])
goal.append(tmp)
return goal
|
def binomial_coeff(n, k):
"""
Math is fun (Thanks Adrien and Eric)
"""
import functools as ft
import operator as op
k = min(k, n - k)
n = ft.reduce(op.mul, range(n, n - k, -1), 1)
d = ft.reduce(op.mul, range(1, k + 1), 1)
return n / d
|
def _pure_cyclotron_freq(q, m, B):
"""pure cyclotron frequency"""
return B * q / m
|
def scale_to_100(value):
"""Scale the input value from 0-255 to 0-100."""
return max(0, min(100, ((value * 100.0) / 255.0)))
|
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc):
"""
Calculate the average range rate. eqn 6.37 in Montenbruck 2000.
tc = length of integration interval, i.e. length of CPI
Created: 04/04/17
"""
range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor. 19.04.17
return range_rate
|
def _KeyMissing(side):
"""One log is missing a key present in the other log."""
return 'Key missing from %s' % side
|
def prepare_package(date, metainfo=None):
""" Prepare metainfo for package """
base = {
'publishedDate': date,
'releases': [],
'publisher': {
'name': '',
'scheme': '',
'uri': ''
},
}
if metainfo:
base.update(metainfo)
return base
|
def separate_file_from_parents(full_filename):
"""Receives a full filename with parents (separated by dots)
Returns a duple, first element is the filename and second element
is the list of parents that might be empty"""
splitted = full_filename.split('.')
file = splitted.pop()
parents = splitted
return (file, parents)
|
def stations_by_river(stations):
"""Find stations which are by the same river
Args:
stations (list): list of MonitoringStation objects
Returns:
dictionary: river name as key to a list of station names
"""
dic_stations_river = {}
for station in stations:
key = station.river
if key in dic_stations_river:
dic_stations_river[key].append(station.name)
else:
dic_stations_river[key] = [station.name]
return dic_stations_river
|
def objsize(obj):
"""
Returns the size of a deeply nested object (dict/list/set).
The size of each leaf (non-dict/list/set) is 1.
"""
assert isinstance(obj, (dict, list, set)), obj
if not obj:
return 0
if isinstance(obj, dict):
obj = obj.values()
elem = next(iter(obj))
if isinstance(elem, (dict, list, set)):
return sum(objsize(v) for v in obj)
else:
return len(obj)
|
def concatStrDict(d, order=[]):
"""Concatenates all entries of a dictionary (assumed to be
lists of strings), in optionally specified order."""
retstr = ""
if d != {}:
if order == []:
order = list(d.keys())
for key in order:
itemlist = d[key]
for strlist in itemlist:
retstr += "".join(strlist)
return retstr
|
def line_value(line_split):
"""
Returns 1 string representing the value for this line
None will be returned if theres only 1 word
"""
length = len(line_split)
if length == 1:
return None
elif length == 2:
return line_split[1]
elif length > 2:
return b' '.join(line_split[1:])
|
def restructure_stanford_response(json_doc):
"""Restructure the JSON output from stanford KP.
:param: json_doc: the API response from stanford KP
"""
# convert from list to dict
if isinstance(json_doc, list):
json_doc = {'data': json_doc}
if 'data' in json_doc:
for _doc in json_doc['data']:
# store restructured attributes info
new_attr = {}
for _attr in _doc['attributes']:
if 'attributeValueTermUri' not in _attr:
new_attr[_attr['attributeName'].replace(' ', '_')] = _attr['attributeValue']
else:
new_attr[_attr['attributeName'].replace(' ', '_')] = {'name': _attr['attributeValue']}
if 'PATO_' in _attr['attributeValueTermUri']:
new_attr[_attr['attributeName'].replace(' ', '_')]['pato'] = 'PATO:' + _attr['attributeValueTermUri'].split('_')[-1]
elif 'MONDO_' in _attr['attributeValueTermUri']:
new_attr[_attr['attributeName'].replace(' ', '_')]['mondo'] = 'MONDO:' + _attr['attributeValueTermUri'].split('_')[-1]
elif 'BTO_' in _attr['attributeValueTermUri']:
new_attr[_attr['attributeName'].replace(' ', '_')]['bto'] = 'BTO:' + _attr['attributeValueTermUri'].split('_')[-1]
elif 'CLO_' in _attr['attributeValueTermUri']:
new_attr[_attr['attributeName'].replace(' ', '_')]['clo'] = 'CLO:' + _attr['attributeValueTermUri'].split('_')[-1]
_doc['attributes'] = new_attr
return json_doc
return {}
|
def app(environ, start_response):
"""A barebones WSGI app.
This is a starting point for your own Web framework
"""
status = "200 OK"
response_headers = [("Content-Type", "text/plain")]
start_response(status, response_headers)
return [b"Hello world from a simple WSGI application\n"]
|
def split_simple(molname_simple):
"""split simple molname
Args:
molname_simple: simple molname
Return:
atom list
number list
Example:
>>> split_simple("Fe2O3")
>>> (['Fe', 'O'], ['2', '3'])
"""
atom_list=[]
num_list=[]
tmp=None
num=""
for ch in molname_simple:
if ch.isupper():
if tmp is not None:
atom_list.append(tmp)
num_list.append(num)
num=""
tmp=ch
elif ch.islower():
tmp=tmp+ch
elif ch.isdigit():
num=ch
atom_list.append(tmp)
num_list.append(num)
return atom_list,num_list
|
def initialize_3d_list(a, b, c):
"""
:param a:
:param b:
:param c:
:return:
"""
lst = [[[None for _ in range(c)] for _ in range(b)] for _ in range(a)]
return lst
|
def find_idx_scalar(scalar, value):
"""
Retrieve indexes of the value in the nested list scalar.
The index of the sublist corresponds to a K value.
The index of the element corresponds to a kappa value.
Parameters:
scalar -- list, size 2^n x 2^n
value -- float
"""
# Give sublist index and element index in scalar if element == value
indexes = [[sublist_idx, elem_idx] for sublist_idx,sublist in enumerate(scalar) for elem_idx, elem in enumerate(sublist) if elem==value]
return indexes
|
def recursive_update(target, update):
"""Recursively update a dictionary. Taken from jupytext.header
"""
for key in update:
value = update[key]
if value is None:
# remove if it exists
target.pop(key, None)
elif isinstance(value, dict):
target[key] = recursive_update(target.get(key, {}), value)
else:
target[key] = value
return target
|
def _sum_state_financial_outlay(results:dict):
"""
Aggregate state total financial outlay for FRT
Arguments:
results {dict} -- Result set from `get_state_frts`
Returns:
float -- Returns total financial outlay
"""
if results == None:
return 0
total_financial_outlay = 0
for result in results:
if result['financial_outlay_cr']:
total_financial_outlay += result['financial_outlay_cr']
return total_financial_outlay
|
def _check_maybe_route(variable_name, variable_value, route_to, validator):
"""
Helper class of ``SlashCommand`` parameter routing.
Parameters
----------
variable_name : `str`
The name of the respective variable
variable_value : `str`
The respective value to route maybe.
route_to : `int`
The value how much times the routing should happen. by default should be given as `0` if no routing was
done yet.
validator : `callable` or `None`
A callable, what validates the given `variable_value`'s value and converts it as well if applicable.
Returns
-------
processed_value : `str`
Processed value returned by the `validator`. If routing is happening, then a `tuple` of those values is
returned.
route_to : `int`
The amount of values to route to.
Raises
------
ValueError
Value is routed but to a bad count amount.
BaseException
Any exception raised by `validator`.
"""
if (variable_value is not None) and isinstance(variable_value, tuple):
route_count = len(variable_value)
if route_count == 0:
processed_value = None
elif route_count == 1:
variable_value = variable_value[0]
if variable_value is ...:
variable_value = None
if validator is None:
processed_value = variable_value
else:
processed_value = validator(variable_value)
else:
if route_to == 0:
route_to = route_count
elif route_to == route_count:
pass
else:
raise ValueError(f'`{variable_name}` is routed to `{route_count}`, meanwhile something else is '
f'already routed to `{route_to}`.')
if validator is None:
processed_value = variable_value
else:
processed_values = []
for value in variable_value:
if (value is not ...):
value = validator(value)
processed_values.append(value)
processed_value = tuple(processed_values)
else:
if validator is None:
processed_value = variable_value
else:
processed_value = validator(variable_value)
return processed_value, route_to
|
def normalize_url_without_bewit(url, bewit):
"""Normalizes url by removing bewit parameter."""
bewit_pos = url.find('bewit=')
# Chop off the last character before 'bewit=' which is either a ? or a &
bewit_pos -= 1
bewit_end = bewit_pos + len("bewit=" + bewit) + 1
o_url = ''.join([url[0:bewit_pos], url[bewit_end:]])
return o_url
|
def expandBrackets(f, lower, upper, step=1.1, step_mod=1.0, max_iteration=1<<10):
"""Expand brackets upwards using a geometric series
@param f callable (function of form f(x) = 0)
@param lower float (initial guess, not varied)
@param upper float (initial guess, is expanded)
@param step float (used in geometric series)
@param step_mod float (used to modify the geometric series: deltaX_n = step_mod * step ** n)
@param max_iteration int (default 2^10)
@return float or False
"""
v_upper = 0.
v_lower = f(lower)
count = 0
while count < max_iteration:
count += 1
v_upper = f(upper)
if v_upper * v_lower < 0:
return (lower, upper)
elif count < 1e3:
upper += step_mod * step ** count
else:
upper += step_mod * step ** 1e3
return False
|
def disp_to_depth(disp, min_depth, max_depth):
"""Convert network's sigmoid output into depth prediction
"""
min_disp = 1 / max_depth
max_disp = 1 / min_depth
scaled_disp = min_disp + (max_disp - min_disp) * disp
depth = 1 / scaled_disp
return scaled_disp, depth
|
def rootssq(ll):
"""Return the root of the sum of the squares of the list of values. If a
non-iterable is passed in, just return it."""
try:
return sum([ss**2 for ss in ll])**0.5
except TypeError:
pass # ll is not iterable
return ll
|
def _CreateLinkColumn(name, label, url):
"""Returns a column containing markdown link to show on dashboard."""
return {'a_' + name: '[%s](%s)' % (label, url)}
|
def create_default_config(schema):
"""Create a configuration dictionary from a schema dictionary.
The schema defines the valid configuration keys and their default
values. Each element of ``schema`` should be a tuple/list
containing (default value,docstring,type) or a dict containing a
nested schema."""
o = {}
for key, item in schema.items():
if isinstance(item, dict):
o[key] = create_default_config(item)
elif isinstance(item, tuple):
value, comment, item_type = item
if isinstance(item_type, tuple):
item_type = item_type[0]
if value is None and (item_type == list or item_type == dict):
value = item_type()
if key in o:
raise KeyError('Duplicate key in schema.')
o[key] = value
else:
raise TypeError('Unrecognized type for schema dict element: %s %s' %
(key, type(item)))
return o
|
def replace_string_newline(str_start: str, str_end: str, text: str) -> str:
"""
re.sub function stops at newline characters, but this function moves past these
params: str_start, the start character of the string to be delted
str_end, the end character of the string to be deleted
text, the string to be edited
return: text, a string without the string between str_start and str_end
"""
while text.find(str_start) != -1:
begin = text.find(str_start) # also just starts w/o http, has (/
nextp = text.find(str_end, begin, len(text))
text = text.replace(text[begin-1:nextp+1], ' ')
return text
|
def check_password_requirements(password: str) -> str:
"""Check if password meets requirements."""
if len(password) < 8:
return "Password must be at least 8 characters long."
if not any(char.isdigit() for char in password):
return "Password must contain at least one number."
if not any(char.isupper() for char in password):
return "Password must contain at least one uppercase letter."
if not any(char.islower() for char in password):
return "Password must contain at least one lowercase letter."
return ""
|
def reldiff(x,y,floor=None):
"""
Checks relative (%) difference <floor between x and y
floor would be a decimal value, e.g. 0.05
"""
d = x-y
if not d:
return 0
ref = x or y
d = float(d)/ref
return d if not floor else (0,d)[abs(d)>=floor]
#return 0 if x*(1-r)<y<x*(1+r) else -1
|
def html_quote( line ):
"""Change HTML special characters to their codes.
Follows ISO 8859-1 Characters changed: `&`, `<` and `>`.
"""
result = line
if "`" not in result:
result = line.replace( "&", "&" )
result = result.replace( "<", "<" )
result = result.replace( ">", ">" )
return result
|
def _xor(bs1, bs2, n):
"""Return exclusive or of two given byte arrays"""
bs = bytearray()
for (b1, b2) in zip(bs1, bs2):
bs.append(b1 ^ b2)
return bs
|
def process_standard_commands(command, game):
"""Process commands which are common to all rooms.
This includes things like following directions, checking inventory, exiting
the game, etc.
Returns true if the command is recognized and processed. Otherwise, returns
false.
"""
if command == 'north':
room = game.current_room.north
if room:
game.current_room = room
else:
print('There is no room to the north')
elif command == 'south':
room = game.current_room.south
if room:
game.current_room = room
else:
print('There is no room to the south')
elif command == 'east':
room = game.current_room.east
if room:
game.current_room = room
else:
print('There is no room to the east')
elif command == 'west':
room = game.current_room.west
if room:
game.current_room = room
else:
print('There is no room to the east')
elif command == 'description':
print(game.current_room.description)
elif command == 'inventory':
print('Inventory %s' % game.player.inventory)
elif command == 'quit':
game.player.alive = False
else:
# unrecognized command
return False
return True
|
def unitarity_decay(A, B, u, m):
"""Eq. (8) of Wallman et al. New J. Phys. 2015."""
return A + B*u**m
|
def get_optimal_knapsack_value(W, items):
"""
Gets the highest value the knapsack can carry
given items of the form [(weight, value)]
up to a weight W
Complexity: O(n * S)
"""
n = len(items)
knapsacks = dict()
for i in range(n, -1, -1):
for j in range(W + 1):
if i == n:
knapsacks[(i, j)] = 0
continue
if j == 0:
knapsacks[(i, j)] = 0
continue
weight, value = items[i]
if weight <= j:
knapsacks[(i, j)] = max(
knapsacks[(i + 1, j)],
knapsacks[(i + 1, j - weight)] + value)
else:
knapsacks[(i, j)] = knapsacks[(i + 1, j)]
return knapsacks[(0, W)]
|
def _check_return_value(ret):
"""
Helper function to check if the 'result' key of the return value has been
properly set. This is to detect unexpected code-paths that would otherwise
return a 'success'-y value but not actually be succesful.
:param dict ret: The returned value of a state function.
"""
if ret["result"] == "oops":
ret["result"] = False
ret["comment"].append(
"An internal error has occurred: The result value was "
"not properly changed."
)
return ret
|
def find_item(keys, d, create=False):
"""Return a possibly deeply buried {key, value} with all parent keys.
Given:
keys = ['a', 'b']
d = {'a': {'b': 1, 'c': 3}, 'b': 4}
returns:
{'a': {'b': 1}}
"""
default = {} if create else None
value = d.get(keys[0], default)
if len(keys) > 1 and type(value) is dict:
return {keys[0]: find_item(keys[1:], value, create)}
else:
return {keys[0]: value}
|
def sum_numbers_in_list(array: list) -> int:
"""
BIG-O Notation = O(n)
"""
result = 0
for i in array:
result += i
return result
|
def _include_spefic_ft(graph, ft_type, method, sorted_features, ft_dict):
""" Execute features individually """
num_of_feature_type = 0 if ft_type in ft_dict else None
if ft_type in sorted_features and ft_type in ft_dict:
num_of_feature_type = len(sorted_features[ft_type])
for f in sorted_features[ft_type]:
method(graph, f)
return num_of_feature_type
|
def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization.
"""
attrs = ['tags']
ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id']
sp_attrs = ['secret']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
if managed_cluster.agent_pool_profiles is not None:
for ap_profile in managed_cluster.agent_pool_profiles:
for attr in ap_attrs:
if getattr(ap_profile, attr, None) is None:
delattr(ap_profile, attr)
for attr in sp_attrs:
if getattr(managed_cluster.service_principal_profile, attr, None) is None:
delattr(managed_cluster.service_principal_profile, attr)
return managed_clusters
|
def ts(nodes, topo_order): # topo must be a list of names
"""
Orders nodes by their topological order
:param nodes: Nodes to be ordered
:param topo_order: Order to arrange nodes
:return: Ordered nodes (indices)
"""
node_set = set(nodes)
return [n for n in topo_order if n in node_set]
|
def _normalize_requirement_name(name: str) -> str:
"""
Normalizes the string: the name is converted to lowercase and all dots and underscores are replaced by hyphens.
:param name: name of package
:return: normalized name of package
"""
normalized_name = name.lower()
normalized_name = normalized_name.replace('.', '-')
normalized_name = normalized_name.replace('_', '-')
return normalized_name
|
def list_evolution(list1,list2):
"""
returns the index evolution of each element
of the list 1 compared to the index within list 2
NB: if lists length do not match, place None value at missing index
"""
# return [list2.index(x) - list1.index(x) for x in list1 if x in list2]
evo = []
for x in list1:
if x in list2:
evo.append(list2.index(x) - list1.index(x))
else:
evo.append(None)
return evo
|
def check_pid(pid):
""" Check For the existence of a unix pid. """
import os
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
|
def get_unique_value_from_summary_ext(test_summary, index_key, index_val):
""" Gets list of unique target names and return dictionary
"""
result = {}
for test in test_summary:
key = test[index_key]
val = test[index_val]
if key not in result:
result[key] = val
return result
|
def add_modules_to_metadata(modules, metadata):
"""
modules is dict of otus, metadata is a dictionary of dictionaries where outer dict keys
are features, inner dict keys are metadata names and values are metadata values
"""
for module_, otus in modules.items():
for otu in otus:
if str(otu) in metadata:
metadata[str(otu)]['module'] = module_
else:
metadata[str(otu)] = dict()
metadata[str(otu)]['module'] = module_
return metadata
|
def perplexity(probability: float, length: int) -> float:
"""Return the perplexity of a sequence with specified probability and length."""
return probability ** -(1 / length)
|
def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, pos
return char, pos+1
|
def get_pacer_case_id_from_nonce_url(url):
"""Extract the pacer case ID from the URL.
In: https://ecf.almd.uscourts.gov/cgi-bin/DktRpt.pl?56120
Out: 56120
In: https://ecf.azb.uscourts.gov/cgi-bin/iquery.pl?625371913403797-L_9999_1-0-663150
Out: 663150
"""
param = url.split("?")[1]
if "L" in param:
return param.rsplit("-", 1)[1]
return param
|
def condense_multidimensional_zeros(css):
"""Replace `:0 0 0 0;`, `:0 0 0;` etc. with `:0;`."""
css = css.replace(":0 0 0 0;", ":0;")
css = css.replace(":0 0 0;", ":0;")
css = css.replace(":0 0;", ":0;")
# Revert `background-position:0;` to the valid `background-position:0 0;`.
css = css.replace("background-position:0;", "background-position:0 0;")
return css
|
def remove_digits(s):
"""
Returns a string with all digits removed.
"""
return ''.join(filter(lambda x: not x.isdigit(), s))
|
def parse_core_proc_tomo_fh_section(root):
"""
place older function to be developed yet
"""
core_proc_tomo_fh_obj = None
return core_proc_tomo_fh_obj
|
def persistence_model(series):
"""DOCSTRING
Wrapper for baseline persistence model"""
return [x for x in series]
|
def rep_int(value):
""" takes a value and see's if can be converted to an integer
Args:
value: value to test
Returns:
True or False
"""
try:
int(value)
return True
except ValueError:
return False
|
def equal_para(struct):
"""compares the number of '(' and ')' and makes sure they're equal.
Return bool True is ok and False is not a valid structure."""
if struct.count('(') == struct.count(')'):
return True
else:
return False
|
def build_history_object(metrics):
"""
Builds history object
"""
history = {
'batchwise': {},
'epochwise': {}
}
for matrix in metrics:
history["batchwise"][f"training_{matrix}"] = []
history["batchwise"][f"validation_{matrix}"] = []
history["epochwise"][f"training_{matrix}"] = []
history["epochwise"][f"validation_{matrix}"] = []
return history
|
def Serialize(obj):
"""Convert a string, integer, bytes, or bool to its file representation.
Args:
obj: The string, integer, bytes, or bool to serialize.
Returns:
The bytes representation of the object suitable for dumping into a file.
"""
if isinstance(obj, bytes):
return obj
if isinstance(obj, bool):
return b'true' if obj else b'false'
return str(obj).encode('utf-8')
|
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test_all': ['test_list_services', 'test_delete_bp', 'test_execute_bp',
'test_get_bp', 'test_restore_bp', 'test_archive_bp', 'test_update_bp',
'test_create_bp', 'test_list_bps', 'test_delete_repo', 'test_get_repo',
'test_create_repo', 'test_list_repos', 'install']
}
|
def capital_case(st: str) -> str:
"""Capitalize the first letter of each word of a string. The remaining characters are untouched.
Arguments:
st {str} -- string to convert
Returns:
str -- converted string
"""
if len(st) >= 1:
words = st.split()
return ' '.join([f'{s[:1].upper()}{s[1:]}' for s in words if len(s) >= 1])
else:
return ''
|
def decode(bytedata):
"""Convert a zerocoded bytestring into a bytestring"""
i = 0
l = len(bytedata)
while i < l:
if bytedata[i] == 0:
c = bytedata[i+1] - 1
bytedata = bytedata[:i+1] + (b"\x00"*c) + bytedata[i+2:]
i = i + c
l = l + c - 1
i = i + 1
return bytedata
|
def get_headers(sql, prefix=None):
"""Returns a list of headers in an sql select string"""
cols = []
open_parenth = False
clean_sql = ""
# Remove anything in parentheses, liable to contain commas
for i, char in enumerate(sql):
if char == "(":
open_parenth = True
elif char == ")":
open_parenth = False
if not open_parenth:
clean_sql += sql[i].replace("\t", " ")
for col in clean_sql.split("FROM")[0].replace("SELECT", "").split(","):
if " as " in col.lower():
c = col.split(" as ")[-1]
elif "." in col.lower():
c = col.split(".")[-1]
else:
c = col
cols.append(c.strip())
if prefix != None:
cols = ", ".join([".".join([prefix, col]) for col in cols])
return cols
|
def split_NtoM(N, M, rank):
"""
split N to M pieces
see https://stackoverflow.com/a/26554699/9746916
"""
chunk = N // M
remainder = N % M
if rank < remainder:
start = rank * (chunk + 1)
stop = start + chunk
else:
start = rank * chunk + remainder
stop = start + (chunk -1)
return start, stop
|
def handle_index(l, index):
"""Handle index.
If the index is negative, convert it. If the index is out of range, raise
an IndexError.
"""
# convert negative indices to positive ones
if index < 0:
# len(l) has always type 'int64'
# while index can be an signed/unsigned integer
index = type(index)(len(l) + index)
# check that the index is in range
if not (0 <= index < len(l)):
raise IndexError("list index out of range")
return index
|
def growing_plant(upSpeed, downSpeed, desiredHeight) -> int:
"""
Each day a plant is growing by upSpeed meters. Each night
that plant's height decreases by downSpeed meters due to the
lack of sun heat. Initially, plant is 0 meters tall. We plant
the seed at the beginning of a day. We want to know when the
height of the plant will reach a certain level.
:param upSpeed:
:param downSpeed:
:param desiredHeight:
:return:
"""
height = 0
days = 0
while height <= desiredHeight:
height += upSpeed
days += 1
if height >= desiredHeight:
return days
height -= downSpeed
return days
|
def get_definitions_diff(previous_definition_string, new_definition_string):
"""Returns a triple of lists (definitions_removed,
definitions_shared, definitions_added)"""
old_definitions = [i for i in previous_definition_string.split('|') if i]
new_definitions = [i for i in new_definition_string.split('|') if i]
return (tuple(i for i in old_definitions if i not in new_definitions),
tuple(i for i in old_definitions if i in new_definitions),
tuple(i for i in new_definitions if i not in old_definitions))
|
def knapsack_rec(W, val, weight, n):
"""recursive knapsac problem where
W = max weight knapsack can hold
val = array of values
weight = array of weights associated with values
n = length of the arrays
"""
# Base case
if n == 0 or W == 0:
return 0
# if weight of item is more than max wt of knapsack
if weight[n-1] > W:
return knapsack_rec(W, val, weight, n-1)
# if weight can be added to the knapsack
else:
return max(val[n-1] + knapsack_rec(W-weight[n-1], val, weight, n-1),
knapsack_rec(W, val, weight, n-1))
|
def problem_forms(doc):
"""
Return non-XFormInstances (duplicates, errors, etc.)
"""
return doc["doc_type"] != "XFormInstance"
|
def hyper_replace(text, old: list, new: list):
"""
Allows you to replace everything you need in one function using two lists.
:param text:
:param old:
:param new:
:return:
"""
msg = str(text)
for x, y in zip(old, new):
msg = str(msg).replace(x, y)
return msg
|
def confirm(cause):
"""
Display confirm msg (Green)
"""
return ("\033[1;32;40m [+] "+cause + " \033[0m ")
|
def repeating_key_xor(message_bytes, key):
"""Returns message XOR'd with a key. If the message, is longer
than the key, the key will repeat.
"""
output_bytes = b''
index = 0
for byte in message_bytes:
output_bytes += bytes([byte ^ key[index]])
if (index + 1) == len(key):
index = 0
else:
index += 1
return output_bytes
|
def _getText(nodelist):
""" returns collected and stripped text of textnodes among nodes in nodelist """
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc.strip()
|
def pop_path(path):
"""Return '/a/b/c' -> ('a', '/b/c')."""
if path in ("", "/"):
return ("", "")
assert path.startswith("/")
first, _sep, rest = path.lstrip("/").partition("/")
return (first, "/" + rest)
|
def init_field(height=20, width=20):
"""Creates a field by filling a nested list with zeros."""
field = []
for y in range(height):
row = []
for x in range(width):
row.append(0)
field.append(row)
return field
|
def getAverageScore(result):
"""
Get the average score of a set of subscores for a student
\n
:param result: A dicitonary containing the results of a student \t
:type result: {extensions : {http://www.boxinabox.nl/extensions/multiple-results : [{value, ...}], ...}, ...} \n
:returns: The average score \t
:rtype: double \n
"""
extensions = result["extensions"]["http://www.boxinabox.nl/extensions/multiple-results"]
extensions = extensions.values()
extensions = [elem for elem in list(extensions) if isinstance(elem["value"], int)]
extensions = map(lambda res: res["value"], extensions)
extensions = list(extensions)
if (len(extensions) == 0):
return 0
return sum(extensions) / len(extensions)
|
def div_to_int(int_numerator, int_denominator, round_away=False):
"""Integer division with truncation or rounding away.
If round_away evaluates as True, the quotient is rounded away from
zero, otherwise the quotient is truncated.
"""
is_numerator_negative = False
if int_numerator < 0:
int_numerator = -int_numerator
is_numerator_negative = True
is_denominator_negative = False
if int_denominator < 0:
int_denominator = - int_denominator
is_denominator_negative = True
quotient, remainder = divmod(int_numerator, int_denominator)
if round_away and remainder > 0:
quotient += 1
if is_numerator_negative != is_denominator_negative:
quotient = -quotient
return quotient
|
def firstTarget(targets):
"""
Return the first (year, coefficient) tuple in targets with coefficient != 0.
"""
targets.sort(key=lambda tup: tup[0]) # sort by year
for year, coefficient in targets:
if coefficient: # ignore zeros
return (year, coefficient)
|
def a2idx(a):
"""
Tries to convert "a" to an index, returns None on failure.
The result of a2idx() (if not None) can be safely used as an index to
arrays/matrices.
"""
if hasattr(a, "__int__"):
return int(a)
if hasattr(a, "__index__"):
return a.__index__()
|
def unbinary(value):
"""Converts a string representation of a binary number to its equivalent integer value."""
return int(value, 2)
|
def arg_name(name):
"""Get the name an argument should have based on its Python name."""
return name.rstrip('_').replace('_', '-')
|
def isBin(s):
"""
Does this string have any non-ASCII characters?
"""
for i in s:
i = ord(i)
if i < 9:
return True
elif i > 13 and i < 32:
return True
elif i > 126:
return True
return False
|
def s_hex_dump(data, addr=0):
"""
Return the hex dump of the supplied data starting at the offset address specified.
:type data: Raw
:param data: Data to show hex dump of
:type addr: int
:param addr: (Optional, def=0) Offset to start displaying hex dump addresses from
:rtype: str
:return: Hex dump of raw data
"""
dump = byte_slice = ""
for byte in data:
if addr % 16 == 0:
dump += " "
for char in byte_slice:
if 32 <= ord(char) <= 126:
dump += char
else:
dump += "."
dump += "\n%04x: " % addr
byte_slice = ""
dump += "%02x " % ord(byte)
byte_slice += byte
addr += 1
remainder = addr % 16
if remainder != 0:
dump += " " * (16 - remainder) + " "
for char in byte_slice:
if 32 <= ord(char) <= 126:
dump += char
else:
dump += "."
return dump + "\n"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.