content
stringlengths 42
6.51k
|
|---|
def a_star(graph, heuristic, start, goal):
"""
Finds the shortest distance between two nodes using the A-star (A*) algorithm
:param graph: an adjacency-matrix-representation of the graph where (x,y) is the weight of the edge or 0 if there is no edge.
:param heuristic: an estimation of distance from node x to y that is guaranteed to be lower than the actual distance. E.g. straight-line distance
:param start: the node to start from.
:param goal: the node we're searching for
:return: The shortest distance to the goal node. Can be easily modified to return the path.
"""
# This contains the distances from the start node to all other nodes, initialized with a distance of "Infinity"
distances = [float("inf")] * len(graph)
# The distance from the start node to itself is of course 0
distances[start] = 0
# This contains the priorities with which to visit the nodes, calculated using the heuristic.
priorities = [float("inf")] * len(graph)
# start node has a priority equal to straight line distance to goal. It will be the first to be expanded.
priorities[start] = heuristic[start][goal]
# This contains whether a node was already visited
visited = [False] * len(graph)
# While there are nodes left to visit...
while True:
# ... find the node with the currently lowest priority...
lowest_priority = float("inf")
lowest_priority_index = -1
for i in range(len(priorities)):
# ... by going through all nodes that haven't been visited yet
if priorities[i] < lowest_priority and not visited[i]:
lowest_priority = priorities[i]
lowest_priority_index = i
if lowest_priority_index == -1:
# There was no node not yet visited --> Node not found
return -1
elif lowest_priority_index == goal:
# Goal node found
# print("Goal node found!")
return distances[lowest_priority_index]
# print("Visiting node " + lowestPriorityIndex + " with currently lowest priority of " + lowestPriority)
# ...then, for all neighboring nodes that haven't been visited yet....
for i in range(len(graph[lowest_priority_index])):
if graph[lowest_priority_index][i] != 0 and not visited[i]:
# ...if the path over this edge is shorter...
if distances[lowest_priority_index] + graph[lowest_priority_index][i] < distances[i]:
# ...save this path as new shortest path
distances[i] = distances[lowest_priority_index] + graph[lowest_priority_index][i]
# ...and set the priority with which we should continue with this node
priorities[i] = distances[i] + heuristic[i][goal]
# print("Updating distance of node " + i + " to " + distances[i] + " and priority to " + priorities[i])
# Lastly, note that we are finished with this node.
visited[lowest_priority_index] = True
# print("Visited nodes: " + visited)
# print("Currently lowest distances: " + distances)
|
def human_to_bytes(size):
"""Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
"""
bytes = size[:-1]
unit = size[-1].upper()
if bytes.isdigit():
bytes = int(bytes)
if unit == 'P':
bytes *= 1125899906842624
elif unit == 'T':
bytes *= 1099511627776
elif unit == 'G':
bytes *= 1073741824
elif unit == 'M':
bytes *= 1048576
elif unit == 'K':
bytes *= 1024
else:
bytes = 0
else:
bytes = 0
return bytes
|
def sortGlyphs(glyphlist):
"""
Sort glyphs in a way that glyphs from the exceptionList, or glyphs starting
with 'uni' names do not get to be key (first) glyphs. An infinite loop is
avoided, in case there are only glyphs matching above mentioned properties.
"""
exceptionList = 'dotlessi dotlessj kgreenlandic ae oe AE OE uhorn'.split()
glyphs = sorted(glyphlist)
for i in range(len(glyphs)):
if glyphs[0] in exceptionList or glyphs[0].startswith('uni'):
glyphs.insert(len(glyphs), glyphs.pop(0))
else:
continue
return glyphs
|
def encode_synchsafe_int(i, per_byte):
"""Encode synchsafe integers for ID3v2 tags."""
if i > 2 ** (per_byte * 4) - 1:
raise ValueError(
f"{i} is too large to be represented by a synchsafe "
f"integer with {per_byte} bits per byte."
)
v = 0
mask = 0x7F
value = i
while ((mask ^ 0x7FFFFFFF) > 0):
v = value & ~mask
v = v << (8 - per_byte)
v = v | (value & mask)
mask = ((mask + 1) << 8) - 1
value = v
return value.to_bytes(4, byteorder='big')
|
def get_state_feature(num_states_in_group, num_groups, state):
"""
Given state, return the feature of that state
Args:
num_states_in_group [int]
num_groups [int]
state [int] : 1~500
Returns:
one_hot_vector [numpy array]
"""
### Generate state feature
# Create one_hot_vector with size of the num_groups, according to state
# For simplicity, assume num_states is always perfectly divisible by num_groups
# Note that states start from index 1, not 0!
# Example:
# If num_states = 100, num_states_in_group = 20, num_groups = 5,
# one_hot_vector would be of size 5.
# For states 1~20, one_hot_vector would be: [1, 0, 0, 0, 0]
one_hot_vector = [0] * num_groups
for k in range(num_groups):
group_end = num_states_in_group * (k + 1)
group_start = group_end - num_states_in_group + 1
if (state <= group_end) & (state >= group_start):
one_hot_vector[k] = 1
else:
one_hot_vector[k] = 0
return one_hot_vector
|
def make_pure_python(obj):
"""
Take dict object which can include either dict or numpy scalars or Python scalars, and
convert to pure Python.
"""
if isinstance(obj, dict):
for key, val in obj.items():
obj[key] = make_pure_python(val)
return obj
elif hasattr(obj, 'item'):
return obj.item()
else:
return obj
|
def _flatten(container):
"""
_flatten a sequence of sequences into a single list
"""
_flattened = []
for sequence in container:
_flattened.extend(sequence)
return _flattened
|
def _div_ceil(a, b):
"""Calculate ceil of a/b without decaying to float."""
return -(-a // b)
|
def sanitize(this) -> str:
""" Convert object to string.
Args:
this (object).
Returns:
str(this) (str)
Raises:
none.
"""
if this is None:
return "None"
else:
return str(this)
|
def ValidationForm(consideration, condition, consideration_types={}):
"""
The basic structure of all the validator methods.
"""
if consideration is None:
return True
elif (
consideration and
(bool(type(consideration) in consideration_types)
if consideration_types else True)
):
return condition
return not condition
|
def _get_input_shape(shape_x):
"""_get_input_shape"""
dim_a = shape_x[0]
dim_b = shape_x[1]
res = []
if dim_a % 16 != 0:
dim_a = (dim_a // 16) * 16 + 16
res.append(dim_a)
else:
res.append(dim_a)
if dim_b % 16 != 0:
dim_b = (dim_b // 16) * 16 + 16
res.append(dim_b)
else:
res.append(dim_b)
return res
|
def pass_bot(func):
"""This decorator is deprecated, and it does nothing"""
# What this decorator did is now done by default
return func
|
def export_tripletes_from_color(hex_color):
"""<Short Description>
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
hex_triplets = [hex_color[i:i+2] for i in range(0, len(hex_color), 2)]
triplets_integer = [int(hex_triplets[i], 16)
for i in range(len(hex_triplets))]
return triplets_integer
|
def minOperations(n):
"""
In a text file, there is a single character H. Your text editor can execute
only two operations in this file: Copy All and Paste. Given a number n,
write a method that calculates the fewest number of operations needed to
result in exactly n H characters in the file.
Returns an integer
If n is impossible to achieve, returns 0
"""
if not isinstance(n, int):
return 0
op = 0
i = 2
while (i <= n):
if not (n % i):
n = int(n / i)
op += i
i = 1
i += 1
return op
|
def has_same_letter_repeated(box, times):
"""Check if box has any letter repeated number of times."""
return any(
box.count(letter) == times
for letter in box
)
|
def getOverviewLegendType(distance_heatmap_dict):
"""
Get overview legend types.
Parameters
-----------
distance_heatmap_dict : Dictionary
Distance Heatmap Dictitonary List formatted for use in visualization.
Returns
--------
overview_legend_types: List
Legend types for overview distance matrices
"""
overview_legend_types = [hd['overview_legend_type'] for hd in distance_heatmap_dict]
# get unique values in overview_legend_types
legend_types_unique = set(overview_legend_types)
overview_legend_types = list(legend_types_unique)
return overview_legend_types
|
def stringify(value):
""" Stringify a value to insert cleanly into the test DB. """
return '\'{}\''.format(value) if value else 'NULL'
|
def rayTracingPlotFileName(
key, site, telescopeModelName, sourceDistance, zenithAngle, label
):
"""
Ray tracing plot file name.
Parameters
----------
key: str
Quantity to be plotted (d80_cm, d80_deg, eff_area or eff_flen)
site: str
South or North.
telescopeModelName: str
LST-1, MST-FlashCam, ...
sourceDistance: float
Source distance (km).
zenithAngle: float
Zenith angle (deg).
label: str
Instance label.
Returns
-------
str
File name.
"""
name = "ray-tracing-{}-{}-{}-d{:.1f}-za{:.1f}".format(
site, telescopeModelName, key, sourceDistance, zenithAngle
)
name += "_{}".format(label) if label is not None else ""
name += ".pdf"
return name
|
def fromBytestoInt(b,k):
"""
Convert a bytes array to a tuple of int ranging from 0 to 256**(k-1)
"""
assert len(b)% k == 0
i = 0
ck = 0
T = ()
while i < len(b):
nb = 0
while ck < k :
nb = nb + b[i]*(256**ck)
i+=1
ck+=1
ck = 0
T = T+(nb,)
return T
|
def split_node_id(node_id):
""" split and extract collection name """
col_name = ""
key_only = ""
if isinstance(node_id, str):
key_only = node_id
splits = node_id.split("/")
if len(splits) == 2:
col_name = splits[0]
key_only = splits[1]
return col_name, key_only
|
def is_contain_chinese(check_str):
"""Check whether string contains Chinese or not.
Args:
check_str (str): String to be checked.
Return True if contains Chinese, else False.
"""
for ch in check_str:
if u'\u4e00' <= ch <= u'\u9fff':
return True
return False
|
def a1(row_index, column_index):
"""Get an A1 notation for a cell specified by its row index
and column index"""
ord_first = ord('A')
ord_last = ord('Z')
letters_count = ord_last - ord_first + 1
level, letter_index = divmod(column_index, letters_count)
letter = chr(ord_first + letter_index) * (1 + level)
number = row_index + 1
return '{letter}{number}'.format(letter=letter, number=number)
|
def vectorOFRightDirection(OFvect, FOE):
"""Returns True if OF vector is pointing away from the FOE, False otherwise."""
# Get points of optical flow vector
a1, b1, c1, d1 = OFvect
# If left side of FOE
if a1 <= FOE[0]:
if c1 <= a1:
return False
# If right side of FOE
else:
if c1 >= a1:
return False
return True
|
def subtract_Q_from_identity(Q):
"""
If Q = [
[1,2,3],
[4,5,6],
[7,8,9],
]
I - Q:
[[1,0,0] [[0,-2,-3]
[0,1,0] - Q = [-4,-4,-6]
[0,0,1]] [-7,-8,-8]]
"""
n = len(Q)
for row in range(len(Q)):
for item in range(len(Q[row])):
if row == item:
Q[row][item] = 1 - Q[row][item]
else:
Q[row][item] = -Q[row][item]
return Q
|
def _make_pretty_name(method):
"""Makes a pretty name for a function/method."""
meth_pieces = [method.__name__]
# If its an instance method attempt to tack on the class name
if hasattr(method, 'im_self') and method.im_self is not None:
try:
meth_pieces.insert(0, method.im_self.__class__.__name__)
except AttributeError:
pass
return ".".join(meth_pieces)
|
def room_url_for_room_id(roomid):
"""
room schedule url from room id
"""
template = 'https://www-sbhome1.zv.uni-wuerzburg.de/qisserver/rds?state=wplan&act=Raum&pool=Raum&raum.rgid={}'
url = template.format(roomid)
return url
|
def doi_prefix(v):
"""
Return the prefix of a DOI.
"""
parts = v.split("/")
if len(parts) == 1:
raise ValueError("invalid doi: {}".format(v))
return parts[0]
|
def getfirstbest(bests,threashold=-1):
"""
finds all the molecules that are among the best 'threashold', and stores them into a set.
The previous version of the set is passed to the function as the first variable, and the union of the two is then returned
"""
if threashold==-1:
threashold=len(bests)
b=set([])
for t in range(1,threashold+1): b|=bests[t]
return b
|
def test_line_seg_intersect(line1,line2):
"""Tests to see if two lines segments intersect. The lines are defined as:
line1 = [ p0_x, p0_y, p1_x, p1_y ]
line2 = [ p2_x, p2_y, p3_x, p3_y ]
"""
#See http://stackoverflow.com/questions/563198/how-do-you-detect-where-
#two-line-segments-intersect for algorithm details
#Read in individual point x,y positions from arguments
p0_x, p0_y, p1_x, p1_y = line1
p2_x, p2_y, p3_x, p3_y = line2
s1_x = p1_x - p0_x
s1_y = p1_y - p0_y
s2_x = p3_x - p2_x
s2_y = p3_y - p2_y
denom = (-s2_x * s1_y + s1_x * s2_y)
num_s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y))
num_t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x))
#Detect if lines are parallel or coincident
if -1e-10 < denom < 1e-10:
if abs(num_s) - abs(num_t) < 1e-5:
#Lines are coincident
return True
else:
#Lines are parallel, but not coincident
return False
s = num_s / denom
t = num_t / denom
if 0.0 <= s <= 1.0 and 0.0 <= t <= 1.0:
#Lines intersect (or meet at endpoints)
return True
else:
#Lines do not intersect
return False
|
def get_steps(x, shape):
"""
Convert a (vocab_size, steps * batch_size) array
into a [(vocab_size, batch_size)] * steps list of views
"""
steps = shape[1]
if x is None:
return [None for step in range(steps)]
xs = x.reshape(shape + (-1,))
return [xs[:, step, :] for step in range(steps)]
|
def format_nltk_inputs(input, target):
"""
Prepare NLTK inputs as tuple of dict and target
:return:
"""
input_nltk = []
for input_feat, tar in zip(input, target):
list_dict = {}
for index, feat_val in enumerate(input_feat):
index = index + 1
k = f'feat_{index}'
list_dict[k] = feat_val
input_nltk.append((list_dict, tar))
return input_nltk
|
def get_centre(bounds):
"""
Get the centre of the object from the bounding box.
"""
if len(bounds) != 6:
return [None] * 6
return [bounds[i] - (bounds[i] - bounds[i - 1]) / 2.0 for i in range(1, len(bounds), 2)]
|
def _last_build_infos_to_mock_returns(last_builds):
"""
Helper function for testing waiting for a build. Turns a series of
last_build_info dictionaries into a list suitable for returning
sequentially from requests_mock.
"""
return [{'json': {'last_build_info': build_info}}
for build_info in last_builds]
|
def get_branch_code(location_code: str) -> str:
"""
Returns branch code from normalized location code
"""
branch = location_code[:2]
return branch
|
def parse_range(entry, valid, default):
"""
parsing entries
entry - value to check
default - value if entry is invalid
valid - valid range
return - entry or default if entry is out of range
"""
if valid[0] <= entry <= valid[1]:
result = entry
else:
result = default
return result
|
def can_make_metal(i, amount, treasury, formulas):
"""Returns True if we can make amount of metal i."""
if treasury[i] >= amount:
treasury[i] -= amount
return True
elif treasury[i] >= 0:
treasury[i] -= amount
extra = -treasury[i]
metal_1, metal_2 = formulas[i]
result = (can_make_metal(metal_1, extra, treasury, formulas) and
can_make_metal(metal_2, extra, treasury, formulas))
if result:
treasury[i] += extra
return result
else:
return False
|
def cmd_list_to_string(cmds):
"""Converts list of commands into proper string for NX-API
Args:
cmds (list): ordered list of commands
Returns:
str: string of commands separated by " ; "
"""
command = ' ; '.join(cmds)
return command + ' ;'
|
def multiple_benchmark_thetas(benchmark_names):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying multiple parameter benchmarks.
Parameters
----------
benchmark_names : list of str
List of names of the benchmarks (as in `madminer.core.MadMiner.add_benchmark`)
Returns
-------
output : tuple
Input to various SampleAugmenter functions
"""
return "benchmarks", benchmark_names
|
def clean_usage(usage):
"""
Remove Duplicate weeks based on the start day of the week
:param usage:
:return:
"""
return list({week["days"][0]["dayDate"]: week for week in usage}.values())
|
def code_is_executable(estimator_code):
"""Determine if code string is executable.
:param str estimator_code: string to check.
:returns bool: True if executable
"""
try:
eval(estimator_code)
return True
except:
return False
|
def FirstActiveGeneral(activities, timepoints):
"""Given a list of temporal activities in the coded activity state from
ConvertWindowState, return the time point at which the protein is first
active (not in the 0 inactive state) or 'Not active'. Does not assume
any knowledge of the time points. Returns the 0-based index.
"""
assert len(list(activities)) == len(
list(timepoints)), "Must have same length activities and time points"
for t in range(len(list(activities))):
if not activities[t] == "0":
return str(timepoints[t])
return "Not active"
|
def _orthogonal_vector(vector):
""" Given a vector, returns a orthogonal/perpendicular vector of equal length.
Returns
------
(float, float): A vector that points in the direction orthogonal to vector.
"""
return -1 * vector[1], vector[0]
|
def remove_duplicates(oldlist):
"""
:param oldlist:
:return:
"""
newlist = []
for item in oldlist:
if item not in newlist:
newlist.append(item)
return newlist
|
def deepReverse(L):
"""reverses order of list"""
def reverseHelp(L, lst, c):
if(L == []):
return lst
if(isinstance(L[c], list)):
#if(isinstance(L[1], list)==False):
return reverseHelp(L[0], lst, 0)
else:
return reverseHelp(L[c:], [L[c]]+lst, c+1)
return reverseHelp(L, [], 0)
|
def quasilexico_key(x):
"""Returns a key suitable for a quasi-lexicographic sort [1]_.
Objects are sorted by length first, then lexicographically.
Examples
--------
>>> L = ['a', 'aa', 'b']
>>> sorted(L, key=quasilexico_key)
['a', 'b', 'aa']
References
----------
.. [1] Calude, Cristian (1994). Information and randomness. An algorithmic
perspective. EATCS Monographs on Theoretical Computer Science.
Springer-Verlag. p. 1.
"""
return (len(x), x)
|
def as_bytes(value, length):
"""Turn an integer into a byte array"""
return value.to_bytes(length, byteorder="big", signed=False)
|
def is_legal(letters):
"""
:param letters:str, the string that user inputs
:return:bool, letters is legal type or not
"""
if len(letters) == 7: # Legal input combines with four characters and three empty spaces
if letters[1] == letters[3] == letters[5] == ' ':
if letters[0].isalpha() and letters[2].isalpha() and letters[4].isalpha() and letters[6].isalpha():
return True
else:
return False
|
def both_args_present_or_not(lhs=None, rhs=None):
""" function is used to determine, that both arguments
are either passsed or excluded """
return all([lhs, rhs]) or not any([lhs, rhs])
|
def list_reduce(fn, lst, dftl):
"""Implementation of list_reduce."""
res = dftl
for elem in lst:
res = fn(res, elem)
return res
|
def avatar(author):
"""
Cites the creator of botjack's avatar.
-----
:param <author>: <class 'str'> ; author of the command
"""
msg = f"Hello {author}.\nMy avatar was made by: ScarfyAce. Please check their reddit:\n" + \
"https://www.reddit.com/user/ScarfyAce/"
return msg
|
def slope(p1, p2):
"""Estimate the slope between 2 points.
:param p1: (tuple) first point as (x1, y1)
:param p2: (tuple) second point as (x2, y2)
:returns: float value
"""
# test types
try:
x1 = float(p1[0])
y1 = float(p1[1])
x2 = float(p2[0])
y2 = float(p2[1])
except:
raise
# test values (p1 and p2 must be different)
if x1 == x2 and y1 == y2:
raise Exception
x_diff = x2 - x1
y_diff = y2 - y1
return y_diff / x_diff
|
def bubble_sort(arr):
"""
Exchange sort (bubble sort)
1. Take the first element each time and compare it with the next element. If the former is larger than the latter,
switch positions and compare with the latter. If the latter bit is greater, it is not exchanged.
Then the next bit is compared with the next bit until the last indexed element. At this time,
the last indexed element is the largest, and it is also the element that will never be moved after sorting.
That is, L[n-i:n] is arranged so as not to move.
2. The above rule loops for n-1 rounds, then the sorting is complete.
Average Time Complexity: O(n**2)
Space Complexity: O(1)
stability: Yes
Best Time Complexity: O(n)
Worst Time Complexity: O(n**2)
:param arr:
:return:
"""
for i in range(len(arr)-1):
for j in range(len(arr)-1-i):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
|
def app_models(raw_models):
"""
For a list of raw models return the list of the corresponding app models.
"""
return [model.get_app_model() if model is not None else None for model in raw_models]
|
def d4(dx, fc, i):
""" fourth-order centered derivative at index i """
D = -fc[i+2] + 8.0*fc[i+1] - 8.0*fc[i-1] + fc[i-2]
D = D/(12.0*dx)
return D
|
def schema_id(origin_did: str, name: str, version: str) -> str:
"""
Return schema identifier for input origin DID, schema name, and schema version.
:param origin_did: DID of schema originator
:param name: schema name
:param version: schema version
:return: schema identifier
"""
return '{}:2:{}:{}'.format(origin_did, name, version)
|
def denormalize(x, min, max):
"""
Data min-max denormalization:
"""
return x * (max - min) + min
|
def gen_bom_list(mod_list):
"""generate BOM list"""
mod_list.sort(key=lambda desig: desig[0]) # sort by desig_sign
return [bom_line[1] for bom_line in mod_list]
|
def jaccard(seq1, seq2):
"""
Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 1 means equal, and 0 totally different.
"""
set1, set2 = set(seq1), set(seq2)
return len(set1 & set2) / float(len(set1 | set2))
|
def similarity(dx1, dy1, dz1, d1, d2):
"""
uses the rules of similarity in geometry to calculate lengths
of edges of a pyramid similar to another pyramid
"""
dx2 = d2 * dx1 / d1
dy2 = d2 * dy1 / d1
dz2 = d2 * dz1 / d1
return dx2, dy2, dz2
|
def lib_utils_oo_dict_to_keqv_list(data):
"""Take a dict and return a list of k=v pairs
Input data:
{'a': 1, 'b': 2}
Return data:
['a=1', 'b=2']
"""
return ['='.join(str(e) for e in x) for x in data.items()]
|
def points_to_coords(points, level):
"""Transform from [-1, 1] to [0, 2^l]"""
return (2**level) * (points*0.5 + 0.5)
|
def PVIFA(i,n,m=1):
"""
interest
years
optional payments per year"
"""
PVIFA = (1 - (1 / ((1 + i / m)**(m * n)))) / i
return PVIFA
|
def process_chunk_info(line):
"""
Processes a unified diff chunk header and returns a tuple indication the start and length of the deletion and
addition hunks.
:param line: Unified diff chunk marker, beginning with '@@'
:type line: str
:return: a 4-tuple of deletion start, deletion length, addition start, addition length
:rtype: tuple[int]
"""
parts = line.split(' ')
del_info = parts[1][1:]
add_info = parts[2][1:]
del_start, del_length = map(int, del_info.split(',')) if ',' in del_info else (int(del_info), 1)
add_start, add_length = map(int, add_info.split(',')) if ',' in add_info else (int(add_info), 1)
return del_start, del_length, add_start, add_length
|
def get_topic_for_path(channel, chan_path_tuple):
"""
Given channel (dict) that contains a hierary of TopicNode dicts, we use the
walk the path given in `chan_path_tuple` to find the corresponding TopicNode.
"""
assert chan_path_tuple[0] == channel['dirname'], 'Wrong channeldir'
chan_path_list = list(chan_path_tuple)
chan_path_list.pop(0) # skip the channel name
if len(chan_path_list) == 0:
return channel
current = channel
for subtopic in chan_path_list:
current = list(filter(lambda d: 'dirname' in d and d['dirname'] == subtopic, current['children']))[0]
return current
|
def GetClosestSupportedMotionBuilderVersion(Version: int):
"""
Get the closest MotionBuilder version that is supported
"""
if Version < 2018:
return 2018
if Version == 2021:
return 2022
return Version
|
def organize_array_by_rows(unformatted_array, num_cols):
"""Take unformatted array and make grid array"""
num_rows = int(len(unformatted_array) / num_cols)
array = []
for row in range(num_rows):
array.append(unformatted_array[row * num_cols:(row + 1) * num_cols])
return array
|
def list_devices_to_string(list_item):
"""Convert cfg devices into comma split format.
Args:
list_item (list): list of devices, e.g. [], [1], ["1"], [1,2], ...
Returns:
devices (string): comma split devices
"""
return ",".join(str(i) for i in list_item)
|
def update_item_tuple(data, index, value):
"""
Update the value of an item in a tuple.
Args:
data (tuple): The tuple with item to update.
index (int): The index of the item to update.
value (various): The new value for the item to be updated.
Returns:
tuple: A new tuple with the updated value.
"""
list_data = list(data)
list_data[index] = value
new_tuple = tuple(list_data)
return new_tuple
|
def separate_tour_and_o(row):
"""
The tour line typically contains contig list like:
tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900-
This function separates the names from the orientations.
"""
tour = []
tour_o = []
for contig in row.split():
if contig[-1] in ("+", "-", "?"):
tour.append(contig[:-1])
tour_o.append(contig[-1])
else: # Unoriented
tour.append(contig)
tour_o.append("?")
return tour, tour_o
|
def _default_kwargs_split_fn(kwargs):
"""Default `kwargs` `dict` getter."""
return (kwargs.get('distribution_kwargs', {}),
kwargs.get('bijector_kwargs', {}))
|
def egg_name(name, version, build):
"""
Return the egg filename (including the .egg extension) for the given
arguments
"""
return "{0}-{1}-{2}.egg".format(name, version, build)
|
def dash_to_underscore(obj):
"""
Configuration data is not underscored
:param obj: The object to convert
:return:The converted object
"""
if isinstance(obj, list):
ret_obj = []
for item in obj:
ret_obj.append(dash_to_underscore(item))
elif isinstance(obj, dict):
ret_obj = dict()
for key in obj.keys():
new_key = key.replace('-', '_')
ret_obj[new_key] = dash_to_underscore(obj[key])
else:
ret_obj = obj
return ret_obj
|
def maybe_zero(x: float, tol: float) -> float:
"""Turn almost zeros to actual zeros"""
if abs(x) < tol:
return 0
return x
|
def _Theta(x, y, eps):
"""Theta tmp
Args:
x:
y:
eps:
Returns:
int: 0 or 1.
"""
sm = 0
for k in range(len(x)):
sm += (x[k]-y[k])**2
if sm > eps:
return 0
return 1
|
def safe_encode(s, coding='utf-8', errors='surrogateescape'):
"""encode str to bytes, with round-tripping "invalid" bytes"""
return s.encode(coding, errors)
|
def join_path_segments(*args):
"""
Join multiple lists of path segments together, intelligently
handling path segments borders to preserve intended slashes of the
final constructed path.
This function is not encoding aware. It doesn't test for, or change,
the encoding of path segments it is passed.
Examples:
join_path_segments(['a'], ['b']) == ['a','b']
join_path_segments(['a',''], ['b']) == ['a','b']
join_path_segments(['a'], ['','b']) == ['a','b']
join_path_segments(['a',''], ['','b']) == ['a','','b']
join_path_segments(['a','b'], ['c','d']) == ['a','b','c','d']
Returns: A list containing the joined path segments.
"""
finals = []
for segments in args:
if not segments or segments == ['']:
continue
elif not finals:
finals.extend(segments)
else:
# Example #1: ['a',''] + ['b'] == ['a','b']
# Example #2: ['a',''] + ['','b'] == ['a','','b']
if finals[-1] == '' and (segments[0] != '' or len(segments) > 1):
finals.pop(-1)
# Example: ['a'] + ['','b'] == ['a','b']
elif finals[-1] != '' and segments[0] == '' and len(segments) > 1:
segments = segments[1:]
finals.extend(segments)
return finals
|
def _check_do_transform(df, reference_im, affine_obj):
"""Check whether or not a transformation should be performed."""
try:
crs = getattr(df, "crs")
except AttributeError:
return False # if it doesn't have a CRS attribute
if not crs:
return False # return False for do_transform if crs is falsey
elif crs and (reference_im is not None or affine_obj is not None):
# if the input has a CRS and another obj was provided for xforming
return True
|
def _point_in_bbox(point, bounds):
"""
valid whether the point is inside the bounding box
"""
return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2]
or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])
|
def suffixes(word):
"""Returns the list of propper suffixes of a word
:param word: the word
:type word: str
:rtype: list
.. versionadded: 0.9.8"""
return [word[i:] for i in range(1, len(word))]
|
def remove_prefix_from_string(prefix, string):
"""Removes a prefix from a string if it exists. Otherwise returns the unmodified string."""
if string.startswith(prefix):
string = string[len(prefix):]
return string
|
def logged_in(cookie_string, prefix='', rconn=None):
"""Check for a valid cookie, if logged in, return user_id
If not, return None."""
if rconn is None:
return
if (not cookie_string) or (cookie_string == "noaccess"):
return
cookiekey = prefix+cookie_string
try:
if not rconn.exists(cookiekey):
return
user_info = rconn.lrange(cookiekey, 0, -1)
# user_info is a list of binary values
# user_info[0] is user id
# user_info[1] is a random number, added to input pin form and checked on submission
# user_info[2] is a random number between 1 and 6, sets which pair of PIN numbers to request
user_id = int(user_info[0].decode('utf-8'))
# and update expire after two hours
rconn.expire(cookiekey, 7200)
except:
return
return user_id
|
def _is_regular_token(token):
""" Checks if a token is regular (does not contain regex symbols).
Args:
token (`str`): the token to be tested
Returns:
bool: whether or not the token is regular
"""
token_is_regular = True
if not token.isalnum():
# Remove escaped characters
candidate = token.replace('/', '')
candidate = candidate.replace('"', '')
candidate = candidate.replace(r'\^', '')
candidate = candidate.replace('\'', '')
candidate = candidate.replace('-', '')
candidate = candidate.replace('^', '')
candidate = candidate.replace('_', '')
candidate = candidate.replace(':', '')
candidate = candidate.replace(',', '')
candidate = candidate.replace(r'\.', '')
candidate = candidate.replace(r'\|', '')
token_is_regular = candidate.isalnum() or candidate == ''
return token_is_regular
|
def __fix_misspelled_words__(text):
"""
Fixes the misspelled words in the specified text
(uses predefined misspelled dictionary)
:param text: The text to be fixed
:return: the fixed text
"""
mispelled_dict = {'proflie': 'profile'}
for word in mispelled_dict.keys():
text = text.replace(word, mispelled_dict[word])
return text
|
def keypoint_scale(keypoint, scale_x, scale_y, **params):
"""Scales a keypoint by scale_x and scale_y."""
x, y, a, s = keypoint
return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
|
def get_threat_component(components, threat_type):
"""
Gets a certain threat component out a list of components
Args:
components: List of threat components
threat_type: Type of threat we are looking for
Returns: Either the component that we asked for or None
"""
for component in components:
if component.get('name') == threat_type:
return component
else:
return None
|
def contains_active_student(node_name, adjancy, roles, keep):
"""
Finds if there is a student in the children of `node_name`
Arguments
---------
node_name: str
Name of the current node
adjancy: dict(str: [str])
Adjancy list of agents
roles: dict(str: str)
Role of the agents
Return
------
True or False
"""
if node_name in keep:
return True
for child_name in adjancy[node_name]:
if contains_active_student(child_name, adjancy, roles, keep):
return True
return False
|
def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices
|
def new_confirmed_case_row(region_name, cases, coords):
"""Creates a row object. Separate to avoid typos"""
return {'name': region_name, 'cases': cases, 'coord': coords}
|
def clean_end_str(end_str, source_str):
"""Remove the specified at the end of the string"""
tem1 = end_str[::-1]
tem2 = source_str[::-1]
return tem2[len(tem1):len(tem2)][::-1]
|
def to3(pnts):
"""
Convert homogeneous coordinates to plain 3D coordinates.
It scales the x, y and z values by the w value.
Aruments:
pnts: A sequence of 4-tuples (x,y,z,w)
Returns:
A list of 3-tuples (x,y,z)
"""
return [(p[0] / p[3], p[1] / p[3], p[2] / p[3]) for p in pnts]
|
def first_index(L, value):
"""
Find the first occurrence of value in L.
"""
val = next(iter(filter(lambda x: x[1] == value, enumerate(L))))
if val:
return(val[0])
else:
raise(ValueError("{} is not in the list.".format(value)))
|
def productOfAdjacents(i, n, number):
"""Returns the product of n adjacent digits starting at i"""
"""Takes in the number as a string"""
product = 1
for i in range (i, i+n):
product *= int(number[i])
return product
|
def fun_lr(lr, milestones, gamma, iters):
"""MultiStep learning rate"""
for milestone in milestones:
lr *= gamma if iters >= milestone else 1.0
return lr
|
def mean(num_1st):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_1st : list
List of numbers to calculate the averge of
Returns
--------
The average/mean of num_1st
avgMean
Examples
--------
>>> mean([1,2,3,4,5])
3.0
"""
Sum = sum(num_1st)
N = len(num_1st)
avgMean = float(Sum/N)
return avgMean
|
def nested_sum(t):
"""Computes the total of all numbers in a list of lists.
t: list of list of numbers
returns: number
"""
total = 0
for nested in t:
total += sum(nested)
return total
|
def generate_block(name, abstract, authors, contributors, types, tags, category,
img_url, article_url=None, deployment_url=None):
"""Generate json documentation for a training program block.
If both `article_url` and `deployment_url` are None, the block is assumed
to be a container for further sub-blocks (i.e. has an "open" button).
Otherwise, either one of or both `article_url` and `deployment_url` must
be provided.
"""
block = {
"name": name,
"abstract": abstract,
"authors": authors,
"contributors": contributors,
"types": types,
"tags": tags,
"category": category,
"imageUrl": img_url
}
if article_url is None and deployment_url is None:
block["parts"] = []
if deployment_url is not None:
block["deploymentUrl"] = deployment_url
if article_url is not None:
block["articleUrl"] = article_url
return block
|
def ndec(x, max=3): # --DC
"""RETURNS # OF DECIMAL PLACES IN A NUMBER"""
for n in range(max, 0, -1):
if round(x, n) != round(x, n-1):
return n
return 0
|
def plain_subject_predicate(line):
"""
Converts spo format into something approximately human readable.
:param line:
:return:
"""
if '22-rdf-syntax-ns#' in line:
return line.split('/')[-1].split('#')[-1]
else:
return line.split('/')[-1]
|
def intersperse(lst, sep):
""" #### Insert a separator between every two adjacent items of the list.
Input list and separator
return list with separator between every two adjacent items
"""
result = [sep] * (len(lst) * 2 - 1)
result[0::2] = lst
return result
|
def is_remote_list(values):
"""Check if list corresponds to a backend formatted collection of dicts
"""
for v in values:
if not isinstance(v, dict):
return False
if "@type" not in v.keys():
return False
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.