dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def fileExists(self, oc, filepath): try: oc.file_info(filepath) return True except Exception as e: if str(e)[-3:] == "404": return False def isFolder(self, filepath): oc = self.oc return oc.file_info(filepath).is_dir(), oc.file_info(fil...
This function removes a shared file/folder for a specified user, checking if the file exists, if it's shared to the user, and if duplicates exist. It deletes shares, removes files/folders when no longer shared, and cleans up empty directories. It returns success or failure reasons based on existence, sharing status, an...
def removeShare(self, username, userpasswrd, filepath): if self.fileExists(self.oc, filepath): oc = self.oc bool0, p = self.isFolder(filepath) bool1, duplicateFileList1, userList1 = self.checkDuplicateExist(filepath) duplicateFileList = self.column(duplicateFileLi...
def fileExists(self, oc, filepath): try: oc.file_info(filepath) return True except Exception as e: if str(e)[-3:] == "404": return False def dirPathList(self, filepath): k = [] l = filepath if l.rfind('/') == (len(l)-1): ...
This function removes a specified file or folder by checking its existence, handling duplicates, and deleting associated paths. It processes directory structures, removes empty directories, and manages user-specific deletions. If duplicates exist, it ensures proper cleanup. The task involves securely removing files whi...
def removeFileAdmin(self, filepath): if self.fileExists(self.oc, filepath): oc = self.oc list1 = self.dirPathList(filepath)[1] list0 = list1 list1.reverse() list2 = [] list3 = [] ogDirectory = '/' if self.checkDuplic...
def fileExists(self, oc, filepath): try: oc.file_info(filepath) return True except Exception as e: if str(e)[-3:] == "404": return False def isFolder(self, filepath): oc = self.oc return oc.file_info(filepath).is_dir(), oc.file_info(fil...
The code modifies a file's contents in a cloud storage system, updating duplicate files if they exist. It checks if the path exists and is a file, converts content to bytes, writes it to the primary file, and synchronizes duplicates. Returns success messages or errors for non-existent paths/folders.
def modifyFile(self, filepath, filecontents): if self.fileExists(self.oc, filepath): oc = self.oc bool1, p = self.isFolder(filepath) if bool1: return {'message': 'Given Path is a Folder and not a file'} else: str1 = filecontents ...
def ocUser(self, username, userpasswrd): ocu = owncloud.Client('http://34.123.27.121/') ocu.login(username, userpasswrd) return ocu def fileExists(self, oc, filepath): try: oc.file_info(filepath) return True except Exception as e: if str(e)[-3:...
The main task of the code is to share a file or folder via an OC (object cloud) system, checking if it already exists in the user's space. If not, it verifies the file's existence in the main OC, handles duplication by copying and renaming if needed, and shares the file while adhering to a duplicate threshold. It retur...
def shareFile(self, username, userpasswrd, filepath): ocu = self.ocUser(username, userpasswrd) if self.fileExists(ocu,filepath): return {'message': 'File already shared'} else: if self.fileExists(self.oc, filepath): oc = self.oc _, p = ...
def mp_based_tagging_algorithm(name_position, pf_dict, spe_tax, short_distance_dict, pf_id, pos_tax, gain_pf_str_list, loss_pf_str_list, never_pf_str_list, if_transfer_network, transfer_network_output, domain, itol_branch_symbol): mid_node_tag = dict() # tag count_0 = 0 count_1 = 0 for leaf_node in ...
The function performs domain-based clustering and evolutionary event detection using the MP method. It processes gain/loss/never domain events, generates iToL/Sankey visualizations for single domains, and analyzes multiple domain combinations. Outputs include JSON data, event frequency statistics, and annotated tree fi...
def clustering_and_detection(method, name_position, pf_dict, spe_tax, short_distance_dict, pos_tax, domain, json_gain, json_loss, json_never, if_transfer_network, if_itol_sankey, if_number, if_combination, transfer_network_output, itol_output, sankey_output, number_output, domain_combination_output, itol_node, itol_bra...
def handle_login(self, c, address): con = sqlite3.connect("clientdata.db") cur = con.cursor() c.send("Username: ".encode()) username = c.recv(1024).decode() c.send("Password: ".encode()) password = c.recv(1024).decode() password = hashlib.sha256(password.encode())...
This code handles client requests by processing commands like CONNECT, SIGNIN, SIGNUP, and ASK. It sends responses, authenticates users, and manages file operations (publishing/discovering files) via JSON data. The server listens for messages, validates actions, and interacts with clients based on received commands, en...
def handle_client(self, connection, address): try: while True: mess = connection.recv(1024).decode() if not mess: break print(mess) if mess == "CONNECT": connection.send("RESPONSE 200".encode()) ...
def _student_loss(self, student_output, labels): if self.distillation_token: return self.student_loss_fn(student_output.cls_logits, labels) else: return student_output.loss def _print_layer_shapes(self, teacher_output, student_output): if not self.printed: ...
The code computes the total loss for a student model during knowledge distillation. It calculates the student's loss against labels, the distillation loss comparing student and teacher model outputs, and optionally adds attention, hidden state, attribution, or ATS losses. The final loss combines these components with w...
def compute_loss(self, student, inputs, return_outputs=False): for k, v in inputs.items(): inputs[k] = v.to(get_device()) student_inputs = inputs if self.distillation_token: student_inputs = {'pixel_values': inputs['pixel_values']} kwargs = {} s_kwargs...
def init_functions(directory, country, lineage_column='pangolin_lineage', division_column='division', date_column='date', variant_column='variant', id_column='gisaid_epi_isl', with_phrase='metadata', without_phrase='aggregated', meta_cols=['strain', 'gisaid_epi_isl', 'date', 'regio...
The main task of the code is to process epidemiological data for Southeast Asian countries by generating area charts of divisions, cleaning output directories, and combining aggregated results into unified files. It iterates through each country to initialize data, create visualizations, and consolidate outputs, exclud...
def main(countries=['Brunei', 'Cambodia', 'Indonesia', 'Laos', 'Malaysia', 'Myanmar', 'Philippines', 'Singapore', 'Thailand', 'Timor-Leste', 'Vietnam']): for country in countries: print(country) shutil.rmtree(f'output/11_regions/{country}', ignore_errors=True) ...
def get_style_string(sld_file): style_string = _execute_xslt("style", os.path.join(sld_file)) return style_string def get_symbol_string(sld_file): symbol_string = _execute_xslt("symbol", os.path.join(sld_file)) return symbol_string def _get_output_filepath(sld_file, output_dir, ext): basenamepath = ...
This function converts an SLD file into two output files: a style file (".style") and a symbol file (".symbol"), saving them in the specified output directory. It extracts style and symbol definitions from the SLD, handles errors silently or with messages, and writes the extracted content to respective files while prov...
def _convert_sld_cli(sld_file, output_dir, silent=True): try: style_string = get_style_string(sld_file) symbol_string = get_symbol_string(sld_file) except Exception as e: if not silent: print("error occured during transforming sld: " + str(e)) exit(1) rais...
def update_interface(self): """ Called by handle_guess method to update the interface and show the user where they are in the game. Also checks if there are any unfilled spots in the display, meaning the user has won, or if the user is out of guesses, meaning they lost. """ ...
The `runGame` method updates the game interface and repeatedly prompts the user for guesses until the maximum allowed attempts are reached or the game concludes. It uses a loop to manage guesses, checking if the attempt count is under the limit and the game status is unresolved. Upon loop exit, it triggers the `endGame...
def runGame(self): """ Updates interface and tells the game to continue prompting responses until the game ends. """ self.update_interface() while( self.wrong < self.guess_limit and self.status == None): self.prompt_guess() self.endGame(self.status)
def update_interface(self, display): """ Called by handle_guess method to update the interface and show the user where they are in the game. Also checks if there are any unfilled spots in the display, meaning the user has won, or if the user is out of guesses, meaning they lost. ...
The main task of the code is to run the game loop by updating the interface, repeatedly prompting the user for guesses until the guess limit is reached or the game status is determined (win/lose), then triggering the end-game logic based on the final status.
def runGame(self): """ Updates interface and tells the game to continue prompting responses until requirements are met to end the game (win or lose) """ self.update_interface(self.display) while( self.wrong < self.guess_limit and self.status == None): self.p...
def prompt_difficulty(self): """ Prompts user for difficulty and sets the cleaned variable to the instance variable """ diff = input("Select your difficulty (easy, medium, hard): ") self.diff = self.clean_input(diff) def set_up_word(self): """ Instructs data layer...
The main task of the code is to orchestrate a game's execution by sequentially prompting for difficulty, setting up the game word, and running the game logic. It integrates controller methods to ensure the game completes from initialization to conclusion, managing user input and game state transitions.
def entire_game(self): """ Pulls together the controlller methods needed to run a game to completion. """ self.prompt_difficulty() self.set_up_word() self.runGame()
def set_up_word(self): """ Instructs data layer to pull the word list. Sets up a display of the required length. """ self.available_words.get_wordlist() word_length = self.available_words.get_random_word() self.display = "".join( ["_" for char in range(word_leng...
The main task of the code is to orchestrate a complete game by sequentially initializing the target word, prompting the user for the number of allowed guesses, and executing the game loop to handle guesses and determine the outcome.
def entire_game(self): """ Pulls together the controlller methods needed to run a game to completion. """ self.set_up_word() self.prompt_num_guesses() self.runGame()
def inst_path_rule(self, path): for n in range(1, len(path) - 1): node, out_port = path[n] datapath = self.dpids[node] parser = datapath.ofproto_parser match = parser.OFPMatch(eth_dst=path[-1], eth_src=path[0]) actions = [parser.OFPActionOutput(out_p...
This code handles packet-in events in a SDN controller, determining forwarding paths using a network graph. It processes Ethernet/ARP packets, resolves unknown destinations via ARP, retrieves available paths, installs flow rules for two paths, selects one based on a counter, forwards packets, and periodically deletes t...
def _packet_in_handler(self, ev): print(self.c) msg = ev.msg datapath = msg.datapath dpid = datapath.id ofproto = datapath.ofproto parser = datapath.ofproto_parser in_port = msg.match['in_port'] pkt = packet.Packet(msg.data) eth = pkt.get...
def get_query_contents(self): """ Reads and returns the file contents from the original upload """ # get the app base dir BASE_DIR = Path(__file__).resolve().parent.parent file_path = f"{BASE_DIR}/uploads/{str(self.file)}" return open(file_path, "r").re...
This function processes an uploaded file to determine if it is a Hidden Markov Model (HMM), Multiple Sequence Alignment (MSA), or another format. It stores the HMM profile if applicable, identifies the file type, sets the upload type, and initializes model parameters based on the HMM data. The process involves analyzin...
def init_params_from_hmm(self): """ Analyse the file uploaded to determine if it is a HMM, MSA or something else; also returns the HMM profile """ # get the uploaded file contents file_content = self.get_query_contents() # convert processing to alignment ...
def open_db(db_folder, create_if_not_exist=True): if not db_exists(db_folder) and not create_if_not_exist: raise ValueError(f'Database at {db_folder} does not yet exist and open_db has been told not to create a database if it does not exit yet. Erroring out') os.makedirs(db_folder, exist_ok=True) l...
This function loads configuration and data associated with a specific config_id from a ZODB database. It opens the database if no existing connection exists, retrieves config and data using zodb_op_load with distinct keys, and closes the connection if newly opened. The main task is to fetch and return config and data e...
def load_data_config_from_id(config_id, db_folder): global zodb_connection if zodb_connection is None: db, connection, root, lock = open_db(db_folder, create_if_not_exist=False) else: db, connection, root, lock = zodb_connection config = zodb_op_load(root, config_id, DB_CONFIGS_KEY) ...
def average_poses(poses): """ Calculate the average pose, which is then used to center all poses using @center_poses. Its computation is as follows: 1. Compute the center: the average of pose centers. 2. Compute the z axis: the normalized average z axis. 3. Compute axis y': the average y axis. ...
The function generates a spiral trajectory of camera poses for NeRF validation by averaging input poses, calculating focus depth, determining spiral radii, and creating a spiral path around the average pose with specified parameters.
def get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120): """ Generate a set of poses using NeRF's spiral camera trajectory as validation poses. """ # center pose c2w = average_poses(c2ws_all) # Get average pose up = normalize(c2ws_all[:, :3, 1].sum(0)) # Find a reasonable "foc...
def center_poses(poses, blender2opencv): """ Center the poses so that we can use NDC. See https://github.com/bmild/nerf/issues/34 Inputs: poses: (N_images, 3, 4) Outputs: poses_centered: (N_images, 3, 4) the centered poses pose_avg: (3, 4) the average pose """ poses =...
The main task of the code is to load and preprocess camera metadata and video data for a neural rendering task. It processes camera poses, rescales focal lengths, generates ray directions, and prepares training/validation data (RGB images, rays, and time steps) by loading video frames, stacking tensors, and handling me...
def load_meta(self): """ Load meta data from the dataset. """ # Read poses and video file paths. poses_arr = np.load(os.path.join(self.root_dir, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5) self.near_fars = poses_arr[:, -2:]...
def display_board(): print(board[0]+" | "+ board[1]+" | "+ board[2]) print(board[3]+" | "+ board[4]+" | "+ board[5]) print(board[6]+" | "+ board[7]+" | "+ board[8]) def handle_turn(player): print(player+"'s Turn.") position=input("Choose a position from 1-9: ") valid=False while not valid:...
This code defines a function to play a game, handling player turns, checking game status, and determining the winner or tie. It displays the board, alternates players, checks for win/tie conditions, and prints the result once the game ends.
def play_game(): display_board() # when game is going while game_still_going: # handle the turn of player handle_turn(current_player) #check if the game has ended check_if_game_over() #Flip to other player flip_player() # the game has ...
def display_board(): print(board[0]+" | "+ board[1]+" | "+ board[2]) print(board[3]+" | "+ board[4]+" | "+ board[5]) print(board[6]+" | "+ board[7]+" | "+ board[8]) def handle_turn(player): global human_player if player==human_player: print(player+"'s Turn.") # enter only if current...
This function plays a game where players take turns making moves on a board. It handles each player's turn, checks for a win or tie condition after each move, and alternates turns until the game ends. Finally, it announces the winner or declares a tie if no winner is found.
def play_game(): display_board() # when game is going while game_still_going: # handle the turn of player (who ever's turn has to be played) handle_turn(current_player) #check if the game has ended check_if_game_over() #Flip to other player ...
def loadAllData(filesDir, allInstances, trainingSet, testSet, split, classList): # get all class filename filesList = [f for f in listdir(filesDir) if isfile(join(filesDir, f))] # for every file for file in filesList: # load it dataSet = loadData(filesDir+file) # split its instances into training and test on...
The code implements a K-Nearest Neighbors (KNN) classification algorithm with a 67:33 train-test split and k=1. It initializes data structures, loads and splits dataset, computes classification accuracy across multiple loops, tracks incorrect predictions, and generates a confusion matrix. The average accuracy is calcul...
def main(): # initiate all data needed confusionMatrix = {} incorrectGuess = [] allInstances=[] predictions=[] trainingSet=[] classList=[] testSet=[] # setup the split to 67:33 and k to 1 split = 0.67 k = 1 # setup the number of times the algorithm will loop and the average accuracy loopTimes = 1 averag...
def __is_root(self): root_config_docs_dir = self.__get_root_docs_dir() abs_root_config_file_dir = self.__get_root_config_file_path() abs_root_config_docs_dir = path.join(abs_root_config_file_dir, root_config_docs_dir) return path.realpath(abs_root_config_docs_dir) in self.page.file.abs_src_path def __h...
The code generates an edit URL for a page. If it's the root page, it returns the direct edit URL. If the page has a repository, it combines the repository URL, edit URI from config, and the page's source path to form the edit link. Otherwise, it returns None.
def build(self): if self.__is_root(): return self.page.edit_url if self.__has_repo(): config = self.__get_page_config_file_yaml() return config['repo_url'] + config['edit_uri'] + self.__get_page_src_path() return None
def prepare_SFA(self): """ Generates info needed per SFA stream. """ self.SFA_chunk_size = [] self.base_interval_per_SFA_chunk = [] framerate = 29.97 # I just noticed that audio framerate is not based off the video input, in fact, it seems to be locked at 29.97 if self.au...
The main task of the code is to build a USM (Uncompressed Speech Model) data structure in memory by preparing audio-specific components (SFA and SFV) and ensuring data integrity. It raises an error if the USM is unsupported, prioritizes in-memory storage over disk to handle potential failures, and returns the construct...
def build(self) -> bytes: if not self.ivfObj: raise NotImplementedError("Loaded USM is not supported yet.") # saved with get_usm() if self.audio: self.prepare_SFA() self.prepare_SFV() # This will be a hit to performance, but I will store the building USM on memor...
def write_header(self, keyless: bool = False) -> bytearray: if self.encrypted: mask = 0x7F7F7F7F self.hca["CipherType"] = 0 else: mask = 0xFFFFFFFF if keyless: mask = 0x7F7F7F7F self.hca["CipherType"] = 1 else: ...
This function encrypts an HCA file using a provided keycode by applying an encryption table to each frame, appending CRC16 checksums, and updating the file stream. It validates the file type, ensures it's unencrypted, and constructs a new encrypted byte stream. If 'keyless' is True, encryption is bypassed. The process ...
def encrypt(self, keycode: int, keyless: bool = False) -> None: """ Encrypts an HCA file with the given keycode, if they encryption is set to keyless, the keycode will be ignored. """ # This will encrypt the HCA file with the given keycode. if not (self.filetype == "hca" or (self.hcabytes and se...
def write_header(self, keyless: bool = False) -> bytearray: if self.encrypted: mask = 0x7F7F7F7F self.hca["CipherType"] = 0 else: mask = 0xFFFFFFFF if keyless: mask = 0x7F7F7F7F self.hca["CipherType"] = 1 else: ...
This function decrypts an HCA file using a provided key by decrypting each frame through a generated lookup table, recalculating CRC checksums for each frame, and reconstructing the decrypted data stream while updating the file's internal state to mark it as unencrypted.
def decrypt(self) -> None: """ Decrypts an HCA file with the provided key in initialization. """ # This will use the init HCA values to decrypt. if not (self.filetype == "hca" or (self.hcabytes and self.hcastream)): raise ValueError("Decrypt function is only used for HCA files.") ...
def Pyparse_header(self) -> None: self.HcaSig, self.version, self.header_size = HcaHeaderStruct.unpack( self.hcastream.read(HcaHeaderStruct.size) ) if self.HcaSig in [HCAType.HCA.value, HCAType.EHCA.value]: if not self.hcabytes: self.filetype = "hca" ...
This function encodes a WAV file into HCA format, handling input validation, looping control, encryption with optional key specification, and returns the encoded HCA data as bytes. It checks for valid input type, sets looping flags, performs encoding, parses headers, applies encryption if requested, and outputs the res...
def encode(self, force_not_looping: bool = False, encrypt: bool = False, keyless: bool = False) -> bytes: if self.filetype == "hca": raise ValueError("Input type for encoding must be a WAV file.") if force_not_looping == False: force_not_looping = 0 elif force_not_looping...
def flatten_sequences(expr): """Flatten lists marked as sequences, i.e., of the form ``[:seq, ...]``. ``[:seq, ...]`` expressions are not allowed to contain such expressions as sequence elements (i.e., these would not be flattened. It would be easy to allow them, but for the pattern transductions here no such ...
This function recursively fills a template structure using `match_result` by processing atoms, lists, position indices, and special functions. It replaces template elements with corresponding values from `match_result`, applies predefined functions, and combines results into a flattened structure.
def fill_template_rec(template, match_result): nonlocal preds if template == 0 or template == '0': return flatten_sequences(match_result) ii = position_index(template) if ii or ii == 0: return flatten_sequences(indexed_element_of(match_result, ii)) if atom(template): return templa...
def reconnect(self): self.odrive = self.get_odrive() self.flywheel = self.odrive.axis1 self.axle = self.odrive.axis0 def configure(self): print("Erasing old configuration") try: self.odrive.erase_configuration() except ObjectLostError: pass ...
The code defines an initializer method that sets up an object by reconnecting, configuring, and calibrating it, with calibration enabled by default. The main task is to initialize the object's state through these three setup processes, ensuring proper connection, configuration, and calibration for operation.
def __init__(self, calibrate=True): self.reconnect() self.configure() self.calibrate()
def loadSourcePreset(source): if source=="stripe": for s in SourcesProperty(SourcesIngest, "static/sources.json").values: if s.name == "stripe": return s else: return "Source stripe: string incorrect" else: return "Source not found" def getData(source): if source=="stripe": if os.path.exists('sta...
This function configures a data source by checking if it's a preset. If so, it loads predefined settings, retrieves associated data, stores it in persistent memory, updates the session, generates header options for a form, and renders the index template with source/field forms. If not a preset, it logs a custom source ...
def configureSource(): sourceForm = SourceForm() fieldForm = FieldForm() source = request.args.get('source') if source in PRESETS: loadSource = loadSourcePreset(source) data = getData(loadSource.name).charges addToPersistentMem("data", data) session["source"] = source session.modified = True headers =ge...
def loadSourcePreset(source): if source=="stripe": for s in SourcesProperty(SourcesIngest, "static/sources.json").values: if s.name == "stripe": return s else: return "Source stripe: string incorrect" else: return "Source not found" def loadFieldPreset(source): path = "static/field_presets_"+source...
The code processes user-selected fields by retrieving data, matching them with predefined field presets, generating a CSV file, and rendering an HTML template with processed data and forms for data handling tasks like export and Salesforce integration.
def sendValuesFromInput(): sourceForm = SourceForm() fieldForm = FieldForm() downloadForm = DownloadForm() exportForm = ExportForm() salesforceForm = SalesforceForm() cadenceForm = CadenceForm() fieldList = [] fields = request.form.getlist("fields") data = PERSIST[session["data"]] source = loadSourcePreset(se...
def loadFromPersistentMem(key): val = PERSIST[session[key]] return val def loadSourcePreset(source): if source=="stripe": for s in SourcesProperty(SourcesIngest, "static/sources.json").values: if s.name == "stripe": return s else: return "Source stripe: string incorrect" else: return "Source not f...
The code generates a CSV file named 'balance_transactions_YYYYMMDD.csv' by retrieving user request data and a source preset, then returns it as a downloadable file with appropriate headers and MIME type.
def download(): name = "balance_transactions_"+DATE data = {"data": loadFromPersistentMem("userrequest")} source = loadSourcePreset(session["source"]) csv = makeCSV(data, source) addToPersistentMem("csv", csv) return Response(csv, mimetype="text/csv", headers={"Content-disposition":"attachment; filename="+name+"....
def loadFromPersistentMem(key): val = PERSIST[session[key]] return val def loadSourcePreset(source): if source=="stripe": for s in SourcesProperty(SourcesIngest, "static/sources.json").values: if s.name == "stripe": return s else: return "Source stripe: string incorrect" else: return "Source not f...
The main task of the code is to export user request data to a Google Sheet by generating a CSV file, uploading it to a specified Google Drive folder, and redirecting the user to the created spreadsheet. It retrieves data from persistent memory, formats it into CSV using a source preset, stores the CSV temporarily, uplo...
def export(): name = "balance_transactions_"+DATE loc = exp.create(name, DRIVE_EXPORT_FOLDER_ID) data = {"data": loadFromPersistentMem("userrequest")} source = loadSourcePreset(session["source"]) csv = makeCSV(data, source) addToPersistentMem("csv", csv) exp.import_csv(loc.id, csv) link = "https://docs.google.c...
def _session_handler(self, ControlMode="RemoteControl"): """ Handle the session to the USB camera device Args: - mode (str): The specific mode to use to open the session to the camera. This is used only for opening the session. Indeed for clos...
This method initializes a camera using a series of handshake steps and checks responses for success. It configures the camera with the specified ControlMode, verifies initialization status, retrieves camera properties, and determines if the camera is in 'Video' or 'Photo' mode based on exposure settings.
def initialize_camera(self, ControlMode="RemoteControl"): """Initialize the camera. The full handshake has been found using reverse engineering Args: - ControlMode (str): The specific mode to control the camera """ self._session_handler(ControlMode=ControlMode) ...
def get_camera_properties(self, file_props=None): """Ask the camera for all the properties Returns: - vals (str) : A decoded dictionary with all the properties """ if file_props is None: file_path = "sour/camera_database/" file_name = self.name.strip().l...
The main task of the code is to switch the camera's focus mode to manual and set the focus distance to infinity by adjusting the manual focus value. It retrieves current camera properties, checks if autofocus is enabled, disables it if so, calculates a target distance (100 - current value), and attempts to set the focu...
def _set_focus_infinity(self): self.get_camera_properties() if self.__focus_mode == "AF_S": self._set_focus_mode(mode="manual") current_distance = self.camera_properties["ManualFocusDistance"][ "CurrentValue" ] nstep = 100 - current_distance ...
def _set_focus_mode(self, mode="auto"): if mode == "manual": mode = "MF" elif mode == "auto": mode = "AF_S" params = { "Msg": { "Value": self._PROPCODES["Values"]["FocusMode"], "DataType": self._PROPCODES["DataType"], ...
This code handles camera control commands by parsing input messages, extracting commands and values, and invoking corresponding private methods like setting focus mode, shutter speed, or capturing images. It processes parameters, handles special cases (e.g., "infinity" or "further" for focus distance), and returns resu...
def messageHandler(self, msg): command = copy.copy(msg[0]) if len(msg) == 2: value = copy.copy(msg[1]) else: value = copy.copy(msg[1:]) cmd = command.strip().lower().replace(" ", "") if cmd == "focusmode": out = self._set_focus_mode(value) ...
def open_cell(self, i_cell, j_cell): if (i_cell < 0) or (j_cell < 0) or (i_cell >= self.height) or (j_cell >= self.width): return if self.user_map[i_cell][j_cell] != '#': return if self.bomb_map[i_cell][j_cell] == 1: self.game_over() self.user_map[i_ce...
The function `make_move` processes a player's action on a specified cell in a grid-based game. It validates the cell coordinates, executes the action ("Open" or "Flag"), and checks if the game has ended.
def make_move(self, i_cell, j_cell, action): if (i_cell < 0) or (j_cell < 0) or (i_cell >= self.height) or (j_cell >= self.width): return if action == "Open": self.open_cell(i_cell, j_cell) elif action == "Flag": self.flag_cell(i_cell, j_cell) self.che...
def parse_policy(csp): """ Return a dictionary of directives with a list of directive values for each directive discovered. Parameters ---------- csp : str The content security policy of interest. Returns ------- directives : dict A dictionary of directives wit...
The main task of the code is to validate a Content Security Policy (CSP) by parsing its directives and source lists, checking for errors in each component, and returning a dictionary indicating overall validity along with detailed error information for invalid directives.
def validate(csp): """ Main function to parse and validate the given Content Security Policy. Parameters ---------- csp : str The content security policy of interest. Returns ------- result : dict A dictionary with two keys ("valid", "errors"). The stru...
def generate_unconflicted_data_index_oc(q, beta_2=0.9): unconf, conf = thresholding(q, beta_2=beta_2) return unconf, conf def target_distribution(self, p,unconflicted_ind, conflicted_ind): ''' q[i] = p[i] if i belongs to the conflicted indexes q[i,argmax(p[i])] = 1 and q[i,j≠argmax(p[i])...
The code trains a hybrid clustering-GAN model by optimizing five loss functions: graph reconstruction, ZINB-based, KL-divergence, generator, and discriminator losses. It uses autoencoders, adversarial training, and clustering layers with weighted updates for graph reconstruction and overclustering, logging metrics like...
def alt_train(self, y, epochs=3000, lr_dis=0.0001, lr_gen=0.0001, lr_clus=5e-4, lr_overclus=5e-4, W_a=3, W_x=1, W_c=1.5, W_oc =0.5, info_step=8, n_update=8, centers=None, overcenters=None, save_path='./saving_path', save = False, threshold_2=0.7, threshold_3=0.3, beta_1=0.95, beta_2=0.95, beta_3=0.95, beta_4=0.95, old...
def get_ngram_with_prob(self, words=None): prob_dict, prob_dict_length = self.build_prob_dict(Ngram_Language_Model.FLAVOUR_GENERATE, words) rand = random.randint(0, prob_dict_length) for prob_limit, ngram_arr in prob_dict.items(): if rand <= prob_limit: return ngram_a...
This code generates text using an n-gram language model. It starts with provided context or initializes from scratch, iteratively appending probable n-grams until the output reaches the specified length `n`. It handles cases where initial context is insufficient by extending it with high-probability n-grams, ensuring t...
def generate(self, context=None, n=20): if context is None: result = self.get_ngram_with_prob() words_counter = self.n else: result = context words_counter = len(context.split(" ")) if words_counter < self.n: start_ngram = self.get_fir...
def split_string_to_grams(self, text): """ return an array of grams (words or chars)""" if self.chars: grams = [char for char in text] else: grams = text.split(" ") return grams def smooth(self, ngram): model_length = len(self.model) prob_dict, dic...
This code calculates the log probability of a text sequence using n-grams. It splits text into n-grams, computes their probabilities (with optional smoothing), multiplies them, and returns the log2 of the total. If any n-gram probability is zero, it recursively re-evaluates with smoothing to avoid zero results.
def evaluate(self, text, smooth=False): total_probability = 1 text_ngrams = [] words = self.split_string_to_grams(text) for i in range(0, len(words) - self.n + 1): text_ngrams.append(words[i: i + self.n]) for current_ngram in text_ngrams: if smooth: ...
def get_ngram_with_prob(self, words=None): # words: array prob_dict, prob_dict_length = self.build_prob_dict(words) rand = random.randint(0, prob_dict_length) for prob_limit, ngram_arr in prob_dict.items(): if rand <= prob_limit: return ngram_arr prob...
The code generates text by iteratively extending a given context with predicted n-grams. It starts with an initial context or generates from scratch, then appends the most probable next word(s) based on n-gram probabilities until the output reaches length `n`. The loop ensures the result grows incrementally by extracti...
def generate(self, context=None, n=20): if context is None: result = self.get_ngram_with_prob() words_counter = self.n else: result = context words_counter = len(context.split(" ")) while words_counter < n - 1: text_words = self.string...
def smooth(self, ngram): current_ngram_prefix = ngram[0:self.n - 1] model_length = len(self.model) prob_dict, dict_length = self.build_prob_dict(current_ngram_prefix) for appearances, dict_ngram in prob_dict.items(): if ngram == dict_ngram.split(): return (1 +...
This function computes the log probability of a given text sequence using n-gram language models. It splits text into words, extracts n-grams, and multiplies their probabilities. If smoothing is enabled, it applies smoothing; otherwise, it returns 0 for zero probabilities. The final result is the base-2 logarithm of th...
def evaluate(self, text, smooth=False): total_probability = 1 text_ngrams = [] words = text.split() for i in range(0, len(words) - self.n + 1): text_ngrams.append(words[i: i + self.n]) for current_ngram in text_ngrams: if smooth: total_pro...
def FTP(self) : #self.PATH = "./Config/vsftpd.conf" self.PATH = "/etc/vsftpd/vsftpd.conf" self.configuration = {11:"anonymous_enable=NO",113:"listen=YES",122:"listen_ipv6=NO"} self.RESTARTER() def doer(self): with open(self.PATH,"r") as config_file : self.config_list=config_file.readlines() ...
The code defines a method `CALLER` that checks the value of `self.service`. If the service is "vsftpd", it calls `self.FTP()` and `self.doer()`. If the service is "dhcpd", it invokes `self.DHCPD()`. The method's primary task is to route execution to specific service-handling functions based on the configured service ty...
def CALLER(self) : if self.service == "vsftpd" : self.FTP() self.doer() if self.service == "dhcpd" : self.DHCPD()
def init_configuration(self) : self.infromation(True) lol = [] with open("Config/samba/origin.conf","r") as file : lol = file.readlines() position = self.getPosition(lol,"hosts allow = ") joined = ".".join(self.allowedHost) lol[position[0]] = f"\t{lol[position[0]].strip()} {joined}. \n " ...
This code initializes a Samba configuration by setting parameters like file paths, user permissions, and network settings. It calls methods to configure the setup, add share entries, initialize network interfaces, and restart the SMB service to apply changes. The main task is automating Samba share configuration and se...
def __init__(self): self.smbPATH = "/etc/samba/smb.conf" # self.smbPATH = "Config/samba/smb.conf" self.folderName = "" self.theAdmin = "" self.validUsers = [] self.directoryMask = "" self.createMask = "" self.writable = "" self.path = "" self.allowedHost = ""...
def get_range_bounds(offset_x: Fraction, offset_y: Fraction, left: Ray, right: Ray, py: int, x_min: int, x_max: int): for line_start, line_end in _get_range_bounds(offset_x, offset_y, left, right, py, x_min, x_max): if line_start < line_end: yield line_start, line_end def get_range(offset_x: Fra...
The function renders a game tile's texture on the screen at calculated coordinates, adjusting for player position and rotation. It checks screen bounds, handles ray visibility, and applies textures using Pygame. If the tile is transparent, it recursively renders adjacent tiles in four directions with adjusted rotations...
def render_part(screen_settings: ScreenSettings, tile: TileRotation, x: int, y: int, left0: Ray, right0: Ray, rot: int = 0): x_on_screen = screen_settings.player_x + x y_on_screen = screen_settings.player_y + y if x or y: if not (0 <= x_on_screen < screen_settings.screen_x and 0 <= y_on_screen < scr...
def modInv(x,n): # Call the Extended Euclidean. arr = EEA(n, x) # Indicates that there is no solution. if arr[2] != 1: return 0 # Do the wrap around, if necessary. if arr[1] < 0: arr[1] += n # This is the modular inverse. return arr[1] def fastmodexpo(base,exp,mod): ...
The code performs RSA decryption by calculating the private key (d) using given primes p, q and public exponent e, then decrypting input ciphertext blocks with modular exponentiation and converting the resulting numbers back to plaintext strings.
def main(): # Get p, q, e. p = 221122112213 q = 123456790003 e = 7455573413522025488689 blocksize = 16 numBlocks = int(13) # Calculate n, phi(n). n = p*q phi = (p-1)*(q-1) d = modInv(e, phi) print("p =",p) print("q =",q) print("n =",n) print("e =",e) prin...
def modInv(x,n): # Call the Extended Euclidean. arr = EEA(n, x) # Indicates that there is no solution. if arr[2] != 1: return 0 # Do the wrap around, if necessary. if arr[1] < 0: arr[1] += n # This is the modular inverse. return arr[1] def fastmodexpo(base,exp,mod): ...
The code decrypts RSA-encrypted messages using a private key. It calculates RSA parameters (n, phi, d), reads ciphertext blocks, decrypts each with modular exponentiation, and converts numerical plaintext back to strings using a block size of 19.
def main(): # Get p, q. p = 36279836279899 q = 76214213232259 # Calculate n, phi(n). n = p*q phi = (p-1)*(q-1) e = 922535452715757606722838121 # d is always the modular inverse of e mod phi. d = modInv(e,phi) # Get number of blocks from file. (I'll pipe the file in as input.....
def get_extension(self): if self.filename: return self.filename.split('.')[-1] def get_period_label(self, period_label): if not period_label: return False elif period_label is True: period_label = {'size': 12} if self.orientation == 'h': ...
(The code initializes a visualization class by configuring parameters for data display, including orientation, sorting, bar properties, styling, and data preparation from a DataFrame. It sets up attributes for rendering charts with customizable options like colors, fonts, animation settings, and data filtering, prepari...
def __init__(self, df, filename, orientation, sort, n_bars, fixed_order, fixed_max, steps_per_period, period_length, interpolate_period, label_bars, bar_size, period_label, period_fmt, period_summary_func, perpendicular_bar_func, figsize, cmap, title, title_size, bar...
def get_model_files(model_name: str) -> List[Path]: """ List all model files that you want to load and convert # Args. model_name: name(like `bigscience/bloom`) or local directory of the model # Returns. List[Path] model file paths """ import glob from huggingface_hub import tr...
This function processes and converts model parameters from a pre-trained model into a specified format, saving them to a directory. It loads model files, converts parameter names, applies transformations (e.g., transposing), handles exceptions, and distributes the workload across multiple processes if specified. The co...
def process_by_model_param(model_id: str, dtype: torch.dtype, tp_size: int, save_dir: Path, nproc: int): """ Process conversion parameter by parameter. """ # init bloom config model_config = BloomConfig.from_pretrained(model_id) # list all model files model_files = get_model_files(model_id) ...
def get_model_files(model_name: str) -> List[Path]: """ List all model files that you want to load and convert # Args. model_name: name(like `bigscience/bloom`) or local directory of the model # Returns. List[Path] model file paths """ import glob from huggingface_hub import tr...
The main task of the code is to convert a large model into smaller shards using parallel processing. It initializes the model configuration, lists model files, and processes each shard either sequentially (if nproc=1) or in parallel (if nproc>1) using multiprocessing. The goal is to optimize conversion time and memory ...
def process_by_model_shard(model_id: str, dtype: torch.dtype, tp_size: int, save_dir: Path, nproc: int): """ Process conversion shard by shard. Benchmarks @ 64C(Intel Xeon 6326 2.90GH) x 756G: | model | format | by-shard | nproc | elapsed(s) | mem | |------------|--------------...
def get_args(): global _args if _args is not None: return _args parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-i', '--input-dir', type=str, metavar='DIR', required=True, help='A checkpoint directory of a h...
The code converts a Hugging Face checkpoint to FT format, either by model sharding or parameters, using specified tensor parallelism and data type. It creates a save directory, processes input files, and logs the conversion time.
def main(): start_time = time.time() args = get_args() tp_size = args.tensor_para_size dtype = DATATYPE_MAP[args.data_type] save_dir = Path(args.output_dir) / f'{tp_size}-gpu' save_dir.mkdir(exist_ok=True, parents=True) if args.by_shard: process_by_model_shard(args.input_dir, dtype...
def term_stringify(e: tn.Term) -> str: """ Pretty-print a tinyscript term Args: e (tn.Term): Term to print Returns: str: Pretty-printed term Raises: TypeError: Argument is not a valid tinyscript term """ match e: case tn.Const(val): ...
The function `stringify` converts a tinyscript program (`tn.Prog`) into a human-readable, indented string representation. It handles various program constructs (e.g., `skip`, assignments, sequences, conditionals, loops) by recursively formatting each node with appropriate syntax and indentation. The output mimics struc...
def stringify(alpha: tn.Prog, indent=0) -> str: """ Pretty-print a tinyscript program Args: alpha (tn.Prog): Program to print indent (int, optional): Starting indentation, defaults to `0` Returns: str: Pretty-printed program Raises: TypeError: If the ar...
def vars_term(e: tn.Term) -> list[tn.Var]: """ Collect the variables appearing in a term Args: e (tn.Term): Term to collect from Returns: list[tn.Var]: List of variables in argument Raises: TypeError: If the argument is not a valid tinyscript term """ match e: case tn.Const(val): return...
The function `vars_prog` collects all variables present in a given program (`tn.Prog`) by recursively examining its structure. It handles different program constructs (e.g., assignments, sequences, conditionals, loops) to aggregate variables from expressions, conditions, and sub-programs. It returns a list of unique va...
def vars_prog(alpha: tn.Prog) -> list[tn.Var]: """ Collect the variables appearing in a program Args: alpha (tn.Prog): Program to collect from Returns: list[tn.Var]: List of variables in argument Raises: TypeError: If the argument is not a valid tinyscript program """ match alpha: case tn....
def term_exc(state: tn.State, aexp: tn.Term) -> int: match aexp: case tn.Const(val): return val case tn.Var(name): if name not in state.variables: raise RuntimeError( f"Variable {name} undefined in state {state}") return state.v...
The function `exc` executes a TinyScript program (`alpha`) in a given `state`, handling commands like assignment, sequencing, conditionals, loops, and output. It updates the state, tracks execution status (e.g., termination, error, max steps), and returns the final state, status, and remaining steps. It respects `max_s...
def exc( state: tn.State, alpha: tn.Prog, max_steps: int=None, quiet: bool=False ) -> tuple[tn.State, Status, int]: """ Execute a TinyScript program. Args: state (tn.State): initial state alpha (tn.Prog): program to execute max_steps (int, optional): maximum number o...
def TermParser(): term = Forward() const = Regex(r"-?\d+").set_parse_action(tn.Const.parseaction) ident = IdentParser().set_parse_action(tn.Var.parseaction) lpar, rpar = map(Suppress, "()") paren = lpar + term + rpar plus, minus, times = map(Suppress, "+-*") atom = const | ident | paren ...
This code defines a parser for a programming language using recursive descent parsing. It constructs a parser (`prog`) that recognizes statements like assignments, conditionals, loops, and outputs, combining them with sequence and recursion handling. The parser uses defined grammatical rules and parse actions to conver...
def ProgramParser(): term = TermParser() fmla = FormulaParser() prog = Forward() lpar, rpar = map(Suppress, "()") condition = lpar + fmla + rpar assign_prog = (IdentParser() + Suppress(":=") + term).set_parse_action( tn.Asgn.parseaction) if_prog = (Suppress("if") + condition + Sup...
def get_pending_requests_path(self): return os.path.join(FILES_DIR_NAME, PENDING_REQUEST_JSON) def handle_request(self, user, request): '''This function handles request raised by CHILD''' if request.get('action') == "ADD_FUNDS": return self.add_funds(user, request) elif reque...
This function displays a user's pending requests by filtering those initiated by the user, checks if the user's profile is non-parent, and either lists the requests or processes them. If no file exists, it creates one. It updates and saves request data after handling, ensuring proper display and management of pending t...
def show_pending_requests(self,user): '''This functions displays pending requests''' profile = user.get('profile') username = user.get('username') pending_request_path = self.get_pending_requests_path() if os.path.exists(pending_request_path): pending_request = Reques...
def CalculateLoss(x, w, lmbda, nonLinearFunction): #x is N x 3 a collection of randomly generated points from non linear function; w is 16 x 1; lmbda (lambda) is constant residuals = LossFunctionResidualPass(x, w, lmbda, nonLinearFunction) #find the residual vector, essentially the diff. between what the neural net...
This function trains a neural network using the Levenberg-Marquardt algorithm by iteratively minimizing a loss function's first-order Taylor approximation. It adjusts weights via normal equations with a trust lambda regularization term, updating the trust parameter based on whether the loss decreases (smaller steps) or...
def TrainNetwork(trainingData, iterations, initialWeights, lossLambda, initialTrustLambda, nonLinearFunction, stopLossThreshold = 0.1, enableAutoStop = False): #train network iteratively using Levenberg-Marquardt algorithm print("Training network!\n") trustLambda = np.copy(initialTrustLambda) #pass in tr...
def pick_up_card(self, player, amount=1): """Pick card from stock and add to player hand. Parameters: player -- Player who picks the card Keyword arguments: amount -- number of cards to pick (default 1) Returns: number of cards actually picked Picks n ...
The method processes a player's turn by applying penalties (skip, draw2, draw4), displaying game info, determining discardable cards, letting the player select/discard a card, and drawing/discarding if no valid discard is made. It returns False if the player wins during their turn, otherwise continues the game.
def run_player(self, player): """Process a single player's turn. Parameters: player -- Player to make the turn Returns: True if no-one has won within his turn, otherwise False. In each turn, game effects are applied according to the outcome of the last turn. Th...
def read_params(config_path): with open(config_path) as yaml_file: config = yaml.safe_load(yaml_file) return config def get_feat_and_target(df, target): x = df.drop(target, axis=1) y = df[[target]] return x, y def train_and_evaluate_model(model_name, model, train_x, train_y, test_x, test_y, ...
(The main task of the code is to train and evaluate multiple machine learning models (Random Forest, Logistic Regression, KNN, Decision Tree) on a classification task using data from specified CSV files. It leverages MLflow for experiment tracking, loading hyperparameters and configuration settings from a YAML file. Th...
def main(config_path): config = read_params(config_path) train_data_path = config["processed_data_config"]["train_data_csv"] test_data_path = config["processed_data_config"]["test_data_csv"] target = config["interim_data_config"]["target"] avg_method = config["metrics"]["average_method"] train ...
def insert_data_to_search_results(search_query, document_df, topics_and_weights, topics_over_time, metadata): cursor = __get_db_cursor() cursor.execute(INSERT_SEARCH_RESULTS_QUERY, params=( search_query, document_df, topics_and_weights, topics_over_time, metadata)) __get_db().commit() return cur...
The main task of the code is to insert test data into a search results table using the `insert_data_to_search_results` function, then close the database cursor and connection to ensure proper resource management.
def main(): print(insert_data_to_search_results("test", "{}", "{}", "{}", "{}")) __get_db_cursor().close() __get_db().close()
def _diffPos(self, key): """ Returns (parents, node, id, diffPos), with diffPos being the prefix at which the key should be inserted into the Patricia trie. Returns -1 for diffPos if `key` exists in the tree (exact match). """ # Find the location where the item should be inserte...
This code inserts a key into a trie structure, updating or adding it if it doesn't exist. It checks for valid key ranges, locates insertion points via prefix differences, and handles compact mode optimizations. If the key exists, it updates data; otherwise, it creates new nodes, manages parent-child relationships, and ...
def _set(self, key, data=None): # Is key in the allowed bit range? (no overflow) # assert (key is not None and key >= 0 and not (key >> self.MAX_PREFIX)) # Find the location where it should be inserted into the trie # (parents, node, id, diffPos) = self._diffPos(key) ...
def analyse_game(self, payoffs_per_player): # Let a1, a2, a3 and a4 denote payoffs[0][0][0], payoffs[0][0][1], # payoffs[0][1][0] and payoffs[0][1][1], respectively. # Let b1, b2, b3 and b4 denote payoffs[1][0][0], payoffs[1][0][1], # payoffs[1][1][0] and payoffs[1][1][1], respectively. ...
This function resets graphical elements by restoring default colors, clearing special expectations, and deleting all graphics. If payoffs exist, it analyzes the game, draws regret lines, highlights cells, and displays special information to update the visual representation of the game state.
def display_graphics_and_special_information(self): self.game_matrix.restore_default_colours() self.special_expectations[0].set('') self.special_expectations[1].set('') self.graph.delete(tk.ALL) if self.game_matrix.get_payoffs(): self.analyse_game(self.game_matrix.pay...
def plot_elbow_method(i, X, k_max=5, max_iter=1000, dist="cityblock", plusplus=True): st = time.time() plus_sse = calculate_WSS(X, k_max, max_iter=max_iter, dist=dist, plusplus=plusplus) plots.elbow_method(i, [plus_sse], range(1, k_max + 1), [dist], "K++") logging.info(f"...
The main task of the code is to perform text clustering using Word2Vec embeddings. It loads preprocessed text data, extracts embeddings, applies dimensionality reduction via PCA, determines optimal cluster counts using the elbow and gap methods, and executes KMeans clustering with the averaged optimal K value, finally ...
def main(): logging.info(f"Loading data...") st = time.time() _, _, proc_texts, _ = preprocess.get_all_texts() logging.info(f"{preprocess.get_duration(st, time.time()):>20}\tData loaded...") st = time.time() model = Word2Vec.load("data/unigrams_15_min-10.w2v") logging.info(f"{preprocess.get...
def is_empty(self): """ Checks if the `RBT()` instance is empty or not in constant time. Returns ------- bool: A boolean flag showing if the `RBT` instance is empty or not. `True` shows that this instance is empty and `False` shows it'...
The `insert` method adds a numeric value to a Red-Black Tree (RBT), adhering to both binary search tree (BST) insertion rules and RBT balancing constraints. It validates input type and raises errors for invalid values. If the tree is empty, it creates a black root node. Otherwise, it inserts the value, adjusts the tree...
def insert(self, value): """ Inserts a numeric value in the `RBT()` instance according to the rules of binary search trees and the rules red-black trees as well. Args: ---------- value: int or float The new numeric value that will be inserted. Raises...
def _recvProcess(self, log=False, clearBuffer=False): # [NOTE] Create mode_setting if to simulate low node, do not use list... instead use one packet at a time self.rcvdPkt = [] # Recieve packets with self.sockLck: try: while True: self.rcv...
The code's main task is to manage node communication by broadcasting rank, processing received packets, updating configurations, and disseminating network maps. It initializes node rank, continuously checks cache flags for actions like packet reception, rank broadcasts, connection requests, and map updates, then execut...
def run(self, log=False): _sendBuffer = self.pktBffr + self.macAdrs + bytes('>rnk>', 'utf8') # Root node with self.cachLck : _getVal = self.cache['nod'] if not _getVal and self.nodeRnk == 254 : self.nodeRnk = 1 _sendBuffer += bytes(str(self.nodeRnk) + ...
def move(self,spaces): if self.square + spaces >= 40: self.cash += 200 print('You passed Go. Collect $200') self.square = (self.square + spaces) % 40 print('You landed on {}'.format(self.get_position().name)) input('') clear() self.action() def go_...
The code handles dice rolling mechanics in a board game, managing movement and jail status. If not in jail, it rolls two dice, allowing repeated turns for doubles (up to two) or sending the player to jail on the third double. If in jail, it presents options to roll dice (with fines on third non-double), pay $50, or use...
def roll_dice(self): if self.injail == False: d1 = randint(1,6) d2 = randint(1,6) total = d1 + d2 if d1 == d2: # Rolled a double if self.doubles < 2: # Rolled fewer than two doubles before - repeat turn ...
def roll_dice(self): if self.injail == False: d1 = randint(1,6) d2 = randint(1,6) total = d1 + d2 if d1 == d2: # Rolled a double if self.doubles < 2: # Rolled fewer than two doubles before - repeat turn ...
This method manages a player's turn in a board game, checking bankruptcy status, displaying options (roll dice, trade, build, etc.), and executing chosen actions. If bankrupt, it skips the turn. Otherwise, it processes selections like rolling dice, viewing properties, or declaring bankruptcy, which resets ownership and...
def run_turn(self): if self.bankrupt == True: # Skip player if bankrupt print('Player {} is bankrupt'.format(self.no+1)) self.game.turn = (self.game.turn + 1) % self.game.no_of_players print('\nPass turn to Player {}'.format(self.game.turn+1)) input(''...
def generate_bbox(self) -> List[List[float]]: """ Creates a geographic bounding box around the start and end stations, including a buffer. The bounding box encompasses the minimum and maximum latitude and longitude values of the start and end stations, with an additional buffer added to...
The main task of the code is to generate 3D building faces (base, top, and side faces) from 2D building footprints by converting geographic coordinates to Cartesian coordinates. It processes each building's polygon geometry, creates base and top faces with z-values of 0 and height, and constructs vertical side faces by...
def generate_building_faces(self) -> List[List[List[float]]]: """ Generate 3D faces for buildings based on their 2D footprints. This method iterates over the buildings obtained from `get_2d_buildings_data` and generates 3D faces for each building based on its 2D footprint. The generated...
def get_snakefile(self): return imp.load_module('snakefile', *self.find_snakefile()) def get_snakefile_path(self, snakefile): return os.path.dirname( os.path.abspath(os.path.expanduser(snakefile.__file__))) def get_tasks(self): tasks = {} namespaces = {} for obj_name ...
The main task of the code is to initialize a Snakefile by determining its module, path, and associated tasks. It checks if a Snakefile name is provided; if not, it retrieves it via `get_snakefile()`. It then sets the Snakefile path, loads tasks using `get_tasks()`, and notifies the user of the Snakefile's location. Thi...
def init_snakefile(self): if self.snakefile_name is None: self.snakefile_module = self.get_snakefile() self.snakefile_name = self.snakefile_module.__name__ else: self.snakefile_module = sys.modules[self.snakefile_name] self.snakefile_path = self.get_snakefile_...
def get_parser(self): parser = optparse.OptionParser(usage=self.usage) parser.disable_interspersed_args() parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help="give more output") parser.add_optio...
This code processes command-line arguments to adjust verbosity settings, initializes a Snakefile, and executes specified tasks. It parses options like --verbose and --quiet to modify verbosity levels, then runs tasks listed in the arguments using the Snakefile workflow system.
def run(self): parser = self.get_parser() options, args = parser.parse_args() if options.verbose: self.verbosity += 1 if options.quiet: self.verbosity -= 1 self.init_snakefile() for name in args: self.run_task(name)
def constructIV(i, j, p, c): iv = bytearray((i).to_bytes(j+1, 'big')) if j == 15: return iv for k in range(15-j): p1 = bytearray((16-j).to_bytes(1, 'big')) p2 = p[j+k+1:j+k+2] c1 = c[j+k+1:j+k+2] iv = iv + bytearray(bxor3(p1, p2, c1)) return iv def trydecrypt(c1, ...
The function decrypts a block of encrypted data using brute-force by iterating through possible byte values (0-255) for each position in the 16-byte block. It constructs an IV for each guess, checks if the decryption of the base64-encoded payload is valid, and if so, XORs the IV and ciphertext to recover the plaintext ...
def decryptblock(block1, block2): solve = bytearray(16) for j in range(15,-1,-1): for i in range(256): iv = constructIV(i,j, solve, block1) payload = base64.b64encode(iv+block2) if trydecrypt(payload): pad = bytearray((16-j).to_bytes(1, 'big')) ...
def constructIV(i, j, p, c): iv = bytearray((i).to_bytes(j+1, 'big')) if j == 15: return iv for k in range(15-j): p1 = bytearray((16-j).to_bytes(1, 'big')) p2 = p[j+k+1:j+k+2] c1 = c[j+k+1:j+k+2] iv = iv + bytearray(bxor3(p1, p2, c1)) return iv def trydecrypt(c1, ...
The code decrypts a block by iterating through possible IV values, attempting decryption, and reconstructing the plaintext block using XOR operations when successful. It uses brute-force to find the correct IV, then updates the block with derived bytes from the decrypted payload.
def encryptblock(block2, ptextblock): block1 = bytearray(16) for j in range(15,-1,-1): for i in range(256): iv = constructIV(i,j, block1, ptextblock) payload = base64.b64encode(iv+block2) if trydecrypt(payload): pad = bytearray((16-j).to_bytes(1, '...
def generate_trajectory(self,t,l,Z): inv_warp = self.g(l,t) X_obs = self.f(inv_warp,Z) X_orig = self.f(t,Z) return X_obs,X_orig def class_probs(self,Z): c1 = 2*(Z[0]*math.sin(9*math.pi*0.25)/(9*math.pi)+Z[1]*(0.5**3/3-0.25**3/3)) c2 = -2*Z[2]*(math.cos(0.75)-math.cos(0.5)...
This code initializes a synthetic dataset for machine learning by generating trajectories (X) and binary labels (y) based on random parameters. It uses PyTorch to create N samples, computes class probabilities for labels, transforms features using basis functions (G), and stores processed data tensors (X, y) and transf...
def __init__(self, N,T,nb_basis=64): self.X = [] self.y = [] self.N = N self.T = T self.nb_basis = nb_basis Z_all = [] l_all = [] for i in range(N): #using torch and not numpy l = torch.rand(1)*20 Z = torch.rand(4)*8-4 ...
def parse_neighborhoods(borough): column_name = borough.split(".")[0].replace("-", " ").title() filename = "./boroughs/" + borough borough_df = pd.read_csv(filename, sep='\n') return [borough_df, column_name] def get_zip_codes(dataframes): """ :param dataframes: Two dataframes (1) - ba...
This function processes a specified borough's neighborhood data by parsing it, extracting zip codes, and optionally converting the resulting data to JSON format based on user input. If the 'parse' parameter is set to 'skip', it bypasses processing. The task involves data retrieval, user confirmation for formatting, and...
def borough_parse(parse, borough, borough_name): if parse != "skip": df_arr = parse_neighborhoods(borough) borough_data = get_zip_codes(df_arr) convert_to_json = input("Convert " + borough_name + " data to json format? (yes/no) => ") if convert_to_json == "yes": print("Wr...
def parse_neighborhoods(borough): column_name = borough.split(".")[0].replace("-", " ").title() filename = "./boroughs/" + borough borough_df = pd.read_csv(filename, sep='\n') return [borough_df, column_name] def get_subway_stations(dataframes): borough_data, column_name = dataframes borough_da...
This function processes borough data by parsing neighborhoods, retrieving subway station information, and optionally converting the data to JSON format based on user input. If 'parse' is not 'skip', it processes the borough, collects subway data, and asks the user to convert results to JSON. If 'skip' is specified, it ...
def borough_parse(parse, borough, borough_name): if parse != "skip": df_arr = parse_neighborhoods(borough) borough_data = get_subway_stations(df_arr) convert_to_json = input("Convert " + borough_name + " data to json format? (yes/no) => ") if convert_to_json == "yes": pri...
def clear_matrix(): # void clear_matrix(void); camlib.clear_matrix.argtypes = [] camlib.clear_matrix.restype = None camlib.clear_matrix() def clear_paimage(): # void clear_paimage(void); camlib.clear_paimage.argtypes = [] camlib.clear_paimage.restype = None camlib.clear_paimage() def i...
The main task of the code is to demonstrate real-time image processing with adjustable CLAHE filtering and brightness/contrast controls. It initializes a camera, captures and buffers frames, applies histogram equalization, and displays processed images in two OpenCV windows with interactive trackbars for user-adjustabl...
def demo_image(): global img clear_matrix() clear_paimage() h = init(fps=DEF_FPS, SL=DEF_SL, BP=DEF_BP, AGC=DEF_AGC, nuc=DEF_NUC) # We load a bunch of frames after init of the camera to get some history. for i in range(0, 120): load_frame_buffer(h) load_matrix_buffer(False) ...
def clear_matrix(): # void clear_matrix(void); camlib.clear_matrix.argtypes = [] camlib.clear_matrix.restype = None camlib.clear_matrix() def clear_paimage(): # void clear_paimage(void); camlib.clear_paimage.argtypes = [] camlib.clear_paimage.restype = None camlib.clear_paimage() def i...
The code demonstrates real-time video processing with adjustable brightness and contrast using OpenCV. It initializes a camera, creates windows for CLAHE-filtered and adjusted images, adds trackbars for brightness/contrast control, processes frames in a loop, and exits on 'q'.
def demo_video(): global img clear_matrix() clear_paimage() h = init(fps=DEF_FPS, SL=DEF_SL, BP=DEF_BP, AGC=DEF_AGC, nuc=DEF_NUC) cv.namedWindow("CLAHE filter", cv.WINDOW_GUI_EXPANDED) cv.namedWindow("Brightness/Contrast", cv.WINDOW_GUI_EXPANDED) cv.createTrackbar( "Brightness", "B...
def assign_input(product, property_name, value): value = cvt_if_js_value(value) compare = default_cmp if value is not None and hasattr(value, '__array_interface__'): compare = array_cmp variable_name = f"_{property_name}" assert(issubclass(type(product), Product)) current = getattr(p...
This method updates the dependencies of an object by removing all existing dependencies and adding new ones specified in the input. It is intended for QML usage only, with Python code using add/remove_dependency methods instead.
def set_dependsOn(self, v): ''' *Important" this property is meant to be used only from QML. Use add/remove_dependency() from python. ''' old = self._dependsOn if assign_input(self, "dependsOn", v): for d in old: self.remove_dependency(...
def fx(x, a1, a2): res = (x**(a1-1))*((1-x)**(a2-1)) res /= beta(a1, a2) return res def generateBeta(a1, a2, c, N): res = [] for i in range(N): while True: u1 = np.random.uniform(0.00, 1.00) u2 = np.random.uniform(0.00, 1.00) if fx(u1, a1, a2) >= c*u2: res.append(u1) break return res def plot...
The code calculates a parameter x based on inputs a1 and a2, computes a value c using fx(), and generates Beta distribution samples with varying sizes (100, 1000, etc.), plotting histograms to visualize the distribution's behavior. The main task is to demonstrate how the Beta distribution evolves with different sample ...
def solve(a1, a2): x = (a1-1)/(a1+a2-2) print('*x = {}'.format(x)) c = fx(x, a1, a2) print('f(*x) = {}'.format(c)) res = generateBeta(a1, a2, c, 100) plotHistogram(res, a1, a2, 100) res = generateBeta(a1, a2, c, 1000) plotHistogram(res, a1, a2, 1000) res = generateBeta(a1, a2, c, 10000) plotHistogram(res...
def prepare_data(self, data_set, validation_split, batch_size): if 0. < validation_split < 1.: split_at = int(data_set.shape[0] * (1. - validation_split)) self.train_set = data_set[:split_at] self.valid_set = data_set[split_at:] else: self.train_set = data...
The code trains a generative model (e.g., GAN) by iterating over epochs, performing batch training, logging losses and metrics, and saving checkpoints. It tracks training progress, updates the best model based on validation metrics, and optionally returns training history with mean, min, and max values of key metrics. ...
def train(self, data_set, batch_size=32, epochs=1, verbose=True, checkpoint_range=100, checkpoint_callback=None, validation_split=0, save_best_model=False, collect_history=True): # mean min max max_hist_size = epochs//checkpoint_range + 1 history = { 'best_metric':0, ...
def reset_window(self) -> None: """This function clear the window from all widgets""" for widget in self.__window.winfo_children(): widget.destroy() def create_buttons_in_buttons_frame(self) -> None: """This function use the create button function to make all the button letters in ...
The main task of the code is to initialize and configure a Boggle game interface by resetting the window, creating frames for score, timer, word display, buttons, and solutions, setting up labeled UI components with specific styling, organizing buttons into frames, and starting a 3-minute timer to begin the game.
def start_new_game(self) -> None: """This function reset the window that displayed and create a window with the boggle game with all the information that needs to each label or button""" self.reset_window() # Clear the pre window root = self.__window self.__buttons = [] ...
def getPosX(x_center): if x_center < 160: pos_x = 90 elif x_center >= 160 and x_center < 320: pos_x = 67 elif x_center >= 320 and x_center < 480: pos_x = 45 elif x_center >= 480 and x_center < 640: pos_x = 22 print(pos_x) print(x_cente...
The main task of the code is to collect a paper object by moving to its designated position, pick it up, and then drop it at a new location by adjusting the robot's position through a series of left/right movements and steps. The function uses input coordinates to determine movement paths for collecting and dropping th...
def collect_paper(x_center, y_center): pos_x = getPosX(x_center) pos_y = getPosY(y_center) # approach an object move_left(pos_x) # collect the object collect_object_steps(pos_y) move_right(pos_x) #drop the object move_left(90) drop_object_steps() move_right(90)
def getPosX(x_center): if x_center < 160: pos_x = 90 elif x_center >= 160 and x_center < 320: pos_x = 67 elif x_center >= 320 and x_center < 480: pos_x = 45 elif x_center >= 480 and x_center < 640: pos_x = 22 print(pos_x) print(x_cente...
The code navigates to collect an object at specified coordinates (x_center, y_center) by moving left, collecting it, then returning right. It then moves to a fixed position (135) to drop the collected object, using directional movement functions and step-based collection/drop actions.
def collect_metal(x_center, y_center): pos_x = getPosX(x_center) pos_y = getPosY(y_center) # approach an object move_left(pos_x) # collect the object collect_object_steps(pos_y) move_right(pos_x) #drop the object move_left(135) drop_object_steps() move_right(13...
def getPosX(x_center): if x_center < 160: pos_x = 90 elif x_center >= 160 and x_center < 320: pos_x = 67 elif x_center >= 320 and x_center < 480: pos_x = 45 elif x_center >= 480 and x_center < 640: pos_x = 22 print(pos_x) print(x_cente...
This function controls a robotic arm to collect plastic objects by moving to their position (x_center, y_center), grasping them, transporting them to a designated drop zone, and releasing them. It uses positional calculations to navigate, collect, and drop objects systematically.
def collect_plastic(x_center, y_center): pos_x = getPosX(x_center) pos_y = getPosY(y_center) # approach an object move_left(pos_x) # collect the object collect_object_steps(pos_y) move_right(pos_x) #drop the object move_left(180) drop_object_steps() move_right(...
def collect_object_steps(): # collect the object seek(90) drop(150) grab(90) pick(150) deseek(90) def move_left(angle): move_forward(angle, 0) def drop_object_steps(): # drop the object drop(150) release(90) pick(150) def move_right(angle): move_backwards(angle, 0)
The main task of the code is to collect an object, move left by 90 units, drop the collected object, and then return to the original position by moving right by 90 units. The function orchestrates a sequence of actions involving object collection, lateral movement, and object placement, ensuring precise positioning thr...
def collect_paper(): collect_object_steps() move_left(90) drop_object_steps() move_right(90)
def collect_object_steps(): # collect the object seek(90) drop(150) grab(90) pick(150) deseek(90) def move_left(angle): move_forward(angle, 0) def drop_object_steps(): # drop the object drop(150) release(90) pick(150) def move_right(angle): move_backwards(angle, 0)
The code defines a function `collect_metal()` that performs three main tasks: collecting an object via `collect_object_steps()`, moving left by 135 units, dropping the collected object via `drop_object_steps()`, and finally moving right by 135 units to return to the original position. The primary goal is to navigate, c...
def collect_metal(): collect_object_steps() move_left(135) drop_object_steps() move_right(135)
def collect_object_steps(): # collect the object seek(90) drop(150) grab(90) pick(150) deseek(90) def move_left(angle): move_forward(angle, 0) def drop_object_steps(): # drop the object drop(150) release(90) pick(150) def move_right(angle): move_backwards(angle, 0)
The code defines a function `collect_plastic()` that performs a sequence of actions: collecting an object, moving left by 180 units, dropping the object, and then moving right by 180 units. The primary task is to collect a plastic object, transport it to a new position by moving left, release it, and reposition by movi...
def collect_plastic(): collect_object_steps() move_left(180) drop_object_steps() move_right(180)
def get_cifar10_raw_data(data_dir): """ Gets raw CIFAR10 data from http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz. Args: data_dir: Data directory. Returns: X_train: CIFAR10 train data in numpy array with shape (50000, 32, 32, 3). Y_train: CIFAR10 train labels in numpy array with shape (5000...
The function reads CIFAR-10 datasets from a directory, preprocesses images/labels, applies one-hot encoding if enabled, splits training data into train/validation sets based on validation_size, and returns a dictionary containing train, validation, and test datasets using the DataSet class.
def read_data_sets(data_dir, one_hot = True, validation_size = 0): """ Returns the dataset readed from data_dir. Uses or not uses one-hot encoding for the labels. Subsamples validation set with specified size if necessary. Args: data_dir: Data directory. one_hot: Flag for one hot encoding. validat...
def load_config(default_file: str = TRAIN_DEFAULT_CONFIG_FILE) -> ConfigTree: args = parse_args() config_dict = config_args_to_dict(args) conf = parse_config(config_dict, args.config_file, default_file) return conf.get_config("config") def train(conf: ConfigTree): # various inits, derived attributes...
The main task of the code is to load a configuration, validate its contents, train a model using the specified parameters, record training duration and performance metrics (best validation loss and iteration count), then save these results to a JSON file named with the model type and seed value. The code ensures proper...
def main(): conf = load_config() print(conf) seed = conf.get_int("seed") modeltype = conf.get_string("wandb_run_name")[1:-1] assert len(conf) > 0, "no configuration provided" start_time = time.time() best_val_loss, iter_num = train(conf) write_results(f'bayesian_results/results_{mod...
def _data_readers(): datadir = Path.cwd().joinpath("baseballdatabank", "core").resolve() for path in sorted(datadir.glob("*.csv")): with path.open("r") as file: yield path.stem, DictReader(file) def _get_column_type_for_field(field: str, rows: list): values = set( map(lambda r: ...
This code generates SQLAlchemy model classes from data readers by determining field types from data rows, collects necessary imports, and writes the resulting models to a Python file named 'models.py' in the specified directory.
def generate(c): models = [] outfile = Path.cwd().joinpath("baseball", "db", "models.py").resolve() for name, reader in _data_readers(): model = {"name": name} logger.info("Generating model {}".format(model["name"])) rows = [row for row in reader] model["fields"] = { ...
def _draw_die(self, x, y, die): # Draw a die onto the window and return its bounding box as a # Rect. # # Arguments: # x - the desired x coordinate of the top-left corner of the # die in the window. # y - the desired y coordinate of the top-left corne...
This method updates the game state in the MAIN_GAME phase by updating dice animations, rendering them at specific positions, and delegating to either the roll or move sub-phase based on the current TurnStage.
def _tick_main_game(self): # Render items onto the window and update the game in the # MAIN_GAME state. self._die1.update() self._die2.update() self._die1_collision_rect = self._draw_die(973, 260, self._die1) self._die2_collision_rect = self._draw_die(1126, 260, ...
def _tick_setup(self): # Render items onto the window and update the game in the SETUP # state. self._die1.update() self._draw_die(1050, 260, self._die1) if self._rolling_player == "red": if self._has_rolled_before: self._display_text("Red pla...
The `tick` method updates the game state, renders graphics (including the board, frogs, and message box), handles user events, and returns whether the game should exit. It processes different game states (e.g., setup, main game) by calling corresponding methods, ensuring the display is refreshed each frame for smooth g...
def tick(self): """ Update the game and its display; return whether to quit. Render everything onto the window, update the game based on its current states, handle events, and return whether or not the game should quit. Each call to this method comprises one frame ...
def read_docs(file, mode='bow'): docs = list() labels = list() if re.search('smsspam', file) or re.search('sent_imdb', file) or re.search('sent_yelp', file) or re.search('health', file): with open(file) as f: for line in f: try: doc_id, label, text = l...
The code evaluates text classification models using various preprocessing (stemming, stopword removal) and weighting schemes (uniform, exponential decay, etc.) on multiple datasets. It computes TF-IDF vectors, compares cosine similarities between document profiles, and measures accuracy for each configuration, printing...
def experiment(): train_set = ['tank-train.tsv', 'plant-train.tsv', 'perplace-train.tsv', 'smsspam-train.tsv', 'sent_imdb-train.tsv', 'sent_yelp-train.tsv', 'health-train.tsv'] dev_set = ['tank-dev.tsv', 'plant-dev.tsv', 'perplace-dev.tsv', 'smsspam-dev.tsv', 'sent_imdb-dev.tsv', 'sent_yelp-dev.tsv', 'health-de...
def get_links(url): res = request.urlopen(url) return list(parse_links(url, res.read())) def writelines(filename, data): with open(filename, 'w') as fout: for d in data: print(d, file=fout) def get_nonlocal_links(url): '''Get a list of links on the page specificed by the url, but...
The main task of the code is to crawl a specified website, extract its links, distinguish local and non-local links, and save the visited URLs and extracted text content into separate text files for analysis and record-keeping.
def main(): site = sys.argv[1] links = get_links(site) writelines('links.txt', links) nonlocal_links = get_nonlocal_links(site) writelines('nonlocal.txt', nonlocal_links) visited, extracted = crawl_priority(site, ['text']) writelines('visited.txt', visited) writelines('extracted.txt',...
def choice_wipe(self): """ Wipes the move choice of everyoen in the round. """ for x in self.in_the_round: x.round_choice = "" def bet_ask(self): """ Simulates the betting round by asking each of the players/bots still in the round for their moves. Als...
The function `the_river` simulates the river phase of a poker round by dealing the fifth community card, displaying it, prompting bets, evaluating hand strengths, distributing winnings to the winner, and announcing the result. It manages game flow, player interactions, and monetary distribution after the final betting ...
def the_river(self): """ Simulates the river of the curreent round (final river state/5 cards). """ self.choice_wipe() print("\n\n\n\n\n\n\n\n") self.river.append(self.deck.pop()) print("\n River: ") print(self.river) print("\n") self.bet_...
def choice_wipe(self): """ Wipes the move choice of everyoen in the round. """ for x in self.in_the_round: x.round_choice = "" def player_removal(self): """ Checks the list of players for anybody who has a balance less than or equal to zero. I...
The code simulates the pre-flop phase of a poker round, handling initial betting with small and big blinds, managing all-in scenarios, updating the pot, dealing cards, and processing remaining players' actions. It ensures proper betting sequence, checks for winners, and resets game state variables for subsequent rounds...
def preflop(self): """ Simulates the pre-flop of the current round (Initial betting before the river is drawn). """ print("\n\n\n\n\n\n\n\n") self.choice_wipe() self.player_removal() if(self.win_check()): self.announce_winner() ...
def player_removal(self): """ Checks the list of players for anybody who has a balance less than or equal to zero. If a player is found, that player is removed from the game and any money they had in the pot becomes community property. """ for players ...
This code simulates a Texas Hold'em poker game by iterating through rounds, shuffling a deck, managing player hands, and progressing through pre-flop, flop, turn, and river stages. It handles player elimination, resolves all-in scenarios, compares hands to determine winners, distributes money, and repeats until a final...
def play(self): """Simulates a game of Texas Hold'em poker""" while(self.win_check): self.player_removal() self.deck = random.sample(list(p.card.Card), len((list(p.card.Card)))) # Makes a new shuffled deck after each round for x in self.player_list: ...
def detectCars(self, image): # ============================================================================= # if self.imageWidth is None or self.imageHeight is None: # (self.imageHeight, self.imageWidth) = image.shape[:2] # ==================================================================...
This code processes video frames to detect and track cars. It resizes the tracking region, reads each frame, resizes it for debugging, draws a bounding box, detects cars, tracks them, displays the output, and attempts to write the processed frame. The writer may fail due to resized dimensions.
def detectAndTrack(self): #loop over frames from vid file x1, y1, x2, y2 = int(self.resizeImageRatio * self.trackingRegionInRealSize.x1), \ int(self.resizeImageRatio * self.trackingRegionInRealSize.y1), \ int(self.resizeImageRatio * self.trackingRegionIn...
def train_embeddings(corpus_file, param, model_name, iter=1): sentences = Notes(corpus_file) print("Finished loading notes\n") start = time.time() col_results = [ ("epochs", "start_alpha", "end_alpha", "vector_size", "min_count", "window", "PP_mean", "PP_sd", "w2v")] results = [] list_pa...
(The code trains and evaluates Word2Vec models on non-redundant and redundant note datasets. It trains models with different parameters (param_r/param_nr), computes perplexity on corresponding test sets, and compares performance metrics. The task involves assessing model effectiveness in handling redundancy by measurin...
def run_w2v(file_name, raw_file_name, param_r, param_nr, iter): print(f"Parameters redundancy: {param_r}\n") print("Non-redundant notes training\n") nr_models, nr_vcb = train_embeddings(f'{file_name}_train.csv', param=param_r, ...
def num01(ngram, full, d): try: first_term_num = max(ngram[full]-d,0) except: first_term_num = 0 return first_term_num def den01(unique,ngram, history,n): denom = 0 for word in unique: temp = ngramm(tokenize(word), 1) curr = temp[len(temp)-1] corpus = history ...
The function implements Kneser-Ney smoothing for n-gram language models, calculating the probability of a word sequence by combining discounted counts of higher-order n-grams with lower-order backoff probabilities. It uses recursion to handle n-gram orders, applying different formulas based on the `check` flag and n=1 ...
def Kneser_Ney(history, ngram, check, current,unique,n): d = 0.10 full = history + current # print(n , " ujuj ", full) if (n==1): num1 = num01(ngram[n], full, d) den1 = den01(unique, ngram, history, n) try: term1 = num1/den1 except: term1 =0 ...