dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def init_weights_and_bias_with_zeros(dim): w = np.zeros((dim,1)) b = 0 return w, b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): #This function optimizes w and b by running a gradient descent algorithm costs = [] for i in range(num_iterations): # Cost and g...
The function implements a logistic regression model to classify data. It initializes parameters (weights and bias), performs gradient descent to optimize these parameters using training data, and evaluates model performance on training and test sets. It calculates accuracy, stores costs, predictions, and parameters in ...
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_trai...
def hide(self, channel: int) -> None: if(self.channelComponents[channel].isVisible()): self.channelComponents[channel].hide() self.setChannelChecked[channel].setChecked(False) self.clear(channel) else: self.setChannelChecked[channel].setChecked(True) ...
The main task of the code is to load a signal file for a specified channel by opening a file dialog, hiding/clearing the channel's UI, storing the selected file path, and invoking the openFile method to process the loaded file.
def browse(self, channel: int) -> None: self.hide(channel) self.clear(channel) self.filenames[channel] = qtw.QFileDialog.getOpenFileName( None, 'Load Signal', './', "Raw Data(*.csv *.txt *.xls)") path = self.filenames[channel][0] self.openFile(path, channel)
def toggle(self, channel: int) -> None: if(self.channelComponents[channel].isVisible()): self.channelComponents[channel].hide() self.setChannelChecked[channel].setChecked(False) self.clear(channel) else: self.setChannelChecked[channel].setChecked(True) ...
This code initializes a GUI application with three signal channels, setting up graphs, spectrograms, and controls (play, pause, zoom, etc.) for each channel. It connects UI elements to functions for data handling, visualization, and PDF generation, while organizing data structures to manage signal amplitude, time, and ...
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filenames = ['', '', ''] self.graphChannels = [self.ui.signal1Graph, self.ui.signal2Graph, self.ui.signal3Graph] self...
def hide(self, channel: int) -> None: if(self.channelComponents[channel].isVisible()): self.channelComponents[channel].hide() self.setChannelChecked[channel].setChecked(False) self.clear(channel) else: self.setChannelChecked[channel].setChecked(True) ...
This code initializes a GUI application for multi-channel signal processing. It sets up three signal channels with associated graphs, spectrograms, and controls (play, pause, zoom, clear). It connects UI elements to functions, initializes data structures for real-time plotting, and configures initial states (e.g., show...
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filenames = ['', '', ''] self.graphChannels = [self.ui.signal1Graph, self.ui.signal2Graph, self.ui.signal3Graph] self...
def f(self, x): return f(x, self.x_opt, self.Q) def grad(self, x): return grad(x, self.x_opt, self.Q) def backtracking(self, x, p, g, omega): alpha = self.alpha_0 while self.f(x + alpha*p) > (self.f(x) + omega*p.T@g*alpha): alpha = self.rho * alpha return alpha def fr_beta(self, g, gp): return np....
The code performs four variants of conjugate gradient optimization (Fletcher-Reeves, Polak-Ribière, Hestenes-Stiefel, Dai-Yuan) with backtracking line search. It iteratively updates the search direction using gradient information, tracks iterations and function values, and terminates when gradient norm falls below a th...
def update(self, x_k): x_0 = x_k for i in range(4): k = 0 x_k = x_0 self.itr[i].append(k) self.f_val[i].append(self.f(x_k)[0]) g_k = self.grad(x_k) p_k = - g_k while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) alpha_k = self.backtracking(x_k, p_k, g_k, se...
def f(self, x): return f(x, self.n) def grad(self, x): return grad(x, self.n) def backtracking(self, x, d): alpha = self.alpha_0 while self.f(x + alpha*d) > (self.f(x) - 0.5*(np.linalg.norm(d, 2)**2)*alpha): alpha = self.rho * alpha return alpha
This code implements gradient descent with backtracking line search to minimize a function. It iteratively updates the parameter x_k by moving in the direction of the negative gradient, using backtracking to determine the step size alpha_k. The algorithm tracks iterations and function values, stopping when the gradient...
def update(self, x_k): k = 0 self.itr.append(k) self.f_val.append(self.f(x_k)[0]) while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) d_k = - g_k alpha_k = self.backtracking(x_k, d_k) x_next = x_k + alpha_k*d_k k += 1 self.itr.append(k) self.f_val.append(self.f(x...
def f(self, x): return f(x, self.n) def grad(self, x): return grad(x, self.n) def backtracking(self, y, d): alpha = self.alpha_0 while self.f(y + alpha*d) > (self.f(y) - 0.5*(np.linalg.norm(d, 2)**2)*alpha): alpha = self.rho * alpha return alpha
The code performs gradient descent optimization with backtracking line search. It iteratively updates the solution vector $ x_k $ by computing the gradient $ g_k $, determining a step size $ \alpha_k $, and adjusting $ x_k $ along the direction $ -g_k $. The algorithm tracks iterations, function values, and a parameter...
def update(self, x_k): y_k = x_k k = 0 self.itr.append(k) self.f_val.append(self.f(x_k)[0]) while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) d_k = - g_k alpha_k = self.backtracking(y_k, d_k) x_next = y_k + alpha_k*d_k if self.f(x_next) <= self.f(x_k): tau_n...
def f(self, x): return f(x, self.n) def grad(self, x): return grad(x, self.n) def backtracking(self, x, p, g): alpha = self.alpha_0 while self.f(x + alpha*p) > (self.f(x) + self.omega*p.T@g*alpha): alpha = self.rho * alpha return alpha def dy_beta(self, gp, y, p): return np.linalg.norm(gp,2)**2 / ...
This code implements a conjugate gradient descent algorithm with backtracking line search to minimize a function. It iteratively updates the parameter vector x_k using gradient information, computes search directions p_k, and adjusts step sizes via backtracking. The loop continues until the gradient norm falls below a ...
def update(self, x_k): x_0 = x_k k = 0 x_k = x_0 self.itr.append(k) self.f_val.append(self.f(x_k)[0]) g_k = self.grad(x_k) p_k = - g_k while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) alpha_k = self.backtracking(x_k, p_k, g_k) x_next = x_k + alpha_k*p_k g_next...
def f(self, x): return f(x, self.n) def grad(self, x): return grad(x, self.n) def backtracking(self, x, d, g): alpha = self.alpha_0 while self.f(x + alpha*d) > (self.f(x) + self.omega*d.T@g*alpha): alpha = self.rho * alpha return alpha def bfgs(self, H, s, y): return -(s@y.T@H + H@y@s.T)/(s.T@y) +...
This code implements the BFGS quasi-Newton optimization algorithm, iteratively updating the parameter vector $x_k$ and the inverse Hessian approximation $H_k$ using gradient information and a backtracking line search. It terminates when the gradient norm falls below a threshold or after 1000 iterations, recording funct...
def update(self, x_k, H_k): x_0 = x_k H_0 = H_k k = 0 x_k = x_0 H_k = H_0 self.itr.append(k) self.f_val.append(self.f(x_k)[0]) g_k = self.grad(x_k) while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) d_k = - H_k@g_k alpha_k = self.backtracking(x_k, d_k, g_k) x_n...
def f(self, x): return f(x, self.x_opt, self.Q) def grad(self, x): return grad(x, self.x_opt, self.Q) def backtracking(self, y, g): alpha = self.alpha_0 while self.f(y - alpha*g) > (self.f(y) - 1/2*(np.linalg.norm(g, 2)**2)*alpha): alpha = self.rho * alpha return alpha
This code performs iterative optimization using gradient descent with a backtracking line search. It updates the solution $ x_k $ by adjusting the step size $ \alpha_k $ and computes a new search direction $ y_k $. The algorithm maintains a sequence of iterates, function values, and a parameter $ \tau $ to control conv...
def update(self, x_k): k = 0 self.itr.append(k) self.f_val.append(self.f(x_k)[0]) y_k = x_k while np.linalg.norm(self.grad(x_k), 2) >= self.epsilon: g_k = self.grad(x_k) alpha_k = self.backtracking(y_k, g_k) x_next = y_k - alpha_k*g_k if self.f(x_next) <= self.f(x_k): tau_next = 1/2 * (1 ...
def grad(self, x): return grad(x, self.x_opt, self.Q) def r(self, x, g, a, b, delta): r = [] for i in range(len(g)): if x[i] < a[i] + delta: r.append(min([0,g[i]])) elif a[i] + delta <= x[i] and x[i] <= b[i] - delta: r.append(g[i]) else: r.append(max([0,g[i]])) r = np.array(r, dtype=float)...
This code implements an iterative optimization algorithm using gradient descent with backtracking line search and projection. It updates the solution $ x_k $ by computing gradients, determining step sizes via backtracking, projecting onto feasible regions, and iterating until the residual $ r_k $ falls below a threshol...
def update(self, x_k): k = 0 g_k = self.grad(x_k) d_k = - g_k r_k = self.r(x_k, g_k, self.a, self.b, self.delta) self.itr.append(k) self.f_val.append(self.f(x_k)[0]) while np.linalg.norm(r_k, 2) >= self.epsilon: g_k = self.grad(x_k) d_k = - g_k alpha_k = self.backtracking(x_k, g_k) v_k = x_k ...
def berry_collision(self): head = self.snake.blocks[0] if (head.x == self.berry.position.x and head.y == self.berry.position.y): self.position_berry() self.score += 1 else: self.snake.blocks.pop() def head_hit_wall(self): head = self.snake....
The code runs a game loop for a snake game, handling user input, updating the snake's position, checking collisions with walls/body, and rendering frames. It terminates when the game ends (e.g., collision) or the user quits, displaying the final score before exiting Pygame.
def play(self): while self.running: for event in pygame.event.get(): if event.type == QUIT: self.running = False self.frame = (self.frame + 1) % 2 self.snake.handle_input() self.berry_collision() if self.head_hit_wa...
def berry_collision(self): head = self.snake.blocks[0] if (head.x == self.berry.position.x and head.y == self.berry.position.y): self.position_berry() self.score += 1 self.reward = 10 else: self.snake.blocks.pop() def head_hit_wall(self...
The function processes a game step by handling the given action, updating the snake's state, checking collisions with walls/body, and determining game over conditions. It returns the reward, game status, and score, while managing game events, frame updates, and rendering.
def play_step(self, action): game_over = False self.reward = 0 for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() self.total_step += 1 self.frame = (self.frame + 1) % 2 self.s...
def get_merged_walks(self, jawbone5): save_file_path = "./data/merged_walks.csv" if os.path.exists(save_file_path): merged_walks = pd.read_csv(save_file_path) else: sorted_minutes = jawbone5[ jawbone5["steps"] > Preprocessor.MINIMUM_STEPS_PER_MINUTE ...
The code preprocesses Jawbone activity data by selecting relevant columns, filtering users with insufficient data (≥10 days), calculating walking statistics (minutes/day, walks/day), merging walking intervals, generating hour-matrix features, analyzing missing data, and preparing structured input for a machine learning...
def preprocess(self): log("Preprocessor.preprocess()") if self.model_parameter in ("walk only", "walk and alarm"): ###### 1. Selecting columns ###### log("###### 1. Selecting columns ######") # duplicate jawbone data jawbone2 = self.data_loader.raw_data["...
def get_r1cs_file(circ_file): return get_base(circ_file) + ".r1cs" def get_sym_file(circ_file): return get_base(circ_file) + ".sym" def get_wasm_file(circ_file): return os.path.join(get_js_dir(circ_file), get_base(circ_file) + ".wasm") def get_js_dir(circ_file): return get_base(circ_file) + "_js"
The code compiles a circuit using the Circom tool, generating an R1CS constraint system file, symbols file, WebAssembly (WASM) file, and JavaScript directory. It executes the `circom` command with specified flags, captures output, and stores paths to the generated files in instance variables for later use.
def compile(self): """Compiles the circuit and generates an r1cs file, a symbols file, a wasm file, and a js dir""" subprocess.run( ["circom", self.circ_file, "--r1cs", "--sym", "--wasm", '-o', self.output_dir], capture_output=True, cwd=self.working_dir, ) ...
def _init_dir(self): """ create directories if they don't exist yet """ for dir in [self.outdir_poe, self.outdir_res]: if not os.path.isdir(dir): os.makedirs(dir) def catch(self, osvtype='POE', start=None, stop=None): """ check a server for fil...
The main task of the code is to download missing POE (Product of Earth) files from the ESA Quality Control server and optionally update RES (Reference Earth) files by retrieving newer RES files and deleting outdated ones. It ensures all necessary data is locally available for multi-node SAR processing, handling large d...
def update(self, update_res=True): """ Caution! This method is intended for downloading all available POE files and all RES files for whose time span no POE file yet exists. This will be a data volume of several GB and is particularly suited for multi-node SAR processing where not ...
def branch_disorder(data, target_classifier): """Given a list of points representing a single branch and a Classifier for determining the true classification of each point, computes and returns the disorder of the branch.""" num_branch = len(data) classified_data = split_on_classifier(data, target_c...
The function constructs a greedy ID tree by recursively selecting the best classifier to split data into branches, aiming for perfect classification. It starts with a node, checks if data is homogeneous (if so, sets classification), else picks the best classifier, splits data, and recursively builds subtrees. If no goo...
def construct_greedy_id_tree(data, possible_classifiers, target_classifier, id_tree_node=None): """Given a list of points, a list of possible Classifiers to use as tests, a Classifier for determining the true classification of each point, and optionally a partially completed ID tree, returns a completed ID ...
def rstButton(self): self.answer = "" self.updtQuestion() self.letters = list(set(self.picFiles[self.picNum].upper())) while len(self.letters) < 12: self.new_letter = chr(random.randint(65, 90)) if self.new_letter not in self.letters: self.letters....
The main task of the code is to reset the game state by initializing the level to 1, re-enabling the submit button, restoring the game frame visibility, and updating the interface elements (button, status, question) to prepare for a new game session.
def restartGame(self): self.level = 1 self.submit_button.config(state=NORMAL) self.gameFrame.deiconify() self.rstButton() self.updtStatus() self.updtQuestion()
def updtStatus(self): self.level_text.config(text=f"Level {self.level}") self.coins_label.config(text=f"{self.coins}") if self.coins >= 2: self.hint_button.config(state=NORMAL) else: self.hint_button.config(state=DISABLED) if self.coins >= 10 and self.leve...
The code's main task is to load a saved game from a JSON file. It opens a file dialog for the user to select a game file, reads the JSON data, retrieves level, coins, and picture number values, updates the game's visual elements (like the current picture), and refreshes the game state by calling methods to update statu...
def loadGame(self): self.openFile = filedialog.askopenfilename(initialdir="savefile", title="Select saved game file", filetypes=(("JSON files", "*.json"), ("All files", "*.*"))) if self.openFile: with open(self.openFile, "r") as f: self.data = json.load(f) sel...
def gameWidgets(self): self.gm_image = PhotoImage(file="widget_textures/background.png") self.gm_label = Label(self.gameFrame, image=self.gm_image) self.gm_label.place(x=0, y=0, relwidth=1, relheight=1) self.status_label = Frame(self.gameFrame, width=900, height=50, bg="#1a1e27") ...
This code initializes a Tkinter-based game window for "Four Pictures One Word," setting up the GUI with a title, size, and background. It loads image file paths from 'picList.txt' using exception handling, initializes game variables (level, coins, etc.), and calls methods to create game widgets, reset buttons, update s...
def __init__(self): super().__init__() self.gameFrame=Tk() self.gameFrame.title("Four Pictures One Word") self.gameFrame.geometry("600x600") self.gameFrame.configure(background="#1d222e") self.random=random self.level = 1 self.coins = 100 self.answ...
def updtStatus(self): self.level_text.config(text=f"Level {self.level}") self.coins_label.config(text=f"{self.coins}") if self.coins >= 2: self.hint_button.config(state=NORMAL) else: self.hint_button.config(state=DISABLED) if self.coins >= 10 and self.leve...
The code checks if the user's answer matches the current picture's filename by comparing character sets. If valid, it rewards the player with coins, advances the level, updates the status, ends the game, and loads the next picture.
def finalAnswer(self): winsound.PlaySound('sounds/submit.wav',1) if set(self.answer.lower()) == set(self.picFiles[self.picNum].lower()) and \ all(x in self.picFiles[self.picNum].lower() for x in self.answer.lower()): self.coins += 10 self.level += 1 se...
def updtStatus(self): self.level_text.config(text=f"Level {self.level}") self.coins_label.config(text=f"{self.coins}") if self.coins >= 2: self.hint_button.config(state=NORMAL) else: self.hint_button.config(state=DISABLED) if self.coins >= 10 and self.leve...
The main task of the code is to allow a player to skip a level by spending 10 coins. If the player has sufficient coins, the function deducts 10 coins, increments the level, updates the game status, finishes the current game state, changes the visual display, and updates the question. A sound effect is played to confir...
def skipLevel(self): winsound.PlaySound('sounds/skip.wav',1) if self.coins >= 10: self.coins -= 10 self.level += 1 self.updtStatus() self.finishGame() self.changePic() self.updtQuestion()
def get_most_common_words(uploaded_file_location): word_list = [] with pdfplumber.open(uploaded_file_location) as pdf: for i in range(len(pdf.pages)): page = pdf.pages[i] text = page.extract_text().splitlines() for line in text: words = line.split(" "...
The main task of the code is to process a given cloud file by extracting keywords from its content and abstract, generating a report of these keywords, storing the results in a cloud bucket, logging processing time, updating a database, and sending status messages via a producer. The function handles file retrieval, ke...
def output_file(cloud_file_location): start_time = timeit.default_timer() event_id = str(uuid.uuid4()) file_name = os.path.basename(cloud_file_location).split(".")[0] service_type = os.environ.get("APP_NAME") thesis_id = file_name producer = Producer() uploaded_file_location = get_file_fr...
def parse_ipv4(ipv4_bytes): ipv4_parts = [] for byte in ipv4_bytes: ipv4_parts.append(str(byte)) return '.'.join(ipv4_parts) def parse_name(self, byte_nameserver, dns_answer): parts = self.get_parts_ns(byte_nameserver, dns_answer) decoded_parts = [] for part i...
This function parses DNS response records from the provided byte data, extracts details like type, class, TTL, and the actual response value, and appends them to the dns_response structure. It processes multiple records based on answer_count, handling IPv4, name, and IPv6 responses differently, then returns the remaini...
def add_info_to_resp_and_return_ans_tail(self, answer_part, dns_response, full_dns_answer, answer_type, answer_count): for _ in range(answer_count): response_type = int.from_bytes(answer_part[2:4], "big") ...
def parse_header(bytes_header): return {"transaction_id": int.from_bytes(bytes_header[:2], "big"), "resp_code": int.from_bytes(bytes_header[2:4], "big"), "question_count": int.from_bytes(bytes_header[4:6], "big"), "...
The code parses a DNS response message into a structured dictionary, extracting the header and body sections. It processes the question and answer sections using helper methods, organizing data into 'question', 'answers', 'authoritative', and 'additional' fields within the response. The parsed result is returned as a d...
def parse(self, dns_answer): header = self.parse_header(dns_answer[:12]) dns_response = {"header": header} tail = dns_answer[12:] dns_response["body"] = {"question": [], "answers": [], "authoritative": [], "additional": []} dns_response["body"]["...
def is_dir(self, directory): """Helper function to create directories if they don't exist Args: directory (str): Directory path """ if not os.path.isdir(directory): os.makedirs(directory) print(f'Creating {directory}...') def read_img(self): """Fu...
The code's main task is to perform edge detection on an image using a series of steps: reading the image, applying Gaussian smoothing, calculating gradients with Prewitt's operator, performing non-maxima suppression, and applying thresholding. These operations are executed in sequence within a class method to process a...
def driver(self): """Calls canny edge detection functions in order: - Read image - Gaussian smoothing - Gradient and gradient magnitude calculation using prewitt's operator - Non-maxima suppression - Thresholding """ self.is_dir(self.ou...
def gradient_info_calc(self, img): """Calculates horizontal and vertical gradients, gradient magnitude, and gradient angle. Gradient magnitude is normalized by 3*root(2) Gradient angle is set to range [0,180]. If negative: Add 360. If > 180: Subtract 180. Args: img (nd...
The function computes Histogram of Oriented Gradients (HOG) descriptors for a grayscale image by calculating gradient magnitude and direction, generating cell-wise histogram bins, normalizing these histograms in blocks, and flattening the result into a 7524-length descriptor vector. It returns the normalized gradient m...
def hog_driver(self, img): """Driver function to call steps of HOG to create descriptors Args: img (ndarray): Numpy array of grayscale image Returns: ndarray: Numpy array of normalized gradient magnitude ndarray: Numpy array of descriptor, column vector of l...
def bgr_2_gray(self, img): """BGR to GRAY conversion. cv2::imread returns image in BGR format Args: img (ndarray): Numpy array for colored image Returns: ndarray: Numpy array for grayscale image """ blue, green, red = img[:,:,0], img[:,:,1], i...
The main task of the code is to process image data by parsing folders, reading images, computing HOG descriptors, and organizing them into training/test dictionaries. Training data includes images with class labels and descriptors, while test data adds predicted labels and KNN info. Specific images are written to a des...
def load_data(self): """Main function, parses through image data folder, reads image, calculates descriptor and stores in a dict based on training/test substring Dict structure: Training images: {image_filename:{'img':img,'class':class label,'descriptor':descriptor}...
def load_data(self): """Main function, parses through image data folder, reads image, calculates descriptor and stores in a dict based on training/test substring Dict structure: Training images: {image_filename:{'img':img,'class':class label,'descriptor':descriptor}...
The main task of the code is to orchestrate a workflow by sequentially calling three methods: loading data, performing classification, and displaying results, thereby automating the end-to-end process of data handling and analysis.
def driver(self): """Driver calls data loading, classification, and result display """ self.load_data() self.classify() self.display()
def backpropagate(self, input_values, ideal_values, learning_rate=1): self.feedforward(input_values) self.__calculate_deltas(ideal_values) self.__calculate_gradients() self.__correct_weights(learning_rate) def feedforward(self, input_values): self.__set_input_values(input_values)...
This code trains a neural network using backpropagation until the error falls below a specified threshold. It iteratively adjusts weights by propagating errors through the network, calculates total error across training data, and prints progress. Training stops manually via Ctrl-C, which triggers data saving. If traini...
def train(self, training_data, learning_rate=1, max_error=0.01): print("Training network with rate set to {0}, until error is less than {1} .".format(learning_rate, max_error)) print("Press Ctrl-C to stop.") try: saved_db = False error = 1 while error > max_er...
def CheckInputs(self): if (self.playing): for event in pygame.event.get(): if (event.type == QUIT): self.running = False elif (event.type == KEYDOWN): if (event.key == K_ESCAPE): self.menu.ShowMenu() ...
This code manages a game loop, handling input, rendering, and game state updates. It maintains the game's running state, checks for time limits, updates AI when playing, and spawns time-over enemies if applicable. The loop runs at a defined FPS, ensuring smooth gameplay and proper timing for level progression and time-...
def Run(self): self.running = True # True while the game is not exited self.playing = False # True while a level is being played self.timeOver = False # True while a level is being played and the 60 seconds are over while (self.running): self.CheckInputs() self.D...
def welcome(self,chatID, noWelcome = False): welcome_string = '' if (noWelcome == False): welcome_string = "WhatsApp Demo Bot Python\n" else: welcome_string = """Incorrect command Commands: 1. chatid - show ID of the current chat 2. time - show server time 3. me - show yo...
The code processes incoming messages by checking if they contain specific commands. If a message is not from the user, it identifies the command (e.g., 'hi', 'time', 'file') and triggers corresponding actions like sending a welcome message, time, or handling files. If no valid command is detected, it defaults to a welc...
def processing(self): if self.dict_messages != []: for message in self.dict_messages: text = message['body'].split() if not message['fromMe']: id = message['chatId'] if text[0].lower() == 'hi': return se...
def get_twitter(): return TwitterAPI(consumer_key, consumer_secret, access_token, access_token_secret) def read_screen_names(filename): path = 'E:/MS in CS/SEM 2/OSNA/Assignments/juhideshpande/a0/candidates.txt' candidates_file = open(path,'r') return(candidates_file.read().split()) def get_users(twitte...
The main task of the code is to analyze Twitter user relationships by retrieving candidate screen names, fetching their friend data, calculating overlaps, and visualizing the network. It connects to Twitter, processes user data, computes friend counts, identifies common friends, and generates a graph to visualize conne...
def main(): """ Main method. You should not modify this. """ twitter = get_twitter() screen_names = read_screen_names('candidates.txt') print('Established Twitter connection.') print('Read screen names: %s' % screen_names) users = sorted(get_users(twitter, screen_names), key=lambda x: x['screen_...
def download_data(): """ Download and unzip data. DONE ALREADY. """ url = 'https://www.dropbox.com/s/8oehplrobcgi9cq/imdb.tgz?dl=1' urllib.request.urlretrieve(url, 'imdb.tgz') tar = tarfile.open("imdb.tgz") tar.extractall() tar.close() def read_data(path): """ Walks all subdirect...
The code evaluates text classification models by testing various tokenization and feature extraction combinations on training data. It computes cross-validation results, identifies the best/worst performing configurations, visualizes accuracy trends, and trains the optimal classifier. The model's coefficients are analy...
def main(): """ Put it all together. ALREADY DONE. """ feature_fns = [token_features, token_pair_features, lexicon_features] # Download and read data. download_data() docs, labels = read_data(os.path.join('data', 'train')) # Evaluate accuracy of many combinations # of tokenizatio...
def compute_key_schedule(key: List[bool]) -> List[List[bool]]: """For the decryption compute the entire key_schedule.""" key_registry = key schedule = [] for round in range(1, 33): schedule.append(key_registry[:64]) key_registry = update_registry(key_registry, round) return schedule ...
The code decrypts a bitfield ciphertext using the PRESENT algorithm by applying the inverse key schedule, P-layer, and S-box layers in reverse order, starting with the last round key and iteratively reversing operations for each preceding round key to recover the original plaintext.
def decrypt(ciphertext: List[int], key: int): """Decrypt a bitfield ciphertext through PRESENT.""" schedule = compute_key_schedule(key) state = ciphertext add_round_key(state, schedule[-1]) for roundKey in reversed(schedule[:-1]): state = p_layer(state, reverse=True) s_box_layer(stat...
def conversion(key,keysize): "Convert the 128-key in 4 32-bit block" string = bin(key) list1 = [] list1[:0]=string list1 = list1[2:] "For a 4/6/8 number of 32-bit block" result = [] n = len(list1) temp = '' ### ------------------------------------ " 128-bit lenght key "...
The function generates round keys for LEA ciphers (128/192/256-bit) using key-specific schedules. It applies bitwise rotations, modular additions, and deltaList values to transform the input key across multiple rounds, appending derived keys to a list. The output is a list of round keys tailored to the specified keysiz...
def roundKeyGeneration(key,keysize): "This function generates the list of roundKeys" n_round = 0 K = [] "Key-schedule for LEA-128" if (keysize == 128) : n_round = 24 T = conversion(key,keysize) for i in range (n_round) : T[0] = bitwiseRotation(modularAddition(T[0...
def multiply_by_two(byte): """Multiply byte by two, reducing the result with the Rijndael polynomial.""" result = (byte << 1) & 0xFF if (byte >> 7) & 1 == 1: result ^= 0x1B return result def mix_one_column(col: List[int]) -> List[int]: """Multiply a column with the MixColumns matrix.""" ...
The main task of the code is to test AES encryption implementation by verifying individual operations (e.g., `multiply_by_two`, `mix_one_column`) and full-round transformations (`sub_bytes`, `shift_rows`, `mix_columns`) against known test vectors. It also validates end-to-end encryption by comparing plaintext-to-cipher...
def main(): """Test the implementation with some test vectors.""" # Test basic funtions assert multiply_by_two(0x80) == 0x1B assert mix_one_column([0xDB, 0x13, 0x53, 0x45]) == [0x8E, 0x4D, 0xA1, 0xBC] # Test round transformations before_sub_bytes = [0x19, 0x3D, 0xE3, 0xBE, 0xA0, 0xF4, 0xE2, 0x2...
def conversion(key,keysize): "Convert the 128-key in 4 32-bit block" string = bin(key) list1 = [] list1[:0]=string list1 = list1[2:] "For a 4/6/8 number of 32-bit block" result = [] n = len(list1) temp = '' ### ------------------------------------ " 128-bit lenght key "...
The function encrypts a 128-bit plaintext using a key through multiple rounds of bitwise operations (XOR, modular addition, rotation) with generated round keys. It applies transformations iteratively, updating state variables, and outputs a 128-bit ciphertext via deconversion.
def encryption(plaintext,key,keysize) : "This function encrypts the plaintext with the key" X = conversion(plaintext,128) # The plaintext is always 128-bit K = roundKeyGeneration(key,keysize) # Generates all the roundkey associated to the key lenght #print(f'The lenght of Roundkey is : {len(K)}') N...
def conversion(key,keysize): "Convert the 128-key in 4 32-bit block" string = bin(key) list1 = [] list1[:0]=string list1 = list1[2:] "For a 4/6/8 number of 32-bit block" result = [] n = len(list1) temp = '' ### ------------------------------------ " 128-bit lenght key "...
This function decrypts a 128-bit ciphertext using a key through a series of inverse rounds. It generates round keys from the input key, applies modular differences, bitwise rotations, and XOR operations in reverse order across multiple rounds (determined by keysize), and reconstructs the original 128-bit plaintext by r...
def decryption(ciphertext,key,keysize) : "This function decrypts the ciphertext with the key" X = conversion(ciphertext,128) # The ciphertext is always 128-bit K = roundKeyGeneration(key,keysize) # Generates all the roundkey associated to the key lenght Nr = len(K) for i in range (Nr-1,-1,-1) : ...
def multiply_by_fourteen(byte: int) -> int: """Shortcut for 14.""" return multiply_by_two(multiply_by_two(multiply_by_two(byte) ^ byte) ^ byte) def multiply_by_eleven(byte: int) -> int: """Shortcut for multiply by 11.""" return multiply_by_two(multiply_by_four(byte) ^ byte) ^ byte def multiply_by_thirte...
The function applies the inverse MixColumns transformation to a single column of an AES state matrix by performing matrix multiplication with the inverse MixColumns matrix coefficients, using XOR and Galois Field multiplications to compute each new element of the transformed column.
def inv_mix_one_column(col: List[int]) -> List[int]: """Multiply a column with the inverse MixColumns matrix.""" b_0, b_1, b_2, b_3 = col return [ multiply_by_fourteen(b_0) ^ multiply_by_eleven(b_1) ^ multiply_by_thirteen(b_2) ^ multiply_by_nine(b_3), multiply_by_nine...
def generate_prime(self): """ Generate a prime number using CSPRNG for more security and Miller-Rabin primality test Returns: p: the prime number """ while True: # Generate a random number of length bits p = int.from_bytes(get_random_bytes(self.lengt...
(The code initializes an RSA cryptographic object by generating prime numbers p and q (if not provided), computing RSA modulus n, Euler's totient φ(n), and determining public (e) and private (d) keys. It sets default key length to 1024 bits and ensures all essential RSA parameters are calculated for encryption/decrypti...
def __init__(self, length=None, p=None, q=None): """ Initialize the RSA object Args: p: first prime number q: second prime number """ # If length is not provided, set it to 1024 bits if length is None: length = 1024 self.length = len...
def getPieceRowAndCol(app, piece): for row in range(app.rows): for col in range(app.cols): if app.board[row][col] == piece: return row, col return (-1, -1) def getLegalPawnMoves(app, startRow, startCol): legalMoves = set() #This checks for en passant. If the opponent...
This function determines if the current player is in checkmate or stalemate by simulating all legal moves for their pieces. It checks if any move allows the king to escape check. If no valid moves exist and the king is in check, checkmate is declared; if no valid moves but not in check, stalemate is declared.
def isInCheckmate(app): if app.whitesMove: king = 'K' else: king = 'k' kingRow, kingCol = getPieceRowAndCol(app, king) setOfAllLegalMoves = set() setForStalemate = set() for row in range(app.rows): for col in range(app.cols): if (app.whitesMove and app.boar...
def getCell(app, x, y): if (not pointInGrid(app, x, y)): return (-1, -1) gridWidth = app.width/2 - 2*app.margin gridHeight = app.height - 2*app.margin cellHeight = gridHeight / app.rows cellWidth = gridWidth / app.cols row = int((y - app.margin) / cellHeight) col = int((x - app.marg...
This code handles mouse clicks in a chess game to move pieces, validate legal moves, manage special rules (pawn promotion, en passant, castling), check for check/checkmate, and update the game state, including turn switches and move history tracking.
def mousePressed(app, event): if app.gameOver: return row, col = getCell(app, event.x, event.y) #if this is a first move, then you aren't moving a piece so movingPiece = False #otherwise you are moving a piece so movingPiece = True if (app.startRow, app.startCol) == (None, None): mov...
def multi_head_self_attention(query, key, value, num_heads, params): query = split_heads(linear_activation(query, params[0], params[1]), num_heads) key = split_heads(linear_activation(key, params[2], params[3]), num_heads) value = split_heads(linear_activation(value, params[4], params[5]), num_heads) ...
The code implements a transformer decoder layer, performing multi-head self-attention on the input, followed by layer normalization and a feed-forward network. It returns attention scores and the normalized output after residual connections.
def transformer_decoder(input, num_heads, params): attn_scores, attn_out = multi_head_self_attention( query=input, key=input, value=input, num_heads=num_heads, params=params[:8]) norm1 = layer_normalization(input + attn_out, params[12], params[13]) ff_out = feed_fo...
def multi_head_self_attention(query, key, value, num_heads, params): query = split_heads(linear_activation(query, params[0], params[1]), num_heads) key = split_heads(linear_activation(key, params[2], params[3]), num_heads) value = split_heads(linear_activation(value, params[4], params[5]), num_heads) ...
The code implements a transformer encoder layer, performing multi-head self-attention on the input, followed by layer normalization and a feed-forward network. It returns attention scores and the normalized output after residual connections and normalization.
def transformer_encoder(input, num_heads, params): attn_scores, attn_out = multi_head_self_attention( query=input, key=input, value=input, num_heads=num_heads, params=params[:8]) norm1 = layer_normalization(input + attn_out, params[12], params[13]) ff_out = feed_fo...
def positional_encoding(input, n=10000): batch_size, seq_length, d_model = input.shape pe = np.zeros(shape=(seq_length, d_model)) for k in range(seq_length): for i in np.arange(int(d_model / 2)): denominator = np.power(n, 2 * i / d_model) pe[k, 2*i] = np.sin(k / denomina...
This code processes input through a transformer model with positional encoding, two decoder layers using parameter subsets, a linear activation layer, and a sigmoid function, returning intermediate scores and the final output tensor.
def transformer(input, num_heads, params): out = positional_encoding(input) # decoder layers _, out = transformer_decoder(out, num_heads, params[:16]) scores, out = transformer_decoder(out, num_heads, params[16:32]) # final layer out = linear_activation(out, params[32], params[33]) ...
def positional_encoding(input, n=10000): batch_size, seq_length, d_model = input.shape pe = np.zeros(shape=(seq_length, d_model)) for k in range(seq_length): for i in np.arange(int(d_model / 2)): denominator = np.power(n, 2 * i / d_model) pe[k, 2*i] = np.sin(k / denomina...
The code processes input through a transformer model with two encoder layers and a final linear layer. It applies positional encoding, uses parameters for encoder and activation layers, and returns transformed scores and output via sigmoid activation.
def transformer(input, num_heads, params): out = positional_encoding(input) # decoder layers _, out = transformer_encoder(out, num_heads, params[:16]) scores, out = transformer_encoder(out, num_heads, params[16:32]) # final layer out = linear_activation(out, params[32], params[33]) ...
def transformer(input, num_heads, params): out = positional_encoding(input) # decoder layers _, out = transformer_decoder(out, num_heads, params[:16]) scores, out = transformer_decoder(out, num_heads, params[16:32]) # final layer out = linear_activation(out, params[32], params[33]) ...
The code evaluates a transformer model's forecasting accuracy on river data by calculating the Mean Absolute Error (MAE) for each prediction window. It processes input batches, inverses transformations to restore original values, compares predicted vs. actual outputs, aggregates MAE metrics, resamples results hourly, a...
def getRiverCastMAE(): # measure accuracy of each window accuracy = [] predictions = [] for input, label in batches: input = np.reshape(input, (1, SEQ_LEN, D_MODEL)) scores, pred = transformer(input=input, num_heads=NUM_HEADS, params=params) # make forecast pred = np.re...
def transformer(input, num_heads, params): out = positional_encoding(input) # decoder layers _, out = transformer_encoder(out, num_heads, params[:16]) scores, out = transformer_encoder(out, num_heads, params[16:32]) # final layer out = linear_activation(out, params[32], params[33]) ...
The main task of the code is to evaluate a transformer model's forecasting accuracy on time series data by calculating the Mean Absolute Error (MAE) for each prediction window. It processes input batches, inverses data scaling, compares predicted and actual values, aggregates MAE metrics, and saves results in a CSV. Th...
def getBidirectionalMAE(): # measure accuracy of each window accuracy = [] predictions = [] for input, label in batches: input = np.reshape(input, (1, SEQ_LEN, D_MODEL)) scores, pred = transformer(input=input, num_heads=NUM_HEADS, params=params) # make forecast pred = n...
def make_tk(): planckk, pk_z1100, sdssk, sdsspk, sdsserr = import_powerspectra(err=True) sdsserr_spline = UnivariateSpline(sdssk, sdsserr, s=0., ext='zeros') sdss_spline, log10planck_spline = make_splines(planckk, pk_z1100, sdssk, sdsspk) planckk, pk_z1100_u, sdssk, sdsspk_u = import_powers...
The main task of the code is to generate Green's function data using Gaussian process regression on cosmological power spectrum data. It combines transfer function data (tk), SDSS measurements, and CAMB theoretical models to compute real-space Green's function values (Gr) with uncertainty bounds (Gr_l/Gr_u), then saves...
def make_greens(): ## get tk try: tkdat = pd.read_csv(RESULTSDIR+'data_products/transfer.dat') k = tkdat['k'] tk = tkdat['Tk'] except: make_tk() tknorm = 1./tk[0] ##first non-zero tk spline value ## get sdssk for rarray later. sdssk, __, __, __ = np.loadtxt(DATAD...
def generateLargePrime(keysize): """ return bilangan prima dengan jumlah bit sebesar keysize """ while True: num = random.randrange(2 ** (keysize - 1), 2 ** keysize - 1) if (isPrime(num)): return num def isCoPrime(p, q): """ return true kalau gcd(p,q) = 1...
The code generates RSA cryptographic keys by selecting two large primes (p, q), computing the modulus N = p*q, Euler's totient φ(N) = (p-1)(q-1), choosing a public exponent e coprime to φ(N), and determining the private exponent d as the modular inverse of e modulo φ(N). It returns the public key (e, N) and private key...
def generateKeys(keysize=1024): e = d = N = 0 p = generateLargePrime(keysize) q = generateLargePrime(keysize) # print("p :", p) # print("q :", q) N = p*q phiN = (p - 1) * (q - 1) while True: e = random.randrange(2 ** (keysize - 1), 2 ** keysize - 1) if (isCoPrime(e,ph...
def generate_output_image(input_grid): output = [] for r in range(1, input_grid.shape[0] - 1): row = [] for c in range(1, input_grid.shape[1] - 1): row.append(get_output_image_character(input_grid, (r, c))) output.append(row) return np.array(output) def expand_grid(grid,...
The function processes an input grid through multiple iterations of image generation, expanding and transforming the grid each time, and finally returns the count of '#' characters (representing lit pixels) in the resulting flattened grid.
def get_num_light_pixels(input_grid, iterations): output = input_grid for i in range(iterations): output = generate_output_image(expand_grid(output, get_empty_char(i, algo))) return output.flatten().tolist().count("#")
def init_bdd1(): """ Creates the initial graph BDD for the project """ initialized = False for i in range(0, 32): for j in range(0, 32): if (i + 3) % 32 == j % 32 or (i + 8) % 32 == j % 32: if initialized: bdd1 = create_bool_formula(i, j) | bdd1 else: bdd1 = create_bool_formula(i, j) ...
The code constructs and manipulates Binary Decision Diagrams (BDDs) by initializing variables, composing functions, applying logical operations (OR, NOT), and smoothing. It evaluates a complex logical expression involving BDDs, ultimately computing the negation of a derived expression and printing test results. The mai...
def main(): g = init_bdd1() prime = init_prime() even = init_even() rr = compose(g,g) rrstar = create_Rstar(rr) x1 = bddvar('x', 1) x2 = bddvar('x', 2) x3 = bddvar('x', 3) x4 = bddvar('x', 4) x5 = bddvar('x', 5) x = [x1, x2, x3, x4, x5] y1 = bddvar('y', 1) y2 = bddvar('y', 2) y3 = bddvar('y', 3) y4 = bd...
def _load_puzzle(self, filename): ''' Reads puzzle from input file. ''' x = numpy.loadtxt(filename, dtype=numpy.int) assert x.shape == (9, 9), 'ERROR: wrong-shape puzzle in %s' % filename assert x.max() <= 9, 'ERROR: puzzle.max() = %i' % x.max() assert x.min() >= 0, 'ERRO...
The code initializes a Sudoku puzzle by loading the puzzle from an input file, filling it, validating the puzzle's values (1-9), setting a random seed for stochastic processes, and initializing parameters like energy and beta for solving the puzzle.
def __init__(self, input_file, seed=0): ''' Initializes an instance of the Sudoku class. Arguments: input_file : file with the puzzle seed* : seed for the random-number generator (if 0, a random value is chosen as seed) ''' pr...
def is_solution(board): """Checks if the board is completely filled with non zero numbers""" for row in range(9): for col in range(9): if board[row][col] not in get_valid_numbers(board, row, col): return False return True def get_first_unfilled_square(board): """Gets ...
This function solves a Sudoku board using DFS backtracking. It recursively fills empty cells with valid numbers, visualizing each step via a GUI by highlighting correct attempts in green and backtracking errors in red. If a solution is found, it returns the solved board; otherwise, it backtracks by resetting cells and ...
def dfs_solve(board, gui): """Solves the sudoku board represented as a nested list using DFS backtracking. If a GUI reference is passed in, the solving process is displayed to the user""" if is_solution(board): return board row, col = get_first_unfilled_square(board) possible_solutions = get...
def get_domain_name(url): domain_parts = url.split('.') domain_name = '.'.join(domain_parts[-2:]) return domain_name def get_ip_address(url): try: ip = socket.gethostbyname(url) return ip except socket.gaierror: return None def get_whois_info(url): try: w = whois....
The main task of the code is to test the `gather_info()` function by verifying it correctly collects and saves information (domain name, IP address, WHOIS data) from a valid URL into designated files within a project directory. It checks if the function creates the directory structure, writes the URL, domain name, IP a...
def test_gather_info_valid_url(self): """Test that the `gather_info()` function correctly gathers information for a valid URL.""" name = "Google" url = "https://www.google.com" domain_name = get_domain_name(url) ip_address = get_ip_address(domain_name) whois_info = get_...
def __set_attributes(self): """ Clear and set all the instance variables """ job_type, where, keywords = self.__get_query_parameters() self.job_type = "-".join(job_type.split()) self.where = "-".join(where.split()) self.keywords = [keyword.strip() for keyword ...
The code's main task is to search for and print matching job listings from seek.com by iterating through pages, collecting job links, sorting them, and allowing user interaction to terminate the search. It continuously fetches job data, enforces search limits, and presents results until the user chooses to exit.
def find_jobs(self): """ Search and print the matching jobs on seek.com """ while True: self.__set_attributes() page_searches = 0 continue_flag = True while self.limit_flag: self.__get_job_links() page_se...
def getLabeledThumbprint(data, wavelet, ns=50, numslices=5, slicethickness=0.12, valleysorpeaks='both'): ''' This function creates two fingerprints, one for the peaks of the wavelet coefficient matrix and another for the valleys. This allows more separation between the fingerpr...
The function processes a fingerprint image by labeling regions, removing small objects, correcting labels, visualizing the fingerprint and ridge count, and calculating the center of mass (CoM) for each fingerprint region. It returns the processed fingerprint matrix and a matrix of CoM coordinates for labeled objects.
def getProcessedFP(vec, wvt, ns=50, numslices=5, slice_thickness=0.12, threshold=50): fp = getLabeledThumbprint(vec, wvt, ns=ns, numslices=numslices, slicethickness=slice_thickness) _dropSmallObjs(fp, threshold) _fixLabels(fp) plt.figure() plt.subpl...
def summarizer(text,model,tokenizer): text = text.strip().replace("\n"," ") text = "summarize: "+text max_len = 512 encoding = tokenizer.encode_plus(text,max_length=max_len, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device) input_ids, attention_mask = encoding["input_ids"], encoding["a...
The function generates multiple-choice questions with answers and distractors based on a summary of the input context. It first creates a summary, extracts keywords, then generates questions and distractors using specified models. Distractors are obtained via WordNet or embeddings, and the output includes questions, an...
def generate_summary_questions(context, modelopt): print('Generating summary...') summary_text = summarizer(context,summary_model,summary_tokenizer) print('Generating questions...') np = get_keywords(context,summary_text) output = [] for answer in np: temp = [] ques = get_questi...
def generate_dialog(api_key): """ Generates a dialog with random speakers based on funny topics and unique personalities. """ # Generate funny topics topics_prompt = [ ("List two funny and dark existential conversation topics by " "people who are surprised and relieved to re...
The main task of the code is to generate a dialog using an API key, format its topic and speakers, and vocalize each speaker's lines via the `say` command with specific audio quality and voice settings. It processes the dialog script, applies formatting functions, and sequentially outputs each speech segment as audio, ...
def main(): dialog = generate_dialog(api_key) #time.sleep(35) format_topic(dialog.topic) format_speakers(dialog.speakers) for speaker, speech in dialog.script: format_script(speaker, speech) subprocess.check_call(["say", "--quality=127", "-v", speaker, speech]) #time.sleep(...
def Q1(): print ("\nQ1:") Gs = read_graphs('graph1.txt', 'graph2.txt') # List of graphs # Simulate election process for both graphs to get final voting preference final_confs = [sim_election(G) for G in Gs] # Get the winner of the election, and the difference in votes for both # graphs ...
The main task of the code is to sequentially execute four functions—Q1(), Q2(), Q3(), and Q4()—within the main() function, likely performing distinct operations or tasks in a predefined order.
def main(): Q1() Q2() Q3() Q4()
def find_land_event(present_events): landings = ['punt_land', 'punt_received', 'punt_muffed', 'fair_catch', 'out_of_bounds', 'touchback'] for l in landings: if l in present_events: return l def pull_tracking_data(play_tracking_grid, event_to_accept, foo...
This function calculates the distance in yards from the ball's landing position to the goal line, returning the rounded value. It uses tracking data to determine the final x-coordinate of the ball and identifies the goal line position before computing the absolute difference.
def nn_yards_to_goal_line(play_tracking_grid, present_events, *args): land_event = find_land_event(present_events) final_x = pull_tracking_data(play_tracking_grid, land_event, football_only=True, cols_to_return=['x'])[0] goal_line = find_back_goal_line(play_tracking_grid, present_events) return round(ab...
def login(): user = input("Enter your name: ") print("Hello how are you?, " + user) file = open("run.txt", "a+") file.close() file = open("run.txt", "r") lines = file.readlines() users = {} if len(lines)> 0: file.seek(0,0) users = eval(file.read()) file.close() if user in users: return user else: ...
The main task of the code is to provide a user interface for managing running data, allowing users to add new runs, view their run history, calculate daily averages, and sign out. It uses a loop to display options, processes user input, and calls corresponding functions like `newRun`, `printRun`, and `averageRun` based...
def main(): user = login() choice = '' while choice.upper() != 'Q': print("Welcome to RunTracker! These are your options: ") print("1 - Add a new run!") print("2 - Show your Run!") print("3 - Get your day to day average!") print("Q - Sign Out") choice = input("What would you like to do?") if choice ==...
def get_total_strength(pieces): return sum([piece[1].strength for piece in pieces]) def get_nearby_pieces(gmap, location): """Returns a list of (location, Site) tuples.""" nearby_sites = [gmap.getSite(location, d) for d in ACT_DIRECTIONS] nearby_locations = [gmap.getLocation(location, d) for d in ACT_DI...
The main task of the code is to determine whether to attack a target or wait based on the relative strength of allied pieces. If allied strength exceeds the target's, it moves adjacent pieces to attack, refreshes the target if necessary, and directs non-adjacent pieces to either eliminate nearby neutrals or move toward...
def attack_target_or_wait(my_id, game_map, data): moves = [] if get_total_strength(data["pieces"]) > data["target"][1].strength: # attack adjacent_allied = [p for p in get_nearby_pieces(game_map, data["target"][0]) if p[1].owner == my_id] if not adjacent_allied: ...
def _init_ui(self): self._load_images() self._frame = ScrollableCanvas(self._root) self._canvas = self._frame.canvas self._canvas.config(width=640, height=480) self._canvas.config(bg="white") self._frame.grid(row=0, column=0) self._frame.pack(fill=tk.BOTH, expand...
This code initializes a Karel environment GUI by setting up a Tkinter window, configuring UI components like canvas and frames, loading visual assets (walls, beepers, Karel images), and starting the first level. It initializes level tracking, UI elements, and prepares the environment for interactive level navigation an...
def __init__(self, level_list): self._level_list = level_list self._curr_level = 0 self._level = None self._root = tk.Tk() self._root.title("Karel") self._frame = None self._canvas = None self._border_width = 10 self._wall_width = 2 self....
def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0. Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of shape (dim, 1) b -- initialized scala...
The code implements a logistic regression model to classify data. It initializes parameters, optimizes them using gradient descent, trains on provided data, evaluates accuracy on training and test sets, and returns a dictionary containing model parameters, costs, and accuracy metrics.
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): """ Builds the logistic regression model Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a num...
def set_side(self, choice): if choice == 0: self.side = 0 else: self.side = 1 def get_position(self): ''' Get the next position to work on. If the study_game is empty, update it with a new chapter. Whenever a study_game is out of move, reset it to...
This code trains a user by prompting them to input chess moves, validating the moves (UCI or SAN format), updating accuracy metrics, and displaying the board with study/chapter info. It loops until no more positions remain, providing real-time feedback and ensuring correct move input through error handling and re-promp...
def training(self): ''' Main training function. ''' self.set_side(int(input("Pick your side for training (0 for white, 1 for black): "))) board = self.get_position() while board != None: self.clear_screen() if self.side == 0: self....
def remove_random_nodes(graph, num_nodes): while graph.number_of_nodes() > num_nodes: graph = remove_random_node(graph) return graph def add_random_nodes( graph, num_nodes, id_node_start, number_label_node, number_label_edge, min_edges, max_edges, ): graph_nodes = graph....
The main task of the code is to generate a non-isomorphic subgraph from a given graph, ensuring it meets specified node count, degree distribution, and connectivity constraints. It iteratively samples nodes, adjusts the subgraph size, applies random modifications, and verifies non-isomorphism using graph matching algor...
def generate_noniso_subgraph( graph, no_of_nodes, avg_degree, std_degree, number_label_node, number_label_edge, *args, **kwargs ): graph_nodes = graph.number_of_nodes() node_ratio = no_of_nodes / graph_nodes if node_ratio > 1: node_ratio = 1 min_edges = int(no_of...
def getRootServers(cfg_file): servers = [] with open(cfg_file) as f: for line in f: root_server_name, root_server_ip = line.strip().split(":") servers.append(root_server_ip) return servers def getResponse(domain,servers): for server in servers: try: qu...
The code resolves DNS hierarchy for a domain using DNSSEC validation, verifying each level's authenticity through cryptographic checks. It traverses domain parts backward, validating KSK, RRset, and DS records against hash functions. If validation fails at any step, it returns None; otherwise, returns updated DNS serve...
def resolveHeirarchy(domain): servers = getRootServers(cfg_file) if domain in hot_list and domain not in cold_list: domain = "www." + domain domain_heirarchy = domain.strip().split(".") sub_domain = domain_heirarchy[-1] + "." ds_record, hash_fn, response = getResponse(sub_domain, servers)...
def conv_layer(self, bottom, filter_size, in_channels, out_channels, name): with tf.variable_scope(name): filt, conv_biases = self.get_conv_var(filter_size, in_channels, out_channels, name) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') bias = tf.nn.bias_add(...
This code builds a neural network combining a VGG-style encoder with a decoder for depth estimation or segmentation. It processes RGB images by converting them to BGR, applies convolutional layers and pooling (VGG-style), then constructs upsampling branches with skip connections to reconstruct spatial features. The fin...
def build(self, rgb, train_mode=False, resume=True): """ load variable from npy to build the VGG :param rgb: rgb image [batch, height, width, 3] values scaled [0, 1] :param train_mode: a bool tensor, usually a placeholder: if True, dropout will be turned on """ rgb_scal...
def __normalize_path_end(path): return path if path.endswith(FORMAT.SLASH.value) else path + FORMAT.SLASH.value def __has_next_page(last_nr, current_idx): if last_nr is None: return True if last_nr > current_idx: #Note that we use last page number, but current page index return True ...
The function extracts URLs of ACL volumes from overview pages by downloading HTML content, parsing volume links, managing pagination, and cleaning up temporary files. It handles URL construction, downloads pages, extracts volume URLs using a helper function, logs progress, and deletes temporary files if specified. The ...
def extract_volume_overviews( output_path, output_temp_fn=None, url_stem=HTML.VOLUME_URL_STEM.value, pagination_mark=HTML.PAGINATION_STRING.value, last_page=None, restrictions=None): """Extracts the urls for the ACL volumes from the ACL Anthology overview pages. The overview pages a...
def extract_volume_overviews( output_path, keep_output_fn, url_stem=HTML.VOLUME_URL_STEM_CLOSED.value, restrictions=None): """Extracts the urls for the ACL volumes from the ACL Anthology volume website. The overview pages are downloaded in a temporary file which will be deleted as soon as n...
This function downloads ACL conference volume bibliographies from specified URLs, handles errors, optionally reformats them, and concatenates results into a single file. It creates output directories, extracts volume URLs, downloads BibTeX files, reformats them if requested, logs issues, and combines files when a conca...
def main_download_acl_bibs(output_path, keep_overviews, reformat_bibs, concatenated_filename=None, restrictions=None, input_url_stem=HTML.VOLUME_URL_STEM_CLOSED.value): """Main func...
def load_argument_parser(print_help=False): """Loads the command line arguments, or print the help message. :param print_help: whether to print the help message :return: ArgumentParser according to the command line arguments """ parser = argparse.ArgumentParser( description=f'downl...
The main task of the code is to download and process ACL conference proceedings' BibTeX files based on user-specified parameters such as output path, year ranges, venue filters, and formatting preferences. It sets up logging, parses command-line arguments, applies download restrictions, and executes the download proces...
def run_download_acl_bibs(args_raw:List): #LOG #logger = logging.getLogger("biblogger") #logger.setLevel(logging.DEBUG) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) argparser = load_argument_parser() args = argparser.parse_args(args_raw) output_...
def isDiagonal(line: Line) -> bool: return not isVertical(line) and not isHorizontal(line) def sumHazards(map: Dict[Any, int]) -> int: hazardPointCount = 0 for point in map: if(map[point] >= 2): hazardPointCount += 1 return hazardPointCount def findHazards(lines: List[Line]): hazardMap = {} for l...
The code processes a list of lines by filtering out diagonal lines, identifies hazards from the remaining lines, and returns the total number of hazards by summing them up.
def partOne(data: List[Line]): lines = filter(lambda l: not isDiagonal(l), data) return sumHazards(findHazards(lines))
def freq_to_angular_freq(freq): omega = 2*math.pi*freq return omega def freq_to_bark(freq): omega = freq_to_angular_freq(freq) coef = omega/(1200*math.pi) bark = 6*math.log(coef + (coef**2 + 1)**0.5) return bark def critical_band_convolution(warped_label,pow_frame): omega = [] for index ...
The function computes Perceptual Linear Prediction (PLP) coefficients from audio power frames. It applies frequency warping to Bark scale, performs critical band convolution, equal loudness filtering, amplitude compression, inverse Fourier transform, and LPC analysis on each frame to model perceptual auditory features.
def PLP_slow(pow_frames, p, sample_rate): freq_label = np.linspace(0, sample_rate/2, len(pow_frames[0])) afreq_label = [freq_to_angular_freq(i) for i in freq_label] #sample_label = [i for i in range(len(freq_label))] warped_label = [freq_to_bark(i) for i in freq_label] perceptual_coeffs = [] ...
def incomplete_or_corrupt(chunk): for x in clean_chunk(chunk): if x in character_scores.keys(): return x return 'incomplete' def autocomplete_score(autocomplete_chunk): score = 0 for x in autocomplete_chunk: score = score * 5 + autocomplete_scores_dict[x] return score def...
The function calculates the median of scores generated by autocompleting and scoring incomplete items in the input data.
def median_score(data): scores = [] for x in data: if incomplete_or_corrupt(x) == 'incomplete': scores.append(autocomplete_score(autocomplete(x))) return median(scores)
def find_nearby_coordinates(x, y): nearby_coordinates = [[x - 1, y], [x, y - 1], [x + 1, y], [x, y + 1]] return remove_out_of_bounds_coordinates(nearby_coordinates) def remove_9_points(coordinates, points): bad_coordinates = [] ...
The code identifies all coordinates in a terrain grid that are higher than the starting point (x,y) and recursively collects their adjacent higher points, returning a list of these coordinates.
def higher_adjacent_points(x, y): higher_points = [] point = terrain[x][y] nearby_coordinates = find_nearby_coordinates(x, y) nearby_points = [terrain[i][j] for i, j in nearby_coordinates] nearby_coordinates, nearby_points = remove_9_points(nearby_coordinates, nearby_points) for nearby_coordinat...
def extrapolate_data(left_value, right_value, ms): ms = ms % 1000 result = left_value + (right_value - left_value) * (ms / 1000) return result def walk_track_left(Dist, x_a, y_a): left_x = map_left[int(x_a)] left_y = map_y[int(left_x)] left_distance = Dist while left_distance > 0: to...
This code simulates the movement of an object along a track based on input acceleration/brake values (-100 to 100). It calculates position, speed, and acceleration using physics models, checks for success (reaching 1000 units) or failure (low efficiency), and outputs simulation data. The core task is to model dynamic m...
def print_gene(ABinput): """ :param ABinput: array with values from -100 (brake) to 100 (accelerate) :return: None """ last_position = start_distance last_speed = 0 total_distance = 0 positions = [last_position] simdata = [] index = 0 for AB in ABinput: position_...
def extrapolate_data(left_value, right_value, ms): ms = ms % 1000 result = left_value + (right_value - left_value) * (ms / 1000) return result def walk_track_left(Dist, x_a, y_a): left_x = map_left[int(x_a)] left_y = map_y[int(left_x)] left_distance = Dist while left_distance > 0: to...
The code simulates a vehicle's movement based on acceleration/braking inputs (ABinput), applying physics calculations to track position, speed, and grip. It evaluates fitness by checking if the vehicle reaches the finish line (1000 units), penalizes excessive speed or insufficient speed, and computes an average "speed ...
def run_input(ABinput): """ :param ABinput: array with values from -100 (brake) to 100 (accelerate) :return: fitness of AB """ last_position = start_distance last_speed = 0 total_distance = 0 positions = [last_position] # remove from this function speed_respect = [0] # how well ...
def set_zero_values(): global unit_mass, unit_power, unit_brake, unit_length, weight_center global start_distance, plan_length global map_left, map_right, map_y, map_angle, map_is_node global map_speed_max, map_speed_min, map_grip, map_friction global nodes, cars unit_mass = 0 unit_power = ...
The main task of the code is to simulate a scenario using specified 'plan' and 'unit' files by loading their data into memory, configuring environmental parameters like gravity and efficiency thresholds, and initializing simulation variables. It handles file loading errors and prepares the simulation environment for ex...
def run_simulation(plan, unit): print("Running " + unit + " on " + plan) set_zero_values() plan_path = os.path.join(documents_path, 'upRail/plans', plan + '.upmap') unit_path = os.path.join(documents_path, 'upRail/units', unit + '.uptrain') env_path = os.path.join(documents_path, 'upRail', 'Environm...
def clean_target(clean_type = TYPE_NONE, dest = None): if (clean_type == TYPE_FILE) or (clean_type == TYPE_FOLDER): parent_path = os.path.dirname(dest) exitcode , output = run_cmd([uploader, "--port", port, "ls", parent_path]) if exitcode == EXIT_CODE_SUCCESS: for item in output...
This function performs a firmware update on hardware by removing old files, updating configuration settings, uploading new firmware, and restoring configuration files. It checks each step's success, exiting if any step fails.
def noramal_firmware_update(): print("Removeing old files from Hardware...") if clean_target() != EXIT_CODE_SUCCESS: exit(0) update_flash_time_to_config() print("\nUploading new files to Hardware...") if upload_firmware() != EXIT_CODE_SUCCESS: exit(0) restore_config_file()
def check_folder_exist(folder_path): actual_folder_path = os.path.abspath(folder_path).replace(os.path.abspath(path), "") exitcode , output = run_cmd([uploader, "--port", port, "ls", actual_folder_path]) return exitcode def clean_target(clean_type = TYPE_NONE, dest = None): if (clean_type == TYPE_FILE)...
The function performs a partial firmware update by processing each file in the provided list. It checks if files exist, ensures target directories are created, cleans existing targets, and creates new files or folders as needed. If no configuration file is updated, it updates metadata, creates a new config file with a ...
def partial_firmware_update(file_list): config_update = False for file in file_list: file_destination = os.path.abspath(file).replace(os.path.abspath(path), "") if os.path.basename(file) == config_file: config_update = True if os.path.isfile(file): if check_folder...
def get_embeddings(paths): ''' Get ECAPA-TDNN embeddings for all files in Inputs: paths - list of all file paths (list of strings) Outputs: xv - numpy array containing all embeddings (# files x embedding dim (192)) ''' #load the necessary embeddings xv = [] for i in range(len(paths...
The main task of the code is to evaluate a speaker verification system using PLDA (Probabilistic Linear Discriminant Analysis). It processes a dataset to train a PLDA model, calculates thresholds (EER or minDCF), scores test data, and computes performance metrics (precision, recall, F-score, etc.). Results are saved in...
def main(): # PARSE ARGUMENTS parser = argparse.ArgumentParser() #required arguments parser.add_argument("-d", "--dataset", required=True, help="specify path to dataset description - make sure description is in proper format") parser.add_argument("-o", "--output_dir", required=True, help="specifies ...
def process_scan(self, scan): retention_time = scan["scanList"]["scan"][0]["scan start time"] * CON.MINUTES_TO_SECONDS tuple_list = [] for j in range(len(scan["m/z array"])): if scan["intensity array"][j] > CON.NOISE_LIMIT: tuple_list.append((scan["m/z array"][j], sca...
This code reads an mzML file to count MS level 1 scans, extract their retention times, and process each scan. It prints progress updates, processes each scan via `self.process_scan`, and prepares a sliding window dictionary using the final retention time for downstream analysis.
def read_mzml(self, file: str): total = 0 print() print("(initializing)") with mzml.read(file) as f: for scan in f: if scan["ms level"] == 1: total += 1 count = 0 retention_time = None with mzml.read(file) as f: ...
def read_input(self, file: str): with open(file, 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: self.add_peptide(row['Peptide'], float(row['Precursor']), int(row['Charge']), float(row["ScanNum"])) def set_pep_retention_ti...
This function processes hydrogen-deuterium exchange data by converting scan numbers to retention times from an identification file, matches deuterium atoms in peptides, and writes results to an output file. It iterates through peptides, tracks progress, measures processing time, and generates a named output file for ea...
def hydrogen_deuterium_exchange(self, identification_file: str): """This function reads the identification file and converts the scan #'s to retention times. Then it goes through each peptide and matches each deuterium if possible. This ends by writing to an output file which contains in...
def generate_recommendation_table_1(self): top_header = ["Start", "End", "Sequence", "Peptide mass (Da)", "Retention time (min)"] bot_header = ["Start", "End", "Sequence", "Peptide mass (Da)", "Retention time (min)"] self.update_headers(top_header, bot_header, "Uptake " + CON.CONDITION1 + " (D)"...
The code's main task is to generate output by creating two recommendation tables and, if the instance is marked as differential, producing two differential Woods plots with varying parameters and a summary table. This method orchestrates data visualization and tabular output generation based on the differential flag st...
def generate_output(self): self.generate_recommendation_table_1() self.generate_recommendation_table_2() if self._is_differential: self.generate_differential_woods_plot(CON.WOODS_PLOT_TITLE) self.generate_differential_woods_plot(CON.WOODS_PLOT_TITLE, False) se...
def set_fit(self): intensities = [] for key in self._deuterium_dictionary.keys(): intensities.append(self._deuterium_dictionary[key]["intensity"]) self._fit = fit_gaussian(intensities) def get_max_deuterium(self): return self.max_deuterium def get_deuterium(self, deuterium): ...
The main task of the code is to generate a list of data rows based on deuterium levels, incorporating different conditions (CON.CONDITION1 or CON.CONDITION2) depending on the input complexity. Each row contains attributes like start/end positions, sequence, charge, mass-over-charge, retention time, and other parameters...
def get_rows(self, complexity: str): if complexity: condition = CON.CONDITION2 else: condition = CON.CONDITION1 line_list = [] self.set_fit() for i in range(self.get_max_deuterium() + 1): mz, intensity, ppm = self.get_deuterium(i) ...
def __printBoldWithLineBreak(self, text): printBold(f"{text}\n") def __changeState(self, state): self.state = state self.__introduceState() def __isItemGiven(self, item): try: return item['Given'] except KeyError: return False def __introduceState(self): self.__printBoldWithLineBreak(self.state['Descr...
This code processes game commands by handling state transitions based on direction and required items, granting items, executing unique actions like "inventory" or "quit", and displaying relevant feedback. It filters data to update the game state, checks item availability, and manages user interactions within a state-d...
def __processCommand(self, command, arguments = []): try: self.__printBoldWithLineBreak(command['ReplyText']) except KeyError: pass try: direction = command['Direction'] try: directionData = self.state[direction] try: self.__changeState(list(filter(lambda state: state['Id'] == directionD...
def permuteMatrix(arrayDF): # Takes a dataframe as a parameter. arrayMat = arrayDF.to_numpy() np.random.shuffle(arrayMat) print(arrayMat) plt.imsave('shuffle.png', np.array(arrayMat).reshape( len(arrayMat), len(arrayMat[0])), cmap=cm.gray) return (arrayMat) de...
The main task of the code is to process an input dataset by permuting its matrix, calculating Pearson correlations of the permuted data, applying clustering recovery to generate a signature matrix, and passing this result to Task1 for further analysis. The function then confirms completion.
def Task2(iFile): # Function to execute the Task2 of the program. permutedMat = permuteMatrix(iFile) # Takes original dataset as parameter permutedCorrMat = PearsonCorrelation(permutedMat) signaturePermutedMat = clusterRecover(permutedMat) T...
def sortinterval(input): """ Sorts the input interval string and returns the corresponding Binance API constant. Args: input: The input interval string. Returns: The corresponding Binance API constant. Raises: None. """ revintverals ={ '1m':Client.KLINE_INTERVA...
The code downloads cryptocurrency market data from Binance for specified clients, saving it to a designated directory. It processes client credentials from a list or CSV file, converts market cap thresholds to integers, and manages data retrieval based on time ranges, frequency, and token filters. The function checks f...
def download(clients=None,datapath="data",starttime="2023-01-01 00:00:00",endtime="now",freq="1d",mcap="5m",tokens=["BUSD"]): """ Downloads data from Binance for specified clients and saves it to a specified data path. Args: clients: A list of clients or a path to a CSV file containing client infor...
def cleanData(self): if self.match(self.author, "((.|\s)+,){2}(.|\s|\d)+."): self.cleanAuthor() if self.author.endswith('.'): self.author = self.author.rstrip('.') self.removeJobTitle() def addEntry(self): entry = { "line1" : "1 CD(s) & Booklet", ...
This code parses a CSV file, extracts and cleans 'Title', 'Creator', and 'Call Number' fields by removing slashes and non-digit characters, then processes and stores the cleaned data using helper methods before writing the final entry to a file.
def parse(self): reader = csv.DictReader(self.f) for row in reader: try: self.title = row[' Title'].replace('/',"").strip() except: self.title = "" try: self.author = row[' Creator'].replace('/',"").strip() except: se...
def new_split(self, model): self.train, self.test = next(self.splits_iter) self.train_len = len(self.train) self.test_len = len(self.test) self.train_idx = 0 for layer in model.children(): if hasattr(layer, 'reset_parameters'): layer.reset_parameters()...
This code performs cross-validation by iterating through folds, training a model on each fold's data, evaluating performance, and aggregating results. It handles mixed precision training, runs training and evaluation loops, and prints average accuracies for sleep-deprived, well-rested, and total categories across all f...
def run(self, model, epochs): if self.dtype == torch.float16: model.half() for f in range(len(self)): print(f'Starting fold {f}') print("==========================") self.new_split(model) self.__train_loop(f, model, epochs) print(f'...
def getImagePath(): global newImagePath projectPath = lx.eval("query platformservice path.path ? project") scene_name = get_project_name() if scene_name != "": scene_name += "\\" dirPath = projectPath + "\\Images\\baking\\" + scene_name if not os.path.exists(dirPath): try: ...
The function generates materials for a 3D mesh by creating shader nodes, gradients, and image maps for properties like roughness, metallic, ambient occlusion, and lighting. It links these elements to the mesh's UV map, sets texture effects, and configures blending modes. The code dynamically creates and positions nodes...
def generateMaterials(mesh): for vmap in mesh.geometry.vmaps.uvMaps: searchName = mesh.name.split(splitTag)[1] if searchName == vmap.name: uvMap = vmap newImagePath = getImagePath() newImagePath_tmp = getImagePath_tmp() masterShader = None for item in scene.renderItem.chi...
def getImagePath_tmp(): path_tmp = '%stmp\\' % getImagePath() if not os.path.exists(path_tmp): try: os.makedirs(path_tmp) except: path_tmp = getImagePath() print('tmp dir making error') return path_tmp def newTexture(curMask, uvMap, newImagePath, namePrefi...
The main task of the code is to generate low-poly materials for each UV map on a mesh by creating texture maps (base color, normal, roughness, etc.), baking high-poly details onto low-poly geometry using specified UV maps, and managing material/textures cleanup, shader linking, and bake settings. It ensures existing ma...
def createLpMaterial(mesh): for uvMap in mesh.geometry.vmaps.uvMaps: # print 'uvMap : %s | len : %s' % (uvMap.name, len(uvMap)) try: # TODO delete existing lpMaterial and children textures scene.deselect() lpMatExisting = scene.item('%s%s (Material)' % (lpMatTag,...
def readmap(filename): f = open(filename, "r") str = f.read() for x in range(len(str)): if str[x] == NORMAL or str[x] == HIGHWAY or str[x] == HARD_TO_TRAVERSE or str[x] == BLOCKED: graph.append(Cell(int(x/2) % columns, int(int(x/2) / columns), str[x])) f.close() for x in range(le...
The code processes 10 map files, iterating through 10 test files per map. For each combination, it reads map/test data, initializes a heatmap, runs a processing cycle, clears temporary data, and resets the graph. The nested loops systematically handle all map-test pairs to analyze or visualize data patterns, likely for...
def readall(): for i in range(10): readmap(f"ground_truth/map{i}.txt") for j in range(10): readgtruth(f"ground_truth/map{i}test{j}.txt") initheatmap() pcycle() clearall() graph.clear()
def getSO(filepath1: str, filepath2: str): area_floor_list, area_roof_list, so_list = [], [], [] xlist, y1listlist, y2listlist = alignPoints(filepath1, filepath2) for i in range(len(y1listlist)): y1list = y1listlist[i] y2list = y2listlist[i] y1list = [abs(i) for i in y1list] ...
The code calculates statistical measures (SO, Pearson correlation, SAM, Spearman rank correlation) between human and model data from input files. It compiles these metrics into a DataFrame, then either saves the results to a CSV file (if an output path is specified) or prints descriptive statistics of the metrics. The ...
def main(args): human_file = args.human model_file = args.model _, _, SO_list = getSO(human_file, model_file) CORR_list = getPearson(human_file, model_file) SAM_list = getSAM(human_file, model_file) SPEAR_list = getSpearmanr(human_file, model_file) df = DataFrame({'SO': SO_list, 'CORR': COR...
def expand(mat): shape = mat_shape(mat) new = mat_create([x+2 for x in shape], '.') mat_apply(mat, lambda val,*index: mat_set_index(new, [x+1 for x in index], val)) return new def mat_shape(mat): shape = [] val = mat while isinstance(val, list): shape.append(len(val)) if len(...
The code simulates a cellular automaton for 6 steps, updating a grid of '#' and '.' characters based on neighbor counts. It expands the grid, tracks its shape and active cell count at each step, applies update rules (cell becomes '#' if 3 neighbors or remains if 2), and returns the final count of '#' cells.
def solve(): global lines lines = [lines] grid = expand(lines) for step in range(6): shape = mat_shape(grid) print(step, shape, mat_sum(grid, lambda x: x == '#')) def update(val,*index): n = sum(neighbor == '#' for neighbor, *_ in mat_neighbors(grid, index)) ...
def findFirstLinMonEntry(fh): data = fh.read(100) pos = data.find(b'COM') if pos < 0: raise Exception('Could not find COM in first 100 bytes') fh.seek(pos) def readLinMonEntry(fh): src = fh.read(5).decode("ascii") ts = xlrd.xldate_as_datetime(struct.unpack('d', fh.read(8))[0], 0) len...
The function `parseShrubFromFile` reads binary data from a file, processes entries from COM1 and COM2 sources, and parses them into two separate lists (`shrub1` and `shrub2`) using a helper function. It buffers data for each source, iteratively extracts structured information, and returns the parsed results. The code h...
def parseShrubFromFile(fname): shrub1 = [] shrub2 = [] buff1 = bytearray() buff2 = bytearray() n = 1 try: with open(fname, "rb") as fh: findFirstLinMonEntry(fh) while True: (psrc, ts, data) = readLinMonEntry(fh) if psrc == 'COM1:': ...
def mail_alert(mail_content, sleep_time): # The mail addresses and password sender_address = 'sender_address' sender_pass = 'sender_pass' receiver_address = 'receiver_address' # Setup MIME message = MIMEMultipart() message['From'] = 'Trading Bot' message['To'] = receiver_address mes...
The code manages a trading bot that monitors open crypto positions, adjusts trailing stop-loss prices, and executes sell orders when price thresholds are met. It checks for new trade signals, enforces a max-trade limit, tracks bought assets, and logs alerts. The bot continuously evaluates open orders, updates stop-loss...
def mainNEW(open_positions): tickers_bought = [] mail_alert("The Bot Started Running on {} at {}".format(dt.now().strftime("%Y-%m-%d"), dt.now().strftime("%H:%M:%S")), 0) try: while True: # Checking Returns every time loop runs if os.path.isfile('ORD...
def createRoutingTables(grid): # Initialize the graph with vertices for each tile in the grid for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] in ["G", "P"]: grid[i][j] = 1 else: grid[i][j] = 0 graph = {} for i in rang...
This code initializes a state for a probabilistic planning problem by processing passengers based on forbidden tiles and their goals. It identifies and removes passengers whose goals or destinations are blocked, prioritizing those with higher probabilities and fewer goals. It then sets up a state space with a queue for...
def __init__(self, initial): self.initial = initial self.passengers_to_del = [] self.map = self.initial["map"] self.gas_stations = [] self.forbidden_tiles = [] for i in range(len(self.map)): for j in range(len(self.map[0])): if self.map[i][j] =...