content
stringlengths 42
6.51k
|
|---|
def id2char(dictid):
""" Converts single id (int) to character"""
if dictid > 0:
return chr(dictid)
else:
return ' '
|
def linreg(X, Y):
"""
Summary
Linear regression of y = ax + b
Usage
real, real, real = linreg(list, list)
Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value
"""
if len(X) != len(Y): raise ValueError("unequal length")
N = len(X)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for x, y in zip(X, Y):
Sx = Sx + x
Sy = Sy + y
Sxx = Sxx + x*x
Syy = Syy + y*y
Sxy = Sxy + x*y
det = Sxx * N - Sx * Sx
a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
meanerror = residual = 0.0
for x, y in zip(X, Y):
meanerror = meanerror + (y - Sy/N)**2
residual = residual + (y - a * x - b)**2
RR = 1 - residual/meanerror
ss = residual / (N-2)
Var_a, Var_b = ss * N / det, ss * Sxx / det
return a, b, RR, Var_a, Var_b
|
def afs_concordant(af1, af2):
""" Checks whether the allele frequencies of two palindromic variants are
concordant. Concordant if both are either >0.5 or both are <0.5.
Args:
af1, af2 (float): Allele frequencies from two datasets
Returns:
Bool: True if concordant
"""
assert isinstance(af1, float) and isinstance(af2, float)
if (af1 >= 0.5 and af2 >= 0.5) or (af1 < 0.5 and af2 < 0.5):
return True
else:
return False
|
def convert_bool(bool_str: str) -> bool:
"""Convert HTML input string to boolean"""
return bool_str.strip().lower() in {"true", "yes", "on", "1", "enable"}
|
def format_taxon_str(row) -> str:
"""Format a taxon name including common name, if available"""
common_name = row.get('taxon.preferred_common_name')
return f"{row['taxon.name']}" + (f' ({common_name})' if common_name else '')
|
def is_int(string: str) -> bool:
"""
Gets an string and tries to convert it to int
:param string: string to be converted
:return: True or False
"""
try:
int(string)
return True
except ValueError:
return False
|
def _serialise(block):
"""
Serialise block data structure.
:param block: block data structure to serialise.
:return: string representation of block.
"""
out = []
for type in ['points', 'curves', 'loops', 'surfaces']:
if type not in block:
continue
for element in block[type]:
out += [str(component) for component in block[type][element]]
return out
|
def set_master_selectors(facts):
""" Set selectors facts if not already present in facts dict
Args:
facts (dict): existing facts
Returns:
dict: the facts dict updated with the generated selectors
facts if they were not already present
"""
if 'master' in facts:
if 'infra_nodes' in facts['master']:
deployment_type = facts['common']['deployment_type']
if deployment_type == 'online':
selector = "type=infra"
else:
selector = "region=infra"
if 'router_selector' not in facts['master']:
facts['master']['router_selector'] = selector
if 'registry_selector' not in facts['master']:
facts['master']['registry_selector'] = selector
return facts
|
def HTMLColorToRGB(colorstring):
""" convert #RRGGBB to an (R, G, B) tuple
from http://code.activestate.com/recipes/266466-html-colors-tofrom-rgb-tuples/
"""
colorstring = colorstring.strip()
if colorstring[0] == '#': colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError ("input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
r, g, b = [int(n, 16) for n in (r, g, b)]
return (r, g, b)
|
def underscore_to_camel(underscore_str):
"""Convert a underscore_notation string to camelCase.
This is useful for converting python style variable names
to JSON style variable names.
"""
return ''.join(w.title() if i else w
for i, w in enumerate(underscore_str.split('_')))
|
def isscalar(string):
"""
Return True / False if input string can transform to a scalar
Can not deal with too large number (float)
"""
try:
float(string)
return True
except ValueError:
return False
|
def num_permutazioni2(n):
"""ritorna il numero di permutazioni di n oggetti"""
if n==0:
return 1
risp=0
for first in range(n):
risp += num_permutazioni2(n-1)
return risp
|
def digit_sum(n: int) -> int:
"""
Returns the sum of the digits of the number.
>>> digit_sum(123)
6
>>> digit_sum(456)
15
>>> digit_sum(78910)
25
"""
return sum(int(digit) for digit in str(n))
|
def flatten_list(nested_list):
# Essentially we want to loop through each element in the list
# and check to see if it is of type integer or list
"""
Flatten a arbitrarily nested list
Args:
nested_list: a nested list with item to be either integer or list
example:
[2,[[3,[4]], 5]]
Returns:
a flattened list with only integers
example:
[2,3,4,5]
"""
result = []
for element in nested_list:
if isinstance(element, int):
result.append(element)
elif hasattr(element, '__iter__'):
#check to see if it is of type list
list_result = flatten_list(element) #recursive call
for single_integer in list_result:
result.append(single_integer)
return result
|
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
def second_eight(k):
if k % 10 == 8:
return True
else:
return False
if n % 10 == 8:
return True and second_eight(n//10)
else:
if n // 10:
return double_eights(n // 10)
else:
return False
|
def _get_weights(max_length, alphabet):
"""Get weights for each offset in str of certain max length.
Args:
max_length: max length of the strings.
Returns:
A list of ints as weights.
Example:
If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa",
"ab", "b", "ba", "bb". So the weight for the first char is 3.
"""
weights = [1]
for i in range(1, max_length):
weights.append(weights[i-1] * len(alphabet) + 1)
weights.reverse()
return weights
|
def implements(obj: type, interface: type) -> bool:
"""Return true if the give object (maybe an instance or class) implements
the interface.
"""
kimplements = getattr(obj, "__implements__", ())
if not isinstance(kimplements, (list, tuple)):
kimplements = (kimplements,)
for implementedinterface in kimplements:
if issubclass(implementedinterface, interface):
return True
return False
|
def build_profile(first,last, **user_info):
"""Build a dict containing everything we know about user"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
|
def sls_cmd(command, spec):
"""Returns a shell command string for a given Serverless Framework `command` in the given `spec` context.
Configures environment variables (envs)."""
envs = (
f"STAGE={spec['stage']} "
f"REGION={spec['region']} "
f"MEMORY_SIZE={spec['memory_size']} "
f"DATA_BUCKET_NAME={spec['data_bucket_name']} "
)
return f"{envs}serverless {command} --verbose"
|
def get_specification_kinds(specifications):
"""Required by the framework function"""
specifications.setdefault("interface specification", {"tags": ['categories']})
specifications.setdefault("event specification", {"tags": ["environment processes", "functions models"]})
specifications.setdefault("instance maps", {"tags": ["instance maps"]})
return ["interface specification", "event specification", "instance maps"]
|
def schelling_draw(agent):
"""
Portrayal Method for canvas
"""
if agent is None:
return
portrayal = {"Shape": "circle", "r": 0.5, "Filled": "true", "Layer": 0, "stroke_color" : "#4a4a4a"}
if agent.type == "Orange":
portrayal["Color"] = ["#ff962e", "#ff962e"]
else:
portrayal["Color"] = ["#2ee0ff", "#2ee0ff"]
return portrayal
|
def angle_subtract(a, b):
"""Find the difference between two angles.
The result should be between -180 (if a<b) and +180 (if a>b)
"""
res = (a - b) % 360
if res > 180:
res -= 360
return res
|
def pathCount(stairs: int):
"""number of unique ways to climb N stairs using 1 or 2 steps"""
#we've reached the top
if stairs == 0:
return 1
else:
if stairs < 2:
return pathCount(stairs - 1)
return pathCount(stairs - 2) + pathCount(stairs - 1)
|
def findDisappearedNumbers(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# For each number i in nums,
# we mark the number that i points as negative.
# Then we filter the list, get all the indexes
# who points to a positive number
for i in range(len(nums)):
index = abs(nums[i]) - 1
nums[index] = - abs(nums[index])
return [i + 1 for i in range(len(nums)) if nums[i] > 0]
|
def normalize_output(generated_images):
""" Normalize from [-1,1] to [0, 255] """
return (generated_images * 127.5) + 127.5
|
def average(values):
"""
Return the average of a set of scalar values using built in python functions.
"""
return sum(values) / len(values)
|
def calcular_precio_producto(coste_producto):
"""
num -> num
se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste
:param coste_producto: valor numerico del coste
:return: precio del producto
>>> calcular_precio_producto(1000)
1500.0
>>> calcular_precio_producto(2000)
3000.0
"""
if(coste_producto <= 0):
return 'El costo del producto debe ser mayor a cero.'
precioProducto = (coste_producto * 0.5) + coste_producto
return precioProducto
|
def sort_children_key(name):
"""Sort members of an object
:param name: name
:type name: str
:return: the order of sorting
:rtype: int
"""
if name.startswith("__"):
return 3
elif name.startswith("_"):
return 2
elif name.isupper():
return 1
else:
return 0
|
def make_dictnames(tmp_arr, offset=0):
"""
Helper function to create a dictionary mapping a column number
to the name in tmp_arr.
"""
col_map = {}
for i, col_name in enumerate(tmp_arr):
col_map.update({i + offset: col_name})
return col_map
|
def get_nested_key(element, keys):
"""
Returns the key at the nested position inside element, which should be a nested dictionary.
"""
keys = list(keys)
if not keys:
return element
key = keys.pop(0)
if key not in element:
return
return get_nested_key(element[key], keys)
|
def _encode_for_display(text):
"""
Encodes strings so they can display as ASCII in a Windows terminal window.
This function also encodes strings for processing by xml.etree.ElementTree functions.
Returns an ASCII-encoded version of the text.
Unicode characters are converted to ASCII placeholders (for example, "?").
"""
return text.encode('ascii', errors="backslashreplace").decode('utf-8')
|
def n_char(record:str, char="", digit=False):
"""
This function get the number of characters of certain kind from a string
"""
if digit or char!="":
if digit:
n = len([k for k in record if k.isdigit()])
else:
n = len([k for k in record if k==char])
else:
raise ValueError("Please select a character")
return n
|
def precisionatk_implementation(y_true, y_pred, k):
"""Fujnction to calculate precision at k for a given sample
Arguments:
y_true {list} -- list of actual classes for the given sample
y_pred {list} -- list of predicted classes for the given sample
k {[int]} -- top k predictions we are interested in
"""
# if k = 0 return 0 as we should never have k=0
# as k is always >=1
if k == 0:
return 0
# as we are interested in top k predictions
y_pred = y_pred[:k]
# convert predictions to set
pred_set = set(y_pred)
# convert actual values to set
true_set = set(y_true)
# find comon values in both
common_values = pred_set.intersection(true_set)
# return length of common values over k
return len(common_values) / len(y_pred[:k])
|
def _get_timestamps(ix_list, ix, orig_ixs):
"""Returns the first and the last position in a list of an index.
Args:
ix_list (List): A sorted list of indicies, indicies appear multiple times
ix (Int): Index
Returns:
Tuples: Returns two tuples.
"""
first_ix = ix_list.index(ix)
last_ix = (len(ix_list) - 1 - ix_list[::-1].index(ix))
# position of relevant data in array
arraystamps = (first_ix, last_ix + 1)
# position of relevant data in submission file
filestamps = (orig_ixs[first_ix] % 5, orig_ixs[last_ix] % 5 + 1)
# add 1 at the end because they are meant as list indices
return arraystamps, filestamps
|
def lorentzian_function(x_L, sigma_L, amplitude_L):
"""Compute a Lorentzian function used for fitting data."""
return amplitude_L * sigma_L**2 / (sigma_L**2 + x_L ** 2)
|
def getLonLatCrs(searchList):
"""get the correct names of the columns holding the coordinates
@param header Header of the CSV
@returns (lon, lat, crs) where lon, lat, crs are the column names
"""
lng = None
lat = None
crs = None
for t in searchList:
if t.lower() in ("longitude", "lon", "long", "lng"):
lng = t
if t.lower() in ("latitude", "lat"):
lat = t
if t.lower() in ("crs", "srs", "coordinate reference systems", "reference systems", "spatial reference system"):
crs = t
return (lng, lat, crs)
|
def configure_proxy_settings(ip, port, username=None, password=None):
"""
Configuring proxies to pass to request
:param ip: The IP address of the proxy you want to connect to ie 127.0.0.1
:param port: The port number of the prxy server you are connecting to
:param username: The username if requred authentication, need to be accompanied with a `password`.
Will default to None to None if not provided
:param password: The password if required for authentication. Needs to be accompanied by a `username`
Will default to None if not provided
:return: A dictionary of proxy settings
"""
proxies = None
credentials = ''
# If no IP address or port information is passed, in the proxy information will remain `None`
# If no proxy information is set, the default settings for the machine will be used
if ip is not None and port is not None:
# Username and password not necessary
if username is not None and password is not None:
credentials = '{}:{}@'.format(username, password)
proxies = {'http': 'http://{credentials}{ip}:{port}'.format(credentials=credentials, ip=ip, port=port),
'https': 'https://{credentials}{ip}:{port}'.format(credentials=credentials, ip=ip, port=port)
}
return proxies
|
def _flatten(source, key=None):
"""Flattens a dicts values into str for submission
Args:
source (dict): Data to flatten, with potentially nonhomogeneous
value types (specifically, container types).
Returns:
Dict with all values as single objects.
"""
result_dict = {}
if isinstance(source, dict):
for k, v in source.items():
if key:
recurse_key = '{}=>{}'.format(key, k)
else:
recurse_key = k
result_dict.update(_flatten(v, key=recurse_key))
elif isinstance(source, (list, tuple)):
if all(isinstance(i, (int, float, str)) for i in source):
result_dict[key] = ", ".join(str(i) for i in source)
else:
for index, value in enumerate(source):
result_dict.update(_flatten(value, key='{}=>{}'.format(key, index)))
elif source is None:
source = ""
else:
result_dict[key] = source
return result_dict
|
def human_readable_size(byte_size):
"""Return human-readable size string, using base-10 prefixes."""
if byte_size < 10**3:
return f'{byte_size}B'
if byte_size < 10**6:
return f'{byte_size / 10**3:.1f}kB'
if byte_size < 10**9:
return f'{byte_size / 10**6:.1f}MB'
return f'{byte_size / 10**9:.1f}GB'
|
def count_leading_spaces(string: str) -> int:
"""
Count the number of spaces in a string before any other character.
:param string: input string
:return: number of spaces
"""
return len(string) - len(string.lstrip(" "))
|
def split_identifier(identifier):
"""
Split an SQL identifier into a two element tuple of (namespace, name).
The identifier could be a table, column, or sequence name might be prefixed
by a namespace.
"""
try:
namespace, name = identifier.split('"."')
except ValueError:
namespace, name = "", identifier
return namespace.strip('"'), name.strip('"')
|
def prune_cells(grid):
"""Given a grid, scan each row for solved cells, and remove those
numbers from every other cell in the row.
Note that 'grid' can be an iterable of rows, columns, or 3x3 squares.
Since the component cells (sets) are modified in-place it still works
if you rearrange things.
Return True or False depending on whether any pruning was done.
"""
changes = False
for row in grid:
singletons = [cell for cell in row if isinstance(cell, int)]
for key in singletons:
prunable = [cell for cell in row if isinstance(cell, set) and key in cell]
for cell in prunable:
cell.remove(key)
changes = True
return changes
|
def row_col_indices_from_flattened_indices(indices, num_cols):
"""Computes row and column indices from flattened indices.
Args:
indices: An integer tensor of any shape holding the indices in the flattened
space.
num_cols: Number of columns in the image (width).
Returns:
row_indices: The row indices corresponding to each of the input indices.
Same shape as indices.
col_indices: The column indices corresponding to each of the input indices.
Same shape as indices.
"""
# Avoid using mod operator to make the ops more easy to be compatible with
# different environments, e.g. WASM.
row_indices = indices // num_cols
col_indices = indices - row_indices * num_cols
return row_indices, col_indices
|
def searchRange( nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res=[-1,-1]
l,r=0,len(nums)-1
while l<=r:
m=l+(r-l)//2
if nums[m]<target:
l=m+1
else:
r=m-1
res[0]=l
l,r=0,len(nums)-1
while l<=r:
m=l+(r-l)//2
if nums[m]<=target:
l=m+1
else:
r=m-1
res[1]=l-1
return res if res[0]<=res[1] else [-1,-1]
|
def get_change(m):
"""
get_change finds the minimum number of coins needed to change the input value
(an integer) into coins with denominations 1, 5, and 10.
:param m: integer represents the change
:return: the min number of coins needed to change m
"""
m1 = m % 10
m2 = m1 % 5
return m//10 + m1//5 + m2
|
def merge(left, right):
"""
deep merge dictionary on the left with the one
on the right.
Fill in left dictionary with right one where
the value of the key from the right one in
the left one is missing or None.
"""
if isinstance(left, dict) and isinstance(right, dict):
for key, value in right.items():
if key not in left:
left[key] = value
elif left[key] is None:
left[key] = value
else:
left[key] = merge(left[key], value)
return left
|
def fixture_inst_jenny():
"""Define example instance data: Jenny."""
return {
'InstanceId': '8675309',
'State': {
'Name': 'stopped'
},
'PublicIpAddress': '10.11.12.13',
'Tags': [{
'Key': 'Name',
'Value': 'minecraft-main-server-jenny'
}, {
'Key': 'Environment',
'Value': 'main'
}]
}
|
def vecDotProduct(inVecA, inVecB):
""" returns dotproct inVecZ dot inVecB """
return inVecA[0] * inVecB[0] + inVecA[1] * inVecB[1] + inVecA[2] * inVecB[2]
|
def _maybe_encode_unicode_string(record):
"""Encodes unicode strings if needed."""
if isinstance(record, str):
record = bytes(record, "utf-8").strip()
return record
|
def get_header(token):
"""Return HTTP header."""
return {
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(token),
}
|
def capitalize(string):
"""
Capitalizes the first letter of a string.
"""
return string[0].upper() + string[1:]
|
def extractPath(val):
"""
extract the path from the string returned by an ls -l|a command
"""
return 'gs://' + val.split('gs://')[1].split('#')[0]
|
def clean_dict(dictionary, to_del='_'):
"""
Delete dictionary items with keys starting with specified string
Works recursively
Args:
:dictionary: Dictionary object
:to_del: Starts-with identifier
"""
to_delete = []
for k, v in dictionary.items():
if isinstance(v, dict):
v = clean_dict(v)
if k.startswith('_'):
to_delete.append(k)
for k in to_delete:
del dictionary[k]
return dictionary
|
def vdc(n, base=2):
""" Create van der Corput sequence
source for van der Corput and Halton sampling code
https://laszukdawid.com/2017/02/04/halton-sequence-in-python/
"""
vdc, denom = 0, 1
while n:
denom *= base
n, remainder = divmod(n, base)
vdc += remainder / denom
return vdc
|
def denormalize(val):
""" De-normalize a string """
if val.find('_') != -1:
val = val.replace('_','-')
return val
|
def _handle_sort_key(model_name, sort_key=None):
"""Generate sort keys according to the passed in sort key from user.
:param model_name: Database model name be query.(alarm, meter, etc.)
:param sort_key: sort key passed from user.
return: sort keys list
"""
sort_keys_extra = {'alarm': ['name', 'user_id', 'project_id'],
'meter': ['user_id', 'project_id'],
'resource': ['user_id', 'project_id', 'timestamp'],
}
sort_keys = sort_keys_extra[model_name]
if not sort_key:
return sort_keys
# NOTE(Fengqian): We need to put the sort key from user
#in the first place of sort keys list.
try:
sort_keys.remove(sort_key)
except ValueError:
pass
finally:
sort_keys.insert(0, sort_key)
return sort_keys
|
def decode_to_str(batch_text, max_len=512) :
"""
Converts bytes string data to text. And truncates to max_len.
"""
return [ ' '.join(text.decode('utf-8').split()[:max_len]) if isinstance(text, bytes) else text[:max_len]
for text in batch_text ]
|
def isPhoneNumber(text):
"""check if string matches phone number pattern"""
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
|
def get_max_delta_score(spliceai_ano_dict_by_symbol):
"""
get_max_delta_score
===================
Method to get the max SpliceAI delta score from a specific ref/alt key in the spliceai_region_dict
Parameters:
-----------
1) spliceai_ano_dict_by_symbol: (dict) A sub-dict of the spliceai_region_dict for a current pos/ref/alt
Returns:
++++++++
1) (float) The max delta score
"""
max_delta_score = 0.0
for gene, spliceai_annotation in spliceai_ano_dict_by_symbol.items():
## Get the current max delta score
max_ds = max(
spliceai_annotation["DS_AG"],
spliceai_annotation["DS_AL"],
spliceai_annotation["DS_DG"],
spliceai_annotation["DS_DL"],
)
if float(max_ds) > float(max_delta_score):
max_delta_score = float(max_ds)
return max_delta_score
|
def factorial(n):
"""Compute n! where n is an integer >= 0."""
if (isinstance)(n, int) and n >= 0:
acc = 1
for x in range(1, n + 1):
acc *= x
return acc
else:
raise TypeError("the argument to factorial must be an integer >= 0")
|
def get_username(strategy, uid, user=None, *args, **kwargs):
"""Removes unnecessary slugification and cleaning of the username since the uid is unique and well formed"""
if not user:
username = uid
else:
username = strategy.storage.user.get_username(user)
return {'username': username}
|
def helper(numRows, triangle):
"""
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
"""
if numRows <= 2:
return triangle[numRows-1]
line = [1]
prev_line = helper(numRows-1, triangle)
for i in range(len(prev_line)-1):
line.append(prev_line[i] + prev_line[i + 1])
line.append(1)
triangle.append(line)
return line
|
def DeepSupervision(criterion, xs, y):
"""DeepSupervision
Applies criterion to each element in a list.
Args:
criterion: loss function
xs: tuple of inputs
y: ground truth
"""
loss = 0.0
for x in xs:
loss += criterion(x, y)
loss /= len(xs)
return loss
|
def square_variables(n, m):
"""dict of symbols and list of values for m-bit binary numbers arranged in an n-by-n square;
symbols maps array indices to string encoding those indices"""
symbols = dict()
values = range(2**m)
for i in range(n):
for j in range(n):
symbols[(i, j)] = '(%i, %i)' % (i, j)
return symbols, values
|
def add_sub_idx(i1: int, change: int):
"""
Adds or subtracts an index from another one and skips 0 if encountered.
:param i1: The start index
:param change: The change (+ or -)
:return: The new index
>>> add_sub_idx(-10, 10)
1
>>> add_sub_idx(10, -10)
-1
>>> add_sub_idx(-5, 10)
6
"""
return i1 + change + (1 if i1 < 0 < i1+change+1 else -1 if i1+change-1 < 0 < i1 else 0)
|
def pad(b):
""" Follows Section 5.1: Padding the message """
b = bytearray(b) # convert to a mutable equivalent
l = len(b) * 8 # note: len returns number of bytes not bits
# append but "1" to the end of the message
b.append(0b10000000) # appending 10000000 in binary (=128 in decimal)
# follow by k zero bits, where k is the smallest non-negative solution to
# l + 1 + k = 448 mod 512
# i.e. pad with zeros until we reach 448 (mod 512)
while (len(b)*8) % 512 != 448:
b.append(0x00)
# the last 64-bit block is the length l of the original message
# expressed in binary (big endian)
b.extend(l.to_bytes(8, 'big'))
return b
|
def terminal_side_effect(state, depth_remaining, time_remaining):
""" Side effect returns true if we reach a terminal state
:param state: the state of the game to evaluate
:param depth_remaining: true if there is depth remaining
:param time_remaining: true if there is time remaining
:return: true if we are terminating
"""
if not depth_remaining:
return True
end_state_nodes = []
for alpha in list(map(chr, range(101, 110))): # iterate from e-m
end_state_nodes.append(str(alpha))
if state in end_state_nodes:
return True
return False
|
def exclude_deprecated_entities(script_set, script_names,
playbook_set, playbook_names,
integration_set, integration_ids):
"""Removes deprecated entities from the affected entities sets.
:param script_set: The set of existing scripts within Content repo.
:param script_names: The names of the affected scripts in your change set.
:param playbook_set: The set of existing playbooks within Content repo.
:param playbook_names: The ids of the affected playbooks in your change set.
:param integration_set: The set of existing integrations within Content repo.
:param integration_ids: The ids of the affected integrations in your change set.
:return: deprecated_messages_dict - A dict of messages specifying of all the deprecated entities.
"""
deprecated_messages_dict = {
'scripts': '',
'playbooks': '',
'integrations': ''
}
deprecated_entities_strings_dict = {
'scripts': '',
'playbooks': '',
'integrations': ''
}
# Iterates over three types of entities: scripts, playbooks and integrations and removes deprecated entities
for entity_set, entity_names, entity_type in [(script_set, script_names, 'scripts'),
(playbook_set, playbook_names, 'playbooks'),
(integration_set, integration_ids, 'integrations')]:
for entity in entity_set:
# integrations are defined by their ids while playbooks and scripts and scripts are defined by names
if entity_type == 'integrations':
entity_name = list(entity.keys())[0]
else:
entity_name = list(entity.values())[0].get('name', '')
if entity_name in entity_names:
entity_data = list(entity.values())[0]
if entity_data.get('deprecated', False):
deprecated_entities_strings_dict[entity_type] += entity_name + '\n'
entity_names.remove(entity_name)
if deprecated_entities_strings_dict[entity_type]:
deprecated_messages_dict[entity_type] = 'The following {} are deprecated ' \
'and are not taken into account in the test collection:' \
'\n{}'.format(entity_type,
deprecated_entities_strings_dict[entity_type])
return deprecated_messages_dict
|
def float_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval.
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
A float that results from scaling `maxval` according to `level`.
"""
return float(level) * maxval / 10.0
|
def flatten_rules(rules):
"""
Convenience function to flatten lists which may contain lists of rules to a list with only rules.
"""
result = []
for rule in rules:
if type(rule) is list:
result.extend(rule)
else:
result.append(rule)
return result
|
def get_email_properties(indicator: dict) -> tuple:
"""
Extract the email properties from the indicator attributes.
Example:
Indicator:
{
"attributes":
[
{
"createdAt": "2019-05-13T16:54:18Z",
"id": "abc",
"name": "email-body",
"value": "\r\n\r\n-----Original Message-----\r\nFrom: A \r\nSent:
Monday, May 13, 2019 12:22 PM\r\nTo:
},
{
"createdAt": "2019-05-13T16:54:18Z",
"id": "def",
"name": "from",
"value": "foo@test.com"
},
{
"createdAt": "2019-05-13T16:54:18Z",
"id": "cf3182ca-92ec-43b6-8aaa-429802a99fe5",
"name": "to",
"value": "example@gmail.com"
}
],
"createdAt": "2019-05-13T16:54:18Z",
"falsePositive": false,
"id": "ghi",
"type": "E-mail",
"updatedAt": "0001-01-01T00:00:00Z",
"value": "FW: Task"
}
Return values:
:param indicator: The email indicator
:return: Email body, To and From
"""
email_to_attribute: list = list(filter(lambda a: a.get('name') == 'to', indicator.get('attributes', [])))
email_to: str = email_to_attribute[0].get('value') if email_to_attribute else ''
email_from_attribute: list = list(filter(lambda a: a.get('name') == 'from', indicator.get('attributes', [])))
email_from: str = email_from_attribute[0].get('value') if email_from_attribute else ''
email_body_attribute: list = list(filter(lambda a: a.get('name') == 'email-body', indicator.get('attributes', [])))
email_body: str = email_body_attribute[0].get('value') if email_body_attribute else ''
return email_body, email_to, email_from
|
def e_m(val):
"""energy multiplier"""
if val == 5: return 10
elif val >= 6: return 100
else: return None
|
def check_set(card_set):
"""
Decide whether the three cards meet the criteria for a set
:param card_set: should contain three cards
:return: True/False
"""
allowed = 1, 3
colors = set([])
numbers = set([])
shades = set([])
shapes = set([])
for card in card_set:
colors.add(card['color'])
numbers.add(card['number'])
shades.add(card['shade'])
shapes.add(card['shape'])
check_colors = len(colors) in allowed
check_numbers = len(numbers) in allowed
check_shades = len(shades) in allowed
check_shapes = len(shapes) in allowed
if check_colors and check_numbers and check_shades and check_shapes:
return True
else:
return False
|
def spin(x, dancers):
"""
Remove x characters from the end of the string
and place them, order unchanged, on the front.
Parameters
----------
x : int
Number of characters to be moved from end of dancers
to the front of dancers.
dancers : str
A mutable sequence of characters
"""
end = dancers[-x:]
return end + dancers[:len(dancers)-x]
|
def SanitizeSQL(sql):
"""Convert singled quotes to dual single quotes, so SQL doesnt terminate the string improperly"""
sql = str(sql).replace("'", "''")
return sql
|
def is_float4x4(items):
"""Verify that the sequence contains 4 sequences of each 4 floats.
Parameters
----------
items : sequence
The sequence of items.
Returns
-------
bool
"""
return (
len(items) == 4 and
all(
len(item) == 4 and
all(isinstance(i, float) for i in item) for item in items
)
)
|
def get_computed_response_parameter_number(response):
"""
extract the number of parameters from the Dialogflow response, fallback: 0
"""
try:
return len(response.query_result.parameters)
except:
return 0
|
def binary_search(target, lst):
"""
Perform binary search over the specified list with the specified target.
The type of the target should match the types of the elements of the list and the list should be sorted.
Parameters
----------
target : Any
The element to search for in the list.
lst : list of Any
The list.
Returns
-------
bool
A boolean value indicating whether the target is found in the list.
int
The index in the list matching the target.
"""
low = 0
high = len(lst) - 1
while low < high:
mid = low + (high - low)//2
if lst[mid] == target:
return True, mid
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return False, -1
|
def probs(pct):
"""
Return a human-readable string representing the probabilities.
This scheme is shamelessly ripped from CIA's Words of Estimative
Probability.
https://www.cia.gov/library/center-for-the-study-of-intelligence/csi-publications/books-and-monographs/sherman-kent-and-the-board-of-national-estimates-collected-essays/6words.html
100% Certainty
93% +/- ~6% Almost certain
75% +/- ~12% Probable
50% +/- ~10% Chances about even
30% +/- ~10% Probably not
7% +/- ~5% Almost certainly not
0% Impossibility
"""
pct = int(pct * 100)
if pct == 100:
return "certain"
if pct > 87:
return "almost certain"
if pct > 63:
return "probable"
if pct > 40:
return "about even"
if pct > 20:
return "probably not"
if pct > 2:
return "almost certainly not"
return "an impossibility"
|
def split_bits(word : int, amounts : list):
"""
takes in a word and a list of bit amounts and returns
the bits in the word split up. See the doctests for concrete examples
>>> [bin(x) for x in split_bits(0b1001111010000001, [16])]
['0b1001111010000001']
>>> [bin(x) for x in split_bits(0b1001111010000001, [8,8])]
['0b10011110', '0b10000001']
not the whole 16 bits!
>>> [bin(x) for x in split_bits(0b1001111010000001, [8])]
Traceback (most recent call last):
AssertionError: expected to split exactly one word
This is a test splitting MOVE.B (A1),D4
>>> [bin(x) for x in split_bits(0b0001001010000100, [2,2,3,3,3,3])]
['0b0', '0b1', '0b1', '0b10', '0b0', '0b100']
"""
nums = []
pos = 0
for amount in amounts:
# get a group of "amount" 1's
mask = 2**amount - 1
# shift mask to the left so it aligns where the last
# iteration ended off
shift = 16 - amount - pos
mask = mask << shift
# update location in the word
pos += amount
# extract the relavent bits
bits = word & mask
# shift back and insert the list to be returned
nums.append(bits >> shift)
assert pos == 16, 'expected to split exactly one word'
return nums
|
def calc_piping_thermal_losses_cooling(Total_load_per_hour_W):
"""
This function estimates the average thermal losses of a distribution for an hour of the year
:param Tnet_K: current temperature of the pipe
:param m_max_kgpers: maximum mass flow rate in the pipe
:param m_min_kgpers: minimum mass flow rate in the pipe
:param L: length of the pipe
:param Tg: ground temperature
:param K: linear transmittance coefficient (it accounts for insulation and pipe diameter)
:param cp: specific heat capacity
:type Tnet_K: float
:type m_max_kgpers: float
:type m_min_kgpers: float
:type L: float
:type Tg: float
:type K: float
:type cp: float
:return: Qloss: thermal lossess in the pipe.
:rtype: float
"""
Qloss = 0.05 * Total_load_per_hour_W #FixMe: Link the value directly to the thermal network matrix
return Qloss
|
def parseFloat(value, ret=0.0):
"""
Parses a value as float.
This function works similar to its JavaScript-pendant, and performs
checks to parse most of a string value as float.
:param value: The value that should be parsed as float.
:param ret: The default return value if no integer could be parsed.
:return: Either the parse value as float, or ret if parsing not possible.
"""
if value is None:
return ret
if not isinstance(value, str):
value = str(value)
conv = ""
value = value.strip()
dot = False
for ch in value:
if ch not in "+-0123456789.":
break
if ch == ".":
if dot:
break
dot = True
conv += ch
try:
return float(conv)
except ValueError:
return ret
|
def _deps_compare(package):
"""Compare deps versions."""
d_compare = None
d_version = None
for compare in [">=", "<=", ">", "<", "="]:
c_idx = package.rfind(compare)
if c_idx >= 0:
d_compare = compare
d_version = package[c_idx + len(compare):len(package)]
package = package[0:c_idx]
break
return d_version, d_compare
|
def max_mod(n, inlist):
"""Returns k in inlist with the maximum value for n%k"""
currMax = 0
ret = inlist[0] #defaults to some item in inlist.
for item in inlist:
if currMax < n%item:
currMax = n%item
ret = item
return ret
|
def split_reference_name(reference_name, at="_"):
"""
Split reference_name at the first `at`.
This returns the TE family name if the TEs are named "$ID_$NAME_$SUPERFAMILY".
>>> split_reference_name('FBti0019298_rover_Gypsy')
'rover'
"""
if at in reference_name:
return "_".join(reference_name.split(at)[1:-1])
else:
return reference_name
|
def str_to_array_of_int(value):
""" Convert a string representing an array of int into a real array of int """
return [int(v) for v in value.split(",")]
|
def is_env_var(s):
"""Environmental variables have a '$$' prefix."""
return s.startswith('$$')
|
def remove_prefix(string: str, prefix: str) -> str:
"""
Remove prefix from string.
Parameters
----------
string
Given string to remove prefix from.
prefix
Prefix to remove.
Raises
------
AssertionError
If string doesn't start with given prefix.
"""
if string.startswith(prefix):
string = string[len(prefix) :]
else: # pragma: nocover
raise AssertionError(f"{string} doesn't start with prefix {prefix}")
return string
|
def shift(string: str, shift_num: int) -> str:
"""
:param shift_num:
can be passed as a negative int or a positive one.
:return:
shifts the string characters by shift_num
"""
encrypted = ""
for let in string:
encrypted += chr(ord(str(let)) + shift_num)
return encrypted
|
def flip_alt_week(
alt_week: str,
) -> str:
"""Flip an alternate week value."""
return 'B2' if alt_week == 'B1' else 'B1'
|
def check_set(set_playable: list, expected: list ) -> bool:
""" helperfunction for testing playable sets
**Params**:
------------------------
set_playable: A set of cards
Description
"""
return all(True for card in set_playable if card in expected)
|
def ppi2microns(val):
"""convert LCD display resolution in PPI to microns, which is the size
of each display pixel. """
return 1000*25.4/val
|
def median(xs, sort=True):
"""Returns the median of an unsorted or sorted numeric vector.
@param xs: the vector itself.
@param sort: whether to sort the vector. If you know that the vector is
sorted already, pass C{False} here.
@return: the median, which will always be a float, even if the vector
contained integers originally.
"""
if sort:
xs = sorted(xs)
mid = int(len(xs) / 2)
if 2 * mid == len(xs):
return float(xs[mid-1] + xs[mid]) / 2
else:
return float(xs[mid])
|
def list_to_str(l, commas=True):
"""Converts list to string representation"""
if commas:
return ','.join(l)
else:
return ''.join(l)
|
def get_choice_files(files):
"""
Adapted from http://stackoverflow.com/questions/4558983/slicing-a-dictionary-by-keys-that-start-with-a-certain-string
:param files:
:return:
"""
# return {k:v for k,v in files.iteritems() if k.startswith('choice')}
return dict((k, files[k]) for k in files.keys() if k.startswith('choice'))
|
def getattribute(objeto, name: str):
"""Returns the attribute matching passed name."""
# Get internal dict value matching name.
value = objeto.__dict__.get(name)
if not value:
# Raise AttributeError if attribute value not found.
return None
# Return attribute value.
return value
|
def get_dict(post, key):
""" Extract from POST PHP-like arrays as dictionary.
Example usage::
<input type="text" name="option[key1]" value="Val 1">
<input type="text" name="option[key2]" value="Val 2">
options = get_dict(request.POST, 'option')
options['key1'] is 'Val 1'
options['key2'] is 'Val 2'
"""
result = {}
if post:
import re
patt = re.compile('^([a-zA-Z_]\w+)\[([a-zA-Z_\-][\w\-]*)\]$')
for post_name, value in post.items():
value = post[post_name]
match = patt.match(post_name)
if not match or not value:
continue
name = match.group(1)
if name == key:
k = match.group(2)
result.update({k: value})
return result
|
def aread8(np, input, output):
""" command: aread8 -p demp.tif -ad8 demad8.tif [-o outletfile.shp] [-wg demwg.tif] [-nc], pfile: input flow directions grid, ad8file: output contributing area grid, Outletfile: input outlets shapefile, wgfile: input weight grid file """
aread8 = "mpirun -np {} aread8 -p {} -ad8 {}".format(
np, input, output)
return aread8
|
def deg_to_dms(deg):
"""Convert decimal degrees to (deg,arcmin,arcsec)"""
d = int(deg)
deg-=d
m = int(deg*60.)
s=deg-m//60
return d,m,s
|
def basis_function_ders(degree, knot_vector, span, knot, order):
""" Computes derivatives of the basis functions for a single parameter.
Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param span: knot span, :math:`i`
:type span: int
:param knot: knot or parameter, :math:`u`
:type knot: float
:param order: order of the derivative
:type order: int
:return: derivatives of the basis functions
:rtype: list
"""
# Initialize variables
left = [1.0 for _ in range(degree + 1)]
right = [1.0 for _ in range(degree + 1)]
ndu = [[1.0 for _ in range(degree + 1)] for _ in range(degree + 1)] # N[0][0] = 1.0 by definition
for j in range(1, degree + 1):
left[j] = knot - knot_vector[span + 1 - j]
right[j] = knot_vector[span + j] - knot
saved = 0.0
r = 0
for r in range(r, j):
# Lower triangle
ndu[j][r] = right[r + 1] + left[j - r]
temp = ndu[r][j - 1] / ndu[j][r]
# Upper triangle
ndu[r][j] = saved + (right[r + 1] * temp)
saved = left[j - r] * temp
ndu[j][j] = saved
# Load the basis functions
ders = [[0.0 for _ in range(degree + 1)] for _ in range((min(degree, order) + 1))]
for j in range(0, degree + 1):
ders[0][j] = ndu[j][degree]
# Start calculating derivatives
a = [[1.0 for _ in range(degree + 1)] for _ in range(2)]
# Loop over function index
for r in range(0, degree + 1):
# Alternate rows in array a
s1 = 0
s2 = 1
a[0][0] = 1.0
# Loop to compute k-th derivative
for k in range(1, order + 1):
d = 0.0
rk = r - k
pk = degree - k
if r >= k:
a[s2][0] = a[s1][0] / ndu[pk + 1][rk]
d = a[s2][0] * ndu[rk][pk]
if rk >= -1:
j1 = 1
else:
j1 = -rk
if (r - 1) <= pk:
j2 = k - 1
else:
j2 = degree - r
for j in range(j1, j2 + 1):
a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]
d += (a[s2][j] * ndu[rk + j][pk])
if r <= pk:
a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]
d += (a[s2][k] * ndu[r][pk])
ders[k][r] = d
# Switch rows
j = s1
s1 = s2
s2 = j
# Multiply through by the the correct factors
r = float(degree)
for k in range(1, order + 1):
for j in range(0, degree + 1):
ders[k][j] *= r
r *= (degree - k)
# Return the basis function derivatives list
return ders
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.