content
stringlengths 42
6.51k
|
---|
def fade(begin, end, factor):
""" return value within begin and end at < factor > (0.0..1.0)
"""
# check if we got a bunch of values to morph
if type(begin) in [list, tuple]:
result = []
# call fade() for every of these values
for i in range(len(begin)):
result.append(fade(begin[i], end[i], factor))
else:
# return the resulting float
result = begin + (end - begin) * factor
return result
|
def abs_val(num):
"""
Find the absolute value of a number.
>>abs_val(-5)
5
>>abs_val(0)
0
"""
if num < 0:
return -num
# Returns if number is not < 0
return num
|
def _clip_count(cand_d, ref_ds):
"""Count the clip count for each ngram considering all references"""
count = 0
for m in cand_d.keys():
m_w = cand_d[m]
m_max = 0
for ref in ref_ds:
if m in ref:
m_max = max(m_max, ref[m])
m_w = min(m_w, m_max)
count += m_w
return count
|
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() == "true": return True
if str(value).lower() == "false": return False
raise Exception('Invalid value for boolean conversion: ' + str(value))
|
def get_int_with_default(val, default):
"""Atempts to comvert input to an int. Returns default if input is None or unable to convert to
an int.
"""
if val is None:
return default
try:
return int(val)
except ValueError:
pass
return default
|
def cnr(mean_gm, mean_wm, std_bg):
"""Calculate Contrast-to-Noise Ratio (CNR) of an image.
- CNR = |(mean GM intensity) - (mean WM intensity)| /
(std of background intensities)
:type mean_gm: float
:param mean_gm: The mean value of the gray matter voxels.
:type mean_wm: float
:param mean_wm: The mean value of the whiet matter voxels.
:type std_bg: float
:param std_bg: The standard deviation of the voxel intensities of the
background (outside the head) voxels.
:rtype: float
:return: The contrast-to-noise (CNR) ratio.
"""
import numpy as np
cnr_val = np.abs(mean_gm - mean_wm)/std_bg
return cnr_val
|
def get_object_map(id_offset: int) -> dict:
"""
Returns ID to communication object mapping of a given CAN node ID.
Map taken from https://en.wikipedia.org/wiki/CANopen#Predefined_Connection_Set[7]
"""
return {
0x000 : "NMT_CONTROL",
0x001 : "FAILSAFE",
0x080 : "SYNC",
0x080 + id_offset : "EMERGENCY",
0x100 : "TIMESTAMP",
0x180 + id_offset : "TPDO1",
0x200 + id_offset : "RPDO1",
0x280 + id_offset : "TPDO2",
0x300 + id_offset : "RPDO2",
0x380 + id_offset : "TPDO3",
0x400 + id_offset : "RPDO3",
0x480 + id_offset : "TPDO4",
0x500 + id_offset : "RPDO4",
0x580 + id_offset : "TSDO",
0x600 + id_offset : "RSDO",
0x700 + id_offset : "NMT_MONITORING",
0x7E4 : "TLSS",
0x7E5 : "RLSS"
}
|
def make_negative(number):
"""Return the negative of the absolute value of number."""
return abs(number) * -1
|
def get_filings_query(api_key):
"""
keys = ["total_disbursements", "committee_id", "candidate_id"]
"""
return "https://api.open.fec.gov/v1/filings/?sort_nulls_last=false&sort=-receipt_date&sort_hide_null=false&per_page=20&page=1&api_key={api_key}&sort_null_only=false".format(
api_key=api_key
)
|
def calc(number: int) -> int:
"""Makes the number a multiple of 80 (fix incorrect matrix multiplication in Transform class)"""
return (number // 80 + 1) * 80 if number % 80 > 40 else number // 80 * 80
|
def valid_password(password):
"""
The password must be at least nine characters long. Also, it must include characters from
two of the three following categories:
-alphabetical
-numerical
-punctuation/other
"""
punctuation = set("""!@#$%^&*()_+|~-=\`{}[]:";'<>?,./""")
alpha = False
num = False
punct = False
if len(password) < 9:
return False
for character in password:
if character.isalpha():
alpha = True
if character.isdigit():
num = True
if character in punctuation:
punct = True
return (alpha + num + punct) >= 2
|
def healthcheck_timeout_calculate(data):
"""Calculate a BIG-IP Health Monitor timeout.
Args:
data: BIG-IP config dict
"""
# Calculate timeout
# See the f5 monitor docs for explanation of settings:
# https://goo.gl/JJWUIg
# Formula to match up the cloud settings with f5 settings:
# (( maxConsecutiveFailures - 1) * intervalSeconds )
# + timeoutSeconds + 1
timeout = (
((data['maxConsecutiveFailures'] - 1) * data['intervalSeconds']) +
data['timeoutSeconds'] + 1
)
return timeout
|
def gcd(a,b):
"""Find GCD"""
if(b==0):
return a
else:
return gcd(b,a%b)
|
def itemize(*items):
"""Restructured text formatted itemized list
>>> print itemize('alpha', 'beta')
* alpha
* beta
"""
return '\n'.join(['* ' + item for item in items])
|
def pentagonal(n):
"""Return nth pentagonal number e.g. 1, 5, 12, 22, 35, ..."""
return n*(3*n - 1)/2
|
def readLinesFromFile(filename):
"""
Returns the read file as a list of strings.
Each element of the list represents a line.
On error it returns None.
"""
try:
with open(filename, "r") as input_file:
lines = input_file.readlines()
return lines
except EnvironmentError:
return None
|
def add_latex_line_endings(lines):
"""Add latex newline character to each line"""
return [line + r" \\" for line in lines]
|
def invalid_sn_vsby(i, v):
"""Checks if visibility is inconsistent with SN or DZ
Returns 0 if consistent, -1 if too high, +1 if too low"""
if i == '+':
if v > 0.25:
return -1
else:
return 0
elif i == '':
if v > 0.5:
return -1
elif v <= 0.25:
return 1
else:
return 0
elif i == '-':
if v <= 0.5:
return 1
else:
return 0
else:
return 0
|
def is_power_of_2(x):
"""Determine if a number is a power of 2"""
return ((x != 0) and not(x & (x - 1)))
|
def is_match_coverage_less_than_threshold(license_matches, threshold):
"""
Returns True if any of the license matches in a file-region has a `match_coverage`
value below the threshold.
:param license_matches: list
List of LicenseMatch.
:param threshold: int
A `match_coverage` threshold value in between 0-100
"""
coverage_values = (
license_match.match_coverage for license_match in license_matches
)
return any(coverage_value < threshold for coverage_value in coverage_values)
|
def hra(basic):
""" hra Is 15% Of Basic Salary """
hra = basic*15/100
return hra
|
def permutate_NNlayer_combo_params(layer_nums, node_nums, dropout_list, max_final_layer_size):
"""
to generate combos of layer_sizes(str) and dropouts(str) params from the layer_nums (list), node_nums (list), dropout_list (list).
The permutation will make the NN funnel shaped, so that the next layer can only be smaller or of the same size of the current layer.
Example:
permutate_NNlayer_combo_params([2], [4,8,16], [0], 16)
returns [[16, 4], [16, 8], [8,4]] [[0,0],[0,0],[0,0]]
If there are duplicates of the same size, it will create consecutive layers of the same size.
Example:
permutate_NNlayer_combo_params([2], [4,8,8], [0], 16)
returns [[8, 8], [8, 4]] [[0,0],[0,0]]
Args:
layer_nums: specify numbers of layers.
node_nums: specify numbers of nodes per layer.
dropout_list: specify the dropouts.
max_last_layer_size: sets the max size of the last layer. It will be set to the smallest node_num if needed.
Returns:
layer_sizes, dropouts: the layer sizes and dropouts generated based on the input parameters
"""
import itertools
import numpy as np
layer_sizes = []
dropouts = []
node_nums = np.sort(np.array(node_nums))[::-1]
max_final_layer_size = int(max_final_layer_size)
# set to the smallest node_num in the provided list, if necessary.
if node_nums[-1] > max_final_layer_size:
max_final_layer_size = node_nums[-1]
for dropout in dropout_list:
_repeated_layers =[]
for layer_num in layer_nums:
for layer in itertools.combinations(node_nums, layer_num):
layer = [i for i in layer]
if (layer[-1] <= max_final_layer_size) and (layer not in _repeated_layers):
_repeated_layers.append(layer)
layer_sizes.append(layer)
dropouts.append([(dropout) for i in layer])
return layer_sizes, dropouts
|
def only_printable(string):
""" Converts to a string and removes any non-printable characters"""
string = str(string)
return "".join([s for s in string if s.isprintable()])
|
def help(command=""):
"""
Return a help manual to slack, which helps the user understand how to use a command.
@params:
input -> A specific command that the user want to look for. Default is "",
which would lead to an explanation of all command.
"""
command = command.lower()
if command == "search":
return "/jama search,keyword` search any item that has your given keyword."
elif command == "create":
return "`/jama create` create an item."
elif command == "comment":
return "By using `/jamaconnect comment` command, a dialog box would appear for for your input:\n" +\
"`Project Reference` In case you do not remember the project id, you can check it here by " +\
"typing the project name.\n" + \
"`Input Project ID` The project id of the item you want to comment on. This is not required, " +\
"but you can limit the item search result by typing the project ID. \n" +\
"`Item ID or Keyword` The item you want to comment on, You can use the item id or any keyword " +\
"to find the item you want.\n" + \
"`Comment` The content you want to comment.\n\n" + \
"If you already know the item id and want a simple fast comment method, you can use the inline " +\
"commend `/jamaconnect comment:itemId,commentBody` to comment an item.\n" +\
"`itemId` The id of the item you want to comment on.\n" +\
"`commentBody` The content you want to put into the comment."
elif command == "oauth":
return "`/jamaconnect oauth,clientID,clientSecret` provides OAuth information to jamaconnect that allows it to act on jama on your behalf.\n" +\
"A client ID and Secret can be obtained on your jama profile -> 'Set API Credentials' -> 'Create API Credentials'."
elif command == "attach file" or command == "attach" or command == "attachment":
return "By using the Slack Action `Attach file` (which can be found at the `...` sign of each Slack " +\
"massage), a dialog box would appear for for your input.\n" +\
"`Item ID` The id of the item you want to attach your file to.\n" +\
"`Description` The description of the file."
return "`/jamaconnect search,keyword` search any item that has your given keyword.\n" +\
"`/jamaconnect create` create an item.\n" +\
"`/jamaconnect comment` to comment an item.\n" +\
"`/jamaconnect oauth,clientID,clientSecret` to provide OAuth information.\n" +\
"`/jamaconnect help,command` to see the detail of a Jama's Slack command\n" +\
"Slack Action `Attach file` to attach a file from Slack to Jama"
|
def scramble(lis1, lis2):
""" Takes two lists, one as values and the other as indies. Then sorts
the value list according to the indies and returns a list. """
# This is very much like flatten() from above. Only keys and values
# are reversed.
temp_zip = zip(range(len(lis1)), lis1)
temp_dict = {k: v for (k, v) in temp_zip}
scrambled = []
for num in lis2:
scrambled.append(temp_dict.get(num))
return scrambled
|
def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
Args:
bbox (tuple): Denormalized bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
Returns:
tuple: Normalized bounding box `(x_min, y_min, x_max, y_max)`.
Raises:
ValueError: If rows or cols is less or equal zero
"""
(x_min, y_min, x_max, y_max), tail = bbox[:4], tuple(bbox[4:])
if rows <= 0:
raise ValueError("Argument rows must be positive integer")
if cols <= 0:
raise ValueError("Argument cols must be positive integer")
x_min, x_max = x_min / cols, x_max / cols
y_min, y_max = y_min / rows, y_max / rows
return (x_min, y_min, x_max, y_max) + tail
|
def unique_values(rows, idx):
"""Checking for unique values in table.
rows : [{ }, { }, ...]
idx : dict key (column name)
"""
# counting occurances of the values (value for "idx" key)
cnt = {}
for i,x in enumerate(rows):
try:
value = x[idx]
except KeyError:
msg = 'ERROR in table row {}: "{}" key not found'
print(msg.format(i, idx))
continue
try:
cnt[value] += 1
except KeyError:
cnt[value] = 1
# error if duplicates found
errors = []
for k,v in cnt.items():
if v > 1:
msg = 'ERROR: "{}" is found {} times in table'
errors.append(msg.format(k,v))
return errors
|
def return_user_filter(user_to_search: str, users_list):
"""
Looks through the inputted list and if the user to search for exists, will return the user. Otherwise, it will
return an empty dict
Args:
user_to_search: The user we are searching for
users_list: A list of user dictionaries to search through
Returns:
The dict which matched the user to search for if one was found, else an empty dict.
"""
users_filter = list(filter(lambda u: u.get('name', '').lower() == user_to_search
or u.get('profile', {}).get('display_name', '').lower() == user_to_search
or u.get('profile', {}).get('email', '').lower() == user_to_search
or u.get('profile', {}).get('real_name', '').lower() == user_to_search, users_list))
if users_filter:
return users_filter[0]
else:
return {}
|
def find_moves(board):
"""returns list of valid moves"""
moves = []
for col in range(7):
if board[0][col] == " ":
moves.append(col)
return moves
|
def is_arithmetic_series(series: list) -> bool:
"""
checking whether the input series is arithmetic series or not
>>> is_arithmetic_series([2, 4, 6])
True
>>> is_arithmetic_series([3, 6, 12, 24])
False
>>> is_arithmetic_series([1, 2, 3])
True
"""
if len(series) == 1:
return True
common_diff = series[1] - series[0]
for index in range(len(series) - 1):
if series[index + 1] - series[index] != common_diff:
return False
return True
|
def md_getLat(field):
"""Get latitude"""
return field.split(',')[1].strip()
|
def divide1(a, b):
"""Manually exam to avoid error.
"""
if b == 0:
raise ValueError("Zero division Error!")
return a * 1.0 / b
|
def b_oblate(kappa):
"""
-1 = oblate <= b_O <= 0 = prolate
Townes and Schawlow, Ch. 4
"""
return (kappa-1.)/(kappa+3.)
|
def ordinal_suffix(day):
"""Return ordinal english suffix to number of a day."""
condition = 4 <= day <= 20 or 24 <= day <= 30
return 'th' if condition else ["st", "nd", "rd"][day % 10 - 1]
|
def V1compat(t):
"""V1compat - create a V1 compatible tick record from a V20 tick."""
T = t['time']
T = T[0:len(T)-4]+"Z"
rv = dict()
if t['type'] == 'PRICE':
rv = {"tick": {"instrument": t['instrument'],
"time": T,
"bid": float(t['bids'][0]['price']),
"ask": float(t['asks'][0]['price'])}
}
else:
rv = {'heartbeat': {"time": T}}
return rv
|
def divide(arg1, arg2):
""" (float, float) -> float
Divides two numbers (arg1 / arg2)
Returns arg1 / arg2
"""
try:
return arg1 / arg2
except TypeError:
return 'Unsupported operation: {0} / {1} '.format(type(arg1), type(arg2))
except ZeroDivisionError as zero_error:
return 'Unsupported operation: {0} / {1} -> {2}'.format(arg1, arg2, zero_error)
except Exception as other_error:
return 'Oops... {0}'.format(other_error)
|
def convertType(pair:tuple):
"""Convert items to the appropriate types
Arguments:
pair: A tuple containing 2 items
Returns:
pair: A tuple containing 2 items where the second item is converted to the appropriate types
"""
#If it is not a pair
if len(pair) != 2:
#Return the pair
return pair
#Check if it is boolean
if pair[1].lower() == "true":
return pair[0],True
elif pair[1].lower() == "false":
return pair[0],False
#Check if it is numbers
elif pair[1].isdigit():
if pair[0].isdigit():
return int(pair[0]), int(pair[1])
else:
return pair[0],int(pair[1])
#Otherwise return the original pair
else:
return pair
|
def distND(pt1, pt2):
"""Returns distance between two nD points (as two n-tuples)"""
return (sum((vv2 - vv1)**2.0 for vv1, vv2 in zip(pt1, pt2)))**0.5
|
def read_input(filename):
"""
Read data from input file on form:
eg.
5 14 1 5 6 3 10
where first number is N, second is K and rest is data set.
args:
filename :: string
path to input file
returns:
out :: list of tuples.
"""
out = []
with open(filename, 'r') as f:
for l in f:
try:
d = l.split()
n = int(d[0])
K = int(d[1])
ts = [int(i) for i in d[2:]]
if len(ts) != n:
raise TypeError('N not equal to length of T')
out.append([n,K,ts])
except IndexError:
pass
return out
|
def tokenize(s):
"""
:param s: string of the abstract
:return: list of word with original positions
"""
def white_char(c):
return c.isspace() or c in [',', '?']
res = []
i = 0
while i < len(s):
while i < len(s) and white_char(s[i]): i += 1
l = i
while i < len(s) and (not white_char(s[i])): i += 1
r = i
if s[r-1] == '.': # consider . a token
res.append( (s[l:r-1], l, r-1) )
res.append( (s[r-1:r], r-1, r) )
else:
res.append((s[l:r], l, r))
return res
|
def is_numeric(input_str):
"""
Takes in a string and tests to see if it is a number.
Args:
text (str): string to test if a number
Returns:
(bool): True if a number, else False
"""
try:
float(input_str)
return True
except ValueError:
return False
|
def gr1c_to_python(ast, symtable=None):
"""Create new AST that uses Python from one having gr1c syntax.
If symtable is not None, it will be used to ensure primed
variables get unique names. Else, every primed variable is named
as the original variable with the suffix '_next'.
"""
if isinstance(ast, tuple):
if len(ast) == 2 and ast[1] == "'":
return ast[0]+'_next'
elif len(ast) == 3 and ast[0] == '<->':
return (' or ',
(' and ',
gr1c_to_python(ast[1], symtable=symtable),
gr1c_to_python(ast[2], symtable=symtable)),
(' and ',
('not ', gr1c_to_python(ast[1], symtable=symtable)),
('not ', gr1c_to_python(ast[2], symtable=symtable))))
elif len(ast) == 3 and ast[0] == '->':
return (' or ',
('not ', gr1c_to_python(ast[1], symtable=symtable)),
gr1c_to_python(ast[2], symtable=symtable))
else:
return tuple([gr1c_to_python(sub, symtable=symtable) for sub in ast])
else:
if ast == '&':
return ' and '
elif ast == '|':
return ' or '
elif ast == '!':
return 'not '
else:
return ast
|
def proportional_resize(orig_size, desired_width, aspect_ratio=2.0):
"""proportionally resize an image with a given aspect-ratio"""
w,h = orig_size
return (desired_width, int(round(desired_width / aspect_ratio / w * h)) )
|
def column_integer_to_index(idx):
"""Convert integer column index to XLS-style equivalent
Given an integer index, converts it to the XLS-style
equivalent e.g. 'A', 'BZ' etc, using a zero-based
counting system (so zero is equivalent to 'A', 1 to 'B'
etc).
"""
# Convert integer column to index equivalent
col = ''
while idx >= 0:
col += chr((idx%26)+65)
idx = idx//26-1
return col[::-1]
|
def valid_taxa(value):
"""Given a queryset of taxa, filters so only valid taxa stays"""
return [taxon for taxon in value if taxon.is_valid]
|
def Sort_Points_2(x_values, y_values):
"""
Combine three arrays and sorts by ascending values of the first.
Args:
x_values (1darray):
Array of x-values. This array is the one which sorting will be based.
Each index of this array is related to the same index value of the other.
y_values (1darray):
Array of y-values. Each index of this array is related to the same
index value of the other.
Returns:
x_val (1darray):
x_values array sorted in ascending order.
y_val (1darray):
y_values array sorted based on new index order of x_val.
"""
to_return = []
# If/Else statement to confirm that the arrays are the same length. Print error message if not.
if len(x_values) == len(y_values):
for j in range(len(x_values)):
file_point = (((x_values[j])), (y_values[j]))
to_return.append(file_point)
to_return.sort()
x_val = [x[0] for x in to_return]
y_val = [y[1] for y in to_return]
else:
print('the given arrays are of different lengths')
x_val = False
y_val = False
return(x_val, y_val)
|
def extract_QnA_Ans_Sent(tab):
"""
Preprocessing of Data
"""
input_tuple =[]
extract = []
for index, item in enumerate(tab):
src = item['question']+ " <sep> "+ item['answer']
trg = item['answer_sentence']
input_tuple = [src,trg]
extract.append(input_tuple)
return extract
|
def is_tag_restriction_pattern_valid(text):
"""
Determines if a given piece of text is considered a valid restricted tag pattern.
Valid patterns:
- Length: 0 < x <= 100 -- Prevents absurd tag lengths.
- If string contains a ``*``, must only contain one *, and be three characters or more.
Parameters:
text: A single candidate restricted tag entry.
Returns:
Boolean True if the tag is considered to be a valid pattern. Boolean False otherwise.
"""
if len(text) > 100:
return False
elif text.count("*") == 1 and len(text) > 2:
return True
elif text and "*" not in text:
return True
return False
|
def return_limit(x):
"""Returns the standardized values of the series"""
dizionario_limite = {'BENZENE': 5,
'NO2': 200,
'O3': 180,
'PM10': 50,
'PM2.5': 25}
return dizionario_limite[x]
|
def forecasted_occlusion_position(occlusion_bool_list):
""" Given a boolean list of occlusion events, return the index position of the forecasts
that indicate that an occlusion event has been predicted. """
positional_list = []
for i in range(len(occlusion_bool_list)):
if occlusion_bool_list[i] == "Yes":
positional_list.append(i)
return positional_list
|
def is_error(data):
"""check for error indication in data"""
return data[0] == 255
|
def parse_unwanted_urls(content):
"""
Parse the unwanted urls file.
This parse the raw content of the unwanted_urls file in order to get a nice
list. This file is originally a host file to prevent connection to/from
nasty websites (http://sbc.io/hosts/alternates/fakenews-gambling-porn/hosts).
:param content: The file content
:type content: str
:return: Unwanted urls list
:rtype: list
"""
content = content.replace('0.0.0.0 ', '')
content_list = content.split('\n')
content_list = [x for x in content_list if x]
content_list = [a for a in content_list if not a.startswith('#')]
return content_list
|
def check_true(expr, ex=AssertionError, msg="expr was not True"):
"""
Raises an Exception when expr evaluates to False.
:param expr: The expression
:param ex: (optional, default AssertionError) exception to raise.
:param msg: (optional) The message for the exception
:return: True otherwise
"""
if not bool(expr):
raise ex(msg)
else:
return True
|
def config_parser(*args):
"""
<config> ::= <m-confs> <symbols>
<m-confs> ::= " " | <id> | "[" <id> {<id>} "]"
<symbols> ::= [["Not"] (<id> | "[" <id> {<id>} "]")]
Empty spaces in <m-confis> means "keep the previous input m-configuration
list <m-confs>". Both "None" and "Any", as symbol <id>s, have special
meaning: a the "blank"/empty square and a non-"blank"/non-empty square,
respectively.
"""
if len(args) == 1:
return args, []
return args[:1], args[1:]
|
def startswith(text, starts):
"""Filter to check if a string starts with a specific format"""
if isinstance(text, str):
starts = starts.split(",")
for start in starts:
if text.startswith(start):
return True
return False
|
def get_messages_by_line(messages):
"""Return dictionary that maps line number to message."""
line_messages = {}
for message in messages:
line_messages[message.lineno] = message
return line_messages
|
def add_suffix(signals, suffix):
"""Adds `suffix` to every element of `signals`."""
return [s + suffix for s in signals]
|
def get_value(item, path: list):
""" Goes through the json item to get the information of the specified path """
child = item
count = 0
# Iterates over the given path
for i in path:
# If the child (step in path) exists or is equal to zero
if i in child or i == 0:
# Counts if the iteration took place over every path element
count += 1
child = child[i]
else:
return False
# If the full path is not available (missing field)
if len(path) != count:
return False
value = str(child)
# REPLACEMENTS
value = value.replace('\t', ' ') # replace \t with ' '
value = value.replace('\\', '\\\\') # adds \ before \
value = value.replace('"', '\\"') # adds \ before "
value = value.replace('\n', '') # removes new lines
return value
|
def generateGetoptsFlags(emailFlagTuples):
"""
Generates the part of the getopts argument,
which declares the flags to look for.
Uses flags in emailFlagTuples.
"""
flagsString = ''
for emailFlagTuple in emailFlagTuples:
flagsString += emailFlagTuple[1]
return flagsString
|
def bmi_to_bodytype(bmi):
"""
desc : converts bmi to a category body type based on CDC guidelines https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html
args:
bmi (float) : the users bmi
returns:
bodytype (string) : The users bodytype
"""
if bmi < 18.5:
return "Underweight"
elif 18.5 <= bmi < 24.9:
return "Normal"
elif 24.9 <= bmi < 29.9:
return "Overweight"
else:
return "Obese"
|
def strip_string_literals(code, prefix='__Pyx_L'):
"""
Normalizes every string literal to be of the form '__Pyx_Lxxx',
returning the normalized code and a mapping of labels to
string literals.
"""
new_code = []
literals = {}
counter = 0
start = q = 0
in_quote = False
hash_mark = single_q = double_q = -1
code_len = len(code)
quote_type = None
quote_len = -1
while True:
if hash_mark < q:
hash_mark = code.find('#', q)
if single_q < q:
single_q = code.find("'", q)
if double_q < q:
double_q = code.find('"', q)
q = min(single_q, double_q)
if q == -1:
q = max(single_q, double_q)
# We're done.
if q == -1 and hash_mark == -1:
new_code.append(code[start:])
break
# Try to close the quote.
elif in_quote:
if code[q-1] == u'\\':
k = 2
while q >= k and code[q-k] == u'\\':
k += 1
if k % 2 == 0:
q += 1
continue
if code[q] == quote_type and (
quote_len == 1 or (code_len > q + 2 and quote_type == code[q+1] == code[q+2])):
counter += 1
label = "%s%s_" % (prefix, counter)
literals[label] = code[start+quote_len:q]
full_quote = code[q:q+quote_len]
new_code.append(full_quote)
new_code.append(label)
new_code.append(full_quote)
q += quote_len
in_quote = False
start = q
else:
q += 1
# Process comment.
elif -1 != hash_mark and (hash_mark < q or q == -1):
new_code.append(code[start:hash_mark+1])
end = code.find('\n', hash_mark)
counter += 1
label = "%s%s_" % (prefix, counter)
if end == -1:
end_or_none = None
else:
end_or_none = end
literals[label] = code[hash_mark+1:end_or_none]
new_code.append(label)
if end == -1:
break
start = q = end
# Open the quote.
else:
if code_len >= q+3 and (code[q] == code[q+1] == code[q+2]):
quote_len = 3
else:
quote_len = 1
in_quote = True
quote_type = code[q]
new_code.append(code[start:q])
start = q
q += quote_len
return "".join(new_code), literals
|
def quarter_from_month(month: int) -> int:
"""Calculate quarter (1 indexed) from month (1 indexed).
>>> [quarter_from_month(month) for month in range(1, 13)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
"""
return ((month - 1) // 3) + 1
|
def null_distance_results(string1, string2, max_distance):
"""Determines the proper return value of an edit distance function
when one or both strings are null.
**Args**:
* string_1 (str): Base string.
* string_2 (str): The string to compare.
* max_distance (int): The maximum distance allowed.
**Returns**:
-1 if the distance is greater than the max_distance, 0 if the\
strings are equivalent (both are None), otherwise a positive number\
whose magnitude is the length of the string which is not None.
"""
if string1 is None:
if string2 is None:
return 0
else:
return len(string2) if len(string2) <= max_distance else -1
return len(string1) if len(string1) <= max_distance else -1
|
def findval(elems, key):
"""Help function for looking up values in the lmf."""
def iterfindval():
for form in elems:
att = form.get("att", "")
if att == key:
yield form.get("val")
yield ""
return next(iterfindval())
|
def format_time_to_HMS( num_seconds ):
"""
Formats 'num_seconds' in H:MM:SS format. If the argument is a string,
then it checks for a colon. If it has a colon, the string is returned
untouched. Otherwise it assumes seconds and converts to an integer before
changing to H:MM:SS format.
"""
if type(num_seconds) == type(''):
if ':' in num_seconds:
return num_seconds
secs = int(num_seconds)
nhrs = secs // 3600
secs = secs % 3600
nmin = secs // 60
nsec = secs % 60
hms = str(nhrs)+':'
if nmin < 10: hms += '0'
hms += str(nmin)+':'
if nsec < 10: hms += '0'
hms += str(nsec)
return hms
|
def added_json_serializer(obj):
"""
Default json encoder function for supporting additional object types.
Parameters
----------
obj : `iterable`
Returns
-------
result : `Any`
Raises
------
TypeError
If the given object is not json serializable.
"""
obj_type = obj.__class__
if hasattr(obj_type, '__iter__'):
return list(obj)
raise TypeError(f'Object of type {obj_type.__name__!r} is not JSON serializable.',)
|
def simplify_nested_dict(dictionary, name, separator='_'):
"""
Takes a nested dictionary and transforms it into a flat one.
:param dictionary: (dict) dictionary to transform
:return: (dict) result dictionary
"""
res = dict()
for key in dictionary:
if isinstance(dictionary[key], dict):
res.update(simplify_nested_dict(
dictionary[key],
"{}{}{}".format(name, separator, key),
separator))
else:
res['{}{}{}'.format(name, separator, key)] = dictionary[key]
return res
|
def are_strings_mappable(s1, s2):
"""
Takes in two strings and evaluates if a direct mapping relationship is possible
Returns True if possible or False otherwise
"""
if type(s1) != str or type(s2) != str:
raise TypeError("Arguments of are_strings_mappable must be a string")
if len(s1) != len(s2):
return False
tracker = {}
for i in range(0, len(s1)):
if s2[i] in tracker:
if tracker[s2[i]] != s1[i]:
return False
else:
continue
else:
tracker[s2[i]] = s1[i]
return True
|
def search_data(sequence_length, num_of_depend, label_start_idx,
num_for_predict, units, points_per_hour):
"""
Parameters
----------
sequence_length: int, length of all history data
num_of_depend: int,
label_start_idx: int, the first index of predicting target
num_for_predict: int, the number of points will be predicted for each sample
units: int, week: 7 * 24, day: 24, recent(hour): 1
points_per_hour: int, number of points per hour, depends on data
Returns
----------
list[(start_idx, end_idx)]
"""
if points_per_hour < 0:
raise ValueError("points_per_hour should be greater than 0!")
if label_start_idx + num_for_predict > sequence_length:
return None
x_idx = []
for i in range(1, num_of_depend + 1):
start_idx = label_start_idx - points_per_hour * units * i
end_idx = start_idx + num_for_predict
if start_idx >= 0:
x_idx.append((start_idx, end_idx))
else:
return None
if len(x_idx) != num_of_depend:
return None
return x_idx[::-1]
|
def taskname(*items):
"""A task name consisting of items."""
s = '_'.join('{}' for _ in items)
return s.format(*items)
|
def coerce_url(url, default_schema='http'):
"""
>>> coerce_url('https://blog.guyskk.com/feed.xml')
'https://blog.guyskk.com/feed.xml'
>>> coerce_url('blog.guyskk.com/feed.xml')
'http://blog.guyskk.com/feed.xml'
>>> coerce_url('feed://blog.guyskk.com/feed.xml')
'http://blog.guyskk.com/feed.xml'
"""
url = url.strip()
if url.startswith("feed://"):
return "{}://{}".format(default_schema, url[7:])
if "://" not in url:
return "{}://{}".format(default_schema, url)
return url
|
def tofloat(x):
"""Convert to floating point number without throwing exception"""
from numpy import nan
try: return float(x)
except: return nan
|
def check_last_chunk(sublist, full_list):
""" Identify if the current list chunk is the last chunk """
if sublist[-1] == full_list[-1]:
return True
return False
|
def t_gate_counts_nondeterministic(shots, hex_counts=True):
"""T-gate circuits reference counts."""
targets = []
if hex_counts:
# T.H
targets.append({'0x0': shots / 2, '0x1': shots / 2})
# X.T.H
targets.append({'0x0': shots / 2, '0x1': shots / 2})
# H.T.T.H = H.S.H
targets.append({'0x0': shots / 2, '0x1': shots / 2})
else:
# T.H
targets.append({'0': shots / 2, '1': shots / 2})
# X.T.H
targets.append({'0': shots / 2, '1': shots / 2})
# H.T.T.H = H.S.H
targets.append({'0': shots / 2, '1': shots / 2})
return targets
|
def merge_lists(a, b):
"""
Merge lists - e.g.,
[1, 2, 3, 4, 5, 6] & ['a', 'b', 'c']
=> [1, 'a', 2, 'b', 3, 'c', 4, 5, 6]
:param a: List a
:param b: List b
:return: Merged lists
"""
result = []
length = min([len(a), len(b)])
for i in range(length):
result.append(a[i])
result.append(b[i])
result += a[length:] + b[length:]
return result
|
def is_palindrome(n):
"""Determine whether n is palindrome."""
# Convert the given number into list.
number_original = list(map(int, str(n)))
# First, store a copy of the list of original number.
number_reversed = number_original[:]
# Then, reverse the list.
number_reversed.reverse()
return number_original == number_reversed
|
def combine_dict(dict0, dict1, update_func=lambda a, b: b):
"""Combine two dictionaries
Args:
dict0: dict
dict1: dict
update_func: the function to combine two values from the same key;
default function uses the value from dict1
Returns:
dict2: combined dict
Examples:
dict0 = {'a': [1], 'b': [2], 'c': [3]}
dict1 = {'a': [11], 'd': [4]}
combine_dict(dict0, dict1)
"""
dict2 = {k: dict0[k] for k in set(dict0).difference(dict1)} # the unique part from dict0
dict2.update({k: dict1[k] for k in set(dict1).difference(dict0)}) # the unique part from dict1
for k in set(dict0).intersection(dict1):
dict2[k] = update_func(dict0[k], dict1[k])
return dict2
|
def get_geometry_type(gi):
""" Return the geometry type from a __geo_interface__ dictionary """
if gi["type"] == "Feature":
return get_geometry_type(gi["geometry"])
elif gi["type"] in ("FeatureCollection", "GeometryCollection"):
return get_geometry_type(gi["geometries"][0])
else:
return gi["type"]
|
def get_most_significant_bits(uuid_val):
"""Equivalent to getMostSignificantBits() in Java."""
msb_s = ''.join(str(uuid_val).split('-')[:3])
msb = int(msb_s, 16)
if int(msb_s[0], 16) > 7:
msb = msb - 0x10000000000000000
return msb
|
def __assert_sorted(collection):
"""Check if collection is sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is sorted
:raise: :py:class:`ValueError` if collection is not sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>> __assert_sorted([10, -1, 5])
Traceback (most recent call last):
...
ValueError: Collection must be sorted
"""
if collection != sorted(collection):
raise ValueError('Collection must be sorted')
return True
|
def is_prime(n):
""" Return True if n is a prime number, else False. """
if n < 2:
return False
raise NotImplementedError("This exercise is still unsolved.")
|
def base_url(skin, variables):
""" Returns the base_url associated to the skin.
"""
return variables['skins'][skin]['base_url']
|
def merge_from_cfg(cfg, base_cfg):
"""
merge the cfg to base cfg
"""
for k, v in cfg.items():
if base_cfg.get(k) and isinstance(v, dict):
base_cfg.update({k: merge_from_cfg(v, base_cfg.get(k))})
else:
base_cfg.update({k: v})
return base_cfg
|
def to_num(numstr):
"""Turns a comma-separated number string to an int"""
return int(numstr.replace(",", ""))
|
def list_remove_repeat(x):
"""Remove the repeated items in a list, and return the processed list.
You may need it to create merged layer like Concat, Elementwise and etc.
Parameters
----------
x : list
Input
Returns
-------
list
A list that after removing it's repeated items
Examples
-------
>>> l = [2, 3, 4, 2, 3]
>>> l = list_remove_repeat(l)
... [2, 3, 4]
"""
y = []
for i in x:
if not i in y:
y.append(i)
return y
|
def shower(pct, data):
"""show a proper point based on the percentage"""
absolute = round(pct / 100 * sum(data), 2)
return f'{round(pct,2)} %\n{absolute} GB'
|
def bitCount(int_type):
"""
Counting bits set, Brian Kernighan's way.
Source: http://wiki.python.org/moin/BitManipulation
"""
count = 0
while int_type:
int_type &= int_type - 1
count += 1
return count
|
def make_dicts(param_list):
"""
makes array of dictionaries with parameters to load
"""
param_dicts = []
for teff in param_list[0]:
for logg in param_list[1]:
for feh in param_list[2]:
for aM in param_list[3]:
param_dict = {'Teff':teff, 'logg':logg, 'FeH': feh, 'aM': aM}
if param_dict not in param_dicts:
param_dicts.append(param_dict)
return param_dicts
|
def parse_adr(feature):
"""
returns dict
'id', 'category' - required keys
'dist_meters' - distance from point in search
"""
res = {
'id' : feature['id'],
'category' : 'adr_address',
'adr_name' : feature['properties']['name'],
'str_name' : feature['properties']['street'],
'str_type' : feature['properties']['street_type'],
'stl_name' : feature['properties']['settlement'],
'stl_type' : feature['properties']['settlement_type'],
'stl_id' : feature['properties']['settlement_id'],
'dist_meters' : feature['properties']['dist_meters']
}
try:
res['geometry'] = feature['geometry']
except:
pass
return res
|
def child_max(dependencies, dependents, scores):
""" Maximum-ish of scores of children
This takes a dictionary of scores per key and returns a new set of scores
per key that is the maximum of the scores of all children of that node plus
its own score. In some sense this ranks each node by the maximum
importance of their children plus their own value.
This is generally fed the result from ``ndependents``
Examples
--------
>>> dsk = {'a': 1, 'b': 2, 'c': (inc, 'a'), 'd': (add, 'b', 'c')}
>>> scores = {'a': 3, 'b': 2, 'c': 2, 'd': 1}
>>> dependencies, dependents = get_deps(dsk)
>>> sorted(child_max(dependencies, dependents, scores).items())
[('a', 3), ('b', 2), ('c', 5), ('d', 6)]
"""
result = dict()
num_needed = dict((k, len(v)) for k, v in dependencies.items())
current = set(k for k, v in num_needed.items() if v == 0)
while current:
key = current.pop()
score = scores[key]
children = dependencies[key]
if children:
score += max(result[child] for child in children)
result[key] = score
for parent in dependents[key]:
num_needed[parent] -= 1
if num_needed[parent] == 0:
current.add(parent)
return result
|
def ndvi(nir, red):
"""
Compute Vegetation Index from RED and NIR bands
NDVI = \\frac { NIR - RED } { NIR + RED }
:param nir: Near-Infrared band
:param red: Red band
:return: NDVI
"""
return (nir-red) / (nir+red)
|
def _relative_path(from_dir, to_path):
"""Returns the relative path from a directory to a path via the repo root."""
return "../" * (from_dir.count("/") + 1) + to_path
|
def function_to_vector(function, model):
"""Assigns a vector to a function.
Args:
function (str): the function name.
model (dict): A mapping that words as follows:
model[function] == vector
Returns:
vector: A numpy array, or None if the function was not found in the
model.
"""
try:
return model[function]
except:
return None
|
def clean_command_type(text: str) -> str:
"""Remove parents from the command type"""
text = text.replace("Command.", "")
text = text.replace("CommandType.", "")
return text
|
def _get_rule_conditional_format(type_, values, format_, ranges):
"""
Get rule to conditionally highlight cells.
:param type_: Type of conditional comparison to make.
:param values: User entered values (using '=A1' notation).
:param format_: Format of cells matching condition.
:param ranges: Ranges to apply conditional formatting.
:return: dict form of rule.
"""
d = {
"booleanRule": {
"condition": {
"type": type_,
"values": values
},
"format": format_
},
"ranges": ranges
}
return d
|
def obinfo(ob):
"""A bit of information about the given object. Returns
the str representation of the object, and if it has a shape,
also includes the shape."""
result = str(ob)
if hasattr(ob,"shape"):
result += " "
result += str(ob.shape)
return result
|
def teams_and_members(review_teams):
"""Fixture with a dictionary contain a few teams with member lists."""
return {
"one": ["first", "second"],
"two": ["two"],
"last_team": [str(i) for i in range(10)],
**review_teams,
}
|
def get_chars_match_up(data: list) -> dict:
"""
Gets the relevant match ups for all characters
"""
match_up = {}
for game in data:
win_char = game["_source"]["winner_char"]
lose_char = game["_source"]["loser_char"]
if win_char not in match_up:
match_up[win_char] = {}
if lose_char not in match_up[win_char]:
match_up[win_char][lose_char] = [0, 0]
if lose_char not in match_up:
match_up[lose_char] = {}
if win_char not in match_up[lose_char]:
match_up[lose_char][win_char] = [0, 0]
match_up[win_char][lose_char][0] += 1
match_up[lose_char][win_char][1] += 1
for key1 in match_up:
for key2 in match_up[key1]:
percent = match_up[key1][key2][0] / (match_up[key1][key2][0] + match_up[key1][key2][1])
match_up[key1][key2] = int(percent * 100) / 100
for key in match_up:
match_up[key] = {k: v for k, v in sorted(match_up[key].items(), key=lambda item: item[1])}
return {k: v for k, v in sorted(match_up.items())}
|
def reynolds(rhosuspension, flowrate, tubediameter, mususpension_value):
"""Returns Reynolds number in a pipe.
#Inputs:
#rhosuspension : Density of the culture suspension ; kg.m-3
#flowrate : Flow rate in the pipe ; m.s-1
#tubediameter : Tube diameter ; m
#mususpension_value : Dynamic viscosity of the suspension ; Pa.s
#Outputs:
#Re : Reynolds number ; .
"""
Re = (rhosuspension*flowrate*tubediameter)/mususpension_value
return Re
|
def parse_etraveler_response(rsp, validate):
""" Convert the response from an eTraveler clientAPI query to a
key,value pair
Parameters
----------
rsp : return type from
eTraveler.clientAPI.connection.Connection.getHardwareHierarchy
which is an array of dicts information about the 'children' of a
particular hardware element.
validate : dict
A validation dictionary, which contains the expected values
for some parts of the rsp. This is here for sanity checking,
for example requiring that the parent element matches the
input element to the request.
Returns
----------
slot_name,child_esn:
slot_name : str
A string given to the particular 'slot' for each child
child_esn : str
The sensor id of the child, e.g., E2V-CCD250-104
"""
for key, val in validate.items():
try:
rsp_val = rsp[key]
if isinstance(val, list):
if rsp_val not in val:
errmsg = "eTraveler response does not match expectation for key %s: " % (key)
errmsg += "%s not in %s" % (rsp_val, val)
raise ValueError(errmsg)
else:
if rsp_val != val:
errmsg = "eTraveler response does not match expectation for key %s: " % (key)
errmsg += "%s != %s" % (rsp_val, val)
raise ValueError(errmsg)
except KeyError:
raise KeyError("eTraveler response does not include expected key %s" % (key))
child_esn = rsp['child_experimentSN']
slot_name = rsp['slotName']
return slot_name, child_esn
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.