dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def overlapping_token_similarity_matrix(self, tokens_of_A, tokens_of_B): sim_matrix = np.zeros((len(tokens_of_A), len(tokens_of_B))) print("Lengths of similarity matrix:" , len(tokens_of_A), len(tokens_of_B)) words_multisets_A = [] words_multisets_B = [] for (i, token_A) in enumerate(token...
This function computes a normalized similarity matrix between two sets of text tokens (A and B) using a specified method from sim_config. It selects between overlapping token similarity, Jaccard, BERT/GloVe/SBERT embeddings, TF-IDF, or Hamming methods, applies the chosen algorithm, and returns the normalized matrix. If...
def get_similarity_matrix_text_text(self, tokens_of_A, tokens_of_B, sim_config): if sim_config == None: self.raw_sim_matrix = self.overlapping_token_similarity_matrix(tokens_of_A, tokens_of_B) return self.raw_sim_matrix elif sim_config['sim'] in ['overlapping_token_similarity_matrix', 'j...
def load_sbert_embedding(self, path): if os.path.exists(path): embs = np.load(path) return embs else: raise Exception(path + " does not exist.") def normalize(self, raw_sim_matrix, sim_config): if 'normalization' not in sim_config: return self.z_normalize_with_sigmoid(self.raw_...
The main task of the code is to compute a similarity matrix between two token sets (A and B) based on their type (character, word, or embedding). It checks token size compatibility, loads SBERT embeddings if needed, applies corresponding similarity methods (e.g., cosine similarity for embeddings), normalizes results, a...
def get_similarity_matrix(self, tokens_of_A, tokens_of_B, token_size_of_A, token_size_of_B, threshold, similarity_config): if token_size_of_A == 'embedding_dir': if token_size_of_B == 'embedding_dir': tokens_of_A = self.load_sbert_embedding(tokens_of_A) tokens_of_B = self.load_sbert_embedding(...
def _recv_raw(self, timeout): char = self.getc(1, timeout) if char == '': return TIMEOUT if char is not TIMEOUT: char = ord(char) return char def _recv_bin16_header(self, timeout): ''' Recieve a header with 16 bit CRC. ''' header = ...
The function receives a header from a communication stream by detecting ZPAD and ZDLE framing, parsing the header type (ZBIN, ZHEX, ZBIN32), and handling errors/timeouts. It returns the parsed header or TIMEOUT if errors exceed the limit.
def _recv_header(self, timeout, errors=10): header_length = 0 error_count = 0 char = None while header_length == 0: # First ZPAD while char != ZPAD: char = self._recv_raw(timeout) if char is TIMEOUT: return TIMEO...
def _recv_16_data(self, timeout): char = 0 data = [] mine = 0 while char < 0x100: char = self._recv(timeout) if char is TIMEOUT: return TIMEOUT, '' elif char < 0x100: mine = self.calc_crc16(chr(char & 0xff), mine) ...
This function receives data based on the specified bit size (16 or 32), processes the frame type (e.g., ZCRCG, ZCRCE), updates file positions, and returns status codes (FRAMEOK, ENDOFFRAME, TIMEOUT) or data. It handles frame continuation, termination, and acknowledgment logic, sending ZACK headers when required.
def _recv_data(self, ack_file_pos, timeout): zack_header = [ZACK, 0, 0, 0, 0] pos = ack_file_pos if self._recv_bits == 16: sub_frame_kind, data = self._recv_16_data(timeout) elif self._recv_bits == 32: sub_frame_kind, data = self._recv_32_data(timeout) el...
def _send_pos_header(self, kind, pos, timeout): header = [] header.append(kind) header.append(pos & 0xff) header.append((pos >> 0x08) & 0xff) header.append((pos >> 0x10) & 0xff) header.append((pos >> 0x20) & 0xff) self._send_hex_header(header, timeout) def _recv_h...
This function receives file data from a network stream, ensuring it aligns with the specified position. It waits for data headers, validates block positions, and writes received data chunks to a file handle. It handles timeouts and returns the final status along with the total bytes written.
def _recv_file_data(self, pos, fp, timeout): if pos == 0: self._send_pos_header(ZRPOS, pos, timeout) kind = 0 dpos = -1 while dpos != pos: while kind != ZDATA: if kind is TIMEOUT: return TIMEOUT, '' else: ...
def _recv_data(self, ack_file_pos, timeout): zack_header = [ZACK, 0, 0, 0, 0] pos = ack_file_pos if self._recv_bits == 16: sub_frame_kind, data = self._recv_16_data(timeout) elif self._recv_bits == 32: sub_frame_kind, data = self._recv_32_data(timeout) el...
The main task of the code is to receive a file over a network connection, validate its metadata, write the data to a file in the specified directory, and update the file's modification time. It handles corrupted metadata, receives file content in chunks, logs transfer details, and ensures proper file creation even for ...
def _recv_file(self, basedir, timeout, retry): log.info('Abort to receive a file in %s' % (basedir,)) pos = 0 # Read the data subpacket containing the file information kind, data = self._recv_data(pos, timeout) pos += len(data) if kind not in [FRAMEOK, ENDOFFRAME]: ...
def get_ruleset(self, rule: int) -> typing.Dict[str, int]: """Gets a ruleset which is either binary of ternary depending on the rule number""" if rule != None: return self.binary_ruleset(rule) if rule <= 255 else self.ternary_ruleset(rule) return {'': 0} def set_colors(self) -> None:...
The code initializes a cellular automaton by setting up initial cell states, next state buffer, result storage, loading rules based on a rule number, and configuring visualization and color settings. It prepares the system for simulation by resetting iteration counters and invoking the run method to start the process.
def start(self) -> None: """Sets starting conditions""" self.cells: typing.List[int] = [c for c in self.c0] # set cells from init pattern self.__next_state: typing.List[int] = [0 for _ in self.c0] # initialize next state to be all zeros self.result: typing.List[int] = [0 for _ in self.c0...
def generate_render_rays(self): """ Generates rays used to render a video using a trained mip-NeRF """ print("Generating Render Poses") self.generate_render_poses() print("Generating rays") self.generate_rays() def generate_training_rays(self): """ ...
The main task of the code is to load and prepare ray data based on the specified split ("render" or training). It generates corresponding rays, converts them into Jittor-compatible tensors via `flatten_to_jittor()`, and outputs a completion message. This function likely supports rendering or training processes in a neu...
def load(self): if self.split == "render": self.generate_render_rays() else: self.generate_training_rays() self.flatten_to_jittor() print('Done') print()
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
This code retrieves a string from the first argument, verifies that register R0 contains a valid integer index within the string's bounds, and then stores the character at that index into the location specified by the second argument.
def p_sat (self, args: list): the_string=self.get_data(args[0]) ; self.make_sure(isinstance(the_string, str),"sat expected STRING, got: %s"%the_string) self.make_sure(isinstance(self.registers[0],int),"sat expects INT at register R0, got: %s"%str(self.registers[0])) self.make_sure(self....
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
This function performs division of two integer values retrieved from data. It validates both values are integers and at least one is zero, then stores the result of dividing the target value by the source value back into the target data location.
def p_div(self, args: list): source_v=self.get_data(args[0]) ; target_v=self.get_data(args[1]) self.make_sure(isinstance(source_v,int) and isinstance(target_v,int) and (0 in (source_v, target_v)),"div expects INT, got: %s/%s"%(str(source_v),str(target_v))) self.set_data(target_v/source_v,args[...
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
The function multiplies two integers retrieved from specified data locations, validates they are integers, and stores the result back into the second location.
def p_mul(self, args: list): source_v=self.get_data(args[0]) ; target_v=self.get_data(args[1]) self.make_sure(isinstance(source_v,int) and isinstance(target_v,int),"mul expects INT, got: %s/%s"%(str(source_v),str(target_v))) self.set_data(target_v*source_v,args[1])
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
The main task of the code is to subtract two integer values from a data structure. It retrieves values from specified positions, validates they are integers, computes their difference, and stores the result back in the original position. The function ensures type safety and performs in-place subtraction, updating the d...
def p_sub(self, args: list): source_v=self.get_data(args[0]) ; target_v=self.get_data(args[1]) self.make_sure(isinstance(source_v,int) and isinstance(target_v,int),"sub expects INT, got: %s/%s"%(str(source_v),str(target_v))) self.set_data(target_v-source_v,args[1])
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
This function adds two integer values from specified registers, updating the target register with the sum of the source and target values. It retrieves data from the source and target registers, verifies they are integers, then stores the result back in the target register.
def p_add(self, args: list): # !! NOTE: ex: add R0, R1: R1=R1+R0 !! source_v=self.get_data(args[0]) ; target_v=self.get_data(args[1]) self.make_sure(isinstance(source_v,int) and isinstance(target_v,int),"add expects INT, got: %s/%s"%(str(source_v),str(target_v))) self.set_data(target_...
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
This code decrements the integer value stored at the location specified by args[0]. It retrieves the value, validates it as an integer, subtracts 1, and updates the storage location with the new value.
def p_dec(self, args: list): source_v=self.get_data(args[0]) ; self.make_sure(isinstance(source_v,int),"inc expects INT, got: %s"%str(type(source_v))) self.set_data(source_v-1, args[0])
def get_data(self, token: str): """get_data: adquire (return) data by given token.""" self.debug.ll("get_data(token: %s)"%(token)) if token[0] in ('"',"'"): return token[1:len(token)-1] elif (token[0]=='%'): v_name=token[1:len(token)] ; return self.get_var(v_name) ...
This method increments the integer value stored at the specified data location. It retrieves the value, validates it as an integer, increments it by 1, and updates the data with the new value.
def p_inc(self, args: list): source_v=self.get_data(args[0]) ; self.make_sure(isinstance(source_v,int),"inc expects INT, got: %s"%str(type(source_v))) self.set_data(source_v+1, args[0])
def entropy(y, weights): # parts = dict {keys: unique elems, values: [indices of keys]} value_indices_dict = partition(y) # dictionary entropy = 0 for val in value_indices_dict.keys(): y_prob = probability(val, y, weights) entropy -= y_prob*np.log2(y_prob) return entropy def part...
The code calculates mutual information $ I_{XY} $ between variables $ X $ and $ Y $, using weighted probabilities. It computes marginal entropy $ H(Y) $ and conditional entropy $ H(Y|X) $ by iterating over unique $ X $ values, extracting corresponding $ Y $ subsets, and weighting their entropies. Mutual information qua...
def mutual_information(x, y, weights): # Compute entropy of y. H(Y) = SUM(P(Y=y) * log2 P(Y=y)), # y: a unique value from Y H_y = entropy(y, weights) # Compute entropy of y|x. # H(Y) = SUM(P(X=x)) * SUM(P(Y=y|X=x) * log2 P(Y=y | X=x))) # x: a unique value from X, y: a unique value from Y...
def mutual_information(x, y, weights): # Compute entropy of y. H(Y) = SUM(P(Y=y) * log2 P(Y=y)), # y: a unique value from Y H_y = entropy(y, weights) # Compute entropy of y|x. # H(Y) = SUM(P(X=x)) * SUM(P(Y=y|X=x) * log2 P(Y=y | X=x))) # x: a unique value from X, y: a unique value from Y...
The code implements the ID3 algorithm to build a decision tree for classification. It recursively selects the attribute-value pair with the highest information gain to split the dataset, partitions the data, and constructs tree nodes. The process stops when all labels are pure, no attributes remain, or max depth is rea...
def id3(x, y, weights, attr_value_pairs=None, max_depth=3, depth=0): # elements and counts of y y_elements, y_counts = np.unique(y, return_counts=True) # If the entire set of labels (y) is pure (all y = only 0 or only 1), # then return that label if(len(y_elements) == 1): return y_elemen...
def get_data(dataset_name='dummy', extension='.data'): data_path = './' return np.genfromtxt((data_path + dataset_name + extension), missing_values=0, skip_header=0, delimiter=',', dtype=int) def id3(x, y, weights, attr_value_pairs=None, max_depth=3, depth=0): # elements and counts of...
The code implements a bagging algorithm using decision trees. It loads training and test data, trains multiple trees via bootstrapped sampling, and combines their predictions through majority voting. The function outputs a confusion matrix for test set evaluation, aiming to improve accuracy and reduce overfitting by ag...
def bagging(dataset_name, depth=5, num_trees=10): print("Bagging", end='\n') # Load the train data data_train = get_data(dataset_name, '.train') X_train = data_train[:, 1:] y_train = data_train[:, 0] # Load the test data data_test = get_data(dataset_name, '.test') X_test = data...
def get_data(dataset_name='dummy', extension='.data'): data_path = './' return np.genfromtxt((data_path + dataset_name + extension), missing_values=0, skip_header=0, delimiter=',', dtype=int) def id3(x, y, weights, attr_value_pairs=None, max_depth=3, depth=0): # elements and counts of...
This code implements AdaBoost using decision stumps as weak learners. It trains multiple stumps on weighted training data, calculates their error rates, updates weights based on performance, and combines hypotheses with weighted votes for final predictions. The algorithm iteratively improves accuracy by focusing more o...
def boosting(dataset_name, depth=1, num_stumps=10): print("Boosting", end='\n') # Load the train data data_train = get_data(dataset_name, '.train') X_train = data_train[:, 1:] y_train = data_train[:, 0] # Load the test data data_test = get_data(dataset_name, '.test') X_test = data_t...
def get_consignment_instance(self, consignment_id=None): if consignment_id not in EMPTY_VALUES: return Consignment.objects.get(id=consignment_id) return Consignment() def save_to_db(self, consignment_instance): consignment_instance.date = self.date consignment_instance.nhrt_n...
The main task of the code is to update a consignment's data by retrieving its instance, saving it to the database, updating related transactions, and returning the updated consignment instance.
def update(self, consignment_id): consignment_instance = self.get_consignment_instance(consignment_id) self.save_to_db(consignment_instance) self.update_transactions(consignment_instance) return consignment_instance
def get_trip_instance(self, trip_id=None): if trip_id not in EMPTY_VALUES: return Trip.objects.get(id=trip_id) return Trip() def save_to_db(self, trip_instance): trip_instance.truck = self.get_truck_instance() trip_instance.consignment = self.get_consignment_instance() ...
The main task of the code is to create and process a trip instance by retrieving it, saving it to the database, generating intermediate transactions, and returning the updated instance.
def create(self): trip_instance = self.get_trip_instance() trip_instance = self.save_to_db(trip_instance) trip_instance = self.create_intermediate_transactions(trip_instance) return trip_instance
def get_trip_instance(self, trip_id=None): if trip_id not in EMPTY_VALUES: return Trip.objects.get(id=trip_id) return Trip() def save_to_db(self, trip_instance): trip_instance.truck = self.get_truck_instance() trip_instance.consignment = self.get_consignment_instance() ...
The code updates a trip instance by retrieving it via `get_trip_instance`, saving it to the database with `save_to_db`, updating its transactions via `update_transactions`, and returning the modified instance. The main task is to persist and modify trip data, ensuring transactions are updated, then return the finalized...
def update(self, trip_id): trip_instance = self.get_trip_instance(trip_id) trip_instance = self.save_to_db(trip_instance) trip_instance = self.update_transactions(trip_instance) return trip_instance
def _score_matrix_conv2d(self, module, input_shape): # only supports conv2d layers with dilation = 1 return self.get_conv_matrix(input_height=input_shape[2], input_width=input_shape[3], \ weights=module.weight.cpu().detach().numpy(), stride = module.stride[0], pad = module.p...
The function computes and returns an absolute value of a score matrix for a given neural network layer based on its type. It checks the module's type (e.g., Conv2d, Linear, MaxPool2d) and calls corresponding helper methods to generate the score matrix, ensuring compatibility with different layer operations. If the modu...
def _get_layer_score_matrix(self, module, layer_info): if isinstance(module, nn.Conv2d): return abs(self._score_matrix_conv2d(module, layer_info['input_shape'])) elif isinstance(module, nn.Linear): return abs(self._score_matrix_linear(module)) elif isinstance(module, nn.M...
def make_connection(database = None): if database is None: database = os.path.join(os.path.dirname(__file__), 'activities.db') conn = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES) conn.row_factory = sqlite3.Row return conn def initial_setup(conn): with conn: conn.e...
The main task of the code is to simulate a user authentication and data management workflow. It creates a user, logs them in, loads a text file, checks/extends their session, retrieves activity maps, logs, and cache data. The commented-out sections suggest potential transaction handling functionality. The code demonstr...
def main(): conn = make_connection() initial_setup(conn) create_user(conn, 'asdf', 'qwer') res = log_in(conn, 'asdf', 'qwer') user_id = res['user_id'] load_text_file(conn, user_id, 'record.txt') res_session = check_session_id(conn, user_id, res['sessi...
def read_in_chunks(file, chunk_size=8192): # reads from txt file with specific chunk_size while True: data = file.read(chunk_size) if not data: break yield data def compress(piece_of_text, input_args): # returns bytearray to write bytes_to_write = bytearray() # c...
The code performs compression or decompression based on the 'm' parameter. In 'k' mode, it reads input files in chunks, compresses each, and writes the output. In 'd' mode, it decodes binary data by extracting chunk lengths, dictionaries, and padded bits, then reconstructs text using the dictionary. The result is writt...
def main(input_args): if input_args.m == "k": with open(input_args.i, "r") as first_file: for piece in read_in_chunks(first_file): bytes_to_write = compress(piece, input_args.o) if input_args.o: with open(input_args.o, "ab") as second_file: ...
def bytes_to_bits(_bytes): # input bytes to bit/string in 8-bit format to_bits = ''.join(format(x, '08b') for x in _bytes) return to_bits def calc_crc32(list_int): if _ran: init32() crc = init for char in list_int: crc = update32(crc, char) crc = crc ^ init return crc def...
The function decodes Hamming-encoded data by extracting original data and CRC32 checksum from input bytes. It recalculates CRC32, compares it with the stored checksum, corrects errors if detected, and outputs the decoded data as a string. If CRCs match, it processes data chunks, applies error correction, and reconstruc...
def hamming_decode(read_bytes, output_file): # hamming decode # converts bytes to bitstring bitstring_from_bytes = bytes_to_bits(read_bytes) # original data of decoded chunk original_data = bitstring_from_bytes[:-64] # CRC32 decoded from decoded chunk decoded_crc = bitstring_from_bytes[-64...
def convert_chunk_into_bitstring(piece_of_text): # converts piece of text into bitstring result_text = "" for char in piece_of_text: result_text += string_to_bin(char) return result_text def bits2hamming(substring_arr): # makes huffman code (8,4) for each 4 bits of bitstring data result_...
The main task of the code is to encode a piece of text into Hamming code (8,4), compute CRC32 for error detection, encode the CRC32 result with Hamming code, and either output the combined encoded data to a binary file or print it. It processes text into bitstrings, splits them into chunks, applies Hamming encoding, ca...
def hamming_code(piece_of_text, output_file): # transforms piece of text into bitstring bitstring_text = convert_chunk_into_bitstring(piece_of_text) # transformed text into list of substring with size of 4 substring_arr = re.findall('....', bitstring_text) # bitstring transformed into bitstring, w...
def read_in_chunks(file_to_read, chunk_size=4096): # reads from txt file with specific chunk_size while True: data = file_to_read.read(chunk_size) if not data: break yield data def hamming_code(piece_of_text, output_file): # transforms piece of text into bitstring bit...
The code's main task is to process input files using Hamming coding/decoding based on the mode flag ('k' for encoding, 'd' for decoding). It reads input files in chunks, applies Hamming code/decode operations, and writes results to an output file. The 'k' mode processes text chunks, while 'd' handles binary data in 820...
def main(input_args): if input_args.m == "k": with open(input_args.i, "r") as first_file: for piece in read_in_chunks(first_file): hamming_code(piece, input_args.o) first_file.close() elif input_args.m == "d": with open(input_args.i, "rb") as first_file: ...
def print_location_and_velocity(name,x,v): print("SATELLITE " + str(name) + " STARTING LOCATION: " + x.__str__() + " STARTING " "VELOCITY: " + v.__str__()) def transmit_message(self): message = Message(self.count*sel...
This function updates an object's position and velocity using acceleration from interacting masses, applying either provided or environment-derived time steps. It tracks simulation time, triggers periodic events (like message emission) based on a clock speed, and updates system state. The core task is physics-based mot...
def _step(self,dt=None,u=0): #move in time. Do m if debug: print(self.name + ": ") for mass in self.env.masses: u += mass.get_acceleration(self.x) if dt != None: self.x = .5*u*dt**2 +self.v* dt + self.x self.v = u * dt + self.v elif self.e...
def new_game(): user = " " row1 = [i for i in user[:3]] tic_tac.append(row1) row2 = [i for i in user[3:6]] tic_tac.append(row2) row3 = [i for i in user[6:]] tic_tac.append(row3) def printer(): print("---------") print("|", tic_tac[0][0], tic_tac[0][1], tic_tac[0][2], "|") ...
The code implements a menu loop for a Tic-Tac-Toe game, handling user commands like "start" and "exit". It initializes game parameters, processes player types (user/easy AI), and alternates turns between players or bots. The loop manages game state, executes moves, and checks for game termination conditions (win/draw) ...
def menu_loop(): global finish while True: command = input("Input command: ") if command == "exit": break try: start, X, O = command.split() except ValueError: print("Bad parameters!") continue if start == "start": ...
def check_exist(path): return os.path.exists(path) def eventEmit(self, msg): print(msg) self.copy_status.emit(msg) def process_files(self, base_path, files): for f in files: self.eventEmit("Processing in " + base_path + " file : " + f) if self.validate_file(f): ...
The code synchronizes files from specified source directories to a destination by validating the destination path, checking source directory existence, copying files if enabled, and generating a JSON file. It skips invalid paths, emits status messages for errors or skips, and processes valid files through `process_file...
def sync(self): print("Reading source directories" + self.destination) if not self.check_exist(self.destination): self.eventEmit( "<span style=\" font-size:8pt; font-weight:600; color:red;\" >" + "Invalid Destination Folder. Please check and verify" + "</span>") r...
def check_exist(self, path, emit_type=""): status = os.path.exists(path) if not status: self.eventEmit("Skipping {} path {} Does not Exist".format(emit_type, path)) return status def generate_file_list(self): files = [(dire, f, self.destination) for dire in self.input_direct...
The code's main task is to synchronize files by checking the destination's existence, generating a file list, updating the total file count in `FileSyncProcess`, and initiating the file copy process via `processWorkerCopy`. It ensures synchronization starts only if the destination exists and prepares necessary data for...
def sync(self): if not self.check_exist(self.destination, "destination"): return files = self.generate_file_list() FileSyncProcess.total_files = len(files) self.processWorkerCopy(files)
def check_exist(self, path, emit_type=""): status = os.path.exists(path) if not status: self.eventEmit("Skipping {} path {} Does not Exist".format(emit_type, path)) return status def generate_file_list(self): files = [(dire, f) for dire in self.input_directory if self.check_...
The code's main task is to synchronize files by checking the destination's existence, generating a file list, setting total file counts, and initiating parallel file copying via a thread pool. It also creates a JSON file to record the process, ensuring efficient data transfer and state tracking during synchronization.
def sync(self): if not self.check_exist(self.destination, "destination"): return files = self.generate_file_list() self.total_files = len(files) print(files) self.totalFiles = len(files) self.threadPoolWorkerCopy(files) #self.threadWorkerCopy(files) ...
def get_words_of_size(word_list, word_length=5): #built for wordle new_word_list = [] for word in word_list: if len(word)==word_length: new_word_list.append(word) return new_word_list def get_dictionary_word_list(remove_words=True): word_list = list(english_words_lower_alpha_set) ...
The main task of the code is to assist in guessing a word by filtering possible candidates based on known letters, their positions, and excluded letters. It generates visualizations showing letter frequency and position likelihoods in remaining word possibilities to guide the user's next guesses.
def game_helper(known_locations, known_letters, letters_cant_be): #input unknown letters of word as ? to tell program you don't know #get initial word list word_length = len(known_locations) words = get_words_of_size(get_dictionary_word_list(), word_length) #get the updated list of words word...
def get_nerdle_equation_list(equation_length=8, equal_spots=[5,6,7]): num_op_combo = NUMBERS + OPERATORS #create the possible combinations for left and right handed sides valid_equations = [] ttl_combos = 0 for spot_diff in equal_spots: #create list of possible characters for left and righ...
This code generates potential equations based on known character positions and excluded characters, filters valid equations, evaluates their scores, and visualizes character frequency in equation spots to aid in solving a game like Nerdle.
def game_helper(known_locations, known_characters, characters_cant_be, equal_spots = [5,6,7]): #input unknown letters of word as ? to tell program you don't know #get initial equation list equation_length = len(known_locations) eqn_list = get_nerdle_equation_list(equation_length=equation_length, equal...
def _setup_logger() -> None: log_formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(log_formatter) console_handler.propagate = False logging.getLogger().addHandler(console_handler) log.set...
The code's main task is to either scrape Windows 11 CPU information from websites or upload pre-scrapped CPU data to a Google Sheet. It uses command-line arguments to determine the action, requiring Google API credentials and a co-owner email for spreadsheet sharing. The script loads data from a pickle file for upload ...
def main() -> None: parser = argparse.ArgumentParser(description='Windows 11 CPU information scraper') parser.add_argument('action', metavar='ACTION-TO-DO', help='Mandatory action to do: scrape or upload.') parser.add_argument('--google-credentials', metavar='GOOGLE-JSON-CREDENTIALS-...
def calc_qw_check_norm(self, qx, qy, qz): """ Calculate scalar component of quaternion and check norm and normalize if norm is greater than one""" # turn warnings into errors warnings.filterwarnings("error") try: qw = pow(1 - pow(qx,2) - pow(qy,2) - pow(qz,2), 0.5) ex...
This function uses an Extended Kalman Filter (EKF) to estimate the system's state (position, velocity, orientation) from IMU measurements and control inputs. It transforms IMU data into the inertial frame, constructs state and measurement matrices, and computes the EKF update to refine the state estimate. The result is...
def imu_ekf_estimation(self, imuMsg): """ Use ekf to create a state estimate when given imu and control input data""" # get the current time currentTime = rospy.get_time() # calculate the time delta b/t previous measurement and current measurement if self.firstMeasurementPassed:...
def getDataSet(predict_metric_name, path_org, data_path,day): paths = get_paths(path_org, predict_metric_name) csv_data_cores = [getCsv(data_path, path_org, path[0], path[1],day) for path in paths] csv_data_cores = reduce(lambda left, right: merge_and_drop_dups(left, right), csv_data_cores) none_tech_me...
The main task of the code is to preprocess time-series data for machine learning, including setting random seeds, loading and scaling features, adding moving averages, handling feature multiplication, splitting data into train/test sets, and configuring hyperparameter tuning via random grid search for an LSTM model. Th...
def main(arguments): random.seed(100) np.random.seed(100) tensorflow.random.set_seed(100) # get_data with no date, and all data in csv # new_path = data_path_servers + country_AM + cores_40_path new_path = data_path_servers + country_US + cores_32_path data_to_scale_no_dates, csv_data_with_d...
def tree_layout(G): # Create a copy of the graph so we don't modify the original H = copy.deepcopy(G) # Get the edges and nodes of the graph edges = list(H.edges()) nodes = list(H.nodes()) # Create a dictionary to store the position of each node pos = {} # Set the position of the root...
The code constructs a supplier-buyer relationship graph based on product similarities from a user's purchase history. It connects to MongoDB to retrieve invoices, uses OpenAI API to analyze product relevance, builds network connections, and generates a visual graph with nodes (suppliers/buyers) and edges (products). Th...
def makegraph(username): # Connect to the MongoDB database client = pymongo.MongoClient( "mongodb+srv://user:HIZ05Jh0NVv6YKg@suplaisense.8zr73kh.mongodb.net/?retryWrites=true&w=majority") invoice_db = client.user_invoices user_db = client.user_login_system.users user=user_db.find_one({'name'...
def _getPath(self, row): '''return the destination path of an image''' return self.outFolder + os.sep + self._getName(row) def _hasPermissiveLicense(self, row): if row['license'].startswith('Creative Commons') or row['license'].startswith('Nomination File'): return True if ro...
The code synchronizes the database by updating photo metadata (download status, dimensions, license, resolution) based on file existence and image analysis, while optionally removing non-downloaded photos when purge=True.
def synchronize(self, purge=False): '''read and update effective photo size and remove non downloaded photo from the database''' logging.info('Synchronizing database...') cpt = 0 for site in self.photos: photos = self.photos[site] for i in reversed(range(len(photo...
def _initialize_parameter(self): """Initializatin of the clustering barycenter""" if self.init_method == 'kmeans': total_sample_size = 10000 X = rmixGaussian(self.means, self.covs, self.weights, total_sample_size, self.random_state)[0] gm ...
This code implements an iterative optimization algorithm for clustering, updating weights and support parameters while checking for convergence. It removes empty clusters, monitors objective function changes, and terminates early if convergence is achieved or if the objective increases, raising errors in such cases. If...
def iterative(self): self._initialize_parameter() obj = np.Inf for n_iter in range(1, self.max_iter + 1): proc_time = time.time() obj_current = self._weight_update() # remove the empty cluster centers index = np.where(self.ot_plan.sum(axis=0) != 0)...
def parse_args(): parser = argparse.ArgumentParser(description='Process RNAqua output for further analysis') parser.add_argument('-i', '--input', type=str, help='Input file name') parser.add_argument('-d', '--directory', type=str, help='Process all files in the directory') parser.add_argument('-o', '--o...
The main task of the code is to generate processing commands for RNA structures based on input files or directories. It validates user arguments, selects between RNAqua or rna-tools, processes inputs using `process_file`/`process_directory`, verifies output directories, and writes generated commands to the specified ou...
def main(): args = parse_args() if args.input is not None and args.directory is not None: print('Please specify either input file or directory') return centroids = get_centroids() if args.rna_tools is not None: print("Preparing commands for rna-tools") else: prin...
def get_opened_fingers(self): if self.results.multi_hand_landmarks: self.opened_fingers = [] for finger in self.fingers: if finger == "Thumb": d1 = self.get_distance(4, 13) d2 = self.get_distance(4, 5) else: ...
The code detects hand gestures to determine actions like "Move" or "Zoom" based on finger positions and distances between specific landmarks. It uses `get_opened_fingers` and distance calculations to classify gestures, returning the action type and relevant details for further processing.
def find_action(self): action_type, action_details = None, None if self.results.multi_hand_landmarks: self.get_opened_fingers() if self.get_distance(8, 12) < 1.5 * self.get_distance(5, 9): action_type = "Move" action_details = self.get_landmark...
def send_message(self, event, message): for user in self.users: user.receive_message(event, message) def serialize(arr): return json.loads(json.dumps(arr, default=lambda cls: cls.json())) def next_user(self, current_user): current_index = self.users.index(current_user) if current_index == len(self.users) - 1:...
This function manages player turns in a game. It updates the current player's bid to -1 if it was 0, sends bid/switch messages, transitions to the final phase when returning to the first player, and sets a timer for the next turn switch.
def switch_player(self): if self.current_user.bid == 0: self.current_user.bid = -1 self.send_message("user_bid", {"from_user": serialize(self.current_user), "bid": self.current_user.bid}) if self.next_user(self.current_user) == self.current_first_user: return self.final_phase() self.current_user = self....
def send_message(self, event, message): for user in self.users: user.receive_message(event, message) def serialize(arr): return json.loads(json.dumps(arr, default=lambda cls: cls.json())) def switch_player(self): if self.current_user.bid == 0: self.current_user.bid = -1 self.send_message("user_bid", {"fro...
This code handles a "make_bid" event by validating the bid amount against the current user's coins, updating the bid if valid, canceling a timer, notifying the next player, and switching turns. It returns success if all conditions are met; otherwise, it returns failure.
def event(self, data, from_user): if data['event'] == "make_bid": if self.current_user == from_user: if data['bid'] <= self.current_user.coins: self.current_user.bid = int(data['bid']) self.timer.cancel() self.send_message("user_bid", {"from_user": serialize(self.current_user), "bid": self.curre...
def contains(self, user_to_find): filtered_users = filter(lambda user: user == user_to_find, self.users) found_user = next(filtered_users, None) return found_user if found_user else False def switch_player(self): if self.current_user.bid == 0: self.current_user.bid = -1 self.send_message("user_bid", {"fro...
The code removes a user by checking if they are the current user, cancels their timer, switches players if needed, and broadcasts the user's departure with serialized data.
def remove(self, user_id): target_user = self.contains(User("", user_id)) if target_user and self.current_user.id == target_user.id: self.timer.cancel() self.switch_player() self.send_message("user_leave", {"from_user": serialize(target_user)})
def json_logic_replace_data(rule, data, string_data=None, json_data=None): replace_data = jsonLogic(rule, data, ops) it = iter(replace_data) res_dct = dict(zip(it, it)) if string_data: for key, val in res_dct.items(): string_data = string_data.replace(key, str(val)) return ...
This function updates vtiger CRM records by setting specified field values using JSON logic rules. It processes static and function-based values, constructs a revision payload, and invokes vtiger's revise API via HTTP POST to update records with the new data.
def trigger_set_value_task(set_value_fields, conf, rule, session_name, vtiger_access): """ this function will execute revise query on vtiger for setting values params: 1.set_value_fields : json object which have list of json payload of values to be set 2.conf : conf object ...
def json_logic_replace_data(rule, data, string_data=None, json_data=None): replace_data = jsonLogic(rule, data, ops) it = iter(replace_data) res_dct = dict(zip(it, it)) if string_data: for key, val in res_dct.items(): string_data = string_data.replace(key, str(val)) return ...
The function processes web service configurations by applying JSON logic rules to replace data in the request object, then invokes an HTTP request using extracted parameters (URL, headers, type, payload) and returns the response if the request succeeds.
def invoke_web_service_task(conf, web_service_configs): """ Web service task: params: 1. conf: conf object 2. web_service_configs: json object containing web service task configurations Execution: 1. get request object and rule from conf 2. replace data using json_lo...
def buildquery(json_object): if 'field' in json_object.keys(): # In this case the json_object is an object which describes a single query if json_object.get("operator") != 'BETWEEN': return json_object.get("field") + " " + json_object.get("operator") + " '" + json_object.get("value") + "...
The main task of the code is to determine if conditions are met to trigger an external workflow in a VTiger system. It constructs and executes database queries based on configuration rules, replaces variables using JSON logic, and triggers workflows (e.g., import/manual or event-based) with retrieved or provided data v...
def run_external_workflow(conf, external_workflow_config, vtiger_access): """ this function will get check if conditions are satisfied for triggering external workflow or not. input: 1.conf : conf object 2.external_workflow_config : config dictionary containing workflow, event_type, search_...
def get_session_name(user_access_key, vtiger_url, vtiger_username): # get challenge headers = {'content-type': 'application/json'} challenge_url = '{vtiger_url}/webservice.php?operation=getchallenge&username={vtiger_username}'.format( vtiger_url=vtiger_url, vtiger_username=vtiger_username) res...
This function executes a set value task in vtiger CRM by querying records based on configured conditions and updating specified fields if conditions are met. It retrieves vtiger session credentials, constructs SQL queries with sorting/limiting, validates conditions, and triggers field updates via API calls. The task us...
def invoke_set_value_task(conf, set_value_configs, vtiger_access): """ this function will execute set value task. params: 1.conf : conf object 2.set_value_configs : conf dictionary containing rule, search_module_object, set_value_fields 3.vtiger_access : json object...
def valid(matrix): if np.size(matrix) == 0: return False for i in matrix: for j in i: if j < 0: return False return True def plurality_value(matrix): pos = p_total(matrix) neg = n_total(matrix) if pos > neg: return 2 elif neg > pos: ...
The code recursively constructs a decision tree by selecting the best attribute (randomly or via information gain), partitioning examples based on attribute values, and creating subtrees until base cases like uniform classification or no attributes remain are met.
def decision_tree_learning( examples, attributes_list, parent_examples, random_importance ): attributes = list( attributes_list ) # make a shallow copy of attribute_list as not to change the global variable if not valid(examples): return Tree(plurality_value(parent_examples)) elif s...
def make_testmatrix(): i = 0 j = 0 with open("test.txt") as test_file: for line in test_file: line.replace("\n", "\t") attributes = line.split("\t") for att in attributes: test_matrix[j][i] = att i += 1 if i == np.si...
The main task of the code is to construct and evaluate decision trees using two distinct attribute importance strategies. It first prepares test and training data matrices, then builds two trees: one with computed attribute importance and another with random importance. Both trees are tested on the test matrix to compa...
def main(): make_testmatrix() # making the test_matrix with data from "test.txt" make_examplesmatrix() # making the examples matrix with data from "training.txt" tree2 = decision_tree_learning( examples, attributes, [], False ) # building a tree with non-random importance of attributes. ...
def load_customers(): try: input_file = open(FILE, "rb") cust_dct = pickle.load(input_file) input_file.close() except IOError: cust_dct = {} return cust_dct def admin_menu(customers): pass customers = load_customers() while True: try: ...
The code provides a menu-driven interface allowing users to select between Administrator, Customer systems, or exit. It loads customer data, handles input validation, and routes users to respective functions (admin_menu or cust_input) based on their choice, with error handling for invalid inputs.
def main(): customers = load_customers() while True: try: print(f"\n{'Menu':^20}") print(f"{'-'*20}") print("""Which system would you like to access: 1: Administrator 2: Customer 3: Exit""") selection = int(input('Please make your selection: ')) ...
def load_customers(): try: input_file = open(FILE, "rb") cust_dct = pickle.load(input_file) input_file.close() except IOError: cust_dct = {} return cust_dct def cust_input(account): id = int(input('Please input your six-digit ID: ')) customer = account.get(id, 'User ...
The main task of the code is to manage customer data by loading it, displaying customer keys, accepting user input for modifications, and saving the updated data. It loads customer information, iterates through keys to print identifiers, processes user input via `cust_input`, and persists changes using `save_customers`...
def main(): list = load_customers() # list = create_cust() for v in list.keys(): print(v) # view_cust(list) cust_input(list) save_customers(list)
def _auth(image_name: str): content = _get_json( f"https://auth.docker.io/token?service=registry.docker.io&scope=repository:{image_name}:pull" ) return content["token"] def _list_layers_digest(image_name: str, image_label: str, access_token: str): content = _get_json( f"https://registry...
The main task of the code is to pull a Docker image by downloading its layers from a registry, authenticating with the registry, and extracting the layers into a specified root directory. The function handles image name parsing, layer retrieval, and tarball extraction to reconstruct the image locally.
def pull(image: str, root_path: str): if ":" not in image: name, label = image, "latest" else: name, label = image.split(":", 2) if "/" not in name: name = f"library/{name}" access_token = _auth(name) layers_digest = _list_layers_digest(name, label, access_token) for l...
def get_players_names(self) -> None: name_1 = input("Please enter player 1's name:\t") self.add_player(name_1, "X") print(f"Thanks {name_1.title()}.") name_2 = input("Please enter player 2's name:\t") self.add_player(name_2, "O") print(f"Thanks {name_2.title()}.") def wai...
The main task of the code is to orchestrate a Connect 4 game by welcoming players, collecting their names, initiating the game loop, determining the winner, and displaying results. It manages game flow, handles win/draw outcomes, and ensures proper timing between actions.
def play(self) -> None: print("Welcome to Connect 4!") self.get_players_names() print("Let's play Connect 4!") self.wait(2) winning_player = self.run_loop_until_game_ends_and_get_winner() if winning_player is not None: winning_player.show_winner_message() ...
def set_topological_order(self): """ This function calls topological sort function and set the topological sort. """ if self.sorted_nodes is not None: return if self.sorted_nodes is None: self.sorted_nodes = [] visited = {node: False for node i...
This function estimates the likelihood of a query given evidence in a Bayesian network using importance sampling. It generates samples by iterating through nodes in topological order, sampling non-evidence variables from their conditional probability tables, and weighting samples consistent with evidence. The ratio of ...
def likelihood_sample(self, query, evidence, num_iter): """ Parameters ---------- query: query set evidence: evidence set num_iter: number of genereted samples Returns ------- ...
def generate_initial_population(self, n: int, k: int) -> np.ndarray: """ Generate initial population: This function is used to generate the initial population. Inputs: - n: number of chromosomes in the population - k: number of genes in each chromosome It must generate ...
This function implements a genetic algorithm to find the optimal solution for a given problem. It initializes a population, iteratively selects parents, applies crossover and mutation to generate children, and replaces parents with children if they yield lower costs. It tracks the best cost and solution across generati...
def run_algorithm(self, S: np.ndarray, T: int, crossover_probability: float = 0.5, mutation_probability: float = 0.1, population_size: int = 100, num_generations: int = 100): """ Run algorithm: This function is used to run the genetic algorithm. Inputs: - S: array ...
def prior_sample(self, query, evidence, num_iter): """ Parameters ---------- query: query set evidence: evidence set num_iter: number of genereted samples Returns ------- ...
The code implements a sampling-based approximation of $ P(\text{query}|\text{evidence}) $ using four methods: Prior, Rejection, Likelihood Weighting, and Gibbs. It dispatches to the corresponding method based on `sampling_method`, generating `num_iter` samples. For Gibbs, it ignores initial `num_burnin` samples to ensu...
def sampling(self, query, evidence, sampling_method, num_iter, num_burnin=1e2) -> float: """ Parameters ---------- query: list list of variables an their values e.g. [('a', 0), ('e', 1)] evidence: list list of observed variables and their value...
def playing_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.MOUSEBUTTONDOWN: selected = self.mouseOnGrid() if selected: self.selected = selected ...
The code runs a game loop that processes events, updates the game state, and draws elements when the state is "playing". The loop continues while self.running is True, and exits by quitting Pygame and the application when the loop ends.
def run(self): while self.running: if self.state == "playing": self.playing_events() self.playing_update() self.playing_draw() pygame.quit() sys.exit()
def reconstruct_courses(basic_courses): ''' A function to reconstruct the course list based on limited data ''' courses = [] for entry in basic_courses: basic = entry.split(':') for course in section_list: if course["code"] == basic[0]: if course["sections...
This function randomly selects valid courses based on request parameters (term, algorithm, ignoreTBA), ensuring they are open, match the specified term, avoid TBA status, have unique names, and do not conflict with provided courses. It iterates up to 10,000 times to find 5 - len(courses) non-conflicting courses from a ...
def random_course(): ''' A function that will return a random course. ''' course = {} found_courses = [] section = None term = None courses = None names = None count = 0 find = 0 algorithm = None ignore_flag = False if "term" in request.args: term = reque...
def _parse_args(cliargs): ''' Parse arguments from command line into structure. Inputs: cliargs - The arguments provided to the command line. Returns: A structure which contains all of the parsed arguments. ''' parser = argparse.ArgumentParser( prog='search', description='Recursi...
This code processes command-line arguments to search files using find/grep, optionally replacing text with sed. It handles dry runs (printing commands), user confirmation for replacements, and returns status codes for normal exit, cancellation, or invalid input.
def main(cliargs): ''' Main function for this module. Inputs: cliargs - The arguments given at command line, excluding the executable arg. Returns: 0 if processed normally 1 if operation cancelled 2 if invalid entry provided ''' args = _parse_args(cliargs) if args.v...
def is_maximally_entangled_basis(A): """ Checks if columns of matrx form a maximally entanfgled basis. Maximally entanfgled basis is basis consisting of maximally entangled orthonormal states. """ assert A.shape == (4, 4) assert is_unitary(A) return all([is_maximally_entangled_state(A[:,...
The code partially decomposes a 4x4 unitary matrix `Psi` with fully entangled columns into two unitary matrices `UA` and `UB`, and a phase vector `zeta`, such that `(UA ⊗ UB) * Psi * exp(i * diag(zeta)) = Phi`. It aligns with Lemma 1 from a reference paper, transforming `Psi` via complex-phase adjustments and Kronecker...
def decompose_4x4_partial(Psi): """Partially decomposes 4x4 unitary matrix. Takes matrix Psi, columns of which form fully entangled basis. Returns matrices UA, UB and vector zeta, such that: (UAxUB) * Psi * exp(i * diag(zeta)) = Phi. Implements algorithm in Lemma 1 in Appendix A from [2]. """ ...
def is_maximally_entangled_basis(A): """ Checks if columns of matrx form a maximally entanfgled basis. Maximally entanfgled basis is basis consisting of maximally entangled orthonormal states. """ assert A.shape == (4, 4) assert is_unitary(A) return all([is_maximally_entangled_state(A[:,...
The code decomposes a unitary matrix $ U $ into a product of single-qubit special unitaries (with determinant 1), a "Magic N" matrix parameterized by $ \alpha $, and a global phase. It implements an algorithm from a referenced paper, transforming $ U $ via eigenvalue analysis, basis transformations, and decomposition o...
def decompose_to_magic_diagonal(U): """Decomposes unitary U as follows: U = e^(if) * (UAxUB) * N(alpha) * (VAxVB) f - global phase. UA, UB, VA, VB - 1-qubit _special_ unitaries (det=1). N(alpha) - "Magic N" matrix. Implements algorithm described in Appendix A in [2]. """ # assert is_unit...
def default(n): A, B, C = matmul(n, n, n) return te.create_schedule(C.op), (A, B, C) def parallel(n): s, (A, B, C) = reorder(n) s[C].parallel(C.op.axis[0]) return s, (A, B, C) def reorder(n): s, (A, B, C) = default(n) (x, y), (k,) = C.op.axis, C.op.reduce_axis s[C].reorder(x, k, y) r...
The code defines a tiling function for optimizing matrix operations. It sets tile sizes, splits and fuses axes, applies parallelism, reorders dimensions, and uses vectorization/unrolling to enhance computational efficiency for parallel execution on hardware like GPUs.
def tiling(n): tx, ty, tk = 32, 32, 4 s, (A, B, C) = default(n) xo, yo, xi, yi = s[C].tile(*C.op.axis, tx, ty) xy = s[C].fuse(xo, yo) s[C].parallel(xy) ko, ki = s[C].split(s[C].op.reduce_axis[0], factor=tk) s[C].reorder(ko, xi, ki, yi) s[C].vectorize(yi) s[C].unroll(ki) return s,...
def nS_over_nN0(x =np.arange(-.001,.001,0.00001)*const.e,te=4,teC=9.2): '''Returns the number of Cooper pairs over the number of electrons in normal state at 0 K, dependent on the energy. \frac{N_\text{S}(T)}{N_\text{N}(T=0\,\text{K})} Tinkham equ. 3.73 Default values are used for testing inpu...
This function tests the 'nS_over_nN0' function by plotting Cooper Pair Density vs. energy near the Fermi surface, using given temperature parameters. It visualizes the relationship across a specified energy range, marks critical energy thresholds with vertical lines, and labels axes for analysis of superconducting prop...
def _nS_over_nN0_Test(energyRange=np.arange(-.01*const.e,.01*const.e,.0001*const.e),te=4,teC=10): '''Test function of :fun: nS_over_nN0. ------ inputs ------ energyRange: 1D array energy values relative to the fermi surface in J tested te: float or int The actual temperature of t...
def mident(self, c: str) -> bool: """match identifier""" return self.mlc(c) or self.muc(c) or self.mnum(c) def midentsym(self, c: str) -> bool: """match identifier along with symbols""" return self.mident(c) or self.msym(c) def mws(self, c: str) -> bool: """match whitespaces""" ...
This function tokenizes an input string into a list of Token objects, handling variables, strings, operators, and identifiers. It processes characters sequentially, appending tokens for strings, operators (like EOLs, >, |, &), and variables. It manages quoted strings with potential variable interpolation, ensures prope...
def tokenize(self, string: str, variables={}) -> List[Token]: tokens = [] temp: List[str] = [] i = 0 while i < len(string): c = string[i] if c in EOLS: if temp: tokens.append(Token("".join(temp), TokenType.STRING)) temp.clear() ...
def make_grid_model_mbatch(G_net, autoencode, mbatch, device, hard_thres=-1, max_rows=32, show_gt=True, blur_mask_sigma=0.0, select_biggest=False): # Do exactly what validation does fores = mbatch['fore'].to(device) backs = mbatch['back'].to(device) irrels = mbatch['irrel'].to...
The main task of the code is to train a GAN (Generative Adversarial Network) with a generator (G_net) and discriminator (D_net), focusing on mask generation and object reconstruction. It processes batches of data, computes adversarial losses, alternates training between generator and discriminator, tracks multiple loss...
def train(G_net, D_net, autoencode, back_real, loader, device, writer, imgs_dir, optimizer_G, optimizer_D, epoch): start = time.time() G_net.train() D_net.train() # Visualize dataset & model examples mbatch = next(iter(loader)) grid = make_grid_model_mbatch(G_net, autoencode, mbatch, device...
def make_grid_model_mbatch(G_net, autoencode, mbatch, device, hard_thres=-1, max_rows=32, show_gt=True, blur_mask_sigma=0.0, select_biggest=False): # Do exactly what validation does fores = mbatch['fore'].to(device) backs = mbatch['back'].to(device) irrels = mbatch['irrel'].to...
The function `val` evaluates the performance of a generator (G_net) and discriminator (D_net) on a validation dataset. It computes various loss components (e.g., G_fake, D_real, mask losses) and scores (e.g., foreground, composite, background scores) for each batch, aggregates statistics, and logs metrics like ODP (obj...
def val(G_net, D_net, autoencode, back_real, loader, device, writer, imgs_dir, epoch): start = time.time() G_net.eval() D_net.eval() autoencode = False # DO NOT attempt to reconstruct at evaluation time! # Visualize dataset & model examples mbatch = next(iter(loader)) grid = make_grid_m...
def init_logger(OUTPUT_DIR): log_file = OUTPUT_DIR+'train.log' from logging import getLogger, INFO, FileHandler, Formatter, StreamHandler logger = getLogger(__name__) logger.setLevel(INFO) handler1 = StreamHandler() handler1.setFormatter(Formatter("%(message)s")) handler2 = FileHandler(fil...
This code trains a CustomResNext model for a classification task using the provided data loaders. It initializes a model, optimizer, and scheduler, then iterates over epochs to train and validate the model. The training loop calculates loss, validates predictions, updates the scheduler, and logs metrics like loss and s...
def train_loop(train_loader, valid_loader, valid_labels, OUTPUT_DIR): LOGGER = init_logger(OUTPUT_DIR) LOGGER.info(f"========== Started training ==========") # ==================================================== # model & optimizer # ==================================================== model =...
def get_last_epoch(model_path): # Load existing model if possible (in case training was interrupted) & return path for try_epoch in range(5000, -1, -1): load_path = model_path.format(try_epoch) if os.path.exists(load_path): print('Found existing model at epoch: {}'.format(try_epoch +...
This function trains and validates generator (G_net) and discriminator (D_net) networks for a specified number of epochs. It resumes training from existing checkpoints if available, loads pre-trained UNet weights if starting fresh, and saves model states periodically. Validation tracks Object Discovery Performance (ODP...
def train_val_epochs(G_net, D_net, train_loader, val_loader, device, writer, imgs_dir, optimizer_G, optimizer_D, scheduler_G, scheduler_D, num_epochs, path_G, path_D, autoencode, back_real): # Create directories if needed if not(os.path.exists(Path(path_G).parent)): os.makedirs(Path...
def get_transforms(*, data): if data == 'train': return Compose([ # Resize(CFG.size, CFG.size), RandomResizedCrop(CFG.size, CFG.size, scale=(0.85, 1.0)), HorizontalFlip(p=0.5), Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, ...
The main task of the code is to train and evaluate machine learning models on multiple datasets by splitting data, creating loaders, training models, and calculating performance scores on test sets, while saving results in designated directories.
def main(): base_train = pd.read_csv("data/Competition_data/train.csv") train_data, test_data = train_test_split(base_train, test_size=0.1) test_dataset = TrainDataset(test_data, train_path="data/Competition_data/train", transform=get_transforms(data='valid')) test_loade...
def auth2_step1(self): """Auth2 step 1 obtain tokens""" _LOGGER.debug("Running Step1 new!") headers = { **loginHeaders, } code1 = ''.join(random.choice(string.ascii_lowercase) for i in range(43)) code_verifier = self.generate_hash(code1) step1_session ...
The main task of the code is to implement an authentication system with retry logic. It executes authentication steps (primarily auth2_step1 and auth2_step2), checks for successful token acquisition, and retries up to 10 times if errors occur. If errors exceed the limit, it raises exceptions. On success, it resets erro...
def auth(self): """New Authentication System """ _LOGGER.debug("New System") _LOGGER.debug(self.errors) # Run Step 1 auth access_tokens = self.auth2_step1() # ibm_urls = self.auth_step1() # if ibm_urls is None: # self.errors += 1 # if se...
def read_token(self): """Read saved token from file""" try: with open(self.token_location, encoding="utf-8") as token_file: token = json.load(token_file) return token except ValueError: _LOGGER.debug("Fixing malformed token") se...
The main task of the code is to acquire and manage access tokens by reading from a file if it exists, validating token expiry, and refreshing tokens (via `auth()` or `refresh_token_func`) when expired or missing. It handles both regular and auto-generated tokens, ensuring valid credentials are available for API/auth op...
def __acquire_token(self): # Fetch and refresh token as needed # If file exists read in token file and check it's valid _LOGGER.debug("Fetching token") if self.save_token: if os.path.isfile(self.token_location): data = self.read_token() self.to...
def __acquire_token(self): # Fetch and refresh token as needed # If file exists read in token file and check it's valid _LOGGER.debug("Fetching token") if self.save_token: if os.path.isfile(self.token_location): data = self.read_token() self.to...
The main task of the code is to retrieve vehicle messages from an API. It first acquires an authentication token, sends a GET request, and returns parsed messages if the response is successful (status 200). If authentication fails (status 401), it re-authenticates, retries the request, and returns the messages if succe...
def messages(self): """Get Vehicle messages from API""" _LOGGER.debug("Getting Messages") self.__acquire_token() response = self.get_messages() if response.status_code == 200: result = response.json() return result["result"]["messages"] # _LOGG...
def __acquire_token(self): # Fetch and refresh token as needed # If file exists read in token file and check it's valid _LOGGER.debug("Fetching token") if self.save_token: if os.path.isfile(self.token_location): data = self.read_token() self.to...
The main task of the code is to retrieve a list of vehicles from an account by handling authentication and retrying on specific HTTP status codes (401 and 403). It first acquires a token, fetches vehicle data, and returns the JSON result if the response is successful (status 207). If unauthorized (401), it re-authentic...
def vehicles(self): """Get vehicle list from account""" self.__acquire_token() response = self.get_vehicles() if response.status_code == 207: result = response.json() return result if response.status_code == 401: self.auth() respo...
def parse(puzzle_input): """Parse input""" data = [[int(v) for v in s] for s in puzzle_input.split('\n')] return data def part1(data): """Solve part 1""" gamma_code = (sum(np.array(data))*2/len(data)).astype(int) gamma, epsilon = (bin2dec(code) for code in (gamma_code, 1-gamma_code)) re...
The code solves a puzzle by parsing the input data and computing two separate solutions using `part1` and `part2` functions. It returns both results as a tuple. The primary task is to process the input, split it into two parts, and generate answers for each part of the puzzle. Your return
def solve(puzzle_input): """Solve the puzzle for the given input""" data = parse(puzzle_input) solution1 = part1(data) solution2 = part2(data) return solution1, solution2
def _get_encoding(self, file): rawdata = open(file, 'rb').read() enc = chardet.detect(rawdata) file_encoding = enc['encoding'].lower() return file_encoding def _normalize_encoding(self, file, enc_old, enc_new): # creates temporary file and converts it's encoding to utf-8 ...
This code shifts the timing in subtitle files (.srt or .sub) by specified hours, minutes, seconds, and milliseconds. It converts the file encoding to UTF-8, creates a temporary file, reads and adjusts timestamps, generates a new shifted subtitle file, and deletes the temporary file.
def shift(self, filename, hours, minutes, seconds, milliseconds): # resyncs file by given time enc_old = self._get_encoding(filename) self._normalize_encoding(filename, enc_old, "utf-8") temp_filename = f"temp_{filename}" # convert time to milliseconds millis = self._time...
def compileScript(func): global msc, refs, localVars, localVarTypes localVars = [x.name for x in func.decl.type.args.params] if func.decl.type.args != None else [] localVarTypes = dict([(x.name, x.type.type.names[-1]) for x in func.decl.type.args.params] if func.decl.type.args != None else []) argCount ...
The code compiles an AST by validating global variables (no initializers, no redeclaration) and functions (no redeclaration), collecting their types, compiling function definitions into scripts, resolving references, and writing the result to a file.
def compileAST(ast): global args, msc, refs refs = FileRefs() msc = MscFile() for decl in ast.ext: if isinstance(decl, c_ast.Decl): if decl.init != None: raise CompilerError("Error at %s: Global Variables cannot have an initial value, instead include the declaration i...
def getPoints(matrix): startPoint = (0, matrix[0].index(".")) endPoint = (len(matrix) - 1, matrix[-1].index(".")) points = [startPoint, endPoint] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == "#": continue neighbors = 0...
The code reads a grid from a file, identifies start/end points and obstacles, constructs a graph representation, and uses depth-first search (DFS) to find a path from the start to the end point in the maze.
def solve(filename): input = open(filename, 'r').read().splitlines() matrix = [[value for value in row] for row in input] startPoint, endPoint, points = getPoints(matrix) graph = buildGraph(points, matrix) return dfs(startPoint, endPoint, graph, set())
def __loadImgs(self): imgSize = self.info.IMGSIZE img = Image.open(path.join("media", "wumpus.png")) img.thumbnail(imgSize, Image.ANTIALIAS) self.__wimg = ImageTk.PhotoImage(img) imgSize = self.info.IMGSIZE img = Image.open(path.join("media", "deadwum.png")) img.t...
This code initializes a graphical interface component by creating a Tkinter container frame with fixed dimensions, setting its grid layout, positioning an agent at a specific coordinate, defining its initial direction, and loading images, widgets, and world elements for a grid-based simulation or game.
def __onInit(self): wsize = self.info.size * 90 self.__container = tk.Frame( self.__tk, width=wsize, height=wsize + 10, bg="#ffffff" ) self.__container.grid_propagate(0) self.__container.grid(row=1, columnspan=self.info.size, pady=5, padx=5) self.__x, self.__y...
def pprint(string, level): delim = '-' + '-' * (level) * 2 print(delim,'\n',string) def run_filter(self): if not self.current_timestep_jedi_obs_found: print("jedi_obs_in does not exist, not running filter") return pprint('Running JEDI filter', 2) cd(self.workflow_...
The code executes a cycling process from a start time to an end time. It repeatedly runs filtering, restart incrementing, ensemble execution, and cycle preparation (with advancement) until the current time reaches the end. The process logs start/end messages and iteratively processes tasks within the defined time frame...
def cycle(self): pprint("Starting Cycling Process", 1) print(" starting at", self.time.start) while self.time.current < self.time.end: self.run_filter() self.increment_restart() self.run_ensemble() self.prep_cycle(advance=True) print(" Endi...
def jedi_obs_init(self): self.jedi_obs = [] for obs in self.jedi_yaml.yaml['observations']['observers']: self.jedi_obs.append(wf.Obs(self.obs_dir, obs, self.time)) self.update_jedi_yaml_obs() def prep_cycle(self, advance): cd(self.workflow_work_dir) if advance: ...
The function `setup_experiment` initializes an experiment by setting dates for land surface and hydrological files, copying necessary files from either past ensemble members (if `precyclerun` is True) or restart directories, preparing the cycle without advancing time, and setting up the WRFHydroPy framework for simulat...
def setup_experiment(self, precyclerun=False): self.lsm_file.set_date(self.time.current) self.hydro_file.set_date(self.time.current) self.jedi_obs_init() if not os.path.isdir(self.workflow_work_dir): os.mkdir(self.workflow_work_dir) # -- collect starting files ...
def pprint(string, level): delim = '-' + '-' * (level) * 2 print(delim,'\n',string) def read_yaml_experiment(self): experiment = self.workflow_yaml.yaml['experiment'] self.name = experiment['name'] self.num_p = experiment['num_p'] self.compiler = self.parse_compiler(experiment['c...
The main task of the code is to read and process multiple YAML configuration files for a workflow, initializing components like experiments, time settings, JEDI, increments, and WRF-Hydro. It collects YAMLs/JSONs, parses their contents, and sets up the workflow's structural and operational parameters for subsequent pro...
def read_yamls(self): pprint("Reading yamls", 2) self.workflow_yaml = wf.YAML_Filename(self.workflow_yaml_f) self.read_yaml_experiment() self.read_yaml_init() self.read_yaml_time() self.read_jedi_yaml() self.read_increment_yaml() self.collect_yamls_and_jso...
def pprint(string, level): delim = '-' + '-' * (level) * 2 print(delim,'\n',string) def run_ensemble(self): pprint('Running ensemble WRF-Hydro', 2) cd(self.workflow_work_dir) ensemble = wrfhydropy.EnsembleSimulation() ensemble.add(self.simulation) ensemble.replicate_membe...
The main task of the code is to execute a pre-cycle process in a simulation framework. It runs an ensemble, updates the time status, initializes the experiment with pre-cycle settings, and prepares the cycle without advancing. This ensures initial conditions and configurations are set before the main cycle begins, typi...
def precycle(self): if self.time.pre_wrf_h: # else read from restart pprint("Starting Pre-Cycle Process", 1) self.run_ensemble() self.time.pre_wrf_h_done() self.setup_experiment(precyclerun=True) self.prep_cycle(advance=False) pprint("Endin...
def pprint(string, level): delim = '-' + '-' * (level) * 2 print(delim,'\n',string) def parse_commandline_args(self, args): if len(args) > 1: self.workflow_yaml_f = args[1] else: print("ERROR: pass jedi_workflow yaml in command line") sys.exit() def get_resour...
The code initializes a workflow system by parsing command-line arguments, loading resource information, reading YAML configurations, setting up the experiment, and logging initialization status. It records the start time, handles hardcoded resource details, and outputs setup details for workflow execution.
def init(self, args): pprint("Initializing Workflowpy", 1) self.start_time = py_time.time() self.parse_commandline_args(args) self.get_resource_info() # todo: one node hard coded self.read_yamls() self.setup_experiment() self.print_setup() pprint("Finished...
def pprint(string, level): delim = '-' + '-' * (level) * 2 print(delim,'\n',string) def init(self, args): pprint("Initializing Workflowpy", 1) self.start_time = py_time.time() self.parse_commandline_args(args) self.get_resource_info() # todo: one node hard coded self.read...
The code initializes a workflow by setting up the environment with given arguments, performing pre-processing steps, executing the main cycle of operations, and finalizing the process. It logs the start of the workflow and sequentially calls methods to initialize, pre-process, run the core cycle, and conclude the workf...
def __init__(self, args): pprint('Starting Workflowpy', 0) self.init(args) self.precycle() self.cycle() self.end()
def clock(self): """ Starts a clock that displays the current time in the central timezone. """ # create a function to get the current time in central timezone def get_central_time(): """ Gets the current time in central timezone. Returns ...
This code initializes a GUI interface by setting up the user interface and connecting various buttons to specific functions. It links the reset button to a reset method, navigation buttons to a next_page function, and arithmetic/operation buttons to a determine_function method, enabling interaction with mathematical op...
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.clock() self.reset_pushButton.clicked.connect(lambda: self.reset()) self.pushButton_page_1.clicked.connect(self.next_page) self.pushButton_page_2.clicked.connect(self.next_page...
def patch_moverscore_v2(model: str): # The moverscore_v2 model is loaded when the module is being imported # If moverscore_v2 was previously imported with a different model, # we have to forcibly reload it. os.environ["MOVERSCORE_MODEL"] = model import moverscore_v2 if moverscore_v2.model_name ...
The function `evaluate_moverscore` computes the **Word Mover's Score (WMS)** metric for evaluating the similarity between candidate sentences and their reference lists. It processes batches of inputs, generates IDF dictionaries for candidates and references, and applies the `word_mover_score` algorithm in parallel. The...
def evaluate_moverscore( candidates: List[str], references: List[List[str]], model: Optional[str] = None, batch_size: int = DEFAULT_BATCH_SIZE, ) -> List[float]: """ Compute moverscore metric for a batch of sentences. params: - cands : List[str] - refs List[List[str]] ou...
def full_model(summary = True): input_img = Input(shape=(m, n, 1)) generator = generator_model(input_img) feat = feat_model(generator) #model = Model(input=input_img, output=[generator, feat], name='architect') model= Model(name="image",inputs=input_img,outputs=[generator, feat]) model.summary()...
The code defines a function `evalfn` that loads a pre-defined neural network model, compiles it with MAE loss and Adam optimizer, trains it on the 'zubud' dataset for 5 epochs, and prints the accuracy. It optionally loads provided weights before training. The main task is to evaluate model performance on the dataset by...
def evalfn(weights=None): gen_start_time = time.time() model = full_model() model.compile(loss='mae', optimizer='adam' , metrics=['accuracy','mse']) #mae, mse if weights is not None: model.load_weights(weights) X,Y,W = get_batch(1, dataset='zubud') history = model....
def get_sha256(s): return hashlib.sha256(s.encode('utf-8')).hexdigest() def generate_some_flag(): # [0-9A-Z]{31}= flag = [] for i in range(31): flag.append(random.choice(flag_alphabet)) flag.append('=') return ''.join(flag) def get_session_with_retry( retries=3, backoff_...
(The code tests a service's functionality by creating a user with a generated nickname and password, authenticating, and performing actions like creating posts and liking them. It verifies service responses, handles timeouts, and raises exceptions for errors, ensuring the service correctly processes user interactions a...
def check(hostname: str) -> None: try: nickname = 'user-' + str(uuid.uuid4()) password = str(uuid.uuid4()) password_sha256 = get_sha256(password) flag = generate_some_flag() log.info(f">>>>> {nickname} with password {password} and flag {flag}") session = get_session...
def get(hostname: str, flag_id: str, flag: str) -> None: try: response = get_session_with_retry().get( f"http://{hostname}:{TB_API_PORT}/api/users", headers={TB_AUTH_HEADER: flag_id}, timeout=3 ) log.debug(f'response: \ncode: {response.status_code}\nheade...
This code processes command-line arguments to execute different actions (get, put, check, attack, run) on a target host. It calls corresponding functions for each command, handles errors with specific return codes, and prints results or errors. The function returns 101 on success, or error codes for exceptions like inv...
def main(args: argparse.Namespace, usage: Callable[[], None]) -> int: try: if args.command == "get": get(args.host, args.flag_id, args.flag) elif args.command == "put": flag_id = put(args.host, args.flag) print("flag_id: " + flag_id) elif args.command == "...
def gen_payload_status( session_id: str = None, client_id: str = None, shop_id: str = None, status: int = None, max_clients: int = 1, max_shops: int = 1, ) -> dict: session_id_value = gen_session_id() if session_id is None else session_id payload = { "ts": _gen_timestamp(), ...
The function `gen_payload_basket` generates a dictionary payload for a basket, combining status data from `gen_payload_status` with SKU details, quantity, and unit price. It uses default values, generates SKUs if none are provided, and ensures compliance with maximum limits for clients, SKUs, and shops.
def gen_payload_basket( session_id: str = None, client_id: str = None, shop_id: str = None, sku: str = None, qty: int = 1, max_clients: int = 1, max_skus: int = 1, max_shops: int = 1, ) -> dict: payload = gen_payload_status( session_id=session_id, client_id=client_id,...
def initialize_parser(): """Sets up an argparse.ArgumentParser object with desired command line options.""" parser = argparse.ArgumentParser(description="Simulate a user study using LLMs.", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--number_users', default=50, type=int, ...
The code's main task is to set up and conduct simulated interviews by parsing command-line arguments, generating user profiles (default or from CSV data), selecting questions (automatically, manually, or all), and either simulating interviews with reasoning methods or generating agreement scenarios based on user inputs...
def main(): """Sets up and conducts interviews.""" # ------------------------------------- parse arguments -------------------------------------------- parser = initialize_parser() args = parser.parse_args() # ----------------------------------------- profiling -------------------------------...
def get_handicap(self): """ Function that updates the handicap """ to_par_list = [] with open('round_history.csv', 'r', newline="") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) for line in csv_reader: ...
The main task of the code is to initialize a GUI application by setting up UI components, connecting button interactions to corresponding functions (e.g., navigating between pages, handling score posting, and managing data), and configuring initial states such as displaying buttons, hiding error messages, and initializ...
def __init__(self): """ Function that initializes the starting values and button functionalities """ super().__init__() self.setupUi(self) # Showing Buttons self.button_home.show() self.button_post_score.show() self.button_stats.show() ...
def _get_stations_raw(self, path): """ get stations file from ftp """ files = list(ftp_list(self.ftp, path)) stations_file = [f.strip() for f in files if f.endswith('.txt')][0] return ftp_get_file(self.ftp, stations_file).getvalue() def _parse_stations(self, data, limit = None): ...
The main task of the code is to import and parse station data from a specified source, generate Voronoi regions for spatial analysis, and yield parsed station objects. It decodes station files, processes data, extracts regions using Voronoi diagrams, and outputs the number of imported stations.
def do_import(self, limit = None): print("Importing from %s (%s)\n" % (self.host, self.path)) # station file is iso8859 encoded data = self._get_stations_raw(self.path).decode("iso-8859-1").encode("utf-8") # parse stations, download each zip, unpack it and parse data print("Pars...
def _flatten_batch(batch: pa.RecordBatch) -> Generator: for i, field in enumerate(batch.schema): array = batch.column(i) yield from _flatten_struct_array(field, array) def _find_first_nonnull(xs: list[T | None]) -> T | None: return next((x for x in xs if x is not None), None) def _unflatten_batc...
This function constructs a final Apache Arrow RecordBatch by combining original and user-modified data. It flattens the input batch, processes field updates with type inference, ensures row alignment by padding missing values, and reassembles the data into a structured format.
def finish(self: "_ResultsBuffer") -> pa.RecordBatch: output_data: Dict[str, Tuple[pa.Field, pa.Array]] = {} original_fieldnames = set() # Construct flattened output batch. This implicitly handles deleted # fields as well, since those won't have any recorded output values: input_...
def class_is_instrumented(instrumented_class: Type) -> bool: """Check if a class has already been instrumented.""" return getattr( instrumented_class, _mangled_instrumented_boolean_attribute_name(instrumented_class), False, ) def _instrument_method( tracer: Tracer, instrument...
(The function instruments specified classes by wrapping their `run` methods with tracing capabilities using a provided `TracerProvider`. It conditionally instruments `ActionExecutor` and `ValidationAction` classes, applying method-level tracing with module-specific tracers and attribute extractors. If not already instr...
def instrument( tracer_provider: TracerProvider, action_executor_class: Optional[Type[ActionExecutorType]] = None, validation_action_class: Optional[Type[ValidationActionType]] = None, ) -> None: """Substitute methods to be traced by their traced counterparts. :param tracer_provider: The `TracerPro...
def _get_sub_token(self) -> _Token: start = self.index self.eat('{') nopen = 1 comma = None while nopen > 0: c = self.eat() if c is None: self._raise_parsing_error('Pattern ends with unterminated {{ from index {}'.format(start)) ...
This method identifies the next token in a stream by checking the current character. If the character is '{', '%', or in a regex-only set, it delegates to specialized token retrieval methods. Otherwise, it returns a string token. The function handles EOF, sub-token, group-token, regex-token, and string-token cases, ret...
def next_token(self) -> _Token: if self.curr_char is None: return _Token(_TokenType.EOF, '', '') if self.curr_char == '{': return self._get_sub_token() if self.curr_char == '%': return self._get_group_token() if self.curr_char in self._regex_only_ch...
def identify_target_map() -> str: # return target map key from config-file.json try: with open('config-file.json') as f: config = json.load(f) except: print('Error: config-file.json not found') sys.exit(1) return config['target-map'] def collect_logs(target_map: str) ...
The main task of the code is to render a specified map by identifying the target map, collecting logs, rendering nodes, and generating the map visualization. It handles command-line arguments for force rerendering (which clears `rendered_nodes.json`) and determines whether to render PDFs. The process involves logging, ...
def main() -> None: # args: force rerender of all nodes # if force rerender, clear rendered_nodes.json # args: render pdfs # which map are we rendering? target_map = identify_target_map() collect_logs(target_map) render_nodes(target_map) draw_map(target_map)