content stringlengths 42 6.51k |
|---|
def _uint_to_int(uint, bits):
"""
Assume an int was read from binary as an unsigned int,
decode it as a two's compliment signed integer
:param uint:
:param bits:
:return:
"""
if (uint & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
uint = uint - ... |
def fed_avg(weights, factors):
"""
compute FedAvg
param::weights locally trained model weights
param::factors factors determined by the number of data points collected
"""
fed_avg_wegiths = []
n_clients = len(weights)
for w_index, w in enumerate(weights[0]):
layer_fed_avg_weight ... |
def micro_f1_similarity(
y_true: str,
y_pred: str
) -> float:
"""
Compute micro f1 similarity for 1 row
Parameters
----------
y_true : str
True string of a space separated birds names
y_pred : str
Predicted string of a space separated birds names
Returns
... |
def update_param_grid(param_grid, sizes):
"""Update parameters of the grid search.
Args:
param_grid: current grid search dictionary
sizes: dataset.shape
Returns:
param_grid: updated grid search dictionary
"""
if 'h_units' in param_grid.keys():
# NN and simple_linear data
if sizes[1] > 1:
... |
def _are_filter_operations_equal_and_possible_to_eliminate(
filter_operation_1: str, filter_operation_2: str
) -> bool:
"""Return True only if one of the filters is redundant."""
if filter_operation_1 == filter_operation_2 == "<":
return True
if filter_operation_1 == filter_operation_2 == ">=":
... |
def remove_muts(remove_lost, pop, mut):
"""
This function removes lost mutations, if desired
"""
if remove_lost:
keep = pop.any(axis=0)
mut = mut[keep]
pop = pop[:, keep]
return [pop, mut] |
def create_numeric_classes(lithologies):
"""Creates a dictionary mapping lithologies to numeric code
Args:
lithologies (iterable of str): Name of the lithologies
"""
my_lithologies_numclasses = dict([(lithologies[i], i) for i in range(len(lithologies))])
return my_lithol... |
def get_xl_version_string(exe: str) -> str:
"""
Extracts the version string from a SHELXL executable.
This is fast and needs no hashes etc.
:type exe: str
:param exe: path to SHELXL executable
"""
try:
with open(exe, 'rb') as f:
binary = f.read()
position = bi... |
def _replace_all(string, substitutions):
"""Replaces occurrences of the given patterns in `string`.
There are a few reasons this looks complicated:
* The substitutions are performed with some priority, i.e. patterns that are
listed first in `substitutions` are higher priority than patterns that are
... |
def a_slash_b(a, b):
"""Creates the string "a/b" where a is as wide as b."""
b_str = str(b)
return "{a: >{fill}}/{b}".format(a=a, b=b_str, fill=len(b_str)) |
def is_unique(x):
"""tests if there is not 2 same elements in x
Args:
x (list of int]): [the list to test]
Returns:
[bool]: [show if there is not 2 same elements in x]
"""
flag = True
for i in range(len(x)):
for j in range(i + 1, len(x)):
if x[i] == x[j]:
... |
def win(s1, s2):
"""Return true if s1 defeats s2, false otherwise."""
if ((s1 == 'r' and s2 == 's') or
(s1 == 'p' and s2 == 'r') or
(s1 == 's' and s2 == 'p')):
return True
return False |
def A000119(n: int) -> int:
"""Give the number of representations of n as a sum of distinct Fibonacci numbers."""
def f(x, y, z):
if x < y:
return 0 ** x
return f(x - y, y + z, y) + f(x, y + z, y)
return f(n, 1, 1) |
def get_anchor_box(clusters):
"""
"""
return sorted(clusters, key = lambda x : x[0] * x[1]) |
def samedomain(netloc1, netloc2):
"""Determine whether two netloc values are the same domain.
This function does a "subdomain-insensitive" comparison. In other words ...
samedomain('www.microsoft.com', 'microsoft.com') == True
samedomain('google.com', 'www.google.com') == True
samedomain('api.gith... |
def speed_control(target, current, Kp=1.0):
"""
Proportional control for the speed.
:param target: target speed (m/s)
:param current: current speed (m/s)
:param Kp: speed proportional gain
:return: controller output (m/ss)
"""
return Kp * (target - current) |
def header_definition(num_state,version_protocol):
"""
This function generate Headers of client messages.
@param num_state: (int) it's a number that indicate the instruction for header
@param version_protocol:(str) that indicate the actual version of the game
@return :(bytes or 0) bytes that are the header of ... |
def get_module_parent(module_name):
""" Return the parent module name
>>> get_module_parent('django.conf')
'django'
>>> get_module_parent('django')
'django'
"""
splitted = module_name.split(".")
if len(splitted) == 1:
return module_name
else:
return ".".join(splitted... |
def transform_post(post):
"""Transforms post data
Arguments:
post {dict} -- Post data
"""
return {
'id': post['id'],
'title': post['title'],
'url': post['url'],
'image': post['feature_image'],
'summary': post['custom_excerpt'] \
if post['c... |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
>>> from construct_check import check
>>> # ban iteration
>>> check(HW_SOURCE_FILE, 'count_c... |
def inverse_color(color):
""" inverse a rgb color"""
return [abs(d - 255) for d in color] |
def binary_search(array: list, target: int) -> int:
"""
binary search
"""
start = 0
end = len(array) - 1
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
start = mid + 1
else:
... |
def string_xyz(xyz):
"""Returns an xyz point as a string like (121234.56, 567890.12, 3456.789)"""
return '({0:4.2f}, {1:4.2f}, {2:5.3f})'.format(xyz[0], xyz[1], xyz[2]) |
def rule_id(arg):
"""Return a regex that captures rule id"""
assert isinstance(arg, str)
return r"(?P<%s>\d+)" % (arg,) |
def MapInstanceLvsToNodes(cfg, instances):
"""Creates a map from (node, volume) to instance name.
@type cfg: L{config.ConfigWriter}
@param cfg: The cluster configuration
@type instances: list of L{objects.Instance}
@rtype: dict; tuple of (node uuid, volume name) as key, L{objects.Instance}
object a... |
def get_statistics(my_list):
"""
Function to determine the min, max, average and standard deviation.
"""
n = len(my_list)
av = sum(my_list)/n
ss = sum((x-av)**2 for x in my_list)
if n < 2:
return min(my_list), max(my_list), av
else:
return min(my_list), max(my_list), av... |
def make_layout(rows, columns):
"""Create a layout of rooms represented by a set of coordinates."""
locations = set()
for y in range(rows):
for x in range(columns):
locations.add((x, y))
return locations |
def _parse_signature(input_length, output_length):
"""Helper function that construct the desired signature string based on the
shape of input_columns and output_columns defined in transform_config.
The signature string will be used for invoking numpy.vectorize function.
Args:
input_length: (int), length of... |
def _nm_multiply(multiplier, A):
"""calculate the product of a rational number multiplier and matrix A"""
m, n = len(A), len(A[0])
B = []
for row in range(m):
current_row = []
for col in range(n):
current_row.append(multiplier*A[row][col])
B.append(tuple(current_row))... |
def h2r(_hex):
"""
Convert a hex string to an RGB-tuple.
"""
if _hex.startswith('#'):
l = _hex[1:]
else:
l = _hex
return list(bytes.fromhex(l)) |
def compute_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_r... |
def ordinal(n):
"""
A compact function for generating ordinal suffixes (1st, 2nd, etc.)
:param n:
:return:
>>> ordinal(1)
'1st'
>>> ordinal(2)
'2nd'
"""
return "%d%s" % (n, "tsnrhtdd"[(n / 10 % 10 != 1) *
(n % 10 < 4) * n % 10::4]) |
def generate_random_key(length):
"""
Generate key of specific length
"""
import random
import string
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length)) |
def fix_wifi_csv(header: bytes, rows_list: list, file_name: str):
""" Fixing wifi requires inserting the same timestamp on EVERY ROW.
The wifi file has its timestamp in the filename. """
time_stamp = file_name.rsplit("/", 1)[-1][:-4].encode()
# the last row is a new line, have to slice.
for row in ... |
def checkLabels(x):
"""
Make a warm fuzzy about the classes being balanced
"""
s_id = 0.0
s_type = 0.0
s_color = 0.0
total = len(x)
for v in x:
if v[2][0]:
s_id += 1
if v[2][1]:
s_type += 1
if v[2][2]:
s_color += 1
print('P(... |
def str_list_oconv(x):
"""
Convert list into a list literal.
"""
return ','.join(x) |
def boundary_constraint(node_density, hole):
""" Each hole should be at least 2 vertices away from the edge,
so the edge could form a face."""
for key, val in hole.items():
# Setting the minimum boundary between edge and hole.
# Min two vertices away so edge could form face.
upper_b... |
def ascls(maybe_cls):
"""Sometimes code wants the class but is given an object. ascls just takes that small piece of logic and provides
a clean method call to ensure the code is working on a class not an instance.
:param Any maybe_cls:
:return: Type
"""
cls = maybe_cls
if not isinstance(ma... |
def center(bbox):
"""get the center coord of bbox"""
return [(bbox[0]+bbox[2])/2, (bbox[1]+bbox[3])/2] |
def all_subsets(lst):
"""
Iteratively finds all possible subsets of a list
(including the trivial and null subsets)
>>> all_subsets([1,2,3])
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
"""
results = [[]]
while lst:
results += [q + [lst[0]] for q in results]
ls... |
def concat_iterable(iterable, concatenators):
"""
Take an iterable containing iterables of strings,
return a list of strings concatenating inner iterables with '::'.
E.g.:
``
result = concat_iterable([('x', 'y', 'z'), ('1', '2', '3')], [':', ':'])
result == ['x:y:z', '1:2:3']
result = ... |
def iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : list
['x1', 'x2', 'y1', 'y2']
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : list
['x... |
def scalar_function(x, y):
"""
Returns the f(x,y) defined in the problem statement.
"""
#Your code here
return x*y if x<=y else x/y |
def extract_results_from_ldap_data(data):
"""
LDAP returns a list of 2-element lists::
data := [[unused, attrs], [unused, attrs], ..]
attrs is a dictionary mapping:
``attribute names -> [attribute value, attribute value, ..]``
In every case used here, there is exactly one value in the list... |
def apply_eqn(x, eqn):
"""
Given a value "x" and an equation tuple in the format:
(m, b)
where m is the slope and b is the y-intercept,
return the "y" generated by:
y = mx + b
"""
m, b = eqn
return (m * x) + b |
def is_before(one, two):
"""
return True if ones turn is before twos,
where one, two = [time_spent, last_move_number]
"""
if one[0] < two[0] or (one[0] == two[0] and one[1] > two[1]):
return True
return False |
def quantify(iterable, pred=bool):
"""Return the how many times the predicate is true.
>>> quantify([True, False, True])
2
"""
return sum(map(pred, iterable)) |
def filter_python_file(files):
"""filter python files from simulation folder"""
python_files = []
for i in files:
parent_dir = i.split("/")[0]
if parent_dir == "simulations" and i.endswith(".py"):
python_files.append(i)
return python_files |
def select_best_model(models):
""" Selection best model based on score
:param: Models dictionary
:return: Best model
:return: Accuracy score of model
"""
best_model = "none"
max_score = 0
for model in models:
if models[model] > max_score :
max_score = models[model]
... |
def linear_equation(val1, val2, time1, time2, current_time):
"""Linear equation to get interpolated value.
:param float val1: first keyframe value
:param float val2: second keyframe value
:param float time1: first keyframe local time
:param float time2: second keyframe local time
:param float c... |
def bubble_sort(list):
"""
list: array of unsorted integers
return: list sorted in ascending order
"""
for i in range(len(list)):
# length of the list left to run through
for j in range(len(list) - i - 1):
# swap elements
if list[j] > list [j+1]:
list[j], list[j+1] = list[j+1], lis... |
def my_add_to_list2(sequence, target=None):
"""
Uses None as default and creates a target list on demand.
"""
if target is None:
target = []
target.extend(sequence)
return target |
def _valid_device(device):
"""Check if device data is valid"""
required_fields = ('name', 'type', 'group', 'canonical_name')
if all(field in device for field in required_fields):
return True
return False |
def group_by(objects, attrs):
"""Groups `objects' by the values of their attributes `attrs'.
Returns a dictionary mapping from a tuple of attribute values to a list of
objects with those attribute values.
"""
groups = dict()
for obj in objects:
key = tuple(getattr(obj, attr) for attr i... |
def geojson_feature_to_geocouch(feature):
"""
Convert GeoJSON to GeoCouch feature:
{'type': 'Feature', 'properties': {'foo': 'bar'}, 'geometry': {...}}
-> {'properties': {'foo': 'bar'}, 'geometry': {...}}
This function reuses and modifies the `feature['properties']` dictionary.
"""
_id = fe... |
def MaybeStripNonSFISuffix(s):
"""Removes _NONSFI suffix if possible, otherwise |s| as is."""
return s[:-len('_NONSFI')] if s.endswith('_NONSFI') else s |
def checkIncreaseTomorrow(close,tol):
""" Determine if price will increase, decrease, or stay the same within specified tolerance
Input tol = Tolerance for price movement as a percent
ex. 0.02 = 2% tolerance
Output increased: Array of output values
... |
def is_real(e) -> bool:
""" Returns ``True`` if `e` is a ``float``. """
return type(e) is float |
def RPL_UNAWAY(sender, receipient, message):
""" Reply Code 305 """
return "<" + sender + ">: " + message |
def binarySearchLoop(sort: list, target: int, start: int, stop: int, value: bool):
"""binary search with while"""
while start <= stop:
mid = (start + stop) // 2
if target == sort[mid]:
if value:
return sort[mid]
else:
return mid
... |
def _bool_to_str(val):
"""
This function converts the bool value into string.
:param val: bool value.
:return: enable/disable.
"""
return (
"enable"
if str(val) == "True"
else "disable"
if str(val) == "False"
else val
) |
def max(a,b):
"""Return the maximum value of the two arguments"""
if a >= b:
result = a
else:
result = b
return result |
def invert_bitstring(string):
""" This function inverts all bits in a bitstring. """
return string.replace("1", "2").replace("0", "1").replace("2", "0") |
def update_month_index(entries, updated_entry):
"""Update the Monthly index of blog posts.
Take a dictionaries and adjust its values
by inserting at the right place.
"""
new_uri = list(updated_entry)[0]
try:
entries[new_uri]['updated'] = updated_entry['updated']
except Exception:
... |
def set_config_defaults(config):
"""Add defaults so the site works"""
new_config = config.copy()
new_config.setdefault("window_title", "Materials Cloud Tool")
new_config.setdefault(
"page_title",
"<PLEASE SPECIFY A PAGE_TITLE AND A WINDOW_TITLE IN THE CONFIG FILE>",
)
new_confi... |
def _resolve_layout(N: int, gate_wires: list):
"""
Resolve the layout per layer to make sure the space usage is optimal
Args:
*N (int)*:
The number of qubits.
*gate_wires (list)*:
List of lists containing the gate wires.
Returns (dict, int):
First retu... |
def is_number(s):
"""
Check if it is a number.
Args:
s: The variable that needs to be checked.
Returns:
bool: True if float, False otherwise.
"""
try:
float(s)
return True
except ValueError:
return False |
def startswith(string, incomplete):
"""Returns True when string starts with incomplete
It might be overridden with a fuzzier version - for example a case insensitive version
Parameters
----------
string : str
The string to check
incomplete : str
The incomplete string to compare... |
def factorial(n):
"""return n!"""
return 1 if n < 2 else n * factorial(n - 1) |
def letter_count(s: str) -> dict:
"""
Count lowercase letters in a given string
and return the letter count in a hash with
'letter' as key and count as 'value'.
:param s:
:return:
"""
result: dict = dict()
for char in s:
if char.islower():
if char not in result:... |
def explicit_no_context(arg):
"""Expected explicit_no_context __doc__"""
return "explicit_no_context - Expected result: %s" % arg |
def _contains_table_start(line, debug=False):
"""Check if line is start of a md table."""
is_table = False
nb_of_pipes = line.count('|')
nb_of_escaped_pipes = line.count(r'\|')
nb_of_pipes = nb_of_pipes - nb_of_escaped_pipes
nb_of_dashes = line.count('--')
if debug:
print('Number o... |
def quote(value, sign="'"):
"""
quotes the given string value.
:param str value: value to be quoted.
:param str sign: quotation sign to be used.
defaults to single quotation if not provided.
:rtype: str
"""
return "{sign}{value}{sign}".format(sign=sign, value=str(valu... |
def convert_to_dict(obj):
"""Converts a tianqiaiObject back to a regular dict.
Nested tianqiaiObjects are also converted back to regular dicts.
:param obj: The tianqiaiObject to convert.
:returns: The tianqiaiObject as a dict.
"""
if isinstance(obj, list):
return [convert_to_dict(i) f... |
def get_tagstring(refid, tags):
"""Creates a string from a reference ID and a sequence of tags, for use in report filenames."""
return "_".join([refid] + [t[0] + "." + (t[1] if t[1] else "None") for t in tags]) |
def sum(iterable, start=0) -> object:
"""sum."""
for elem in iterable:
start += elem
return start |
def get_data_list(loc_list):
"""
This function divides movie name and address into two separate lists
"""
f_list = []
for row in range(len(loc_list)):
p_list = []
for elem in loc_list[row]:
stuff = list(elem)
for elem_2 in stuff:
if elem_2 == "... |
def annual_profit(daily_mining_profit: float, precision: int) -> float:
"""
Computes how much money you gain after paying the annual mining expense. Formula:
days_in_year = 365
daily_mining_profit * days_in_year
:param daily_mining_profit: Float. Money you gain after paying the daily mining expense... |
def writeInt(value, nbytes=4):
"""Write nbytes length integer encoded little endian.
"""
outbytes = bytearray(nbytes)
for idx in range(nbytes):
outbytes[idx] = value & 0xff
value = value >> 8
return bytes(outbytes) |
def strip_json_cruft(text: str) -> str:
"""Removes `for(;;);` (and other cruft) that preceeds JSON responses"""
try:
return text[text.index("{") :]
except ValueError:
raise ValueError("No JSON object found: {!r}".format(text)) |
def line_intersection(line1, line2):
"""
Computes the intersection point between line1 and line2.
https://stackoverflow.com/a/20677983
Args:
line1: A length-2 tuple (A, B), where both A and B are each a length-2 tuple (x, y).
line2: Same as `line1`.
Returns:
A length-2 tuple... |
def is_power(n, m):
"""
judge if n is power of m;(n>0,m>1)
"""
import math
result = math.log(m, n)
if m <= 1 or n <= 0:
raise Exception('\n\tInvalid parameter ! \n\tBe Sure:p1>0 p2>1')
return int(result) == result |
def print_LHBlist(LHBlistStr, DEBUG=False):
"""
The function prints login hash block list for debug.
If login hash block list length is above 1, login hash block prints line by line.
:param LHBlistStr:
:return:
"""
if LHBlistStr == None:
text = '[info:print_LHBlist] user.Lhashblock... |
def point_inside_square(x, y, limits):
""" determine if a point is inside a given square or not
limits is a tuple, (x_min, x_max, y_min, y_max)"""
inside_x = False
inside_y = False
# print x, y
# print limits
if limits[0] < x < limits[1]:
# print 'x in square'
inside_x = True... |
def get_category_response(meetup_id: int = 34, content: bool = False) -> dict:
"""
create a Category response
Keyword arguments:
meetup_id -- meetup id
content -- if True -> add optional fields
return -> category dict
"""
response: dict = {
"id": meetup_id,
}
if conte... |
def get_sentiment_label(sentiment):
"""Return the sentiment label based on the sentiment quantity."""
if sentiment < 0:
return -1
elif sentiment > 0:
return 1
else:
return 0 |
def check(checkRow, checkColumn):
"""checks if this row and column is valid, used when looking at possible piece movement"""
if 0 <= checkRow <= 7 and 0 <= checkColumn <= 7:
return True
return False |
def _make_plus_helper(obj, fields):
""" add a + prefix to any fields in obj that aren't in fields """
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith('_'):
# if there's a subschema apply it to a list or subdict
if fields.get(key):
... |
def format_number(number, num_decimals=2):
"""
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no... |
def parse_http1_headers(body):
"""Parse a given HTTP/1.1 request into a header dictionary.
Achieves near-parity with HTTP/2 headers.
Args:
body (bytes): Client request to parse.
Returns:
dict, request headers.
"""
body = body.decode('utf-8')
request_headers = {}
li... |
def RPL_SERVLISTEND(sender, receipient, message):
""" Reply Code 235 """
return "<" + sender + ">: " + message |
def format_symbol(item):
"""
items may be a list of strings, or a list of string lists.
In the latter case, each entry in the quick panel will show multiple rows
"""
return [item.get("name")] |
def map_rcs_to_ordered(nh, nv, row, col, spin):
"""Mapping (row, column, spin-type) to ordered encoding.
Args:
nhoriz -- number of horizontal sites
nvert -- number of vertical sites
row -- row location of the qubit in the lattice
col -- column location of the qubit in the lattic... |
def equal_ignore_order(a, b):
""" Use only when elements are neither hashable nor sortable! """
unmatched = list(b)
for element in a:
try:
unmatched.remove(element)
except ValueError:
return False
return not unmatched |
def gray_decode(tone):
""" Gray-decode the received tone number """
return (tone>>1)^tone |
def battery_lifetime(lifetime_cycles, total_energy_stored,
depth_of_discharge):
"""Compute the lifetime of a battery in energy terms
Arguments
=========
lifetime_cycles
total_energy_stored
size of battery (kWh)
depth_of_discharge
the depth of discharge for ... |
def get_unique_name(description_dict, user_run_name):
"""
Parameters
----------
description_dict: dict
A parsed dictionary created from the description from the fastq record
user_run_name: str
The user run name that we have been given on the command line
Returns
-------
... |
def inverse_permutation(permutation, j):
""" Inverse the permutation for given input j, that is, it finds i such that p[i] = j.
>>> permutation = [1, 0, 3, 2]
>>> inverse_permutation(permutation, 1)
0
>>> inverse_permutation(permutation, 0)
1
"""
for i, pi in enumerate(permutation):
... |
def project_name(settings_dict):
"""Transform the base module name into a nicer project name
>>> project_name({'DF_MODULE_NAME': 'my_project'})
'My Project'
:param settings_dict:
:return:
"""
return " ".join(
[
x.capitalize()
for x in settings_dict["DF_MODU... |
def parse_string_as_list (string):
###############################################################################
"""
Takes a string representation of nested list and creates
a nested list of stirng. For instance, with
s = "(a,b,(c,d),e)
l = parse_string_as_list
we would have l = ['a', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.