dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _polar2cartesian(laser_range, angle, position): # type: (float, float, (float, float)) -> (float, float) x = laser_range * cos(angle) + position[0] y = laser_range * sin(angle) + position[1] return x, y def _obstacles_on_line(self, start, end): # type: ((float, float), (float, float)) -> set...
The code updates a grid's obstacle map by processing laser scan data from the robot's state. It calculates obstacle positions using polar-to-Cartesian conversions, adds newly detected obstacles, and removes those no longer within the scan range. The function maintains accurate obstacle tracking by comparing detected po...
def update(self, robot_state): # type: (RobotState) -> None """ Update the grid obstacles. Args: robot_state: The robot state. """ position = robot_state.proximal_position rotation = robot_state.proximal_rotation laser_scan = robot_state.laser_scan ...
def _check_events_main_screen(self): #check if the player is on ground #if not apply gravity if(self.onGround(self.player)): self.player.setGravity(False) if(self.player.yVelocity < 0): self.player.yVelocity = 0 else: self.player.setGravity(True) #check if the enemies are on ground #apply gra...
The code defines a method `_check_events` that routes event handling to different screen-specific methods based on the current screen state stored in `self.settings.screen`. It checks the screen value and calls either `_check_events_main_screen`, `_check_events_game_screen`, or `_check_events_prepare_screen` accordingl...
def _check_events(self): if(self.settings.screen == "main"): self._check_events_main_screen() elif(self.settings.screen == "game"): self._check_events_game_screen() elif(self.settings.screen == "instructions"): self._check_events_prepare_screen()
def only_idlemotion(file_path): filtered_df = read_data(file_path) return set(filtered_df['Activity']) == {'IdleMotion'} def process_sequence(self, file_path): filtered_df = read_data(file_path) sequence = filtered_df.loc[(filtered_df.shift() != filtered_df).any(axis=1)] sequence = seque...
The main task of the code is to merge data from two files ('data4testing_R.txt' and 'data4testing_L.txt') into a unified dictionary. It processes each file, skips idle motion data, and combines activity-related 'precondition' and 'effect' entries using a simplification function. Duplicates are resolved by merging and s...
def merge(self): buffer = {} for file_name in ['data4testing_R.txt', 'data4testing_L.txt']: file_path = os.path.join(self.path, file_name) if not only_idlemotion(file_path): dicts = self.process_sequence(file_path) for activity, info in dicts.items...
def _aggregate(self, xt, qt, ht, batch_size): r""" Parameters: xt: input one-hot question answering features at the current timestamp qt: question indices for all students in a batch at the current timestamp ht: hidden representations of all concepts at the current ti...
The code processes input sequences of student learning data (features and questions) to predict the probability of correctly answering the next question in the sequence. It iterates through each time step, updating hidden states using aggregation and transformation modules, while optionally generating VAE-related embed...
def forward(self, features, questions): r""" Parameters: features: input one-hot matrix questions: question index matrix seq_len dimension needs padding, because different students may have learning sequences with different lengths. Shape: features: [b...
def forward_propagate(self, X): """ propagates tensor forwards through network """ # check dimensions of input matrix match those of input layer assert(X.shape[0] == self.Ws[1].shape[1]) # forward propagate and cache entire batch self.As[0] = X for i in range(1, self.L):...
This code trains a neural network by performing gradient descent over multiple epochs. It conducts forward and backward propagation to compute gradients, updates weights and biases using a learning rate (alpha), and calculates cross-entropy loss with L2 regularization (lambda). Progress is printed at intervals if enabl...
def fit(self, X, Y, epochs=10_000, alpha=1e-2, printProg=False, lambd=1e-2 ): for epoch in range(epochs): # get all activations, weighted inputs, and gradients self.forward_propagate(X) self.back_...
def set_visible_have_background(group, mode): for layer in group: if layer.kind == 'group' and layer.name.lower() != 'background': layer.visible = mode set_visible_have_background(layer, mode) else: if layer.kind == 'group' and layer.name.lower() == 'background': ...
The function generates a background image by processing a root element with specified text and color settings, saves it as a PNG file named after the found option, and stores the output with a standardized filename.
def photo_stack_with_option(root, option_f=None, set_text_f=None, color_f=None, ttf_f=None): if not option_f or not set_text_f or not root: print('wrong params root, option, text') return set_visible_have_background(root, False) check_option = find_option(root, option_f) if check_option...
def visible_background(root, mode): for layer in root: if layer.name.lower() == 'background': layer.visible = mode def gen_path(current_path, branch, reverse=True): if len(branch) == 1: return current_path if len(branch) > 1: if reverse: branch.reverse() ...
The main task of the code is to render and save images and thumbnails for layers in a PSD file, organizing them hierarchically. It processes background layers by compositing and saving PNGs, generates thumbnails, handles text layers to extract properties, and constructs file paths based on layer hierarchy. The function...
def render_img(layers, path): list_layers = [] for layer in layers: if layer.kind == 'group': if layer.name.lower() == 'background': if not os.path.isfile(f'../lab1/{layer.name}.png'): layer_img = PSDImage.open(path) visible_background(...
def visible_background(root, mode): for layer in root: if layer.name.lower() == 'background': layer.visible = mode def gen_path(current_path, branch, reverse=True): if len(branch) == 1: return current_path if len(branch) > 1: if reverse: branch.reverse() ...
This function processes PSD layers to render and save individual layer images and thumbnails, handling background layers by generating composite images, text layers by extracting location/text data, and other layers by organizing files into directory structures. It also manages threading for concurrent processing and e...
def render_img(layers, path): list_layers = [] for layer in layers: if layer.kind == 'group': if layer.name.lower() == 'background': if not os.path.isfile(f'{OUTPUT_DIR}/{layer.name}.png'): layer_img = PSDImage.open(path) visible_backgr...
def set_visible_all(root, mode): for layer in root: if layer.kind == 'group': layer.visible = mode set_visible_all(layer, mode) else: layer.visible = mode def set_visible(group, mode): for layer in group: if layer.kind == 'group' and layer.name.lower()...
The code processes a PSD image by hiding all layers, rendering the image, and saving the structured output as JSON. It resets logs, counts image elements, generates content, and writes the result to a JSON file for further use.
def start(path): reset_log() psd = PSDImage.open(path) set_visible_all(psd, False) set_visible(psd, False) print('Start render image :') count_images(psd) count_images(psd) content = render_img(psd, path) content_output = { "Root": content } print('DONE') with o...
def set_visible_all(root, mode): for layer in root: if layer.kind == 'group': layer.visible = mode set_visible_all(layer, mode) else: layer.visible = mode def set_visible(group, mode): for layer in group: if layer.kind == 'group' and layer.name.lower()...
This code processes a PSD image by setting up output directories, rendering the image layers, and saving the result as a JSON file. It initializes the output path, ensures directory structure, hides layers, counts image elements, renders the content, and writes the structured data to 'output.json' in the specified dire...
def start(path): reset_log() global OUTPUT_DIR OUTPUT_DIR = "./OUTPUT" + "/" + os.path.basename(path) if os.path.isdir(OUTPUT_DIR): shutil.rmtree(OUTPUT_DIR) if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) if not os.path.exists(f"{OUTPUT_DIR}/thumbnail"): os.m...
def _log(msg, EnableLog: bool) -> None: if EnableLog: print(msg) def getPreamble(inst, debug: bool = False) -> Preamble: """Reads the preamble from the oscilloscope. :param inst: The instrument object from pyscpi or pyvisa :param debug: Print debug messages :return: A Preamble object "...
The function reads multiple channels from an oscilloscope, processes waveform data using parameters from the instrument's preamble, and returns time and voltage arrays. It configures the instrument, digitizes specified channels, retrieves waveform data, scales it to voltage, calculates time stamps, and optionally resta...
def readChannels(inst, channels: list[int], points: int = 0, runAfter: bool = True, debug: bool = False) -> tuple[np.ndarray, np.ndarray]: """Reads multiple channels from the oscilloscope. :param inst: The instrument object from pyscpi or pyvisa :param channels: A list of channels to read eg. [1, 2] :p...
def add_classifiers(population, matrice): Gene.clear() add_unfitness(population, matrice) #print(population[0]) add_fitness(population) #print(population[0]) add_weights(population) def find_best(new_population): best_member = new_population[0] for member in new_population: if me...
The code implements a genetic algorithm to evolve a population of solutions, aiming to find the optimal member (best_member) based on a given matrix. It iteratively selects parents, reproduces offspring via crossover (algorithm-specific), applies mutation, and evaluates fitness. If no improvement occurs for 'unchanged_...
def genetic_algorithm(population, matrice, unchanged_limit, mutation_chance, algorithm, positions): #sets random variable of population as best_member # wont realy affect anythin same_values = 0 #print(matrice) #print(population[0].get_gene()) add_classifiers(population, matrice) # print_pop(...
def get_matrice(): matrice = read_matrice() convert_matrice_tostr(matrice) return matrice def create_population(length_of_gene, population_size): towns = list(range(length_of_gene)) population = [] # print("gene lenght: " + str(length_of_gene) + "population_size " + str(population_size)) for ...
The code implements a genetic algorithm to find the optimal path in a matrix-based problem. It initializes population parameters, loads a matrix and map positions, and executes the algorithm with specified mutation and convergence limits. The goal is to determine the best route, likely for a traveling salesman problem,...
def main(): size_of_population = 1000 unchanged_limit = 20 mutation_chance = 0.3 algorithm = 1 matrice = get_matrice() assert(len(matrice) != 0) gene_length = len(matrice[0]) if gene_length == 1: print(matrice[0]) return 0 population = create_population(gene_leng...
def get_tag_ind_off(a,b): result = [] bin_addr = decimal_to_binary(a) if b == 'L1': offset_bits = math.ceil(math.log(L1_block_size,2)) L1_offest = bin_addr[(32-offset_bits):33] if L1_no_sets == 0: index_bits = 0 L1_index = '' else: index_bits = math.ceil(math.log(L1_no_sets,2)) L1_index = bin...
The function inserts a value into the L1 cache by locating the appropriate set and block. If an empty slot exists, it directly stores the value; otherwise, it replaces the least recently used block. It updates the cache structure, recalculates the address components (tag, index, offset), and propagates the value to the...
def insert_L1_cache(a,value): # Function for inserting a word into L1 cache addre = [] latency = L1_cache_latency L1_flag = False addre = get_tag_ind_off(a,'L1') for blocks in range(len(L1_cache[addre[1]])): if L1_cache[addre[1]][blocks][addre[2]][0] == '': L1_flag = True L1_cache[addre[1]][blocks][addre...
def set_female_voice(self): voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) female_voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SPEECH\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0" def greet(self): self.speak("Hello! How can I assist you today?") def spea...
The code defines a 'listen' method that initializes a female voice, greets the user, and enters a loop to continuously prompt for commands. It processes each input statement by executing the corresponding task until manually stopped.
def listen(self): self.set_female_voice() self.greet() while not self.stopped: self.speak("What can I do for you?") statement = self.take_command() if statement: self.perform_task(statement)
def get_features(augmentation, network, dataset, source, target, num): ''' get features ''' source_features_path = 'feature_weights/{}_{}_{}_{}.pt'.format(augmentation, network, dataset, source) target_features_path = 'feature_weights/{}_{}_{}_{}.pt'.format(augmentation, network, dataset, target) s...
The main task of the code is to perform domain adaptation by aligning source and target features using CORAL or PADD alignment, then training a classifier with self-training iterations to improve target domain accuracy. It collects accuracies and predictions at each stage, returning results, the classifier, and feature...
def get_results(network, inc, source, target, dataset, num=3, device='cuda'): # list of tuples (target_acc, source_acc, val_acc, unlabeled_preds) # saved at each stage return_list = [] # Get features source_features, source_labels, val_target_features, val_target_labels, unlabeled_target_featur...
def get_features(augmentation, network, dataset, source, target, num): ''' get features ''' source_features_path = 'feature_weights/{}_{}_{}_{}.pt'.format(augmentation, network, dataset, source) target_features_path = 'feature_weights/{}_{}_{}_{}.pt'.format(augmentation, network, dataset, target) s...
The code performs domain adaptation using multiple networks, aligning source and target features via CORAL, then trains a classifier on labeled data. It iteratively refines the model through self-training with pseudo-labels, appending accuracy metrics at each stage. The main task is to adapt a model from a source domai...
def get_results(source, target, dataset, num=3, device='cuda'): # list of tuples (target_acc, source_acc, val_acc, unlabeled_preds) # saved at each stage return_list = [] # Get features # source_features, source_labels, val_target_features, val_target_labels, unlabeled_target_features, unlabele...
def _parse_id(self, page_id: str) -> str: if 'https://www.notion.so/' in page_id: page_id = re.sub(r'https://www.notion.so/', '', page_id) return page_id def _validation(self, _id: str) -> bool: status_code, res = self.client.get_page(_id) if 200 <= status_code < 300: ...
The code exports a specified page by validating the page ID and creating a file at the given export path. It parses the page ID, checks its validity, raises an error if invalid, and generates the file if valid.
def export(self, page_id: str, export_path: str) -> NoReturn: page_id = self._parse_id(page_id=page_id) self.validated = self._validation(page_id) if not self.validated: raise ValueError('Could not find the page') self._create_file(page_id=page_id, export_path=export...
def load_onnx_model(self, onnx_file, input_shapes: list): self.model = onnx.load(onnx_file) self.input_names = self.get_input_names(self.model) self.num_input = len(self.input_names) self.input_shape_assign(input_shapes) self.input_shapes = self.get_input_shapes(self.model) ...
This code initializes a model converter by loading an ONNX model, setting up MLIR importers, and preparing operation conversion functions. It stores model parameters, loads weights, and prepares to translate ONNX operations like Add/Relu into MLIR format for hardware acceleration. The class enables ONNX-to-MLIR convers...
def __init__(self, model_name: str, onnx_file: str, input_shapes: list, mlir_file: str): super().__init__() self.model_name = model_name self.weight_file = "{}_tops_weight.npz".format(model_name) self.mlir_file = mlir_file self.input_names = list() self.output_names = lis...
def initial_data_setup(data: Union[List[Dict[str, Any]], Dict[str, Any]], endpoint_name: str) -> Tuple[PandasDataFrame, Dict[...
This function converts nested JSON data into multiple long-form Pandas DataFrames by recursively unpacking nested structures. It enhances flexibility beyond json_normalize(), handling complex nesting by iteratively breaking down columns, managing primary keys, and organizing results into a dictionary of processed DataF...
def breakdown_json(data: Union[List[Dict[str, Any]], Dict[str, Any]], endpoint_name: str = "root", drop_empty: bool = False) -> Dict[str, PandasDataFrame]: """ Unpacks json data and converts to multiple long-form 'atomic' dataframes. Panda's `json_normalize()` is helpf...
def filter_node(self, node): return isinstance(node, (ast.Str, ast.Constant)) def reform_node(self, node): value = node.s if isinstance(node, ast.Str) else node.value if not isinstance(value, (list, tuple, set, dict, str)): return node obfnode = self._reform_value(value) ...
This code recursively traverses an AST (Abstract Syntax Tree) node, checking each field. If a field's value is a list, it processes each element, replacing it with a transformed version if it matches the filter criteria. If the value is an AST node, it recursively visits it. For non-list values, it applies the same tra...
def visit(self, node): for field, value in ast.iter_fields(node): if isinstance(value, list): for i in range(len(value)): if self.filter_node(value[i]): value[i] = self.reform_node(value[i]) elif isinstance(value[i], ast...
def openConnection(): connection = sqlite3.connect("influencers.db", check_same_thread=False) return connection def getCurrentInfluencers(): connection = openConnection() currentInfluencers = [] connection.row_factory = lambda cursor, row: row[0] c = connection.cursor() for row in c.execute(...
The main task of the code is to retrieve 'follows' data from multiple database tables named after current influencers, process their names, aggregate the results into a dictionary, clear existing data, and return the updated dictionary of influencer follows.
def dumpNewFollows(): connection = openConnection() newFollows = {} currentInfluencers = getCurrentInfluencers() for i in range(len(currentInfluencers)): currentInfluencers[i] = checkName(currentInfluencers[i]) connection.row_factory = lambda cursor, row: row[0] c = connection.cu...
def retrieve_cached_results(destination, session, url): """Retrieves Destination Knowledgebase results that are cached and returns them to object format. If the results indicate that the last observed time is more than two weeks ago, a new lookup should occur, be saved (if it's fully-formed), and then...
The function retrieves destination information by querying a knowledgebase API or loading cached data. It constructs a URL with parameters like destination name, protocol, and port, then checks if cached results exist (if use_cache is True). If cached data is valid, it returns it; otherwise, it fetches fresh data from ...
def get_destination_info(session, dst, protocolinfo, port, use_cache=True, verbose=False): """Either queries the Destination Knowledgebase or loads data from the cache. Returns the resulting data. """ data = None if port: url = f"{config.BAYSE_KB_API_URL}?name={dst}&protocol={protocolinfo}&port=...
def init_mode(self): logger.debug(f'init mode {self.mode}') if self.mode == 0: self.midi_controller.init_instrument_layout(self.octave) self.update_instrument() elif self.mode == 1: self.midi_controller.init_drums_layout(self.get_drum_current_kit()) self.update_drums(DRUMS_DATA['KIT'...
The code initializes a MIDI processing system that listens for input from a specific MIDI device, switches between instrument and drum modes based on control change messages, and sends corresponding MIDI outputs. It loads a sound font, maps note events to instrument/drums configurations, and updates the output port wit...
def run(self): device_listener_thread = threading.Thread(target=self.device_listener) device_listener_thread.daemon = True device_listener_thread.start() signal.signal(signal.SIGINT, self.end_process_handler) signal.signal(signal.SIGTERM, self.end_process_handler) while DEVICE_PORT_NAME not in...
def get_id(): machine_id = "76adfa47-8614-474c-b534-c28cd80b3d77" return machine_id def get_headers(): token = get_token() headers = { 'x-auth-token': token, 'Host': "192.168.1.33:8041", 'X-Amz-Date': "20190522T125452Z", 'Authorization': "AWS4-HMAC-SHA256 Credential=undef...
The main task of the code is to retrieve resource data for a specific machine by sending a GET request to an API endpoint using its ID, then fetch and process a list of metrics by iterating through them and calling a function to obtain their measures.
def main(): machine_id = get_id() url = "http://192.168.1.33:8041/v1/resource/instance/" + machine_id headers = get_headers() get_request("data", url, headers) metric_list = get_metrics() for m in metric_list: get_measures(m)
def majority_class(examples): classes = [example[-1] for example in examples] return max(set(classes), key = classes.count) def same_class(examples): classes = [example[-1] for example in examples] return (len(set(classes)) == 1) def best_feature(features, examples): # Return index of feature with l...
The code recursively builds a decision tree by selecting the best feature to split examples, creating child nodes for each feature value, and terminating when all examples share the same class or no features remain, using majority class for leaf nodes.
def build_tree_1(examples, features): tree_node = TreeNode(majority_class(examples)) # if examples all have same class, then return leaf node predicting this class if same_class(examples): return tree_node # if no more features to split on, then return leaf node predicting majority class if ...
def spr_sidebar(): """ Renders the sidebar for the app and sets the app mode based on the selected option. """ menu = option_menu( menu_title=None, options=['Home', 'Results', 'About'], icons=['house', 'book', 'info-square'], menu_icon='cast', default_index=0, ...
The main task of the code is to run a Streamlit app that dynamically renders different pages (Home, Results, About) based on the user-selected mode from the sidebar, using session state to track the current mode and conditional calls to corresponding page functions.
def main(): """ Main function to run the app. Renders different pages based on the app mode set in the sidebar. """ spr_sidebar() if st.session_state.app_mode == 'Home': home_page() if st.session_state.app_mode == 'Results': result_page() if st.session_state.app_mode == 'Abou...
def handle_all_dirs_operations(dir: os.DirEntry, n): handle_biggest_dirs(dir, n) print(f'Biggest Directories: {biggest_dirs}\n') def handle_all_file_operations(file: os.DirEntry, n): handle_duplicate(file) handle_newest_files(file, n) handle_oldest_files(file, n) print(f'Newest files: {newest_fi...
The main task of the code is to recursively scan directories starting from a given path, processing each directory and file with specific handler functions (`handle_all_dirs_operations` for directories and `handle_all_file_operations` for files). It traverses all subdirectories and collects directory information, thoug...
def scan_dirs(path: str, n): """Goes over all the dirs in the given path and returns a list of all the directories containing their info. Parameters: -------------- path: str, required The parent directory which acts as the starting path for the scan. dir_list: list, required ...
def parse_args(): parser = argparse.ArgumentParser(prog='p144') parser.add_argument('--pbrt-folder', type=str, help='path to pbrt binaries folder', required=True) parser.add_argument('--ignore-errors', action='store_true', default=False) parser.add_argument('--incremental', action='store_true', default=...
The code validates input parameters for a rendering task, ensuring 4 unique scenes, 3 integrators, 4 samplers, 3 sample counts, and 144 total combinations. It checks these conditions, prints errors if violated, and runs combinations if valid.
def main(): parser = parse_args() scenes = [] scene_filenames = [] for f in parser.scenes: ftext = f.read() scenes.append(ftext) scene_out = modify_scene(ftext, "test_integrator", "test_sampler", "test_sample_count", test=True) if scene_out == False: eprint(...
def setup_new_profile(): webbrowser.open_new_tab("https://dev.twitch.tv/console/apps") client_id = input("Enter the Client ID: ") client_secret = input("Enter the Client Secret: ") channel_list = input("Enter your twitch channel: ") to_write = [ f'TWITCH_CLIENT_ID="{client_id}"', f'T...
The main task of the code is to retrieve a valid Twitch OAuth access token by checking environment variables, handling token expiration, and refreshing tokens when necessary. It ensures a valid token is obtained either from existing files, refresh tokens, or by requesting new ones, exiting if unsuccessful.
def get_token() -> str: if not os.path.isfile(DOTENV_FPATH): setup_new_profile() load_dotenv() client_id = os.environ[TWITCH_CLIENT_ID] client_secret = os.environ[TWITCH_CLIENT_SECRET] redirect_uri = os.environ[TWITCH_REDIRECT_URI] if not os.path.isfile(OAUTH_TOKEN_FPATH): acce...
def step(self): #check if we're at EOF if(self.pos == len(self.tokens) -1): self.end_cursor() else: self.pos = self.pos + 1 def eval_token(self, token): # get function from tables func_pack = table_king.check_token(token) # if the functio...
The main task of the code is to process tokens by comparing them to function tables, execute corresponding functions if matched, and add unmatched tokens to the data stack. It advances processing via `self.step()`, evaluates the current token using `eval_token()`, and recursively continues processing tokens through `re...
def read_tokens(self): """compares tokens to function tables, then executes the corresponding function. if no match is found, the token is added to the data stack """ self.step() if self.active: self.eval_token(self.tokens[self.pos]) self.read_tokens()
def get_new_course_sequence(table_data, index): string_data = table_data[index].strong.string.lower() course_type = get_course_type(string_data) num_required = get_num_required(table_data, index) return num_required, course_type def is_num_required(table_element, index): return table_element[index]....
The function parses an HTML course table, extracting course sequences and individual courses. It identifies different row structures to determine course types (prerequisites, options, etc.), processes data accordingly, and builds a Program object with the extracted information, cleaning it before returning.
def get_program_data(course_table): course_type = CourseType.prereq program = Program() index = 1 table_data = course_table.find_all('tr') while index < len(table_data): if len(table_data[index]) == 2 and table_data[index].find('strong') is not None: new_sequence_data = get_new...
def get_url(config, program_name, program_type): if program_type == ProgramType.immersion: return config['immersions']['immersion_site'] + program_name elif program_type == ProgramType.minor: return config['minor']['minor_site'] + program_name return config['major']['major_site'] + program_n...
The main task of the code is to fetch and parse data from a webpage based on provided configuration and program details. It constructs a URL, retrieves HTML content, extracts specific elements like notes and program data using BeautifulSoup, structures the information into a program object, and returns it with associat...
def get_data(config, program_name, program_type): url = get_url(config, program_name, program_type) immersion_page = urllib.request.urlopen(url).read() soup = BeautifulSoup(immersion_page, features='html.parser') notes = get_notes(soup.find_all('ul')[2]) program = get_program_data(soup.table.tbody...
def get_product(pid, user): return make_request('get', user, '/product', { 'pid': pid }, lambda x: pid == x['pid']) def place_order(pid, user): ret = make_request('post', user, '/order', { 'pid': pid, 'uid': user['uid'] }) # print(ret) return ret def pay_order(order_id, u...
The main task of the code is to simulate a user's interaction with a product by randomly selecting a user and product, retrieving product details, placing an order, and attempting payment if the order succeeds. It collects results from these steps and returns them via a pipe. The process includes handling user selectio...
def run_all(user_index=None): user = None if user_index is not None: user = user_list[user_index] else: user = user_list[random.randint(0, len(user_list) - 1)] userQueue.put(user['uid']) product = product_list[random.randint(0, len(product_list) - 1)] ret_result = [] print('U...
def greedyExe(self): result = [] env = gym.make(self.scenario) q = self.q_init(env) for i_episode in range(self.episode_num): old_state = env.reset() if self.scenario == "CartPole-v1": old_state = self.discrete_state(old_state) reward_s...
The main task of the code is to execute a greedy algorithm 10 times, collect results in a matrix, compute average values from these results, and calculate two distinct reward averages. This process likely evaluates the performance or outcomes of the greedy approach through statistical aggregation.
def initGreedy(self): matrix = [] for _ in range(10): result = self.greedyExe() matrix.append(result) self.avg_values = self.avgValues(matrix) self.reward_avg = self.reward_average() self.reward_avg_2 = self.reward_average_2()
def find_near_vertices(tree: Tree, new_vertex: Vertex, near_dist: float, reachable_dist: typing.Optional[float]) -> \ typing.List[Vertex]: n_vertices = len(tree.vertices) dist_range = near_dist * math.sqrt(math.log(n_vertices) / n_vertices) if reachable_dist: dist_range = min(reachable_dist...
This function extends a tree in a path planning algorithm by generating a new sample, finding the nearest vertex, creating a trajectory to the sample, checking for collisions, adding a new vertex to the tree, optimizing its parent connection, rewiring nearby paths, and checking if the goal is reached.
def update_tree( env: Environment, params: Parameters, goal: Point2d, steering_policy: typing.Callable[ [Vertex, Point2d], typing.Tuple[float, Trajectory] ], nearest_policy: typing.Callable[[Point2d, Tree], Vertex], sample_generation_policy: typing.Cal...
def reduce_graph(adj, nIS_vec_local, pnum, lock): global best_IS_num global best_IS_vec global bsf_q global adj_0 global q_ct global id global out_id global res_ct remain_vec = (nIS_vec_local == -1) # reduce graph # reduced_node, reduced_adj, mapping, reverse_mapping, crt_i...
The code implements a parallel search algorithm for finding the maximum independent set (MIS) in a graph using a deep graph convolutional network (GCN). It leverages TensorFlow for model training, processes graph structures through neural network evaluation, and employs multi-threading with locks to explore candidate s...
def MPSearch(pnum, lock): import tensorflow as tf from models import GCN_DEEP_DIVER global best_IS_num # global bsf_q # global q_ct # global res_ct # global best_IS_vec # global start_time global adj_0 global opt_num global edges_0 global nn global features_all ...
def test_reg_tform(img): img = img.copy() img = (img - img.mean()) / img.std() # normalize img img = torch.tensor(img) img, nonpadded_crop = padd_test_img(img) return img[None][None], nonpadded_crop def tt_aug_tform(img): img = img.copy() sigmas = [0, 0.001, 0.005, 0.01, 0.1] probs = [...
This function predicts test images using a trained model, applies optional test-time augmentation, and saves segmentation results as NIfTI files. It processes each batch in evaluation mode, transforms inputs, generates predictions via argmax, adjusts crop regions, and logs results with Weights & Biases if enabled. Outp...
def predict_test_set(model, test_loader, device, save_dir, tt_aug=None, num_of_aug=40, wandb_callback=False, wandb_args=None): if wandb_callback: assert wandb_args # the args need to be not None wandb.login(key='588ccf0f1631d995e385af0b2675f0214d2fb9ff') # team-dd wand...
def compute_gradients(self, X, y_true): """ X: d x batch_size y_true: k x batch_size """ size = y_true.shape[1] y_pred, h = self.evaluate_classifier(X) g_batch = y_pred - y_true grad_w2 = np.dot(g_batch, h.T) / size + 2 * self.lamda * self.w2 ...
The code trains a neural network using mini-batch gradient descent with cyclical learning rate scheduling. It iterates over epochs, shuffles batches, computes gradients, updates weights, and tracks training/validation costs/accuracies. After training, it evaluates test accuracy and optionally plots performance metrics.
def train(self, x_train, y_train, x_val, y_val, x_test, y_test): num_batches = int(x_train.shape[1] / self.batch_size) self.ns = 10 * num_batches train_cost_hist = [] train_acc_hist = [] val_cost_hist = [] val_acc_hist = [] lr_vs_acc = [] lr = [] ...
def compute_gradients(self, X, y_true, loss="cross entropy"): """ X: d x batch_size y_true: k x batch_size """ size = y_true.shape[1] if loss == "cross entropy": y_pred = self.evaluate_classifier(X) g_batch = y_pred - y_true gra...
The code trains a machine learning model using mini-batch gradient descent with learning rate decay. It iterates over epochs, shuffles batches, computes gradients, updates model parameters, and tracks training/validation loss, cost, and accuracy. After each epoch, it decays the learning rate, evaluates metrics, and log...
def train(self, x_train, y_train, x_val, y_val, x_test, y_test): num_batches = int(x_train.shape[1] / self.batch_size) train_loss_hist = [] train_cost_hist = [] train_acc_hist = [] val_loss_hist = [] val_cost_hist = [] val_acc_hist = [] for i in range(s...
def evaluate_classifier(self, X): """ w: k x d X: d x n b: k x 1 output: n x k """ return self.softmax(np.dot(self.w, X) + self.b) def compute_gradients(self, X, y_true, loss="cross entropy"): """ X: d x batch_size y_true: k x batch_...
The main task of the code is to compare analytically computed gradients (grad_w, grad_b) with numerically approximated gradients (grad_w_num, grad_b_num) using a mean squared error metric. It evaluates a classifier's predictions, computes gradients via analytical and numerical methods, then prints the MSE between them ...
def check_gradients(self, X, y_true): y_pred = self.evaluate_classifier(X) grad_w, grad_b = self.compute_gradients(X, y_true) grad_w_num, grad_b_num = self.ComputeGradsNum(X, self.w, self.b, self.lamda, y_true, y_pred, 1e-6) print("MSE: ", np.mean((grad_w - grad_w_num) ** 2))
def mkdirs( p ): try: os.makedirs( p ) except FileExistsError: pass def GetGadgetConfigDir( vimspector_base ): return os.path.join( GetGadgetDir( vimspector_base ), '.gadgets.d' ) def GetConfigDirForFiletype( vimspector_base, filetype ): if not filetype: filetype = 'default' return os.path.join( ...
The code creates necessary directories for a plugin's configuration by generating paths based on the provided base directory and a universal '_all' filetype, ensuring proper structure for different file types.
def MakeInstallDirs( vimspector_base ): mkdirs( GetGadgetConfigDir( vimspector_base ) ) mkdirs( GetConfigDirForFiletype( vimspector_base, '_all' ) )
def _FindLineBreakpoint( self, file_name, line ): file_name = os.path.abspath( file_name ) for index, bp in enumerate( self._line_breakpoints[ file_name ] ): self._SignToLine( file_name, bp ) if bp[ 'line' ] == line: return bp, index return None, None def _PutLineBreakpoint( self, file_...
(Toggles a breakpoint in a Vim buffer: adds it if absent, disables if enabled and disconnected, or deletes if already active. Updates the UI afterward.)
def ToggleBreakpoint( self, options ): line, _ = vim.current.window.cursor file_name = vim.current.buffer.name if not file_name: return bp, index = self._FindLineBreakpoint( file_name, line ) if bp is None: # ADD self._PutLineBreakpoint( file_name, line, options ) elif bp[ 's...
def _FindLineBreakpoint( self, file_name, line ): file_name = os.path.abspath( file_name ) for index, bp in enumerate( self._line_breakpoints[ file_name ] ): self._SignToLine( file_name, bp ) if bp[ 'line' ] == line: return bp, index return None, None def _PutLineBreakpoint( self, file_...
This function sets or updates a line breakpoint in a debugger. It checks if a breakpoint exists at the specified file and line; if so, it updates its options. If not, it creates a new breakpoint. Finally, it triggers a UI update with the provided 'then' parameter to handle post-breakpoint actions.
def SetLineBreakpoint( self, file_name, line_num, options, then = None ): bp, _ = self._FindLineBreakpoint( file_name, line_num ) if bp is not None: bp[ 'options' ] = options return self._PutLineBreakpoint( file_name, line_num, options ) self.UpdateUI( then )
def _FindLineBreakpoint( self, file_name, line ): file_name = os.path.abspath( file_name ) for index, bp in enumerate( self._line_breakpoints[ file_name ] ): self._SignToLine( file_name, bp ) if bp[ 'line' ] == line: return bp, index return None, None def _DeleteLineBreakpoint( self, bp...
The function `ClearLineBreakpoint` removes a breakpoint set at a specified line in a given file. It first locates the breakpoint using `_FindLineBreakpoint`; if found, it deletes the breakpoint via `_DeleteLineBreakpoint` and triggers a UI update with `self.UpdateUI()` to reflect the change. If no breakpoint exists at ...
def ClearLineBreakpoint( self, file_name, line_num ): bp, index = self._FindLineBreakpoint( file_name, line_num ) if bp is None: return self._DeleteLineBreakpoint( bp, file_name, index ) self.UpdateUI()
def _FindLineBreakpoint( self, file_name, line ): file_name = os.path.abspath( file_name ) for index, bp in enumerate( self._line_breakpoints[ file_name ] ): self._SignToLine( file_name, bp ) if bp[ 'line' ] == line: return bp, index return None, None def _DeleteLineBreakpoint( self, bp...
The main task of the code is to remove a temporary breakpoint at a specified line in a file, if it exists. It checks if the breakpoint is marked as temporary, deletes it if so, and updates the UI to reflect the change.
def ClearTemporaryBreakpoint( self, file_name, line_num ): bp, index = self._FindLineBreakpoint( file_name, line_num ) if bp is None: return if bp[ 'options' ].get( 'temporary' ): self._DeleteLineBreakpoint( bp, file_name, index ) self.UpdateUI()
def read_input(path: str): assert os.path.getsize(path) < INPUT_SIZE_LIMIT, 'This input file is too large' with open(path) as fp: G = nx.node_link_graph(json.load(fp), multigraph=False) if validate_input(G): return G def write_output(G: nx.Graph, path: str, overwrite=False): asse...
The code processes an input file using a solver, writes the result to an output file, and prints the input file name with its score. It reads the input, applies the solver, updates the instance if output exists, writes to the output file (overwriting if allowed), and displays the cost.
def run(solver, in_file: str, out_file: str, overwrite: bool=False): print(in_file) instance = read_input(in_file) output = solver(instance) if output: instance = output write_output(instance, out_file, overwrite) print(f"{str(in_file)}: cost", score(instance))
def read_input(path: str): assert os.path.getsize(path) < INPUT_SIZE_LIMIT, 'This input file is too large' with open(path) as fp: G = nx.node_link_graph(json.load(fp), multigraph=False) if validate_input(G): return G def visualize(G: nx.Graph): output = G.nodes(data='team', defau...
The main task of the code is to process an input file using a solver, visualize the resulting solution, and save the output to a specified file. It reads the input, applies the solver, updates the instance if output is generated, visualizes the result, writes the final instance to the output file (overwriting if allowe...
def run_vis(solver, in_file: str, out_file: str, overwrite: bool=False): print(in_file) instance = read_input(in_file) output = solver(instance) if output: instance = output visualize(output) write_output(instance, out_file, overwrite) print(f"{str(in_file)}: cost", score(instance))
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def get_user_to_select_a_goal(array_of_goals,verb="work on"): hide = True if verb == "work on" else False print(f"please select a goal to {verb} from the following") print_all_goals(array_of_goals,hide) selection = input() if s...
The code manages goal-based task organization by letting users select a goal, add subtasks, work on subgoals, or toggle their visibility. It integrates with ManicTime for tracking, recursively handling subgoals and updating the database with new tasks. The main task is interactive goal management with hierarchical task...
def work_on_goal(array_of_goals): clear_screen() selected_goal = get_user_to_select_a_goal(array_of_goals) if selected_goal==None: print("not found") return clear_screen() print("cool lets work on \n", selected_goal["name"]) add_to_manictime(get_mt_tag(selected_goal),selected_...
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def save_to_database(): database.truncate() for qn in main_questions_array: database.insert(qn) def work_on_Question(array_of_questions): selected_question = get_user_to_select_a_Question(array_of_questions) if selected_qu...
The main task of the code is to provide a menu-driven interface for managing questions. It allows users to add new questions (storing titles in a list and saving to a database) or work on existing questions. The loop continues until the user selects 'q' to quit, with options to add questions (option 2) or process exist...
def main(): selection = "a" while selection != 'q': if selection == "2": clear_screen() question_title = input("enter title of new question\n") if question_title == 'q': return main() new_question = Question(question_title) main_questions_array...
def parse_service_name(self): pb_head_file = self.src_pb_path + '/' + self.project_name + '.pb.h' file = open(pb_head_file, 'r') origin_text = file.read() # parse all rpc interface method from pb.h file begin = origin_text.find('virtual ~') i1 = origin_text[begin...
The main task of the code is to generate a minimal RPC framework by orchestrating multiple steps: parsing service names, creating exception classes, defining include files, generating server implementation, main execution logic, interface base classes, and individual service interfaces. This method initializes the fram...
def generate_framework_code(self): print('=' * 100) print('Begin to generate tinyrpc framework code') self.parse_service_name() self.gen_exception() self.gen_include_name() self.gen_server() self.gen_main() self.gen_interface_base() self.ge...
def parseInput(self): opts,args=getopt.getopt(sys.argv[1:],"hi:o:p:h:",["help","input=","output="]) for opts,arg in opts: if opts=="-h" or opts=="--help": self.printHelp() sys.exit(0) if opts=="-i" or opts=="--input": self.proto_fil...
This code generates a TinyRPC project by creating directory structures, protocol buffer files (.proto), Makefile, run scripts, configuration files, and framework code. It parses input first, then sequentially generates project components, handling exceptions to print error details if failures occur during generation.
def generate_tinyrpc_project(self): try: self.parseInput() print('=' * 150) print('Begin generate tinyrpc project') self.generate_dir() self.gen_pb_files() self.gen_makefile() self.gen_run_script() self.gen_co...
def get_font(size): # Returns Press-Start-2P in the desired size return pygame.font.Font("font.ttf", size) def try_again(): main_page() def quit(): pygame.quit() sys.exit()
The main task of the code is to display a game over menu with "THE END!" text and two interactive buttons ("Restart" and "QUIT") using Pygame. It continuously updates the screen, detects mouse interactions, and triggers actions: restarting the game or exiting when buttons are clicked. The loop handles events like quitt...
def main_menu(): while True: SCREEN.blit(BG, (0, 0)) MENU_MOUSE_POS = pygame.mouse.get_pos() MENU_TEXT = get_font(70).render("THE END!", True, "White") MENU_RECT = MENU_TEXT.get_rect(center=(620, 270)) TRY_AGAIN_BUTTON = Button(image=None, pos=(640,...
def _build_model(self, n_features): """ Creates the computational graph. :type n_features: int :param n_features: Number of features. :return: self """ self.input_data, self.input_data_corr = self._create_placeholders(n_features) self.W_, self.bh_, self.bv_ = s...
The main task of the code is to train a TensorFlow model using the provided training data, optionally with validation data, and save the trained model. It builds the model architecture based on the input features, initializes TensorFlow utilities, executes training, and persists the model to disk. If `restore_previous_...
def fit(self, train_set, validation_set=None, restore_previous_model=False): """ Fit the model to the data. :param train_set: Training data. :param validation_set: optional, default None. Validation data. :param restore_previous_model: if true, a previous trained mod...
def score(self,original): i=1 chosen_idx = random.randrange(apilen) # Send the sample to VirusTotal for pop in self.population: if pop.vt_result != None: i+=1 continue # p.build_lief(pop.fbytes,original.name) p...
The code's main task is to evolve a population of malware samples through generations by applying mutations and selection, tracking metrics like functionality, VirusTotal detection rates, and perturbations. It logs detailed statistics for each generation and individual, aiming to generate variants with desired properti...
def generation(self,original,gnum): self.score(original) # self.score_without_vt(original) if self.generationnum == 1: with open(self.output_path,"a") as wf: wf.write("1 generation\n") func = 0 for i in range(self.size): ...
def prepare_telegram_token(): if os.path.exists('telegram.json'): return config = { 'token': input('Please enter Telegram bot token: '), 'chat_id': input('Please enter Telegram chat id: ') } with open('telegram.json', 'w') as fo: json.dump(config, fo) def zerofill_disk(di...
The main task of the code is to capture and upload a disk image to Amazon S3, focusing only on changed blocks to optimize storage. It uses command-line arguments for the local disk path and S3 destination name, handles errors via Telegram notifications, and includes steps to zero-fill the disk and process blocks before...
def main(): parser = argparse.ArgumentParser( prog='./disk2s3blocks.py', description='Captures and uploads a disk image to S3, minding the changed blocks' ) parser.add_argument('disk_path', help='Local path to the block device, e.g. /dev/sda') parser.add_argument('s3_name', help='Disk im...
def validate_is_valid_dna(raw_dna): validate_is_valid_dna_letters(raw_dna) validate_is_valid_dna_proper_array(raw_dna) validate_is_valid_dna_proper_array_groups(raw_dna) def update_dna(dna): return db.run_query(update_dna_query, (dna,)) def get_dna(dna): return db.run_query(get_dna_query, (dna,)) de...
The function determines if input DNA is mutant by validating it, converting to a string, updating DNA data, and checking the result. If update_dna returns a positive value, it verifies the creation type. Otherwise, it checks via is_mutant, saves the DNA as mutant or human, and returns the corresponding boolean result.
def create_mutant(raw_dna) -> bool: validate_is_valid_dna(raw_dna) dna_plain_string = ''.join(raw_dna) result = update_dna(dna_plain_string) if result > 0: result = get_dna(dna_plain_string) (key, creation_type, count) = result[0] return DNA_TYPE_MUTANT == creation_type else:...
def sendAllDown(cubes): """Sends all cubes one row down""" result = False for y in range(rowY-1,-1,-1): for x in range(rowX): cube = findCube(x, y, cubes) if (cube): if cube.moveDown(cubes): result = True return result def refreshScreen...
The main task of the code is to move cubes downward with a delay of `n` seconds, refresh the screen if enabled, and generate new random cubes if movement occurred. It returns `True` if any cubes moved, otherwise `False`.)>
def downAction(screen, cubes, n): """Action of moving down with delay of n seconds""" i = 0 while sendAllDown(cubes): time.sleep(n) if(display): refreshScreen(screen, cubes) i += 1 for cube in cubes: cube.merged = False if i != 0: genRand...
def sendAllUp(cubes): """Sends all cubes one row up""" result = False for y in range(0,rowY): for x in range(rowX): cube = findCube(x, y, cubes) if (cube): if cube.moveUp(cubes): result = True return result def refreshScreen(screen, cub...
This function moves cubes upward with a delay, refreshing the screen if enabled. It repeatedly attempts to move all cubes up, pauses for `n` seconds each time, and tracks iterations. Afterward, it resets cube merge states and generates new cubes if movement occurred, returning `True` if any action was performed, otherw...
def upAction(screen, cubes, n): """Action of moving up with delay of n seconds""" i = 0 while sendAllUp(cubes): time.sleep(n) if(display): refreshScreen(screen, cubes) i += 1 for cube in cubes: cube.merged = False if i != 0: genRandom(cub...
def sendAllLeft(cubes): """Sends all cubes one row left""" result = False for x in range(0,rowX): for y in range(rowY): cube = findCube(x, y, cubes) if (cube): if cube.moveLeft(cubes): result = True return result def refreshScreen(scree...
The function `leftAction` moves cubes left with a delay, repeatedly applying left movement until no more can occur. It updates the screen if enabled, resets cube merge statuses, and generates new random cubes if movement happened, returning `True` if any action occurred, otherwise `False.`
def leftAction(screen, cubes, n): """Action of moving left with delay of n seconds""" i = 0 while sendAllLeft(cubes): time.sleep(n) if(display): refreshScreen(screen, cubes) i += 1 for cube in cubes: cube.merged = False if i != 0: genRandom(c...
def sendAllRight(cubes): """Sends all cubes one row right""" result = False for x in range(rowX-1,-1,-1): for y in range(rowY): cube = findCube(x, y, cubes) if (cube): if cube.moveRight(cubes): result = True return result def refreshScr...
The main task of the code is to move cubes right with a delay, repeatedly until no further movement occurs. It refreshes the screen if enabled, resets cube merge states, and generates new random cubes if movement happened. The function returns True if any movement occurred, otherwise False.
def rightAction(screen, cubes, n): """Action of moving right with delay of n seconds""" i = 0 while sendAllRight(cubes): time.sleep(n) if(display): refreshScreen(screen, cubes) i += 1 for cube in cubes: cube.merged = False if i != 0: genR...
def downAction(screen, cubes, n): """Action of moving down with delay of n seconds""" i = 0 while sendAllDown(cubes): time.sleep(n) if(display): refreshScreen(screen, cubes) i += 1 for cube in cubes: cube.merged = False if i != 0: genRand...
This function handles keyboard input events to control cube movements on a screen. It detects arrow key presses, triggers corresponding directional actions (down/up/left/right), and uses a 'keyReady' flag to prevent repeated actions during key holds. The function is designed as a default input handler, intended for cus...
def getInput(screen, cubes, event): """Default input configuration. Intended to be rewritten for algorithms. User-defined by default.""" global keyReady if event.type == pygame.KEYUP: keyReady = True if event.type == pygame.KEYDOWN and keyReady: keyReady = False if event.key == p...
def getInput(screen, cubes, event): """Default input configuration. Intended to be rewritten for algorithms. User-defined by default.""" global keyReady if event.type == pygame.KEYUP: keyReady = True if event.type == pygame.KEYDOWN and keyReady: keyReady = False if event.key == p...
The code defines the main function for a 2048 game, initializing Pygame, setting up the game window, and managing game logic. It creates initial tiles, handles user input, updates the game state, and renders the screen. The loop processes events (e.g., quitting), updates cube positions, and refreshes the display. Final...
def main(): """Run game of 2048""" pygame.init() pygame_window_title = '2048' pygame.display.set_caption(pygame_window_title) screen = pygame.display.set_mode((SCREENX, SCREENY), pygame.RESIZABLE) screen.fill((205, 193, 180)) global score global gameRunning gameRunning = ...
def get_plan_module_id_list(self, plan_id: int) -> Union[List[int], None]: id_list = None result = self.__get_rows(SELECT_PLAN_MODULE_IDS, (plan_id,)) if result: id_list = [row["moduleId"] for row in result] return id_list def associate_modules_to_plan(self, plan_id: int, mod...
The function updates a plan's associated modules by synchronizing the existing module IDs with a new list. It removes modules no longer in the new list and adds new ones not previously associated, then returns the updated module ID list for the plan.
def update_plan_modules( self, plan_id: int, new_module_list: Union[List[int], None] ) -> Union[List[int], None]: existing_ids = self.get_plan_module_id_list(plan_id) if not existing_ids: self.associate_modules_to_plan(plan_id, new_module_list) else: delete_li...
def __write_data(self, query: str, params: Tuple[Any] = ()) -> int: cur = self.__get_cursor().execute(query, params) row_id = cur.lastrowid assert isinstance(row_id, int), 'Did not receive row_id from INSERT call.' cur.connection.commit() return row_id def update_plan_modules( ...
The main task of the code is to update a plan by writing its title and ID, updating its modules, and retrieving the modified plan. It invokes `__write_data` to store plan details, `update_plan_modules` to adjust modules, and `get_plan` to fetch the updated plan, ensuring data consistency and module synchronization.
def update_plan(self, plan: Plan) -> Plan: self.__write_data(UPDATE_PLAN, (plan.title, plan.id)) self.update_plan_modules(plan.id, plan.modules) return self.get_plan(plan.id)
def random_tree_of_depth(depth, n_nodes, seed=None): assert depth < n_nodes assert depth > 0 assert n_nodes > 0 if seed is not None: seed_all(seed) node_names = list(range(n_nodes)) random.shuffle(node_names) nodes = [TreeNode(n) for n in node_names] for i in range(depth): ...
The code generates a random tree structure with specified node count and depth, converts it into token sequences representing the tree path and goal, then processes these tokens into input indices using a tokenizer for model input preparation.
def generate_sample(self, n_nodes, possible_depths, seed=None): depth = random.choice(possible_depths) tree, goal = random_tree_of_depth(depth=depth, n_nodes=n_nodes, seed=seed) prompt_tokens, path_tokens = create_tree_path(tree, goal) return create_input_idx(prompt_tokens, path_tokens, ...
def validate_input(self, player_input, players_output, prompt, desire_type, allawed_input=None, error_mess="Invalid Option!", str_len=None): ''' loop while receive correct value param allowed_input can be list of allowed values param str_len is two sized tuple if m...
The main task of the code is to connect a player to a game server by validating their input of a game password with up to three attempts. If the password matches `self.GamePass`, the player proceeds to choose a name; otherwise, their connection is closed. The loop ensures players repeatedly attempt the password until c...
def connect_player(self,player): Pass = 0 #cicle for all players trying to connect while Pass != self.GamePass: player.conn, addr = self.server.accept() #3 chances per player to guess the Pass for i in range(3): prompt = "Game Password? (try " ...
def myprint(self, players_IDs, msg): #for debug print(msg) msg = msg + "\n" if players_IDs == PRINT_TO_ALL: #send message to all connected players for player in self.game.players: if player.conn is not None: player.conn.send(msg...
The main task of the code is to allow the "MASTER" to add up to four players in a game. It initializes player setup, iterates to add players with formatted prompts, and provides a menu to either add more players or start the game with the current count. Input validation ensures valid choices, breaking the loop when the...
def master_prompt_for_players(self): '''put all players in the game''' counts = ("first", "second", "third", "fourth last") text_add = "Add {} player" for i in range(2): if i == 0: self.myprint([MASTER],"Setting up your player (MASTER)") else: ...
def master_prompt_for_players(self): '''put all players in the game''' counts = ("first", "second", "third", "fourth last") text_add = "Add {} player" for i in range(2): if i == 0: self.myprint([MASTER],"Setting up your player (MASTER)") else: ...
This method initializes a new game by prompting players, waiting for their connections, and displaying their information.
def load_players_for_new_game(self): self.master_prompt_for_players() self.wait_for_connections() self.print_players_info()
def myprint(self, players_IDs, msg): #for debug print(msg) msg = msg + "\n" if players_IDs == PRINT_TO_ALL: #send message to all connected players for player in self.game.players: if player.conn is not None: player.conn.send(msg...
The code initializes a game by setting up a master player, loading game data, and starting the game loop. It handles graceful exit on keyboard interrupts or EOF errors, printing an exit message. The method configures game components, adds the master player, retrieves game pass info, and proceeds to play the game after ...
def start(self, master_conn, server): '''main method, starting cli''' self.master_conn = master_conn self.server = server master = Player(MASTER, "yellow", 'Master', None, master_conn) self.game.add_player(master) self.myprint(PRINT_TO_ALL,'\n') self.GamePass = se...
def read_queries(): with open("data/100QueriesSet4.txt", "r") as f: queries = f.readlines() return queries def read_google_result(): with open("data/Google_Result4.json", "r") as j: result = json.load(j) return result def read_json_result(file_name): with open(file_name, "r") as j: ...
The main task of the code is to process search query data from multiple sources (Google, DuckDuckGo) by reading JSON files, analyzing them with a helper function to generate statistical results, and then exporting these results to a CSV file for further analysis or reporting.
def main(): queries = read_queries() google_result = read_google_result() duckduckgo_result = read_json_result("data/hw1.json") stat_result = task_two_helper(queries, duckduckgo_result, google_result) write_csv("data/hw1.csv", stat_result)
def Empezar(Texto:string) -> int: pos_init=0 romper:bool=False while pos_init<len(Contenido) and not romper: pos:int=Conseguir_inicio("CLASS=")+1 pos_init=pos if pos_init<len(Contenido)-1: while Contenido[pos]!="\"": pos+=1 clase:string= Conte...
This function extracts specific web elements based on given tags, processes content to identify and retrieve element data, increments a global counter when a match is found, and appends extracted information to a global results list. It handles text slicing, element identification, and data extraction for targeted web ...
def COnseguir_clase(Clase:string,ELMNT:string) -> int : Clase= Clase.upper() #Buscaremos la clase que queremos Indicio:int=Empezar(Clase) #Indicio:int= Conseguir_inicio(Clase) #Buscaremos el inicio del elemento Indicio= Buscar_ini_elemento(Indicio) #Buscamos que etiqueta es nuestro elemento ...
def add_message(self, message: str): self.messages.append(message) def basic_chat( self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str, ): print(f"basic_chat(): {agent_a.name} -> {agent_b.name}") agent_a.send(message, agen...
The main task of the code is to orchestrate a sequential conversation between agents, passing messages either through basic chat or function calls. It iterates through agent pairs, processes the latest message, and checks if the final message contains a "complete" keyword to determine success, returning a boolean and m...
def sequential_conversation(self, prompt: str) -> Tuple[bool, List[str]]: """ Runs a sequential conversation between agents For example "Agent A" -> "Agent B" -> "Agent C" -> "Agent D" -> "Agent E" """ print(f"\n\n--------- {self.name} Orchestrator Starting --------...
def add_message(self, message: str): self.messages.append(message) def memory_chat( self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str, ): print(f"memory_chat() '{agent_a.name}' --> '{agent_b.name}'") agent_a.send(message...
The main task of the code is to broadcast a message from the first agent to all other agents in a conversation, handling both string-based messages and function calls. It iterates through each agent, logs interactions, updates memory, and returns a success status along with the conversation history.
def broadcast_conversation(self, prompt: str) -> Tuple[bool, List[str]]: """ Broadcast a message from agent_a to all agents. For example "Agent A" -> "Agent B" "Agent A" -> "Agent C" "Agent A" -> "Agent D" "Agent A" -> "Agent E" """ ...
def icmp_reply(): try : # local_ip = [int(x) for x in socket.gethostbyname(socket.gethostname()).split('.')] #print(local_ip) conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) while ...
The main task of the code is to prompt the user for input and execute one of three functions—icmp_reply(), arp_reply(), or dns_reply()—based on whether the input matches 'ICMP', 'ARP', or 'DNS', respectively.
def main(): inp = input('what ? ') if(inp == 'ICMP'): icmp_reply() elif(inp == 'ARP'): arp_reply() elif (inp == 'DNS'): dns_reply()
def csv2dict(csv_string): """ Convert a CSV file in the form of a string to a dictionary of lists """ data_dict = {} # Convert the CSV string to a list of rows csv_rows = csv_string.splitlines() # Use the first row as column headers headers = csv_rows[0].split(',') num_columns = le...
The code analyzes CSV frequency data to detect intermodulation conflicts, generating detailed reports. It processes input CSV strings into frequency lists, checks for conflicts, and accumulates aggressor/victim scores. If multiple frequency lists are present, it compiles aggregate scores. The function returns a report ...
def analyze(csv_string, label_equations): """ Analyze the list of frequencies in the CSV file for intermod conflicts. Args: csv_string (string): The user's CSV file in the form of one long string. label_equations (boolean): If True, label the frequencies that appear ...
def redo(self): if self.RStack.size() > 1: text = self.RStack.peek() self.TextBox.delete('1.0', END) self.TextBox.insert(END, text) self.UStack.add(text) self.RStack.remove() def undo(self): self.isFileChange = True if self.UStack.size(...
This code handles keyboard events to perform actions like undo/redo, file operations, and track text changes. It uses a stack (UStack) to record input states, updates it on key presses (e.g., Enter, Backspace, arrows), and marks file changes. Specific keys trigger functions like retrieve_input, open_file, or quit. It a...
def key_pressed(self, event): if event.char == "\x1a" and event.keysym == "Z": self.redo() elif event.char == "\x1a" and event.keysym == "z": self.undo() elif event.char == "\x13": self.retrieve_input() elif event.char == "\x0f": self.open_...
def send_to_client(package): package = pickle.dumps(package) conn.send(package) def create_and_send_table(player): x = player[0] y = player[1] ind_x = player[2] ind_y = player[3] table = [['.' for i in range(table_size)]for i in range(table_size)] table[x][y] = "X" table[ind_x][ind_...
The function `prepare_to_game` handles client input to initiate or exit a game. If the input is 'y', it sends a "GO!" message, generates random non-edge coordinates for a player, creates and sends the game table, then waits for the client to start the game. If the input is 'n', it sends a farewell and closes the connec...
def prepare_to_game(data, connection): while True: if data == 'y': answer = "\nGO!\n" send_to_client(answer) while True: ind_x = random.randint(0, table_size-1) ind_y = random.randint(0, table_size-1) if (ind_x != 0 and in...
def make_set(parent, rank, n): for i in range(n): parent[i] = i rank[i] = 0 def find_parent(parent, component): if parent[component] == component: return component parent[component] = find_parent(parent, parent[component]) return parent[component] def union_set(u, v, parent, ran...
The code implements **Kruskal's algorithm** to compute the **total weight of a Minimum Spanning Tree (MST)** for a given graph. It sorts edges by weight, uses Union-Find (disjoint set) to detect cycles, and adds edges to the MST if they connect disjoint components. The final sum of selected edge weights is returned as ...
def kruskal_algo(n, edge): edge.sort(key=lambda x: x[2]) parent = [0] * n rank = [0] * n make_set(parent, rank, n) min_cost = 0 for i in range(len(edge)): v1 = find_parent(parent, edge[i][0]) v2 = find_parent(parent, edge[i][1]) wt = edge[i][2] if v1 != v2: ...
def playMove(board,move): pieces=copy.deepcopy(board) if move[0]=='set': player=move[1] x=move[2] y=move[3] z=move[4] pieces['pieces'][x][y][z]=player if player==1: pieces['countWhite']-=1 pieces['onBoardWhite']+=...
The function `getMoves` generates all valid moves for a given player on a board, considering both placing new pieces (`'set'` moves) and moving existing pieces (`'move'` moves). It checks for mill formations, removes opponent pieces if a mill is created, and returns a list of resulting board states and corresponding mo...
def getMoves(board,player): moves = [] ListBoard=[] countPlayer=0 if player==1: countPlayer=board['countWhite'] elif player==-1: countPlayer=board['countBlack'] if countPlayer>0: index1=0 while index1<len(board['pieces'...
def getMoves(board,player): moves = [] ListBoard=[] countPlayer=0 if player==1: countPlayer=board['countWhite'] elif player==-1: countPlayer=board['countBlack'] if countPlayer>0: index1=0 while index1<len(board['pieces'...
The function evaluates a board game state (likely Nine Men's Morris) by calculating a heuristic score based on factors like legal moves, blocked pieces, mill formations, and piece counts. It adjusts the evaluation dynamically depending on the game difficulty level (easy, medium, hard), prioritizing different strategies...
def evaluate(board,originalPlayer,type): evaluation=0 legalMovesPlayerOne=len(getMoves(board,originalPlayer)[0]) legalMovesPlayerTwo=len(getMoves(board,originalPlayer*-1)[0]) blockedBlack=NumberBlockedPiece(board,originalPlayer) blockedWhite=NumberBlockedPiece(board,originalPlayer*-1) nuumMillDoubleBlac...
def gameOver(board,player): legalMovesPlayerOne=len(getMoves(board,1)[0]) legalMovesPlayerTwo=len(getMoves(board,-1)[0]) if (board['onBoardWhite']==2 and board['countWhite']==0) or legalMovesPlayerOne==0: return True if (board['onBoardBlack']==2 and board['c...
This function implements the Alpha-Beta pruning algorithm for game tree search, evaluating board states to determine optimal moves. It alternates between maximizing (pl=True) and minimizing (pl=False) players, recursively exploring possible moves up to maxDepth. The algorithm prunes branches where alpha ≥ beta to optim...
def alphaBeta(pl,board,current,depth,maxDepth,alpha,beta,dificulty,originalPlayer): if depth==maxDepth or gameOver(board,current): #print(dificulty,evaluate(board,originalPlayer,dificulty)) return evaluate(board,originalPlayer,dificulty),None,None next...
def parse_model_name(CFG, model_name): cfg_dict = dict([tok.split('-') for tok in model_name.split('_')]) CFG.encoder = cfg_dict['a'] CFG.seq_len = int(cfg_dict['len']) CFG.emb_size = int(cfg_dict['e']) CFG.hidden_size = int(cfg_dict['h']) CFG.nlayers = int(cfg_dict['l']) CFG.nheads = int(cf...
The code performs model validation by preprocessing data, creating a dataset/loader, loading the model, and calculating the AUC score using validation data. It parses model settings, prepares validation samples, initializes a dataset, loads the trained model, evaluates predictions, and computes the ROC AUC metric to as...
def run_validation(settings=None, parameters=None, CFG=None, model_name="", df_=None): CFG = parse_model_name(CFG, model_name) (valid_df, valid_samples, cate_offset) = \ preprocess(settings=settings, parameters=parameters, mode='validation', update_flag=True) CFG.total_cate_size = cate_offset ...
def correct_perspective(image, min_length_ratio = 0.3, pad_ratio = 0.2, min_area_ratio = 0.2, out_width = 500, out_height = 400): hlines, vlines = get_bounding_lines(image, min_length_ratio = min_length_ratio, pad_ratio = pad_ratio) if len(hlines) == 0 or len(vlines) == 0: return image min_area = ...
The function processes an image by correcting its perspective, adjusting orientation, generating variations, and extracting text using PyTesseract OCR. It returns a list of lowercase text blobs extracted from the processed image variations.
def read_text_process(image: np.array, method = 'pytess') -> list: image = correct_perspective(image, out_width = 500, out_height = 400) images = fix_orientation(image) images = get_image_variations(images) text_blobs = [] for image in images: if method == 'pytess': text_blobs...
def f_force_nms_cpu(frozen_graph): for node in frozen_graph.node: if 'NonMaxSuppression' in node.name: node.device = '/device:CPU:0' return frozen_graph def f_replace_relu6(frozen_graph): return convert_relu6(frozen_graph) def f_remove_assert(frozen_graph): remove_op(frozen_graph, 'A...
This function converts a pre-trained object detection model into a frozen TensorFlow graph. It modifies config parameters, exports an initial inference graph, applies optimizations (NMS to CPU, ReLU6 replacement, assert removal), and returns the modified graph with input/output names for deployment.
def build_detection_graph(config, checkpoint, batch_size=1, score_threshold=None, iou_threshold=None, force_nms_cpu=True, replace_relu6=True, remove_assert=True, input_shape=None, output_dir='.generated_model'): """Builds a frozen graph for a pre-train...
def conc(self): """ Calculates the concentration of OH, based on the wt fraction (%) and temperature Returns ------- concentration : float concentration of the OH in electrolyte [mol/dm^3] """ concentration=self.w*self.density()/56.1 #56.1 is the m...
The function calculates the complete reversible overpotential (V_re) considering pressure dependence. It uses temperature (T_in), electrolyte weight fraction (w), and system pressure (P_s) to compute vapor pressures (Pv_h2O, Pv_KOH) and activity coefficients (alfa_H2O). The result combines the base reversible voltage (...
def v_rev(self): """ Complete reversible overpotential, including the pressure dependence part Parameters ---------- T_in : float Temperature [K] w : float [0-1] Weight fraction of the electrolyte P_s : float System pressure [...
def refresh(win_x, win_y, win): try: if (draw_sensors_with_distance_on_x_axis_flg != 1): draw_background(win_x, win_y, win, axis_flg) draw_sensors(win) else: draw_background(win_x, win_y, win, axis_flg) draw_sensors_with_distance_on_x_axis(args.se...
The code processes a file line-by-line to extract speed values and coordinate data. It updates a display, simulates clicks on circles using parsed coordinates, and introduces delays based on the extracted speed. The function reads input data, parses parameters, and triggers timed actions for graphical interactions or s...
def target_file_data(target_file_dir): new_speed = 1 f = open(str(target_file_dir), "r") for line in f: new_speed_flg = re.match("speed=", line) if new_speed_flg: speed = re.split("speed=", line) new_speed = float(speed[1]) else: ...
def draw_background(win_x, win_y, win, axis_flg): if (axis_flg != 1): backround = Rectangle(Point(0,0), Point(win_x, win_y)) backround.setFill(color_rgb(30,30,30)) backround.draw(win) else: backround = Rectangle(Point(10,10), Point(win_x, win_y)) backround.setFill(color_...
The main task of the code is to create a graphical simulation window for visualizing sensor data or paths based on command-line arguments. It handles input methods (mouse, socket, file), draws sensors, target coordinates, and paths, and uses argparse to parse parameters like window size, sensor placement, and output fi...
def main(): global args, win, win_x, win_y, axis_width, axis_flg parser = argparse.ArgumentParser(description="Quick script") parser.add_argument("-d", "--distance", default=None, type=int, help="This is the distance between sensors") parser.add_argument("-sx", "--sensor_start_x", default=200, type=in...
def _loop_to_stable_state(interval, is_last_speed): unstable_data = pd.DataFrame() temp_his = Queue(60) while True: time.sleep(interval) ret, state = _sys_prober() if not _check_cpu_usage(state["cpu_percent"]): unstable_data.drop(unstable_data.index, inplace=True) ...
The function collects thermal data under varying fan speeds (85%, 60%, 40%, 30%) to ensure system stability during model training. It sets fan speeds manually, monitors system states, validates CPU usage, and accumulates stable/unstable data. If instability occurs (e.g., invalid states or excessive CPU), it terminates ...
def _do_collect_stable_thermal_data(interval): ''' When the fan speed is 30%, model training continues even if the device does not enter the stable state due to component overtemperature, but unsteady data needs to be fitted. ''' collected_data = pd.DataFrame() unstable_data = pd.DataFrame()...
def set_current_freq_governor(gov): """ Set the freq governor. return type: bool""" if gov in _read_file(SYSFS_AVAILABLE_GOVERNORS).strip().split(" "): _set_freq_policy("scaling_governor", gov) return True return False def _get_max_cpufreq(): if os.path.exists(SYSFS_AVAILABLE_FREQUENCIES...
The main task of the code is to configure the CPU to operate in performance mode by setting the frequency governor to "performance" and adjusting the maximum CPU frequency to its highest available value, ensuring optimal system performance by prioritizing speed over power efficiency.
def set_sys_to_performance_mode(): """ Set the system to PERFORMACE mode""" if set_current_freq_governor(PERFORMANCE_GOV): return max_freq = _get_max_cpufreq() if max_freq: _set_freq_policy("scaling_cur_freq", str(max_freq * 1000))
def send_to_all(self, msg): for conn in self.connections: conn.sendall(msg.encode()) def print_board(self, board): rows = [" | ".join(board[i:i+3]) for i in range(0, 9, 3)] separator = "\n" + "-" * 9 + "\n" return separator.join(rows) def get_player_move(self, conn): ...
The code implements a multiplayer Tic-Tac-Toe game where two players (one human via network connection, one AI) take turns making moves on a 3x3 board. It handles game state updates, validates moves, checks for win/tie conditions, and sends real-time updates to clients. The loop continues until a player wins or the gam...
def play_game(self): board = [' ' for _ in range(9)] current_player = 'X' while True: for i, conn in enumerate(self.connections): self.send_to_all(self.print_board(board)) if current_player == 'X' and i == 0: conn.sendall("\nPlayer...
def matchWL(self,player,matches): matchesWon = [] matchesLost = [] for match in matches: if player == match.getWinner(): matchesWon.append(match) if player != match.getWinner() and player in match.getPlayers(): matchesLost.appe...
This code adjusts players' "Pass3 Part2" ratings in a tournament system based on their match outcomes and Pass2 data. It calculates points gained, applies tiered adjustments (copying Pass2, adding points, or averaging best/worst results), and enforces special rules. The goal is to refine player ratings using win/loss r...
def pass3(self): for player in self.tournament.getListOfPlayers(): playerWL = self.matchWL(player, self.matches[player.getID()]) if player.getRating() == 0 and (playerWL["matchesWon"] == 0 or playerWL["matchesLost"] == 0): ...
def pass1(self): playerGains = {} for player in self.tournament.getListOfPlayers(): if player.getRating() == 0: continue pointsGained = self.pointExchangeTable(player, self.matches[player.getID()]) player.setPass1Gai...
The code's main task is to sequentially execute four methods (pass1 to pass4), print a completion message, and return 0. It orchestrates a multi-step process, ensuring each method is called in order before finalizing with a return value of 0.
def calculate(self): self.pass1() self.pass2() self.pass3() self.pass4() print("Finished calculating!") return 0
def drawLapangan(): if modeLapangan == 1: mapImage[:] = (0, 153, 0) cv2.rectangle(mapImage, (100,100), (1300,900), (255,255,255), 3) #Garis Luar cv2.rectangle(mapImage, (20,600), (100,400), (255,255,255), 3) #Garis Luar Gawang Kiri cv2.rectangle(mapImage, (1300,600), (1380,4...
The main task of the code is to implement a particle filter for robot localization in a 2D environment, using sensor fusion data (kinematic and IMU inputs) and landmark positions to estimate the robot's global position. It initializes particles, updates their positions based on motion models, calculates weights using d...
def main(): global ObstaclePosition global obstacleAngle global imuCurentHeading #Inisialisasi awalan robot robotInitialPosition[0] = 0 robotInitialPosition[1] = 0 robotInitialPosition[2] = 0 #Inisial Posisi landmark if modeLapangan == 1: #Gawang Kiri landmarkPo...
def rgb_to_percents(rgb): """ This function takes rgb tuple values ranging from 0 to 255 and converts them to percent rgb tuple values ranging from 0.0 to 1.0. :inputs: There is a single argument which is a tuple of length 3 with integer values ranging from 0 to 255 :returns: This fu...
The function generates a color palette with 4 colors from a dominant color by converting it to HLS format and creating monochromatic, analogous, tetradic, and miscellaneous color schemes, returning them as a tuple with their types.
def palette_generator(dom): """ This function generates a palette of 4 colors from a single dominant color that has """ # Converting rgb to hls tuple rgb = rgb_to_percents(dom) dom_hls = rgb_to_hls(rgb[0], rgb[1], rgb[2]) # Generating monochromatic palettes mono_u = mono_up(dom_hl...
def rgb_to_percents(rgb): """ This function takes rgb tuple values ranging from 0 to 255 and converts them to percent rgb tuple values ranging from 0.0 to 1.0. :inputs: There is a single argument which is a tuple of length 3 with integer values ranging from 0 to 255 :returns: This fu...
The code generates complementary and analogous color palettes from a dominant color. It converts the dominant color's RGB values to HLS format, then uses helper functions to derive complementary and analogous shades. The result is a tuple containing the palette type ("relcolors"), the complementary colors ("Complimenta...
def related_colors_generator(dom): """ """ # Converting rgb to hls tuple rgb = rgb_to_percents(dom) dom_hls = rgb_to_hls(rgb[0], rgb[1], rgb[2]) # Generating monochromatic palettes compl = get_complimentary(dom_hls) analg = get_analogous_centered(dom_hls) return ("relcolors",...
def getNamesFromWebPage(Everything): LISTO = {} for sitting in list(Everything.keys()): link = Everything[sitting][0] soup = getHtmlPageFromLink(link) tags = getTagsFromProperty(soup) text = getTextFromList(tags) LISTO[sitting] = text return LISTO def getNamesFromSit...
The function compares names of attendees from HTML pages and a database for multiple sittings, checking discrepancies. It optionally returns timing metrics for each processing step, including data retrieval and comparison. The TODOs indicate planned optimizations and validation checks for member eligibility and quorum ...
def wieOntrbreekt(aantalZittingen, time=False): A1 = t.time() #stap 1 Everything = sq.getAllSittingsFromEveryBestuursEenheid(aantalZittingen) #aanwezigen volgens html pagina(we nemen aan dat dit altijd correct ingevuld is) A2 = t.time() #stap 2 #TODO getNamesFromWebPage efficienter maken. Lijs...
def get_direction_of_movement(self, box, obj_id, frame_idx): direction = "N" if len(self.prev_detections) > 3: prev_detection_all_list = self.prev_detections[-1] if len(prev_detection_all_list) > frame_idx: prev_detection_frame_list = prev_detection_all_list[fram...
The main task of the code is to process multiple video streams in real-time, performing object detection and tracking to monitor traffic violations (lane, red light, parking). It creates separate windows for each camera, writes video chunks, detects violations, saves violation data with timestamps, and displays output....
def run(self): try: # Create separate windows for each frame if self.show_video_output: for idx, _ in enumerate(self.videos): cv2.namedWindow(f"camera {idx}", cv2.WINDOW_NORMAL) cv2.resizeWindow(f"camera {idx}", self.window_size[0],...
def import_data(): os.chdir('../../data/MachineLearning') with open('Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, test_features , train_labels, test_labels = split(data) train_features, train_labels = ...
The main task of the code is to train a Gaussian Mixture Model (GMM) on training data, predict labels for test data, compute classification performance metrics (e.g., accuracy, confusion matrix, DR, FAR), and save results. It measures training time, evaluates model performance, and returns test features with prediction...
def process(): train_features, train_labels, test_features,test_labels = import_data() #training the data t0 = time() clf = GaussianMixture(n_components=2, reg_covar=1) clf.fit(train_features) tt = time()-t0 print("Classified in {} seconds".format(round(tt,3))) label_prediction = clf.pre...
def import_training_data(): os.chdir('../../data/MachineLearning') with open('Monday-WorkingHours.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, train_labels = split_divide(data) convertAndClean(train_features,train_labels,'train') tr...
The code trains a Label Propagation model on training data, evaluates its performance on test data by predicting labels, and calculates accuracy, detection rate, and false alarm rate. It measures training time, saves metrics and data sizes, then returns test features and predictions. The main task is semi-supervised cl...
def process(): train_features, train_labels = import_training_data() test_features,test_labels = import_testing_data() #training the data t0 = time() label_prop_model = LabelPropagation() label_prop_model.fit(train_features,train_labels) tt = time()-t0 print("Classified in {} seconds".fo...