dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_message_type(packet):
_, _, body, _ = parse_packet(decrypt_message(packet))
message = body.split('$;')[0]
return message
def get_packet_type(packet):
packet_type, _, _, _ = parse_packet(decrypt_message(packet))
return packet_type
def handle_reciving_data(server_data, packet_type, message, ad... | The main task of the code is to process network packets by analyzing message types, validating data integrity via checksums, managing client connections (join/disconnect), enforcing access control (authentication, username uniqueness, server capacity), and routing messages (chat invitations, user lists, file forwarding... | def analise_data(data, addr):
KEY = 'network'
msg = get_message_type(data)
pkt_type = get_packet_type(data)
msg = handle_reciving_data(data, pkt_type, msg, addr)
# check if the checksum is correct
if recalculate_checksum(data) != get_checksum(data):
msg = ""
data = saved_data
p... |
def get_packet_type(packet):
packet_type, _, _, _ = parse_packet(decrypt_packet(packet))
return packet_type
def get_data_size(packet):
_, _, body, _ = parse_packet(decrypt_packet(packet))
size = sys.getsizeof(body)
return size
def get_message_type(packet):
print(f'PACKET RECEIVED[Ionut Client] <... | This function handles server-client communication by receiving and processing data packets, calculating throughput/RTT, managing chat invitations, file transfers, user lists, and error responses. It uses global variables for timing, processes packet types, and triggers actions like chat threads or file saves based on m... | def handle_server():
global t1
global t2
global t3
global send_time
global receive_time
connected = True
t1 = time.time()
while connected:
t2 = time.time()
server_data = client.recv(SIZE)
if get_packet_type(server_data) == 'DATA':
... |
def analise_data(data, addr):
KEY = 'network'
msg = get_message_type(data)
pkt_type = get_packet_type(data)
msg = handle_reciving_data(data, pkt_type, msg, addr)
# check if the checksum is correct
if recalculate_checksum(data) != get_checksum(data):
msg = ""
data = saved_data
p... | The function processes client messages by determining their type, sending appropriate responses (like user lists, access grants, or error messages), and terminating the connection after handling each message. It breaks the loop upon specific conditions such as invitations, disconnect requests, or successful message pro... | def handle_client(data, addr):
packet_type, response = analise_data(data, addr)
connected = True
while connected:
# checks the type of message recieved
message = response
packet_type = packet_type
# if an invitation has been sent we brake out of the loop
if message =... |
def build_words_graph(data):
words = set()
POSS = set()
for dg in data:
for (head, headPOS),rel, (dep, depPOS) in dg.triples():
words.add(head)
words.add(dep)
POSS.add(headPOS)
POSS.add(depPOS)
return words, POSS
def getStringToIdx(words, tags):
... | The code trains a model on a dataset using word and POS tag mappings, evaluates it on test data, calculates partial and cumulative accuracy percentages, and visualizes these metrics with a plot showing both curves for comparison. | def main():
words, POSS = build_words_graph(train_data)
stringToIdx, lenWords, lenTags = getStringToIdx(words, POSS)
w = trainModel(train_data, stringToIdx)
testModel(test_data, w, stringToIdx)
print(partialPercent)
print(percentage)
partial, = plt.plot(range(len(partialPercent)), partialPer... |
def parse_file(filein, threshold):
with open(filein) as f:
lines = f.readlines()
header = lines.pop(0).strip()
pixelstats = lines.pop(0).strip()
print("Header: ", header)
print("Pixelstats: ", pixelstats)
counter = 0 # For running on mini dataset for debugging
events = []
sumCh... | The main task of the code is to analyze and compare two datasets by parsing event data, aligning events, and generating visualizations. It plots cluster size vs. theta angle for both datasets, creates delta cluster size plots, and generates histograms for parameters like sumCharge, xSpan, ySpan, and Area. The code chec... | def main():
(arr_events, cluster_truth, sumCharge, xSpan, ySpan, Area, theta_angle) = parse_file(filein="../Runs/"+filename+".out", threshold=10)
print("Done analyzing dataset 1.")
print(cluster_truth[-1], Area[-1])
(arr_events2, cluster_truth2, sumCharge2, xSpan2, ySpan2, Area2, theta_angle2) = parse_... |
def display_welcome(self):
print('Welcome to Robots vs Dinosaurs.')
def battle(self):
while len(self.herd.dinosaurs) > 0 and len(self.fleet.robots) > 0:
dice_roll = random.randint(1, 10)
if dice_roll % 2 == 0:
self.dino_turn()
if len(self.fleet.rob... | The code defines a method `run_game` that executes three key steps in a game: displaying a welcome message, initiating a battle, and showing the winners. Its main task is to orchestrate the game flow by sequentially calling these methods, ensuring the game starts, progresses through combat, and concludes by announcing ... | def run_game(self):
self.display_welcome()
self.battle()
self.display_winners() |
def print_order_menu():
ui.c_Print(orderMenu)
def prompt_order_menu():
user_input = ui.prompt_User(prompt_text, order_menu_options)
return user_input
def add_order(state):
ui.clear_Term()
new_row = ui.prompt_row_for_order(state["customer"], state["courier"])
db.new_order(
conn,
s... | The main task of the code is to manage order operations via a menu-driven interface. It loops to display options, processes user inputs (show, add, basket, change, return), and updates the transaction state accordingly. Functions like `add_order`, `basket_menu`, and `change_order_status` modify the state, while "show" ... | def order_menu(state):
while True:
ui.clear_Term()
print_order_menu()
user_input = prompt_order_menu()
if user_input == "show":
ui.clear_Term()
ui.print_table(state["transaction"], "transaction")
ui.prompt_User("Press Enter")
elif user_inpu... |
def print_Main_Menu():
ui.c_Print(mainMenu)
def prompt_Main_Menu():
user_input = ui.prompt_User(prompt_text, main_Menu_options)
return user_input
def sub_menu(state, table_name):
while True:
ui.clear_Term()
print_sub_menu(table_name)
user_input = prompt_sub_menu()
if user... | The main task of the code is to serve as a main menu loop for a system, allowing users to navigate options like managing couriers, products, customers, orders, and save/load data. It updates the system state based on user input and exits when "exit" is selected. | def main_menu(state):
while True:
ui.clear_Term()
print_Main_Menu()
user_input = prompt_Main_Menu()
if (
user_input == "courier"
or user_input == "product"
or user_input == "customer"
):
state = sub_menu(state, user_input)
... |
def initialize_weights(self, shape):
"""Initialize the weights of the model using the given shape."""
# Our function is not convex, so initialization with zero is not helpful
return he_weights_initialization(shape)
def _learn_using_SGD(self, y, tx, w, batch_size, fn, gamma, lambda_, regularizati... | The code trains a machine learning model using gradient descent (GD) or stochastic gradient descent (SGD), depending on the batch size. It optimizes model weights by minimizing a loss function computed via the provided `fn` method, incorporating regularization (if specified). The training tracks losses and test accurac... | def train(self, y, tx, y_test, tx_test, fn, max_iters=8000, gamma=1, batch_size=None, all_output=False,
reg_lambda=None, regularization=None, gamma_decay=None, reinitialize_weights=False):
"""
Trains the model.
Args:
y: Labels given for the training dataset
... |
def fen_to_matrix(fen):
#fen = fen.split(' ')[0] # splicing out non-matrix part of fen
fen = fen.split(' ')
players_turn = fen[1]
fen = fen[0]
board_fen = [fen]
split_board = board_fen [0].split ('/')
a1_perspective_board = []
a8_perspective_board = []
for row in reversed(split_board) :
new_row... | The function evaluates a chess board state from a given FEN string, calculating the score difference between the current player and their opponent. It converts the FEN to matrices (a1 or a8 perspective), identifies piece positions, computes scores for both sides using `evaluate_one_side`, and returns the net score (our... | def evaluate(fen, Parameters, maximizing_player=True):
# Note: fen to matrix makes a matrix from black's perspective (a8 is 00) if the fen is black's move
# Note: fen to matrix makes a matrix from white's perspective (a1 is 00) if the fen is white's move
a1_matrix, a8_matrix, opponents_turn = fen_to_matrix(fen)... |
def evaluate(fen, Parameters, maximizing_player=True):
# Note: fen to matrix makes a matrix from black's perspective (a8 is 00) if the fen is black's move
# Note: fen to matrix makes a matrix from white's perspective (a1 is 00) if the fen is white's move
a1_matrix, a8_matrix, opponents_turn = fen_to_matrix(fen)... | This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move in a chess game. It evaluates board positions recursively, considering material differences and avoiding draws by adjusting evaluation scores. The maximizing player (White) seeks to maximize the score, while the minimiz... | def minimax_alpha_beta(board, depth, alpha, beta, maximizing_player, parameters):
if depth == 0 or board.is_game_over():
not_maximizing = not maximizing_player
return evaluate(board.fen(), parameters, not_maximizing), None
if maximizing_player: # White is maximising player
max_eval = f... |
def load(self, file, device):
x1, x2, edge1, g1, edge2, g2, train_set, eval_set, test_set = torch.load(file)
self.x1, self.edge1, self.g1 = x1.to(device), edge1.to(device), g1
self.x2, self.edge2, self.g2 = x2.to(device), edge2.to(device), g2
self.train_set, self.eval_set, self.test_set ... | The main task of the code is to initialize an object that either loads preprocessed data from a file or processes and saves new data based on file existence. It sets random seeds for reproducibility, constructs a file path using parameters, checks if the file exists, and uses `self.load()` or `self.process()`/`self.sav... | def __init__(self, path, embs, rate=0.3, seed=1, device='cuda', rev_edge=True):
self.path = path
self.rate = rate
self.seed = seed
self.embs = embs
self.device = device
self.rev_edge = rev_edge
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
t... |
def _most_common_label(self, y):
counter = Counter(y)
value = counter.most_common(1)[0][0]
return value
def _best_split(self, X, y, feat_idxs):
# Initializes a variable to keep track of the best information gain.
best_gain = -1
# Initialize variables for best feature inde... | The function `_grow_tree` recursively constructs a decision tree by selecting random features, determining the optimal split, and creating child nodes. It halts when reaching maximum depth, encountering a pure node, or having insufficient samples, returning a leaf node with the most common label. If splitting continues... | def _grow_tree(self, X, y, depth = 0): # recursive method responsible for growing the decision tree.
n_samples, n_feats = X.shape # number of samples (rows) and features in the current node
n_labels = len(np.unique(y)) #represents the number of unique labels in the current node.
# che... |
def _create_clusters(self, centroids):
"""
Assign each sample to the closest centroids.
Parameters:
- centroids (list): List of cluster centroids.
Returns:
- list: List of clusters, where each cluster contains indices of samples.
"""
clusters = [[] for _... | The code performs KMeans clustering by initializing centroids, iteratively assigning data points to the nearest centroid, updating centroids as cluster means, and repeating until convergence. It returns predicted cluster labels for each data point. | def predict(self, X):
"""
Perform KMeans clustering on input data.
Parameters:
- X (numpy array): Input data.
Returns:
- numpy array: Predicted cluster labels for each data point.
"""
self.X = X
self.n_samples, self.n_features = X.shape
... |
def _initialize_centroids(self):
"""
Initialize centroids using KMeans++ algorithm.
KMeans++ employs a probabilistic approach to select centroids, ensuring a more even spread of initial cluster representatives in the feature space
Returns:
- list: List of cluster centroids.
... | The code performs KMeans++ clustering by initializing centroids using the KMeans++ algorithm, iteratively updating centroids as the mean of assigned clusters, and assigning data points to the nearest centroid. It returns predicted cluster labels after convergence or early stopping when centroid updates cease to change. | def predict(self, X):
"""
Perform KMeans++ clustering on input data.
Parameters:
- X (numpy array): Input data.
Returns:
- numpy array: Predicted cluster labels for each data point.
"""
self.X = X
self.n_samples, self.n_features = X.shape
... |
def _get_neighbours(self, sample_i):
"""
Get neighboring points (within distance of eps) for a given sample.
Parameters:
- sample_i: Index of the sample for which neighbors need to be found.
Returns:
- neighbours: Array of indices of neighboring samples.
"""
... | This code implements the DBSCAN clustering algorithm by fitting the model to input data, identifying core points with sufficient neighbors, expanding clusters from these points, and assigning cluster labels to each sample. It iterates through all data points, checks for core points meeting the minimum neighbor threshol... | def fit_predict(self, X):
"""
Fit the DBSCAN model to the data and return cluster labels.
Parameters:
- X: Input data (numpy array).
Returns:
- cluster_labels: Array of cluster labels for each sample.
"""
self.X = X
self.clusters = [] # List cont... |
def random_brain():
# 24 - 4
lay1 = np.random.uniform(-1,1,(24,4))
add1 = np.random.uniform(-1,1,(1,4))
return [lay1,add1]
def run_game(brain):
states = []
size = 41
board = new_board(size)
moves = 100
score = 0
while moves > 0:
moves = moves - 1
score ... | The code implements a simple genetic algorithm to evolve neural networks (brains) for a game. It initializes a population of random brains, evaluates their performance, selects top-performing brains, introduces mutations, and generates new generations over a specified number of iterations (gens). The best score from ea... | def basic_sim(pop,gens):
best_of_gen = []
pop_brains = [random_brain() for i in range(pop)]
pop_games = [run_game(brain) for brain in pop_brains]
pop_games = sorted(pop_games, reverse = True, key=lambda x: x[0])
top_percent = 0.05
rand_percent = 0.4
top_nums = int(top_percent * p... |
def multi_mutate(brains, children):
out = brains
for i in range(len(brains)):
brain = brains[i]
for i in range(children):
new_brain = deepcopy(brain)
new_brain.lay1.weights += np.random.randn(16, 24) * np.random.randn(16, 24)
#new_brain.lay1.biases += 0.01 *... | This code implements an evolutionary learning algorithm where neural networks (brains) are trained over multiple generations. Each generation evaluates brains through trials, selects top-performing networks, mutates them, and evolves the population toward better performance. The process tracks best scores, saves top br... | def prog_learn(networks,gens,best=None):
save_rate = 10
trials = 10
top_brains = int(networks/10)
if best == None:
trial_brains = [Brain() for i in range(networks)]
else:
trial_brains = multi_mutate([best], networks-1)
output = []
for i in range(gens):
g... |
def randombrain(population): #random networks
brains=[]
for i in range(population):
net1=emptymatrix(14,16) #16 inputs
net2=emptymatrix(4,14) #4 outputs
for x in range(net1.shape[0]):
for y in range(net1.shape[1]):
net1[x,y]=random.randint(-100,100)
... | The main task of the code is to evolve the best brain over multiple generations. It initializes a population of random brains, evaluates each brain's performance in a game, selects the top-performing brain, and evolves a new population of brains based on it. This iterative process repeats for a specified number of gene... | def play(pop,gens,brain):
#brains=evolve(pop,brain)
brains=randombrain(pop)
for i in range(gens):
print('\nGeneration'+str(i+1)+'\n')
scores=[]
for brain in brains:
scores.append(game(brain))
bestnum=scores.index(max(scores))
bestbrain=brains[bestnum]
... |
def read_modbus_data_inverter(self):
inverter_data = self.read_holding_registers(unit=self._address, address=40071, count=38)
if not inverter_data.isError():
decoder = BinaryPayloadDecoder.fromRegisters(
inverter_data.registers, byteorder=Endian.Big
)
... | The main task of the code is to read Modbus data from multiple devices, including an inverter, three meters, storage, and two batteries, by calling their respective methods. It returns `True` only if all data-read operations succeed, using logical `and` to ensure all methods return valid results. This function coordina... | def read_modbus_data(self):
return (
self.read_modbus_data_inverter()
and self.read_modbus_data_meter1()
and self.read_modbus_data_meter2()
and self.read_modbus_data_meter3()
and self.read_modbus_data_storage()
and self.read_modbus_data_bat... |
def isNonNegativeInt(s):
try:
i = int(s)
return i>=0
except:
return False
def printMatrix(matrix):
for i in range(matrix.shape[0]):
print(','.join(map(str,np.round(matrix[i],4))))
def weightedAdjacencyMatrix(df, N):
matrix = np.zeros((N,N))
for i in range(N):
... | The main task of the code is to process command-line arguments, validate inputs, and compute specific graph-related matrices (weighted adjacency, diagonal degree, or Laplacian norm) from a CSV dataset based on a specified goal. It reads a file, checks parameters like `k` and the goal type, and outputs the corresponding... | def main():
#Check if we have the right amount of args
numOfArgs = len(sys.argv)
assert numOfArgs==4, "Incorrect number of arguments"
#Check if k>=0 and type(k)=int
assert isNonNegativeInt(sys.argv[1]), "'k' is not a non-negative int"
k = int(sys.argv[1])
file_name = sys.argv[3]
... |
def dicts_to_mats(self, alphabetize=True):
"""Description:
Central to many functions. Generates numpy arrays for S, lb, ub, and b. Also generates lists for
named reactions and named metabolites.
Input:
alphabetize (boolean, optional): Often assumed to be true, orders named reactions and metabolites
Ou... | The function generates warmup vectors for coordinate direction hit-and-run sampling in flux balance analysis. It creates feasible reaction flux points by optimizing constrained linear programs with Gurobi, iteratively sampling at varying flux levels, removing duplicates, and ensuring thermodynamic feasibility. The outp... | def generate_warmup_gb_pinch(self, max_search_number, sampling_levels, pinch_tol=1e-6, pinch_1_norm=None,
repeat_basis=1,
points_save_path="", model_save_path="",
required_rank=np.inf, rxn_penalty_vec=None, unique_vector_threshold_exponent=9,
trans_NS=None, rxn_scan=False,
*... |
def dicts_to_mats(self, alphabetize=True):
"""Description:
Central to many functions. Generates numpy arrays for S, lb, ub, and b. Also generates lists for
named reactions and named metabolites.
Input:
alphabetize (boolean, optional): Often assumed to be true, orders named reactions and metabolites
Ou... | The code generates warmup vectors for coordinate direction hit-and-run sampling in metabolic flux analysis. It creates a set of thermodynamically feasible flux points by solving linear programs with random objectives, ensuring linear independence and constraint adherence. The vectors are sampled at varying flux levels ... | def generate_warmup_gb_pinch_scan_br(self, max_search_number, sampling_levels, biomass_values,
biomass_reaction_name, pinch_tol=1e-6, pinch_1_norm=None,
repeat_basis=1,
points_save_path="", model_save_path="",
required_rank=np.inf, rxn_penalty_vec=None, unique_vector_threshol... |
def dicts_to_mats(self, alphabetize=True):
"""Description:
Central to many functions. Generates numpy arrays for S, lb, ub, and b. Also generates lists for
named reactions and named metabolites.
Input:
alphabetize (boolean, optional): Often assumed to be true, orders named reactions and metabolites
Ou... | The main task of the code is to generate thermodynamically feasible flux points using a biased hit-and-run sampling method, constrained by gene expression data (RPS values) and thermodynamic limitations. It samples points within a defined flux space, ensuring adherence to reaction bounds, thermodynamic constraints, and... | def HRSampler_gene_bias_lincomb_pinch(self, origin_and_warmup_points, number_of_points, stepsPerPoint, RPS,
max_sampling_level, pinch_tol=1e-6,
gene_penalty_mod=1, thermo_const=None, rxn_penalty_vec=None, term_val=1e5,
print_percent=True, print_error=True, **kwargs):
"""Description... |
def get_next_indexes(current_index, n, forbidden=None):
"""Get the next indexes on along the x-axis where queens are
non-attacking.
Args:
current_index (int): The current index where a queen has been placed.
n (int): number of queens. Same as size of chessboard.
forbidden (set, opti... | The function `find_queens(n)` solves the N-Queens problem by finding all valid configurations where `n` queens can be placed on an `n x n` chessboard without attacking each other. It uses backtracking to explore possible positions, generating forbidden positions for each queen placement to avoid conflicts. The results ... | def find_queens(n):
"""Find the positions of the non-attacking queens"""
paths = []
for index in range(n):
next_indexes = get_next_indexes(index, n)
forbidden = gen_forbidden(index, 1, n)
paths.extend(find_paths(next_indexes, forbidden, 2, n, [index]))
for path in paths:
... |
def initialize_phase_one(f_1, f_3, A_f3, g_list):
G = precompute(g_list)
x_list = generate_binaries([[0], [1]], len(g_list)-1)
A_hg = [0] * (2 ** (len(g_list) - 1))
# Question 3: How to efficiently search for all (z, x, y) s.t. f_1(z, x, y)!=0 (How to utilize the fact that f_1 is sparse?)
nonzero_args = nonzero_ar... | This function performs two sum-check product computations in distinct phases, combining results from polynomial commitments. It initializes parameters for each phase, computes intermediate lists (a_list_first and a_list_second) using product operations on functions and lists, then returns their concatenation. The TBD c... | def sum_check_gkr(f_1, f_2, f_3, u_list, v_list, g_list):
A_hg = initialize_phase_one(f_1, f_3, A_f3, g_list)
# TBD: h_g(x)
a_list_first = sum_check_product(A_hg, f_2, A_f2, u_list)
A_f1 = initialize_phase_two(f_1, g_list, u_list)
a_list_second = sum_check_product(f_1(g, u, y), A_f1, f_3(y)*f_2(u), A_f3*f_2(u), v_... |
def extract_test_data(self):
"""Extracts data emitted by the test."""
cmd = [
'idevicefs',
'--udid', self.udid,
'pull',
'@%s/Documents' % self.cfbundleid,
os.path.join(self.out_dir, 'Documents'),
]
try:
print_process_output(self.start_proc(cmd))
except s... | The main task of the code is to perform post-test cleanup by capturing desktop screenshots, retrieving derived and test data, collecting crash reports, and uninstalling apps to ensure a clean state after each test execution. | def tear_down(self):
"""Performs cleanup actions which must occur after every test launch."""
self.screenshot_desktop()
self.retrieve_derived_data()
self.extract_test_data()
self.retrieve_crash_reports()
self.uninstall_apps() |
def set_up(self):
"""Performs setup actions which must occur prior to every test launch."""
raise NotImplementedError
def get_launch_command(self, test_filter=None, invert=False):
"""Returns the command that can be used to launch the test app.
Args:
test_filter: List of test cases to filter.
... | The main task of the code is to launch a test application, handle crashes during startup or test execution, retry failed tests, and compile detailed test results. It initializes the app, executes tests, resumes from crashes by skipping completed tests, retries failures, logs outcomes, and returns success status based o... | def launch(self):
"""Launches the test app."""
self.set_up()
cmd = self.get_launch_command()
try:
result = self._run(cmd=cmd, shards=self.shards or 1)
if result.crashed and not result.crashed_test:
# If the app crashed but not during any particular test case, assume
# it cras... |
def polynomialFunction(self, variable):
return ((variable ** 3)/(variable+1))*cos(variable**2)
def legendreZeroes(self, polynomialDegree, i):
xnew = 0.0
xold = cos(3.141592*(i-1/4.0)/((polynomialDegree+1)/2.0))
iteration = 1
while True:
if not (iteration is 1):
xold = xnew
xnew = xold - (self.le... | This code performs numerical integration using Gaussian quadrature. It calculates the integral of a polynomial function over a specified interval by summing weighted evaluations at Legendre polynomial roots, then scales the result by the interval's width. The absolute value of the scaled sum is returned as the approxim... | def exec(self):
integral = 0.0
counter = 1
while counter <= self.polynomialDegree:
integral += (self.polynomialFunction(self.legendreZeroes(self.polynomialDegree, counter))*self.weight(self.polynomialDegree, self.legendreZeroes(self.polynomialDegree, counter)))
counter += 1
return abs(((self.upBo... |
def prediction_output(pred_run_limit, folder_count, patch_count, Random_Data, save_pred_im = False,
update_confusion = False):
#precision and recall, pr[x][y]
# x is grade, y is true positive (0), false positive (0), false negative(0)
flipper = 0
while flipper < 2:
if ... | The main task of the code is to train a machine learning model using specified parameters (e.g., batch size, steps, data partitions) while optionally performing predictions, evaluations, and visualization at defined intervals. It manages data loading, training loops, and progress tracking, with conditional execution of... | def main(unused_argv):
print(TRAINED_DICT)
# Train Settings
Train_Model = True
train_steps = 25
folder_count = 15
patch_count = 20
batch_size = 50
#Predict Settings
Predict_Model = False
#predict_steps = 100
#predict_path = DATA_PATH
save_pred_im = False
pred_run_lim... |
def is_remote(path):
"""Determine if a uri is located on a remote server
First figures out if there is a ':' in the path (e.g user@host:/path)
Then looks if there is a single @ in part preceding the first ':'
:param path: uri/path
:type path: str
:return: True if path points to remote server, Fa... | This function implements 'mv' (move) and 'cp' (copy) operations between Kosh stores, handling file URI updates. It parses command-line arguments, validates sources/destinations, uses rsync for data transfer, and updates dataset records in Kosh stores with new URIs. It also manages store synchronization and error handli... | def _mv_cp_(self, command):
"""core function to implement mv and cp"""
if command == "mv":
command_str = "move"
elif command == "cp":
command_str = "copy"
else:
raise ValueError("Unknown command {}".format(command))
parser = argparse.ArgumentP... |
def mat_make(sefl,bd,ind,n):
i=random.choices(ind,k=1)[0]
bd[i//n][i%n]=1
ind.pop(ind.index(i))
return i
def perc(self,bd,ob,o,n):
i=o//n
j=o%n
if i==0 :
if j==0: self.un(0,1,0,1,i,j,bd,ob,n)
elif j!=n-1: self.un(0,1,1,1,i,j,bd,ob,n)
... | The main task of the code is to simulate and solve a percolation problem on an n×n grid using a union-find data structure. It iteratively generates and processes the grid, checking for connectivity between nodes until a percolation path is found or 75% of the grid is processed. The loop runs 'nu' times, tracking time a... | def main(self,n,nu):
s=0
t=nu
while(nu>0):
bd=[[] for i in range(n)]
for i in bd:
for j in range(n): i.append(0)
ob=uf(n)
ind=list(np.arange(0,n**2))
f=0
c=0
st=time.time()
start=time.... |
def graph(i,j,dist,cost):
return node(i,j,dist,cost)
def get_man_dist(z,en):return abs(z[0]-en[0])+abs(z[1]-en[1])
def deque(q):
if len(q)==1:return q[0],[]
new_q=[]
min=q[0].dist+q[0].cost
mine=q[0]
for i in q:
if (i.dist+i.cost)<min:
min= i.dist+i.cost
mine=i
... | The code solves a maze by finding a path from a selected start point to a selected end point using a modified BFS approach with heuristic guidance. It identifies middle start/end points, explores valid moves, tracks paths, and backtracks upon reaching the goal. The solution is printed and returned as a path string. | def maze_runner(maze,n):
start_points=[]
for i in range(len(maze)):
if maze[0][i]==1: start_points.append([0,i])
st=start_points[len(start_points)//2]
end_points=[]
for i in range(len(maze)):
if maze[len(maze)-1][i]==1: end_points.append([len(maze)-1,i])
en=end_po... |
def graph(i,j):return node(i,j)
def dq(q):
if len(q)==1:return q[0],[]
new_q=[]
for i in range(1,len(q)):new_q.append(q[i])
return q[0],new_q
def get_moves(maze,ob,n):
i=ob.pos[0]
j=ob.pos[1]
moves=[]
if i==0:
if j==0:moves=move_plus(maze,moves,0,1,0,1,i,j)
elif j==n-1:mo... | The code solves a maze by performing a breadth-first search (BFS) from each starting point in the first row (where cell value is 1) to find paths reaching the last row (n-1). It tracks visited nodes, backtracks to construct solutions, and stores results in a dictionary. For each start point, it prints the solution path... | def maze_runner(maze,n):
start_points=[]
for i in range(len(maze)):
if maze[0][i]==1: start_points.append([0,i])
sts={}
for z in start_points:
q=[graph(z[0],z[1])]
# print()
nodes=[graph(z[0],z[1])]
goal=False
while not goal:
if len(q)==0: bre... |
def surface_parameters(object_number):
"""
Loads the different surface parameters (centroids, starts and ends) for a given object.
:param object_number: int describing object type. 1-4 pillar, 5-6 beam, 7-8 strut.
:return: area and normal parameters of the object.
"""
# Object selection:
# ... | The function integrates the Froude-Kriloff function over surfaces of specified objects (pillars, beams, struts) using wave angle and number. It loads surface parameters, computes wave angles in radians, checks integration type, and accumulates integrated cosine/sine values multiplied by surface normals into result vect... | def object_integrator(object_number, wave_angle, k):
"""
Initiates the froude-kriloff function and integrates it over the surfaces
:param object_number: int describing object type. 1-4 pillar, 5-6 beam, 7-8 strut.
:param wave_angle: int describing wave angle in degrees.
:param k: float describing th... |
def read_data_from_file(filename):
with open(filename) as file:
return_list = [line.rstrip('\n') for line in file]
return return_list
def process_input(bingo_data):
call_list = bingo_data[0].split(',')
boards = []
for i in range(1, len(bingo_data)-1, 6):
board = []
for line i... | (The code reads Bingo game data from a file, processes it into a list of called numbers and game boards, simulates the game to determine the winning board and its score, then calculates and prints the product of the winning number and score.) | def main():
bingo_data = read_data_from_file("bingo.txt")
#call_list, boards = process_input(simple_bingo)
call_list, boards = process_input(bingo_data)
#print(call_list)
# print_boards(boards)
num, score = play2(call_list, boards)
print (int(num) * score ) |
def load_settings():
if not os.path.exists('settings.json'):
create_settings()
try:
with open('settings.json', 'r') as file:
settings = json.load(file)
return settings
except Exception as error:
log(error, 'e')
def log(text, type=None, var=None, newline=False,... | This function updates nested settings in a launcher configuration by assigning a value to a specified key path within the 'launcher_settings' dictionary. It handles varying levels of nesting based on provided parameters (search_4 to search) and logs errors if the assignment fails. The updated settings are saved after t... | def set_launcher_setting(value, search, search_2=None, search_3=None, search_4=None):
settings = load_settings()
if not settings:
return
if search_4:
try:
settings['launcher_settings'][search][search_2][search_3][search_4] = value
except Exception as error:
lo... |
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3][search_4]
except Exceptio... | The main task of the code is to monitor the game process "HallsOfTorment.exe", track its log file ("godot.log") for new entries, and manage process lifecycle. It continuously checks if the game is running, retrieves processes, logs changes in the log file size, and exits gracefully if the game stops. Errors are logged,... | def watch_game():
log_file = get_launcher_setting('paths', 'logs', 'game', 'default')
if not log_file:
return
log_file += 'godot.log'
file_size = 0
processes = None
log('[Launch Game]', 'title', newline=True)
time.sleep(1)
while True:
if is_running('HallsOfTorment.exe'):
... |
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3][search_4]
except Exceptio... | The main task of the code is to extract a game pack file using the GDRE tool. It retrieves necessary file paths from launcher settings, constructs a command to run the extraction, sets console size, executes the subprocess to recover the pack file, and handles potential errors or interruptions during the process. | def extract_pack_file():
game_path = get_launcher_setting('paths', 'game', 'default')
gdre_tool = f'"{get_launcher_setting('paths', 'tools', 'gdre', 'default')}\\gdre_tools.exe"'
pack_file = f'"{game_path}' + '\\HallsOfTorment.pck"'
extract_path = f'"{get_launcher_setting('paths', 'game_extracted', 'def... |
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3][search_4]
except Exceptio... | This function executes an external tool (GoDotPCKExplorer.UI.exe) located at a path retrieved from launcher settings, logs the tool's path for debugging, attempts to run it via os.system, catches and logs any exceptions, then pauses execution. The main task is to launch the specified PCK file explorer tool with error h... | def create_pack_file():
pack_explorer_tool = f'"{get_launcher_setting('paths', 'tools', 'pck_explorer', 'default')}\\GoDotPCKExplorer.UI.exe"'
log(pack_explorer_tool, 'd')
try:
os.system(f'{pack_explorer_tool}')
except Exception as error:
log(error, 'e')
wait() |
def clear():
os.system('cls')
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3]... | The main task of the code is to configure critical file paths for a mod loader (CatModLoader) by prompting the user to set or confirm the game folder path, extracted game files folder path, and GDRE tools folder path. It uses default values if the user agrees, or allows custom paths with confirmation, updating launcher... | def setup_catmodloader():
while True:
clear()
## Step 1: Make sure the paths are correct. ##
selected_game_path = get_launcher_setting('paths', 'game', 'selected')
game_path = get_launcher_setting('paths', 'game', selected_game_path)
log('[Setup CatModLoader - Paths]', 'title... |
def set_console_size(cols, lines):
try:
pass
#os.system(f'mode con: cols={cols} lines={lines}')
except Exception as error:
print(str(error))
def create_launch_game_command(pack_file):
if not pack_file:
return
commands = ['start']
cmd = ''
cmd_args = ''
if get_... | The main task of the code is to launch a game by adjusting the console size, clearing the screen, generating platform-specific launch commands based on the provided version, and executing the game using those commands. | def menu_option_launch_game(version):
set_console_size(60, 10)
os.system('cls')
commands = create_launch_game_command(version)
launch_game(commands) |
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3][search_4]
except Exceptio... | The main task of the code is to add the CatModLoader to a Godot game project's `project.godot` file under the `[autoload]` section if it's not already present. It reads the file, checks for existing entries, inserts the loader configuration if missing, saves the changes, and logs a confirmation message upon successful ... | def add_modloader_to_game():
project_file_path = get_launcher_setting('paths', 'game_extracted', 'selected')
project_file = get_launcher_setting('paths', 'game_extracted', project_file_path) + '\\project.godot'
if os.path.exists(project_file):
with open(project_file, 'r') as file:
lines ... |
def get_launcher_setting(search, search_2=None, search_3=None, search_4=None):
if not search:
return
settings = load_settings()
if not settings:
return
if search_4:
try:
return settings['launcher_settings'][search][search_2][search_3][search_4]
except Exceptio... | The code displays a menu for configuring launch settings, allowing users to toggle the 'Auto Start Game' option and navigate back. It continuously clears the screen, lists available options with their current states, and processes user input to update settings or exit the menu. | def menu_launch_settings():
while True:
os.system('cls')
options = [
['Auto Start Game', str(get_launcher_setting('autostart_enabled'))]
]
log('[Launch Settings]', 'title', newline=True)
for index, option in enumerate(options):
log(f'[{(index + 1)}] - ... |
def set_console_size(cols, lines):
try:
pass
#os.system(f'mode con: cols={cols} lines={lines}')
except Exception as error:
print(str(error))
def create_main_menu_options():
# Menu options
options = {
0: {
'text': Fore.LIGHTGREEN_EX + "Start Modded Game" + Fore... | The main task of the code is to manage a game launcher menu, handling first-time setup, autostart configuration, and user input to launch different game modes or options. It checks for initial setup, enables auto-start if configured, modifies menu options based on mod loader status, logs actions, and gracefully handles... | def menu_start():
set_console_size(60, 15)
options = create_main_menu_options()
if get_launcher_setting('first_launch') == True:
setup_catmodloader()
set_launcher_setting(False, 'first_launch')
if get_launcher_setting('autostart_enabled') == True:
while True:
while is... |
def prepare_for_training(model,
base_learning_rate: float,
new_learning_rate: float,
weight_decay: float):
base_params_list = []
new_params_list = []
for name, param in model.named_parameters():
if "acoustic_transformer" or "... | The function trains a model using specified learning rates and weight decay, iterating over epochs to train and validate on provided datasets. It tracks training and validation losses, evaluates metrics (Rouge, Bleu, Meteor), and saves the model. Early stopping is implemented based on validation Rouge-2 scores, halting... | def train(model,
tokenizer,
train_data_loader,
val_data_loader,
test_data_loader,
base_learning_rate,
new_learning_rate,
weight_decay,
**gen_kwargs):
optimizer = prepare_for_training(model=model,
... |
def startAcrossWord(self, x, y):
return self.hasBlack(x, y, 'L') and not self.isBlack(x, y) and not self.hasBlack(x, y, 'R')
def startDownWord(self, x, y):
return self.hasBlack(x, y, 'T') and not self.isBlack(x, y) and not self.hasBlack(x, y, 'B')
def cellAt(self, x, y):
for c in self.cells:
... | The main task of the code is to assign sequential numbers to cells in a grid that are the starting points of either across or down words. It iterates through each cell, checks if it marks the beginning of a word using `startAcrossWord` or `startDownWord`, and assigns an incrementing number to eligible cells. This is co... | def setNumbering(self):
thisNumber = 1
for y in range(self.height):
thisNumbers = []
for x in range(self.width):
if self.startAcrossWord(x, y) or self.startDownWord(x, y):
self.cellAt(x, y).number = str(thisNumber)
thisNumbe... |
def setNumbering(self):
thisNumber = 1
for y in range(self.height):
thisNumbers = []
for x in range(self.width):
if self.startAcrossWord(x, y) or self.startDownWord(x, y):
self.cellAt(x, y).number = str(thisNumber)
thisNumbe... | The main task of the code is to collect and organize all horizontal (across) word entries in a crossword grid. It identifies starting cells for across words, builds each word by concatenating non-black cell letters, and stores them in a dictionary with their numbering, constructed word, and cell coordinates. The functi... | def acrossEntries(self):
# Set the numbering if it doesn't already exist
self.setNumbering()
acrossEntries = {}
thisNum = None
for y in range(self.height):
for x in range(self.width):
if self.startAcrossWord(x, y):
thisNum = self.ce... |
def setNumbering(self):
thisNumber = 1
for y in range(self.height):
thisNumbers = []
for x in range(self.width):
if self.startAcrossWord(x, y) or self.startDownWord(x, y):
self.cellAt(x, y).number = str(thisNumber)
thisNumbe... | This function collects vertical entries in a crossword grid by iterating through cells, initializing entries when a new numbered cell is found, appending letters to corresponding entries, and terminating entries upon encountering black cells. It returns a dictionary mapping entry numbers to their constructed words and ... | def downEntries(self):
# Set the numbering if it doesn't already exist
self.setNumbering()
downEntries = {}
thisNum = None
for x in range(self.width):
for y in range(self.height):
if self.startDownWord(x, y):
thisNum = self.cellAt(x... |
def initialize_session_state():
"""
Session State is a way to share variables between reruns, for each user session.
"""
st.session_state.setdefault('history', [])
st.session_state.setdefault('generated', ["Hello! I am here to provide answers to questions extracted from uploaded PDF files."])
s... | The main task of the code is to create a Streamlit-based chatbot application that allows users to upload PDF files, processes them into a vector database (FAISS), integrates a local language model (Mistral 7B via llama.cpp), and enables interactive Q&A via a conversational chain. The app includes UI setup, session stat... | def main():
"""
First function to call when we start streamlit app
"""
# Step 1: Initialize session state
initialize_session_state()
st.title("Chat Bot")
image = Image.open('chatbot.jpg')
st.image(image, width=150)
hide_streamlit_style = """
<style>
... |
def mod512(n):
return n % 512
def int32(n):
"""Return the 32 least significant bits of the number n"""
return n % 4294967296
def g1(x, y, z):
return int32((rotl(x, 22) ^ rotl(z, 9)) + rotl(y, 24))
def h1(x):
return int32(Q[get_byte(x, 0)] + Q[256 + get_byte(x, 2)])
def g2(x, y, z):
return int32((rotl(x, 10)... | The code generates a 32-bit key using a pseudo-random algorithm. It updates global arrays P and Q with values derived from modular arithmetic and custom functions (g1/g2, h1/h2), then computes the key via XOR operations. The key is formatted as a hexadecimal string after byte reversal, with i incrementing each call to ... | def keygen():
"""Generates and returns a 32 bit key"""
global P
global Q
global i
j = mod512(i)
key = None
if (i % 1024) < 512:
P[j] = int32(P[j] + g1(P[mod512(j-3)], P[mod512(j-10)], P[mod512(j-511)]))
key = h1(P[mod512(j-12)]) ^ P[j]
else:
Q[j] = int32(Q[j] + g2(Q[mod512(j-3)], Q[mo... |
def get_round_turn(self):
print(f"\nRound {self.round}.{self.turn} {'(Tie Breaker)' if self.round > self.rounds else ''}")
def get_players(self):
self.players_list = self.players if self.turn == 0 else [self.players_list[i] for i in self.max_turn_ndx]
def get_gestures(self):
for player in self.p... | The code defines a method for a Rock-Paper-Scissors-Lizard-Spock game, processing each round by collecting player gestures, validating inputs, determining the winner, updating game state, and displaying results. It repeatedly executes these steps until the game ends, then shows final statistics. | def rock_paper_scissors_lizard_spock(self):
while self.round:
self.get_round_turn()
self.get_players()
self.get_gestures()
self.check_gestures()
self.display_gestures()
self.get_winner()
self.display_status()
self.se... |
def display_welcome(self):
print("\n********************************* Rock, Paper, Scissors, Lizard, Spock **********************************\n")
print("SAM KASS: Welcome to exciting world of Rock, Paper, Scissors, Lizard, Spock. I am your cohost Sam Kass...")
print("KAREN BRYLA: And I am your c... | The main task of the code is to initialize and run a Rock-Paper-Scissors-Lizard-Spock game by displaying welcome messages and rules, selecting players, determining the game mode, and executing the core game logic through the `rock_paper_scissors_lizard_spock` method. | def run_game(self):
self.display_welcome()
self.display_rules()
self.select_player_no()
self.select_players()
self.display_players()
self.get_game_mode()
self.get_game_mode_var()
self.rock_paper_scissors_lizard_spock() |
def decrypt(words):
count = 0
for word in words:
if count == len(shift_values):
count = 0
number = list(bip39.keys())[list(bip39.values()).index(word)]
input_numbers.append(number)
try:
number -= shift_values[count]
shifted_words.append(bip39[n... | The code's main task is to decrypt input data, generate a valid phrase using shifted words, verify its checksum, and then check a wallet using the validated phrase alongside two specified dates. | def start(first_date, second_date):
decrypt(input_words)
phrase = " ".join(shifted_words)
# use the checksum to ensure we have a new valid phrase
if check(phrase):
check_wallet(phrase, first_date, second_date) |
def listen(self) -> str:
with speech_recognition.Microphone() as source:
print(f"Listening... {self.speech_recognizer.pause_threshold}")
audio = self.speech_recognizer.listen(source)
return self.speech_recognizer.recognize_google(audio, language="en-us")
def wikipedia(self, t... | The code continuously listens for user input in an infinite loop. It processes commands by checking for "exit/quit" to terminate, handling Wikipedia queries, and using `try_commands` for other tasks. If unrecognized, it responds with an apology. The loop pauses for 1 second per iteration. | def run_loop(self) -> None:
while True:
user_request = self.listen()
if user_request:
print(f"You said: {user_request}")
words = user_request.lower().split()
if "exit" in words or "quit" in words:
return
... |
def find_best_guess_optimized(alphabet):
if len(alphabet) == 2315:
# if it's the opening guess, we directly output 'soare'
return 'soare'
elif len(alphabet) == 1:
# if we are certain what the secret word is, directly guess it
return alphabet[0]
elif len(alphabet) <= 3:
... | This function solves a Wordle puzzle by iteratively selecting the optimal guess from a set of possible words, checking the color pattern feedback, and narrowing down remaining possibilities. It counts guesses until the correct word is identified, returning the total number of attempts. | def play_wordle(wordle_game, print_guesses=False):
alphabet = possible_words
num_guesses = 0
while True:
num_guesses += 1
guess = find_best_guess_optimized(alphabet)
color_pattern = wordle_game(guess)
if print_guesses:
print(f'Guess {num_guesses}: {guess} | Patt... |
def extract_rms_chunk(x):
return np.clip((10*np.log10(np.mean(x**2))), -100, 0)
def track_pitch_nccf(x,blockSize,hopSize,fs, thresholdDb):
[xb, timeInSec] = block_audio(x,blockSize,hopSize,fs)
f0 = np.zeros(len(timeInSec))
for idx, val in enumerate(xb):
mod_val = mod_acf2(val)... | The code tracks pitch onsets in audio segments defined by the onset positions array `o`, using RMS energy to detect active notes. For each segment above the RMS threshold, it applies NCCF pitch tracking with a median filter for smoothing, then converts detected frequencies to MIDI notes using A440 tuning. The result is... | def onset_note_tracking(x, o, fs, rmsThreshold):
smallBlockSize = 1024
smallHopSize = 512
a0 = 440
nChunks = o.shape[0]
f0 = np.zeros(nChunks)
for i in range(1, nChunks):
initPos = o[i-1]
endPos = o[i]
rms = extract_rms_chunk(x[initPos:endPos])
if rms > rmsThresho... |
def ToolReadAudio(cAudioFilePath):
samplerate, x = wavfile.read(cAudioFilePath)
if x.dtype == 'float32':
audio = x
else:
# change range to [-1,1)
if x.dtype == 'uint8':
nbits = 8
elif x.dtype == 'int16':
nbits = 16
elif x.dtype == 'int32':
... | The main task of the code is to evaluate the performance of a pitch detection algorithm by comparing estimated frequencies from audio files (`.wav`) with ground truth frequencies from text files (`.txt`). It calculates RMS error, false positives/negatives, plots detected vs. ground truth frequencies, and returns overal... | def run_evaluation(path):
filelist = glob.glob(path+'/'+'*.wav')
estimateInHz = np.array([])
groundtruthInHz = np.array([])
for files in filelist:
fs, x = ToolReadAudio(files)
filename = files.split('.')[0]
txt = glob.glob(filename+'*.txt')
data = open(txt[0])
txt... |
def ToolReadAudio(cAudioFilePath):
[samplerate, x] = wavread(cAudioFilePath)
if x.dtype == 'float32':
audio = x
else:
# change range to [-1,1)
if x.dtype == 'uint8':
nbits = 8
elif x.dtype == 'int16':
nbits = 16
elif x.dtype == 'int32':
... | This function evaluates the performance of three pitch tracking methods (acf, nccf, nsdf) by comparing their estimated fundamental frequencies against ground truth data from CSV files. It processes audio files, computes pitch tracks, calculates RMS errors, and returns average RMS values for each method across all file ... | def evaluate_trackpitch(pathToAudio, pathToGT):
methods = ['acf','nccf','nsdf']
iNumOfFiles = 0
rms_avg = np.zeros((3,2))
for met in range(len(methods)):
rmsAvg = 0
pfp=0
pfn=0
pfp_sum = 0
pfn_sum = 0
rmsAvg_sum = 0
wav_file_names = [os.path.join(... |
def limit(num, min, max):
if num < min:
return min
elif num > max:
return max
else:
return num
def write(self, reg, data):
if reg not in self.registers:
raise Exception("Invaild register: 0x{:02X}".format(reg))
self.cs_pin(0)
time.sleep_us(60)
... | This code sets a position value (pos) by clamping it between 0 and 127, writes it to a register (ADDR_WPR_0), then reads and normalizes the stored value by dividing by 127. The function allows setting and retrieving a bounded position value from a hardware register. | def pos(self, pos=-1):
if pos != -1:
data = limit(int(127 * pos), 0, 127)
self.write(ADDR_WPR_0, data)
return self.read(ADDR_WPR_0) / 127 |
def read_words_from_file(filename):
with open(filename, 'r') as file:
words = file.read().splitlines()
print(len(words))
# print("Completed importing words")
return words
def group_words_by_length(words):
length_groups = defaultdict(list)
for word in words:
length_groups[le... | The code reads words from a file, groups them by length, identifies the most and second most difficult words (based on required guesses) for each length, and prints details including total words, difficult words, and less difficult words for each group. | def main():
filename = "30k.txt"
words = read_words_from_file(filename)
words_by_length = group_words_by_length(words)
most_difficult_words, second_most_difficult_words = find_most_difficult_words(words_by_length)
for word_length, (max_guesses, difficult_words) in most_difficult_words.items():
... |
def mixmatch(input,inputjson):
regex = r"\{(.*?)\}"
matches = re.finditer(regex, input, re.MULTILINE | re.DOTALL)
lishttp = []
for matchNum, match in enumerate(matches):
for groupNum in range(0, len(match.groups())):
lishttp.append(match.group(0))
retlis = {}
datalis = []
for x in lishttp... | The code handles a POST request to update a DataEmail object with form-submitted data. It validates the form, processes JSON data, updates the database, and either updates an existing cloud scheduler job or (commented out) creates a new one. If valid, it returns the job details or errors in the context, then renders th... | def post(self,request, pk):
context ={}
form = EditDataForm(request.POST or None)
if form.is_valid():
jsondata = json.loads(form.data['items'])
print(jsondata)
retlis,datalis = mixmatch(jsondata['bodyhtml'],jsondata)
jsonfinal = makejsonemaildata(jsondata,datalis,retlis,jsondata['bod... |
def mixmatch(input,inputjson):
regex = r"\{(.*?)\}"
matches = re.finditer(regex, input, re.MULTILINE | re.DOTALL)
lishttp = []
for matchNum, match in enumerate(matches):
for groupNum in range(0, len(match.groups())):
lishttp.append(match.group(0))
retlis = {}
datalis = []
for x in lishttp... | The main task of the code is to handle form submission, process JSON data, schedule jobs using a cloud scheduler client, or send HTTP POST requests based on form input, and render an HTML template with the form and context data. It validates the form, generates job configurations, and manages job scheduling or API comm... | def indexdata(request):
context ={}
form = DataForm(request.POST or None)
print(form.data)
if form.is_valid():
formlist = [form]
jsondata = json.loads(form.data['items'])
print(jsondata)
retlis,datalis = mixmatch(jsondata['bodyhtml'],jsondata)
jsonfinal = makejson... |
def turn_lots_into_polygons(features):
'''
Takes in a list of ee feature objects
If any objects contain points that are within the tolerance of each other,
then these objects are combined into one polygon
TOLERANCE = 10 meters (honestly if I could get this into a reliable lat, long magnitude, t... | The main task of the code is to parse a GeoJSON object (either a Feature or FeatureCollection) into corresponding Google Earth Engine (GEE) objects (Feature or FeatureCollection). It recursively processes GeoJSON features, validates their structure, and converts geometries using a helper function. If `transform_to_poly... | def geojson_feature_parser(gj, transform_to_polygons=False):
'''
Takes in full initial geojson and parses it into earth engine types:
FeatureCollection
Feature
Returns object in the form: feature_type : str, feature_object : ee object
'''
if type(gj) is not dict:
print(f"json... |
def kmz_to_geojson(kmz_file_paths):
'''
Takes in the kmz file paths, unzips them to kml files,
then converts them to geojson files,
then returns the new geojson file locations in a list
'''
geojson_paths = []
for path in kmz_file_paths:
kmz = ZipFile(path, "r")
# ta... | The main task of the code is to convert KMZ files to GeoJSON format, create Earth Engine objects from the GeoJSON files, and export these Earth Engine assets. It initializes Earth Engine, processes multiple KMZ files, converts them to GeoJSON, generates corresponding GEE objects, and exports them as assets. The script ... | def main():
ee.Initialize()
kmz_file_paths = glob.glob(f"kmz{os.path.sep}*")
print(kmz_file_paths)
# TODO: only need to generate geojson files once, maybe split into separate script
print("Converting kmz files to geoJSON files...")
geojson_file_paths = kmz_to_geojson(kmz_file_paths)
print("G... |
def generate_query(query_str):
query = json.loads(
bedrock_r.invoke_model(
modelId="anthropic.claude-v2:1",
body=json.dumps(
{
"temperature": 0.1,
"top_p": 1.0,
"max_tokens_to_sample": 1024 * 10,
... | The code processes a user's question by classifying it with Amazon Comprehend, generating/executing SQL queries, handling errors/retries, and streaming responses. It checks for unsafe prompts, executes queries with retry logic, adjusts queries on failures, and returns results via a response stream, logging debug info a... | def question_stream(
original_question, query=None, retry_on_exception=False, retry_on_no_results=False
):
try:
yield {"status": "Comprehend Classifying Prompt"}
prompt_classes = comprehend.classify_document(
EndpointArn=f"arn:aws:comprehend:{comprehend.meta.region_name}:aws:document... |
def get_conditions(filters):
conditions = ""
if filters.get("customer"):
conditions += "and so.customer = %(customer)s"
if filters.get("business_line"):
conditions += "and so.business_line = %(business_line)s"
if filters.get("sales_order"):
conditions += " and so.name = %(sales_... | This function retrieves detailed sales order data including customer, business line, and related financial metrics (e.g., proforma invoice totals, sales invoice sums, delivery note values) from a database. It processes the data with additional details and filtering, returning structured sales order records with calcula... | def get_data(filters):
conditions = get_conditions(filters)
sales_order_data = frappe.db.sql("""SELECT so.name AS 'sales_order',
so.customer_group AS 'customer_group',
so.business_line AS 'business_line',
so.customer_name AS 'customer_name',
'' AS 'opening_debit_balance',
'' A... |
def tadasana_amendments(current_keypoints,ideal_keypoints):
arm_amendments_reqd = arm_amendments(current_keypoints,ideal_keypoints)
if arm_amendments_reqd[0]==False:
side = arm_amendments_reqd[1]
direction = arm_amendments_reqd[2]
message = f'Move your {side} hand {direction}!'
... | The function compares current pose landmarks with ideal positions from a CSV file, generating asana-specific correction suggestions by analyzing discrepancies between real-time keypoints and stored ideal poses, then returns tailored amendment advice. | def amendment_suggestion(current_asana,current_landmarks,current_pose):
current_keypoints = {
'nose' : {'x':current_landmarks[0].x,'y':current_landmarks[0].y,'z':current_landmarks[0].z},
'left_ear' : {'x':current_landmarks[7].x,'y':current_landmarks[7].y,'z':current_landmarks[7].z,'visibility':curre... |
def determine_empty_spot(parking_environment):
global empty_spots
empty_spots = []
for i in range(1, len(parking_environment)):
if i not in parking_environment:
empty_spots.append(i)
print(empty_spots)
return empty_spots
def get_parking_coordinates():
global empty_spots
... | The main task of the code is to move a car towards a determined empty parking spot by incrementally updating its position and rendering the environment. It calculates parking coordinates, adjusts the y-position, and simulates the car's movement in 5 steps using OpenCV visualization. Finally, it initiates the parking pr... | def move_car(self, env, parking):
parking_environment = parking.get_cars()
determine_empty_spot(parking_environment)
print(parking_environment)
to_park_x, to_park_y = get_parking_coordinates()
to_park_y = to_park_y - 12
for i in range(5):
self.update_car_stat... |
def _make_path_from_parameters(self, parameters, parameter_order=None):
parameter_order = self._parameter_order_fix(parameter_order)
cache_path = []
last_non_null = 0
for i, parameter_name in enumerate(parameter_order):
if parameter_name not in parameters:
bre... | The `delete_path` method deletes cache entries under a specified path, using parameters like `path`, `method`, and `user`. It supports recursive deletion or single-key removal based on the `recursive` flag. The `parameter_order` ensures consistent key generation, while `future=True` handles caching of current requests.... | def delete_path(self, **kwargs):
"""
delete_path(path=None, method=None, user=None, GET=None, POST=None, JSON=None, recursive=True, parameter_order=None, future=False)
Delete all caches under this path
recursive: If False, only delete if "path" is a single key
parameter_order: ... |
def modulepath(self, path):
return self.module + '/' + path if self.module else path
def get_version(self, directory, version_file_name='.version'):
if version_file_name in os.listdir(directory):
f = open(directory + '/' + version_file_name)
version = f.read()
f.close()
return version
return '0.0'
def... | The main task of the code is to check for available software updates by examining a 'next' directory and its '.version_on_reboot' file. If an update is detected, it retrieves the version number, notifies the user, and initiates the download/installation process. If no 'next' directory exists, it reports no updates are ... | def start(self):
if 'next' in os.listdir(self.module):
if '.version_on_reboot' in os.listdir(self.modulepath('next')):
latest_version = self.get_version(self.modulepath('next'), '.version_on_reboot')
print('New update found: ', latest_version)
self._download_and_install_update(latest_version)
else:
... |
def get_rounds() -> int:
while True:
print("How many rounds do you want to play?")
try:
rounds = int(input("> "))
if rounds < 1:
raise ValueError
print()
return rounds
except ValueError:
print("Rounds to play must be... | The code implements a multiplication game where users solve random multiplication problems within a chosen difficulty range. It tracks correct answers, adjusts difficulty dynamically, calculates the percentage of correct answers, and assigns a grade based on predefined ranges. The game concludes by displaying results a... | def main() -> None:
print("#######Multiplikationstabell#######")
print("The computer will generate two random numbers in an interval you choose every round, and your job is to multiply them correctly")
print("You are graded based on how many rounds you get right")
print()
# Constants here since glob... |
def ConnectToDB():
try:
sroot = getPath()
sPathAndRoot = sroot + '\\SiteDispatch.db'
conn = sqlite3.connect(sPathAndRoot )
return conn
except Exception as e:
LMPFileLog.WriteLogOut("Database Failed ")
return None
def GetDBSiteMasterRecords():
sitelist =[]
dbc... | This function initializes a database with site data by inserting new records into the SiteMaster table if they don't already exist. It checks each site in the provided CurrentMasterSiteList against existing database records, using the SUPPMWTag as a unique identifier. If a site is not found, it inserts the site's name,... | def InitDBSiteDataModel(CurrentMasterSiteList):
nNumAdded = 0
NewSiteList = [];
dbconn = ConnectToDB()
c = dbconn.cursor()
# c.execute('''DELETE from SiteMaster''')
SiteRecords = GetDBSiteMasterRecords()
dbconn.commit()
for MasterSite in CurrentMasterSiteList['Sites']:
bFoun... |
def parse_args() -> argparse.Namespace:
# parse bool args correctly, see https://stackoverflow.com/a/43357954
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", ... | The main task of the code is to train a reward model based on a T5 transformer architecture using contrastive learning on tokenized dataset entries. It loads/creates training data, initializes the model, and performs iterative training with batch processing, calculating loss via sigmoid differences between positive and... | def main():
print(f"Using pytorch version {torch.__version__}")
args = parse_args()
print("Effective args:", args)
torch.manual_seed(args.manual_seed)
device = torch.device(args.device, args.device_index)
if args.wandb:
wandb_mode = "online"
wandb.login()
else:
wan... |
def appStarted(app): #defines variables necessary for app
app.margin = 50
app.fieldWidth = app.width - 2*app.margin
app.fieldHeight = app.height - 2*app.margin
app.lines = 12
app.player = player.Player(app.margin + app.fieldWidth//2,
app.margin + (app.fieldHeight//app.lines) * (app.line... | This code handles keyboard inputs for a game, managing actions like restarting the game, selecting teams, resetting levels, and controlling player movement. It checks game states (e.g., leaderboard, game over) to determine valid actions, updates player position with boundary checks, and triggers specific responses (e.g... | def keyPressed(app,event):
if app.leaderboard:
if event.key == "r":
appStarted(app)
if app.teamScreen:
if event.key in app.digits:
chooseTeam(app,int(event.key))
app.teamScreen = False
if app.gameOver or app.finished: #restarts game if r is clicked
... |
def findBest(): #parses through text and finds best score
scores = readFile("scores.txt")
scores = scores.splitlines()
bestScore = 0
bestTeam = None
for score in scores:
score= score.split(",")
if int(score[0]) > bestScore:
bestScore = int(score[0])
bestTeam =... | The function identifies the third highest score and its corresponding team from a file, excluding the top two scores. It reads scores from "scores.txt", skips the best and second-best scores, and determines the third highest score and team by iterating through the data. | def thirdBest(): #parses through text and finds third highest score
bestScore, bestTeam = findBest()
secondScore, secondTeam = secondBest()
thirdScore = 0
thirdTeam = None
scores = readFile("scores.txt")
scores = scores.splitlines()
for score in scores:
score = score.split(",")
... |
def ok(x): log(f"[+] {x}")
def Mutate(data: bytes):
data = bytearray(data)
strategies = [
MutateFuzzQword,
MutateFuzzDword,
MutateFuzzWord,
MutateFuzzFlipHiBit,
]
for strategy in strategies:
dbg("Apply {} strategy".format(strategy.__name__))
for out in st... | The function `FuzzWrite` performs fuzz testing on a Write IRP (Input/Output Request Packet) by mutating input data and sending it to a remote device via `WriteFile`. It processes the device name, iterates over mutated data, and executes write operations to test the device's handling of unexpected inputs, aiming to iden... | def FuzzWrite(remote: rpyc.core.protocol.Connection, entry: Irp) -> int:
DeviceName = entry.DeviceName.lower().replace(r"\device", r"\\.")
IoctlCode = entry.IoctlCode
ok("Fuzzing Write IRP #%d" % (entry.Id,))
for mutated_data in Mutate(entry.InputBuffer):
lpIrpDataIn = bytes(mutated_data)
... |
def ok(x): log(f"[+] {x}")
def Mutate(data: bytes):
data = bytearray(data)
strategies = [
MutateFuzzQword,
MutateFuzzDword,
MutateFuzzWord,
MutateFuzzFlipHiBit,
]
for strategy in strategies:
dbg("Apply {} strategy".format(strategy.__name__))
for out in st... | This function fuzzes IOCTL requests by sending mutated input data to a device via remote connection, handling exceptions like BSODs, and prompting user continuation if a crash occurs. It prepares input/output buffers, iterates through mutated data, and invokes DeviceIoctlControl, logging errors and dumping data on crit... | def FuzzIoctl(remote: rpyc.core.protocol.Connection, entry: Irp) -> int:
DeviceName = entry.DeviceName.lower().replace(r"\device", r"\\.")
IoctlCode = entry.IoctlCode
lpIrpDataOut = b"\x00"*entry.OutputBufferLength
ok(f"Fuzzing IOCTL IRP #{entry.Id} for '{DeviceName}'")
for mutated_data in Mutate(en... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | The code implements a deletion safety mechanism for a blockchain application, allowing the owner to initiate or update a deletion request. It checks if the "delete" key exists in global state, initializes it if not, and processes approvals/rejections from users. The function ensures atomic transactions, validates sende... | def del_safe():
is_exists = ScratchVar(TealType.uint64)
is_apr = ScratchVar(TealType.uint64)
apr = ScratchVar(TealType.uint64)
rej = ScratchVar(TealType.uint64)
user_opts = ScratchVar(TealType.uint64)
_oIdx = ScratchVar(TealType.uint64)
return Seq([
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | This function processes a voting transaction in a smart contract, ensuring only authorized users can vote on a specific transaction. It validates input parameters, checks atomic transaction structure, retrieves transaction data, updates user voting status, and adjusts global approval/rejection counters. The logic enfor... | def tx_vote():
seq = ScratchVar(TealType.bytes)
tx = ScratchVar(TealType.bytes)
userOpts = ScratchVar(TealType.uint64)
isApr = ScratchVar(TealType.uint64)
apr = ScratchVar(TealType.uint64)
rej = ScratchVar(TealType.uint64)
lvRound = ScratchVar(TealType.uint64)
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | This code initializes a smart contract by validating a group of three atomic transactions: a treasury payment, a safe top-up, and an application call. It checks ownership, ensures correct transaction types and amounts, verifies global state, and sets an "init" flag to 1 upon successful validation, allowing the contract... | def init():
treasury = ScratchVar(TealType.bytes)
fee = ScratchVar(TealType.uint64)
master = ScratchVar(TealType.bytes)
minTopup = ScratchVar(TealType.uint64)
return Seq([
# 4 atomic transactions
Assert(And(
Global.group_size() == Int(3),
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | This function deletes a safe request if either the rejection count meets the threshold or a deadlock occurs (all owners voted but both approval/rejection are below the threshold). It verifies ownership, checks initialization, validates transaction context, reads approval/rejection counts, and deletes global state entri... | def del_safe_cancel():
is_exists = ScratchVar(TealType.uint64)
apr = ScratchVar(TealType.uint64)
rej = ScratchVar(TealType.uint64)
thres = ScratchVar(TealType.uint64)
return Seq([
# only the opted in owner can make a call
Pop(ownerCheck(Txn.sender())),
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | The code handles the deletion of a contract by verifying the owner's opt-in status, checking initialization, enforcing group size constraints, retrieving approval/rejection counts from a blob, comparing against a global threshold, and approving deletion if the approval count meets or exceeds the threshold. | def getOnDelete():
is_exists = ScratchVar(TealType.uint64)
apr = ScratchVar(TealType.uint64)
rej = ScratchVar(TealType.uint64)
thres = ScratchVar(TealType.uint64)
return Seq([
# only the opted in owner can make a call
Pop(ownerCheck(Txn.sender())),
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | The main task of the code is to remove a specific transaction from the contract's state by validating ownership, verifying transaction parameters, decrementing the initiator's transaction count, updating the global transaction counter, and deleting stored transaction data, ensuring only the owner can execute this actio... | def tx_remove():
seq = ScratchVar(TealType.bytes)
tx = ScratchVar(TealType.bytes)
lvRound = ScratchVar(TealType.uint64)
initiator = ScratchVar(TealType.bytes)
initiator_id = ScratchVar(TealType.uint64)
ptxn_count = ScratchVar(TealType.uint64)
curr_ptxn_count = Scr... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | The code processes a transaction in a smart contract, validating that only the authorized owner can execute it. It checks atomic transaction group size, verifies transaction details, reads approval/rejection counts against a threshold, updates global state by moving data, rekeys to a CA address, adjusts pending transac... | def tx_exec():
thres = ScratchVar(TealType.uint64)
lvRound = ScratchVar(TealType.uint64)
tx = ScratchVar(TealType.bytes)
seq = ScratchVar(TealType.bytes)
apr = ScratchVar(TealType.uint64)
rej = ScratchVar(TealType.uint64)
ca = ScratchVar(TealType.bytes)
... |
def ownerCheck(sender: Expr):
# sender/address we want to check
# Return the index of the owner
o = ScratchVar(TealType.uint64)
idx = ScratchVar(TealType.uint64)
name = ScratchVar(TealType.bytes)
a = ScratchVar(TealType.bytes)
f = ScratchVar(TealType.uint64) # own... | The main task of the code is to create a new transaction entry in a smart contract, ensuring the sender is an authorized owner, validating atomic transactions, limiting transaction counts, verifying signatures, and structuring data into a blob for storage. It enforces constraints like maximum transactions per owner, ch... | def tx_create():
s = ScratchVar(TealType.uint64)
seq = ScratchVar(TealType.bytes)
sig_addr = ScratchVar(TealType.bytes)
initiator = ScratchVar(TealType.bytes)
_oIdx = ScratchVar(TealType.uint64)
ptxs = ScratchVar(TealType.uint64)
owner_ptxn_count = ScratchVar(... |
def basic_search(resource_type,args_dict={},retrieve_all=True):
#print('searching',resource_type,args_dict)
j=omeka_get(resource_type,args_dict,retrieve_all)
return j
def get_property_data(properties):
properties_dump={}
for p in properties:
#print(p)
if type(p)==list:
term=p[0]['term']
property_id=basic... | This function updates an item's properties in an API by merging new data with existing data, filtering based on `keep_nonlinks` and `keep_links` flags. It retrieves the item's current data, processes new properties, and applies updates by either adding new properties or modifying existing ones, ensuring data consistenc... | def update_item(properties,item_id,keep_nonlinks=False,keep_links=True,endpoint='items'):
#print(properties,item_id)
item_data=basic_search(endpoint,args_dict={'id':item_id},retrieve_all=False)[0]
new_properties_data=get_property_data(properties)
headers = {'Content-type': 'application/json'}
this_url=build_url(ba... |
def get_property_data(properties):
properties_dump={}
for p in properties:
#print(p)
if type(p)==list:
term=p[0]['term']
property_id=basic_search('properties',{'term':term})[0]['o:id']
prop_data=[]
for prop_entry in p:
prop_data.append(
format_property_data(
prop_entry['type'],
pr... | The code creates an item in an Omeka system by constructing a JSON payload with specified properties and a resource class, then posting it to the API. It retrieves a resource class ID, formats item data, sends a POST request, and returns the newly created item's ID. | def create_item(properties,item_class=''):
#print(properties)
properties_dump=get_property_data(properties)
resource_class_id=basic_search('resource_classes',{'term':item_class})[0]['o:id']
item_data = {
"@type": ["o:Item",item_class],
"o:resource_class":
{
"o:id": resource_class_id,
"@id": bu... |
def _parse_arguments(desc, args):
"""
Parses command line arguments
:param desc:
:param args:
:return:
"""
parser = argparse.ArgumentParser(description=desc,
formatter_class=Formatter)
parser.add_argument('logdir',
help='Direct... | The main task of the code is to parse CDAPS 0.8.0 logs from a specified directory, generate a summary report, and optionally create monthly reports or send results via email. It processes command-line arguments, handles date ranges, captures output, and includes error handling to return success (0) or failure (2) statu... | def main(args):
"""
Main entry point for program
:param args: command line arguments usually :py:const:`sys.argv`
:return: 0 for success otherwise failure
:rtype: int
"""
desc = """
Parses CDAPS 0.8.0 logs found in <logdir> to generate a summary report
"""
theargs = _parse_argu... |
def move_right(self, piece: Block, x: int):
piece.move(0, x)
def piece_inside_grid(self, piece):
"""Return a boolean to test whether a piece is inside the grid."""
tiles = piece.get_cell_positions()
for tile in tiles:
if self.game_grid.is_inside(tile[0], tile[1]) == False:
... | This code processes a game action in a Tetris-like environment by applying the specified piece rotation and column position, checking for valid movement, locking the piece into the grid, updating the game state, calculating rewards based on cleared rows, and determining if the game is over. It returns the new grid stat... | def step(self, action:tuple, render=False, render_delay=None):
"""Return the updated grid, rewards and done condition when interacting with the environment."""
column, rotation = action
copy_piece = copy.deepcopy(self.current_piece)
copy_grid = copy.deepcopy(self.game_grid)
... |
def reset(self):
"""Return the empty grid as a parameterised vector."""
self.game_grid.reset()
self.game_over = False
self.lines_cleared = 0
self.tetriminoes = [IBlock(),
JBlock(),
LBlock(),
... | The code simulates a Tetris game episode by selecting actions based on a weight vector W, accumulating rewards, and tracking the score. It runs for up to 500 steps, updating the game state iteratively. If a reward of 4 is achieved (e.g., a line cleared), the score increments. The simulation returns total rewards and th... | def simulation(self, W, render=False):
"""One episode of tetris. Select actions according to weight vector."""
rewards_sum = 0
state = self.reset()
done = False
max_steps = 500
score_tetris = 0
# while True:
for i in range(max_steps):
... |
def pipe(self, img):
undist = cv2.undistort(img, self.mtx, self.dist, None, self.mtx)
birds_eye = self.beye(undist)
hsv = cv2.cvtColor(birds_eye, cv2.COLOR_RGB2HSV)
gray = cv2.cvtColor(birds_eye, cv2.COLOR_BGR2GRAY)
hls = cv2.cvtColor(birds_eye, cv2.COLOR_BGR2HLS)
... | This code processes an input image to detect lane lines, calculate lane curvature, and determine vehicle deviation from the center. It warps the image, identifies left/right lane boundaries using sliding windows, computes polynomial fits, validates results, and overlays curvature and deviation metrics onto the output i... | def process(self, img):
self.xsize = img.shape[1]
self.ysize = img.shape[0]
self.counter += 1
warped, undist, birds_eye = self.pipe(img)
left_fit, right_fit, left_centroids, right_centroids = self.slide(warped)
if self.ploty is None:
self.ploty = np.l... |
def parse_game(line: str) -> Game:
game_str, rounds_str = line.split(":")
game_id = int("".join([c for c in game_str if c.isdigit()]))
rounds = [parse_round(round_str) for round_str in rounds_str.split(";")]
return Game(game_id, rounds)
def game_is_within_threshold(game: Game, threshold: Round) -> bool:... | The code reads game data from a CSV file, validates games against a threshold of maximum balls (12 red, 13 green, 14 blue), sums valid game IDs, calculates minimum required balls per game round, and computes the total power of these minimums. It outputs two results: the sum of valid game IDs and the sum of power values... | def main():
with open("data/day2.csv", "r") as file:
data = file.read().splitlines()
THRESHOLD = Round(nr_red=12, nr_green=13, nr_blue=14)
games = [parse_game(line) for line in data]
valid_game_id_2a = [
game.id for game in games if game_is_within_threshold(game, THRESHOLD)
]
pr... |
def generate_random_numbers(n):
return [random.randint(0, 8191) for _ in range(n)]
def generate_sorted_numbers(n):
numbers = generate_random_numbers(n)
numbers.sort()
return numbers
def generate_reverse_sorted_numbers(n):
numbers = generate_sorted_numbers(n)
numbers.reverse()
return numbers
... | The code generates random, sorted, and reverse-sorted number lists of varying lengths (200, 2000, 20000) by iterating through three file-saving cycles per length. It stores each dataset in text files with unique identifiers, creating structured data for potential algorithm testing or analysis. | def generate():
m = 20
for i in range(1, 4):
n = 10**i
l = m * n
for j in range(3):
random_numbers = generate_random_numbers(l)
sorted_numbers = generate_sorted_numbers(l)
reverse_sorted_numbers = generate_reverse_sorted_numbers(l)
# Save ... |
def search_album(album_id):
album_api_response = urlopen(album_api_url + str(album_id))
album_json = json.loads(album_api_response.read())
for song in album_json['songs']:
# get index value of this loop
index = album_json['songs'].index(song)
song_id = song['id']
# 01. song... | The code presents a menu for searching album or song lyrics by ID or song name, executing corresponding functions based on user input. It handles three options: searching an album by ID, fetching a lyric by song ID, or retrieving a song list. Invalid inputs prompt the user to try again, ensuring interaction and data re... | def lyric_fetcher_menu():
user_input = input("\n\nSelect option: \n\n"
"[1] Search album by id\n"
"[2] Search lyric by id\n"
"[3] Search lyric by song name\n\n"
"Enter option: ")
if user_input == '1':
album_id = input('Enter... |
def StartTeachIT(self):
print("\n \n \n ")
print("Hi, Welcome to Teach it. Your Personal Teaching assistant \n ")
#print("- Please Say Start Lecture to start recording \n ")
#print("- Please Say Finish Lecture to stop recording \n ")
self.SpeakText("Hi, Welcome to Teach it. Your ... | The main task of the code is to convert speech from an audio file into text using Google's Speech Recognition API. It continuously processes audio input, appends recognized text to a string, and writes it to a file. When the phrase "lecture finished" is detected, it stops processing, saves the text, and triggers a summ... | def speech_to_text(self):
i = 0
self.StartTeachIT()
self.text_file = open("sample.html", "w")
#playsound('test2.wav')
sleep(0.7)
self.SpeakText("Recording finished, initiating speech to text")
print("Recording finished, Please wait, initiating speech to text")... |
def subtract_min_values(table):
# for i in range(table.spending_matrix_size):
# row_min_value = table.spending_matrix[i][0]
# for j in range(table.spending_matrix_size):
# if row_min_value > table.spending_matrix[i][j]:
# row_min_value = table.spending_matrix[i][j]
# ... | This function solves a transportation problem by iteratively adjusting a spending matrix. It copies the initial matrix, subtracts minimum values, and iterates through solving cases until optimality is achieved. Each iteration prints progress, checks completion, and outputs the table. The final solution is formed using ... | def solve_hm_table(table):
initial_spending_matrix = np.copy(table.spending_matrix)
solving_complete = False
iteration = 1
subtract_min_values(table)
while not solving_complete:
print()
print("ITERATION: {}".format(iteration))
iteration += 1
print()
solve_to_... |
def compensation(self, TC=None):
"""
Set tool compensation mode.
@param TC: Tool compensation direction.
Left compensation: 'l', 'left', 1
Right compensation: 'r', 'right', 2
Center (no) compensation: 'c', 'center', 0
"""
TC = lowerstr(TC)
if TC in [0, "center", "c"]:
... | This function generates toolpaths for machining slots in a CNC context. It defines slots using parameters like width, orientation, and length, either via start/end points or center/angle. It calculates offset paths based on tool diameter and specified offsets, creating linear and arc movements for both inside and climb... | def slot(self, inside=True, climb=True, offsets=[0], **kwargs): #, flat_len=None, oall_len=None, wd=None, ax=None, ay=None, bx=None, by=None, cx=None, cy=None, theta=None):
# Slots are defined with:
# wd, start, end
# wd, center, theta, and a len_
# start, end: tuples of (x,y) points for start and end... |
def compensation(self, TC=None):
"""
Set tool compensation mode.
@param TC: Tool compensation direction.
Left compensation: 'l', 'left', 1
Right compensation: 'r', 'right', 2
Center (no) compensation: 'c', 'center', 0
"""
TC = lowerstr(TC)
if TC in [0, "center", "c"]:
... | This function generates CNC tool paths for circular machining operations, adjusting for tool diameter, offsets, and overlap. It creates arcs with specified directions (climb/conventional), handles multiple passes with varying offsets, and supports segmented chains. Parameters define center, radius/diameter, and pass co... | def circle(self, inside=True, climb=True, offsets=[0], overlap=10, center=None, r=None, d=None, chain_pct=None):
# Circles are defined with:
# - center
# - r: radius, or d: diameter
# offsets is an array of offsets from the final diameter. These can be repeated; e.g. offsets of [0.005,0,0] would give a... |
def dxf_entities(filename, scaling=1.0):
"Stitches DXF entities. Assumes a DXF in the X-Y plane of only lines, arcs, and splines."
EPSILON = 1e-5
doc = dxf.readfile(filename)
msp = doc.modelspace()
segs = []
for e in msp.query('LINE'):
l = math.hypot(e.dxf.start[0]-e.dxf.end[0], e.dxf.start[1]-e.dxf.... | The main task of the code is to generate machine tool paths by following a DXF file's geometry, processing lines and arcs with compensation, direction settings, and offset passes. It parses DXF entities, applies tool compensation, and executes movements (linear or arc) based on entity types, while handling climb direct... | def follow_dxf(self, dxf_filename, dxf_scaling=1.0, inside=True, climb=True, offsets=[0], overlap=0):
"""
Follows a DXF path.
The DXF should only contain one loop (it can be closed or open).
If the loop is open, you may need to change the "inside" parameter to go in the correct direction.
@param of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.