dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def make_input(self, x, y, fx, fy, snake, direction): input = [] # look in direction where snake is moving (new_x, new_y), _ = self.next_position_direction(x, y, direction, 1) dir_x, dir_y = new_x - x, new_y - y input.extend(self.look_in_direction(x, y, dir_x, dir_y, fx, fy, snak...
The main task of the code is to use a neural network to determine the next movement direction for a snake in a game. It processes input features like the snake's position, food location, and direction using a multi-layer perceptron with ReLU activations, outputs a probability distribution via softmax, and returns the d...
def decision_from_nn(self, x, y, snake, direction): closer_to_food = True fx, fy = self.nextFood input = self.make_input(x, y, fx, fy, snake, direction) input = np.array(input) # feed forward output = input for i in range(len(self.weights) - 1): output...
def textract_handler(event, context): try: body = json.loads(event['body']) source_type = body['source_type'] if not source_type: return { "statusCode": 400, "body": json.dumps({"error": "Missing or invalid 'source_type' in the request."}) ...
This Lambda function routes requests to handle AWS service integrations based on the 'action' parameter. It processes actions like text extraction (textract), sentiment analysis (comprehend), text-to-speech (polly), audio transcription, image recognition (rekognition), and SageMaker inference. It validates required inp...
def lambda_handler(event, context): logger.info(f"Received event: {json.dumps(event)}") body = json.loads(event['body']) action = body.get('action') if action == 'textract': return textract_handler(event, context) elif action == 'comprehend': text = body.get('text') if ...
def ethernet_frame(data): """ Unpack the ethernet layer Input: a internet package captured by socket in form of bytes() Return: source mac address, destination mac address, protocol, content of ethernet frame """ dest_mac, src_mac, protocol = struct.unpack("! 6s 6s H", data[:...
This code processes network packets by unpacking Ethernet, IP, and TCP layers to reconstruct HTTP traffic. It checks for valid protocols (Ethernet 8, IP 6/17), identifies TCP port 80 (HTTP), and assembles HTTP data using source/destination IPs, ports, sequence numbers, and packet payloads. The thread continuously deque...
def run(self): """ The main responsabilities of the thread is to pop a internet package from the deque unpack all the layers: ethernet, ip and tcp. Extract the content and reconstruct the original http trafic. """ global queue global count while len(queu...
def str_block(ch): res = 16*(ord(ch[0])-ord('f')) + 1*(ord(ch[1])-ord('f')) return res def byte_str(k): res = "" res += dict[int(k/16)] n = k%16 res += dict[n] return res def applyEAEAE(plain, A, E): res = [0]*8 for i in range(0, len(plain)): res[i] = cal_powr(plain[i], E[i])...
The code decrypts a password by iterating through possible byte values (0-127), constructing candidate strings, encrypting them, and comparing the result to the input's encrypted blocks. It builds the decrypted password byte-by-byte, appending valid bytes to `decrypted_password` and storing their numeric values in `byt...
def Decrypt(password): byte_password = [] for i in range(0, len(password), 2): byte_password.append(str_block(password[i:i+2])) decrypted_password = "" byte_dp = [] for i in range(0, len(byte_password)): for j in range(0, 128): check = decrypted_password + byte_str(j) ...
def str_to_bin(input_str): result = "" for i in input_str: result += "{:0>4b}".format(ord(i) - 102) return result def bin_to_str(input_str): result = "" for i in range(0,len(input_str),4): result += chr( ord('f') + int(input_str[i:i+4],2) ) return result def encrypt(n,key56,roun...
The function `brute_force` attempts to recover a missing portion of a 56-bit key by exhaustively testing all possible combinations of the unknown bits (marked as '#') in the partial key. It iterates through every possible binary value for the unknown bits, constructs candidate keys, encrypts the given plaintext using e...
def brute_force(partial_key56,plaintext,ciphertext ): unk_bits =[] for i,c in enumerate(partial_key56): if c == '#': unk_bits.append(i) final_key = "" l = len(unk_bits) for i in range(2**l): b = "{:0>14b}".format(i) temp_k = partial_key56.copy() f...
def add_page_metrics_to_database(self): page_metrics = models.PageMetrics( xe_id=self.get_integer("id"), saves=self.get_integer("saves"), visits=self.get_integer("visits"), ) page_metrics.save() return page_metrics def add_image_urls_to_database(self):...
The code saves data to a database only if no existing entry with the same property ID and latest modification date exists. It first adds page metrics and image URLs, then checks for duplicates. If no duplicate is found, it inserts the new data; otherwise, it returns False.
def save_to_database(self, data_load: DataLoad): if self.details is None: return False # for every run we save the current page metrics (clicks/saves) self.add_page_metrics_to_database() # we also check the list of images and add any new ones self.add_image_urls_to_...
def assign_complement_ref(self, arg, time_ref): el = arg['elems'][0] obj_ref = "" if 'template_result' in el and el['template_result'] == "NP": obj_ref = self.check_ref(el, time_ref) elif 'template_result' in el and el['template_result'] == "PronP": obj_ref = sel...
This function assigns object references by recognizing entities, handling complements, and updating references based on templates. It checks for specific formulas (e.g., "SVC"), assigns IDs for nouns (NP) or pronouns (PronP), and recursively processes nested elements. It updates the argument with references, appends ID...
def assign_obj_ref(self, arg, time_ref): # one thing - recognize objects # another thing - add info from complements as additional refs if "formula" in arg and arg['formula'] == "SVC": arg = self.assign_complement_ref(arg, time_ref) if 'reference_obj_id' not in arg and 'templ...
def get_timestamp(self, arg): key = str(uuid.uuid4()) time_object = {} time_object['sid'] = arg['sid'] named_tuple = time.localtime() # get struct_time # time_string = time.strftime("%m/%d/%Y, %H:%M:%S", named_tuple) # result = time.strptime(time_string, "%m/%d/%Y, %H:%M...
This function processes a sentence by assigning timestamps and object references. If the sentence is interrogative, it stores the question, retrieves an answer, and sends it via a message. Otherwise, it stores the sentence for later use. Data is saved to JSON files for persistence.
def process_sentence(self, sentence_info): sentence_info = self.get_timestamp(sentence_info) sentence_info = self.assign_obj_ref(sentence_info, sentence_info['timestamp']) # print("Sentence stored: " + str(sentence_info)) # print("Objects: " + str(self.objects)) if sentence_info[...
def work(self): while(True): worktime = round(time.time())+5 num = round(time.time()) while(round(time.time()) <= worktime): if round(time.time()) == num: pass else: print(round(worktime) - round(time.time())); time.sleep(1) self.go...
This code handles user input to control a game's actions, offering options like working, viewing stats, battling, or saving/loading progress. It triggers specific methods based on commands, includes debug options for testing, and manages player health for certain actions.
def input(self): i = input('\nWhat would you like to do next? (type "help" for options)\n> ') if i == 'help': print('\nOPTIONS:\nwork\nstats\nstore\nbattle\ntournament\nsave\nload\n') elif i == 'work': self.work() elif i == 'stats': self.stats() elif i == 'store': self.store() ...
def get_file_name(caption): file = filedialog.askopenfile(parent=root,mode='rb',title=caption) if file != None: data = file.read() #file.close() print (' I got %d bytes from this file.' % len(data)) return file def build_bounding_box(pts): min_x = pts[0][0] max_x = min_x min_y = ...
This code generates drone flight paths for aerial surveys by reading boundary coordinates, calculating necessary parameters like altitude and image overlap, and creating waypoints using a conformal map method. It processes input files, computes bounding boxes, checks geometric validity, and outputs flight plans with op...
def problem_1(): # get boundary file print (' Please browse for border point file') border_points_file = get_file_name(' Please browse for border point file ') bpf_name = border_points_file.name k = 0 # read boundary points gps coordinates latitude = 0 longitude = 0 boundary_points =...
def read_data(): ''' Read the train, dev, and test datasets ''' dev_file = "/22m1079/regression/data/dev.csv" dev_data = pd.read_csv(dev_file) dev_target = dev_data['1'].copy() dev_input = dev_data.drop('1', axis=1) dev_target = np.reshape(np.array(dev_target), (len(dev_target), 1)) dev_...
The main task of the code is to train a neural network with 4 layers of 7 units each using specified hyperparameters (100 epochs, batch size 64, learning rate 0.01, L2 regularization λ=0.1) on training data, validate it on development data, and generate test predictions. The code reads dataset splits, initializes the n...
def main(): # Hyper-parameters max_epochs = 100 batch_size = 64 learning_rate = 0.01 num_layers = 4 num_units = 7 # [7,7,7,7] lamda = 0.1 # Regularization Parameter train_input, train_target, dev_input, dev_target, test_input = read_data() net = Net(num_layers, num_units) opti...
def read_data(): ''' Read the train, dev, and test datasets ''' dev_file = "/22m1079/regression/data/dev.csv" dev_data = pd.read_csv(dev_file) dev_target = dev_data['1'].copy() dev_input = dev_data.drop('1',axis=1) dev_target = np.reshape(np.array(dev_target),(len(dev_target),1)) dev_input = np.array(...
The main task of the code is to train a neural network model with specified hyperparameters (e.g., 4 layers, 9 units, 150 epochs) on a dataset, using PCA-reduced features (80 components) and L2 regularization (λ=0.1). It loads training/validation/test data, initializes the model and optimizer, trains the network with b...
def main(): # Hyper-parameters max_epochs = 150 batch_size = 64 learning_rate = 0.01 num_layers = 4 num_units = 9 lamda = 0.1 # Regularization Parameter Up_c = 4 per_x_epoch = 2 NUM_FEATS_pc = 80 # number of pca components chosen train_input, train_target, dev_input, dev_target, test_input = rea...
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def display_menu(stock_manager): clear_screen() print("Menu") print("-----------------------------------------") # Get snacks in different categories and display them categories = ["Snacks", "Beverages", "Desserts"] fo...
The main task of the code is to provide a menu-driven interface for the Mumbai Munchies Canteen Management System. It allows users to view the menu, authenticate and place orders, check out (pending implementation), or exit. The function interacts with user, stock, and canteen managers to handle operations like authent...
def main_menu(user_manager, stock_manager, sales_analytics, canteen_manager): clear_screen() print("Welcome to Mumbai Munchies - Canteen Management System") print("-----------------------------------------") print("1. View Menu") print("2. Place Order") print("3. Check Out") print("4. Exit")...
def searchSigTag(): getSig() entryList = [] tagList = [] with open('signature_response.json', 'r') as sig_file: for entry in sig_file: entryList.append(json.loads(entry)) if enable_tag_search and enable_group_query: getTag() with open('tag_response.jso...
The main task of the code is to retrieve or prepare data based on conditional flags. It initializes an empty list `x`, clears a JSON file if specified, and assigns `x` the result of `queryHash(getHash())` when `local` is True. The function returns `x`, which may contain data from `queryHash` or remain empty, depending ...
def getData(): x = [] if enable_group_query: searchSigTag() if clean_response_file: with open('response.json', 'w') as f: f.close() if local: # getHash() x = queryHash(getHash()) return x
def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input, verbose...
This function trains a GAN by alternating between training the discriminator on real/fake data and the generator via the GAN model, using batches from the dataset. It tracks discriminator losses for real/fake samples and generator loss, printing progress every 100 batches, and calls a performance summary function after...
def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=100, n_batch=50): acc_real_list, acc_fake_list = [], [] bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_r...
def wake(self): self.send_command("\r\n\r\n") def _read_all(self): return self.send_command(command=None, length_to_read="ALL") def send_command(self, command=None, length_to_read="ALL"): if command: self.last_command = command sleep_time = self.command_object.operation_wait_times[command] if self.command_o...
The main task of the code is to identify the CTD (Conductivity-Temperature-Depth) model by analyzing responses from the device. It wakes the CTD, reads its data, checks for supported models, and creates a corresponding command object. If identification fails, it sends a "DS" command, analyzes its response to guess the ...
def determine_ctd_model(self): try: self.log.debug("Waking CTD") self.wake() ctd_info = self._read_all() # TODO: Is the data returned from wake always junk? What if this is starting up after setting the CTD to autosample, then the server crashes and is reconnecting self.log.debug("CTD responded with {}"....
def _read_all(self): return self.send_command(command=None, length_to_read="ALL") def wake(self): self.send_command("\r\n\r\n") def status(self, status_parts=None): """ Gets and parses the status. Occasionally, there's a race condition where even after checking for new data up front, we can have new data at...
The code reads CTD data and checks if over an hour has passed since the last status update. If so, it wakes the device, updates its status (to refresh battery info), and re-sleeps it—avoiding this if sampling is active and the device can't handle commands during logging. It returns the read data, handling potential sta...
def read_records(self): self.log.debug("Checking for CTD data") data = self._read_all() # this will automatically check for data if (datetime.datetime.now(timezone.utc) - self.last_status).total_seconds() > 3600 and \ ((self.is_sampling is True and self.command_object.supports_commands_while_logging...
def read_records(self): self.log.debug("Checking for CTD data") data = self._read_all() # this will automatically check for data if (datetime.datetime.now(timezone.utc) - self.last_status).total_seconds() > 3600 and \ ((self.is_sampling is True and self.command_object.supports_commands_while_logging...
This function handles commands from a message queue to control monitoring and communication with a CTD device. It processes commands like READ_DATA, STOP_MONITORING, and DISCONNECT, updating flags to stop monitoring, sending commands to the device, and managing the serial connection. It acknowledges messages and logs s...
def interrupt_handler(ch, method, properties, body): """ This function is done as a closure because we want it to be able to access attributes of the class instance namely, the open pipe to the serial port, as well as knowing which COM port we're on so that it can load a RabbitMQ queue with the same name...
def stop_autosample(self): self.log.info("Stopping existing autosampling") self.send_command("STOP", length_to_read=None) self.status() if self.is_sampling is not False: raise CTDOperationError("Unable to stop autosampling. If you are starting autosampling, parameters may not be updated") def send_command(s...
The main task of the code is to configure and initiate autosampling for a CTD sensor, setting parameters like interval and real-time mode, then continuously read and process data samples using a provided handler function. It ensures compatibility with existing sampling states, handles command queues, and supports real-...
def start_autosample(self, interval=60, realtime="Y", handler=None, no_stop=False, max_iterations=None): """ This should set the sampling interval, then turn on autosampling, then just keep reading the line every interval. Before reading the line, it should also check for new commands in a command queue, so it ...
def get_bounding_box_center(pcd): """ Function calculates the oriented bounding box and center of the given point cloud :param pcd: open3D PointCloud object :return: tuple - center and bounding box """ obb = pcd.get_oriented_bounding_box() return obb.get_center(), obb def get_best_candidate(...
The main task of the code is to prepare a dataset for point cloud registration by generating mirrored point clouds from an input PCD file. It computes the bounding box center, determines a symmetry normal using SVD, creates a mirrored version of the point cloud, and extracts FPFH features for both original and mirrored...
def prepare_dataset(voxel_size, filename): """ Function prepared original and mirrored point clouds with their FPFH features :param voxel_size: float :param filename: string, point cloud file, .pcd extension :return: """ # source = o3d.io.read_point_cloud("../generate_dataset/small_damages/p...
def NumData(str): if DataTypes(str)=="int" or DataTypes(str)=="float": return True else: return False def IsArithm(lst): for i in lst: if i in identifiers: x=str(identifiers[i]) lst=lst.replace(i,x) if NumData(str(eval(lst))): return str(eval(lst))...
The code evaluates a comparison expression by identifying operators (e.g., `<`, `>`, `eq`, `noteq`) and operands. It checks if operands are numeric or variables, resolves variables using a dictionary (`identifiers`), and performs the comparison. If operands are valid, it returns `True`/`False` based on the operator. If...
def Comp(str): count=0 op=0 for i in str: if i in Comp_ops: op=i count+=1 if count == 0: if str== "true": return True elif str== "false": return False else: print("Syntax error") return False elif...
def bfs_search(initial_state): """BFS search""" frontier = BFS_queue() frontier.enqueue(initial_state) frontierSet = set() frontierSet.add(tuple(initial_state.getConfig())) explored = set() nodes_expanded = 0 max_search_depth = 0 path = [] ##use a set for this ## max-dep...
The main task of the code is to execute a specified search algorithm (BFS, DFS, or A*) on a puzzle state provided via command-line arguments, track the program's runtime and peak memory usage, and log these metrics to an output file. It initializes the puzzle state, runs the chosen search, records execution time and me...
def main(): search_mode = sys.argv[1].lower() begin_state = sys.argv[2].split(",") tracemalloc.start() begin_state = list(map(int, begin_state)) board_size = int(math.sqrt(len(begin_state))) hard_state = PuzzleState(begin_state, board_size) start_time = time.time() if search_mo...
def assignmentComplete(board): boolean = True for key in board: if int(board[key]) == 0: boolean = False return boolean def select_MRV(board): minimum_remaining_value = "filler" values = [1,2,3,4,5,6,7,8,9] count = 0 ledger = dict() domains = dict() ...
The code implements a backtracking algorithm with MRV (Minimum Remaining Values) heuristic and forward checking to solve a constraint satisfaction problem (e.g., Sudoku). It recursively assigns values to the cell with the fewest options (MRV), checks validity, and propagates constraints. If a valid assignment leads to ...
def backtracking(board): """Takes a board and returns solved board.""" ##implementing this with reference to MRV ##also with forward checking if assignmentComplete(board) == True: solved_board = board return solved_board else: var, domains = select_MRV(board) ...
def setSettingsUI(self): tab_control = ttk.Notebook(self.master, width=self.width-20, height=self.height-120) tab_control.pack(fill=tk.X) self.ch_sel = tk.Frame(tab_control, borderwidth=1, relief='solid') self.st_sel = tk.Frame(tab_control, borderwidth=1, relief='solid') self.f...
This code initializes a settings window in a GUI application. It creates a Toplevel window titled 'SSAVE - Settings', sets its size, assigns a controller for inter-component communication, and initializes various UI panels (settings, channel selection, sleep stage selection, filter settings, epoch size). Finally, it st...
def __init__(self, master, controller): master = tk.Toplevel(master) master.title('SSAVE - Settings') super().__init__(master, 900, 800) self.controller = controller self.setSettingsUI() self.setChannelSelectionPanel() self.setSleepStageSelectionPanel(...
def printDec(msg): print(msg) return horizontal_border = '_' * 50 vertical_border = '|' l = len(horizontal_border) print(horizontal_border) print(' ' * l) msg_part = msg.strip() while len(msg_part) >= l - 4: print(vertical_border + ' ' + msg_part[:l - 4] + ' ' + vertical_b...
The function `extractEpochs` loads or generates epoch-wise EEG data and sleep stage labels. If caching is enabled and precomputed files exist, it directly loads them. Otherwise, it extracts data from annotation files (text or binary) to create epoch-wise representations of EEG signals and corresponding sleep stages for...
def extractEpochs(self): eeg_data_path = f'{self.folder_cache}/{self.sample_name}_eeg.npy' sleep_stage_path = f'{self.folder_cache}/{self.sample_name}_st.txt' if self.use_cache and (os.path.exists(eeg_data_path) and os.path.exists(sleep_stage_path)): self.eeg_data_epoch_wise = np...
def extractEpochs(self): eeg_data_path = f'{self.folder_cache}/{self.sample_name}_eeg.npy' sleep_stage_path = f'{self.folder_cache}/{self.sample_name}_st.txt' if self.use_cache and (os.path.exists(eeg_data_path) and os.path.exists(sleep_stage_path)): self.eeg_data_epoch_wise = np...
This function computes a spectrogram (power spectral density) from EEG data using the multitaper method, with configurable frequency ranges (fmin/fmax) and bandwidth. It leverages caching for efficiency, loads required data if missing, and stores results in a transposed format. The key task is spectral analysis of epoc...
def extractSpectogram(self, fmin=0, fmax=30, nw=2): if not (self.spectogram is None or self.spec_freq is None): return spectogram_path = f'{self.folder_cache}/{self.sample_name}_spec_{nw}.npz' if self.use_cache and os.path.exists(spectogram_path): data = np.load(spectogram_path) ...
def extractEpochs(self): eeg_data_path = f'{self.folder_cache}/{self.sample_name}_eeg.npy' sleep_stage_path = f'{self.folder_cache}/{self.sample_name}_st.txt' if self.use_cache and (os.path.exists(eeg_data_path) and os.path.exists(sleep_stage_path)): self.eeg_data_epoch_wise = np...
The function visualizes sleep data by generating a plot with annotated epochs, optionally including spectrograms and sleep periods. It maps sleep stages to colors, extracts data based on input flags, and saves the resulting visualization as a JPG file in the specified cache directory.
def visualize(self, show_sc=False, show_spec=False): sleep_stage_colors = {Config.WAKE_STAGE:'limegreen', Config.REM_STAGE:'gold', Config.N1_STAGE:'deepskyblue', \ Config.N2_STAGE:'royalblue', Config.N3_STAGE:'darkblue'}#, Config.U_STAGE:'black'}#, 'O':'red', 'NA':'orange'} self.extractEpo...
def load_data(self, loan_input_data_template=None, project_input_data_template=None, loan_input_data_metadata=None, project_input_data_metadata=None, input_data_dir=None): """Load data to FACILITIES_DF and PROJECTS_DF.""" ...
The main task of the code is to initialize a `LoanMatching` object by configuring data paths, dates, and data structures (DataFrames, dictionaries) for loan facilities and projects. It sets up output containers, selected columns, compatibility mappings, and runs initial data loading, preprocessing, and the core matchin...
def __init__(self, dash_config): """Initialize LoanMatching object.""" '''(0) Read Config Data and Define Global Variables''' self.DASH_CONFIG = dash_config self.INPUT_DATA_DIR = self.DASH_CONFIG['data']['input']['dir'] self.OUTPUT_DATA_DIR = self.DASH_CONFIG['data']['output']['...
def parse_args(argv): import argparse parser = argparse.ArgumentParser(description="Recover files from an NTFS volume") parser.add_argument('--sector-size', type=int, help='Sector size in bytes (default: trust filesystem)') parser.add_argument('--cluster-size', type=int, help='Cluster si...
This code recovers files from an NTFS disk image by parsing the Master File Table (MFT), filtering entries based on user-defined patterns, and saving matching files to a specified directory. It reads disk metadata, validates NTFS structure, processes MFT records, and implements error handling for directory creation and...
def main(argv): image_path = input("Enter DD filename:\n") lst = [image_path, '--pattern', '*.*', '--outdir', 'recovered'] args = parse_args(lst) #argv #print(argv) print(args) f = open(args.disk, 'rb') if args.outdir: try: os.makedirs(args.outdir) except OSError...
def parseRow(row): return [c for c in row] def getNumbersAndPos(data): numbers = [] current = None currentPos = [] for i in range(len(data)): for j in range(len(data[i])): c = data[i][j] if c.isdigit(): currentPos.append((i,j)) current ...
The main task of the code is to calculate the sum of all gears in the input data. It processes each row to parse numbers and their positions, then identifies gears using these numbers, and finally returns their total sum.
def answer2(data): data = [parseRow(row )for row in data] numbers = getNumbersAndPos(data) return sum(findGears(data,numbers))
def multiSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1 # Swap if the element found is lesser # than the next elem...
The code groups unranked companies by their count values, creating a list of company groups sorted by weightage. It then sorts these groups using `sortCompanyCat` to return a ranked structure based on company counts, organizing companies into categories with shared count values for prioritization or analysis.
def rank(user_skills, unranked_companies): sorted_company_by_count = multiSort(unranked_companies) # pp.pprint(sorted_company_by_count) company_map_count = [] for company in sorted_company_by_count: if len(company_map_count) == 0: company_map_count.append({"weightage": company["cou...
def recon_criterion(self, input, target): return torch.mean(torch.abs(input - target)) def compute_vgg_loss(self, vgg, img, target): img_vgg = vgg_preprocess(img) target_vgg = vgg_preprocess(target) img_fea = vgg.features(img_vgg) target_fea = vgg.features(target_vgg) ret...
This function updates a generator model in a cycle-consistent GAN framework by computing total loss from reconstruction (image/segmentation), adversarial (GAN), perceptual (VGG), edge, and cross-domain consistency components. It uses encoder-decoder architectures with style vectors, computes gradients via backpropagati...
def gen_update(self, x_a, real_a_seg, x_b, real_b_seg, hyperparameters): self.gen_opt.zero_grad() s_a = Variable(torch.randn(x_a.size(0), self.style_dim, 1, 1).cuda()) s_b = Variable(torch.randn(x_b.size(0), self.style_dim, 1, 1).cuda()) # encode c_a, s_a_prime, c_a_seg = self.ge...
def preprocess_confirmed_cases_input(data): inputdf = data[data[COL_CASES] > 1000] inputdf.loc[:, constants.FLAG_COLUMNS] = inputdf \ .loc[:, constants.FLAG_COLUMNS].fillna(1) inputdf.loc[:, constants.INPUT_COLUMNS] = inputdf \ .groupby(COL_REGION)[constants.INPUT_COLUMNS] \ .transfo...
The code defines a `train` function that processes input data by preprocessing confirmed cases, preparing training data, and returning a trained model. It sequentially applies preprocessing, data preparation, and model training to generate a machine learning model based on the input data.
def train(data): confirmed_cases_input = preprocess_confirmed_cases_input(data) train_data = prepare_train_data(confirmed_cases_input) return train_model(train_data)
def cnt_freq(filename): """ Opens text file and counts the frequency of occurrences of all characters within the file. Args: filename(str): the name of file to be opened Returns: arr: 256 item list with count of every character occurrences """ file = open(fil...
The function encodes a text file using Huffman coding. It reads the input file, generates a frequency list, constructs a Huffman tree, creates binary codes, and writes the encoded data along with a header to an output file. It also produces a compressed version by writing the encoded text with HuffmanBitWriter, ensurin...
def huffman_encode(in_file, out_file): """ Reads a text input file and writes to an output file the encoded version Args: in_file(str): the name of file being read into out_file(str): the desired output name of the file Returns: None """ freq_li...
def parse_header(header_string): """ Parse the header into a list of freqs Args: header_string(str): string of header Returns: list: list of 265 frequencies of the characters """ split_header = header_string.split() list_of_freqs = [0] * 256 for each in rang...
The main task of the code is to decode a Huffman-encoded file by reconstructing the original data. It reads the encoded file, parses the header to extract character frequencies, builds a Huffman tree, and traverses the tree using encoded bits to reconstruct the original string. The decoded string is written to the spec...
def huffman_decode(encoded_file, decode_file): """ Decode the encoded file and output Args: encoded_file(str): name of the encoded file decode_file(str): desired name of output file Returns: None """ try: file = open(encoded_file, 'r') fil...
def _get_session_cookie(request): return request.cookies[SESSION] if SESSION in request.cookies else None def _modify_scheme(orig_uri): if OAUTH_ENV_KEY not in os.environ or os.environ[OAUTH_ENV_KEY] != '1': orig_uri = orig_uri.replace('http://', 'https://') return orig_uri def _respond_with_session_value(res...
This code handles an OAuth2 callback by retrieving user credentials, validating the user's email against an accepted list, and redirecting the user to their original requested URL while setting session and access tokens for authenticated access.
def oauth2callback(): session_cookie = _get_session_cookie(request) state = request.args.get('state') credentials = OauthProvider(state=state).get_credentials( response_url=_modify_scheme(flask.request.url)) email = UserEmailRetriever(credentials=credentials).get_email() if not email: ...
def remove_stopwords(tokenized_data): en_stop = get_stop_words('en') stopped_tokens = [token for token in tokenized_data if token not in en_stop] return stopped_tokens def save_lda_model(self, lda_model, corpus, dictionary, index): index.save(self.lda_path + 'index.lda') pyLDA...
The main task of the code is to build an LDA (Latent Dirichlet Allocation) topic model from a corpus of text data. It tokenizes and preprocesses input documents, creates a dictionary and bag-of-words corpus, trains an LDA model with specified topics, generates document similarity indices, and saves the model and result...
def build_lda_model(self, data, docs, n_topics=5): texts = [] tokenizer = RegexpTokenizer(r'\w+') for d in tqdm(data): raw = d.lower() tokens = tokenizer.tokenize(raw) stopped_tokens = self.remove_stopwords(tokens) stemmed_tokens = stopped_toke...
def generate_key_pair(): """ Generates a pair of RSA keys (private and public). Returns: private_key: object: RSA private key object. public_key: object: RSA public key object. """ private_key = RSA.generate(2048) public_key = private_key.publickey...
The code initializes a Node object by setting up network parameters, generating cryptographic keys, creating a node address, starting a listener for incoming connections, and broadcasting a "new_node" message to known nodes to announce its presence in the network.
def __init__(self, **options): """ Initializes a Node object with the given options. Generates a key pair for the node and creates an address from the public key. Starts listening on the given port and accepts incoming connections. Sends a "new_node" message to all known nodes. ...
def id(self): """ Returns the id of the node, which is a tuple containing the host and port. :return: tuple """ return self.host, self.port def _send(self, data, data_type, receiver=None, sender=None, sender_name=None, data_hash=None, timestamp=None): """ Constru...
This method processes incoming network data by parsing JSON payloads, checking for duplicates via hash, forwarding data to intended recipients if necessary, and routing valid data to specialized handlers based on its type (e.g., transactions, blocks, node updates). It also logs invalid payloads and prevents reprocessin...
def _handle_incoming_data(self, payload, addr): """ Handles incoming data from other nodes in the network. :param payload: str - the data payload received from the sender node :param addr: tuple - the IP address and port of the sender node """ try: # Parse pa...
def input_to_grid(lines): grid = [ [int(x) for x in list(y)] for y in lines] grid = pad_grid(grid, 11) return grid def find_low_points(grid): lowpoints = [] for y in range(0, len(grid)): for x in range(0, len(grid[y])): if grid[y][x] < grid[y-1][x] and grid[y][x] < grid[y+1][x] a...
The code processes a grid of tubes to identify and calculate the product of the three largest basin sizes. It converts input data into a grid, locates low points, determines surrounding basins, and returns the product of the three largest basin sizes. Your return
def part2(tubes): tubes = input_to_grid(tubes) lp = find_low_points(tubes) basins = find_basins(tubes, lp) return prod(sorted(basins)[-3:])
def nu_N_K(N, K): """ Follow notation from Olshanski, 2013. :param N: :param K: :param x: :return: """ a = sp.MatrixSymbol("a", K, 1) x = sp.MatrixSymbol("x", N, 1) indicators = sp.MatrixSymbol("I", K, N) Va = vandermonde_polynomial(a) cNK = compute_cNK(N, K) Vx =...
This code computes marginal densities for each variable in a probabilistic model by integrating out other variables. It uses symbolic manipulation to simplify the joint density, substitutes symbolic variables, and iteratively performs integration over specified bounds while handling dependencies via indicators. The res...
def marginal_densities(N, K): density, a, x, indicators = nu_N_K(N, K) density = density.doit() simple_density = sp.simplify(density) x_ = sp.symbols(f"x1:{N + 1}") a_ = sp.symbols(f"a1:{K + 1}") density_ = simple_density.subs(dict(zip(x, x_))).subs(dict(zip(a, a_))) marginals = [] fo...
def flexible_log_function(dtype): if dtype is sp.Rational: def log_fn(arg): return np.vectorize(sp.Rational)(np.log(arg)) elif dtype is mpmath.mpf: log_fn = np.vectorize(mpmath.log) elif dtype is gmpy2.mpfr: log_fn = np.vectorize(gmpy2.log) elif dtype is sp.Basic: ...
This function computes the logarithm of expectations or determinants involving eigenvalues, using different modes (moment matrix, modified Vandermonde, direct determinant). It returns values like reciprocal sums, matrix determinants, or polynomial terms, adjusted by constants, depending on the specified mode and parame...
def reciprocal_sum_log_expectation(eigenvalues, K, mode, dtype=None): N = eigenvalues.shape[-1] if K == N: return flexible_log_function(dtype)(np.sum(1 / eigenvalues, -1)) if K == 0: return 0 log_fn = flexible_log_function(dtype) if mode == MODE_MOMENT_MATRIX: analytic = dty...
def to_secret(plain_text, key): plain_text = add_padding(plain_text, 0) for i in range(16 - len(plain_text) % 16): plain_text.join(str(i%10)) salt = aes.encrypt(plain_text, key) hashed_text = hashlib.sha512(plain_text.encode('utf-8') + salt.encode('utf-8')).hexdigest() return hashed_text def...
The main task of the code is to securely add a new website-password entry to a JSON database. It generates a secret key from the website and username, checks if the entry exists, and if not, encrypts the password using an AES key derived from the user's master key. The encrypted password is stored under the user's acco...
def add_web_password(username, password): website = input("Enter Website: ") secret_website = to_secret(website+username, KEY1) with open('db.json', 'r+') as db: data = json.load(db) try: old_password = data[username][secret_website] print("website exists!") ...
def to_secret(plain_text, key): plain_text = add_padding(plain_text, 0) for i in range(16 - len(plain_text) % 16): plain_text.join(str(i%10)) salt = aes.encrypt(plain_text, key) hashed_text = hashlib.sha512(plain_text.encode('utf-8') + salt.encode('utf-8')).hexdigest() return hashed_text def...
The code retrieves a user's password from a JSON database by decrypting it with an AES cipher. It prompts for a website, loads the database, and attempts to fetch the encrypted password linked to the username and website. A master key is generated using the username and input password, which decrypts the password, remo...
def get_password(username, password): website = input("Enter Website: ") with open('db.json') as db: data = json.load(db) try: web_password = data[username][to_secret(website+username, KEY1)] user_master_key = generate_master(username, password) db.close() ...
def to_secret(plain_text, key): plain_text = add_padding(plain_text, 0) for i in range(16 - len(plain_text) % 16): plain_text.join(str(i%10)) salt = aes.encrypt(plain_text, key) hashed_text = hashlib.sha512(plain_text.encode('utf-8') + salt.encode('utf-8')).hexdigest() return hashed_text def...
The function updates a user's password for a specified website in a secure JSON database. It generates a secret key from the website and username, retrieves the user's data, encrypts the new password using AES with a master key derived from the user's password, and stores it. If the website is not found, it returns Fal...
def change_web_password(username, password): website = input("Enter Website: ") secret_website = to_secret(website+username, KEY1) with open('db.json', 'r+') as db: data = json.load(db) try: web_password = data[username][secret_website] new_web_password = input("Ente...
def to_secret(plain_text, key): plain_text = add_padding(plain_text, 0) for i in range(16 - len(plain_text) % 16): plain_text.join(str(i%10)) salt = aes.encrypt(plain_text, key) hashed_text = hashlib.sha512(plain_text.encode('utf-8') + salt.encode('utf-8')).hexdigest() return hashed_text def...
The main task of the code is to update a user's password in a JSON database by encrypting their new password, decrypting their stored web passwords using the old password's master key, and re-encrypting them with the new password's master key. It ensures secure password changes by handling encryption/decryption with AE...
def change_password(username, password): new_password = input("Enter new password: ") secret_username = to_secret(username, KEY1) secret_password = to_secret(new_password, KEY1) with open('db.json', 'r+') as users_file: data = json.load(users_file) data["users"][secret_username] = secret...
def word2vec(self, word): vec = [ord(i) for i in word] return vec def encrypt_block(self, block, key): block_matrix = [[], [], [], []] key_matrix = [[], [], [], []] for i in range(len(block)): block_matrix[i % 4].append(block[i]) key_matrix[i % 4].append(k...
The code encrypts an input word using a key by converting both into vectors, splitting the input into blocks, encrypting each block with the key via `encrypt_block`, and converting the resulting vector to hexadecimal format for output.
def encrypt(self, input_word, key_word): input_vector = self.word2vec(input_word) key = self.word2vec(key_word) output_vector = [] for i in range(int(len(input_vector) / self.block_size)): block = input_vector[i*self.block_size: (i+1)*self.block_size] result = sel...
def hex2vec(self, heximal): vec = [int(heximal[2*i], 16) * 16 + int(heximal[2*i+1], 16) for i in range(int(len(heximal)/2))] return vec def word2vec(self, word): vec = [ord(i) for i in word] return vec def decrypt_block(self, block, key): block_matrix = [[], [], [], []] k...
This code decrypts a hexadecimal input string using a provided key. It converts the input and key into vectors, processes the input in blocks of fixed size, decrypts each block with the key, and combines the results into the final decrypted output string.
def decrypt(self, input_hex, key_word): input_vector = self.hex2vec(input_hex) key = self.word2vec(key_word) output_vector = [] for i in range(int(len(input_vector) / self.block_size)): block = input_vector[i*self.block_size: (i+1)*self.block_size] result = self.d...
def change_password(username, password): new_password = input("Enter new password: ") secret_username = to_secret(username, KEY1) secret_password = to_secret(new_password, KEY1) with open('db.json', 'r+') as users_file: data = json.load(users_file) data["users"][secret_username] = secret...
The code provides a menu-driven interface for password management, allowing users to change their password, add or retrieve website passwords, modify website passwords, or exit. It processes user input to call corresponding functions, updates the password as needed, and returns the updated password or False upon exit.
def user_pad(username, password): print("1) Change password") print("2) Add website password") print("3) Get a website password") print("4) Change a website password") print("5) Exit") choice = input("Enter a choice: ") if choice == '1': password = change_password(username, password...
def drop_piece(grid, col, mark, config): next_grid = grid.copy() for row in range(config.rows - 1, -1, -1): if next_grid[row][col] == 0: break next_grid[row][col] = mark return next_grid def moves_available(self): top_row = self.board[0, :] return [column_index for co...
The main task of the code is to simulate a game move by dropping a piece into a specified column, validate the move's availability, evaluate the heuristic score of the resulting board state, and return the game outcome (win status, score) along with a new game instance for the next player's turn.
def forecast_move(self, col): board = drop_piece(self.board, col=col, mark=self.mark, config=self.config) if not col in self.moves_available(): return True, 2 * F, Game(board, config=self.config, mark=self.mark) won, score = get_heuristic(board, self.mark, config=self.config) ...
def moves_available(self): top_row = self.board[0, :] return [column_index for column_index, value in enumerate(top_row) if value == 0] def drop_piece(grid, col, mark, config): next_grid = grid.copy() for row in range(config.rows - 1, -1, -1): if next_grid[row][col] == 0: bre...
The function `forecast_move` simulates a move in a game by checking if the column is valid, updating the board with the current player's piece, evaluating the heuristic score, and returning whether the move results in a win, the score, and a new game state for the opponent. It aids in decision-making by forecasting out...
def forecast_move(self, col): if not col in self.moves_available(): raise Exception("Impossible move requested") board = drop_piece(self.board, col=col, mark=self.mark, config=self.config) won, score = get_heuristic(board, self.mark, config=self.config) mark = 1 if self.mark...
def builder(request): query = SessId.objects.get(session = session_id(request)) code = SessId._meta.get_field('credential') coda = code.value_from_object(query) http = Http() http = coda.authorize(http) service = build('gmail', 'v1', http=http) return service def getFrom(froma,typea): va...
The code retrieves up to 5 unique email contacts from the user's Gmail account by querying messages filtered by a label (if provided). It extracts 'From' headers, parses email addresses, and avoids duplicates by appending exclusion filters. The result includes a count of contacts, raw 'From' headers, and the applied la...
def GetContacts(request): contacts = [] filterer = '' chara = [] while(len(contacts)<5): print(len(contacts)) service = builder(request) results = service.users().messages().list(userId='me',q=filterer,maxResults=1,labelIds=request.GET.get('label',None)).execute() if resu...
def _check_keydown_events(self, event): """ Respond to keydown events """ if event.key == K_UP and not self.ia_active_right: self.paddle_right.move_up = True elif event.key == K_DOWN and not self.ia_active_right: self.paddle_right.move_down = True elif event.key =...
The function `_check_events` handles user input and game events in a Pygame application. It processes QUIT events to exit the game, checks KEYDOWN/KEYUP events for active gameplay input, and responds to MOUSEBUTTONDOWN events when the game is inactive. The method delegates specific event handling to other functions, en...
def _check_events(self): """ Check the game events """ for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN and self.game_active: self._check_keydown_events(event) if ...
def handle_start(): response = {} response['user'] = '' response['text'] = open_file('start.txt') response['command'] = 'INTRO' return response def handle_intro(request, data): text = data['utterance'] display_name = '' response = {} response['command'] = 'CONTINUE' # Check if ...
The function `handle_command` routes incoming commands to specific handler functions based on the value of `data['command']`. If the command is 'START', it triggers `handle_start()`. For 'INTRO', it uses `handle_intro(request, data)`. Any other command is processed by `handle_conversation(request, data)`, enabling dyna...
def handle_command(request, data): command = data['command'] if command == 'START': return handle_start() elif command == 'INTRO': return handle_intro(request, data) else: return handle_conversation(request, data)
def _fast_liberty_check(self, nb_point): lib = self.liberty_of[nb_point] if lib != NULLPOINT and self.get_color(lib) == EMPTY: return True # quick exit, block has a liberty if self._stone_has_liberty(nb_point): return True # quick exit, no need to look at whole block ...
The main task of the code is to determine if the opponent's block at the given point `nb_point` is captured. It checks if the block has no liberties left by first performing a fast liberty check, then verifying the block's liberty status. The function returns `True` if the block is captured (no liberties) and `False` o...
def _detect_capture(self, nb_point): """ Check whether opponent block on nb_point is captured. Returns boolean. """ if self._fast_liberty_check(nb_point): return False opp_block = self._block_of(nb_point) return not self._has_liberty(opp_block)
def _detect_capture(self, nb_point): """ Check whether opponent block on nb_point is captured. Returns boolean. """ if self._fast_liberty_check(nb_point): return False opp_block = self._block_of(nb_point) return not self._has_liberty(opp_block) def _st...
The code checks if placing a stone of a given color at a specific point on a Go board is legal. It verifies the point is empty, checks for captures of opponent's stones, and ensures the move doesn't result in suicide (no liberties). If invalid, the move is undone and returns False; otherwise, True.
def is_legal(self, point, color): """ Check if the move is legal """ assert is_black_white(color) # Special cases if self.board[point] != EMPTY: return False # General case: deal with captures, suicide opp_color = GoBoardUtil.opponent...
def _detect_capture(self, nb_point): """ Check whether opponent block on nb_point is captured. Returns boolean. """ if self._fast_liberty_check(nb_point): return False opp_block = self._block_of(nb_point) return not self._has_liberty(opp_block) def _st...
This function plays a move of the given color on the specified point in a Go game, checking for legality by ensuring the point is unoccupied, detecting captures of opponent's stones, and preventing suicide moves. If valid, it updates the board, switches the current player, and returns True; otherwise, it raises errors ...
def play_move(self, point, color): """ Play a move of color on point Returns boolean: whether move was legal """ assert is_black_white(color) # Special cases if self.board[point] != EMPTY: raise ValueError("occupied") # General cas...
def update_product_text_area(self): self.product_text_box.delete(1.0, tk.END) # Display the updated product information self.product_list.display_products() products_info = self.product_list.display_products() self.product_text_box.insert(tk.END, products_info) def display_order...
The main task of the code is to create a new order by allowing users to input product IDs/names and quantities, validate inputs, update inventory quantities, manage order limits, and display order details. It ensures no orders exceed the maximum limit, handles errors for invalid inputs or no available products, and upd...
def adding_order(self): # Check if the maximum order limit is reached if self.order_counter >= Warehouse.max_orders: messagebox.showinfo("Order Limit", "Order limit reached. You cannot create more orders.") return if not self.product_list.head: print("No products...
def sample_adult_data(file_name, num_contexts, shuffle_rows=True, remove_underrepresented=False): """Returns bandit problem dataset based on the UCI adult data. Args: file_name: Route of file containing the Adult dataset. num_contexts: Number of contexts to sample. shuffle_rows: If True, rows from origi...
The code initializes and preprocesses datasets for different modes (e.g., 'dbbs', 'neuralucb', 'raw', 'cifar10'). It loads data, normalizes contexts, encodes labels, constructs reward matrices, and sets optimal actions. Specific handling includes OpenML datasets, NaN replacement, one-hot encoding, image normalization, ...
def reset(self, noise_var = 0.): from sklearn.preprocessing import normalize if self.mode == 'dbbs': all_data = np.load(self.dataset_path, allow_pickle=True) context_dim = all_data.item().get('context_dim') self.n_arms = all_data.item().get('num_actions') ...
def freqspace(n): device = n.device # Get the device of the input tensor n n = [n, n] a = torch.arange(0, n[1], 1,device=device) b = torch.arange(0, n[0], 1,device=device) f1 = (a - torch.floor(n[1] / 2)) * (2 / n[1]) f2 = (b - torch.floor(n[0] / 2)) * (2 / n[0]) f1, f2 = torch.meshgrid(f1,...
The code computes the power spectral density (PSD) of atmospheric turbulence, combining turbulence parameters (r0, L0, fR0) and noise variance. It generates frequency grids, calculates turbulence and noise PSDs, scales them, and constructs a dictionary containing the mean atmospheric PSD, sampling parameters, and pupil...
def GetTurbulenceParameters(wfs,resAO,nLenslet,r0,L0,fR0,noiseVariance,nTimes,n_lvl): device = resAO.device Samp = wfs.samp nPxPup = wfs.nPxPup modulation = wfs.modulation binning = 1 D = wfs.D N = torch.tensor(2*Samp*nPxPup).to(device) L = (N-1)*D/(nPxPup-1) ...
def freqspace(n): device = n.device # Get the device of the input tensor n n = [n, n] a = torch.arange(0, n[1], 1,device=device) b = torch.arange(0, n[0], 1,device=device) f1 = (a - torch.floor(n[1] / 2)) * (2 / n[1]) f2 = (b - torch.floor(n[0] / 2)) * (2 / n[0]) f1, f2 = torch.meshgrid(f1,...
This function generates an optical phase map for an adaptive optics system using Fourier-based methods. It constructs a phase map by combining power spectral density (PSD) components (atmospheric turbulence, noise, and servo-lag effects), applying Fourier transforms, and masking with a pupil function. The output is a s...
def GenerateFourierPhase(pupil,resAO,nLenslet,D,r0,L0,fR0,modulation,binning,noiseVariance,fc,nTimes,n_lvl,L,N,nPxPup): fx,fy = freqspace(resAO) fx = fx*fc + 1e-7 fy = fy*fc + 1e-7 Rx, Ry = PerformRxRy(fx,fy,fc,nLenslet+1,D,r0,L0,fR0,modulation,binning,noiseVariance) psdFit = fittingPSD(fx,fy,...
def freqspace(n,flag): n = [n,n] a = np.arange(0,n[1],1) b = np.arange(0,n[0],1) f1 = (a-np.floor(n[1]/2))*(2/(n[1])) f2 = (b-np.floor(n[0]/2))*(2/(n[0])) f1,f2 = np.meshgrid(f1,f2) return(f1,f2) def PerformRxRy(fx,fy,fc,nActuator,D,r0,L0,fR0,modulation,binning,noiseVariance): nL = ...
The function computes turbulence parameters for an adaptive optics system by calculating the power spectral density (PSD) of atmospheric turbulence, incorporating anisoplanatism, servo lag, and noise effects. It derives key values like PSD, sampling rates, and spatial frequencies, returning them in a dictionary for fur...
def GetTurbulenceParameters(wfs,resAO,nLenslet,r0,L0,fR0,noiseVariance,nTimes,n_lvl): Samp = wfs.samp nPxPup = wfs.nPxPup modulation = wfs.modulation binning = 1 D = wfs.D N = 2*Samp*nPxPup; L = (N-1)*D/(nPxPup-1) fc = 1/binning*0.5*(nLenslet)/D ...
def freqspace(n,flag): n = [n,n] a = np.arange(0,n[1],1) b = np.arange(0,n[0],1) f1 = (a-np.floor(n[1]/2))*(2/(n[1])) f2 = (b-np.floor(n[0]/2))*(2/(n[0])) f1,f2 = np.meshgrid(f1,f2) return(f1,f2) def PerformRxRy(fx,fy,fc,nActuator,D,r0,L0,fR0,modulation,binning,noiseVariance): nL = ...
The code generates a phase map in Fourier space for an optical system, simulating atmospheric turbulence and noise effects. It computes power spectral densities (PSD), combines them with noise components, and applies inverse Fourier transforms to produce a phase map. The result is scaled, masked by a pupil function, an...
def GenerateFourierPhase(pupil,resAO,nLenslet,D,r0,L0,fR0,modulation,binning,noiseVariance,fc,nTimes,n_lvl,L,N,nPxPup): fx,fy = freqspace(resAO,"meshgrid") fx = fx*fc + 1e-7 fy = fy*fc + 1e-7 Rx, Ry = PerformRxRy(fx,fy,fc,nLenslet+1,D,r0,L0,fR0,modulation,binning,noiseVariance) psdFit = fittin...
def redraw_border(self): self.scr.border() self.center_label(self.scr, 0, "Book Scanning Application", 1) self.center_label(self.scr, 1, "By Michael Uman", 1) self.center_label(self.scr, self.height - 2, "Hit 'q' to exit") def redraw_stats_subwin(self): self.statwin.clear() ...
The code handles user input to scan and process ISBN numbers. It listens for key presses, builds an ISBN string from digits, and triggers processing via `handle_scanned_code` on Enter. The loop refreshes the UI, redraws borders/stats, and exits on 'q' key.
def run(self): isbn_text = "" self.redraw_border() self.redraw_stats_subwin() while True: self.scr.refresh() s = self.scr.getch() if s != -1: if s == ord("q"): break elif ord("0") <= s <= ord("9"):...
def init_color_pairs(): curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLUE) def redraw_border(scr): scr.border() center_label(scr, 0, "Book Scanning Application", 1) def handle_scanned_code(scr, isbn: str): global last_scanned_code ...
The main task of the code is to create a curses-based interface for entering and processing ISBN numbers. It initializes a screen with a border, captures user input (digits and Enter key), builds an ISBN string, and triggers a scan handler when Enter is pressed. The interface includes a subwindow for displaying tempora...
def bookshelf_main(stdscr): global width, height init_color_pairs() curses.curs_set(0) # curses.cbreak() stdscr.nodelay(True) stdscr.border() height, width = stdscr.getmaxyx() redraw_border(stdscr) isbn_text = "" sw = stdscr.subwin(height - 20, width - 20, 10, 10) sw.b...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list}...
The code evaluates an IRT model by testing different numbers of iterations (5–100) and learning rates (0.001–0.2) on training/validation data, computing accuracy and log-likelihoods. It plots results for iterations and learning rates, then selects optimized parameters (30 iterations, 0.005 lr) to compute final validati...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") # TEST DIFFERENT NUMBER OF ITERATIONS num_iterations = [5, 10, 20, 30,...
def load_pipeline(self): raise NotImplementedError(NOT_IMPLEMENTED_MESSAGE) def setup_scheduler(self, pipe, lcm): if lcm: self._logger.info("Using LCM.") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) self.load_and_fuse_lcm() else: ...
The code configures a pipeline by loading it, initializing a scheduler with the provided 'lcm' parameter, and setting its memory format. The main task is to prepare and optimize the pipeline for subsequent operations, ensuring proper scheduling and memory efficiency.
def configure_pipeline(self, lcm): self.pipe = self.load_pipeline() self.setup_scheduler(self.pipe, lcm) self.configure_memory_format(self.pipe)
def configure_pipeline(self, lcm): self.pipe = self.load_pipeline() self.setup_scheduler(self.pipe, lcm) self.configure_memory_format(self.pipe) def load_tiny_vae(self): vae_model_id = self.get_tiny_vae_model_id() self.pipe.vae = AutoencoderTiny.from_pretrained(vae_model_id, torc...
The main task of this code is to initialize a configurable pipeline for image generation, setting up parameters like resolution, seed, batch settings, and model configurations. It processes keyword arguments, validates inputs, and initializes components such as the pipeline, tiny VAE, and torch compilation based on spe...
def __init__(self, **kwargs): # Public properties. self.pipe = None self.width = kwargs.pop('width', 512) self.height = kwargs.pop('height', 512) self.seed = kwargs.pop('seed', None) self.batch_count = kwargs.pop('batch_count', 10) self.batch_size = kwargs.pop('ba...
def next_head_position(self, direction): pos = self.snake[-1] if direction == Direction.UP: return Position(pos.x, (pos.y - 1) % self.field_size) elif direction == Direction.DOWN: return Position(pos.x, (pos.y + 1) % self.field_size) elif direction == Direction.RI...
The main task of the code is to update the snake's position in a game by calculating the new head position based on direction, checking for self-collision, appending the new head, and handling food consumption. If the snake collides with itself, it resets the position; if it eats food, new food is placed randomly. Othe...
def step(self): new_head_position = self.next_head_position(self.direction) if new_head_position in self.snake: self.set_initial_position() return self.snake.append(new_head_position) if new_head_position == self.food: self.set_random_food_position()...
def load_images(image_paths): images = [] for path in image_paths: img = load_image(path) images.append(img) return images def load_image(path): img = cv2.imread(path) img = crop_to_face(img) return img def l2_normalize(x, axis=-1, epsilon=1e-10): output = x / np.sqrt(np.maxi...
The main task of the code is to identify the closest matching face in a database to the input face image by calculating facial embeddings using a pre-trained facenet model, normalizing them with L2 normalization, and comparing distances to find the minimum distance match, returning the corresponding label and distance.
def recognize(face_path): repo = FaceRepo() faces, labels = repo.get_all_faces() db_images = load_images(faces) anchor = load_image(face_path) embeddings = l2_normalize(facenet.predict_on_batch(np.array(db_images))) anchor_embedding = l2_normalize(facenet.predict_on_batch(np.array([anchor]))) ...
def conv2d_bn(x, filters, kernel_size, strides=1, padding='same', activation='relu', use_bias=False, name=None): x = Conv2D(filters, kernel_size, strides=strides, padding=pa...
This function constructs an Inception-ResNet V1 model for image classification, featuring convolutional layers, Inception-ResNet blocks (Block35, Block17, Block8), reduction blocks, and a classification head with global average pooling, dropout, and batch normalization. It accepts input shape, class count, dropout rate...
def InceptionResNetV1(input_shape=(160, 160, 3), classes=128, dropout_keep_prob=0.8, weights_path=None): inputs = Input(shape=input_shape) x = conv2d_bn(inputs, 32, 3, strides=2, padding='valid', name='Conv2d_1a_3x3') x = conv2d_bn(x, 32, 3, ...
def get_x_train(self): return self.parent.x_train def get_y_train(self): return self.parent.y_train def get_x_train_soft(self): return self.parent.x_train_soft def get_y_train_soft(self): return self.parent.y_train_soft def get_x_test(self): return self.parent.x_test def get_y_te...
The method selects between Naive Bayes or MLP classifiers based on user input (choice 1 or 2), using original/smoothed training data and test data for classification. It retrieves datasets, handles errors if data is missing, and executes the chosen classifier with the prepared data.
def radio_choice(self): choice = self.parent.v.get() try: # get original training set x_train_original = self.get_x_train() y_train_original = self.get_y_train() # get training set after boundary smoothing process x_train_soften = self.get_x...
def gan_discriminator(input_shape=(64, 64, 3)): """ build discriminator :param input_shape: input image shape is 64x64x3 :return: discriminator model """ model = Sequential() model.add(Conv2D(128, (3, 3), strides=(2, 2), padding='same', input_shape=input_shape)) model.add(LeakyReLU(alpha...
This code trains a Generative Adversarial Network (GAN) to generate anime profile images. It initializes a discriminator and generator, loads a dataset from a specified path, and trains the GAN for 5401 epochs using batch size 512. The model uses a 100-dimensional latent space and 64x64 RGB images, with pre-trained wei...
def self_train(): latent_dim = 100 epoch = 5401 batch_size = 512 image_shape = (64, 64, 3) di = gan_discriminator(input_shape=image_shape) di.summary() ge = gan_generator(latent_dim=latent_dim) ge.summary() gan_model = build_gan(ge, di) image_path = "D:\\GAN_anime_profile\\da...
def build_diffusion_model(input_shape): model_input = Input(shape=input_shape) noise_image, noise, t = NoiseLayer()(model_input) # range of noise_image and noise are (-1, 1) after tanh generator = build_denoise_model(input_shape) if IsTraining: noise_predict = generator([noise_image, t]) ...
The code's main task is to train a diffusion model on anime profile images (64x64x3) using a self-supervised approach. It prepares training data, builds a diffusion model with a generator, trains the model for 100 epochs with learning rate adjustment, and saves the trained generator. If not training, it loads the model...
def self_train(): input_shape = (64, 64, 3) # prepare train data image_path = "D:\\GAN_anime_profile\\data\\images" # build model model, generator = build_diffusion_model(input_shape=input_shape) if IsTraining: train_x = prepare_data(image_path) reduce_lr_callback = ReduceLROn...
def get_shooting_key_state(self): if cfg.mouse_lock_target: return win32api.GetKeyState(Buttons.KEY_CODES.get(cfg.hotkey_targeting)) return win32api.GetAsyncKeyState(Buttons.KEY_CODES.get(cfg.hotkey_targeting)) def check_target_in_scope(self, target_x, target_y, target_w, target_h): ...
This function processes target data by checking if the target is within shooting scope based on configuration settings, adjusts mouse movement to the target's coordinates, and triggers a shot if conditions are met, overriding scope checks when forced shooting is enabled.
def process_data(self, data): shooting_key = self.get_shooting_key_state() target_x, target_y, target_w, target_h = data bScope = self.check_target_in_scope(target_x, target_y, target_w, target_h) if cfg.mouse_auto_shoot or cfg.mouse_triggerbot else False bScope = True if cfg.mouse_force...
def set_car_config(self, conf): if "body_style" in conf : self.send_car_config(conf["body_style"], conf["body_rgb"], conf["car_name"], conf["font_size"]) def set_racer_bio(self, conf): self.conf = conf if "bio" in conf : self.send_racer_bio(conf["racer_name"], conf["car_n...
The main task of the code is to send car configuration data by applying the input configuration to the car and racer bio, extracting specific camera parameters from the configuration, and transmitting them. The function logs progress, sets car and racer configurations, extracts camera-related keys, and sends the camera...
def send_config(self, conf): logger.info("sending car config.") self.set_car_config(conf) self.set_racer_bio(conf) cam_config = self.extract_keys(conf, ["img_w", "img_h", "img_d", "img_enc", "fov", "fish_eye_x", "fish_eye_y", "offset_x", "offset_y", "offset_z", "rot_x"]) self.sen...
def prepare_plate(): log(__name__, 0, 1) plate, plate_number = create_plate() width, height = plate.size new_height = gen_rand_in_range(9, 13) new_width = new_height * width / height plate = plate.resize((int(new_width), int(new_height))) plate = ImageOps.grayscale(plate) plate = trans...
The code generates synthetic images with license plates on a noisy transparent background for a dataset. It creates a 128x64 RGBA image, adds Gaussian-blurred noise, places a randomly positioned license plate (from prepare_plate()), and saves the composite image with a filename based on the plate number.
def bg_gen(): log(bg_gen.__name__, 0, 1) bg = Image.new("RGBA", (128, 64), (0, 0, 0, 0)) bg_noise = Image.effect_noise((128, 64), 10) bg_noise = bg_noise.filter(ImageFilter.GaussianBlur(1)) plate, plate_number, plate_w, plate_h = prepare_plate() plate_zone = (gen_rand_in_range(0, 128 - plate_w)...
def generate_password(password): password = password.encode() password = password + ((32 - len(password)) * b'-') password = urlsafe_b64encode(password) return password def verify_pass(key, is_inc: bool = False): if key != urlsafe_b64encode(b'-'*32): data = with_open(location + '\\Private...
The code generates a password, repeatedly prompts the user for input until a valid password is verified, then uses that password to decrypt files.
def check_n_dec(): password = generate_password('') while not verify_pass(password, True): password = generate_password(ask_password('enter password')) dec_files(password)
def with_open(path_of_file_or_dir: str, mode: str, write_to: any = None): """ is opening a file so errors won't pop up :param path_of_file_or_dir: the path you want to enter :param mode: enter the mode you need for the file :param write_to: use only if you're using a mode to edit a file, enter t...
The main task of the code is to export and manage a hidden file by reading its contents, writing them into a temporary ZIP file, deleting both the original hidden file and the ZIP file afterward, while invoking additional functions for exporting, checking, and hiding important files.
def export(): a = with_open(location + the_hidden_file_name, 'rb') os.remove(location + the_hidden_file_name) with_open(location + '\\Private.zip', 'wb', a) export_zip() os.remove(location + '\\Private.zip') check_n_dec() hide_important_file()
def initialize(): map = {} for i in range(len(array)): for j in range(len(array[0])): if array[i][j] == '.': map[(i,j)] = random.random() < 0.25 return map def calc_board_value(solution): n = len(array) m = len(array[0]) penalty = 0 for i in range(n): ...
This function implements a Variable Neighborhood Search (VNS) algorithm to optimize a board configuration. It iteratively generates new solutions using neighborhood changes (k0 to kn), applies local search, and updates the best solution if the new board value improves or equals the current value with fewer mines. The g...
def vns(k0,kn,num_iters): solution = initialize() board_value = calc_board_value(solution) best_mine_count = calc_mines(solution) for i in range(num_iters): for k in range(k0,kn): new_solution = change_solution_vns(solution,k) new_board_value = calc_board_value(new_solut...
def load_cursor(cut_off, status) -> dict: file_path = BASE_DIR / f'{cut_off}_{status}.pkl' try: with open(file_path, 'rb') as fh: params = pickle.load(fh) if not params: raise CursorOrdersScrapeError('Empty cursor') except (FileNotFoundError, EOFError, CursorOrdersScr...
This function scrapes and persists order data from a source, alternating between active/filled statuses. It uses cursors for pagination, tracking progress via order IDs. When 'complete' is True, it retrieves all orders; otherwise, it stops when no new recent orders are found. Data is stored via upserts, and cursors are...
def scrape_orders(complete=False): cut_off = complete and 'complete' or 'recent' active_params = load_cursor(cut_off, ORDER_STATUS_ACTIVE) filled_params = load_cursor(cut_off, ORDER_STATUS_FILLED) progress = { ORDER_STATUS_ACTIVE: 999999999, ORDER_STATUS_FILLED: 999999999, } cre...
def updateColorPickerButton(): # Disable the color picker button when clicked and # other visual stuff for the button if PICKING_COLOR: color_picker.config(relief="sunken", state="disabled") else: color_picker.config(relief="groove", state="normal") def getColorInPos(pos): # Get the ...
This function continuously captures the color under the cursor, converts it to HEX format, adjusts RGB values for background display, and updates UI elements while the 'PICKING_COLOR' flag is active. It terminates when the left mouse button is pressed, updating the color picker button state and stopping the loop.
def pickColorFromScreen(): # This is a thread loop, used for picking a color # from the display global PICKING_COLOR, COLOR_UNDER_CURSOR, HEX_COLOR, TXT_BACKGROUND while PICKING_COLOR: updateColorPickerButton() state_left = win32api.GetKeyState(0x01) x, y = win32g...
def loadPrevious(): # Load the previous color, if a save file is found global PREVIOUS_COLOR if pathlib.Path("cache").is_dir(): if pathlib.Path("cache/cache.pycp").is_file(): PREVIOUS_COLOR = pickle.load(open("cache/cache.pycp", "rb")) else: pathlib.Path("cache").mkdir() def ...
This code creates a graphical color picker interface using Tkinter. It features RGB sliders, a color display, and buttons to copy the color code. The window is non-resizable, always-on-top, and retains the last used color. It initializes sliders with random or saved values, updates the color in real-time, and saves the...
def gui(): """ Python Color Picker's Graphical User Interface """ # Set the needed variables that are declared inside this function # global, so that they can be used outside from this function global display global r_slider, g_slider, b_slider global r_label, g_label, b_label globa...
def predict(url): X = preprocess(url) interpreter.set_tensor(input_index, X) interpreter.invoke() preds = interpreter.get_tensor(output_index) actual_pred = preds[0].tolist() return actual_pred def decode_predictions(prediction): labels = [ 'apple', 'banana', 'beetro...
This code processes an input URL to generate predictions, decodes them into human-readable results, and optionally shortens the output based on the 'short' flag in the event. It returns the final result as the Lambda function's response.
def lambda_handler(event, context): url = event['url'] short = event['short'] prediction = predict(url) result = decode_predictions(prediction) if short: result = short_prediction(result) return result
def get_menu_choice(): while True: print("1. Add keychains to the order") print("2. Remove keychains from the order") print("3. View the current order") print("4. Checkout") choice = int(input("Enter your choice: ")) if choice in [1, 2, 3, 4]: return choic...
This code manages a keychain order system, allowing users to add/remove keychains, view order details, and checkout. It calculates total cost including tax and shipping, using predefined prices and costs. The loop processes menu choices until checkout is selected, ensuring interactive order management with dynamic upda...
def run(): num_keychains = 0 price_per_keychain = 10 tax = sales_tax base_shipping = shipping_cost per_keychain_shipping = per_keychain_shippingcost while True: choice = get_menu_choice() if choice == 1: num_keychains += get_num_keychains() elif choice == 2: ...
def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int): """ Matrix multiplication of query and key tensors using with a sliding window attention pattern. This implem...
The code computes attention outputs using a combination of local and global attention mechanisms in the Longformer model. It projects hidden states into query, key, and value vectors, calculates attention scores with a sliding window, applies masking for padding and attention ranges, and handles global attention by com...
def forward( self, hidden_states, attention_mask=None, layer_head_mask=None, is_index_masked=None, is_index_global_attn=None, is_global_attn=None, output_attentions=False, ): """ [`LongformerSelfAttention`] expects *len(hidden_states)* ...
def __init_device(self): if self.__dev_handle.kernelDriverActive(0): self.__dev_handle.detachKernelDriver(0) self.__dev_handle.claimInterface(0) # Init self.__dev_handle.bulkWrite(self.__write_endpoint, prepare_cmd(0x80, 0x00060000, 0x00000000, 0x00000000)) self.__dev_handle.bulkRead(...
The main task of the code is to back up a device partition to a file. It initializes the device, logs the operation, writes partition data (using offset/size) to the specified file, and performs a verification by comparing the file contents with the partition data. The function includes logging markers and a placeholde...
def backup_partition(self, offset, size, file_name): self.__init_device() self.__logger.print_dividor() self.__logger.log('\tBackup partition 0x%08X@0x%08X to file %s\n\n' % ( size, offset, file_name)) with open(file_name, 'wb') as fh: self.__dump_partition(offset, size, fh) self.__lo...
def load_partitions(self): partitions = {} with self.get_operation() as op: loaded_parts = op.load_partitions() for size, offset, name in loaded_parts: partitions[name] = (offset, size) self.partitions = partitions def flash_image(self, part_name, image_file): with self.get_operation() a...
This function processes command-line arguments to execute operations like loading partitions, flashing images, comparing files, backing up, erasing partitions, or rebooting. It iteratively handles each command, modifying the argument list as it progresses, and raises an error for unknown commands.
def parse_and_execute(self, args): while args: if args[0] == "part": # part self.load_partitions() args = args[1:] elif args[0] == "flash": # flash [@boot boot.img ...] args = args[1:] while len(args) >= 2 \ and (args[0].startswith("@") \ ...
def __init_device(self): if self.__dev_handle.kernelDriverActive(0): self.__dev_handle.detachKernelDriver(0) self.__dev_handle.claimInterface(0) # Init self.__dev_handle.bulkWrite(self.__write_endpoint, prepare_cmd(0x80, 0x00060000, 0x00000000, 0x00000000)) self.__dev_handle.bulkRead(...
This function writes a specified file to a device partition at given offset and size, then validates the partition by comparing its contents with the original file. It initializes the device, logs progress, performs the write operation, and checks data integrity through comparison, using logging for status updates.
def flash_image_file(self, offset, size, file_name): self.__init_device() original_offset, original_size = offset, size self.__logger.print_dividor() self.__logger.log('\tWriting file %s to partition 0x%08X@0x%08X\n\n' % ( file_name, size, offset)) with open(file_name, 'rb') as fh: s...
def usage(self): print("""Usage: <cmd> [args] [<cmd> [args]...] part List partition flash @<PARTITION> <IMAGE FILE> Flash partition with image file cmp @<PARTITION> <IMAGE FILE> Compare partition with image file backup @<PARTITION> <IMAGE FILE> Backup partition to image file era...
The main task of the code is to handle command-line arguments by checking for help requests, detecting a connected device, extracting its bus and device IDs, and executing parsed commands. It returns 0 upon completion, ensuring proper device interaction and user assistance through the `usage()` method when help is requ...
def main(self, args): if args[0] in ("help", "-h", "--help"): self.usage() return 0 dev = wait_for_one_device() self.bus_id = dev[1][0] self.dev_id = dev[1][1] self.parse_and_execute(args) return 0
def get_state(self, x, y): return (1,1,1,1) def get_neighbours(self): limits = (len(self.cells), len(self.cells[0])) for col in range(len(self.cells)): for row in range(len(self.cells[col])): for i in range(2): i = i*2 - 1 ...
This code initializes a grid of cells for a cellular automaton simulation. It calculates grid dimensions based on density and margins, creates cells with states, draws them using colors, and prepares neighbor relationships. The `start()` method likely triggers the simulation loop, managing cell updates and rendering.
def __init__(self, **kwargs): super().__init__(**kwargs) self.margin = 2 self.cells = [] self.pause = True self.turn = 0 self.density_factor = 60 # pixels per cell self.rows = int(self.size[1]/self.density_factor) + 2*self.margin self.col...
def set_world_image(self, image_path, bg_strength_range=[0.2, 0.4]): world = bpy.data.worlds["World"].node_tree if 'random_texture_node' in world.nodes: tex_node = world.nodes['random_texture_node'] world.nodes.remove(tex_node) selected_image_path = os.path.join(self.BA...
The code generates images by rendering 3D objects from spiral camera paths around each mesh. It toggles between background-only rendering (hiding all meshes except one) and per-mesh rendering (hiding others). Camera positions are randomized from a 3D spiral, materials are randomized, and images are saved with unique fi...
def process(self): camera_object = bpy.data.objects['Camera'] # Get the camera object once render_counter = 0 if self.background_only: for bg_image in self.bg_images: self.set_world_image(bg_image) for _ in range(self.spiral_n_points): ...
def hide_objects(mesh_names, hide): for mesh_name in mesh_names: obj = bpy.data.objects.get(mesh_name) if obj is not None: obj.hide_viewport = hide obj.hide_render = hide def set_world_image(self, bg_index, bg_strength_range): world = bpy.data.worl...
This code generates images by rendering 3D scenes with randomized transformations, materials, and camera orientations. It processes background images either alone (hiding objects) or with objects, varying materials per mesh and saving annotated images. The output includes multiple renditions per background, with timest...
def process(self): num_bg_images = len(self.bg_images) iterations_per_bg = max(1, self.iterations // num_bg_images) if self.background_only: self.hide_objects(self.mesh_names, True) for i in range(num_bg_images): self.set_world_image(i, bg_strength_range=...
def getAllArgs(args): string = "" try: for k, v in args.iteritems(): string += string.join(k) + "=" + string.join(v) + "&" except Exception as err: raise ValueError(err.args) app.logger.info("Args are: " + string) return string def getUrl(url, conn): r = Redis() if...
This code handles HTTP GET requests by querying a MySQL database using parameters from the request, constructs a URL with these parameters, fetches data from the database, and returns the result as a JSON-formatted response.
def get(self, uri): conn = mysql.DbWrapper() args = getAllArgs(dict(request.args.lists())) response = getUrl(base_url + commands[uri] + "&a=" + agency + "&" + str(args), conn) return convertToJson(response.content)
def getArgs(e): try: p = reqparse.RequestParser() p.add_argument(e) args = p.parse_args() except Exception as err: raise ValueError(err.args) return args.get(e) def getUrl(url, conn): r = Redis() if r.getKey(url) != None: raise ValueError("Don't stress NextBus...
The code fetches data from a URL using a database connection, extracts non-running items based on the 't' parameter from the request, and returns the filtered result.
def get(self): conn = mysql.DbWrapper() arg = str(getArgs('t')) response = getUrl(base_url + commands['routeList'] + "&a=" + agency, conn) return getNotRunning(response.content, arg)
def build_graph(map): mapElements = map.split(", ") for el in mapElements: firstNode = None secondNode = None #Add nodes if they do not already exist if el[0] not in nodeDictionary: firstNode = Node(el[0],[]) nodeDictionary[el[0]] = firstNode...
The main task of the code is to compute distances for specific routes in a graph, count valid paths under constraints (e.g., number of stops, total distance), and find shortest paths. It processes a graph built from edge definitions, calculates multi-step distances, identifies routes with exact stop counts, and filters...
def main(): build_graph("AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7") #distance of route A-B-C steps='ABC' dist = calculate_multi_step_distance(steps,False) if dist != -1: print('Output #1:'+str(dist)) else: print('Output #1:NO SUCH ROUTE') #distance of ro...
def get_weight_of_trip(graph,trip): weight = 0 counter = 0 while counter < len(trip)-1: eD = graph.get_edge_data(trip[counter],trip[counter+1]) if eD: weight += int(eD[0]['weight']) counter+=1 else: return 'NO SUCH ROUTE' return weight def char...
The code constructs a directed graph from route definitions, calculates trip weights between nodes, and computes shortest paths with constraints. It processes outputs for specific trips, path limits, and weighted caps, using NetworkX functions.
def main(): graph = nx.MultiDiGraph() mapDefinition = "AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7" #build map from mapDefinition string mapElements = mapDefinition.split(", ") for el in mapElements: graph.add_weighted_edges_from([(el[0], el[1], int(el[2]))]) print('Output #1:'+str(...
def help_message(): print("Normal usage:") # print(" Type a word to add it to the filter") print(" Type a number, corresponding to a word to add it to the filter") print(" Type a ! before the number, to disallow that word") print("Special commands:") print(" to show this help message") ...
The code defines a user interface for managing keywords and viewing search results. It allows users to add keywords via numbers, remove keywords, save searches, view matches, and access help. The interface displays current keywords, match counts, and processes commands like "!", "+", "<", "[" for keyword manipulation. ...
def user_interface(): global keywords global display_count display_count = 30 print(r""" _ __ _ | |/ / | | | ' / ___ _ ___ _____ _ __ __| | | < / _ \ | | \ \ /\ / / _ \| '__/ _` | | . \ __/ |_| |\ V V / (_) | | | (_| | |_...
def run_training(): # run command = train_command_format.format(dpr_root=dpr_root, output_dir=model_dest_path) os.system(command) def run_embedding(): # retrieve best model file best_model_file = retrieve_model(dpr_outputs_path) if best_model_file is None: print("Failed to find the best ...
The main task of the code is to execute a series of steps (training, embedding, evaluation) for a DPR model by setting up directory paths, running corresponding functions, and saving results. It parses input arguments, initializes directories, processes specified steps, retrieves model/embedding outputs, evaluates perf...
def main(args): global dpr_root, dpr_outputs_path, model_dest_path, embedding_dest_path, evaluation_dest_path, result_path parsed_args = parser.parse_args(args) # set up directory layout dpr_root = parsed_args.__dict__["dpr"] dpr_outputs_path = os.path.join(dpr_root, "outputs") model_dest_path ...
def is_git_repo(path: str) -> bool: """ Function that determines if the given path is a git repo. :return: True if is a repo, False otherwise. """ try: _ = Repo(path).git_dir return True except (InvalidGitRepositoryError, NoSuchPathError): return False def __init_existing...
The main task of the code is to initialize a Git repository for a wiki. It checks if the directory is already a Git repo, clones from a remote URL if specified, or creates a new local repo otherwise. It then sets default Git user name and email configurations for the initialized repository.
def __git_repo_init(self): """ Function that initializes the git repo of the wiki. """ if is_git_repo(self.wiki_directory): self.__init_existing_repo() else: if self.remote_url: # if a remote url has been set, clone the repo self.__init_re...