dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_samples_from_file(self, original, num_samples): """Read new samples from file. Args: original: original model to label synthetic data num_samples (int): number of samples to generate Returns: X_new: generated data y_new: generated labels """ ...
The main task of the code is to retrieve or generate synthetic data samples (X_new, y_new) based on the original model. It prioritizes loading samples from a file if specified, otherwise generates them using `generate_samples`. If saving to a file is enabled, generated samples are also stored. The function returns the ...
def get_samples(self, original, num_samples = 100): """Get new samples from either file or generate them. Args: original: original model to label synthetic data num_samples (int): number of samples to generate Returns: X_new: generated data y_new: generated labe...
def distance_caculate(self, x1, x2, y1, y2): x = math.pow((x1 - x2), 2) y = math.pow((y1 - y2), 2) return math.sqrt(x + y) def check_swamp(self, x, y, swamp_object): if str(x) + "_" + str(y) in swamp_object: return swamp_object[str(x) + "_" + str(y)] else: ...
The code generates a detailed state representation for a game environment, encoding obstacles, gold positions, player proximity, agent energy, and terrain hazards. It creates encoded arrays for neural network inputs, including positional maps, threat indicators, gold locations, and player counts, while returning variab...
def get_state(self): player_object = {} player_object_zero = {} swamp_object, obstacle_object = self.state.mapInfo.get_obstacle_swamp_object() gold_object = self.state.mapInfo.get_gold_amount_object() total_player = 0 for player in self.state.players: if play...
def getActionList(self,currentState): """Generate list of possible actions""" actions = [] for action in range(1,5): if self.checkAction(currentState, action) == True: actions.append(action) return actions def getState(self, state, action): """T...
The code performs value iteration for 100 iterations to compute the optimal policy in a state space. It updates each state's value by evaluating all possible actions, considering deterministic (noise=0) or probabilistic (noise≠0) transitions. For each state, it calculates the expected value of actions, selects the best...
def valueIteration(self, gamma, noise): """ Running value iteration for 100 iterations""" iterations = 100 i = 1 # epsilon = 0.001 """ alternate list to store updated values""" updatedList= list() while (i<=iterations): updatedList.clear() ...
def splite_ref_name(ref): """ Description: generate c language for parse json map string object Interface: None History: 2019-06-17 """ tmp_f, tmp_r = ref.split("#/") if '#/' in ref else (ref, "") return tmp_f, tmp_r def schema_from_file(filepath, srcpath): """ Description: generate ...
The function resolves JSON schema references by recursively loading files, processing $ref directives, and constructing a schema structure for generating C code to parse JSON map objects. It handles nested references, updates schema information, and returns resolved schema components along with a reference name for cod...
def get_ref_root(schema_info, src, ref, curfile): """ Description: generate c language for parse json map string object Interface: None History: 2019-06-17 """ refname = "" tmp_f, tmp_r = splite_ref_name(ref) if tmp_f == "": cur = src else: realpath = os.path.realpat...
def valid_basic_map_name(typ): ''' Description: Valid basic map name Interface: None History: 2019-06-17 ''' return typ != 'mapStringObject' and hasattr(typ, 'startswith') and \ typ.startswith('map') def make_basic_map_name(mapname): ''' Description: Make basic map name Inter...
The function generates a pointer type string by validating the input type `typ` and constructing a prefixed name. If `typ` is invalid, it returns an empty string. Otherwise, it returns a formatted pointer string using either `make_basic_map_name` or `get_prefixed_name` with the provided `prefix` and `name`.)
def get_prefixed_pointer(name, typ, prefix): ''' Description: Make pointer name Interface: None History: 2019-06-17 ''' if typ != 'object' and typ != 'mapStringObject' and \ not valid_basic_map_name(typ): return "" return '%s *' % make_basic_map_name(typ) if valid_basic_m...
def parse_json_to_c(obj, c_file, prefix): """ Description: generate c language for parse json file Interface: None History: 2019-06-17 """ if not helpers.judge_complex(obj.typ): return if obj.typ == 'object' or obj.typ == 'mapStringObject': if obj.subtypname: retu...
The main task of the code is to append C language code generated from JSON data to a specified file. It processes the input object by parsing JSON into C structures, generating memory-free functions, and retrieving JSON-related C code, all prefixed with the given identifier. The function orchestrates these steps to pro...
def append_c_code(obj, c_file, prefix): """ Description: append c language code to file Interface: None History: 2019-06-17 """ parse_json_to_c(obj, c_file, prefix) make_c_free (obj, c_file, prefix) get_c_json(obj, c_file, prefix)
def update(G, color_map, pos): fig = generateFigure(G, color_map, pos) raw_data, size= getRawData(fig) drawFig(raw_data,size) pygame.display.update() clock.tick(fps) pygame.time.delay(time_delay) def searchAnimation(matrix, visited, G, pos, color_map): tmp=[] for v1, v2 in visited.it...
This function executes a specified search algorithm (BFS, DFS, UCS) on a grid, visualizes the path, and animates the search process with a configurable delay. It reads the input matrix, initializes the graph, runs the chosen algorithm, updates the visualization, and continuously checks for a quit event.
def runSearchAlgorithms(input, algorithm, delay): global time_delay time_delay=delay matrix, start, end=readMatrix(input) G, pos, color_map=initialize(matrix) update(G, pos, color_map) if algorithm == 'bfs': visited, path = BFS(matrix, start, end) elif algorithm == 'dfs': ...
def update_uGraph(G, color_map, pos): fig = generateFigure_uGraph(G, color_map, pos) raw_data, size= getRawData(fig) drawFig(raw_data,size) pygame.display.update() clock.tick(fps) pygame.time.delay(time_delay) def MSTAnimations(matrix, edges, G, pos, color_map): for e in edges: p...
This function executes a Minimum Spanning Tree (MST) algorithm on a graph, visualizing the process. It reads a matrix input, initializes an undirected graph, applies the specified algorithm (Prim, Kruskal, or Connected Components), and animates the resulting MST. A global delay parameter controls animation timing. The ...
def runMSTs(input, algorithm, delay): global time_delay time_delay=delay matrix, start, end=readMatrix(input, l=1) G, pos, color_map=initialize_uGraph(matrix) update_uGraph(G, pos, color_map) if algorithm == 'prim': edges = Prim(matrix) elif algorithm == 'kruskal': edges=...
def update_uGraph(G, color_map, pos): fig = generateFigure_uGraph(G, color_map, pos) raw_data, size= getRawData(fig) drawFig(raw_data,size) pygame.display.update() clock.tick(fps) pygame.time.delay(time_delay) def CPAnimations(matrix, edges, G, pos, color_map): n_cp = len(edges) # pr...
The code executes a connected components algorithm on a graph derived from an input matrix, visualizes the graph and its components using animations, and waits for a quit event. It reads the matrix, initializes an undirected graph, computes connected components if the specified algorithm matches, and displays the resul...
def runCP(input, algorithm, delay): global time_delay time_delay=delay matrix, start, end=readMatrix(input, l=1) G, pos, color_map=initialize_uGraph(matrix) update_uGraph(G, pos, color_map) if algorithm == 'connected_components': edges = ConnectedComponents(matrix) else: ...
def make_key(): determinant = 0 C = None while True: # cipher = input("Input 4 letter cipher: ") lst1 = [int(item) for item in input("Enter the list items : ").split()] print("integer key", lst1) cipher = '' for i in lst1: cipher += chr(i + 65) C =...
The code decrypts an encrypted message using a Hill cipher by computing the modular inverse of a 2x2 key matrix, then applying it to the encrypted matrix to retrieve the original plaintext. It processes each character pair, converts them to integers, performs matrix multiplication with the inverse key, and maps results...
def decrypt(encrypted_msg): C = make_key() # Inverse matrix determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0] determinant = determinant % 26 multiplicative_inverse = find_multiplicative_inverse(determinant) C_inverse = C # Swap a <-> d C_inverse[0][0], C_inverse[1][1] = C_inverse[1, 1]...
def get_transformation_matrix(self, tvec, quat): T = np.ones((4,4)).astype('float') r = R.from_quat(quat) if self.imu_quat is not None: # print('Adding rotation') # print() # r_imu = R.from_euler('zyx', [[-self.imu_euler_object.roll, 0, 180 + self.imu_euler_ob...
The main task of the code is to process a point cloud message by filtering, transforming, and analyzing the data to generate a mesh, assess risks (e.g., unsafe slopes or edges), and publish alerts or processed cloud data if safety thresholds are breached. It toggles processing states, applies spatial filters, computes ...
def cloud_sub_callback(self, msg): self.flush = not self.flush self.alert_status = 0 if self.flush: # print('Skipping Data') return xyz = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(msg, remove_nans=True) xyz = xyz[xyz[:,2] > 0.1] xyz ...
def loadExistingResults(self, noCache = False): if (not hasattr(self, '_loadExistingResults') or noCache): self.logger.info("collect information...") total = len(self.allSeeds()) * len(self.allAlgorithms()) * len(self.allTasks()) * len(self.allEvaluations()) counter = 0 ...
The code's main task is to aggregate data by loading existing results, analyzing them to generate statistics, and then creating an ASBenchmark object using the results and statistics. This process likely involves compiling, summarizing, and structuring data for benchmarking or evaluation purposes.
def aggregate(self): results = self.loadExistingResults() statistics = self.analyzeResults(results) self.createASBenchmark(results, statistics)
def loadExistingResults(self, noCache = False): if (not hasattr(self, '_loadExistingResults') or noCache): self.logger.info("collect information...") total = len(self.allSeeds()) * len(self.allAlgorithms()) * len(self.allTasks()) * len(self.allEvaluations()) counter = 0 ...
The code's main task is to log benchmark result statistics, including total evaluations, algorithm/task breakdowns, and completeness metrics, then generate scatter plots visualizing score vs. cost for specific algorithms and evaluations across all tasks. It processes loaded results, analyzes them, and outputs structure...
def showAll(self): results = self.loadExistingResults() statistics = self.analyzeResults(results) self.logger.info("===========================") self.logger.info("Benchmark Result Statistics") self.logger.info("===========================") self.logge...
def menu() -> str: """ The `menu` function returns a string containing a user menu with several options. :return: a string that contains the user menu options. """ menu_message = ('Please, choose an operation (1/2/3/4/5/6/7):\n' '1. See the new words\n' '2. Wr...
The main task of the code is to present a menu, handle user input, and execute corresponding functions (e.g., displaying new words, writing sentences, testing knowledge) based on the user's choice. It includes input validation, recursive calls for menu re-display, and looping to maintain interaction until the program e...
def access_learning(): """ The main function contains the functionalities of the entire program and calls other functions based on the user's choice. """ # Print the menu to the User and ask for input print(menu()) choice = get_input() while True: if choice.lower() == 'm': ...
def greet_user(): print("Hello, Dear User!") time.sleep(0.8) print("Welcome to my application!") time.sleep(1.6) print("\nLearning foreign languages can give you the wings to conquer the world.") print("Are you ready to sink in a world fulfilled with many wonders and knowledge? ") time.sleep...
The main task of the code is to implement a learning system with user authentication, including voice recording, dictionary API integration, a word knowledge quiz game, and email extensions, while reorganizing the program using classes for structure and functionality.
def main(): """ TODO: (4) Configuration: (1) re-write the whole program using classes Learning System: (1) record your own voice reading the sentences (2) add a dictionary API for the translations (3) test_word_knowledge - 1 minute (quick-game) Authentication: ...
def find_runs( run_name_contains=None, exclude_child_runs=False, in_latest_run_group=False, **search_runs_kwargs, ): df = mlflow.search_runs(**search_runs_kwargs) col = f"tags.{MLFLOW_RUN_NAME}" if run_name_contains and (col in df.columns): df = df[df[col].str.contains(run_name_cont...
This function organizes recent Ray runs by identifying the latest experiment runs, grouping them into a summary run, and optionally deleting orphaned runs. It finds runs in the latest group, separates valid runs (mixin_run_ids) from others (cback_run_ids), creates a new summary run, adopts valid runs into it, and delet...
def organize_latest_ray_runs( experiment_name, config_space, run_name="", delete_stray_runs=False ): finds = find_runs( in_latest_run_group=True, experiment_names=[experiment_name], ) mixin_run_ids, cback_run_ids = assimilate_ray_runs(finds) print(mixin_run_ids) tune_summary_run_...
def greeting(): print("WELCOME!") print("Because it's the holidays, you'll receive some cash prizes and other wholesome gifts for using this program :)") def ask_name(): name = input(f"What is your name?\n==> ") print(f"Welcome, {name}! Merry Winter!") return name def special_song(user): prize = user.get_pr...
The code's main task is to initialize a player with a name, distribute tokens and gifts, check for a special song condition, play it if true, and recursively restart the program. It creates an interactive loop for user engagement, possibly in a game or application, allowing repeated actions with player-specific data.
def program(): greeting() user_name = ask_name() player = Player(user_name) player.give_tokens() player.give_gift() if special_song(player): play_song(player) recursive_program(player)
def drawBlockL2(row, col, pencolor, fillcolor): # Make sure the tracer is not on turtle.tracer(False) # Clear the original block clearBlock2(row, col) # Set up the color layer2_drawing_turtles[row][col].pencolor(pencolor) layer2_drawing_turtles[row][col].fillcolor(fillcolor) # Draw the ...
The function `drawGameMap()` renders a game map using Turtle graphics, dynamically drawing blocks, exits, and robot paths while respecting visibility constraints. It initializes the map, updates block colors based on game state (e.g., finished or not), handles partial robot view limitations, and efficiently manages scr...
def drawGameMap(): global draw_init, forceUpdate # Disable the tracer turtle.tracer(False) # If the game is initialized... if not draw_init or is_finished: # Draw the game blocks for row in range(len(game_map_data)): for col in range(len(game_map_data[0])): ...
def moveNorth(): if not startToMove: return move(robot_row - 1, robot_col, "No") robot_turtle.shape("robot_north.gif") def moveSouth(): if not startToMove: return move(robot_row + 1, robot_col, "So") robot_turtle.shape("robot_south.gif") def moveEast(): if not startToMove: ...
The main task of the code is to move a robot on a game map based on a given decision (direction or "NONE"). It executes corresponding movement functions, checks if the robot reaches an exit ("E"), updates game state variables (is_finished, forceUpdate, robot_view), redraws the map, and displays a game-over message if t...
def moveRobot(decision): global is_finished, forceUpdate # Show the decision print(decision) # Move the robot based on the decision if decision == "NORTH": moveNorth() elif decision == "SOUTH": moveSouth() elif decision == "EAST": moveEast() elif decision == "WE...
def n_points_from_density(x, y, points_per_100x100: float): area = x * y unit_area = 100 * 100 return int(points_per_100x100 * area / unit_area) def generate_points( *, min_dist: float, n_points = 10_000, min_x: float = 0, max_x: float = 100, min_y: float = 0, max_y: float = 100,...
The function generates a set of points with specified minimum distance between them within a defined rectangular area. It calculates the number of points based on density if provided, ensures reproducibility via a random seed, and outputs the points to a file and/or as a plot. It validates inputs, raises errors for mis...
def click_main( points_filename, min_dist, n_points, points_per_100x100, min_x, max_x, min_y, max_y, random_seed, plot_filename, marker_size, ): if points_filename is None and plot_filename is None: raise ValueError("No output formats specified") if random_se...
def test_class_token(self): test_output = self.test_patch_embedding(self.test_input) test_output = self.test_class_token(test_output) self.assertEqual(test_output.shape, torch.Size([self.batch_size, self.num_patches + 1, self.embedding_dim])) def test_positional_encoding(self): test_outp...
This code tests the output shape of an encoder layer in a transformer model. It processes input through patch embedding, class token addition, positional encoding, and the encoder layer, then verifies the output tensor has dimensions [batch_size, num_patches + 1, embedding_dim] using an assertion.
def test_encoder_layer(self): test_output = self.test_patch_embedding(self.test_input) test_output = self.test_class_token(test_output) test_output = self.test_positional_encoding(test_output) test_output = self.test_encoder_layer(test_output) self.assertEqual(test_output.shape, ...
def test_class_token(self): test_output = self.test_patch_embedding(self.test_input) test_output = self.test_class_token(test_output) self.assertEqual(test_output.shape, torch.Size([self.batch_size, self.num_patches + 1, self.embedding_dim])) def test_positional_encoding(self): test_outp...
This test verifies the output shape of the encoder after processing inputs through patch embedding, class token addition, positional encoding, and the encoder itself. It ensures the output tensor has dimensions [batch_size, num_patches+1, embedding_dim], confirming correct transformation and alignment of features.
def test_encoder(self): test_output = self.test_patch_embedding(self.test_input) test_output = self.test_class_token(test_output) test_output = self.test_positional_encoding(test_output) test_output = self.test_encoder(test_output) self.assertEqual(test_output.shape, torch.Size([...
def get_title(doc: BeautifulSoup) -> Optional[str]: title_parts = doc.title.string.split('-') if len(title_parts) < 2: return None return '-'.join(title_parts[1:]).strip() def get_dialog(doc: BeautifulSoup) -> Sequence[str]: elems = doc.select('table font') raw_lines = [item for elem in el...
The main task of the code is to process an HTML script file by parsing its content, extracting the episode title and dialog lines, correcting potential issues in the dialog lines with user intervention if needed, stitching modified lines, re-parsing them, and outputting the final parsed results to stdout. It also valid...
def main() -> int: if len(sys.argv) < 2: print('usage: bechtrek.py <scriptfilehtml>', file=sys.stderr) return 1 # Open the script file. htmlscriptfile = sys.argv[1] with open(htmlscriptfile, encoding='ISO-8859-1') as f: htmlscript = f.read() # Parse it. doc = BeautifulS...
def shift_key_resize_event( self, started_resizing: bool, ui_event: hou.ViewerEvent ) -> bool: if ( ui_event.reason() == hou.uiEventReason.Start and ui_event.device().isShiftKey() and not ui_event.device().isCtrlKey() and not ui_event.device().isMiddle...
This method processes mouse events for resizing and cursor interaction. It checks for shift-key resizing, updates cursor position based on mouse input, manages cursor visibility, and handles left-click actions to add projection primitives. The function returns False to indicate the event is not consumed.
def onMouseEvent(self, kwargs): """ Process mouse events """ ui_event = kwargs["ui_event"] dev = ui_event.device() node = kwargs["node"] geometry = node.geometry() # SHIFT DRAG RESIZING started_resizing = False started_resizing = self.shift_key_re...
def serial_write(self, ser, message, file=None): # Check that the device is no longer sending bytes if ser.in_waiting: self.serial_read(ser, message, file) # Check that the serial connection is open if ser.writable(): wait = serial_settings.mxchip_buf_pause # w...
This function handles serial communication with a device, sending commands from an input file and capturing responses. It adjusts baud rates and data cache settings based on device type (ESP32 vs others), manages write/read operations with timing controls, monitors for test completion, logs errors, and writes exit code...
def write_read(self, ser, input_file, output_file): if 'esp32' in serial_settings.device_type: serial_settings.bits_to_cache = 800 serial_settings.baud_rate = 1000000 else: serial_settings.bits_to_cache = 1600 serial_settings.baud_rate = 115200 se...
def serial_write(self, ser, message, file=None): # Check that the device is no longer sending bytes if ser.in_waiting: self.serial_read(ser, message, file) # Check that the serial connection is open if ser.writable(): # special handling for sending a file ...
This function handles serial communication by reading data from an input file, writing it to a serial port, and capturing responses to an output file. It sets serial buffer parameters, sends data line-by-line, waits for responses, checks for test failures, and manages timeouts. After processing, it resets the device if...
def write_read(self, ser, input_file, output_file): session_start = time.time() # set bits to cache variable to allow for mxchip to pass bytes into serial buffer serial_settings.bits_to_cache = 800 if input_file: # set wait between read/write wait = (serial_settin...
def checkCollide(self): self.checkBallBlockCollide() self.checkBallPlayerCollide() flag = True while flag: flag = False for ball in self.balls: if ball.GetRect().y > GAME_SIZE[1]: self.balls.remove(ball) fla...
The code updates the game state by checking if the game is over, updating the player and all balls, detecting collisions, and loading the next level if the game is won.
def update(self): if self.isGameOver: return self.player.update() [ball.update() for ball in self.balls] self.checkCollide() if self.isGameWin(): self.Load( self.level.level + 1 )
def jacobian(self, t1, t2): # the transformation matrices of the links transMatWSL1 = self.linkTransformMat(0, t1) transMatL1L2 = self.linkTransformMat(self.link1Length, t2) transMatL2EE = self.linkTransformMat(self.link2Length, 0) # the transformation matrices of the links to Wo...
This code performs inverse kinematics for a robotic arm by calculating the Jacobian matrix, determining the position error between the target and current end-effector positions, and adjusting joint angles using the pseudoinverse of the Jacobian to minimize the error, updating sliders to move the arm toward the desired ...
def GO(self): t1 = np.deg2rad(self.slider1.get()-90) t2 = np.deg2rad(self.slider2.get()-90) jacobian = self.jacobian(t1, t2) # get the desired position target = np.array([int(self.entry1.get()), int(self.entry2.get())]).T # get the current position transMatWSL1 = ...
def _handle_hybi(self): environ = self.environ version = environ.get("HTTP_SEC_WEBSOCKET_VERSION") environ['wsgi.websocket_version'] = 'hybi-%s' % version if version not in self.SUPPORTED_VERSIONS: self.log_error('400: Unsupported Version: %r', version) self.res...
This method handles WebSocket connections by detecting the protocol version (HyBi or Hixie) from HTTP headers, processing the handshake, and invoking the application if successful. It logs the request and returns an empty list or closes the connection on errors, ensuring proper cleanup.
def _handle_websocket(self): environ = self.environ try: try: if environ.get("HTTP_SEC_WEBSOCKET_VERSION"): result = self._handle_hybi() elif environ.get("HTTP_ORIGIN"): result = self._handle_hixie() except: ...
def FirstTab(self): self.wiPieChart = self.findChild(QChartView, 'wiPieChart') self.wiLineChart = self.findChild(QChartView, 'wiLineChart') self.tblRecentAdditions = self.findChild(QTableWidget, 'tblRecentAdditions') def SecondTab(self): # used to store a number representing one of the l...
This code initializes a main GUI window by loading a UI file, setting up tabs and widgets, connecting UI elements to event handlers, and preparing the interface for user interaction. It references multiple UI components, assigns them to variables, and links button clicks and tab changes to specific methods, enabling dy...
def __init__(self): super(DlgMain, self).__init__() uic.loadUi('../../UI/Main_Window.ui', self) self.FirstTab() self.SecondTab() self.firstTimeSetup() self.tabWidget = self.findChild(QTabWidget, 'tabWidget') self.frmPieChart = self.findChild(QFrame, 'frmPieChart'...
def load_models(): RN_model = rainnet.rainnet() RN_model.load_weights("rainnet_weights.h5") rain_pred_CNN = load_model("rain_classifier.h5") return RN_model, rain_pred_CNN def generate_timestamp(look_back=10): timestamps = [] first_img = True from_zone = tz.gettz('UTC') to_zone = tz.ge...
The function `CNN_get_rain_prediction` uses a CNN model to predict rainfall (binary classification and probability) based on input images, leveraging a specified lead time. It loads pre-trained models, processes timestamped image data, generates predictions, overlays results on a map, and returns whether rain is predic...
def CNN_get_rain_prediction(lead_time=2): print("Loading CNN models...") RN_model , rain_pred_CNN = load_models() print("Done!\n\n") timestamp_list = generate_timestamp() #timestamp_list = ['2020111713350000', '2020111713200000','2020111713050000', '2020111712500000'] #timestamp_list = ['2020111...
def analyze_playlist(self): """ Analyze diversity of playlists from the dataset. """ logging.info("Analyzing Playlists...") pDI = [] pDI_idx = [] playlist_analyzed = 0 for c, playlist in enumerate(self.playlists): playlist_track_tags = [] ...
The code's main task is to analyze playlist diversity from a dataset and random playlists, then generate files for qualitative analysis by executing three steps: calculating playlist diversity indices, analyzing random playlists, and writing the results to files for further evaluation.
def run(self): """ Main function. It performs the diversity on the playlists from the dataset, then on random playlists. Finally, it writes the files with the playlists for performing a qualitative analysis """ pDI, pDI_idx = self.analyze_playlist() self.analyze_...
def applog(app_section: str ,app_message: str): date_time_stamp = datetime.now().strftime("%d.%b.%Y, %H:%M:%S") print(date_time_stamp+" | "+app_section+" | "+app_message) def get_dashboard_config_data(file_path:str): applog("Dashboard","Loading fonts...") #################### #################...
The main task of the code is to monitor system performance metrics (RAM, CPU usage/temperature) and control a dashboard display based on time-based conditions. It initializes configuration parameters, tracks RAM trends, logs system status, and alternates between displaying the dashboard or putting the screen to sleep, ...
def main(): try: performance.cli = sys.argv[1] except: performance.cli = "" applog("Dashboard","Initializing config parameters...") get_dashboard_config_data("dashboard.ini") hourglass.day = 0 screen.clean_screen = 0 trend = 0 ram = getRAMinfo() performance.usedr...
def write_version_py(filename='pywt/version.py'): cnt = """ # THIS FILE IS GENERATED FROM PYWAVELETS SETUP.PY short_version = '%(version)s' version = '%(version)s' full_version = '%(full_version)s' git_revision = '%(git_revision)s' release = %(isrelease)s if not release: version = full_version """ FULLVERS...
The main task of the code is to configure and build the PyWavelets package, generating version files, defining metadata (name, license, dependencies, etc.), handling Cython extensions for compilation, and setting up installation parameters. It ensures proper package structure, supports multiple Python versions, and int...
def setup_package(): # Rewrite the version file everytime write_version_py() metadata = dict( name="PyWavelets", maintainer="The PyWavelets Developers", maintainer_email="umtnj@example.com", url="https://github.com/PyWavelets/pywt", download_url="https://github.com/P...
def step_up(self) -> bool: """ take a step to the left, if possible""" if not self.can_go_up: return False to_x = self.pos_x to_y = self.pos_y - 1 return self._move(to_x, to_y) def step_down(self) -> bool: """ take a step to the left, if possible""" if...
The function `trace_path` executes a sequence of movement actions (up, down, left, right) or resets in a maze, visualizing the path taken. It optionally halts upon reaching the goal or resets if falling into a hole. The maze's ASCII representation with the traced path is returned, restoring original drawing settings af...
def trace_path(self, actions: list[str], autoreset_on_holes: bool = True, autohalt_on_goal: bool = True) -> str: """ runs the sequens of actions as passed and returns a representation of the maze with the path marked out actions are: "lef...
def update_batch(self, batch, eta): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in batch: delta_nabla_b, delta_nabla_w = self.backpropagate(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_...
This code trains a neural network model using mini-batch gradient descent. It shuffles data, divides it into batches, updates model parameters via `update_batch`, and evaluates cross-entropy loss and training accuracy every 10 epochs. The model uses softmax for predictions and tracks performance metrics during training...
def train_model(self, X, y, batch_size=10, epochs=300, learning_rate=0.01, save=False): num_batches = X.shape[0]//batch_size + (X.shape[0] % batch_size > 0) data = list(zip(X, y)) for epoch in range(epochs): np.random.shuffle(data) batches = [data[i * batch_size ...
def create_directory_structure(base_path, platform, ctf_names): directory_structure = { "thm": ["Enumeration", os.path.join("Enumeration", "Autorecon"), "Loot", "Exploit", "Report", "Downloaded_Files", "Notes"], "htb": ["Enumeration", os.path.join("Enumeration", "Autorecon"), "Loot", "Exploit", "Rep...
The code parses command-line arguments to create a directory structure for CTF challenges, manage target environments, perform ping scans on specified targets, start a web server, and connect to a VPN. It handles platform-specific configurations, sets environment variables for targets, and executes scans or server oper...
def main(): parser = argparse.ArgumentParser(description="Create directory structure based on arguments.") parser.add_argument("--ctfname", metavar="<CTFName>", help="CTF names separated by comma") parser.add_argument("--platform", metavar="<Platform type (thm/htb/pgp/vh/oscp/other/bscp)>", choices=['thm', ...
def getConnections(self): if self.readFromCache == False: connectivity = np.zeros((self.getNumElements(), 8)) for point in range(1, self.getNumElements()+1): elx = np.fix((point-1)/(self.nely*self.nelz)) + 1 ely = np.fix(((point-(elx-1)*s...
This code writes topology data to a JSON file when caching is disabled. It retrieves connection details, coordinates, and connected elements, structures them with dimension keys, and serializes the data into 'topologymemory.json' for later reuse.
def writeCachedContents(self): if self.readFromCache == False: print("Writing topology information to memory...") connections = self.getConnections().tolist() coordinates = self.getCoordinates().tolist() conelements = self.getConnectedElements().tolist() ...
def readCachedContents(self): with open('topologymemory.json', 'r') as topologycache: topologyinfo = json.load(topologycache) key = str(self.nelx) + "x" + str(self.nely) + "x" + str(self.nelz) if key in topologyinfo: self.con...
This code initializes a 3D structural optimization problem by setting geometric dimensions (length, width, height) and element counts (nelx, nely, nelz). It prepares cache-related flags, initializes structural data attributes (connections, coordinates), and creates a design matrix of ones with dimensions based on the n...
def __init__(self, length, width, height, nelx, nely, nelz): self.length = length self.width = width self.height = height self.nelx = nelx self.nely = nely self.nelz = nelz self.readFromCache = False self.connections = None self.coord...
def gen_gaussian_sigmas_in_octaves(sigma): """ Given a staring value of sigma, calculate a sequence of sigma values, where each octave value corresponds to doubling the value of the previous sigma. """ # Default parameters from Lowe's SIFT paper. imgs_per_octave = 6 k = 2 ** (1.0 / imgs_per_...
The code extracts SIFT features from an image by converting it to grayscale, generating Gaussian and Difference of Gaussians (DoG) image pyramids, detecting keypoints, removing duplicates, and computing descriptors. It returns the descriptors and corresponding keypoints, mapping each keypoint to a descriptor.
def extract_SIFT_features(img, sigma=1.6): """ Extract the SIFT features from the input image. Returns the extracted keypoints and the generated SIFT descriptors. One keypoint is mapped to one descriptor. """ # SIFT uses only a monochrome intensity image. if len(img.shape) == 3: img...
def _tcp4load(): ''' Read the table of tcp connections & remove the header ''' with open(PROC_TCP4, 'r') as f: content = f.readlines() content.pop(0) return content def _remove_empty(array): return [x for x in array if x != ''] def _convert_ipv4_port(array): host, port = array.split...
The main task of the code is to retrieve detailed TCP connection status information on Linux systems, including local/remote IP:port, connection state, user, process PID, and process name. It processes `/proc/net/tcp` data, converts hex values to readable formats, maps UIDs to usernames, and uses inodes to identify pro...
def netstat_tcp4(): ''' Function to return a list with status of tcp connections on Linux systems. Please note that in order to return the pid of of a network process running on the system, this script must be ran as root. ''' tcpcontent = _tcp4load() tcpresult = [] for line in tcpconte...
def _udp4load(): '''Read the table of udp connections & remove the header ''' with open(PROC_UDP4, 'r') as f: content = f.readlines() content.pop(0) return content def _remove_empty(array): return [x for x in array if x != ''] def _convert_ipv4_port(array): host, port = array.split('...
This function retrieves UDP connection details on Linux systems, including local/remote addresses, state (always 'Stateless'), user, PID, and executable path. It processes netstat data, extracts inode/PID mappings, and compiles results into a list. Requires root privileges to access PID information.
def netstat_udp4(): ''' Function to return a list with status of udp connections on Linux systems. Please note that UDP is stateless, so state will always be blank. Please note that in order to return the pid of of a network process running on the system, this script must be ran as root. ''' ud...
def eval_graph_lp(trackster_data, eid, dX, model, pileup=False, decision_th=0.5): """ Evaluation routine for graph-based link prediction """ pairs = [] preds = [] truths = [] # for each event sub-graph for sample in dX: nidx = sample.node_index # compute predicted edg...
The function evaluates a machine learning model's performance in reconstructing tracksters from cluster data, comparing predictions against simulated and true tracksters. It computes precision, recall, and F1 scores across events, handling graph-based or pairwise prediction modes, pileup scenarios, and multiparticle co...
def model_evaluation( cluster_data, trackster_data, simtrackster_data, assoc_data, model, decision_th=0.5, radius=10, max_events=100, bigT_e_th=50, pileup=True, collection="SC", graph=False, reco_eval=True, link_prediction=False, multiparticle=False, ): ""...
def evaluate(state, player_to_move): score = 0 for y in range(8): for x in range(8): if state[y][x] == player_to_move: score += 1 #if state[y][x] == -player_to_move: # score -= 1 return score - len(findValidMove(state, -player_to_move)) def isNextToCorner(Cell): if Cell in [(0,1), (1,0), (1,1), (6,0)...
This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move in a game state. It evaluates valid moves, prioritizing corner and adjacent-to-corner positions for immediate high-value returns. If time constraints are exceeded, it returns None. The algorithm recursively explores gam...
def minimax_alpha_beta(cur_state, player_to_move, validMove, depth,start, remain_time, alpha, beta): execution_time = time.perf_counter() - start if execution_time > 2.995 or remain_time - execution_time <= 0.0005: #print(execution_time) return None best_move = None if depth == 10 or validMove == []: #pr...
def convert_to_set(sequence): # to convert a sequence of nucleotides to a set, we will simply use python's built-in function return set(sequence) def convert_to_multi_set(sequence): # transform the sequence into a multiset representation: we will refer to the base nucleotides array (numpy array of 4 element...
This function computes similarity scores between a query and documents in a collection using specified vectorization methods (e.g., TF-IDF, set operations). It converts the query and documents into compatible vector formats, iterates through the collection, calculates scores with the provided similarity method, and ret...
def search_collection(query, vector_type, collection, method, return_dict=None, callback=None): # step 1: convert query to idf/tf/tf-idf/set/multiset if method == wf_score: vector1 = query convert_method = lambda x: x['sequence'] elif method == set_intersection_similarity or method == set_d...
def initialise_trees(terminals: list) -> list: """ Create a tree for each terminal and return a list of pairs: the tree graph paired with the terminal. :param terminals: the terminals of the Steiner tree :return: a list of graphs paired with the terminal the graph represents """ trees = [] f...
The function computes an approximate node-weighted minimal Steiner tree for given terminals in a graph using a greedy heuristic. It initializes terminal trees, copies the input graph, generates the Steiner tree via a greedy approach, calculates its total node cost, and returns the tree structure along with the cost. Th...
def approximate_steiner_tree(graph: nx.Graph, terminals: list, seed: int) -> (nx.Graph, int): """ Returns an approximate node-weighted minimal Steiner tree using a greedy heuristic. :param graph: the underlying graph with weighted nodes with "cost" label :param terminals: the terminals of the Steiner t...
def params_vec_to_dict(model, params_vec): params_dict = {} start_offset = 0 for li in np.arange(start=num_of_layers - 1, stop=-1, step=-1): layer_size = model.layers_sizes[li] if li > 0: prev_layer_size = model.layers_sizes[li - 1] else: prev_layer_size = mod...
This function performs an inexact line search to determine an appropriate step size α for optimization. It iteratively reduces α (starting from α₀=1) until two conditions are met: (1) the loss decreases sufficiently (via σ condition) and (2) the gradient's directional derivative meets a curvature condition (via c₂). Th...
def inexact_line_search(w_k, d, model, inputs, labels): alpha_0 = 1 beta = 0.5 sigma = 0.25 c_2 = 0.9 alpha = alpha_0 num_of_layers = len(model.layers_sizes) w_k_dict = params_vec_to_dict(model, w_k) f_w_k = batch_loss(inputs, labels, w_k_dict, num_of_layers) grad_w_k = batch_fwd_and...
def params_vec_to_dict(model, params_vec): params_dict = {} start_offset = 0 for li in np.arange(start=num_of_layers - 1, stop=-1, step=-1): layer_size = model.layers_sizes[li] if li > 0: prev_layer_size = model.layers_sizes[li - 1] else: prev_layer_size = mod...
The code implements a BFGS optimization algorithm for training a neural network. It iteratively updates model parameters to minimize loss by computing gradients, performing inexact line searches for step sizes, and maintaining an approximation of the inverse Hessian matrix (B_k). The process continues until the gradien...
def NN_BFGS(w_0, model, epsilon, inputs, labels): w_k = w_0 w_k_dict = params_vec_to_dict(model, w_k) num_of_layers = len(model.layers_sizes) g_w_k = batch_fwd_and_backprop(inputs, labels, w_k_dict, num_of_layers) g_w_k_norm = np.linalg.norm(g_w_k) n = len(w_k) I = np.identity(n) B_k =...
def load_experiment(self, config, device, train_batch_size=128, test_batch_size=128, num_workers=4, pin_memory=False, load_from_session=True, ...
The main task of the code is to execute a training process using a preconfigured model, optimizer, and dataset setup. It checks if training is already complete, initializes training components, trains the model with early stopping, and saves the model weights, training session, and state. The function returns the updat...
def run_training(self, config, device, train_batch_size=128, test_batch_size=128, num_workers=4, pin_memory=False, completed_ok=False): setup, state = self.load_expe...
def load_experiment(self, config, device, train_batch_size=128, test_batch_size=128, num_workers=4, pin_memory=False, load_from_session=True, ...
This function computes and optionally saves statistics for training and test data using a model and criterion. It loads experiment setup, retrieves dataloaders, calculates stats for train/test sets, and saves them if specified. Returns a dictionary containing train and test statistics.
def run_stats(self, config, device, save_stats=False): setup, state = self.load_experiment(config, device) workspace_dir = self.get_workspace_dir(config) dataloaders = setup['data_setup']['dataloaders'] model = setup['model'] criterion = setup['training_setup']['criterion'] ...
def job_exists(self, job_name: str, job_version: str) -> bool: resource_name = job_resource_name(job_name, job_version) container_name = self.get_container_name(resource_name, 0) return self._container_exists(container_name) def delete_job(self, job_name: str, job_version: str): entrypoi...
The function deploys a Docker-based job locally by creating containers, managing environment variables, handling plugins, and configuring networking. It checks for existing jobs, deletes duplicates, sets up ports, and runs containers with specified configurations, returning a JobDto indicating successful deployment.
def deploy_job( self, manifest: Manifest, config: Config, plugin_engine: PluginEngine, tag: str, runtime_env_vars: Dict[str, str], family: JobFamilyDto, containers_num: int = 1, ) -> JobDto: """Run Job as docker container on local docker""" ...
def terminal_state(self) -> bool: return bool(self.winner) or not self.has_valid_moves() def get_player(self): player1 = sum([self.grid[y][x] == 1 for y, x in itertools.product(range(3), repeat=2)]) player2 = sum([self.grid[y][x] == 2 for y, x in ite...
The main task of the code is to process a player's move in a game, validate its position, update the game board, check for win/draw conditions, and return the new game state. It handles terminal states by setting a draw, validates moves, applies the move if valid, and propagates win/draw checks before returning the upd...
def play(self, move: tuple[int, int], player: PlayerIdType | None = None): if self.terminal_state(): result = GameBoard(self.grid.copy()) result.set_draw() return result if player is None: player = self.get_player() grid = copy.deepcopy(self.grid) ...
def terminal_state(self) -> bool: return bool(self.winner) or not self.has_valid_moves() def has_won(self, player: PlayerIdType) -> bool: grid = self.grid horizontal_top = grid[0][0] == grid[0][1] == grid[0][2] == player horizontal_middle = grid[1][0] == grid[1][1] == grid[1][2] == playe...
This function checks if the game has reached a draw state by verifying if the game is in a terminal state and neither player has won. If true, it marks the game as a draw and returns True; otherwise, returns the result of the check.
def check_draw(self): is_draw = self.terminal_state() and not( self.has_won(PLAYER1_ID) or self.has_won(PLAYER2_ID)) if is_draw: self.set_draw() return is_draw
def browse(mode): if not mode.get(): for i in buts: i.config(state="disabled") for i in selectors: i.config(text = "") def selected_colour(mode,c): browse(mode) global selected selected = c if not mode.get(): show(selected) else: selectors[c].confi...
The code creates a GUI for a Rubik's Cube solver, allowing users to select modes (browse/edit), choose colors, scramble the cube via move buttons, reset the cube, and generate solutions. It sets up frames, buttons, and layout for displaying the cube state and outputting solutions, integrating interactive controls for c...
def main(root): global cols,Cols,selected,buts,selectors,dispcube cols = ["green","blue","white","yellow","red","orange"] Cols = ["g","b","w","y","r","o"] selected = 0 #DEFINING FRAMES title = LabelFrame(root,padx = 300) dispcube = LabelFrame(root,padx = 10,pady = 15,text = "Current State O...
def display(self, color): """Plot the neurons on the canvas as disks.""" # preparations r = self.neurons['radius'] x = self.neurons['x'] y = self.neurons['y'] fig, ax = plt.subplots(figsize=(8, 8), tight_layout=True) neurons_circles = [] for i in range(se...
The code simulates a model over a specified duration, collecting data samples at intervals. It updates the system state using `timestep()`, calculates mutual areas, and stores results in a NumPy array. If `progress=True`, it displays a real-time progress bar. Finally, it saves the sampled data to "data.npy" and display...
def render(self, duration: float=10**5, progress: bool=True) -> None: """Render the model for a set duration. ... Parameters ---------- duration in seconds progress Assign True is you want to see the progress bar. """ self.display(...
def get_current_player(self): return self.players[self.current_player_index] def increment_or_decrement_current_player_index(self, amount): count = self.get_count_of_players() if self.direction == '+': return (self.current_player_index + amount) % count elif self.direction ==...
This function processes a player's move in a card game by validating and executing the played card, updating game state (top card, color, direction), handling special cards (Draw Two/Wild Four) which may skip the next player and force them to draw cards, checking for win conditions, and returning appropriate responses ...
def play_card(self, client_data): client_card, client_card_index = client_data['card'], client_data['index'] client_username, client_next_top_color = client_data['username'], client_data['next_top_color'] # Fetching client_player_object/current_player_object current_player_obj = self.ge...
def color_simple(self): if self.simple_mode.get(): self.c_simple.configure(bg="#9f9") else: self.c_simple.configure(bg="#f99") def buttons_notes(self): frame = self.f_clavier_note bs = ["C", "Cm", "C#", "D", "Dm", "D#", "E", "Em", "E7", "F", "Fm", "F...
This code initializes a GUI window for a musical keyboard interface, setting up a Toplevel window with menus, a text display area, and customizable keyboard controls. It processes input text, enables simple mode toggling, and organizes widgets for note entry and tools, using Tkinter for layout, scrollbars, and interact...
def __init__(self, root, chaine, musique): self.musique = musique self.select = None self.chaine = chaine ch = "> " + chaine.get().replace("lf ", "\n> ").replace("end ", "").replace("end", "") self.root = root self.clavier = tk.Toplevel(self.root) self.clavier.t...
def request_as_df(batch): rows = [] timestamp = time.time() candidates = [key for key in batch.keys() if key.startswith('judgment')] for field in ['name', 'targetId']: if field not in batch: batch[field] = None for candidate in candidates: chtid = css_unescape(candi...
The main task of the code is to handle form submissions by capturing request parameters, storing them in a CSV file, and generating an HTML response that confirms submission, displays the submitted data, and provides status updates on available tasks, user progress, and recently rated items. It also includes error hand...
def submit(): input = dict(request.args.items()) name = request.args.get('name') response = "" if not os.path.exists(os.path.join(app.root_path, 'results')): os.mkdir(os.path.join(app.root_path, 'results')) if len(input) > 1: try: formatted = request_as_df(input) ...
def load_results(pathglob='results/results.*.csv', drop_duplicates=True): colnames = ['rater', 'target', 'candidate', 'judgment', 'notes', 'timestamp'] try: all_df = [pd.read_csv(path, names=colnames) for path in glob.glob(app.root_path + '/' + pathglob)] df = pd.concat(all_df) except: ...
The code generates an HTML response displaying statistics about ratings. It retrieves a user's name, loads data, and appends sections showing: 1) items needing rating, 2) the user's rating count, and 3) recently rated items. The output combines these metrics into a structured webpage for user feedback or analytics.
def stats(): name = request.args.get('name') response = "<h1>Info</h1>" df, rater_targets = load_results() response += "<hr /><h2>More to rate</h2>" response += print_target_counts(rater_targets, rater=name, n=15) response += "<hr /><h2>How much have you rated?</h2>" response += print_rat...
def load_data(self): if self.changes: print("Read csv...") self.people.clear() with open(self.path, "r") as f: csv_reader = csv.DictReader(f) for row in csv_reader: self.people.append(Person.from_row(row)) se...
The main task of the code is to add a new person to a data file. It prompts the user for an ID, first name, and last name, validates the input, appends the new person to the existing data list, and writes the updated data back to the file. It handles exceptions like invalid input and reports success or errors according...
def add(self): print("---> ADDING PERSON <---") try: people = self.load_data() new_person = Person( int(input("Enter id: ").strip()), input("Eneter first name: ").strip(), input("Enter last name: ").strip() ) ...
def get_expiry(self, args): expiry = args.get('expiry') try: return float(expiry) except Exception as e: raise Exception("Invalid expiry {}, {}".format(expiry, e)) def get_option_type(self, args): option_type = args.get('opt_type') valid_type = option_type...
This code handles an HTTP GET request to retrieve option pricing data. It extracts parameters like stock name, expiry, and option type from the request, calculates the option price, strike price, and related metrics using helper methods, formats the results into a structured JSON response, and returns it with a 200 OK ...
def get(self): print("New Option request...") args = request.args stock_name = args.get('stock') try: expiry = self.get_expiry(args) option_type = self.get_option_type(args) option_price, stock_price, strike, strike_pct = self.calculate_option(expiry,...
def _generate_function(func, out): sig = inspect.signature(func) param_names = list(sig.parameters) func_name = func.__name__ out.write(func_start.format(func_name=func_name)) # fmt is the format string that will be used in PyArg_ParseTupleAndKeywords fmt = '' kwlist = [] has_default = F...
The main task of the code is to generate boilerplate code for a Python extension module, including a C source file and setup script. It creates a C file with function stubs, module definitions, and NumPy compatibility if enabled, while also generating a setup.py to compile the module. The code ensures valid identifiers...
def generate_extmod(module_name, module_doc, funcs, numpy=False, c_filename=None, setup_filename="setup.py"): """ Generate the boilerplate code for a Python extenstion module. Parameters ---------- module_name : str The extension module name. module_doc : str or None...
def getDefaultCamera(): return bpy.data.objects['Camera'] def read_obj_model(filename): oldKeys = list(bpy.data.objects.keys()) # copies the object names list bpy.ops.import_scene.obj(filepath=filename) somethingSelected = False object = None for key in bpy.data.objects.keys(): if not (...
This function creates a 3D object based on the input source or file type. It loads a default camera if the source is 'CAMERA', or imports models from .obj/.wrl files. It then applies smooth shading, positions the object at (50000,50000,50000), selects it, and returns the object. If the file type is unsupported, it rais...
def makeDefaultObject(source,filename): if source == 'CAMERA': obj = getDefaultCamera() elif filename.endswith('obj'): obj = read_obj_model(filename) elif filename.endswith('wrl'): obj = read_wrl_model(filename) else: raise UnknownFileTypeException(filename) select_ob...
def run_sampling( self, nlive=200, bound='multi', sample='rwalk', walks=10, facc=0.2, ): self.sampler = dynesty.NestedSampler( self.loglike, self.prior_tranfer, 3, nlive=nlive, bound=bound, sample=sample, walks=walks, facc=facc, ...
The code performs one iteration of a sampling and optimization process. It runs sampling, updates evidence using quantile values, visualizes the iteration, checks convergence by calculating merit from sources and mass distributions, and either returns True if converged or updates the iteration state and returns False o...
def run_this_iteration(self): self.run_sampling() self.evidence_this_iter(self.quantiles[0,1], self.quantiles[1,1], self.quantiles[2,1]) #???? TODO #do visualization self.visualize_iteration(iter_num=self.count_iter) #check convergence self.merit_this_iter = self.merit_...
def stop_blinking(self): if self.blinking_thread: print("stop blinking") self.unblink() self.blinking_thread_stop = True # Signal the thread to stop self.blinking_thread = None def move_eyes(self, x_position, y_position): inverted_x = 1 - x_position ...
The code deactivates a system by setting `self.active` to False, stopping the blinking thread, moving eyes to the center, smoothly closing eyelids via servo positions, and scheduling a 5-second delay to trigger a sleep function.
def deactivate(self): self.active = False self.stop_blinking() # Stop the blinking thread self.move_eyes(0.5, 0.5) # Move eyes to center servo_positions = [(self.rt_eyelid, 0), (self.rb_eyelid, 0), (self.lt_eyelid, 0), (self.lb_eyelid, 0)] smooth_move_servos(servo_positions, 5)...
def is_wake_word(self, words): words = words.lower().strip() common_phrases = [ "hey howee", "howee, wake", "wake up howee", "hey howe", "he yhowee" ] # Check if the input matches closely with any of the common...
This code handles voice command processing based on the assistant's state. If in "LISTENING_FOR_WAKE_WORD" state, it detects a wake word to transition to input mode. If in "LISTENING_FOR_INPUT" state, it processes system commands. It returns appropriate responses and updates the state accordingly, emitting state change...
def web_phrase(self, words): response = "" print(self.state) if self.state == self.LISTENING_FOR_WAKE_WORD: if self.is_wake_word(words): response = self.wake_word_detected() self.state = self.LISTENING_FOR_INPUT self.emit_state() ...
def isHeapEmpty(self) -> bool: return self._currentSize == 0 def _getLastChild(self) -> Node: currentLevelCapacity: int = int(self._getCurrentLevelCapacity()) lastChildPositionInLevelBinary: str = bin(self._currentSize - currentLevelCapacity) pathToLastChild = self._generatePath(current...
This function removes and returns the smallest element from a min-heap. It handles edge cases for empty heaps and single-node heaps, then replaces the root with the last node in the heap, adjusts the heap structure by swapping and moving nodes down to maintain the min-heap property.
def getAndRemoveSmallest(self) -> int: if self.isHeapEmpty(): raise HeapIsEmptyException("Heap empty - cannot return data") oldRoot: Node = self._root if not self._root.right and not self._root.left: assert self._currentSize == 1 self._root = None ...
def get_b_value(graph, node): """ :param graph: Networkx graph :param node: Node :return: the value of attribute 'bValue' on the node """ return graph.nodes[node]['bValue'] def get_eta_value(graph, node): """ Returns the subtraction of the b value of the node from the summation of the b ...
The function identifies a node in the graph with a non-zero b-value, an eta value ≤ 0, and at least one neighbor with a non-zero b-value. It returns the first such node found or -1 if none exist, excluding cases where all neighbors have zero b-values.
def find_eta_lt0(graph): """ finds a node with a eta value less than 0; if none exists returns negative 1 NOTE: We don't want to cover the case where all neighbors bValues are 0 :param graph: Networkx Graph :return: node or -1 """ for n in graph.nodes(): if get_b_value(graph, n) != ...
def test_complete_graph_independence(trials=1000, matching_cap=4, nodes_set=None, min_weight=25, max_weight=2500): print("ANALYZING COMPLETE GRAPH:\n") if nodes_set is None: nodes_set = [50, 75, 100, 150, 200, 250] for nodes in nodes_set: average_recoveries = [] progress_bar = Bar(...
The main task of the code is to execute multiple graph independence tests using a specified capacity parameter. It runs tests on various graph types—complete, random edge, random probability, Barabási-Albert, small-world, near-complete, dominating, and ring—evaluating their independence properties under the given match...
def main(): cap = int(sys.argv[1]) test_complete_graph_independence(matching_cap=cap) test_random_edge_graph_independence(matching_cap=cap) test_random_prob_graph_independence(matching_cap=cap) test_barabasi_albert_graph_independence(matching_cap=cap) test_small_world_graph_independence(matching...
def find_eta_lt0(graph): """ finds a node with a eta value less than 0; if none exists returns negative 1 NOTE: We don't want to cover the case where all neighbors bValues are 0 :param graph: Networkx Graph :return: node or -1 """ for n in graph.nodes(): if get_b_value(graph, n) != ...
The code performs b-matching on a graph by iteratively adjusting edge weights based on node b-values. It identifies dominating nodes, executes block exchanges with neighbors, and repeatedly finds candidate edges with non-zero b-values. The algorithm selects minimal positive values from b-values and mu-values to update ...
def perform_b_matching(original_graph): """ Performs a b-matching on the provided graph with b-values on the nodes. :param original_graph: Networkx graph :return: a graph with weights on edges assigned to from b-values """ # Ensure that no weights exists on edges before beginning matching_gr...
def replayHist(self): if (self.replayData): #print('reading data') #print('fail: ',self.fail) #print(len(self.replayData)) #print(self.replayData[0:8]) self.replayData = self.Capon3DHeader(self.replayData) #print('fail: ',self.fail) ...
The function reads and parses UART data from a sensor, processes it using different header formats based on the SDK version, and saves the parsed data to binary/text files for replay or analysis. It handles error checking, data aggregation over frames, and structured output of point cloud/target information in specifie...
def readAndParseUart(self): self.fail = 0 if (self.replay): return self.replayHist() numBytes = 4666 data = self.dataCom.read(numBytes) if (self.byteData is None): self.byteData = data else: self.byteData += data if (self.saveBi...
def add_defaults(): t1 = world.cfg["server_times"]["renew-timer"] t2 = world.cfg["server_times"]["rebind-timer"] t3 = world.cfg["server_times"]["preferred-lifetime"] t4 = world.cfg["server_times"]["valid-lifetime"] eth = SERVER_IFACE pointer_start = "{" pointer_end = "}" world.cfg["main...
The function configures and deploys Kea DHCP server settings by updating lease file paths, generating configuration files, sending them to a target system via fabric, copying them to designated locations, and removing local temporary files to finalize deployment.
def build_and_send_config_files(): world.cfg['leases'] = SOFTWARE_INSTALL_DIR + 'var/kea/kea-leases6.csv' add_defaults() set_kea_ctrl_config() cfg_write() fabric_send_file(world.cfg["cfg_file"], SOFTWARE_INSTALL_DIR + "etc/kea/kea.conf") fabric_send_file(world.cfg["cfg_file_2"], SOFTWARE_INSTALL...
def build_and_send_config_files(): world.cfg['leases'] = SOFTWARE_INSTALL_DIR + 'var/kea/kea-leases6.csv' add_defaults() set_kea_ctrl_config() cfg_write() fabric_send_file(world.cfg["cfg_file"], SOFTWARE_INSTALL_DIR + "etc/kea/kea.conf") fabric_send_file(world.cfg["cfg_file_2"], SOFTWARE_INSTALL...
The code starts or restarts the Kea DHCP service using generated configuration files. It checks the current status of IPv6 and IPv4 services, stops and restarts Kea if needed, executes commands via `fabric_sudo_command`, and validates the process outcome with `check_kea_process_result`. The function handles both initia...
def start_srv(start, process): """ Start kea with generated config """ build_and_send_config_files() v6, v4 = check_kea_status() if process is None: process = "starting" if not v6: result = fabric_sudo_command('(' + SOFTWARE_INSTALL_DIR + 'sbin/keactrl start ' ...
def rnn_forward(X, Y, a0, parameters): # Initialize x, a and y_hat as empty dictionaries x, a, y_hat = {}, {}, {} a[-1] = np.copy(a0) # initialize your loss to 0 loss = 0 for t in range(len(X)): # Set x[t] to be the one-hot vector representation of the t'th c...
The function `optimize` performs a single optimization step for training an RNN model. It executes forward propagation to compute the loss, backpropagates through time to calculate gradients, clips gradients to prevent exploding values, and updates model parameters using the learning rate. The task involves training th...
def optimize(X, Y, a_prev, parameters, learning_rate : float = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the same as X but shifte...
def initialize_parameters(n_a, n_x, n_y): """ Initialize parameters with small random values Returns: parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiply...
The main task of the code is to train an RNN (likely an LSTM) to generate dinosaur names from a given text corpus. The model iteratively learns to predict the next character in a sequence, using the provided data. During training, it updates parameters via optimization, smooths loss, and periodically samples and prints...
def model(data, num_iterations = 100000, n_a = 50, num_samples = 7, verbose = False): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus num_iterations -- number of iterations to train the model for n_a -- number of units of the RNN cell num_samples -- nu...
def search(self, retries=0): try: params = { 'retmode': 'json', 'db': self.db, 'term': self.term, 'retmax': self.pagination['retmax'], 'retstart': self.pagination['retstart'], } res = requests.get(f'{ENTREZ}/eutils/esearch.fcgi', params=params) result = res.json()['esearchresult'] i...
The main task of the code is to iterate through paginated search results, fetch ID lists from each page, and process them using `fetchIds()`. It starts by initializing search and pagination, then loops through all pages, retrieving and handling IDs until all pages are processed.
def start(self): self.search() self.paginate() print('STARTING...') for page in range(1, self.pagination['total']): idlist = self.search() if(idlist): self.fetchIds(idlist) self.nextPage()
def getId(self, country, field="regex"): try: self.getCountries() # Find by regex for c in self.countries: reg = re.compile(c[field], re.MULTILINE | re.IGNORECASE) match = reg.match(country) if (match): retur...
The main task of the code is to retrieve a country ID from a publication's affiliation data. It first extracts and cleans the country name from the publication's first affiliation, then attempts to get an ID using a helper method. If unsuccessful, it reports the country as not found. If the country name exists but no I...
def findCountry(self): countryId = None try: # Get country of first afiliation countryName = self.publication['affiliations'][0]['country'] countryId = self.getId(countryName.replace('.', '').replace(' ', '').replace(';', '')) except: # Tag Country...
def joint_fuzzy_entropy(self, M_f1, M_f2): h = 0.0 for i in range(self.n_samples): h -= np.log2(self.ind_cardinality(i,M_f1,M_f2)/self.n_samples) h = h / self.n_samples return h def joint_fuzzy_entropy_more(self, M_f_list): h = 0.0 for i in range(self.n_sampl...
The function calculates the conditional fuzzy mutual information between variables X and Y given Z by combining joint fuzzy entropies of (X,Z), (Y,Z), and (X,Y,Z), along with the fuzzy entropy of Z, using the formula: H(X,Z) + H(Y,Z) - H(X,Y,Z) - H(Z).
def canditional_fuzzy_mutual_information(self, M_x, M_y, M_z): Hxz = self.joint_fuzzy_entropy(M_x, M_z) Hyz = self.joint_fuzzy_entropy(M_y, M_z) Hxyz = self.joint_fuzzy_entropy_more([M_x, M_y, M_z]) Hz = self.fuzzy_entropy(M_z) return Hxz + Hyz - Hxyz - Hz
def get_db_cursor(commit=False): with get_db_connection() as connection: cursor = connection.cursor(cursor_factory=DictCursor) # cursor = connection.cursor() try: yield cursor if commit: connection.commit() finally: cursor.close() def get_user_id_f...
This function adds a product to a user's routine wishlist by inserting a record into the 'skineasy_routines' table, ensuring uniqueness through an ON CONFLICT clause. It retrieves user and product IDs from provided input, logs the action, and executes the database insertion.
def add_to_routine(user_product_info): with get_db_cursor(True) as cur: current_app.logger.info('Adding entry to routine table') # Get username and product name username = user_product_info['username'] product_name = user_product_info['productName'] # Build SQL where state...
def get_db_cursor(commit=False): with get_db_connection() as connection: cursor = connection.cursor(cursor_factory=DictCursor) # cursor = connection.cursor() try: yield cursor if commit: connection.commit() finally: cursor.close() def get_user_id_f...
The code removes a product from a user's routine wishlist by executing a SQL DELETE statement on the 'skineasy_routines' table, using the user's ID and product ID derived from input parameters. It retrieves these IDs via helper functions, then deletes the corresponding entry to update the user's routine preferences.
def remove_from_routine(user_product_info): with get_db_cursor(True) as cur: current_app.logger.info('Adding entry to routine table') # Get username and product name username = user_product_info['username'] product_name = user_product_info['productName'] # Build SQL where ...
def get_db_cursor(commit=False): with get_db_connection() as connection: cursor = connection.cursor(cursor_factory=DictCursor) # cursor = connection.cursor() try: yield cursor if commit: connection.commit() finally: cursor.close() def get_product_d...
The main task of the code is to add or update a product review in the database, ensuring the user hasn't already reviewed the product. It validates inputs, checks for existing reviews, updates product review counts, total scores, and average ratings, and inserts or updates review data in the 'skineasy_reviews' table wi...
def add_review(reviewer_name, user_id, product_id, title, content, rating, img_filename, img_stream): with get_db_cursor(True) as cur: # Only add review if we have required parameters if (reviewer_name is None or user_id is None or product_id is None or rating is None): current_app.logg...
def parse_filter_file(filter_file): keys = [] with open(filter_file) as fin: for li in fin: if not li[0] in ['#']: lis = li.split(' ') if len(lis) == 1: key = lis[0].rstrip() if len(key) > 0: keys...
The function `dbd_to_dict` converts a dinkum binary file (raw glider data) into two dictionaries: one containing sensor data and another holding metadata. It parses the ASCII header for metadata, reads binary data using bitstream operations, processes sensor values based on update codes, and filters data according to s...
def dbd_to_dict(dinkum_file, cachedir, keys=None): """ Translate a dinkum binary file to a dictionary of data and meta values. Parameters ---------- dinkum_file : dbd file name (full path) These are the raw data from the glider, either offloaded from a card or from the dockserver. ...
def parse_filter_file(filter_file): keys = [] with open(filter_file) as fin: for li in fin: if not li[0] in ['#']: lis = li.split(' ') if len(lis) == 1: key = lis[0].rstrip() if len(key) > 0: keys...
The function `binary_to_rawnc` converts Slocum glider binary data (`.ebd`, `.dbd`) into raw NetCDF files. It processes science and flight data from specified directories, filters sensors using a list, and uses deployment metadata from a YAML file. It ensures incremental processing by re-parsing only outdated files and ...
def binary_to_rawnc(indir, outdir, cacdir, sensorlist, deploymentyaml, incremental=True, scisuffix='EBD', glidersuffix='DBD'): """ Convert slocum binary data (*.ebd/*.dbd) to raw netcdf files. Parameters ---------- indir : str Directory with the raw *.ebd (science) and *.dbd...
def gaussian_kernel_1d(sigma, asTensor=False, dtype=th.float32, device='cpu'): kernel_size = int(2*np.ceil(sigma*2) + 1) x = np.linspace(-(kernel_size - 1) // 2, (kernel_size - 1) // 2, num=kernel_size) kernel = 1.0/(sigma*np.sqrt(2*np.pi))*np.exp(-(x**2)/(2*sigma**2)) kernel = kernel/np.sum(kernel) ...
The function generates a Gaussian kernel of specified dimension (1D, 2D, or 3D) using the given sigma value. It delegates to specialized helper functions for each dimension and returns the kernel as a tensor or array, with configurable data type and device (CPU/GPU). The dimension is validated to ensure it is between 1...
def gaussian_kernel(sigma, dim=1, asTensor=False, dtype=th.float32, device='cpu'): assert dim > 0 and dim <=3 if dim == 1: return gaussian_kernel_1d(sigma, asTensor=asTensor, dtype=dtype, device=device) elif dim == 2: return gaussian_kernel_2d(sigma, asTensor=asTensor, dtype=dtype, device=...
def _process_variables( env, variables_id, template_variables ): if variables_id != 0: if isinstance( template_variables, dict ): return process_variables( env, variables_id, variables=template_variables ) else: return process_variables( env, variables_id, variables_file=temp...
The main task of the code is to render a Jinja2 template using provided variables, handle template path adjustments, and write the rendered output to a file. It processes input variables, constructs template paths, copies templates if needed, and uses the Jinja2 environment to render the template with specified variabl...
def render_template( env, source, variables_id, template_variables, template_file=None, write=False ): base_path = env['sconstruct_dir'] templates_search_path = env['abs_build_dir'] logger.debug( "source = {}".format( as_info( str(source) ) ) ) logger.debug( "template_file = {}".forma...
def collectAllData(self): """ function -conjunct all .csv file from the dataPath specified as follow output -set self.allNeededData, including the required columns specified by the neededColumns """ dataPath = self.dataPath allName = [f for f in l...
The code's main task is to process social media data by collecting all data from a specified directory, removing duplicated brand entries, filtering the data based on a count threshold, and exporting the cleaned result. The methods ensure data is aggregated, deduplicated, refined, and saved for further analysis or use.
def __init__(self): self.dataPath = "./data/socialstat/" self.collectAllData() self.removeDuplicatedBrands() self.filterDataByCount() self.exportResult() pass
def __parse_path(self, path): dirs = re.sub(r"[/\\]+", r"\\", path).strip("\\").split("\\") return dirs def visit_dir(self, dir) -> RDET: if dir == "": raise Exception("Directory name is required!") dirs = self.__parse_path(dir) if dirs[0] == self.name: cdet = self.DET[self.boot_sector[...
This code reads a text file from a FAT file system by parsing the path, locating the file entry, retrieving its cluster chain, and concatenating the raw data while validating it's a text file. It handles directory traversal, cluster offsets, and Unicode decoding, raising exceptions for invalid paths, directories, or no...
def get_text_file(self, path: str) -> str: path = self.__parse_path(path) if len(path) > 1: name = path[-1] path = "\\".join(path[:-1]) cdet = self.visit_dir(path) entry = cdet.find_entry(name) else: entry = self.RDET.find_entry(path[0]) if entry is None: raise Excep...
def __parse_path(self, path): dirs = re.sub(r"[/\\]+", r"\\", path).strip("\\").split("\\") return dirs def visit_dir(self, dir) -> RDET: if dir == "": raise Exception("Directory name is required!") dirs = self.__parse_path(dir) if dirs[0] == self.name: cdet = self.DET[self.boot_sector[...
This function retrieves the content of a specified file by parsing its path, locating the file entry in the directory structure, validating that it is a regular file (not a directory), and reading its data from disk. It returns the file's content as bytes, raising exceptions if the file does not exist or is a directory...
def get_file_content(self, path: str) -> bytes: path = self.__parse_path(path) if len(path) > 1: name = path[-1] path = "\\".join(path[:-1]) cdet = self.visit_dir(path) entry = cdet.find_entry(name) else: entry = self.RDET.find_entry(path[0]) if entry is None: raise...
def get_starting_location(self): current_row_index = np.random.randint(self.size) current_column_index = np.random.randint(self.size) while self.is_terminal_state(current_row_index, current_column_index): current_row_index = np.random.randint(self.size) current_column_index = np.rand...
This code trains a reinforcement learning agent using Q-learning to navigate a grid environment. It iterates through episodes, updating Q-values based on rewards and temporal differences. The agent learns optimal actions to reach terminal states (item packaging area) while avoiding obstacles (item storage locations).
def train(self): for episode in range(1000): #get the starting location for this episode row_index, column_index = self.get_starting_location() #continue taking actions (i.e., moving) until we reach a terminal state #(i.e., until we reach the item packaging area or crash into a...
def populateGenres(self): self.listOfGenre = self.getPropertyGenres() def getCustomerGenres(self): userGenreIndex = 0 while userGenreIndex < len(self.listOfGenre): userGenreIndex = self.getBookGenreIndex() if userGenreIndex < len(self.listOfGenre): userGen...
The main task of the code is to initialize the shop's functionality by populating available genres, retrieving customer genre preferences, and displaying all books. This method orchestrates setup and presentation of book data tailored to customer interests.
def openShop(self): self.populateGenres() self.getCustomerGenres() self.displayAllBooks()
def speak(audio): printo(audio+"\n") engine.say(audio) engine.runAndWait() def printo(shan): global comtext comtext.set(shan) def wishMe(): hour = int(dt.datetime.now().hour) if hour>=6 and hour<12: speak("Good Morning!" +name) elif hour>=12 and hour<18: speak("Good Afte...
The code captures user's voice input to recognize their name using Google's speech recognition API. It listens via microphone, processes audio, and returns the recognized name. If recognition fails, it prompts the user to repeat. The function recursively retries on errors and returns the name or None if unsuccessful.
def Name(): global r,source,audio,query,name name=" " r = sr.Recognizer() with sr.Microphone() as source: speak("What is your name") printo("Please tell me Your name\n") printo("Listening...\n") audio = r.listen(source) try: printo("Recognizing...\n"...
def Commands(): global r,source,audio,query,usertext r = sr.Recognizer() #recognizer initialized r.energy_threshold=5000 with sr.Microphone() as source: printo("Listening...\n") r.pause_threshold = 1 audio = r.listen(source) try: printo("Recognizing...\n") q...
The main task of the code is to process voice commands and execute corresponding actions, such as searching the web, opening websites, playing media, sending emails, and system shutdown. It acts as a voice-controlled assistant that interacts with the system and external APIs to fulfill user requests based on predefined...
def reco(): query = Commands().lower() # Logic for executing tasks based on query if 'search google' in query: srch_google() elif 'search youtube' in query: search_yt() elif 'open my music website' in query: webbrowser.open("djpunjab.com") elif ...
def _get_random_location(self): if self._random_walk_policy == 'edge': curr = self._get_random_seed(self._center_seed) elif self._random_walk_policy == 'radius': curr = self._get_random_seed_from_radius() else: raise ValueError return curr def _take_ra...
The main task of the code is to simulate the growth of particles through random walks until a specified maximum number of particles is reached. It generates new particles when a random walk intersects with existing structures, incrementally increasing the particle count while logging progress if enabled. The process co...
def grow(self): random.seed() n_particles = 2 n_walks = 0 while n_particles < self._max_particles: curr = self._get_random_location() n_walks += 1 while True: curr = self._take_random_step(curr) if self._is_near_edge(c...
def filter_valid_actions(self, my_unit, my_units, enemies, resource_locs, action, start_turn_actions): dx, dy, dir_param = self.get_dir(action[1]) if my_unit['x']+dx <0 or my_unit['y']+dy <0 or my_unit['x']+dx>=self.map_width or my_unit['y']+dy >=self.map_height: #exceeds map limits return ...
This function determines valid actions for a game unit based on its type, game state, and priority rules. It filters possible actions (e.g., attack, move, harvest) for units like workers, bases, and barracks, prioritizing resource collection, enemy engagement, and strategic positioning. Automated miners follow predefin...
def get_action(self, my_unit, my_units, enemies, resource_locs, start_turn_actions, players_money, replay_action_id, this_cycle_actions): if my_unit['type'] == 'Worker': my_possible_actions = self.worker_actions elif my_unit['type'] == 'Base': my_possible_actions = self.base_act...
def pre_game_analysis(self, time_limit, read_write_directory, current_state_json): self.performed_pre_game_ananlysis = True if self.agent_log_directory is None and read_write_directory is not None: self.agent_log_directory = read_write_directory.replace('\\','/').strip('"').replace('"','') ...
This code processes a game state for an AI agent, managing unit actions, resource allocation, and movement. It initializes game elements, tracks blocked cells, builds mining routes, assigns workers, and handles unit production within a time budget. The function generates actions for the player's units, ensuring they co...
def forward(self, current_state_json, my_player_id): start_frame = time.time() self.current_time_log = {} self.current_time_log['attack_closest'] = 0 self.current_time_log['miner_movement'] = 0 self.player_id = my_player_id self.enemy_id = 1 - my_player_id self....
def test(lane_agent, test_images, thresh = p.threshold_point): result = lane_agent.predict_lanes_test(test_images) confidences, offsets, instances = result[-1] # result: 2x num_batch = len(test_images) out_x = [] out_y = [] out_images = [] IMAGENET_MEAN = np.array([0.485, 0.456, 0.40...
This function evaluates a lane detection model by processing test images through the provided agent, converting predicted coordinates to original image sizes, adjusting them based on target parameters, and saving the results in JSON format. It iterates over test data, applies the model, adjusts predictions, and writes ...
def evaluation(loader, lane_agent, thresh = p.threshold_point, name = None): result_data = deepcopy(loader.test_data) for test_image, target_h, ratio_w, ratio_h, testset_index in loader.Generate_Test(): x, y, _ = test(lane_agent, np.array([test_image]), thresh) x, y = util.convert_to_original_si...
def trans(self, img, xs, ys): sample = img, xs, ys sample = self.Hflip(sample) sample = self.Translation(sample) sample = self.Rotate(sample) sample = self.Gaussian(sample) sample = self.Change_intensity(sample) sample = self.Shadow(sample) img, xs, ys = s...
This code loads an image and lane data for a specific index, resizes the image to a predefined size, processes lane coordinates by scaling them, generates ground truth tensors (including binary and instance masks), and returns the transformed image along with the ground truth data and original coordinates for training ...
def __getitem__(self, idx): data = self.dataset[idx] image = cv2.imread( self.images_path + data['img_path'] + '.bmp' ) # print('imread img shape {}'.format(image.shape)) if image is None: logging.info('ERROR! cant not read image {}'.format(idx)) ratio_w = self.cfg['x...
def conv_layer(input, shape): W = weight_variable(shape) b = bias_variable([shape[3]]) return tf.nn.relu(tf.layers.batch_normalization(conv2d(input, W) + b)) def max_pool_2x2(x): return tf.nn.max_pool( x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME' ) def full_layer(input, size): ...
The code defines a convolutional neural network (CNN) model for classification tasks, specifically emotion detection. It processes input images through multiple convolutional layers with increasing filter counts (C1→C2→C3), followed by max-pooling and dropout for regularization. Features are flattened and passed throug...
def model(x, keep_prob): C1, C2, C3 = 30, 50, 80 F1 = 512 conv1_1 = conv_layer(x, shape=[3, 3, 1, C1]) conv1_1_pool = max_pool_2x2(conv1_1) conv1_2 = conv_layer(conv1_1_pool, shape=[3, 3, C1, C2]) conv1_2_pool = max_pool_2x2(conv1_2) conv1_drop = tf.nn.dropout(conv1_2_pool, keep_p...
def getCurrentTime(self): # Calc current Program time return time.time() - self.startTime def bezierSpline(self, vectors, t): # Build Segments # Add first 4 points arrays = [vectors[:4]] vectors = vectors[4:] # Add subsequent 2 points for _ in range((int)...
The main task of the code is to render a dynamic 3D scene with animated camera movement, dynamic lighting, and textured objects using OpenGL. It sets up a projection/view matrix, binds textures, animates a camera along Bezier curves, controls multiple lights with time-based positions and colors, and renders cubes, a sp...
def display(self): t = self.getCurrentTime() glEnable(GL_DEPTH_TEST) ### --- NEED THIS FOR NORMAL 3D BUT MANY EFFECTS BETTER WITH glDisable(GL_DEPTH_TEST) ... try it! --- ### glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) ### --- YOU CAN ALSO CLEAR ONLY THE COLOR OR ONLY THE DEPTH --- ##...
def generate_parameters(parameters): args = [] for param in parameters: if param[0] == 'i': args.append(get_int_value(param[1:])) elif param[0] == 's': args.append(param[1:]) elif param[0] == 'c': args.append(param[1]) elif param[0] == 'e': ...
The code runs test cases by comparing method implementations between two classes, tracking executed/successful methods, and reporting results. It initializes counters, generates parameters, creates class instances, executes methods, and logs statistics like success percentages and missing methods.
def setup(): global executed_methods, successful_methods, missing_methods successful_tests = 0 executed_tests = 0 successful_methods = 0 executed_methods = 0 missing_methods = [] test_cases = config['testcases'] for test_case_name, test_case in test_cases.items(): execu...