dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def query_oracle_and_update_classifier_and_save_active_learning_results(active_learning_train_cycles, al_model, oracle_results, ground_truth_dir, segmentation_dir, query_num, al_dataloader, criterion, optimizer, classifier_training_dir, run_id, iter_num):
all_patient_scores = []
patient_scores = get_patient_sco... | The main task of the code is to perform an active learning experiment with multiple training cycles. It initializes a UNet model and classifier, iteratively queries an oracle for new data, updates the classifier, retrains the UNet, and evaluates metrics on validation data. The process repeats for a specified number of ... | def active_learning_experiment_multiple(run_id, active_learning_train_cycles, query_num):
# initial unet model
# initial classifier
classifier_training_dir = "/usr/xtmp/vs196/mammoproj/Data/manualfa/train/"
ground_truth_dir = "/usr/xtmp/vs196/mammoproj/Data/manualfa/train/"
# Unbinarized train segme... |
def save_active_learning_results(run_id, iter_num, oracle_results, oracle_results_thresholds, im_dir):
save_dir = "/usr/xtmp/vs196/mammoproj/Code/ActiveLearning/AllOracleRuns/Run_" + \
run_id + "/Iter" + str(iter_num)
correct_segs_save_dir = save_dir + "CorrectSegmentations/"
saved_oracle_filepaths... | This function conducts active learning by iteratively querying an oracle to select informative images, updating a classifier model, and training a UNet for segmentation. It evaluates the segmenter's performance on validation data, saves results, and returns the validation metric and model path. | def active_learning_experiment(active_learning_train_cycles, imgs_seen, segmtr_model, run_id, iter_num, oracle_query_method):
# ACTIVE LEARNING STAGE
# INITIALIZE CLASSIFIER
# File definitions and static setup
# ground_truth_dir = "/usr/xtmp/vs196/mammoproj/Data/manualfa/train/"
ground_truth_dir = ... |
def testInputs(filepath: str, features, seperator: str, scalingFlag, DEBUG_MODE=False):
"""Tests if the specified inputs are viable. If they are not, it raises an Exception.
:param filepath: filepath to the csv-file
:param features: array of features
:param seperator: seperator to read the csv-file
... | This function loads and preprocesses a CSV file by handling missing data, selecting features, applying NLP processing with a specified encoder, splitting vector columns, removing outliers via z-score thresholding, performing PCA for dimensionality reduction, and scaling features. It returns a preprocessed pandas DataFr... | def loadAndPreprocess_function(filepath: str, features=[], chunkSize=318, n_componentsAfterPCA=0, seperator='|',
encoder='mobilebert_multi_cased', zScaleThreshold=3, scalingFlag='maxabs_scale',
debug=False):
"""Loads and preprocesses a csv-file
:par... |
def preprocess_text(self, text):
if len(text)>400:
text = text[-400:]
return text
def _aggregate_features(self, text):
stat_feats = self.get_static_features(text)
tfidf_feats = self.tfidf.transform([text])
all_feats = np.concatenate([tfidf_feats.toarray(), stat_feats]... | The code processes input text by preprocessing it, aggregating features, and using a model to predict a label, which is then mapped to a human-readable format via a dictionary. | def run(self, text):
pre_text = self.preprocess_text(text)
features = self._aggregate_features(pre_text)
lr_preds = self._get_model_pred(features)
#print(lr_preds)
return self.label_dict[lr_preds[0]] |
def extractdata(path):
meta_data = urllib.request.urlopen(path)
html = meta_data.read()
phtml = bs.BeautifulSoup(html,'lxml')
paragraphs = phtml.find_all('p')
texta = ""
#Converting text from HTML Paragraph TAGS
for p in paragraphs:
texta += p.text
# Removing Square Brackets... | The code generates a summary from a webpage by extracting text, tokenizing sentences, applying TextRank for summarization, performing POS tagging on key nouns, and displaying the refined summary in GUI labels with formatting. | def online(url,lbl,lb1):
#Converts in both With Punctuations and Without Punctuations
with_punct,wo_punct=extractdata(url)
#Generate Sentences
sentences=nltk.sent_tokenize(with_punct)
#Divide the Summary to 1/4
N=int(len(sentences)/4)
#Summarizes the Paragraph
Summary,reduced_text = text... |
def textrank(sentences, top_n, stopwords=None):
S = build_similarity_matrix(sentences, stopwords)
sentence_ranks = pagerank(S)
# Sort the sentence ranks
ranked_sentence_indexes = [item[0] for item in sorted(enumerate(sentence_ranks), key=lambda item: -item[1])]
selected_sentences = sorted(ranked_s... | This code processes a text file by cleaning and tokenizing it, using TextRank to generate a summary, extracting nouns via POS tagging, and creating a structured summary. It then updates GUI labels to display the final summary with specific formatting and positioning. | def offline(path,lbl,lb1):
text_file = open(path, "r")
text = text_file.read()
text_wp=text.replace('\n', ' ')
text_wop= re.sub('[^a-zA-Z]', ' ',text_wp)
text_wop= re.sub(r'\s+', ' ', text_wop)
sentences=nltk.sent_tokenize(text_wp)
N=int(len(sentences)/2)
Summary,reduced_text = textran... |
def _g(phi: float) -> float:
# return 1 / math.sqrt(1 + (3 * phi ** 2) / (math.pi ** 2))
return 1 / math.sqrt(1 + 3 * (phi / math.pi)**2)
def _e(mu: float, mu_j: float, phi_j: float) -> float:
return 1 / (1 + math.exp(-_g(phi_j) * (mu - mu_j)))
def _get_v(mu: float, results: ResultList) -> float:
"""Ste... | This function calculates the delta value in the Glicko-2 rating system by summing weighted differences between actual scores and expected scores, then multiplying by a variance factor. It processes each result's rating (mu_j), rating deviation (phi_j), and score (s_j) to compute the adjustment needed for updating playe... | def _get_delta(mu: float, results: ResultList) -> float:
"""Step 4 of the Glicko-2 rating system.
The ratings and rating deviations in `results` should all be in the
Glicko-2 rating system's scale.
"""
delta = 0
for mu_j, phi_j, s_j in results:
delta += _g(phi_j) * (s_j - _e(mu, mu_j, ... |
def update_deviation(deviation: float,
volatility: float,
time: float = 1) -> float:
"""Update a rating deviation."""
_, phi = _convert_v2(float(), deviation)
phi = math.sqrt(phi**2 + time * volatility**2)
_, deviation = _convert_v1(float(), phi)
return devi... | The function updates a player's rating, deviation, and volatility in the Glicko-1 system using their game results. It converts inputs to intermediate values (mu, phi), calculates new parameters (sigma_p, phi_p, mu_p) based on results, and returns updated stats. If no results are provided, it updates deviation alone. Th... | def update_stats(rating: float,
deviation: float,
volatility: float,
results: ResultList,
time: float = 1) -> FullRating:
"""Get new stats for a player based on a collection of games.
Calculate a new rating, deviation, and volatility for a pla... |
def extract_code_blocks(response: str) -> Iterator[tuple[str, str]]:
yield from re.findall(r'^(\S+)\n+```[\w]*\n(.*?)\n```', response, re.DOTALL | re.MULTILINE)
def apply_udiff_edit(original: str, patch: str) -> str:
try:
return apply_patch(original, patch)
except Exception as e:
print(f"Err... | The function processes code blocks from a response, applying edits to existing files or creating new ones. It checks file existence, generates diffs, prompts user confirmation, and saves changes if approved. Modifications are tracked in a dictionary mapping file paths to original-modified content tuples. | def apply_edits(response: str, diff: bool) -> dict[Path, tuple[str, str]]:
modifications = {}
for file_path_str, code_block in extract_code_blocks(response):
file_path = Path(file_path_str).expanduser()
file_exists = file_path.exists()
if file_exists:
file_data = file_path.re... |
def eval_weight(self, e: Edge) -> None:
w = self.expected_dis - self.eval_dis(e)
e.update_weight(w)
def draw(p) -> bool:
return True if np.random.uniform() < p else False
def update_ag_weight(self, ag: Agent) -> None:
for e in ag.edges:
self.eval_weight(e) | This function simulates an agent's iterative interaction in a network by randomly selecting an agent and gene, evaluating edge weights, probabilistically choosing edges based on normalized weights, and altering genes. If an edge's weight is negative, it may flip the gene with 10% chance; otherwise, it applies the gene.... | def simulate_iteration(self):
ag = np.random.choice(self.ags)
gene_idx = np.random.choice(Network.N_DYNAMIC_GENE)
for e in ag.edges:
if e.w is None:
self.eval_weight(e)
e_prob = np.array([abs(e.w) for e in ag.edges])
e_prob = e_prob / np.sum(e_prob)
... |
def _measure_dissonance(self) -> float:
dissonance = 0
for e in self.all_edges:
if e.w is None:
self.eval_weight(e)
o_u = self.ags[e.u].to_ndarray()[:Network.N_DYNAMIC_GENE]
o_v = self.ags[e.v].to_ndarray()[:Network.N_DYNAMIC_GENE]
dissonan... | This function measures dissonance, appends the value to a list for tracking, and optionally prints the iteration index and dissonance value with formatted output if verbosity is enabled. | def measure_record_print(self, iter_idx) -> None:
dissonance = self._measure_dissonance()
self.dissonance_lst.append(dissonance)
if self.verbose:
print_std_out_err("iter {:7d} dissonance: {:.5f}".format(iter_idx, self.get_dissonance())) |
def simulate_iteration(self):
ag = np.random.choice(self.ags)
gene_idx = np.random.choice(Network.N_DYNAMIC_GENE)
for e in ag.edges:
if e.w is None:
self.eval_weight(e)
e_prob = np.array([abs(e.w) for e in ag.edges])
e_prob = e_prob / np.sum(e_prob)
... | The code simulates iterations until termination conditions are met: 1) A statistically significant drop in dissonance followed by no further decline over 1M iterations, or 2) Stagnant dissonance values. It tracks elapsed time, prints diagnostics if enabled, and returns the termination iteration number. | def simulate(self) -> int:
start_time = time.time()
terminate_iter = self.n_iteration
for iter_idx in range(1, self.n_iteration+1):
self.simulate_iteration()
if iter_idx % self.measure_itv == 0:
self.measure_record_print(iter_idx)
# cond... |
def prepare_customer_and_addresses(self, partner, order_response):
"""
Searches for existing customer in Odoo and creates in odoo, if not found.
"""
invoice_address = order_response.get("billingAddress") and \
self.create_or_update_address(
... | The function searches for an existing Odoo customer using their email from external data. If found, it checks credit limit and payment terms to determine if a sale or POS order should be created. If the customer doesn't exist, it creates a new one. It returns flags for order types, the customer ID, and address details,... | def search_customer(self, model_id, instance, order_queue_line, log_book_id, queue_line_details):
"""
This method use for search customer is exists or not in odoo
as well call create customer method for new customer create
@return : sale_order , pos_order , customer_id
sa... |
def prepare_sale_order_vals(self, instance, customer_id, delivery_address, invoice_address, details):
"""
This method used to Prepare a sale order vals.
@return: ordervals
"""
# date_order = self.convert_order_date(order_response)
team_id = self.search_team_from_instance(... | This method creates a sale order and/or POS order based on input parameters, prepares order values, creates order lines, handles payments, and returns the generated order ID. It processes both sales and POS orders, ensuring line items and payment details are correctly added. | def create_order(self, instance, sale_order, POS_order, customer_id, delivery_address, invoice_address, details,
lines, session_id):
"""
This method is use for the create a sale order and pos order.
@return: order_id
"""
sale_order_obj = self.env['sale.order'... |
def check_order_exists_or_not(self, instance, details):
"""
This method use for check current order is exists or not on sale order
or pos order
@return: order
"""
order = self.env['sale.order'].search(
[('fixably_instance_id', '=', instance.id), ('fixably_orde... | This method synchronizes orders from a queue line to Odoo by checking order existence, retrieving customer and product details, validating order lines, handling POS sessions, and creating logs for errors. If no issues occur, it updates the queue line state and creates the Odoo order. | def fixably_sync_orders(self, order_queue_line, instance, log_book_id):
"""
This method is used to sync order from queue line to odoo.
@return: Order
"""
order = False
session_id = False
log_count = 0
common_log_line_obj = self.env["common.log.lines.ept"]
... |
def collect_param(self, sparsify=False):
"""
Participants collect the parameters from the global model
:param sparsify: Not used, if apply sparsify update
:return: None
"""
param = self.global_model.get_flatten_parameters()
pipe_lost = torch.zeros(self.Ph, dtype=t... | This function orchestrates federated learning (FL) training by collecting parameters, performing backpropagation with attack handling, applying defense mechanisms (e.g., pooling, Fang, FL-trust), and logging training/test metrics. It records epoch progress, evaluates model performance, and saves results to a CSV file, ... | def eq_train(self):
"""
Organize the FL training process
"""
epoch_col = []
train_acc_col = []
train_loss_col = []
test_acc_col = []
test_loss_col = []
attacking = False
pooling = False
if self.defender.startswith("p"):
... |
def histEqualization(image):
result = image.copy()
vals = np.zeros(256)
for i in np.arange(len(result)):
for j in np.arange(len(result[i])):
ind = result[i][j]
vals[ind] = vals[ind] + 1
factor = len(image)*len(image[0])
vals[0] = vals[0] / factor
for i in np.arang... | The code segments license plate characters from an image by converting it to grayscale, resizing, thresholding, clustering white pixels, and recognizing characters. It formats detected characters into a structured string, compares them against existing plate data, and updates a list of plates with counts or logs matche... | def segmentation(plateImage, data, plates):
plateImage = cv2.cvtColor(plateImage, cv2.COLOR_BGR2GRAY)
if data[0] == data[2] and len(plates) > 0 and plates[0][1] > 2:
with open('Output.csv', mode='a') as csv_file:
if(plates[0][1] > 2):
writer = csv.writer(csv_file)
... |
def dronecan_type_to_ctype(dronecan_type):
assert dronecan_type.category != dronecan_type.CATEGORY_VOID
if dronecan_type.category == dronecan_type.CATEGORY_COMPOUND:
assert dronecan_type.kind == dronecan_type.KIND_MESSAGE
return 'struct %s' % (underscored_name(dronecan_type))
elif dronecan_t... | This function generates C struct definitions for a given field, handling both static and dynamic arrays. For static arrays, it returns a simple type declaration with size. For dynamic arrays, it creates a struct containing a length field and a data array. Non-array fields are returned as basic type-name pairs. The code... | def field_cdef(field):
assert field.type.category != field.type.CATEGORY_VOID
if field.type.category == field.type.CATEGORY_ARRAY:
if field.type.mode == field.type.MODE_STATIC:
return '%s %s[%u]' % (dronecan_type_to_ctype(field.type.value_type), field.name, field.type.max_size)
else:... |
def check_angles(self,
angles: dict,
) -> bool:
"""
returns false if angles are within range
"""
for i,joint in enumerate(self.servos):
if angles[joint]['qpos'] < self.servo_min[i] or angles[joint]['qpos'] > self.servo_max[i]:
return True
r... | The main task of the code is to validate a robot's state by checking joint angles, fall conditions, and kinematic feasibility. It processes input angles, converts joint values into position/velocity pairs, and sequentially verifies validity using three checks: angle constraints, fall detection, and kinematic constraint... | def check_state(self,
angles: dict,
):
angles = angles.copy()
for key in angles.keys():
if 'joint' in key:
temp = angles[key]
angles[key] = {'qpos' : temp[0], 'qvel' : temp[1]}
if self.check_angles(angles):
return True,None
... |
def front_bottom_pos(self, angle1, angle2):
pos = self.forward_kinematics(angle1,angle2)
vec1 = np.array(pos['knee pos'])
vec2 = np.array(pos['foot pos']) - np.array(pos['knee pos'])
angle = np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2)))
return angle
def... | The main task of this code is to convert input joint angles into corresponding simulated joint positions (qpos) using specific mathematical transformations. It adjusts angles for each joint (e.g., adding/subtracting constants, negating values) and applies helper methods to compute positions for certain joints. The resu... | def rel_to_sim(self,
angles: dict,
) -> bool:
angles_sim = {}
angles_sim['joint00'] = {'qpos' : np.radians(-90 - angles['joint00'])}
angles_sim['joint10'] = {'qpos' : np.radians(angles['joint10'] + 90)}
angles_sim['joint011'] = {'qpos' : np.radians(-79.937 - angles['joint011'... |
def get_subdataset(_S=1, Sess=1):
_file = 'P300/train/Data_S%02d_Sess%02d.csv' % (_S, Sess)
_f = open(_file).readlines()
channels = []
for i, _rows in enumerate(_f):
if i > 0:
channels.append(eval(_rows))
else:
_headers = _rows
return np.array(channels)
def ge... | The function retrieves and preprocesses P300 EEG signals for a specific subject and session. It loads dataset, filters target-labeled instances, extracts samples, and returns a preprocessed signal instance for further analysis. | def get_signals_P300():
sr = 200
session = 1
data = []
for subject in range(1, 2): # 26
s_s_chs = get_subdataset(subject, session)
_index = [i + 1 for i, d in enumerate(s_s_chs[:, -1]) if d == 1]
instances = get_samples(_index, s_s_chs, sr)
for f_instance in range(0, 1):... |
def delta_wave(signal, fs):
return butter_bandpass_filter(signal, fs, 0.5, 4.0, order=4)
def theta_wave(signal, fs):
return butter_bandpass_filter(signal, fs, 4.0, 8.0, order=5)
def alpha_wave(signal, fs):
return butter_bandpass_filter(signal, fs, 8.0, 12.0, order=5)
def beta_wave(signal, fs):
return bu... | This function calculates and returns the frequency bands (delta, theta, alpha, beta, gamma) for a given EEG channel by applying corresponding wave analysis functions, using the provided sampling rate `fs` to process the channel data. | def frequency_bands(channel, fs):
freq_band = [
delta_wave(channel, fs),
theta_wave(channel, fs),
alpha_wave(channel, fs),
beta_wave(channel, fs),
gamma_wave(channel, fs)
]
return freq_band |
def butter_highpass(cutoff, fs, order=6):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='high', analog=False)
return b, a
def get_signals_P300():
sr = 200
session = 1
data = []
for subject in range(1, 2): # 26
s_s_chs = get_subdataset(subj... | The code designs a high-pass Butterworth filter (30 Hz, order 3) at 200 Hz sampling rate, plots its frequency response with markers/lines at 30 Hz, loads a P300 signal, applies a gamma wave filtering function, and visualizes the original and filtered signals in time-domain plots. The task combines filter design, freque... | def lp():
fs = 200.0 # sample rate, Hz
b, a = butter_highpass(30.0, fs, order=3)
w, h = freqz(b, a, worN=2000)
plt.subplot(2, 1, 1)
plt.plot(0.5 * fs * w / np.pi, np.abs(h), 'b')
#plt.plot(12.0, 0.5 * np.sqrt(2), 'ko')
plt.plot(30.0, 0.5 * np.sqrt(2), 'ko')
#plt.axvline(12.0, color='k... |
def get_stamina(hero_id):
h = None
while h is None:
try:
rpc = RPC_SERVERS[CURRENT_RPC]
h = heroes.human_readable_hero(heroes.get_hero(heroes.SERENDALE_CONTRACT_ADDRESS, hero_id, rpc))
except Exception as e:
LOGGER.exception(str(e))
h = warn_sleep_reset("get hero stamina", 1)
c... | The main task of the code is to automate hero questing in a blockchain-based game by managing Ethereum private keys, checking hero stamina, and initiating/ending quests based on conditions. It loads encrypted keys, derives addresses, monitors hero status, skips unsupported quest types, and runs in a loop with error han... | def main(config_path, key_path):
private_key = None # paste in your private key here for competitive autoquesting
addr = None # paste in your address if you want to skip using keys.py
if private_key is None:
w3 = Web3(Web3.HTTPProvider(RPC_SERVERS[CURRENT_RPC]))
encrypted_key = keys.manage_keyfile(key_pa... |
def fetch_from_witai(self, user_query):
url = f"https://api.wit.ai/message?q={user_query}"
response = requests.get(url, headers={"Authorization": "Bearer 7J5ZT2ZAR2ICKM5GSQPGXDJ3CCNPAYXO"})
if response.status_code == 200:
data = response.json()
intent = data["intents"][0]... | This code processes user queries by identifying intent and entities via Wit.ai, then generates responses based on specific intents related to information retrieval. If the intent matches predefined types, it searches for relevant articles, constructs a response, and updates conversation context. Otherwise, it prompts t... | def handle_user_query(self, user_query):
# Fetch intent and entities from Wit.ai
intent, entities = self.fetch_from_witai(user_query)
# If specific intent is found, then process accordingly
if intent in ['get_contribution_between_subject_and_context',
'get_definiti... |
def to_device(self, tensors):
"""Converts all inputs to the device used."""
if isinstance(tensors, list) or isinstance(tensors, tuple):
tensors = [tensor.to(self.device) for tensor in tensors]
return tensors
elif isinstance(tensors, torch.Tensor):
return tenso... | The main task of the code is to compute the loss and accuracy metrics for a training step in a model. It processes input data through the model to generate vectors, computes logits for language generation (lg), calculates loss and accuracy using these logits and labels, and returns the loss value along with the metrics... | def train_step(self, prod_inputs, frag_inputs, lg_labels, lengths, **kwargs):
prod_vecs, frag_vecs_pad = self(prod_inputs, frag_inputs)
lg_labels = self.to_device(lg_labels)
lg_logits, _ = self._compute_lg_logits(frag_vecs_pad, prod_vecs=prod_vecs, lg_labels=lg_labels)
lg_loss, lg_acc =... |
def _compute_lg_logits(self, graph_vecs_pad, prod_vecs, lg_labels=None):
scores = torch.tensor([], device=self.device)
prev_lg_emb = None
entropy = None
if lg_labels is None:
for idx in range(graph_vecs_pad.size(1)):
scores_lg, entropy = self._compute_lg_step... | This function predicts chemical reaction labels for a given product molecule and core edits by processing molecular structures into graph representations, applying neural network models, and returning predicted labels using a vocabulary mapping. | def predict(self, prod_smi: str, core_edits: List, rxn_class: int = None):
"""Make predictions for given product smiles string.
Parameters
----------
prod_smi: str,
Product SMILES string
core_edits: List,
Edits associated with product molecule
"""... |
def config():
# Static configs
ROOT_DIR = Path(os.path.abspath(os.path.dirname(__file__)))
version_map = {
"NIV": "niv.csv",
"ESV": "esv.csv",
}
# Configurable elements
st.sidebar.subheader("Search config")
version = st.sidebar.selectbox("Bible Version:", list(version_map.ke... | The main task of the code is to build a Bible search application using Streamlit, combining TF-IDF and semantic search methods to retrieve and rank relevant Bible chapters based on user queries. It loads Bible data, processes text embeddings, and uses cross-encoder reranking to provide accurate results, with debug mode... | def main():
(
ROOT_DIR,
version,
version_map,
max_texts_limit,
n_results,
debug_mode,
use_tfidf_retriever,
use_semantic_verse_retriever,
) = config()
SEM_SEARCH_THRESHOLD = 0.4
CROSS_ENCODER_THRESHOLD = None
# Load Data
bible_path ... |
def bazel_dockerfile(bazel_version: str):
template_string = load_template("bazel")
return template_string.format(bazel_version=bazel_version)
def tf_dockerfile(py_version: str, tf_version: str, use_cache=False):
bazel_version = tf_bazel_version(tf_version)
numpy_version = tf_numpy_version(py_version)
... | This function generates Dockerfile instructions for specified package types (bazel, tensorflow, tfx) based on version numbers, constructs filenames using version strings, writes the instructions to a file in the 'build_files' directory, and returns the generated filename. | def generate(pkg_type: str, pkg_ver: str, py_ver: typing.Optional[str] = None, **kwargs) -> str:
pkg_ver_flat = "".join(pkg_ver.split("."))
py_ver_flat = "".join(py_ver.split(".")) if py_ver else ""
if pkg_type == "bazel":
df_name = f"bazel_{pkg_ver_flat}"
instructions = bazel_dockerfile(pk... |
def predict(self, num_predictions=10):
"""Make predictions using the trained model."""
x = self.create_input_sequences()
predictions = []
# Start with the last sequence
seq = x[-1]
for _ in range(num_predictions):
x_input = np.expand_dims(seq, axis=0)
... | The code's main task is to execute a prediction process by generating scaled predictions, reversing their scaling, plotting the results, and saving them to a CSV file. It handles exceptions by logging errors with detailed information. | def run(self):
"""Run the prediction process."""
try:
predictions_scaled = self.predict()
predictions = self.inverse_transform_predictions(predictions_scaled)
self.plot_predictions(predictions)
predictions_path = ROOT_DIR / f'{self.PREDICTIONS_FOLDER}/{sel... |
def home_page(self):
# response = requests.get(self.BASE_URL)
# soup = BeautifulSoup(response.text, 'html.parser')
# objs = {}
# objs.update(self.create_obj_FCC(soup,"h2.post-card-title > a",False))
# self.print_news(objs, self.BASE_URL)
posts = self.obj_filler(self.BASE... | The code defines a `menu` method that displays a navigation menu for a web application, allowing users to select options like viewing home page news, tag-based content, trending items, or exiting. It cleans the terminal, presents the menu, captures user input, and routes to corresponding methods (`home_page`, `base_on_... | def menu(self):
'''
This fuction display the Menu of the current web site
'''
self.clean_terminal()
menu = ['Home page news (First 25)', 'Base on tag (First 25)', 'What\'s trending', 'Exit']
option = self.display_menu(menu, "FREE CODE CAMP CONTENT: ")
s... |
def semi_int(dice, move_pieces, player_pieces, enemy_pieces):
if len(move_pieces) == 1:
return move_pieces[0]
pieces_to_goal_lane = piece_to_goal_lane(dice, player_pieces, move_pieces)
pieces_to_goal = piece_to_goal(dice, player_pieces, move_pieces)
home_pieces = out_of_home(dice, player_pieces... | The code trains a reinforcement learning agent for the Ludopy game by simulating matches with semi-intelligent and neural network-based strategies, storing experiences in replay memories, calculating rewards based on game states, and updating memories for each player to learn optimal actions toward winning. | def train_game():
rand_players = [0, 0, 0, 2]
random.shuffle(rand_players)
game = ludopy.Game()
memories = [ReplayMemory(500), ReplayMemory(500), ReplayMemory(500), ReplayMemory(500)]
#memories = ReplayMemory(2800)
there_is_a_winner = False
prev_state = [None, None, None, None]
prev_ac... |
def select_random_action(move_pieces):
# print("random")
return move_pieces[np.random.randint(0, len(move_pieces))], None
def semi_int(dice, move_pieces, player_pieces, enemy_pieces):
if len(move_pieces) == 1:
return move_pieces[0]
pieces_to_goal_lane = piece_to_goal_lane(dice, player_pieces, m... | The code simulates a Ludopy game with four players using different strategies (random, semi-intelligent, or AI) and returns whether the winning player used a semi-intelligent strategy, the total rounds played, and the round when all three of their pieces reached the goal. | def one_game():
rand_players = [0,0,0,2]
random.shuffle(rand_players)
game = ludopy.Game()
there_is_a_winner = False
n_round = 0
g3_goal = 0
#print(rand_players)
while not there_is_a_winner:
n_round += 0.25
(dice, move_pieces, pl... |
def generate_rank_and_regret(self):
self.rank_per_space = {}
self.regret_per_space = {}
self.all_ranks = []
self.all_regrets = []
for _, search_space in enumerate(self.search_spaces):
results_data = {}
for experiment in self.experiments:
... | The code's main task is to generate visualizations for algorithm performance analysis by first computing ranking and regret metrics, then creating individual plots per search space, and finally producing aggregated visualizations across all spaces. The method orchestrates data preparation and plot generation for compar... | def plot(self):
self.generate_rank_and_regret()
self.generate_plots_per_search_space( name= self.name+"_per_space")
self.generate_aggregated_plots(name= self.name+"_aggregated") |
def create_grid(positions = {}):
''' create a grid filled with existing blocks '''
#create empty grid
grid = [[(0,0,0) for _ in range(rows)] for _ in range(colls)]
#filled grid
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j,i) in positions:
grid[... | This code implements a Tetris game using Pygame, handling shape movement, rotation, collision detection, scoring, and game states (play, pause, game over). It initializes the game window, processes user input, updates the grid, checks for row clears, adjusts fall speed, and transitions between states. The game ends whe... | def main(window):
pygame.init()
#create window
window = pygame.display.set_mode((window_width,window_height))
#create grid
grid = create_grid()
positions = {}
#define game state
game_state = State.play
new_shape = False
#create current shape
current_shape = create_new_... |
def draw_waiting(window):
#clear window
window.fill((0,0,0))
#load fonts
pygame.font.init()
white_color = (255,255,255)
#create font
font = pygame.font.SysFont('comicsans',60)
#create label
label = font.render('Waiting for players',1,white_color)
#draw label
window.blit(l... | The code implements a client for a multiplayer Tetris-like game, handling player input, network communication with a server, game state management (waiting, playing, game over), collision detection, shape movement/rotation, score tracking, and rendering the game grid and UI elements. It synchronizes player and friend's... | def client(window = None):
global state
#create window
window = pygame.display.set_mode((window_width,window_height))
net = Network()
#filled positions
positions = {}
#do need create new shape
new_shape = False
#connect to server , receive shape and next shape
data = net.co... |
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def evaluate(board):
# Check rows, columns, and diagonals for a win or loss
for row in board:
if all(cell == "X" for cell in row):
return -1 # Player X wins
elif all(cell == "O" for c... | This code implements a Tic-Tac-Toe game where a player competes against a computer. The player inputs moves (row, col), and the computer uses a best_move function to place 'O'. The game checks for wins/ties after each move, displaying the board and results. The loop continues until a win, tie, or player quit (q). | def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
while True:
print_board(board)
player_move = input("Enter your move (row, col) or 'q' to quit: ")
if player_move == 'q':
break
row, col = map(int, player_move.split(','))
if board[row][co... |
def fix_seeds():
# The below is necessary for starting Numpy generated random numbers
# in a well-defined initial state.
np.random.seed(2022)
# The below is necessary for starting core Python generated random numbers
# in a well-defined state.
python_random.seed(2022)
# The below set_seed(... | The function `run_main` trains a machine learning model using the specified architecture and datasets, ensuring reproducibility if enabled. It initializes the model, trains it, plots training accuracy, and returns the trained model, run ID, and accuracy figure for analysis and evaluation. | def run_main(architecture, train_ds, train_size, val_ds, val_size, reproducible=True):
tf.keras.backend.clear_session()
if reproducible:
fix_seeds()
model, base_model = create_model(architecture)
model, history, run_id = train(model, base_model, architecture, train_ds, train_size, val_ds, val_... |
def getEssential(self,table,essential_implicants):
'''
Args:
Returns:
'''
for i in [x for x in table if len(table[x])==1]:
if table[i][0] not in essential_implicants:
essential_implicants.append(table[i][0])
del tab... | The function `minimalize` simplifies Boolean expressions by selecting essential prime implicants and applying Petrick's method to determine the minimal set of implicants. It constructs a coverage table mapping terms to prime implicants, identifies essential implicants, removes their covered terms, and uses Petrick's me... | def minimalize(self,prime_implicants,min_terms_categorised):
'''
Args:
Returns:
'''
selected_implicants=[]
table={}
essential_implicants=[]
for i,j in min_terms_categorised.items():
for k in j:
table[k[1]... |
def categorize(self,min_terms,variables):
''' Categorises minterms on the basis of number of '1's
Args:
min_terms: A lsit of min terms. Each item is a binary number string e.g-"1001".
variables: The number of variables in the function
Returns:
min_terms_cate... | This function generates prime implicants, identifies essential ones, and constructs minimal logical expressions from categorized min-terms using the Quine-McCluskey algorithm. It converts min-terms to binary, categorizes them, finds prime implicants, determines essential and selected implicants, and returns these along... | def tabulation(self,variables, min_terms):
prime_implicants = []
functions = []
min_terms=[bin(int(x))[2:].zfill(variables) for x in min_terms]
min_terms_categorised = self.categorize(min_terms,variables)
self.getPrimeImplicants(min_terms_categorised,variables,prime_implicants)... |
def create_dataset(path, num_examples):
lines = io.open(path, encoding='UTF-8').read().strip().split('\n') # strip removes space at beginning and end, split splits file into a list, seperator \n
word_pairs = [[preprocess_sentence(w) for w in line.split('\t')] # \t is horizontal whitespace, e.g. whitespace. in this... | The code loads a dataset by creating input-output pairs, adds start/end tokens to target language data, tokenizes both input and target languages, and returns tokenized tensors along with their respective tokenizers for machine translation tasks. | def load_dataset(path, num_examples=None):
# creating cleaned input, output pairs
targ_lang, inp_lang = create_dataset(path, num_examples)
# Changes target language to german
targ_lang = add_start_end_tokens(num_examples)
input_tensor, inp_lang_tokenizer = tokenize(inp_lang)
target_tensor, targ_lang_token... |
def mean(first_list):
# mean Logic
mean_value = summation(first_list)/len(first_list)
return round(mean_value, 6)
def standard_deviation(first_list):
# Standard deviation Logic
standard_deviation_value = math.sqrt(variance(first_list))
return round(standard_deviation_value, 6)
def summation(firs... | The code calculates the skewness of a list by computing the average of the cubed z-scores (standardized values) of its elements. It first checks if all elements are numeric, then computes the mean and standard deviation. Each element's z-score is cubed, summed, and divided by the list length. The result is rounded to s... | def skewness(first_list):
# # Skewness Logic
x_mean = mean(first_list)
sd = standard_deviation(first_list)
a = []
for i in range(len(first_list)):
if (isinstance(i, (int, float)) == False):
return 0
a.append(((first_list[i]-x_mean)/sd) *
((first_list[i... |
def mean(first_list):
# mean Logic
mean_value = summation(first_list)/len(first_list)
return round(mean_value, 6)
def standard_deviation(first_list):
# Standard deviation Logic
standard_deviation_value = math.sqrt(variance(first_list))
return round(standard_deviation_value, 6)
def summation(firs... | The function calculates the kurtosis of a given list by computing the average of the fourth power of the standardized values (z-scores) of the input data. It first checks if each element is a number (with a potential bug in the index check), then computes the mean and standard deviation. The kurtosis value is derived b... | def kurtosis(first_list):
# Kurtosis Logic
x_mean = mean(first_list)
sd = standard_deviation(first_list)
a = []
for i in range(len(first_list)):
if (isinstance(i, (int, float)) == False):
return 0
a.append(((first_list[i]-x_mean)/sd)**4)
kurtosis_value = (summation(a)... |
def semantic_search(query, embedding_model, k):
embedding = np.array(embedding_model.embed_query(query))
with psycopg.connect(
dbname="postgres",
user="postgres",
host="pgvector",
password="postgres"
) as conn:
register_vector(conn)
with conn.cursor() as cur:
... | This method processes a query by performing semantic search to retrieve relevant context chunks, generates a response using a language model with the retrieved context, and returns the query, sources, answer, and model details in a structured format. | def __call__(self, query, num_chunks=5, stream=True):
# Get sources and context
context_results = semantic_search(
query=query,
embedding_model=self.embedding_model,
k=num_chunks)
# Generate response
context = [item["text"] for item in c... |
def user(self, game_board):
"""
User function: updates the game board, and requests a move from the playe, and checks that move to a list of the legal moves to makes sure that it is a valid move.
"""
display.update(game_board.fen())
prompt = f"{self.who(game_board.turn... | This code allows a user to play or watch a chess game against an AI or self-play. It initializes game settings, alternates moves between players (human or AI), updates the board display, checks for game-ending conditions (checkmate, stalemate, etc.), and returns the result, message, and final board state. The game uses... | def play_game(self, pause=0.1):
""" Main function """
#checking if the user wishes to watch a game against two AIs or wishes to play
self.player1 = input("Enter 1 for AI or 2 for self play: ")
self.playerc = 'Black'
if self.player1 == '1':
self.mode = "A"
... |
def getVI(self, trainingValues, Class):
rows = len(trainingValues)
oneCount = 0
zeroCount = 0
for i in range(len(trainingValues)):
if Class[i] == 1:
oneCount += 1
else:
zeroCount += 1
if oneCount == 0 or zeroCount... | This code constructs a decision tree recursively by selecting the best attribute to split the data based on the VI (possibly information gain or variance) measure, partitioning the dataset, and building left/right subtrees until no further splits are possible or impurity is zero. | def VIH(self, trainingValues, Class, attributes):
if len(trainingValues) == 0:
return None
root = Tree(-1)
VI = self.getVI(trainingValues, Class)
root.label = self.getMajority(Class)
if VI == 0 or len(attributes) == 0:
return root
else:
... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates1(channels, counts):
"""Estimates of the three par... | The code fits a Gaussian model to spectral data within a specified region of interest (ROI), plots the data and fitted curve, displays initial/final parameter estimates, and calculates peak counts. It filters data, performs curve fitting, visualizes results with color-coded channels, and sets axis limits for focused an... | def plot_single(x, y, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI)
_p0 = gaussian_initial_estimates1(_channels, _counts)
# show the initial guesses
print("> the initial estimates:")
print... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates2(channels, counts):
"""Estimates of the three par... | The main task of the code is to fit a double Gaussian model to spectral data within a specified region of interest (ROI), plot the data and fitted model, and display initial and final parameter estimates along with peak counts. It processes input data, performs curve fitting, visualizes results, and outputs key metrics... | def plot_double(x, y, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a','mu2', 'sig2', 'a2')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI)
_p0 = gaussian_initial_estimates2(_channels, _counts)
# show the initial guesses
print("> the initial es... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates1(channels, counts):
"""Estimates of the three par... | The function `find_a_values` iterates over datasets in `all_counts`, fits a Gaussian model to each dataset within a specified region of interest (ROI) defined by `x` and `y`, and collects the amplitude parameter 'a' from each fit. It uses initial estimates for Gaussian parameters (mu, sig, a), performs curve fitting, a... | def find_a_values(x, y, z):
for values in all_counts:
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, values, *ROI)
_p0 = gaussian_initial_estimates1(_channels, _counts)
# do the fit
... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates(channels, counts):
"""Estimates of the three para... | This function fits a Gaussian model to spectral data within a specified region of interest (ROI) defined by x and y, then plots the original data and fitted curve. It prints initial parameter estimates, final optimized parameters, and calculates peak counts using the fitted Gaussian function. The plot visualizes the sp... | def plot_single(x, y, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI)
_p0 = gaussian_initial_estimates(_channels, _counts)
# show the initial guesses
print("> the initial estimates:")
print(... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates(channels, counts):
"""Estimates of the three para... | The code fits Gaussian curves to two regions of interest (ROIs) in a dataset, visualizes the data and fitted models, and outputs initial/final parameter estimates and peak counts. It processes input ranges, performs curve fitting, plots the results with specified limits, and calculates peak values for both ROIs. | def plot_two(x1, y1, x2, y2, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI_1 = (x1, y1)
ROI_2 = (x2, y2)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI_1)
_p0 = gaussian_initial_estimates(_channels, _counts)
# show the initial guesses
print("> t... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
# TODO: check x.shape == y.shape?
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates2(channels, counts):
"""Estimates of the three par... | The main task of the code is to fit a double Gaussian model to spectral data within a specified region of interest (ROI), visualize the fitted curve alongside the original data, and output key parameters like peak counts. It processes input data (x, y, z) to filter, estimate initial Gaussian parameters, perform curve f... | def plot_double(x, y, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a','mu2', 'sig2', 'a2')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI)
_p0 = gaussian_initial_estimates2(_channels, _counts)
# show the initial guesses
print("> the initial es... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates(channels, counts):
"""Estimates of the three parameters of the gaussian distribution.""... | The function fits a Gaussian model to spectral data within a specified Region of Interest (ROI), prints initial and final parameter estimates, and visualizes the data with the fitted model. It filters data, performs curve fitting, and plots the spectrum with color-coded ROI, overlaying the Gaussian fit. The peak counts... | def plot_single(x, y, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI = (x, y)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI)
_p0 = gaussian_initial_estimates(_channels, _counts)
# show the initial guesses
print("> the initial estimates:")
print(... |
def filter_in_interval(x, y, xmin, xmax):
"""Selects only elements of x and y where xmin <= x < xmax."""
_mask = in_interval(x, xmin, xmax)
return [np.asarray(x)[_mask] for x in (x, y)]
def gaussian_initial_estimates(channels, counts):
"""Estimates of the three parameters of the gaussian distribution.""... | The code fits two Gaussian curves to data within specified regions of interest (ROI_1 and ROI_2), plots the original data and fitted models, and outputs initial/final parameter estimates and peak counts. It processes channel-count data, performs curve fitting, visualizes results with axis limits, and prints statistical... | def plot_double(x1, y1, x2, y2, z):
GAUSSIAN_PARAMS = ('mu', 'sig', 'a')
ROI_1 = (x1, y1)
ROI_2 = (x2, y2)
# make initial estimates
_channels, _counts = filter_in_interval(CHANNELS, COUNTS, *ROI_1)
_p0 = gaussian_initial_estimates(_channels, _counts)
# show the initial guesses
print("... |
def delinearize_metric(x, metric, bounds):
metric = check_metric(x, metric)
for i in range(len(metric)):
for j in range(len(metric[0])):
# normalize to [0, 1]
metric[i, j] = (metric[i, j] - bounds[0])/(bounds[1] - bounds[0])
# exponentiate
metric[i, j] = 1... | The function `param_optimizer` computes the negative log marginal likelihood of a kernel constructed using a delinearized metric. It takes parameters `M` and additional arguments, derives a metric from them, creates a kernel, and returns the negative log marginal likelihood, likely for optimization in a probabilistic m... | def param_optimizer(M, *args):
metric = delinearize_metric(args[4], M, args[3])
K = make_kernel(args[0], args[2], metric=metric)
return -log_marginal_likelihood(K, args[1]) |
def predict(model, x, x_new):
metric = check_metric(x, model[2])
y_mean = []
y_sigma = []
for new in x_new:
local_kernel = add_to_kernel(model[0], x, new, metric)
K = local_kernel[:len(x), :len(x)]
k = local_kernel[:len(x), -1]
inv_K = np.... | This function evaluates the expected improvement for a new point X_new in a Bayesian optimization context. It checks if predictions from multiple models (args[0]) satisfy constraints (args[2]) and returns 0 if any violation is detected. If all constraints are met, it computes the negative expected improvement using the... | def acquisition_function(X_new, *args):
if len(args[0]) > 1:
for i in range(len(args[0])-1):
pred, sigma = predict(args[0][i], args[1], [X_new])
if not are_contraint_satifcation_probable(pred, sigma, args[2], args[4][i]):
return 0
pred, sigma = predict(args[0][0]... |
def preprocess_inputs(x, data_info):
check_data_info(x, data_info)
inp = copy.deepcopy(x)
for i in range(len(data_info)):
# linearize log scaled variables
if data_info[i][2] == "log":
sign = 1
inf = data_info[i][3][0]
sup = data_info[i][3][1]
... | The code generates next points for Bayesian optimization by calculating optimal metrics and kernels from input-output data. It preprocesses data, computes differences, iterates through constraints to derive metrics and kernels, then uses these to predict next points. The result is postprocessed and returned, enabling i... | def next_points(self, n, a, metric_bounds=[-12, 12]):
x = preprocess_inputs(self.x, self.data_info)
y = preprocess_outputs(self.y)
print(np.hstack([x, y]), flush=True)
self.seed += 1
print("Calculating optimal metrics", flush=True)
diffs = make_diff_list(x, self.data_in... |
def log_msg(message):
"""Print to console and store to Log"""
print(message)
logging.info(message)
def naukri_login(properties, headless=False):
"""Open Chrome browser and Login to Naukri.com"""
status = False
driver = None
try:
driver = load_naukri(headless)
if "naukri" in... | (The main task of the code is to execute a data ingestion workflow using Apache Spark. It initializes a Spark session, loads configuration and input data from JSON files, logs into Naukri, retrieves structured data, and ingests it into a database. The script includes error handling, logging, and cleanup processes. Key ... | def main():
log_msg("-----Naukri.py Script Run Begin-----")
spark = SparkSession \
.builder \
.appName("ingestion") \
.config("spark.jars", "../Database/postgresql-42.3.1.jar") \
.getOrCreate()
with open("data.json", "r") as json_file:
input_file = json.load(json_fi... |
def initialize(self):
return initialize(self.N)
def simulate(self):
beta = 1./self.T
for i in range(self.steps):
update_rand(self.arr, self.N, beta)
Ene = hamiltonian(self.arr)
Mag = mag(self.arr)
#Now save energy magnetization
... | This code simulates a system 'nsim' times, storing results in tensors. It generates a filename using parameters N, T, and nsim, then iterates through simulations, initializing each, calculating magnitudes, and saving data/mags as a PyTorch file. The 'verbose' flag controls progress bar visibility. | def simulate_save(self, path, verbose=False):
filename = os.path.join(path, f'{self.N}_{self.T}_{self.nsim}.pt')
data = torch.empty((self.nsim,self.N,self.N), dtype=torch.int)
mags = torch.empty(self.nsim, dtype=torch.float)
TM1 = 1./self.T
for n in tqdm(range(self.nsim), disabl... |
def fetch_products(limit=4, items_per_page=4, starting_from_page=1):
WC_API_URL = get_secret("WC_API_URL")
WC_CONSUMER_KEY = get_secret("WC_CONSUMER_KEY")
WC_CONSUMER_SECRET = get_secret("WC_CONSUMER_SECRET")
wcapi = API(
url=WC_API_URL,
consumer_key=WC_CONSUMER_KEY,
consumer_se... | The code's main task is to fetch products, process them, sync the processed data to DynamoDB, and return a JSON response indicating success or an error. It handles exceptions by logging errors and returning a 500 status code with error details, ensuring proper HTTP headers for cross-origin requests. | def handler(event, context):
try:
products = fetch_products()
processed_products = process_products(products)
sync_products_to_dynamodb(processed_products)
# Create a message to send back
message = {
"message": "Successfully fetched and processed products",
... |
def add_player(player_name, score):
# Usernames must be unique. Prevent adding an already existing username
try:
db_execute("INSERT INTO players (name, score) VALUES (:name, :score)", {
"name": player_name,
"score": score,
})
return True
except sqlite3.Integri... | The code handles quiz initialization by adding a player, retrieving questions from the database, and rendering the quiz page with fetched questions, answers, and user details. It checks for duplicate usernames and ensures proper data passing to the template for the quiz interface. | def quiz():
username = request.form['username']
if not add_player(username, 0):
return render_template('index.html', duplicate_username=True)
query_result = get_questions()
db_conn_close()
return render_template('quiz.html', questions=query_result[0], answers=query_result[1], num_of_questi... |
def is_logged_in_LN():
if driver.current_url == "https://www.linkedin.com/feed/": return True
if try_linkText(driver, "Sign in"): return False
if try_xp(driver, '//button[@type="submit" and contains(text(), "Sign in")]'): return False
if try_linkText(driver, "Join now"): return False
print_lg("Didn... | The main task of the code is to automate job application processes on LinkedIn using browser automation, including logging in, configuring resume settings, cycling through job filters, and handling errors. It optionally integrates with ChatGPT for resume customization, validates configurations, creates directories, and... | def main():
try:
alert_title = "Error Occurred. Closing Browser!"
validate_config()
make_directories([file_name,failed_file_name,logs_folder_path+"/screenshots",default_resume_path,generated_resume_path+"/temp"])
if not os.path.exists(default_resume_path): raise Exception('Your def... |
def _run_classifier(self) -> float:
# reset current results and add next entry for running loss
self.true_values = []
self.predicted_values = []
self.running_loss.append(0)
self.network.train(not self.validation)
for i, (image, image_class, _) in enumerate(self.loader):... | The code executes a single training/evaluation epoch for a neural network model (classifier or regressor), processes input data, computes loss, updates model parameters via backpropagation (if in training mode), collects true/predicted values, calculates mean absolute error (MAE) and relative error, and returns these m... | def run(self) -> float | Tuple[float]:
"""Run a single epoch loop.
Returns:
Mean absolute error.
"""
if self.mode == "classifier":
return self._run_classifier()
# reset current results and add next entry for running loss
self.true_values = []
... |
def reset_bar(self,text):
self.window['ProgressBar'].update(0)
self.window['-PROGRESS_TEXT-'].update(text)
def start_progress(self):
self.reset_bar(self.progress_text)
def update_bar(self):
item_count = count_all_items(self.project_path)[0]
perc = self.make_percentage(item_count,... | The main task of the code is to update a progress bar during a background process. It initializes the progress with the project name, updates it every second while subprocesses run, and resets the bar once all processes complete, ensuring real-time feedback on the project's build status. | def update_progress(self,project_path,total_count=100):
self.reset_bar(self.default_progress_text)
self.project_path=project_path
self.project_name = os.path.basename(self.project_path)
self.total_count=total_count
self.progress_text = f'building {self.project_name}'
self... |
def get_scan_mode(self, section, list_type):
for mode in self.scan_modes:
if mode['section'] == section:
return mode.get(list_type, None)
return None
def list_dir(self,directory):
directory = directory or self.values[self.event_key_js["-DIR-"]] or self.project_folder_... | The code scans a directory recursively or locally to list files/folders, excluding specified paths, and returns their relative paths as a list. It uses `os.walk` for recursive scans and `os.listdir` for local scans, filtering items based on type and excluded directories. | def scan_directory(self, directory_path, list_type):
"""
List files or folders in the given directory based on the provided type and mode.
Parameters:
-----------
directory_path : str
Path to the directory to scan.
list_type : str
Either 'file' or... |
def set_scan_mode(self, section, list_type, scan_mode):
for mode in self.scan_modes:
if mode['section'] == section:
mode[list_type] = scan_mode
return
# If the section is not found, add a new entry
self.scan_modes.append({"section": section, list_type:... | This function toggles the scan mode between 'RECURSIVE' and 'LOCAL' for files/folders, updates corresponding UI checkboxes by inverting their boolean values, and triggers a scan using the current directory. It determines scan type from the input key, identifies the opposite mode, updates the UI state, then executes the... | def reverse_bool(self,key=None,section=None):
key = key or self.event_key_js['found']
pieces = key[1:-1].split('_')
section = section or self.event_key_js['section']
list_type = 'FILES' if 'FILES' in pieces else 'FOLDERS'
scan_type = 'RECURSIVE' if 'RECU... |
def return_directory(self):
"""
Return the current directory or parent directory if a file path is provided.
Returns:
--------
str:
Directory path.
"""
directory = self.values[self.event_key_js['-DIR-']]
if os.path.isfile(self.values[self.even... | This function navigates to a selected directory or restores from history in a file browser. It constructs a directory path using user input or listbox selection, verifies validity, and updates the interface if valid. If no selection exists, it reverts to the last directory in the history stack, maintaining navigation s... | def forward_navigate(self,forward_value = None):
directory=None
try:
# Navigate down into the selected directory or move to the next history path
if forward_value or self.values[self.event_key_js['-BROWSER_FOLDERS_LIST-']]: # If there's a selected folder in the listbox
... |
def __get_data(self, dictionary):
"""
@param dictionary: a specified test (keys are the definitions of the tests: the metrics, app name and more)
@return: train and test datasets
"""
metric = dictionary["metric"]
app = dictionary["app"]
ss_rate = dictionary["sub s... | The main task of the code is to execute a single test for a specified metric and application by fetching training/test data, instantiating a model, training it, evaluating its performance (MSE, precision, recall, F1, etc.), and returning the results along with training time. | def __do_one_test(self, dictionary):
metric, app = dictionary["metric"], dictionary["app"]
print(self.__msg, f"Fetching data for metric='{metric}', app='{app}'.")
train, test = self.__get_data(dictionary=dictionary)
print(self.__msg, "Making an instance of the class we want to test")
... |
def __do_one_test(self, dictionary):
metric, app = dictionary["metric"], dictionary["app"]
print(self.__msg, f"Fetching data for metric='{metric}', app='{app}'.")
train, test = self.__get_data(dictionary=dictionary)
print(self.__msg, "Making an instance of the class we want to test")
... | The code runs multiple tests on specified applications and metrics, collects performance metrics (MSE, precision, recall, etc.), verifies result consistency, and prints a summary table along with device information. | def run_training_and_tests(self):
print(self.__msg, "Powering on test bench")
full_report = []
for dictionary in self.__tests_to_perform:
app = dictionary["app"]
metric = dictionary["metric"]
print(self.__msg, f"testing metric='{metric}', app='{app}'.")
... |
def gen_start_states1():
s = []
s.append(comp_to_num(1, 4, 0))
s.append(comp_to_num(2, 4, 0))
s.append(comp_to_num(3, 4, 0))
s.append(comp_to_num(6, 4, 0))
s.append(comp_to_num(7, 4, 0))
s.append(comp_to_num(1, 4, 1))
s.append(comp_to_num(2, 4, 1))
s.append(comp_to_num(3, 4, 1))
... | The main task of the code is to initialize and configure a reinforcement learning environment by printing parameters like discount rate, states, actions, and observations, then generating components such as start states, transitions, observations, and rewards through function calls. It sets up a simulation framework wi... | def main():
# discount: %f
# values: [ reward, cost ]
# states: [ %d, <list of states> ]
# actions: [ %d, <list of actions> ]
# observations: [ %d, <list of observations> ]
print("discount:", disc)
print("values: reward")
print("states:", 128)
print("actions:", 5)
print("observ... |
def build_state(actions_to_states, states):
to_states = {}
for state in states:
to_states[state] = []
for from_state in states:
pos1, mat1, arrow1, state1, health1 = from_state
if health1 == 0:
continue
valid_actions = []
for i_state in actions_to_states... | The code implements a reinforcement learning algorithm to determine the optimal policy for Indiana Jones in a grid-based environment. It calculates state utilities using value iteration, considering actions like movement, crafting, gathering, and shooting. The policy is updated iteratively until convergence, with task-... | def Indiana_Jones(task, start_state_num):
actions_to_states = {
"C": [("UP", "N"), ("DOWN", "S"), ("LEFT", "W"), ("RIGHT", "E"), ("STAY", "C"), ("UP", "E"), ("DOWN", "E"), ("LEFT", "E"), ("STAY", "E"), ("SHOOT", "C"), ("HIT", "C")],
"N": [("DOWN", "C"), ("STAY", "N"), ("DOWN", "E"), ("STAY", "E"), (... |
def get_capabilities():
pythonv = '{}.{}.{}'.format(*sys.version_info)
if ((sys.version_info[0] == 2 and sys.version_info[1] < 7) or
(sys.version_info[0] == 3 and sys.version_info[1] < 2) or
# Just in case... Also don't restrict <= 3, script might
# work on Python 4+ too.
... | The main task of the code is to execute an encoding process based on command-line options, manage interactive modes, and handle errors. It initializes system capabilities, processes user-defined options, runs encoding if not in interactive mode, tracks execution time, and ensures cleanup. The code checks for help flags... | def main():
caps = {'pythonv': 'n/a', 'ffmpegv': 'n/a', 'row_mt': False, 'mpvv': 'n/a'}
options = None
try:
if '-cn' not in ARGS:
caps.update(get_capabilities())
if '-hi' in ARGS or '--help-imode' in ARGS:
print_interactive_help()
sys.exit()
option... |
def openRaw(path, bpp, width, height):
return np.fromfile(open(path), np.dtype(bpp), width * height).reshape(height, width)
def applyBLC(raw, blcR, blcGr, blcGb, blcB):
correctedRaw = np.zeros(raw.shape, dtype=np.int32)
correctedRaw[0::2, 1::2] = raw[0::2, 1::2] - blcGr
correctedRaw[0::2, 0::2] = raw[0:... | The code processes a raw Bayer image by applying different Lens Shading Correction (LSC) methods (naive, simple, advanced) after calibrating gain values. It reads a raw image, applies black level correction, generates corrected versions using varying LSC algorithms, converts Bayer patterns to RGB, resizes images to 192... | def main():
tileWidthX = 16
tileWidthY = 16
imgWidth = 1920
imgHeight = 1096
scaleTo = (1920, 1080)
bayerType = cv2.COLOR_BAYER_RG2RGB
raw = openRaw('lsc_1920x1096_RG.raw', 'u2', imgWidth, imgHeight)
raw = applyBLC(raw, 800, 800, 800, 800)
rawOriginal = np.copy(raw)
gainY = cal... |
def _load_nodes(self, memento):
for node_mem in memento.node_mementos:
newnode = Node(node_mem.loc, self)
newnode.idx = node_mem.idx
def _load_grounds(self, memento):
for ground_mem in memento.ground_mementos:
newground = Ground(ground_mem.loc, self)
for i... | The code's main task is to restore an object's state from a memento by extracting node and ground indexes from the memento's data, then delegating to private methods (_load_nodes, _load_grounds, _load_elements) to reconstruct the object's internal structure using the provided memento. This follows the memento design pa... | def load(self, memento):
self.node_idxs = [node.idx for node in memento.node_mementos]
self.ground_idxs = [ground.idx for ground in memento.ground_mementos]
self._load_nodes(memento)
self._load_grounds(memento)
self._load_elements(memento) |
def top(puzzle):
return move_face(puzzle, TOP)
def back(puzzle):
return move_face(puzzle, BACK)
def right(puzzle):
return move_face(puzzle, RIGHT)
def left(puzzle):
return move_face(puzzle, LEFT)
def inv_top(puzzle):
return move_face(puzzle, INV_TOP)
def inv_back(puzzle):
return move_face(puzzle... | The function `pyraminx_nbrs` generates and returns a list of neighboring puzzle configurations by applying eight distinct moves (and their inverses) to the input Pyraminx puzzle state. These moves correspond to rotating the top, back, right, and left faces, along with their inverse rotations, to explore adjacent states... | def pyraminx_nbrs(puzzle):
nbrs = [
top(puzzle),
back(puzzle),
right(puzzle),
left(puzzle),
inv_top(puzzle),
inv_back(puzzle),
inv_right(puzzle),
inv_left(puzzle),
]
return nbrs |
def connect():#tries to connect
host = hostname()
port = portnumber()
gameSocket = socket.socket()
try:
gameSocket.connect((host,port))
gameInput = gameSocket.makefile('r')#reads the current board
gameOutput = gameSocket.makefile('w')#it writes to the board
return (locati... | The main task of the code is to establish a connection, verify its success using a username, and return a boolean indicating connection status along with the connection object if successful, or None if the connection fails. | def run() -> [bool,locationConnection] or None:# is the one fuction that if called runs the connection all the way through
conn = connect()
if conn == None:
return
bol = haveconnected(conn,username())
return [bol,conn] |
def update(self):
for enemy in self.enemys:
enemy.update()
if enemy.life==0:
self.enemys.remove(enemy)
for food in self.foods:
food.update()
if food.life==0:
self.foods.remove(food)
for bullet in self.bullets:
... | This code runs a game loop that continuously updates and renders the game state every 10 milliseconds while the game is active. When 'gameover' is True, it displays "game over" text, clears the screen, and waits for user input to proceed. | def start(self):
while True:
sleep_ms(10)
if self.gameover==False:
self.update()
self.render()
else:
self.clear
self.display.text('game over',20,16)
self.show()
self.waiting_input_... |
def skip_space_and_comments(self):
"""
Consumes characters until we encounter non-whitespace.
Also, skips comments.
Also, stops on end of file.
"""
while self.__cur_char.isspace() or self.__cur_char == '#':
if self.__cur_char == '#':
# consume the rest of the line
... | The main task of the code is to advance the lexer to the next token by skipping whitespace/comments, detecting EOF, and attempting to lex single-character, multi-character fixed, or other tokens. If none match, it creates an invalid token and consumes the current character, returning the resulting token. | def next(self):
"""
Advance the lexer to the next token and return
that token.
"""
# in our language, we skip spaces between tokens
self.skip_space_and_comments()
# detect end of file
if not self.__cur_char:
self.__tok = self.__create_tok(Token.EOF)
return self.... |
def predict_n_save_logo(self, shot_path):
'''
use AWL detector to crop and save logo
Args:
shot_path: path to screenshot
'''
if shot_path is None:
return None, None
logo_path, reference_logo = self.phishintention_wrapper.predict_n_save_... | The main task of the code is to associate a logo or domain with a brand name using OCR and logo detection. It processes input images, extracts brand information via logo2brand or domain2brand methods, validates results, and returns the logo, domains, brand name, logos, processing time, and status (success/failure) base... | def runit_simplified(self, driver, shot_path,
query_domain, query_tld, type='logo2brand'):
# Get Logo
filePath, reference_logo = self.predict_n_save_logo(shot_path)
if type == 'logo2brand':
if reference_logo is None: # no way to run logo2brand
... |
def message(msg,color,font_size,display_width,display_height):
font = pygame.font.Font('freesansbold.ttf',font_size)
text = font.render(msg,True,color)
screen.blit(text,[display_width,display_height])
def name(color,wdt,ht,n):
name = "NONE"
bla = True
text = "PLAYER_" + str(n)
font = pygame.font.Font(None, 50)
... | The main task of the code is to display a player name entry screen, create four player objects with specific colors and positions, and return the player list when the "PLAY" button is clicked. It uses Pygame to handle events, render text, and manage the page's interactive elements. | def page2():
flag = True
page2 = True
screen.fill(skyBlue)
while page2:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
message("ENTER PLAYER NAMES",black,50,width/4,height/8)
#pygame.draw.rect(screen,purple,[350,height-200,100,50])
#message("BACK",dirtyWhite,30,350+10,height-2... |
def activate(self):
active_tokens.append(self)
if self.color==red:
active_red.append(self)
for i in inactive_red:
if i==self:
inactive_red.remove(i)
elif self.color==blue:
active_blue.append(self)
for i in inactive_blue:
if i==self:
inactive_blue.remove(i)
elif self.color==green:
... | This code moves a token on a board by removing it from its current position, updating its position pointer based on color or dice roll, activating the token if necessary, and placing it in the new location. | def get_roll(self,dice):
for i in theBoard[self.position]: # we need to pop the token from the old position before appending it to the new location theBoard[pos]
if i==self:
theBoard[self.position].remove(i)
if self not in active_tokens:
if self.color==red:
self.po... |
def dist(rgb, col=(118, 103, 80), v1=0.1, v2=0.15, v3=0.15): # default col is average grid color
h, s, v = (rgb[0] / 255, rgb[1] / 255, rgb[2] / 255)
if abs(h - col[0]) < v1:
if abs(s - col[1]) < v2:
if abs(v - col[2]) < v3:
return True
return False
def get_letter(img, d... | The code extracts hand-related elements from an image by detecting specific color regions, cropping the image to focus on these areas, and processing the cropped sections to identify and normalize potential hand tiles for further analysis. | def get_hand(img, debug=False):
w, h = img.size
il = img.convert("HSV").load()
col = (76, 111, 111)
col = colorsys.rgb_to_hsv(col[0] / 255, col[1] / 255, col[2] / 255)
x = round(w / 2)
st = 0
en = 0
for y in range(round(h * 0.8), h):
rgb = il[x, y]
if dist(rgb, col, .02, ... |
def upsample(image, coef):
# isinstance(coef, int) is asserted
pixels = image.load()
new_image = Image.new('RGB', multiply_tuple(image.size, coef))
new_pixels = new_image.load()
for h in range(image.size[0]):
for w in range(image.size[1]):
for shift_h in range(coef):
... | The main task of the code is to process multiple images by applying various transformations: upsampling, downsampling, 1/2-pass resampling, greyscale conversion, and Otsu's binarization. Each processed image is saved in the "Data/lab1/" folder with distinct filenames. The function sequentially loads images, applies ope... | def run_test():
folder_path = "Data/lab1/"
img1 = Image.open(folder_path + "img1.bmp")
upsample(img1, 3).save(folder_path + "upsampled_img1.bmp")
downsample(img1, 3).save(folder_path + "downsampled_img1.bmp")
resample_2pass(img1, 7, 3).save(folder_path + "2pass_resampled_img1.bmp")
resample_1pas... |
def get_weight(image):
# calculates the weight of white
weight = 0
pixels = image.load()
for w in range(image.size[0]):
for h in range(image.size[1]):
weight += pixels[w, h]
return image.size[0] * image.size[1] - weight / 255
def get_centre_of_mass(image, weight=None):
if wei... | The function calculates various image features including weight, density, center of mass, inertia moments (horizontal, vertical, diagonal), and their relative values. It computes main inertia moments and optionally generates horizontal/vertical profiles if specified. The results are stored in a dictionary for analysis,... | def calculate_features(image, calculate_profiles=True):
w = 'weight'
d = 'density'
com = 'centre_of_mass'
rcom = 'relative_centre_of_mass'
him = 'horizontal_inertia_moment'
vim = 'vertical_inertia_moment'
rhim = 'relative_horizontal_inertia_moment'
rvim = 'relative_vertical_inertia_momen... |
def clean_letters(l, t, r, b):
left = get_letters(l)
top = get_letters(t)
right = get_letters(r)
bottom = get_letters(b)
pos = {**left, **top, **right, **bottom}
return pos
def solve_puzzle(pos, num, wordfile, exclude = []): # optionally exclude a list of answers
chars = set(pos.keys())
... | The function `transform_hard` processes puzzle data by retrieving a number from request arguments, cleaning specified positions, solving an easy puzzle to get answers, and generating HTML for a harder puzzle while excluding the easy answers. It uses `solve_puzzle` with "words_easy.txt" and `get_html` with "words_hard.t... | def transform_hard():
number = request.args.get('number')
pos = clean_letters('left','top','right','bottom')
easy_answers, num = solve_puzzle(pos, number, "words_easy.txt")
return get_html(pos, number, "words_hard.txt", exclude=easy_answers) |
def retrieve_data(id=None):
try:
# Connect to the SQLite database
conn = sqlite3.connect('words.db')
cursor = conn.cursor()
if id is not None:
# Execute the SQL query to retrieve data for the given id
cursor.execute('''SELECT * FROM description WHERE id = ?''... | This function updates a word and its description in an SQLite database, refreshes the UI with new data, and closes the update window. It connects to 'words.db', executes an SQL UPDATE query using parameters, commits changes, reloads the word list from the database, and triggers UI updates to display the modified conten... | def update_word_in_database(new_word, new_description):
try:
# Connect to the SQLite database
conn = sqlite3.connect('words.db')
cursor = conn.cursor()
# Update word and description in the database
cursor.execute('''UPDATE description SET word=?, desc... |
def display_words_ui(body_frame):
# Get the list of existing widgets
widgets = body_frame.winfo_children()
# Skip the first two widgets (assuming they are the Add New Word and Delete Word buttons)
existing_widgets = widgets[2:]
# Destroy existing word frames
for widget in existing_widgets:
... | The main task of the code is to handle user submission of a word and its description. It validates input fields, checks for duplicates via `check_user_word()`, updates the global `word_list` with parsed JSON data from `retrieve_data()`, and refreshes the UI to display updated word entries. | def submit():
global word_list
word_list = []
# print(f"check{word_list}")
display_words_ui(body_frame)
if word.get() == "" and description.get("1.0", END) == "\n":
alert_message("Both Word and Description are Empty!")
elif word.get() == "":
alert_message(" Word is Empty!")
... |
def display_startup_message(self):
""" Display the welcome prompt. """
print('Welcome to Tic Tac Toe!')
def reset_board(self):
""" Reset the board. """
self.board = self.generate_new_board(self.size)
def display_board(self):
""" Display the board. """
print('\n')
... | The code runs a game loop where players take turns making moves until an end condition is met. It displays the board, handles user input, alternates players, and checks for game over. After each game, it asks the player if they want to replay. | def run(self):
""" Play the game. """
self.display_startup_message()
replay = True
while replay:
self.reset_board()
self.display_board()
while not self.check_for_end_condition():
self.get_user_input()
self.toggle_player... |
def write_conditions(conditions, go_file):
if len(conditions) == 0:
go_file.write("""Conditions: []ParliamentCondition{},
""")
else:
go_file.write("""Conditions: []ParliamentCondition{
""")
for condition in conditions:
go_file.write("""{
""")
go_file.write("""Cond... | This function writes a Go service configuration structure to a file, including conditions, prefix, privileges, resources, and service name. It formats these elements using escape sequences and organizes them within a ParliamentService block. The main task is generating structured Go code from a Python dictionary repres... | def write_service(service, go_file):
go_file.write("""ParliamentService{
""")
write_conditions(service.get("conditions", []), go_file)
go_file.write("""Prefix: \"{0}\",
""".format(escape_string(service["prefix"])))
write_privileges(service.get("privileges", []), go_file)
write_resources(service.get(... |
def KW_INPUT(self):
if (self.tokens[self.current_position].tag == tags.INPUT):
self.pushInStack(self.tokens[self.current_position])
self.current_position += 1
return True
return False
def bkt_open(self):
if self.tokens[self.current_position].tag == tags.BRACKE... | The main task of the code is to validate the syntax of an input statement in a parser. It checks for the presence of a keyword, opening bracket, variable, closing bracket, and semicolon in sequence. If any component is missing, it raises a ParseError with the expected token and current value, or returns False if the ke... | def inputting(self):
if not self.KW_INPUT():
return False
elif not self.bkt_open():
raise ParseError("(", self.tokens[self.current_position].value)
elif not self.var():
raise ParseError("variable", self.tokens[self.current_position].value)
elif not sel... |
def printing(self, value):
if self.variables.get(value) is not None:
print(f"> {str(self.variables.get(value))}")
else:
print(f"> {str(value)}")
def inputting(self, var):
if self.variables.get(var) is not None:
v = str(input("<< "))
self.variable... | The code processes a sequence (`poliz`) by iteratively evaluating elements on a stack. It handles control flow (e.g., `!`, `!F`), I/O operations (`print`, `input`), and arithmetic/logical operations (e.g., `+`, `*`, `and`, `or`). Unrecognized elements trigger errors. The stack manages operands and addresses, while `pos... | def process(self):
while self.pos < len(self.poliz):
self.stack.append(self.poliz[self.pos])
self.pos += 1
stack_head = self.stack.pop()
if stack_head == "!":
self.pos = self.stack.pop()
elif stack_head == "!F":
adr = s... |
def predict_class(self, sentence):
bow = self.bag_of_words(sentence)
res = model.predict(array([bow]))[0]
ERROR_THRESHOLD = 0.25
# storing [index, class]
results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
# sorting the probability in reverse order: high... | The code processes user input by classifying the intent of the message, retrieving a corresponding response from a predefined set of intents, and then vocalizing the generated response. It uses global message data, predicts the intent, fetches the reply, and outputs it through the speak function. | def response(self):
global message
ints = self.predict_class(message)
res = self.get_response(ints, intents)
self.speak(res) |
def center_window(self):
current_position = self.frameGeometry()
center_of_desktop = QDesktopWidget().availableGeometry().center()
current_position.moveCenter(center_of_desktop)
self.move(current_position.topLeft())
def closeCoursework(self,eventbox):
self.eventbox.clear()
... | This code initializes a GUI window with specified dimensions, sets the title and icon, centers the window, creates a text edit widget, and prepares functionality for coursework closure and deadline updates. | def __init__(self, w, h) -> None: #double underscore means prewritten function, to not be confused with functions that i wrote myself
super().__init__() #single undersocre means selfwritten function
self.setWindowTitle("CAGE") #Title of the window appearing in the left hand corner
... |
def checkValid(self):
entry = self.input_bar.text()
if(len(entry) < 15): # unreasonably small entry considering keywords length
return False # not valid
if not (' on ' in entry and ' at ' in entry and ' by ' in entry): # necessary keyword
return False
last_on... | The code adds an event by validating input, appending the uppercase entry to 'userdata.txt', clearing the input field, and updating deadlines/closing coursework. | def add_event(self,eventbox):
entry = self.input_bar.text()
entry.upper()
if self.checkValid():
with open('userdata.txt', 'a+') as f:
f.write("\n" + entry)
self.input_bar.setText('')
self.updateDeadline(self.deadlineBox)
self.closeCoursework(se... |
def send_reaction(gesture):
desktop, zoom = focus_zoom()
meeting_tools = get_meeting_tools()
reactions = meeting_tools.child_window(title='Reactions')
reactions.click()
reactions_panel = desktop['Dialog'] # TODO: this could change
reactions_panel[gesture].click()
def mic_state(getState):
me... | This function maps gesture IDs to specific actions in a Zoom-like interface: triggers predefined reactions for IDs 0-4, disables microphone/video for IDs 5-6, handles live transcription for ID 7 (with external management), and toggles raise-hand status for ID 8. | def zoom_function_wrap(gesture_id):
if gesture_id < 5:
send_reaction(buttons[gesture_id])
elif gesture_id == 5:
mic_state(False)
elif gesture_id == 6:
video_state(False)
elif gesture_id == 7:
pass # This starts live transcription, called elsewhere, so as to avoid sharing... |
def clear_screen(self):
if os.name == 'posix':
# For Unix/Linux/MacOS
os.system('clear')
elif os.name == 'nt':
# For Windows
os.system('cls')
def view_movies(self):
self.cursor.execute("SELECT * FROM movies")
movies_data = self.cursor.fetch... | The main task of the code is to display a customer menu with options to view movies, book tickets, manage bookings, or logout. It handles user input, delegates actions to corresponding methods, and maintains the login state by resetting the logged-in user upon logout. The loop continues until the user selects the logou... | def customer_menu(self, customer):
while True:
self.clear_screen()
print(f"\nHello! " + customer.email)
print("\n1. View movies and showtimes\n2. Book a ticket\n3. Manage bookings\n4. Logout" + self.SELECT_OPTION_PROMPT)
customer_choice = input()
if c... |
def clear_screen(self):
if os.name == 'posix':
# For Unix/Linux/MacOS
os.system('clear')
elif os.name == 'nt':
# For Windows
os.system('cls')
def view_movies(self):
self.cursor.execute("SELECT * FROM movies")
movies_data = self.cursor.fetch... | The code provides an admin menu interface for managing movies, schedules, and bookings. It displays options to view movies, manage schedules, handle bookings, or logout. User input directs actions like viewing, managing, or logging out, with the loop persisting until logout is chosen, which resets the logged-in user an... | def admin_menu(self, admin):
while True:
self.clear_screen()
print("\n1. View Movies and Showtimes\n2. Manage Movies and Schedules\n3. Manage Customer Bookings\n4. Logout" + self.SELECT_OPTION_PROMPT)
admin_choice = input()
if admin_choice == "1":
... |
def gameover(pacman, pinky, blinky):
if pinky == pacman or blinky == pacman:
return 0
else:
return 1
def move_pacman(maze, pacman, pinky, blinky):
best_move_pacman = minimax(0, 0, 1, maze, pacman, pinky, blinky)
return best_move_pacman
def print_board(self):
for i in range(0, 9)... | The code runs a Pacman game loop, moving Pacman based on the `move_pacman` function's output, updating the score and counter when Pacman eats dots, checking win/lose conditions (gameover), and iterating until the game ends. It handles ghost movement, board updates, and displays the score/iteration. | def run_game(self):
while gameover(self.pacman.position, self.pinky.position, self.blinky.position) > 0:
v = move_pacman(self.board, self.pacman.position, self.pinky.position, self.blinky.position)
if v == 1:
self.pacman.up()
elif v == 2:
self.... |
def gameover(pacman, pinky, blinky):
if pinky == pacman or blinky == pacman:
return 0
else:
return 1
def move_pacman(maze, pacman, pinky, blinky):
best_move_pacman = minimax(0, 0, 1, maze, pacman, pinky, blinky)
return best_move_pacman
def can_move_ghost(self, pinky, blinky):
d... | This function simulates a Pacman game test by continuously moving Pacman based on the output of move_pacman(), updating scores when dots are eaten, and checking gameover conditions. It breaks the loop when Pacman loses (collides with ghosts) or wins (collects all dots), incrementing respective counters. The loop runs u... | def run_game_test(self):
while gameover(self.pacman.position, self.pinky.position, self.blinky.position) > 0:
v = move_pacman(self.board, self.pacman.position, self.pinky.position, self.blinky.position)
if v == 1:
self.pacman.up()
elif v == 2:
... |
def init_feature(name,nfeat):
if name == 'sift':
if nfeat is not None:
detector = cv.SIFT_create(nfeat)
norm = cv.NORM_L2
else:
detector = cv.SIFT_create()
norm = cv.NORM_L2
# SURF patent not yet expired
#elif name == 'surf':
# detector ... | This function georeferences an input image using a reference image by detecting and matching keypoints (via FLANN) to compute ground control points (GCPs). It applies transformations, resampling, and saves the aligned output. Optional parameters allow saving GCPs as shapefiles, visualizing matches, and adjusting matchi... | def georef(input_file, reference_file, output_file,
feature_name, target_resize_scale, reference_resize_scale,
nfeat, flann, transform_type, resampleAlg,
gcps_out, tile, offset,ki, kr, ratio=0.75,
noData = 0, draw_plot=False, convert=False, apply_clahe=False):
"""Georefer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.