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 - (1 << bits) # compute negative value
return 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 = sum([factors[i]*weights[i][w_index] for i in range(n_clients)])
fed_avg_wegiths.append(layer_fed_avg_weight)
return fed_avg_wegiths |
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
-------
float
Micro F1 similarity
Examples
--------
>>> from evaluations.kaggle_2020 import micro_f1_similarity
>>> y_true = 'amecro amerob'
>>> y_pred = 'amecro bird666'
>>> micro_f1_similarity(y_true, y_pred)
0.5
"""
true_labels = y_true.split()
pred_labels = y_pred.split()
true_pos, false_pos, false_neg = 0, 0, 0
for true_elem in true_labels:
if true_elem in pred_labels:
true_pos += 1
else:
false_neg += 1
for pred_el in pred_labels:
if pred_el not in true_labels:
false_pos += 1
f1_similarity = 2 * true_pos / (2 * true_pos + false_neg + false_pos)
return f1_similarity |
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:
param_grid['h_units'] = [i for i in param_grid['h_units'] if i < sizes[1]]
else:
param_grid['h_units'] = [1]
if sizes[0] > 10001:
param_grid['batch_size'] = [600]
return param_grid |
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 == ">=":
return True
return False |
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_lithologies_numclasses |
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 = binary.find(b'Version 201')
if position > 0:
f.seek(position + 8, 0) # seek to version string
version = f.read(6) # read version string
return version.decode('ascii')
else:
return ''
except IOError:
print("Could not determine SHELXL version. Refinement might fail to run.")
return '' |
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
listed later.
* We also take pains to avoid doing replacements that overlap with each
other, since overlaps invalidate pattern matches.
* To avoid hairy offset invalidation, we apply the substitutions
right-to-left.
* To avoid the "_quote" -> "_quotequote_" rule introducing new pattern
matches later in the string during decoding, we take the leftmost
replacement, in cases of overlap. (Note that no rule can induce new
pattern matches *earlier* in the string.) (E.g. "_quotedot_" encodes to
"_quotequote_dot_". Note that "_quotequote_" and "_dot_" both occur in
this string, and overlap.).
Args:
string (string): the string in which the replacements should be performed.
substitutions: the list of patterns and replacements to apply.
Returns:
A string with the appropriate substitutions performed.
"""
# Find the highest-priority pattern matches for each string index, going
# left-to-right and skipping indices that are already involved in a
# pattern match.
plan = {}
matched_indices_set = {}
for pattern_start in range(len(string)):
if pattern_start in matched_indices_set:
continue
for (pattern, replacement) in substitutions:
if not string.startswith(pattern, pattern_start):
continue
length = len(pattern)
plan[pattern_start] = (length, replacement)
matched_indices_set.update([(pattern_start + i, True) for i in range(length)])
break
# Execute the replacement plan, working from right to left.
for pattern_start in sorted(plan.keys(), reverse = True):
length, replacement = plan[pattern_start]
after_pattern = pattern_start + length
string = string[:pattern_start] + replacement + string[after_pattern:]
return string |
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]:
flag = False
return flag |
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.github.com', 'www.github.com') == True
"""
domain1 = netloc1.lower()
if '.' in domain1:
domain1 = domain1.split('.')[-2] + '.' + domain1.split('.')[-1]
domain2 = netloc2.lower()
if '.' in domain2:
domain2 = domain2.split('.')[-2] + '.' + domain2.split('.')[-1]
return domain1 == domain2 |
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 message.
"""
dict_headers = {1:"HIII",3:"EXIN",4:"PROC",6:"CONF",7:"EKEY",9:"BEGG",120:"USEI",121:"MOVF",122:"ATQE",123:"GAME",124:"CATI"}
try:
answer_temp = dict_headers[num_state]
except KeyError:
return 0
else:
answer_temp1=" "+str(version_protocol)
answer_temp = answer_temp+answer_temp1+" "+"\r\n "
return bytes(answer_temp,"utf-8") |
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[:-1]) |
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['custom_excerpt'] else post['excerpt']
} |
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_change', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
def highest_coin(i):
if i>amount:
return i//2
return highest_coin(i*2)
def count_partitions(n,m):
if n==0:
return 1
elif n<0:
return 0
elif m==0:
return 0
else:
return count_partitions(n-m,m)+count_partitions(n,m//2)
return count_partitions(amount,highest_coin(1)) |
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:
end = mid - 1
return -1 |
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 as value
"""
return dict(
((node_uuid, vol), inst)
for inst in instances
for (node_uuid, vols) in cfg.GetInstanceLVsByNode(inst.uuid).items()
for vol in vols) |
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, (ss/(n-1))**0.5 |
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 input column
output_length: (int), length of output columnf
Returns:
str
"""
if input_length == 1 and output_length == 1:
return None
elif input_length > 1 and output_length == 1:
return '(n)->()'
elif input_length == 1 and output_length > 1:
return '()->(n)'
else:
return '(n)->(n)' |
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))
return tuple(B) |
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_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S_rec1 + S_rec2
# find the each edge of intersect rectangle
left_line = max(rec1[1], rec2[1])
right_line = min(rec1[3], rec2[3])
top_line = max(rec1[0], rec2[0])
bottom_line = min(rec1[2], rec2[2])
# judge if there is an intersect
if left_line >= right_line or top_line >= bottom_line:
return 0
else:
intersect = (right_line - left_line) * (bottom_line - top_line)
# print(intersect,sum_area)
return (float(intersect) / float(sum_area - intersect)) * 1.0 |
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 rows_list[:-1]:
row = row.insert(0, time_stamp)
if rows_list:
# remove last row (encountered an empty wifi log on sunday may 8 2016)
rows_list.pop(-1)
return b"timestamp," + header |
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(s_id==1):{0} P(s_type==1):{1} P(s_color==1):{2}'.format(
s_id / total, s_type / total, s_color / total))
return s_id / total, s_type / total, s_color / total |
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_bound = node_density - 3 # 0-index node_density-1
lower_bound = 2
if hole[key] >= upper_bound or hole[key] <= lower_bound:
return False
return True |
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(maybe_cls, type):
cls = maybe_cls.__class__
return cls |
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]
lst.pop(0)
return sorted(results,key=len) |
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 = concat_iterable([('x', 'y', 'z'), ('1', '2', '3')], ['::', ':'])
result == ['x::y:z', '1::2:3']
``
"""
if len(iterable) == 0:
return []
concats = concatenators + ['']
string_iter_len = len(iterable[0])
assert all(len(i) == string_iter_len for i in iterable)
assert string_iter_len == len(concats)
return [
''.join([string_iter[i] + concats[i] for i in range(string_iter_len)])
for string_iter in iterable
] |
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
['x1', 'x2', 'y1', 'y2']
The (x1, y2) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
Returns
-------
float
in [0, 1]
"""
x1, y1, w1, h1 = bb1
x2, y2, w2, h2 = bb2
# determine the coordinates of the intersection rectangle
x_left = max(x1, x2)
y_top = max(y1, y2)
x_right = min(x1 + w1, x2 + w2)
y_bottom = min(y1 + h1, y2 + h2)
if x_right < x_left or y_bottom < y_top:
return 0.0
# The intersection of two axis-aligned bounding boxes is always an
# axis-aligned bounding box
intersection_area = (x_right - x_left) * (y_bottom - y_top)
# compute the area of both AABBs
bb1_area = w1 * h1
bb2_area = w2 * h2
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
assert iou >= 0.0
assert iou <= 1.0
return iou |
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.
Each attribute value is encoded in utf-8, and must be
decoded into python-default unicode.
Example usage::
result_type, result_data = <boundldapclient>.result(msgid)
assert result_type == ldap.RES_SEARCH_RESULT
return extract_results_from_ldap_data(result_data)
"""
return [{k:v[0].decode('utf-8')
for k, v in d[1].items()}
for d in data] |
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]
best_model = model
return best_model,max_score |
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 current_time: current animation local time
"""
return val1 + (val2 - val1) / (time2 - time1) * (current_time - time1) |
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], list[j]
return list |
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 in attrs)
groups.setdefault(key, []).append(obj)
return groups |
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 = feature['properties'].pop('_id', False)
_rev = feature['properties'].pop('_rev', False)
result = {
'geometry': feature['geometry'],
'properties': feature['properties']
}
if _id:
result['_id'] = _id
if _rev:
result['_rev'] = _rev
return result |
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
0 = increase next period > tolerance
2 = decrease next period > tolerance
1 = price stays within range of tolerance
"""
tol = tol + 1
increased = []
for i in range(len(close)-1):
if close[i]*tol<close[i+1]:
increased.append(1)
else:
increased.append(0)
increased.append(0)
return increased |
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
elif target < sort[mid]:
stop = mid - 1
else:
start = mid + 1
else:
if value:
return None
else:
return -1 |
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:
entries.update(updated_entry)
finally:
return entries |
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_config.setdefault("custom_css_files", {})
new_config.setdefault("custom_js_files", {})
new_config.setdefault("templates", {})
return new_config |
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 return value is dictionary containing the shift with respect to zero for each gate in the layer.
The second return value is an integer specifying the maximum shift necessary.
"""
shift = dict(zip(range(N), [0 for _ in range(N)]))
for gw in gate_wires:
if len(gw) == 2:
max_shift_gw = max([shift[gw[0]], shift[gw[1]]])
shift[gw[0]], shift[gw[1]] = (max_shift_gw, max_shift_gw)
mingw, maxgw = (min(gw), max(gw))
if maxgw - mingw > 1:
for w in range(mingw + 1, maxgw):
if shift[w] == max_shift_gw:
shift[w] += 1
if len(gw) > 2:
raise NotImplementedError('Drawing circuits is not implemented for gates working on more than 2 qubits.')
return shift, max(shift.values()) |
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 to the begining of string
Returns
-------
bool
True if string starts with incomplete, False otherwise
"""
return string.startswith(incomplete) |
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:
result[char] = 1
else:
result[char] += 1
return 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 of dashes / pipes : {} / {}'.format(nb_of_dashes, nb_of_pipes))
if nb_of_pipes > 2 and nb_of_dashes > 2:
is_table = True
return is_table |
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(value)) |
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) for i in obj]
# This works by virtue of the fact that tianqiaiObjects _are_ dicts. The dict
# comprehension returns a regular dict and recursively applies the
# conversion to each value.
elif isinstance(obj, dict):
return {k: convert_to_dict(v) for k, v in obj.items()}
else:
return obj |
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 == "}":
index = loc_list[row].index(elem)
p_list.append(loc_list[row][0:index + 1])
p_list.append(loc_list[row][index + 2:len(loc_list[row])])
f_list.append(p_list)
list2 = [x for x in f_list if x != []]
return list2 |
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.
:param precision: Int. Precision of computing.
:return: Float. Money you gain after paying the annual mining expense.
"""
return round(daily_mining_profit * 365, precision) |
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 (x, y).
"""
x_diff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
y_diff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(x_diff, y_diff)
if div == 0:
raise RuntimeError("The lines do not intersect.")
d = (det(*line1), det(*line2))
x = det(d, x_diff) / div
y = det(d, y_diff) / div
return x, y |
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:\n{}'.format(LHBlistStr)
return True
if len(LHBlistStr) < 1:
text = '[info:print_LHBlist] user.Lhashblock:\n{}'.format(LHBlistStr)
print(text)
else:
hblist = LHBlistStr.split(',')
text = '[info:print_LHBlist] user.Lhashblock:'
print(text)
for i in hblist:
print(i)
return True |
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
if limits[2] < y < limits[3]:
# print 'y in square'
inside_y = True
# print inside_x and inside_y
return inside_x and inside_y |
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 content:
content_response: dict = {
"name": "Tech",
"shortname": "tech",
"sort_name": "Tech",
}
return {**response, **content_response}
return response |
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):
if isinstance(value, list):
value = [_make_plus_helper(item, fields[key])
for item in value]
# assign the value (modified potentially) to the new_obj
new_obj[key] = value
else:
# values not in the fields dict get a +
new_obj['+%s' % key] = value
return new_obj |
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
decimal places are required to represent the number
they will be omitted regardless of this argument.
:returns: The formatted number (a string).
This function is intended to make it easier to recognize the order of size
of the number being formatted.
Here's an example:
>>> from humanfriendly import format_number
>>> print(format_number(6000000))
6,000,000
> print(format_number(6000000000.42))
6,000,000,000.42
> print(format_number(6000000000.42, num_decimals=0))
6,000,000,000
"""
integer_part, _, decimal_part = str(float(number)).partition('.')
negative_sign = integer_part.startswith('-')
reversed_digits = ''.join(reversed(integer_part.lstrip('-')))
parts = []
while reversed_digits:
parts.append(reversed_digits[:3])
reversed_digits = reversed_digits[3:]
formatted_number = ''.join(reversed(','.join(parts)))
decimals_to_add = decimal_part[:num_decimals].rstrip('0')
if decimals_to_add:
formatted_number += '.' + decimals_to_add
if negative_sign:
formatted_number = '-' + formatted_number
return formatted_number |
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 = {}
lines = body.split('\r\n')
request_line = lines[0].split()
split_headers = [[':method', request_line[0]],
[':path', request_line[1]]]
for header in lines[1:-2]:
removed_delimeter = header.split(':')
key, value = removed_delimeter[0], ':'.join(removed_delimeter[1:])
if key.lower() == 'host':
split_headers.append([':authority', value.strip()])
else:
split_headers.append([key.lower(), value.strip()])
for key, value in split_headers:
request_headers[key] = value
return request_headers |
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 lattice
spin -- spin-type: up or down
Returns:
Number of qubit in ordered encoding
"""
return 2 * nh * row + 2 * col + spin |
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 which lifetime_cycles is defined
(0 <= DoD <= 1)
Returns
=======
battery_lifetime in energy terms - units: kWh"""
lifetime = lifetime_cycles * total_energy_stored * depth_of_discharge
return lifetime |
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
-------
"""
flowcell_name = user_run_name
if "flow_cell_id" in description_dict and "sample_id" in description_dict:
flowcell_name = "{}_{}".format(
description_dict["flow_cell_id"], description_dict["sample_id"]
)
elif "flow_cell_id" in description_dict and "sampleid" in description_dict:
flowcell_name = "{}_{}".format(
description_dict["flow_cell_id"], description_dict["sampleid"]
)
return flowcell_name |
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):
if pi == j:
return i
raise ValueError("inverse_permutation({}, {}) failed.".format(permutation, j)) |
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_MODULE_NAME"].replace("_", " ").split()
]
) |
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', 'b', '(c,d)', 'e']
>>> s = '(a,(b,c))'
>>> l = parse_string_as_list(s)
>>> len(l)
2
>>> l[0] == 'a'
True
>>> l[1] == '(b,c)'
True
>>> ###### NOT STARTING/ENDING WITH PARENTHESES #######
>>> s = '(a,b,'
>>> l = parse_string_as_list(s)
Traceback (most recent call last):
ValueError: Input string must start with '(' and end with ')'.
>>> ################ UNMATCHED PARENTHESES ##############
>>> s = '(a,(b)'
>>> l = parse_string_as_list(s)
Traceback (most recent call last):
ValueError: Unmatched parentheses in input string
"""
if string[0]!='(' or string[-1]!=')':
raise ValueError ("Input string must start with '(' and end with ')'.")
sub_open = string.find('(',1)
sub_close = string.rfind(')',0,-1)
if not (sub_open>=0)==(sub_close>=0):
raise ValueError ("Unmatched parentheses in input string")
# Prevent empty string to pollute s.split()
my_split = lambda str : [s for s in str.split(',') if s.strip() != '']
if sub_open>=0:
l = []
l.extend(my_split(string[1:sub_open-1]))
l.append(string[sub_open:sub_close+1])
l.extend(my_split(string[sub_close+2:-1]))
else:
l = my_split(string[1:-1])
return l |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.