dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def copyState( state1, state2): for i in range(N): state1[i] = state2[i]; def generateBoard( board, state): fill(board, 0); for i in range(N): board[state[i]][i] = 1; def getNeighbour(board, state): opBoard = [[0 for _ in range(N)] for _ in range(N)] ...
The code implements a hill-climbing algorithm to solve a problem (likely N-Queens) by iteratively improving a state. It generates neighboring states, evaluates their objective function (conflicts), and updates the current state if the neighbor offers improvement. If no improvement is found, it prints the result and exi...
def hillClimbing(board, state): neighbourBoard = [[0 for _ in range(N)] for _ in range(N)] neighbourState = [0 for _ in range(N)] copyState(neighbourState, state); generateBoard(neighbourBoard, neighbourState); while True: copyState(state, neighbourState); ...
def get_tiles(self, aoi): geom_filter = api.filters.geom_filter(aoi.geom.convex_hull.__geo_interface__) for date in self.dates: try: aoi.status("checking {} for coverage".format(date.strftime("%Y-%m-%d"), self.min_cover)) res = self.search_date(aoi, date, geom...
The code processes an Area of Interest (AOI) by searching for coverage data, creating an order if specified, and downloading the ordered data if enabled. It returns the AOI, date, tiles, order ID, and downloaded files, handling errors gracefully and updating the AOI's status throughout the process.
def __call__(self, aoi): try: aoi.status("searching for coverage") date, tiles = self.get_tiles(aoi) except Exception as e: aoi.warn("could not find suitable scenes") tiles = [] order_id = None zip_file = None if tiles: ...
def display_image_with_mask(image_path_to_display, mask_path_to_display, mask_npz_path=None, display=1, alpha=0.7): """ display: 1 for display, 2 for delete Iterate through mask file and overlay """ # print(image_path_to_display) image = cv2.imread(image_path_to_display) if mask_npz_path is ...
This function handles image and mask processing tasks based on the input option. It displays images with masks, fixes masks, annotates new images, deletes masks, or changes work types. Each action checks the image post-operation. Option 5 returns True, others return False.
def take_action(option, image_path, mask_path, mask_path_npz, config): if option == 1: display_image_with_mask(image_path_to_display=image_path, mask_path_to_display=mask_path, mask_npz_path=mask_path_npz) check_image(image_path) el...
def training_set(self, df, length=10000): """ Generates an entire training set for all emotions. Params: df - Pandas Dataframe as returned by method get_mapping() length - Length of each emotion's training set Returns: Tuple with two indexes - index 0:...
The main task of the code is to predict emotions in texts from the Emobank corpus using multiple trained models (e.g., Random Forest). For each text, it aggregates predictions across models into a Counter dictionary, indicating how often each emotion was predicted. The result is a Pandas DataFrame with an "emotion" col...
def map_emobank(self, book_id, models=10, train_length=10000, to_save=False, filename="model.csv"): """ Predict the emotions present in each text in Emobank corpus. Returns Emobank corpus as a Pandas Dataframe. Dataframe contains a new column - "emotion", where for each index, e...
def evaluate(self, triples, test_name, partition=None, write_ranks=False, verbose=True): """ Test link prediction purely in python :param triples: [(h, t, r)] :param test_name: name of test case for printing: test, valid, train :return: r_mr, r_mrr, r_hit1, r_hit3, r_hit10, f_mr,...
This code trains a knowledge graph embedding model with constraint enforcement, learning rate scheduling, early stopping, and periodic evaluation. It iteratively optimizes the model using batched triples, tracks validation performance, saves the best model configuration, and logs training metrics including loss, learni...
def run(self): self.logger.info('Start training\n') exp_time = time.time() # in seconds if self.config.constraint: # if constraint not "", enforce constraint on all embs at start self.model.enforce_hardconstraint() self.best_eval_train = self.evaluate(self.data.train_trip...
def truncate_values(a: np.ndarray, tolerance: float) -> np.ndarray: return np.where(np.abs(a) < tolerance, 0, a) def haar_decode(a: np.ndarray) -> np.ndarray: k = int(math.log2(len(a))) row_decoder = np.linalg.inv(get_haar_transform(k)) return row_decoder.T @ a @ row_decoder def calculate_compression_ra...
The main task of the code is to process an encoded image by truncating its values based on a tolerance threshold, decode it using Haar decoding, calculate the compression ratio relative to the original image, and return both the decoded image and the compression ratio. The function prepares data for visualization but d...
def plot_image(original: np.array, encoded: np.array, tolerance: float) -> None: encoded = truncate_values(encoded, tolerance) # Reuse E acrossS iterations because tolerance increases decoded = haar_decode(encoded) # axes_subplot.imshow(decoded, cmap='gray') ratio = calcul...
def generate_template(args, objects_list): template = '' with open(args.template_template, 'r') as f: template = f.read() indices = random.sample(range(0, len(objects_list)), random.randint(1, 3)) # print(indices) for i in range(len(indices)): index = indices[i] inc_file = os...
This code generates images by iterating through a range of indices, combining shuffled objects and backgrounds. It calls functions to create templates and shells, sets an environment variable, executes a rendering script, and updates a counter to track progress.
def generate(args): objects_list = os.listdir(args.object_root) random.shuffle(objects_list) backgrounds_list = os.listdir(args.bg_root) for i in range(args.start, args.start + args.number): generate_template(args, objects_list) generate_shell(args, backgrounds_list) os.putenv('o...
def insert_param1(self, fip_bin, name, value): fip_bin = bytearray(fip_bin) e = self.param1[name] e.content = value fip_bin[e.addr : e.end] = value return self.update_param1_cksum(fip_bin) def pack_ddr_param(self, fip_bin): if not len(self.body2["DDR_PARAM"].content): ...
The main task of the code is to construct a FIP2 binary by appending and updating specific parameters and sections. It inserts a PARAM2_LOADADDR, adds an empty PARAM2 section, packs DDR parameters, and conditionally includes BLCP_2ND, MONITOR, and LOADER_2ND components with run addresses. It then generates a checksum f...
def append_fip2(self, fip1_bin, args): logging.debug("make_fip2:") fip_bin = bytearray(fip1_bin) # Update PARAM2_LOADADDR param2_loadaddr = len(fip1_bin) fip_bin = self.insert_param1(fip_bin, "PARAM2_LOADADDR", pack("<I", param2_loadaddr)) # Add an empty PARAM2 ...
def _get_structure(json_schema: Union[Dict, List[Dict]]) -> Structure: """ Function returns an object of Structure, curated from the input. Args: json_schema (Union[List[Dict], Dict]): Raw JSON schema of the table. If List[Dict] it is assumed that the value is ...
This function creates or updates a BigQuery structure (table, view, or stored procedure) using a provided JSON schema. It identifies the structure type from the schema, applies creation/update logic via internal methods, and returns the corresponding BigQuery object. The schema may define table fields, partitioning, cl...
def create_or_update_structure( self, project: str, dataset: str, structure_id: str, json_schema: Union[List[Dict], Dict], ) -> Union[Table, Routine]: """ Function creates/updates provided json schema to the structure. Args: project (str):...
def verify_credentials(username, password): if not user_exists(username): return set_status_code(301, "Invalid username"), True correct_pw = verify_password(username, password) if not correct_pw: return set_status_code(302, "Invalid password"), False return None, False def set_status_...
This code handles a POST request to process a user's deposit. It verifies credentials, checks if the deposit amount is positive, deducts 1 unit as a fee, adds the remaining amount to the user's account, and transfers 1 unit to the bank. It returns success or error responses based on validation and transaction outcomes.
def post(self): posted_data = request.get_json() username = posted_data["username"] password = posted_data["password"] money = posted_data["amount"] ret_json, error = verify_credentials(username, password) if error: return ret_json if money <= 0: ...
def verify_credentials(username, password): if not user_exists(username): return set_status_code(301, "Invalid username"), True correct_pw = verify_password(username, password) if not correct_pw: return set_status_code(302, "Invalid password"), False return None, False def cash_with_u...
This code handles a money transfer request by verifying user credentials, checking sender's balance, validating the recipient, and updating accounts. It deducts the amount from the sender, adds it to the recipient, and adjusts the bank's balance, returning appropriate status codes for success or errors.
def post(self): posted_data = request.get_json() username = posted_data["username"] password = posted_data["password"] reciever = posted_data["reciever"] money = posted_data["amount"] ret_json, error = verify_credentials(username, password) if error: ...
def verify_credentials(username, password): if not user_exists(username): return set_status_code(301, "Invalid username"), True correct_pw = verify_password(username, password) if not correct_pw: return set_status_code(302, "Invalid password"), False return None, False def cash_with_u...
This code handles a POST request to add a loan to a user's account. It verifies the user's credentials, retrieves their current cash and debt balances, updates both by adding the specified amount, and returns a success status if valid.
def post(self): posted_data = request.get_json() username = posted_data["username"] password = posted_data["password"] money = posted_data["amount"] ret_json, error = verify_credentials(username, password) if error: return ret_json cash = cash_with_u...
def verify_credentials(username, password): if not user_exists(username): return set_status_code(301, "Invalid username"), True correct_pw = verify_password(username, password) if not correct_pw: return set_status_code(302, "Invalid password"), False return None, False def cash_with_u...
This code processes a loan payment by verifying user credentials, checking available cash, updating the user's account by deducting the payment amount from both cash and debt, and returning a success status if all steps are completed without errors.
def post(self): posted_data = request.get_json() username = posted_data["username"] password = posted_data["password"] money = posted_data["amount"] ret_json, error = verify_credentials(username, password) if error: return ret_json cash = cash_with_u...
def create_credentials(scopes: list, directory: str = '.') -> None: ''' generate token.json for user and use it if it exists ''' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first ...
The main task of the code is to fetch Google Calendar events from a specified start date or the last saved event date, process them into a structured DataFrame, and save them as CSV files. It handles OAuth authentication, splits time ranges into chunks, filters calendars, merges existing data if not forced, and exports...
def main(force: bool) -> None: ''' save events data from google calendar as dataframe (events from 2024-02-01 or last saved to now) ''' start_time = '2024-02-01T00:00:00Z' if os.path.exists(f'{DIR_PATH}/all_events.csv') and not force: prev_df = pd.read_csv(f'{DIR_PATH}/all_events.csv') ...
def set_alignment(self): self.align_to(self.get_parent(), lv.ALIGN.BOTTOM_MID, 0, 12) def direction_buttons(self): def _cb_left_btn(event): self.prev_button() def _cb_right_btn(event): self.next_button() left_button = lv.btn(self) left_button.set_size(20,...
The code initializes a MenuBar component by setting up its controller, initial menu, and UI properties. It configures alignment, size, and navigation buttons, then generates the initial menu buttons based on the specified menu list. The task involves setting up a customizable menu interface with interactive elements fo...
def __init__(self, controller, initial_menu='Main', *args, **kwargs): super(MenuBar, self).__init__(*args, **kwargs) self.index = 0 self.initial_menu = initial_menu self.previous_menu = '' self.controller = controller self.visible = False self.clear_flag(lv.obj.F...
def findNumbers(inputString, middle): result = [] if not inputString[middle].isnumeric(): if middle != 0: if inputString[middle-1].isnumeric(): result.append(int(findPrevNumbers(inputString, middle-1))) if middle != len(inputString)-1: if inputString[middl...
The function `findSurroundingNumbers(i,j)` collects numeric values from the immediate surrounding cells of position `(i,j)` in a 2D grid. It gathers numbers from the same column in the previous and next rows, and adjacent horizontal cells (left and right) in the current row. It uses helper functions like `findNumbers`,...
def findSurroundingNumbers(i,j): all_numbers = [] if i == 0: prevLine = [] else: prevLine = input[i-1] all_numbers.extend(findNumbers(prevLine, j)) if i == len(input)-1: nextLine = [] else: nextLine = input[i+1] all_numbers.extend(findNumbers(nextLine,...
def __get_community_antifilter_ip_list() -> list: ip_list_link = 'https://community.antifilter.download/list/community.lst' r = get(ip_list_link, allow_redirects=True) ip_list = r.content.decode("utf-8").split("\n")[:-1] return ip_list def _get_additional_ip_list_retry(self) -> list: ...
The function aggregates IP addresses from three sources: community anti-filter, additional IPs, and external sites (if 'external_sites.json' exists). It combines them into a deduplicated set and returns the IPs as a comma-separated string.
def get_full_ip_list(self): community_antifilter_ip = self.__get_community_antifilter_ip_list() additional_ip = self._get_additional_ip_list_retry() if 'external_sites.json' in os.listdir(): external_ip = self._get_external_ip_list('external_sites.json') full_ip_list = se...
def ON_PATH(S, STATES): return S in STATES def FINAL_STATE(S): return S == (True, True, True, True) def MULT_DFS(STATES, PATH): if not STATES: # base case: if there are no states to explore, return None return None first_state = STATES[0] if FINAL_STATE(first_state): # check if the first sta...
The code implements a depth-first search (DFS) algorithm to find a path to a goal state in a state space. It checks if the current state `S` is already on the path to prevent cycles, returns the path if `S` is a goal state, and recursively explores all successors of `S` while appending `S` to the path. The function rel...
def DFS(S, PATH): if ON_PATH(S, PATH): # check if nnode has already been visited return None if FINAL_STATE(S): # check for goal state return PATH + [S] return MULT_DFS(SUCC_FN(S), PATH + [S])
def try_to_decide1(self, sud_brd): result = [] success = False nums_set = set([el + 1 for el in range(9)]) rows_lng = len(sud_brd) for row_index, cur_row in enumerate(sud_brd): str_copy = [] curr_impossible_set = set() for cur_str in cur_row:...
The main task of the code is to iteratively solve a Sudoku puzzle by applying decision functions (try_to_decide1, try_to_decide2, try_to_decide3) to reduce empty cells while checking for contradictions. It repeatedly refines the board until no further progress is possible or contradictions arise, ultimately returning t...
def try_to_decide_main(self, sudoku_board_original): current_sudoku_board1 = self.try_to_decide1(sudoku_board_original) start_empty_cells, start_contradictions = self.get_board_info(current_sudoku_board1) stop_test = start_contradictions != 0 while not stop_test: current_sud...
def try_to_decide1(self, sud_brd): result = [] success = False nums_set = set([el + 1 for el in range(9)]) rows_lng = len(sud_brd) for row_index, cur_row in enumerate(sud_brd): str_copy = [] curr_impossible_set = set() for cur_str in cur_row:...
This function attempts to solve a Sudoku board using a sequence of decision-making steps (try_to_decide1, try_to_decide2, try_to_decide3) in a loop. It checks for contradictions and reduces empty cells iteratively. The main task is to determine if the board can be fully solved with no contradictions, returning True if ...
def solution_1_level_is_only(self, sudoku_board_original): current_sudoku_board1 = self.try_to_decide1(sudoku_board_original) start_empty_cells, start_contradictions = self.get_board_info(current_sudoku_board1) stop_test = start_contradictions != 0 while not stop_test: curre...
def try_to_decide1(self, sud_brd): result = [] success = False nums_set = set([el + 1 for el in range(9)]) rows_lng = len(sud_brd) for row_index, cur_row in enumerate(sud_brd): str_copy = [] curr_impossible_set = set() for cur_str in cur_row:...
This function identifies cells in a Sudoku board with the fewest possible values (tuples), iterates through each possibility, and recursively solves the board. It returns all valid completed boards where no conflicts exist.
def try_to_decide4(self, sud_brd): rating_dict = {} for inx1 in range(9): for inx2 in range(9): cur_elem = sud_brd[inx1][inx2] if type(cur_elem) is tuple: lng = len(cur_elem) if lng in rating_dict.keys(): ...
def try_to_decide4(self, sud_brd): rating_dict = {} for inx1 in range(9): for inx2 in range(9): cur_elem = sud_brd[inx1][inx2] if type(cur_elem) is tuple: lng = len(cur_elem) if lng in rating_dict.keys(): ...
The main task of the code is to iteratively solve a Sudoku board by applying decision functions (try_to_decide4, try_to_decide1, try_to_decide_main) to reduce possible states. It processes boards in loops, appending fully solved boards to `decided_sudoku_board` and reprocessing unsolved ones until no new elements remai...
def get_solve_array(self, result_sudoku_board): result_sudoku_board_array = [result_sudoku_board] decided_sudoku_board = [] global_stop_test = False while not global_stop_test: current_board_array = [] for current_supposed_sudoku_board in result_sudoku_board_ar...
def try_to_decide_main(self, sudoku_board_original): current_sudoku_board1 = self.try_to_decide1(sudoku_board_original) start_empty_cells, start_contradictions = self.get_board_info(current_sudoku_board1) stop_test = start_contradictions != 0 while not stop_test: current_sud...
This code solves a Sudoku puzzle by first attempting to determine the main solution using `try_to_decide_main`, then updating the input board with the resolved values if valid. If no solution is found, it leaves the board unchanged. The method checks intermediate results to decide whether to apply the solution, ensurin...
def sudoku_solver(self, board): result_sudoku_board = self.try_to_decide_main(board) result_sudoku_board_info = self.get_board_info(result_sudoku_board) if result_sudoku_board_info[0] == 0: for ind_y, el_y in enumerate(result_sudoku_board): for ind_x, el_x in enumera...
def SQL_load(self,cursor): self.load_name(cursor) self.load_hold(cursor) self.load_currentvalue(cursor) self.load_historicvalue(cursor) print('Portfolio ID '+str(self.id)+' load successful') return self def get_historic_data(self): historic_records = pd.DataFrame(...
This code updates portfolio records by checking the time difference between the latest historic data and current date. If more than one day has passed, it fetches missing historic records, inserts them into the database, and reloads values. Otherwise, it skips the update. The function ensures data consistency by condit...
def update_records(self,cursor): if self.historic_value.size==0: self.SQL_load(cursor) if self.hold.size == 0: return self lastdate=str(self.historic_value[-1][0]) lastdate=datetime.strptime(lastdate[2:],'%y-%m-%d') difference=datetime.now()-lastdate print('difference of ...
def make_mashup(singer_name, num_vides, trim_durration, output_file): download_videos(singer_name, num_vides) video_to_audio() trim_audio(trim_durration) concatinate_audio_files(output_file) return def convert_to_zip(zip_filename): folder_name = os.path.join(OUTPUT_PATH, "Final_Mashup") ...
The main task of the code is to handle a POST request for generating a music mashup based on user inputs (singer name, number of videos, duration, and email). It validates the form data, creates the mashup file, packages it into a ZIP, sends it via email, and notifies the user with a confirmation message.
def index(): if request.method == 'POST': singer_name = request.form['singer_name'] num_videos = int(request.form['num_videos']) duration = int(request.form['duration']) email = request.form['email'] if not (singer_name and num_videos and duration and email): fla...
def loadTrainDataFileNamesOnly(datasetCSV,dataFilesPrefix,input_shape,trainAtt,labelColumnName='category_2',modelName='',subset=1.0,fileHandlerMode='dmu-exp',df_filtered=None): # initialize the set of labels from the dataset we are # going to train our network on # grab the list of images in our dataset dir...
The code loads and prepares training/test data based on parameters. It handles three modes: loading only file names, streaming data via generators, or standard non-streaming loading. It returns data splits (train/test), labels, dataframes, or generators depending on the mode, enabling flexible data handling for machine...
def loadData(datasetCSV,dataFilesPrefix,input_shape,trainAtt,tt_split=0.2,ran_state=42,subset=1.0,labelColumnName='category_2', streaming=False,s_batch=8,onlyFileNames=False,fileHandlerMode='dmu-exp',df_filtered=None): # load training data if onlyFileNames: df_train,trainFiles = loadTrai...
def generate_binary_random_string_of_n_bits(prime, generator, length): initial_seed = input("Input a seed in binary for generating initial vector in PRG: ") # print("Input in PRG: " + str(initial_seed)) res = "" exp = int(initial_seed, 2) for i in range(length): ''' calculating modular exp, ...
The code implements CPA-OFB encryption by splitting data into blocks, generating an initial vector (IV), and iteratively producing a pseudorandom function (PRF) using the IV and key. Each block is XORed with the PRF (or a truncated version) to encrypt data, updating the IV to the PRF for subsequent rounds. The encrypte...
def generate_cpa_ofb(prime, generator, data, block_size, key): print("\n***********************Encryption Stage***********************") split_string = [data[i:i+block_size] for i in range(0, len(data), block_size)] print(split_string) # initial_vector = rand_key(block_size) init...
def encode_into_binary_string_of_given_length(num, length): binary = format(num, "b") # padding leading zeros upto length res = binary.zfill(length) return res def generate_prf(prime, generator, initial_seed, key): res = key for i in range(len(initial_seed)): res = generate_prg(prime, ge...
The code generates a Cipher Block Chaining Message Authentication Code (CBC-MAC) by padding data to block size, splitting it into blocks, and iteratively applying a pseudorandom function (PRF) with XOR operations on each block and a running value. It initializes with the data length's PRF, updates the value per block, ...
def generate_cbc_mac(prime, generator, key, data, block_size): print("\n***********************CBC MAC generation stage***********************") unpadded_data_len = len(data) # If the data length is not multiple of block size, pad zeros if(len(data) % block_size != 0): no_of_zeros_to_be_padded =...
def generate_binary_random_string_of_n_bits(prime, generator, length): initial_seed = input("Input a seed in binary for generating initial vector in PRG: ") # print("Input in PRG: " + str(initial_seed)) res = "" exp = int(initial_seed, 2) for i in range(length): ''' calculating modular exp, ...
The main task of the code is to implement a Chosen Plaintext Attack (CPA) secure encryption scheme using Output Feedback (OFB) mode. It splits input data into blocks, generates a pseudorandom function (PRF) with a prime, generator, and key, XORs each data block with the PRF (or a truncated version), and updates the PRF...
def generate_cpa_ofb(prime, generator, data, block_size, key): split_string = [data[i:i+block_size] for i in range(0, len(data), block_size)] print("After dividing the data into blocks of size: " + str(block_size) + " => ") print(split_string) print("\n***********************Encrypt...
def generate_cpa_ofb(prime, generator, data, block_size, key): print("\n***********************Encryption Stage***********************") split_string = [data[i:i+block_size] for i in range(0, len(data), block_size)] print(split_string) # initial_vector = rand_key(block_size) init...
The code implements a cryptographic protocol using a prime and generator for encryption and message authentication. It encrypts data with a block cipher (OFB mode), generates a CBC-MAC tag for integrity, and verifies decryption. If the decrypted data matches the original, it confirms success; otherwise, it flags tamper...
def main(): prime = 1907 generator = 987 prime = int(input( "Enter the prime number(The prime should be such that p-1/2 should also be prime. Sophie Germain Prime)(1907): ")) generator = int( input("Enter the generator(Primitive root for the prime)(987): ")) ''' length of the key an...
def clean_text(text): class HTMLTagStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.strict = False self.convert_charrefs = True self.text = [] def handle_data(self, data): self.text.append(data) ...
This function processes desktop notifications by extracting details from a message, handling image data, and saving notification/popup information. It constructs a dictionary with app, summary, body, time, and image (from file paths, GTK icons, or embedded data), then stores the data for later use.
def notification_callback(bus, message): args = message.get_args_list() details = { "id": datetime.datetime.now().strftime("%s"), "app": args[0] or None, "summary": clean_text(args[3]) or None, "body": clean_text(args[4]) or None, "time": datetime.datetime.now().strftime...
def add_user_message(self, content: str): self.messages.append({"role": "user", "content": content}) self.logger.info(f"Added user message: {content}") def get_token_count(self, messages: List[Dict[str, str]], model: str) -> int: try: encoding = tiktoken.encoding_for_model(model) ...
The code generates a response based on a user prompt by checking token limits for the specified model, logging details, and handling errors. It adds the prompt to the conversation history, validates token counts, invokes a completion API, logs token usage and time, appends the response, and returns it. If errors occur,...
def generate(self, prompt: str) -> str: proceed_to_generate = True self.add_user_message(prompt) if self.model in self.token_limits: prompt_tokens = self.get_token_count(self.messages, self.model) proceed_to_generate = self.validate_token_count(prompt_tokens) else...
def roulette_wheel_selection(self, players, parent_numbers): # # Computes the totallity of the population fitness population_fitness = sum([chromosome.fitness for chromosome in players]) # Computes for each chromosome the probability probabilities = [chromosome.fitness...
This function generates a new population of Player objects using selection (roulette wheel) and crossover. If no previous players exist, it creates random players. Otherwise, it selects parents, applies crossover to generate children, and returns them. The code includes placeholders for additional selection methods and...
def generate_new_population(self, num_players, prev_players=None): # in first generation, we create random players if prev_players is None: return [Player(self.mode) for _ in range(num_players)] else: # TODO # num_players example: 150 # prev_pla...
def getVehicles(): # l.info("Getting vehicles.") # add time in hh:mm:ss format # round to nearest second # return vehicle object # get vehicles # https://feeds.transloc.com/3/vehicle_statuses?agencies=1323 url = "https://feeds.transloc.com/3/vehicle_statuses?agencies="+str(rutgersAgencyCode...
The code periodically fetches and processes vehicle data every 5 seconds from Transloc API, updating 'currently stopped' and general bus lists. It runs in a loop until the current time falls within predefined start/end time ranges, handling exceptions and maintaining 5-second intervals.
def startLoop(routes, stops): l.info("Starting loop.") # wait for next 5s interval tim = datetime.datetime.now() tims = (tim - tim.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() timsr = round(tims) # get unix time timu = int(time.time()) time.sleep(5 - (timsr % 5)) ...
def fetchBusDataNow(): #set url var rutgersAgencyCode = 1323 # url = 'https://transloc-api-1-2.p.rapidapi.com/vehicles.json?agencies='+str(rutgersAgencyCode)+'&callback=call' #set headers # global headers #fetch data # request = urllib.Request(url, headers=headers) url = "https:/...
The main task of the code is to periodically fetch and process bus data every 5 seconds during specific hours (2:00 AM to 4:00 AM), logging timestamps and operation durations. It checks the current time, stops execution outside the designated window, handles errors, and recursively schedules itself to run at the next 5...
def startReading(): # print("Starting reading...") logging.info("Starting reading...") #without using .sleep, run at 4:00:00, 4:00:05, 4:00:10, ... # get current time (I don't care about timezones, use local time) tempcurrenttime = datetime.datetime.now() # get seconds since midnight temps...
def fetchBusDataNow(): #set url var rutgersAgencyCode = 1323 url = 'https://transloc-api-1-2.p.rapidapi.com/vehicles.json?agencies='+str(rutgersAgencyCode)+'&callback=call' #set headers global headers #fetch data request = urllib.Request(url, headers=headers) requestTime = time.ti...
The main task of the code is to periodically fetch, parse, and write bus data every 5 seconds during non-bus hours (2:00-4:00 AM), logging timestamps and performance metrics. It checks the current time, waits for 5-second intervals, executes data operations, and terminates at the end of the "bus day" (4:00 AM). Error h...
def startReading(): # print("Starting reading...") logging.info("Starting reading...") #without using .sleep, run at 4:00:00, 4:00:05, 4:00:10, ... # get current time (I don't care about timezones, use local time) tempcurrenttime = datetime.datetime.now() # get seconds since midnight temps...
def windDown(): # wind down l.info("Exiting.") sys.exit() def getRoutes(): l.info("Getting routes.") # return route object # get routes # https://feeds.transloc.com/3/routes?agencies=1323 url = "https://feeds.transloc.com/3/routes?agencies="+str(rutgersAgencyCode) try: respo...
The main task of the code is to initialize data retrieval by fetching routes and stops, validate the current time against predefined thresholds, and start a 5-second interval loop for processing. It includes error handling for data fetching failures and exits gracefully if conditions are unmet, ensuring operations only...
def startReading(): l.info("Start reading") # 1. get routes # 2. get stops # 3. start 5s loop tim = datetime.datetime.now() tims = (tim - tim.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() timsr = round(tims) # litmus check to see if it is between 3:45am and 5:30am...
def setupLogging(): global outputDir global outputDirAdd # return logging object # create logger l = logging.getLogger() l.setLevel(logging.DEBUG) # create file handler and set level to debug # realtime log: test.log realtimeLog = logging.FileHandler(outputDir+outputDirAdd+'test.l...
The code initializes logging and checks the current time. It determines if the time is after 5:30 AM, before 3:45 AM, or in between. If after 5:30 AM or before 3:45 AM, it starts reading; otherwise, it waits until 5:30 AM. It handles exceptions during execution, logging errors and terminating gracefully. The main task ...
def init(): global dayStr global l # Set up logging l = setupLogging() l.info("Init") # determine time now = datetime.datetime.now() dayStr = now.strftime("%Y-%m-%d") sinceMidnight = now - datetime.datetime.combine(now.date(), datetime.time()) sinceMidnightSeconds = sinceMidnig...
def _generate_otp() -> str: """ Generates a random string of 6 digits. The range of values is "000000" to "999999". This function uses the cryptographically-secure implementation of os.urandom() to generate random bytes. :return: Returns a random string of 6 digits. """ # Generate 4 random bytes...
The main task of the code is to generate an OTP, send it to the provided mobile number, and return the OTP value along with a timestamp.
def generate_otp(mobile_number: str) -> str: """ Generates an OTP and sends it to the user. :return: Returns the generated OTP value, as a string. """ otp = _generate_otp() _send_otp_to_user(otp=otp, mobile_number=mobile_number) return otp, getTimeStamp()
def check_status(player, hand_index=0) : done = False hand_string = '[' for card in player.hand[hand_index][:-1] : hand_string += card.__str__() + ', ' print(f'Current Hand: {hand_string}', end='') sys.stdout.flush() time.sleep(0.5) disp_str_slow(f'{player.hand[hand_index][-1].__str_...
This function processes the dealer's actions in a card game, making them hit until reaching a hard 17, then evaluates all players' outcomes. It updates balances, handles busts, wins, and ties, displays earnings, converts money to chips, and checks if players are broke. For non-dealer players, it triggers decisions and ...
def cycle_decisions(players) : dealer = players[-1] for p in players : if isinstance(p, people.Dealer) : print(f'{p.name} will hit until reaching a hand of at least \'hard\' 17 (without an ace counting for 11).') sys.stdout.flush() time.sleep(0.8) if not c...
def center_selection(self): datalen = len(data_train) number = [] centers = [] distance1 = [] max_part = 0 max_total = 0 i = 0 while i != self.num_centers: index = random.randint(0, datalen - 1) if number.count(index) == 0: ...
The main task of the code is to predict labels for test data using a trained model. It computes weight matrices based on selected centers and sigma values, applies the trained parameters (w_matrix_test) via matrix multiplication, threshold the results to -1/1 for binary classification, and returns the predicted labels.
def get_predict_test(self): centers, sigma = self.center_selection() datalen = len(data_test) centrelen = len(centers) w_matrix = [[0 for j in range(0, centrelen + 1)] for i in range(0, datalen)] for i in range(0, datalen): for j in range(0, centrelen): ...
def train(centers, sigma): datalen = len(data_train) centrelen = len(centers) w_matrix = [[0 for j in range(0, centrelen + 1)] for i in range(0, datalen)] for i in range(0, datalen): for j in range(0, centrelen): w_matrix[i][j] = Neuron(centers[j], sigma, data_train[i]) for k in ...
The main task of the code is to select optimal cluster centers and parameters (sigma) that maximize accuracy for a model. It iterates through sigma values, evaluates accuracy for different center configurations (via training and prediction), tracks the highest accuracy, and returns the best centers, corresponding accur...
def Choose_center(): sigma_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] max_part = 0 max_total = 0 max_maximum = 0 centers= [] moving_list = [] value_list = [] value_list_total = [] centers_proper = [] num_centers_list = [] for i in range(0, 9): sigma = s...
def get_batches(x, y, batch_size): '''Create the batches for the training and validation data''' x, y = unison_shuffle(x, y) for ii in range(0, len(x), batch_size): x_batch = x[ii:ii+batch_size] y_batch = y[ii:ii+batch_size] yield x_batch, y_batch[:, None] def val...
This code trains a Recurrent Neural Network (RNN) using TensorFlow, iterating over epochs with batched data. It logs training and validation metrics, employs early stopping if validation loss stagnates, and saves checkpoints of the model when improvements are detected. The function handles data batching, computes loss/...
def train(self, X, y, epochs, batch_size, log_string, stop_at=3, measures_per_epoch=2): '''Train the RNN Args: X: Tuple of lists corresponding to train and validation data y: Tuple of lists corresponding to train and validation labels epochs: Number of...
def get_batches(x, y, batch_size): '''Create the batches for the training and validation data''' x, y = unison_shuffle(x, y) for ii in range(0, len(x), batch_size): x_batch = x[ii:ii+batch_size] y_batch = y[ii:ii+batch_size] yield x_batch, y_batch[:, None] def val...
This code trains an RNN model using TensorFlow, performing batch-wise training with validation checks at specified intervals. It logs training/validation loss and accuracy, implements early stopping if validation loss stagnates for 'stop_at' epochs, and saves the best model checkpoint. The function returns the saved mo...
def train(self, X, y, epochs, batch_size, log_string, stop_at=3, measures_per_epoch = 2): '''Train the RNN Args: X: Tuple of lists corresponding to train and validation data y: Tuple of lists corresponding to train and validation labels epochs: Number ...
def pos_tag_text(tokenized_text_list): # Tokenized_text_list: a list of lists containing tokenz [n_samples, None] start = time.time() print("-- Starting to pos tag --") it = 0 pos_tagged = [] for tokenz in tokenized_text_list: pos_tagged.append(pos_tag_tokenz(tokenz)) it +=...
This function preprocesses text data by tokenizing tweets, performing POS tagging, converting words and tags to integer embeddings using provided dictionaries, and combining these embeddings into structured arrays for training and testing machine learning models.
def preprocess_data_pos(train, test, word_to_int, add_pad = True): #train: collection of tweet lists [n_collections, n_samples] of strings #test: collection of tweet lists [n_collections, n_samples] os strings #word_to_int: {voc:int} dictionary of word to int # Tokenize data and tag ...
def preprocess_data_standard(data, word_to_int, add_pad = True): #data: [n_samples] List of tweets in string format #word_to_int: {voc:int} dictionary of word to int # Start by tokenizeing the data all_tokenz = tokenizers.custom_twitter_tokenizer.tokenize_text(data) # Embed th...
The main task of the code is to preprocess a collection of text data (e.g., tweets) using different methods based on the specified `type` parameter. It applies transformations such as standard embedding preprocessing, POS tagging, sentence-level processing, average embeddings, or no changes. The function handles batch ...
def preprocess_data_collection(data_collection, word_to_int, embeddings,type="embed", add_pad=True): """ gets a collection of data objects and preprocesses all of them. Data objects are a list of strings, representing the tweets. """ print("Starting to preprocess data sets...") ...
def empty_bed(self, bed, target): # update the bed target (just in case) bed.set_control_target(target) # check if the bed is empty if bed.is_empty() == False: self.logger.log(f'FarmController/empty_bed---> I am not doing anything at the moment!') self.close_valve(bed) # if the bed is not empty, publish...
This code processes incoming messages to manage a specific bed (A1) in a system. It checks if the message relates to emptying, filling, or updating the water level of bed A1. If so, it retrieves the bed object, logs the action, and executes the corresponding operation (emptying, filling, or updating water level). The c...
def process(self, topics, value ): print(f'processing message: {topics} {value}') # for all other messages: fetch the bed label and the message value if self.communicator.is_empty_bed_msg(topics, value): bed_label = self.communicator.get_bed_label(topics) if bed_label != 'A1': return bed = self.far...
def initPop(count, length, maxAcc, tries): pop = [] for i in range(0, count): indiv = produceIndividual(length, maxAcc) pop.append([indiv, fitness2(indiv)]) for i in range(0, tries): pop.sort(key=lambda pair: pair[1]) indiv = produceIndividual(length, maxAcc)...
Your returnThe main task of the code is to perform a genetic algorithm step that generates a new population by selecting, crossing over, and mutating individuals from the input population, while avoiding duplicates. It expands the population, iteratively creates new individuals through crossover and mutation, checks fo...
def geneticStep(pop, relNewSize, duplicatesThreshold, intersectionDelta, mutationProb, mutationDeviation, tries): initSize = len(pop) pop = pop + initPop(int(len(pop) / 10), len(pop[0]), 1, 0) newPop = [] for i in range(0, initSize): indiv = [] for ...
def get_se_input_layer(e, dimension): print('adding the se input layer...') ent_embeddings = tf.Variable(tf.truncated_normal([e, dimension], stddev=1.0 / math.sqrt(e))) return tf.nn.l2_normalize(ent_embeddings, 1) def get_sparse_tensor(e, KG): print('getting a sparse tensor...') M, du = get_mat(e, KG) ind = [] v...
This code constructs a neural network model for embedding entities and relations in a knowledge graph (KG). It initializes input layers, applies sparse tensor operations, and uses diagonal layers with activation functions to process embeddings. The model computes a loss function based on input-output discrepancies (ILL...
def build_SE(dimension, act_func, gamma, k, e, ILL, KG): tf.reset_default_graph() input_layer = get_se_input_layer(e, dimension) M = get_sparse_tensor(e, KG) hidden_layer = add_diag_layer(input_layer, dimension, M, act_func, dropout=0.0) output_layer = add_diag_layer(hidden_layer, dimension, M, None, dropout=0.0) ...
def get_ae_input_layer(attr): print('adding the ae input layer...') return tf.constant(attr) def get_sparse_tensor(e, KG): print('getting a sparse tensor...') M, du = get_mat(e, KG) ind = [] val = [] for fir, sec in M: ind.append((sec, fir)) val.append(M[(fir, sec)] / math.sqrt(du[fir]) / math.sqrt(du[sec]))...
This code constructs an autoencoder (AE) model for learning low-dimensional embeddings. It initializes input layers, processes sparse tensors from a knowledge graph (KG), applies fully connected layers with dropout, and computes a loss function involving item-item interactions (ILL) and a margin parameter (gamma). The ...
def build_AE(attr, dimension, act_func, gamma, k, e, ILL, KG): tf.reset_default_graph() input_layer = get_ae_input_layer(attr) M = get_sparse_tensor(e, KG) hidden_layer = add_full_layer(input_layer, attr.shape[1], dimension, M, act_func, dropout=0.0) output_layer = add_diag_layer(hidden_layer, dimension, M, None, ...
def free_text_query(string,invertedIndex): string = clean_text(string) pattern = re.compile('[\W_]+') string = pattern.sub(' ',string) result = {} for word in string.split(): result = one_word_query_dict(word,invertedIndex,result) #print(result) return result def phrase_query_correct...
The main task of the code is to process different query types (free text, phrase, wildcard) using an inverted index, retrieve matching documents, and print their snippets from the dataset while measuring execution time. It handles query parsing, result extraction, and snippet display for three query modes, with specifi...
def printresult_wc(query_type,query): #prints the snippets start=time.time() if(query_type == "1"): res=free_text_query(query,inverted_index) elif(query_type == "2" ): res=phrase_query_correct(query,inverted_index) elif(query_type == "3"): p =...
def _tsne_window_callback(self, x, y): """ Callback function if pressed in tSNE window. :param x: :param y: :return: """ self._display_from_tsne(x,y) def _main_window_callback(self, x_image, y_image): """ Callback function if pressed in Main windo...
This code handles mouse click events in a GUI, determining which window (tSNE, main, or sub-window) was clicked. It triggers corresponding callbacks with coordinates, and for middle-clicks in sub-windows, it extracts filenames, adjusts paths, updates the main window's display, and redraws the figure to reflect changes.
def _onclick(self, event): """ Main callback if a mouse button is clicked in the main window. :param event: :return: """ # If clicked in tSNE if event.inaxes == self._tsne_window: self._tsne_window_callback(event.xdata, event.ydata) # If cli...
def pixelToMillimiter(tamanho): # 1 milimitro equivale a 3.78 pixels pixels = 3.78 return int(tamanho * pixels) def percorrerImagem(img, raio): for x in range(0, int(img.shape[0])-1): for y in range(0, int(img.shape[1])-1): # Gerar Bordas if(img[x, y] < min + raio and i...
This function scans an image to identify concentration points, converts pixel measurements to millimeters, and checks neighboring regions around these points using a specified radius and percentage threshold to analyze potential anomalies or features.
def iniciarVarredura(img, raio, tamanho, percent): global pontosDeConcentracao tamanho = pixelToMillimiter(tamanho) percent = percent / 100 percorrerImagem(img, raio) for coord in pontosDeConcentracao: verificarVizinhos(tamanho, img, raio, coord._esquerda, coord._y, percent) verific...
def resample(points): I= pathlength(points)/ 31 D = 0.0 newpoints = [points[0]] for i in range(1, len(points)): d = distance(points[i-1],points[i]) if (D+d)>=I: if d==0: d=0.0000001 qx = points[i-1][0]+((I-D)/d)*(points[i][0]-points[i-1][0]) ...
The main task of the code is to standardize a set of points by sequentially resampling, rotating to align with zero, scaling to fit a square, and translating to the origin, ensuring uniform positioning and orientation for further processing.
def transform(points): points = resample(points) points = rotatetozero(points) points = scaletosquare(points,size) points = translatetoorigin(points) return points
def answers_that_meet_criteria(filtr: WordsFilter, words: list[str] = None) -> list[str]: possible_answers = [] if words is None: words = targets_list for word in words: if filtr.IndexedLetters and not matches_exact_letters(word, filtr): continue if filtr.IncludedLetter...
The function calculates the total "narrowing score" for each guess word in the input list across all valid target answers. It accumulates scores by iterating through targets and guesses, adding the score from the narrowing_score function (or 0 if guess equals target) to a dictionary mapping each guess to its cumulative...
def narrowing_score_per_word(guess_list: list[str]) -> dict[str, int]: return_dict = {} targets = answers_that_meet_criteria(blank_filter()) for tgt in targets: for guess in guess_list: return_dict.setdefault(guess, 0) score = narrowing_score(tgt, guess) if guess != tgt else ...
def answers_that_meet_criteria(filtr: WordsFilter, words: list[str] = None) -> list[str]: possible_answers = [] if words is None: words = targets_list for word in words: if filtr.IndexedLetters and not matches_exact_letters(word, filtr): continue if filtr.IncludedLetter...
The function calculates a cumulative score for a given word guess by evaluating its compatibility with multiple target words. It initializes a dictionary, iterates through filtered target answers, computes a score for each target using `narrowing_score`, and accumulates these scores in the dictionary. If the guess matc...
def narrowing_score_per_word_multi_threaded(guess: str) -> dict[str, int]: return_dict = {} targets = answers_that_meet_criteria(blank_filter()) for tgt in targets: return_dict.setdefault(guess, 0) score = narrowing_score(tgt, guess) if guess != tgt else 0 return_dict[guess] += score...
def answers_that_meet_criteria(filtr: WordsFilter, words: list[str] = None) -> list[str]: possible_answers = [] if words is None: words = targets_list for word in words: if filtr.IndexedLetters and not matches_exact_letters(word): continue if filtr.IncludedLetters and n...
This function calculates the cumulative "narrowing score" of a given guess word against multiple target words. It iterates through all qualifying target words, computes the score for each target-guess pair (excluding exact matches), and aggregates the total score in a dictionary with the guess as the key. The result is...
def narrowing_score_per_word_multi_threaded(guess: str) -> dict[str, int]: return_dict = {} targets = answers_that_meet_criteria(blank_filter()) for tgt in targets: return_dict.setdefault(guess, 0) score = narrowing_score(tgt, guess) if guess != tgt else 0 return_dict[guess] += score...
def kwargsDefaults(kwargs:dict): """return default kwargs for the get_events obspy function for elaboration about these arguments: https://docs.obspy.org/packages/autogen/obspy.clients.fdsn.client.Client.get_events.html Args: kwargs (dict): the kwargs that contain parameters for the obsp...
This function generates and saves a seismic event catalog using specified parameters. It creates a folder, retrieves events via ObsPy (with exception handling), saves the catalog as txt/XML, and generates a README file detailing the parameters used.
def createAndSaveCat(containingFolderPath, clientName='NCEDC', saveAsTxt=False, **kwargs): """cretae a txt catalog according to your specifications. Args: containingFolderPath (str, or Path): location to save data. Will create a folder by this name cntaining all relevant data client (str, optio...
def go_to_admin_actions(self): self.stacked.setCurrentWidget(self.admin_actions) def create_month_dialog(self): self.dialog = QDialog(self) self.dialog.setWindowTitle('Switch Month') # self.dialog.setStyleSheet(self.style) self.dialog.resize(200, 100) # Set the size of the dialo...
This function handles UI navigation by checking the text of a menu item (q) and switching to corresponding views like admin actions, month setup, account settings, or logging out, using a stacked widget to display different sections of the application.
def change_view(self, q): if q.text() == 'Transactional Actions': self.go_to_admin_actions() elif q.text() == 'Switch Month': self.create_month_dialog() elif q.text() == 'Edit Account': self.go_to_account_settings() elif q.text() == 'Job Setup': ...
def nonsquare_int(int_max=11): # returns a list of 1 <= intergers <= int_max with no square factors squares = [n**2 for n in np.arange(2,np.ceil(np.sqrt(int_max)))] sqdiv = [] for k in range(int_max+1): sqdiv = sqdiv + [k*s for s in squares] L = [1] for n in range(2, int_max+1): ...
The function `real_to_fraction_x_root_maybe` attempts to represent a real number `x` as a simplified expression involving a square root multiplied by a fraction (e.g., `sqrt(a)*b/c`). It iterates through non-square integers up to a specified `root_max`, divides `x` by the square root of each integer, and checks if the ...
def real_to_fraction_x_root_maybe(x, **param): # tries to convert a real to something like sqrt(a)*b/c # 'a' cannot be larger than 'root_max' # we return a sympy number, a certificate, and a latex string # Here is a stupid implementation for n in nonsquare_int(param['root_max']): y = x / np....
def fraction_to_latex(x, **param): # x is supposed to be a number.Fraction here if x.denominator == 1: return str(x.numerator) elif x.numerator == 0: return '0' else: return display_fraction(str(x.numerator), str(x.denominator), **param) def real_to_fraction_maybe(a, **param): ...
The function `number_to_algebraic` converts a numerical input (real or complex) into a LaTeX-formatted algebraic expression and a simplified approximation. It prioritizes exact representations (e.g., fractions, roots) within a specified tolerance; if unsuccessful, it defaults to a decimal approximation. Complex numbers...
def number_to_algebraic(x, **param): """ Input: x, typically a "number" (can mean many things) Output: latex, approx approx is a hopefully faithful simple equivalent formulation of x could be Fraction, or sympy number, polynomial etc latex is a string representing app...
def plot_pole(self, x, y): target_pole = pg.TargetItem(pos=[x, y], size=20, symbol='x', pen='w', brush='w', movable=True) self.pole_items.append(target_pole) self.plot_widget.addItem(target_pole) target_pole.sigPositionChanged.connect(lambda e: self.pole_moved(id(target_pole), e)) ...
The code handles mouse clicks on a plot to add poles (left-click) or zeros (right-click) based on the checkbox state, appending coordinates to respective lists and updating the plot. It then triggers a frequency response plot update, with identical logic executed regardless of the checkbox status.
def on_click(self, event): pos = self.plot_widget.getViewBox().mapSceneToView(event.scenePos()) if self.reflect_checkbox.isChecked(): if event.button() == 1: # Left mouse button for poles self.poles.append((pos.x(), pos.y())) self.plot_pole(pos.x(), pos.y())...
def conv_2_init(inputs, filter_num, kernel_size=(3,3), strides=(1,1)): """ Defines a 2D Convolution block with 'he_normal' kernel initializer. This function creates a 2D convolutional layer with a specified number of filters (channels), kernel size, strides, and 'he_normal' kernel initializer. Arg...
The code defines a CLCI_Net model for semantic segmentation, using an encoder-decoder structure with skip connections. The encoder extracts multi-scale features through convolutional and pooling layers, while the decoder upsamples and fuses features for precise segmentation. The model outputs a class probability map us...
def CLCI_Net(input_shape=(224, 176, 1), num_class=1): """ Creates the CLCI_Net model for semantic segmentation. Args: input_shape: Tuple representing the shape of the input tensor (height, width, channels). The row and column of the input should be resized or cropped to an inte...
def log_process(log = ""): global use_logs if use_logs == True: new_key = int(list(process_log.keys())[-1]) + 1 process_log["%s" % new_key] = log def get_word(word, arr): # finds a given keyword within the structure wordLen = len(word) ref = None for i in range(0, len(arr) - 1): ...
The code processes a string to structure mathematical expressions, handling numbers (including negatives, decimals), operations, parentheses, and keywords. It replaces "pi" with π, substitutes keywords with structured elements, and returns an array representing the parsed components for further processing.
def structure_string(str): # Analyzes string to generate structure conatining string data # Log process label for structuring log_process("Structuring") # structure multi-digit numbers, negative numbers, decimal numbers, mathematical operations, parenthesis, and square brackets arr = [] digits =...
def json_decode(self,json_bytes): return json.loads(json_bytes.decode('utf-8')) def compute_checksum(self,message): checksum=0 l=len(message) if(l%2==1): l=l+1 xs = bytearray(message) xs.append(0) message =bytes(xs) for i in range(0, l, 2): checksum=checksum+(message[i] << 8)+(message[i+1]) ...
This method receives UDP data, parses headers, extracts content, verifies a checksum, and processes the request if valid. It handles data segmentation, JSON decoding, and integrity checks before triggering request processing.
def read_server(self): try: recv_data,addr=self.sock.recvfrom(4096) self.client=addr except Exception: pass else: if(recv_data): self.recv_data=self.recv_data+recv_data msg=b"" if(self.headers_length is None): header_length = 2 if(len(self.recv_data)>=header_length): msg=ms...
def create_uniform_background(self, height, width, diff_height=0, diff_width=0): images = [] for i in range(self.augmentation_actions["nr_uniform_background"]): random_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) if diff_height == 0 and diff_wi...
The code generates training data for image recognition by creating square and rectangular background images, applying text overlays, blur, and cutout augmentations, then combining and resizing images before saving them to disk.
def create_training_data(self, path_to_output="", create_folder=True): background_images_square = [] background_images_rect = [] ######First create background images##### background_images_uniform_square = self.create_uniform_background(self.image_size[0], self.image_size[1]) ba...
def observe_world(): global last_observed_item x, y = player["pos"] item = world[y][x] if last_observed_item == item: return if item not in WORD_ITEM: return word_item = WORD_ITEM[item] if item == TILLED_SOIL: print_feedback(f"This looks like {word_item}") e...
The code processes game mechanics including updating the game clock, handling user input, managing item pickups (adding to inventory and removing from the map), auto-equipping items, growing seeds through stages, decrementing player hunger at intervals, and deleting expired messages. It maintains world state, player in...
def process(): global player_in_ship global clock global hunger_last_decrement clock = int(time.time()) - clock_start observe_world() # user input poll_user_input() # check for items if player["pos"] in item_map: position = player["pos"] item = item_map[po...
def getAllNodes(self): return list(self.nodes.keys()) def topologicalSort(self): self.visited = {} for node in self.getAllNodes(): self.visited[node] = False self.stack = [] for i in self.getAllNodes(): if self.visited[i] == False: self.t...
This code computes the longest path in a directed acyclic graph (DAG) from a given start node using topological sorting. It initializes distances to negative infinity, sets the start node's distance to 0, processes nodes in topological order, and updates neighbor distances if a longer path is found. Finally, it prints ...
def longestPath(self, startNode): dist = {} for node in self.getAllNodes(): dist[node] = -10**9 self.topologicalSort() dist[startNode] = 0 while (len(self.stack) > 0): u = self.stack[0] del self.stack[0] if (dist[u] != 10**9): ...
def _computegram(self, X, Z): """ Computes the kernel gram matrix which is a measure of similarity between each point in X and each point in Z. Parameters: ----------- X: A matrix of shape (n, -1). Z: Another matrix of shape (n, -1). ...
The code fits a Support Vector Machine (SVM) model for binary classification by initializing parameters, computing the kernel Gram matrix, optimizing model parameters via the _fast method, and storing results like optimized weights, objective function history, and parameter updates. It enforces two-class input, convert...
def fit(self, X, y): """ Fits the SVM model according to the given training data. Parameters: ----------- X: Training vectors of shape (n_samples, n_features). y: Target values of shape (n_samples, 1). Must contain only 2 classes. Return...
def get_train_loader(self, sampler_type: str='std', joint: bool=False, transform_state: str='train', full_data: bool=False, cur_session: int=0): """ @ sampler_type: sample batc...
The code trains a few-shot learning (FSL) model with options for meta-training, data augmentation, and loss combination. It initializes the model, loads data, computes local/global losses, updates parameters via optimizer, and validates periodically. The model is saved if validation accuracy improves. The training incl...
def train(self, reload=True): """ @ para use_auto_scheduler: whether use auto strategy to update lr @ para test_method: the test method, eg: fsl_test or test choice=['fsl', 'single', 'db] @ para global_loss: align the test process @ para reload: whether reload previous model ...
def get_train_loader(self, sampler_type: str='std', joint: bool=False, transform_state: str='train', full_data: bool=False, cur_session: int=0): """ @ sampler_type: sample batc...
The code pretrains a model for a specific session in a continual learning setup, updating its parameters using a training dataset. It trains the model with a custom loss function, tracks training losses, and evaluates performance periodically. The best model is saved based on test accuracy, incorporating both base and ...
def pretrain_process(self, train_log_path, model_save_path, joint: bool=False, cur_session: int=0): num_seen_cls = self.model.base_cls_num + cur_session * self.model.inc_cls_num # set optimizer optimizer, scheduler = get_optimizer(self.model, self.args) # base train loader tra...
def balance_node(self): if self.is_balanced() == True: return values = str(self).split() values = [int(i) for i in values] input_list = middle_out(values) branch = self.branch root = self.root for item in input_list: self.delete_value(item)...
The code balances a data structure by first balancing itself, then processing its string-representation values into integers, reordering them with a `middle_out` function, and recursively balancing each node in the reordered sequence.
def balance(self): self.balance_node() values = str(self).split() values = [int(i) for i in values] values = middle_out(values) for value in values: node = self.search(value)[0] node.balance_node() return
def parseInput(fName="input.in"): rdata = open(fName, "r").readlines() rdata = [i.strip() for i in rdata] return [eval(i) for i in rdata if i != ""] def part1(data): total = 0 i = 0 while i < len(data): left = data[i] right = data[i+1] i += 2 check = compareData(d...
The code's main task is to parse input data from "input.in", solve two parts of a problem using deep copies of the data, and print the results for both parts. Part 1 and Part 2 are executed separately to ensure the original data remains unaltered, with each part's output displayed sequentially.
def solve(): data = parseInput("input.in") print("PART 1 ->", part1(deepcopy(data))) print("PART 2 ->", part2(deepcopy(data)))
def parseInput(fName="input.in"): rdata = open(fName, "r").read().splitlines() sensors: list[tuple[int, int]] = [] beacons: list[tuple[int, int]] = [] for line in rdata: data = line.split("=") sx = data[1].split(",")[0] sy = data[2].split(":")[0] bx = data[3].split(",")[...
The code reads input data from a file (defaulting to "sample.in" or using a command-line argument), parses sensor and beacon positions, and computes solutions for two parts of a problem. It outputs results for **Part 1** and **Part 2**, likely involving spatial analysis (e.g., coverage, distances, or grid-based calcula...
def solve(): file = "sample.in" if len(sys.argv) >= 2: file = sys.argv[1] + ".in" sensors, beacons = parseInput(file) isSample = True if file == "sample.in" else False print("PART 1 ->", part1(sensors, beacons, isSample)) print("PART 2 ->", part2(sensors, beacons, isSample))
def matching_tags(node_w, node_s): """ Function checks if two nodes are matching tags. :param node_w: BeautifulSoup node of wrapper page :param node_s: BeautifulSoup node of wrapper page :return: boolean value indicating if the nodes are matching tags """ return isinstance(node_w, Tag) and i...
The function constructs a union-free regular expression AND-OR tree from wrapper and sample page structures, aligning their elements by recursively matching tags, handling string differences with #PCDATA, and identifying iterators/optionals to represent common patterns between the two pages.
def run_roadrunner(node_wrapper, node_sample): """ Function creates a wrapper of AND-OR tree structure containing union-free regular expressions based on provided sample and wrapper page trees. ? for optional, + for iterator, ( ) for grouping and #PCDATA for any string :param node_wrapper: Beautiful...
def get_url_from_frontier(): url = frontier.get() return url def request_page(url, web_driver=None, threadID=0): """Fetches page at url and returns HTML content and metadata as dict.""" domain = urlparse(url).netloc site_data = None # Parsed SITE metadata page_raw = { "html_content":...
The main task of the code is to fetch the next URL from the frontier, retrieve and parse its content using a web driver, and save the parsed page data along with site information into a database, all while managing thread-specific operations.
def process_next(self): """Fetches, parses and saves next page from frontier.""" url = get_url_from_frontier() page_raw, site_data = request_page(url, web_driver=self.web_driver, threadID=self.threadID) page_obj = parse_page(page_raw, url, self.conn) save_to_db(page_obj, site_da...
def _add_shared_items() -> List: Console.log(message='Adding shared items...') shared_items_confirmed = False while not shared_items_confirmed: Console.log(message='Add shared items:') shared_items = [] item = _add_item() shared_items.append(item) add_more_shared_item...
This function creates a new tab by prompting the user for a tab name, shared items, and participants. It validates inputs, confirms the tab details, and constructs a `Tab` object. If both shared items and participants are empty, it errors out. If participants are missing, it asks for shared participant count. Finally, ...
def _new_tab() -> None: tab_confirmed = False while not tab_confirmed: tab_name = typer.prompt('Tab name', confirmation_prompt=False, hide_input=False) add_shared_items = typer.confirm('Add shared items?') if add_shared_ite...
def check_news_api() -> dict: '''Makes an news API request and returns a notification Information on the latest news is requested and is then filtered so that only relevant articles are considered to be added as notifications. The information on the latest relevant article is returned in di...
The function generates a list of announcements triggered by an alarm, incorporating data from news, COVID, and weather APIs. It processes text by removing punctuation, constructs default announcements, and conditionally adds news/weather updates based on the alarm's settings. It also removes the alarm from the active l...
def create_announcment(alarm: dict) -> list: """Creates a list of announcements to be announcement when an alarm goes off Information is extracted from APIs and the alarm input to construct an announcement based on the set alarm. Keyword arguments alarm -- the alarm from where informatio...
def check_news_api() -> dict: '''Makes an news API request and returns a notification Information on the latest news is requested and is then filtered so that only relevant articles are considered to be added as notifications. The information on the latest relevant article is returned in di...
The function `update_notif` schedules itself to run every four hours (14400 seconds) using `s.enter`. It logs the update process and appends notifications from three APIs—news, weather, and Covid-19—to a global `notifications` list, logging each addition. Its main task is to periodically gather and store notifications ...
def update_notif() -> None: """updates notifications every four hours""" s.enter(14400, 1, update_notif,()) logging.info('notifications updating') notifications.append(check_news_api()) logging.info('news notification added to notifications') notifications.append(check_weather_api()) logging...
def _full_register(self, fcode='', name=True): # Run 3 times as the user may already exist s = requests.Session() for _ in range(3): if name: username = random_name() password = random_string() else: username = random_string...
The main task of the code is to test user actions in a service, including registration, voucher validation, friend code checks, and purchasing expensive items. It maintains a list of users, performs sequential checks, and repeatedly attempts to buy items until successful or reaching a limit. The function returns a chec...
def check_service(self): """ Test various actions the user can do. After X ticks, the checker buys expensive items """ users = checkerlib.load_state("users") reg_res = self._full_register() if type(reg_res) != tuple: # something went wrong return reg_...
def write_code(code, filename): with open(filename, 'w', encoding = 'utf-8-sig') as file: file.write(format_code(code)) def all_effects(): return f""" {select_all_effects()} {clear_all_settings_effect()} {copy_all_settings_effect()} {migrate_all_settings_effect()} """...
The main task of the code is to generate and write scripted effects, triggers, GUIs, and GUI templates to specified file paths in a structured directory hierarchy, likely for a game or application configuration system.
def generate_settings(): write_code(all_effects(), './common/scripted_effects/newsfeed_generated.txt') write_code(all_triggers(), './common/scripted_triggers/newsfeed_generated.txt') write_code(all_scripted_guis(), './common/scripted_guis/newsfeed_generated.txt') write_code(gui_template(), './gui/newsfe...
def is_valid_row(self, row, guess): answer_between_one_and_nine(guess) for box in self.get_row(row): if box.answer == guess: return False return True def is_valid_nonnet(self, row, column, answer): sub_x = 1 + math.ceil(row / 3) * 3 sub_y = 1 + math.ce...
The function checks if a guessed number in a Sudoku puzzle is valid by verifying it against the row, column, and nonet (3x3 subgrid) constraints. It combines three validation checks using bitwise AND to ensure the guess is unique in its row, column, and nonet.
def is_valid_number(self, row, column, guess): return self.is_valid_row(row, guess) & self.is_valid_nonnet(row, column, guess) & self.is_valid_column(column, guess)
def find_emptyspot(self): for row in self.board: for box in row: if box.is_empty(): return box return None def add_answer(self, row, column, number): if self.is_valid_number(row, column, number): return self.get_sudoku_box(row, column)....
This code implements a backtracking algorithm to solve a Sudoku puzzle. It recursively fills empty cells with numbers 1-9, checking validity, and backtracking when a number leads to a dead end. The function returns True if a solution is found, False otherwise.
def solve(self): box = self.find_emptyspot() if box is None: return True else: for i in range(1, 10): if self.add_answer(number=i, column=box.column, row=box.row): if self.solve(): return True box...
def compute_edges(weights) : edges = [] for i in range(len(weights)) : for j in range(i) : if weights[i][j] != 0 : edges.append((i, j)) return edges def get_cuthill_mckee(weights) : graph = csr_matrix(weights) order = reverse_cuthill_mckee(graph) permutation =...
This function computes the optimal permutation of a graph's nodes to minimize bandwidth using Gurobi's integer programming. It defines variables for permutations, absolute differences, and constraints to enforce valid permutations. Depending on the 'deltas' parameter, it uses either binary variables for differences or ...
def best_permutation_gurobi(weights, deltas=True, paramfile=None) : n = len(weights) n = len(weights) edges = compute_edges(weights) initial_solution = get_cuthill_mckee(weights) lower_bound = compute_lower_bound(weights) model = grb.Model() if deltas : delta = {(i, j): mod...
def compute_edges(weights) : edges = [] for i in range(len(weights)) : for j in range(i) : if weights[i][j] != 0 : edges.append((i, j)) return edges def get_cuthill_mckee(weights) : graph = csr_matrix(weights) order = reverse_cuthill_mckee(graph) permutation =...
This code uses Gurobi to solve a graph layout optimization problem, minimizing the sum of absolute differences between connected nodes in a permutation. It initializes with the Cuthill-McKee ordering, defines binary and integer variables for permutation differences, enforces constraints to model absolute values, and ap...
def gurobi_tuning(weights, writefile, limit_time=600) : n = len(weights) n = len(weights) edges = compute_edges(weights) initial_solution = get_cuthill_mckee(weights) lower_bound = compute_lower_bound(weights) model = grb.Model() delta = {(i, j): model.addVar(vtype=grb.GRB.BINARY, ...
def similarity_measure(spectrogram, permutation, norm=1) : """returns a similarity measure for the spectrogram with a given permutation which is the sum of similarities between each pair of neighboring columns""" return sum([get_similarity(spectrogram, permutation[ind], permutation[ind+1], norm) for ind in rang...
The code evaluates multiple algorithms on identical graphs by comparing their average bandwidth improvements against a random permutation and the McAllister method. It generates graphs, computes bandwidths, tracks performance metrics, and visualizes distributions of bandwidth and similarity measures if plotting is enab...
def test_algorithms_on_same_graphs(algorithms, nb_repartitions=1, nb_of_nodes=90, nb_of_test=10, plot_densities=True) : """returns the average bandwith improvements compared to mc_allister and a random permutation, by generating nb_of_tests graphs algorithms is a list of algorithms to test these algorit...
def compute_degrees(weights) : edges = compute_edges(weights) degrees = [0 for i in range(len(weights))] for edge in edges : degrees[fst(edge)] += 1 degrees[snd(edge)] += 1 return degrees def mc_allister(weights, first='random', print_time=False) : t0 = time() n = len(weights) ...
The function determines the optimal node(s) for the McAllister algorithm based on the 'research' parameter, computes labelings for each candidate node, and returns the labeling with the minimum bandwidth sum. It supports three modes: 'complete' (all nodes), 'partial' (nodes with minimum degree), or a specified number o...
def best_mc_allister(weights, research='complete') : n = len(weights) best_sum = 10000000000000 if research == 'complete' : research_set = [i for i in range(n)] elif research == 'partial' : degrees = compute_degrees(weights) min_degree = min(degrees) research_set = [] ...
def bandwidth_sum(permutation, weights) : bandwidth = 0 for i in range(len(weights)) : for j in range(i) : if weights[i][j] != 0 : bandwidth += abs(permutation[i] - permutation[j]) return bandwidth def median_improvement(weights, solution) : n = len(weights) neigh...
The code iteratively applies a "median_improvement" algorithm to optimize a solution based on given weights, tracking the best solution found. It uses a hash table to avoid revisiting solutions and stops based on a specified criterion (e.g., improvement, repetition, or iteration count). The loop continues until the sto...
def median_improvement_while_benefitial(weights, solution, stop_criterion='local_improvement') : old_solution = cp.deepcopy(solution) old_solution_score = bandwidth_sum(old_solution, weights) best_solution, best_score = cp.deepcopy(old_solution), old_solution_score new_solution = median_improvement(weig...
def disable_solving(self): self.btn_solve_BFS.configure(state=DISABLED) self.btn_solve_GBS.configure(state=DISABLED) def add_text_widget(self, text_widget : tk.Text, pos, value, rewrite_or_change=True): text_widget.configure(state=NORMAL) # Change state to enable editing if rewrite_or_ch...
The main task of the code is to execute a map-solving algorithm using the provided solver function, update the UI with the solution path, log the solving process (including solver type and timeout status), and manage button states to prevent user interaction during solving. It handles both successful solutions and "Not...
def solve_map(self, solver_func): if self.map_idx is None: return self.btn_show.configure(state=DISABLED) # Disable show button when playing self.disable_solving() # Disable solving function solution, log = solver_func(os.path.join("map", self.map_name + ".txt"), self.max_tim...
def conv(self,shape,act=tf.nn.relu,pool=True,dropout=False,norm=True,name=None): # True why dropout bad in tensorflow?? with tf.name_scope('conv'): print("input shape ",self.last_shape) print("conv shape ",shape) width=shape[-1] filters=tf.Variable(tf.random_normal(shape), name="filters") # filters ...
This function constructs a DenseNet convolutional neural network with multiple dense blocks and transition layers. It validates input depth format, initializes channels/growth rate, adds initial convolution, iteratively builds dense layers with growth, applies transitions, and concludes with batch normalization, ReLU a...
def buildDenseConv(self): depth = 3 * 1 + 4 if (depth - 4) % 3 : raise Exception("Depth must be 3N + 4! (4,7,10,...) ") # # layers in each denseblock N = (depth - 4) / 3 dropRate = None # nil to disable dropout, non - zero number to enable dropout and set drop rate # # channels before entering the first de...
def print_board(board): print(" | |") print(" {} | {} | {}".format(board[0], board[1], board[2])) print("___|___|___") print(" | |") print(" {} | {} | {}".format(board[3], board[4], board[5])) print("___|___|___") print(" | |") print(" {} | {} | {}".format(board[6], board[7],...
The code implements a tic-tac-toe game on a 3x3 grid of sub-boards. It initializes game boards, alternates between players 'X' and 'O', captures moves, checks for a win condition, and displays the board state. The game continues until a player wins, at which point the winner is announced and the function exits.
def play_game(): big_board = [' '] * 9 board_num_1 = [' '] * 9 board_num_2 = [' '] * 9 board_num_3 = [' '] * 9 board_num_4 = [' '] * 9 board_num_5 = [' '] * 9 board_num_6 = [' '] * 9 board_num_7 = [' '] * 9 board_num_8 = [' '] * 9 board_num_9 = [' '] * 9 player = 'X' whil...
def print_board(board_num_1, board_num_2, board_num_3, board_num_4, board_num_5, board_num_6, board_num_7, board_num_8, board_num_9): print(" ") print(" | | | | | | | | ") print(" {} | {} | {} | {} | {} | {} | {} | {} | {} ".format(board_num_1[0], board_num_1[1], board_nu...
The code defines a function to play a game, likely a tic-tac-toe variant with multiple boards. It initializes boards, alternates between players ('X' and 'O'), processes moves, checks for a win condition, and prints the game state. The main task is to manage the game loop, handle player turns, update the board, and det...
def play_game(): big_board, board_num_1, board_num_2, board_num_3, board_num_4, board_num_5, board_num_6, board_num_7, board_num_8, board_num_9 = ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9), ([' '] * 9) player = 'O' print_board(board_nu...
def _get_node(self, key, create=False): """Returns node for given key. Creates it if requested. Args: key: A key to look for. create: Whether to create the node if it does not exist. Returns: ``(node, trace)`` tuple where ``node`` is the node for given key ...
The `iteritems` method yields key-value pairs from a trie, optionally filtered by a `prefix` and controlled by the `shallow` parameter. It traverses nodes with values, returning them in topological order (siblings' order unspecified unless sorting is enabled). With `prefix`, it limits iteration to a subtrie. When `shal...
def iteritems(self, prefix=_SENTINEL, shallow=False): """Yields all nodes with associated values with given prefix. Only nodes with values are output. For example:: >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar/baz'...
def _slice_maybe(key_or_slice): """Checks whether argument is a slice or a plain key. Args: key_or_slice: A key or a slice to test. Returns: ``(key, is_slice)`` tuple. ``is_slice`` indicates whether ``key_or_slice`` is a slice and ``key`` is either ``key_or...
This method deletes a value associated with a given key or removes a subtrie if a slice is provided. It raises KeyError or ShortKeyError if the key is invalid or has no value, and clears the subtrie's children if a slice is used. The function distinguishes between key and slice inputs, ensuring proper deletion while ha...
def __delitem__(self, key_or_slice): """Deletes value associated with given key or raises KeyError. If argument is a key, value associated with it is deleted. If the key is also a prefix, its descendents are not affected. On the other hand, if the argument is a slice (in which case it...
def _slice_maybe(key_or_slice): """Checks whether argument is a slice or a plain key. Args: key_or_slice: A key or a slice to test. Returns: ``(key, is_slice)`` tuple. ``is_slice`` indicates whether ``key_or_slice`` is a slice and ``key`` is either ``key_or...
This method retrieves a value associated with a key in a trie or returns a generator of values from a subtrie when a slice is provided. It raises KeyError or ShortKeyError if the key is invalid or incomplete, and handles slices by invoking itervalues with the slice's start prefix.
def __getitem__(self, key_or_slice): """Returns value associated with given key or raises KeyError. When argument is a single key, value for that key is returned (or :class:`KeyError` exception is thrown if the node does not exist or has no value associated with it). When argum...
def get_solution_time_info(): '''Get info on solution times. Doesn't actually produce a plot but prints info to screen.''' experiments = { 'example': { 'has_benchmark': False, 'num_years_base': 30, 'agg_num_days_list': [120], 'NUM_SIMULATIONS': 40 # In c...
The main task of the code is to retrieve solution time information, generate an example plot, and create evaluation plots, likely for analyzing performance or visualizing data results in a structured workflow.
def main(): get_solution_time_info() make_example_plot() make_evaluation_plots()
def isGoal(block): x = block.x y = block.y rot = block.rot board = block.board if rot == "STANDING" and \ board[y][x] == 9: return True else: return False def printSuccessRoad(block): print("\nHere is the final Success path:") print("=======================...
This code implements a depth-first search (DFS) algorithm to solve a puzzle represented by a block. It explores possible moves (up, right, down, left) and split moves, tracking virtual steps. If a goal state is reached, it prints the solution path and step count, returning True. Otherwise, it continues until all possib...
def DFS(block): board = block.board Stack = [] Stack.append(block) passState.append(block) virtualStep = 0 print ("Stack length is :", len(Stack)) while Stack: current = Stack.pop() # current.disPlayPosition() # current.disPlayBoard() if isGoal(current)...
def load_config( self, dict_config=dict(), ): if dict_config: self.config = dict_config else: self.config = { "gpg_binary": os.environ.get("PASSBOLT_GPG_BINARY", "gpg"), "gpg_library": os.environ.get("PASSBOLT_GPG_LIBRARY", "PG...
This code initializes a class to interact with an API by loading configuration settings, setting up GPG encryption (via gnupg or PGPy), defining API endpoints, initializing an HTTP session, and authenticating via the login method. It prepares resources for user, group, and resource type management.
def __init__( self, dict_config=dict(), ): self.load_config( dict_config=dict_config, ) # Load key if self.config.get("gpg_library", "PGPy") == "gnupg": self.gpg = gnupg.GPG(gpgbinary=self.config.get("gpgbinary", "gpg")) self.fing...
def go_up(self): if self.snake.direction != "down": self.snake.direction = "up" def go_right(self): if self.snake.direction != "left": self.snake.direction = "right" def go_down(self): if self.snake.direction != "up": self.snake.direction = "down" def go_left(...
The code's main task is to execute a given action (up, right, down, left), update the environment, run the game, and return the new state, reward, and completion status. It processes input actions, modifies the environment accordingly, and provides feedback for reinforcement learning or simulation tasks.
def step(self, action): if action == 0: self.go_up() if action == 1: self.go_right() if action == 2: self.go_down() if action == 3: self.go_left() self.run_game() state = self.get_state() return state, self.reward, s...
def __forward_propagate(self, sample): # prefix 1 to simplify weighted sum with bias unit inputs = np.hstack(([1], sample[:])) for layer in self.network: outputs = [] for neuron in layer: neuron['output'] = self.__activate(np.dot(neuron['weights'], inputs...
This code trains a multi-layer perceptron (MLP) using gradient descent, iterating through epochs to minimize training error while monitoring validation and testing errors. It updates weights via backpropagation, stops when validation error stabilizes or epochs exceed the limit, and visualizes error trends across traini...
def train(self, learning_rate=9e-2, n_epochs=1000, batch_size=-1): epoch = 0 training_error_history = [] validation_error = float('inf') validation_error_history = [] testing_error_history = [] stopping_condition_met = False while not stopping_condition_met: ...