content stringlengths 42 6.51k |
|---|
def csim_to_scamp5(program, doubleShifts=False):
"""
Takes a CSIM program as a list of instructions (strings),
and maps it to a SCAMP5 program.
program: list of instructions, ['instr1', 'instr2', '// comment', ...]. Should
be the exact output of AUKE (we here rely on its specific syntax, such as
whitesp... |
def chunkify(lst, n):
"""
e.g.
lst = range(13) & n = 3
return = [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
"""
return [lst[i::n] for i in range(n)] |
def sign_bit(p1):
"""Return the signedness of a point p1"""
return p1[1] % 2 if p1 else 0 |
def sort_by_visibility(objs: list) -> list:
"""
Sort a list of object by their visibility value (decreasing).
"""
s = True
while s:
s = False
for i in range(len(objs) - 1, 0, -1):
if objs[i].get_visibility_value() > objs[i - 1].get_visibility_value():
# S... |
def wsgi_to_bytes(s):
"""Convert a native string to a WSGI / HTTP compatible byte string."""
# Taken from PEP3333
return s.encode("iso-8859-1") |
def AND(a, b):
"""
Returns a single character '0' or '1'
representing the logical AND of bit a and bit b (which are each '0' or '1')
>>> AND('0', '0')
'0'
>>> AND('0', '1')
'0'
>>> AND('1', '0')
'0'
>>> AND('1', '1')
'1'
"""
if a == '1' and b == '1':
... |
def compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1... |
def launchconfig_dialogs(context, request, launch_config=None, in_use=False, landingpage=False, delete_form=None):
""" Modal dialogs for Launch configurations landing and detail page."""
return dict(
launch_config=launch_config,
in_use=in_use,
landingpage=landingpage,
delete_form... |
def get_item(dictionary, key):
"""Accepts a dictionary and key and returns the contents. Used for
referencing dictionary keys with variables.
"""
# Use `get` to return `None` if not found
return dictionary.get(key) |
def karatsuba(x, y, base=10):
""" Function to multiply 2 numbers in a more efficient manner than the grade school algorithm."""
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
n = max(len(str(x)),len(str(y)))
# that's suboptimal, and ugly, but it's quick to write
n... |
def arn_has_slash(arn):
"""Given an ARN, determine if the ARN has a stash in it. Just useful for the hacky methods for
parsing ARN namespaces. See
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing."""
if arn.count('/') > 0:
return True
... |
def grow_slice(slc, size):
"""
Grow a slice object by 1 in each direction without overreaching the list.
Parameters
----------
slc: slice
slice object to grow
size: int
list length
Returns
-------
slc: slice
extended slice
"""
return slice(max(0, s... |
def get_team_list_from_match(match_data):
"""Extracts list of teams that played in the match with data given in match_data."""
teams = []
for alliance in ['red', 'blue']:
for team in match_data['alliances'][alliance]['team_keys']:
teams.append(int(team[3:]))
return teams |
def calculate_rtu_inter_char(baudrate):
"""calculates the interchar delay from the baudrate"""
if baudrate <= 19200:
return 11.0 / baudrate
else:
return 0.0005 |
def f1_score(cm):
"""
F1 score is the harmonic mean of precision and sensitivity
F1 = 2 TP / (2 TP + FP + FN)
"""
return 2 * cm[1][1] / float(2 * cm[1][1] + cm[0][1] + cm[1][0]) |
def ConvertToRadian(degree):
"""
Converts degree to radian
input: angle in degree
output: angle in radian
"""
degree = float(degree)
pi = 22 / 7
radian = float(degree * (pi / 180))
return radian |
def get_vector10():
"""
Return the vector with ID 10.
"""
return [
0.4418200,
0.5000000,
0.3163389,
] |
def node2geoff(node_name, properties, encoder):
"""converts a NetworkX node into a Geoff string.
Parameters
----------
node_name : str or int
the ID of a NetworkX node
properties : dict
a dictionary of node attributes
encoder : json.JSONEncoder
an instance of a JSON enco... |
def calc_bsa(volume, bsainitial, samples):
"""calculate BSA"""
bsa = (volume / bsainitial) * samples
return bsa |
def unified_diff(a: str, b: str, a_name: str, b_name: str) -> str:
"""
Return a unified diff string between strings `a` and `b`.
:param a: The first string (e.g. before).
:param b: The second string (e.g. after).
:param a_name: The "filename" to display for the `a` string.
:param b_name: The "f... |
def is_singleline_comment_end(code, idx=0):
"""Position in string ends a one-line comment."""
return idx >= 0 and idx+1 < len(code) and code[idx+1] == '\n' |
def _is_valid_pdf(file_path):
"""
**Checks if given file is .pdf file.** Internal function.
"""
if file_path.endswith(".pdf"):
return True
else:
return False |
def isSizeZeroEdge(edge_location_pair):
"""
vertex1 = edge.getFirstVertex()
vertex2 = edge.getSecondVertex()
location1 = vertex1.getLocation()
location2 = vertex2.getLocation()
return location1 == location2
"""
location1 = edge_location_pair[0]
location2 = edge_location_pair... |
def get_article(word):
"""determine article based on
first letter of word
"""
article = ''
if word[0].lower() in 'aeiou':
article = 'an'
else:
article = 'a'
return article |
def _evaluate_matcher(matcher_function, *args):
"""
Evaluate the result of a given matcher as a boolean with an assertion error message if any.
It handles two types of matcher :
- a matcher returning a boolean value.
- a matcher that only makes an assert, returning None or raises an assertion error.... |
def radboud_colon_concepts2labels(report_concepts):
"""
Convert the concepts extracted from reports to the set of pre-defined labels used for classification
Params:
report_concepts (dict(list)): the dict containing for each report the extracted concepts
Returns: a dict containing for each report the set... |
def remap_nested_keys(root, key_transform):
"""This remap ("recursive map") function is used to traverse and
transform the dictionary keys of arbitrarily nested structures.
List comprehensions do not recurse, making it tedious to apply
transforms to all keys in a tree-like structure.
A common issue... |
def is_unique_bis(x):
"""Do exactly what is_unique() does.
Args:
x ([list]): The list you want to test
Returns:
[bool]: True if every element in the list occurs only once
"""
return len(set(x)) == len(x) |
def file_time(filename):
"""
Gives the date of the creation of the file, if exists.
:param str filename: name of the file
:returns: if the file exists, the date of the filename as per os.path.getmtime.
Otherwise it returns 0
"""
import os
if os.path.isfile(filename):
return os.... |
def string_clean(s):
"""
Function will return the cleaned string
"""
cleaned_string = ""
clean_from = "0123456789"
for i in s:
if i not in clean_from:
cleaned_string += i
return cleaned_string |
def speed(params):
"""
Example of using all_wheels_on_track and speed
"""
# Read input variables
all_wheels_on_track = params['all_wheels_on_track']
speed = params['speed']
# Set the speed threshold based your action space
SPEED_THRESHOLD = 1.0
if not all_wheels_on_track:
... |
def namehack(field):
"""
This function is the meat of a hack to handle an issue where trying to
filter by attribute or view led to a very strange-seeming error. The issue
is that attribute names in records with attributes and view names in DNS
records are represented using SlugRelatedFields so they ... |
def process_features(features):
""" Use to implement custom feature engineering logic, e.g. polynomial expansion, etc.
Default behaviour is to return the original feature tensors dictionary as-is.
Args:
features: {string:tensors} - dictionary of feature tensors
Returns:
{string:tensors... |
def future_value(interest, period, cash):
"""(float, int, int_or_float) => float
Return the future value obtained from an amount of cash
growing with a fix interest over a period of time.
>>> future_value(0.5,1,1)
1.5
>>> future_value(0.1,10,100)
259.37424601
"""
if not 0 <= interest... |
def FormForSave(tpl):
"""Form each elemnt to be saved.
Keyword arguments:
--tpl each elment of an RDD
"""
p= []
for ((tx ,lam),index) in tpl:
p.append((tx,lam))
return p |
def readableSize(byteSize: int, floating: int = 2, binary: bool = True) -> str:
"""Convert bytes to human-readable string (like `-h` option in POSIX).
Args:
size (int): Total bytes.
floating (int, optional): Floating point length. Defaults to 2.
binary (bool, optional): Format as XB or ... |
def get_change_dict(position, previous):
"""Return a dictionary that describes the change since last week using Ben Major's API format.
One change from Ben Major's format is that new entries will show as an "up" change and the actual and amount
parts will be computed as if the single or album was at #41 th... |
def humanise(number):
"""Converts bytes to human-readable string."""
if number/2**10 < 1:
return "{}".format(number)
elif number/2**20 < 1:
return "{} KiB".format(round(number/2**10, 2))
elif number/2**30 < 1:
return "{} MiB".format(round(number/2**20, 2))
elif number/2**40 <... |
def count_most(lines, bit_idx):
"""input desire lines, bit index and output the most common bit"""
count_bit = 0
for line in lines:
if line[bit_idx] == 1:
count_bit += 1
else:
count_bit -= 1
most_bit = 1 if count_bit >= 0 else 0
return most_bit |
def excludeListFromList(_list=[], _remove=[]):
"""
Builds a new list without items passed through as _remove.
"""
_remove = set(_remove)
return [i for i in _list if i not in _remove] |
def make_position_string(length):
"""
Takes the length of the state and returns a string 01234... to be
displayed in the interaction to make it easier for the user to pick
the position of the pair to be moved.
make_position_string(int) -> string
"""
string = ""
for i in range(0,leng... |
def exchangeDqsystem():
"""Add docstring."""
ar = dict()
ar["@type"] = "DQSystem"
ar["@id"] = "d13b2bc4-5e84-4cc8-a6be-9101ebb252ff"
ar["name"] = "US EPA - Flow Pedigree Matrix"
return ar |
def half_adder(a, b):
"""
A binary half adder -- performing addition only using logic operators,
A half adder simply adds two bits and outputs a sum and carry
"""
# ^ is logical xor in python
sum = a ^ b
carry = a and b
return carry, sum |
def sort_stories_by_votes(hnlist):
"""Sort stories by total number of votes."""
print(f'Today\'s Top {len(hnlist)} Articles:\n')
return sorted(hnlist, key=lambda k: k['votes'], reverse=True) |
def _is_int_in_range(value, start, end):
"""Try to convert value to int and check if it lies within
range 'start' to 'end'.
:param value: value to verify
:param start: start number of range
:param end: end number of range
:returns: bool
"""
try:
val = int(value)
except (Valu... |
def merge(a, b):
"""
Helper function that sorts each of the smaller arrays from merge_sort.
Help from:
https://codereview.stackexchange.com/questions/154135/recursive-merge-sort-in-python.
"""
merged = []
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
m... |
def maximum(str1: str, str2: str) -> int:
"""Return the maximum common lengths of two strings."""
return len(set(str1) & set(str2)) |
def euler_with_recount(xs, h, y0, f, **derivatives):
"""Euler with recount"""
ys = [y0]
for k in range(len(xs) - 1):
subsidiary_y = ys[k] + f(xs[k], ys[k]) * h
next_y = ys[k] + (f(xs[k], ys[k]) + f(xs[k], subsidiary_y)) * h / 2
ys.append(next_y)
return ys |
def fix_ical_datetime_format(dt_str):
"""
ICAL generation gives timezones in the format of 2018-06-30T14:00:00-04:00.
The Timezone offset -04:00 has a character not recognized by the timezone offset
code (%z). The being the colon in -04:00. We need it to instead be -0400
"""
if dt_str and ":" ... |
def did_win(f_guess, f_correct_answer):
"""
Function to check player guess against the correct answer
Params:
f_guess: int or str
f_correct_answer: int
Returns:
str
"""
try:
f_guess = int(f_guess)
if f_guess > f_correct_answer:
return 'HINT: ... |
def temp_from_ppm(delta):
"""
Calculates temperature from given chemical shift
>>> from watertemp import temp_from_ppm
>>> temp_from_ppm(4.7)
32.0
>>> temp_from_ppm(5.5)
-40.0
"""
return 455 - (90 * delta) |
def stringify_keys(d):
"""Recursively convert a dict's keys to strings."""
if not isinstance(d, dict): return d
def decode(k):
if isinstance(k, str): return k
try:
return k.decode("utf-8")
except Exception:
return repr(k)
return { decode(k): stringify_ke... |
def _select_compcor(compcor_cols, n_compcor):
"""Retain a specified number of compcor components."""
# only select if not "auto", or less components are requested than there actually is
if (n_compcor != "auto") and (n_compcor < len(compcor_cols)):
compcor_cols = compcor_cols[0:n_compcor]
return ... |
def float_or_none(item):
"""
Tries to convert ``item`` to :py:func:`float`. If it is not possible,
returns ``None``.
:param object item: Element to convert into :py:func:`float`.
>>> float_or_none(1)
... 1.0
>>> float_or_none("1")
... 1.0
>>> float_or_none("smth")
... None
... |
def _cgi_post(environ, content_type):
"""
Test if there is POST form data to handle.
"""
return (environ['REQUEST_METHOD'].upper() == 'POST'
and (
content_type.startswith('application/x-www-form-urlencoded')
or content_type.startswith('multipart/form-data'))) |
def get_sentence_relations(annotations, entities):
"""Get relations from annotation dictonary and combine it with information from the corresponding entities
Args:
annotations (dictionary): annotation dictionary (result of calling annotation_to_dict)
entities (dictionary): entity annotation (re... |
def _ensure_str(s):
"""convert bytestrings and numpy strings to python strings"""
return s.decode() if isinstance(s, bytes) else str(s) |
def uncamel(name):
"""converts camelcase to underscore
>>> uncamel('fooBar')
'foo_bar'
>>> uncamel('FooBar')
'foo_bar'
>>> uncamel('_fooBar')
'_foo_bar'
>>> uncamel('_FooBar')
'__foo_bar'
"""
response, name = name[0].lower(), name[1:]
for n in name:
if n.isupper()... |
def extractWordInString(strToParse, index):
""" Exract word (space separated ) at current index"""
i = index
while i!=0 and strToParse[i-1] not in " \t\n&|":
i = i-1
leftPart = strToParse[i:index]
i = index
while i!=len(strToParse) and strToParse[i] not in " \t\n&|":
i = i+1
... |
def from_camel(string: str) -> str:
"""Converting a CamelCase string to non_camel_case"""
assert isinstance(string, str), 'string must be a type of `str`'
out = ''
for i, c in enumerate(string):
addition = c.lower()
if c.isupper():
if i != 0:
addition = '_' + ... |
def remove_dups(extracted_image_data):
"""
So now that we spam and get loads and loads of stuff in our lists, we need
to intelligently get rid of some of it.
@param: extracted_image_data ([(string, string, list, list),
(string, string, list, list),...]): the full list of images, captions,
... |
def sub(x1, x2):
"""Element-wise subtraction of 2 vectors where the second vector is
subtracted from the first. Return `x1 - x2`.
Args:
x1 (list): First vector. 1 or 2 dimensional.
x2 (list): Second vector. Same dimenions as `x1`.
Returns:
list: A element-wise subtracted list. ... |
def discard_sessions_by_scene(sessions, scene):
"""discard certain scenes, e.g., sleeping, which would then be treated as
absence.
Args:
sessions: list of tuples
scene: str
Returns: filtered sessions as list of tuples
"""
return [
session for session in sessions if not... |
def read_stars(st):
"""Reads stars from current line and returns the rest of line."""
star_num = 0
rest = st
while rest.startswith('*'):
star_num += 1
rest = rest[1:]
return (star_num, rest.strip()) |
def main():
"""Main test."""
print("Hello, world!")
return 0 |
def add_two(one, two, **kwargs):
"""
Functions for iterative operations to
accelerate the construction of graphs
:param one: array or graph
:param two: array or graph
:returns: added object
"""
if one is None:
return two
return one + two |
def _get_resource_name(user_id, name):
"""
Get resource name by resource type.
:param str user_id: PipelineAI 8 character user id that uniquely
identifies the user that created the resource
for super users this user_id is not
... |
def phi_square_calc(chi_square, POP):
"""
Calculate Phi-squared.
:param chi_square: chi squared
:type chi_square: float
:param POP: population or total number of samples
:type POP: int
:return: phi_squared as float
"""
try:
return chi_square / POP
except Exception:
... |
def _create_error(property_name, title, description):
"""
"""
return {"errors":
[
{
"property": property_name,
"descriptions":
[
{
"title": title,
... |
def ABS(n):
"""Returns absolute value of a number."""
return n if n >= 0 else n * -1 |
def encode_color(rgb):
"""rgb to 8-color pallete"""
r = "1" if rgb[0] > 127 else "0"
g = "1" if rgb[1] > 127 else "0"
b = "1" if rgb[2] > 127 else "0"
for i in range(8):
if r + g + b == format(i, '03b'):
return i |
def calcTopReward(top_action, gold_labels):
"""
Intermediate top reward.
"""
lenth = len(top_action)
r = [0. for i in range(lenth)]
rem = [0 for i in range(len(gold_labels))]
for i in range(lenth)[::-1]:
if top_action[i] > 0:
ok = -1
for j, label in enumerate(... |
def initialize_hyper_parameters(layer_acts, learning_rate):
"""
Initialize parameters for different levels of the network
Arguments:
layer_acts -- python array (list) containing the activation functions of each layer in the network
learning_rate -- float value used as constant for gradient descent
... |
def intToID(idnum, prefix):
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
rid = chr((idnum % 26) + ord('a')) + rid
idnum = int(idnum / 26)
... |
def birch_murnaghan(V,E0,V0,B0,B01):
"""
Return the energy for given volume (V - it can be a vector) according to
the Birch Murnaghan function with parameters E0,V0,B0,B01.
"""
r = (V0/V)**(2./3.)
return (E0 +
9./16. * B0 * V0 * (
(r-1.)**3 * B01 +
(r-1.)**2 ... |
def finalize_variable_expression(result: str) -> str:
"""Return empty strings for undefined template variables."""
if result is None:
return ''
else:
return result |
def frustrator_function(choice_subject, choice_computer):
"""
Lets the computer always choose the opposite of the user
Parameters
----------
choice_subject : str
stores the decision of the subject between heads and tails of the
current round.
choice_computer : str
stores... |
def CommandCompleterCd(console, unused_core_completer):
"""Command completer function for cd.
Args:
console: IPython shell object (instance of InteractiveShellEmbed).
"""
return_list = []
namespace = getattr(console, u'user_ns', {})
magic_class = namespace.get(u'PregMagics', None)
if not magic_clas... |
def Gini_impurity(splitted_sample=[]):
"""
For example: [194, 106]
note: summation( p_j * (1 - p_j) ) = 1 - summation( p_j^2 )
"""
denominator = sum(splitted_sample)
if denominator == 0:
return 0
Gini_index = 0
for numerator_i in range(len(splitted_sample)):
p_i = splitte... |
def get_list_representation(cflow_output):
"""Return a list object representation of the output from cflow
Example:
If cflow_output is:
main() <int () at main.c:18>:
f() <int () at main.c:4>:
malloc()
printf()
Then this function will return:
['main() <int () at ... |
def max_profit_optimized(prices):
"""
input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int
"""
cur_max, max_so_far = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i-1])
max_so_far = max(max_so_far,... |
def true_s2l(value: float) -> float:
"""Convert SRGB gamma corrected component to linear"""
if value <= 0.04045:
return value / 12.92
return ((value + 0.055) / 1.055) ** 2.4 |
def hex_to_rgb(value):
"""
converts a hex value to an rbg tuple.
>>>hex_to_rgb('#FFFFFF')
(255, 255, 255)
"""
value = value.lstrip('#')
return tuple(int(value[i:i+2], 16) for i in range(0, 6, 2)) |
def _format_exception(exception):
"""Formats the exception into a string."""
exception_type = type(exception).__name__
exception_message = str(exception)
if exception_message:
return "{}: {}".format(exception_type, exception_message)
else:
return exception_type |
def is_url(name: str) -> bool:
"""
Return true if name represents a URL
:param name:
:return:
"""
return '://' in name |
def or_sum (phrase):
"""Returns TRUE iff one element in <phrase> is TRUE"""
total = set()
for x in phrase:
total = total.union(x)
return total |
def predict_classify_details(img_path, ground_true, predict_code, conf):
"""
{
"img_path": "img_full_path" ,
"ground_true": "code1" # ,
"predict_code": "code2",
"conf": 0.8 # 0-1 float ,
}
:return:
"""
data_list = []
data = {}
data['ground_true'] = ground_true
data['predict_cod... |
def need_to_rotate_log(min_size, max_size, max_time_interval, log_size, time_interval):
"""Check if log match criteria for rotation"""
return log_size >= max_size or (time_interval == max_time_interval and log_size >= min_size) |
def get_prefix(text: str, prefix: str):
"""
If a string starts with prefix, return prefix and the text minus the first instance of prefix;
otherwise return None and the text.
"""
if text.startswith(prefix):
return prefix, text[len(prefix):].lstrip()
return None, text |
def round_to_005(x):
"""
rounds to nearest 0.005 and makes it pretty (avoids floating point 0.000001 nonsense)
"""
res = round(x * 200) / 200
return float('%.3f'%res) |
def job_id(config: dict) -> str:
"""The ID for the current job"""
return config["job_id"] |
def write_stress_type(key, options, value, spaces=''):
"""
writes:
- STRESS(SORT1) = ALL
- GROUNDCHECK(PRINT,SET=(G,N,N+AUTOSPC,F,A),THRESH=1e-2,DATAREC=NO) = YES
"""
msg = ''
str_options = ','.join(options)
#print("str_options = %r" % (str_options))
#print("STRESS-type key=%s valu... |
def maxBit(int_val):
"""Return power of 2 for highest bit set for integer"""
length = 0
count = 0
while (int_val):
count += (int_val & 1)
length += 1
int_val >>= 1
return length - 1 |
def _to_url(host, port, cmd):
"""Convert a host, port and command to a url."""
return "http://{:s}:{:d}/{:s}".format(host, port, cmd) |
def invert_dict(input_dict: dict, sort_keys: bool = False) -> dict:
"""Create a new dictionary swapping keys and values.
Invert a given dictionary, creating a new dictionary where each key is
created from a value of the original dictionary, and its value is the
key that it was associated to in the orig... |
def format_custom_attr(ddic):
"""
Format a dictionary of dictionaries in string format in the "custom attribute" syntax
e.g. custom="readingOrder {index:1;} structure {type:heading;}"
"""
s = ""
for k1, d2 in ddic.items():
if s:
s += " "
s += "%s" % k1
s2 = ""... |
def lossy_compresion(text: str, token_separator=" ") -> str:
"""Here we just remove every consecutive duplicate tokens, so we only track changes
e.g text ABC ABC ABC EE A S X X SD will be compressed to:
ABC EE A S X SD.
Args:
text (str): text to be compressed
Returns:
... |
def check_two_shapes_need_broadcast(shape_x, shape_y):
"""Check shape_y needs to be broadcast to shape_x."""
if any(j not in (i, 1) for i, j in zip(reversed(shape_x), reversed(shape_y))):
raise ValueError(f"{shape_y} could not broadcast with {shape_x}.")
return shape_y != shape_x |
def get_curve_shape_name(name=""):
"""
return the name of the curves.
:param name: <str> base name.
:return: <str> curve shape name.
"""
return '{}Shape'.format(name) |
def augmentToBeUnique(listOfItems):
""" Given a list that may include duplicates, return a list of unique items
Returns a list of [(x,index)] for each 'x' in listOfItems,
where index is the number of times we've seen 'x' before.
"""
counts = {}
output = []
if listOfItems is None:
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.