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... |
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':
... |
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... |
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 =... |
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
# Crea... |
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... |
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 considerati... |
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.... |
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_... |
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.
Re... |
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 ... |
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: st... |
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
... |
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... |
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) ... |
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
el... |
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]... |
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.__clas... |
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([])
... |
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-segment... |
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(s... |
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 = ... |
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... |
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
... |
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]
... |
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_ben... |
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. Return... |
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]]+... |
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... |
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(... |
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[... |
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... |
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 ... |
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 &... |
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, addi... |
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 =... |
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... |
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 ("... |
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):
... |
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 pas... |
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_transfo... |
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 n... |
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():
# Remov... |
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.r... |
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 i... |
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 t... |
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 pnt... |
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)
a... |
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 f... |
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.