dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def Init(self): self.window_width = 512 self.window_height = 750 self.reset() self.x = (self.window_width // (self.column_count+1)) self.y = (self.window_height // (2*self.row_count)) # add an offset to x due to road border si...
The function handles key events, specifically restarting the game when the 'r' key is pressed by resetting the game state, redrawing the game window, and displaying a "Restart!" message box.
def window_key_event(event): print ("pressed", repr(event.char)) ch = event.char if (ch == "r"): self.Init() img = self.DrawGameState(self.game_state, self.window_width, self.window_height) self.BlitImageToWindow(img) me...
def get_height(): h = get_int("Height: ") return h def draw(h, s): if h is 1: make(h, s) else: draw(h - 1, s) make(h, s)
The main task of the code is to validate user input for a height value between 1 and 8. If the input exceeds 8 or is less than 1, the function recursively calls itself to re-prompt the user. Once a valid height is provided, it triggers the `draw` function with the height as both parameters, likely generating a visual p...
def main(): height = get_height() if height > 8 or height < 1: main() else: draw(height, height)
def pre_cycle(self): """ Check WIFI and update from wifi. """ ''' if (self.state==DETECT): print ("Connected") self.state=IDLE ''' if (self.state==DETECT): #initialize wifi #initialStateList is in the format [initia...
The main task of the code is to continuously loop through system states (IDLE, INITIAL, ACTIVE), updating connection status and context with PyUI, executing state-specific actions, and maintaining operational state with a 1-second delay between cycles.
def main(self): """ Main function to loop through when system is not in IDLE state. """ while True: self.pre_cycle() # Check connection and update information from PyUI if (self.state==IDLE): self.state_IDLE() elif (self.state==...
def _initialise_population(self): """ Initializes the population with random curve parameters. """ for i in range(self.population_size): self._population.append(self._get_random_curve_param()) def _select_parents(self): """ Selects parent sequences for breedin...
The code uses a genetic algorithm to evolve curve parameters for signal fitting by iterating through generations, selecting parent solutions, generating new populations, and returning the best-performing curve parameters based on fitness evaluation.
def generate(self, generations=1000): """ Generates curve parameters for fitting a signal using genetic algorithm. Parameters: generations (int): Number of generations for evolution. Returns: best_chord_sequence (list): Curve parameters with the highest fitness....
def find_y_bars(n, r_outer, r_inner, g_array): phi_array = find_phi(n, g_array, r_outer) y_bar_o_array = find_y_bar_os(n, r_outer, phi_array) y_bar_i_array = find_y_bar_is(n, r_inner, phi_array) A_outer_array = find_A_outers(n, r_outer, phi_array) A_inner_array = find_A_inners(n, r_inner, phi_array)...
This function calculates deflections and curvatures (kappas) for a range of applied forces on a structural system, considering geometric and material properties. It iterates over 50 force increments, computes corresponding theta and kappa values using a solver, and returns force-deflection-kappa relationships for analy...
def find_forces_thetas_kappas(n, max_force, r_outer, r_inner, g_array, h_array, mu, E_linear, E_super, epsilon_low): eta = 0.35 y_bar_array = find_y_bars(n, r_outer, r_inner, g_array) I_array = find_Is(n, r_outer, r_inner, g_array, y_bar_array) theta_max_array = find_theta_max(n, h_array, r_outer,...
def find_y_bars(n, r_outer, r_inner, g_array): phi_array = find_phi(n, g_array, r_outer) y_bar_o_array = find_y_bar_os(n, r_outer, phi_array) y_bar_i_array = find_y_bar_is(n, r_inner, phi_array) A_outer_array = find_A_outers(n, r_outer, phi_array) A_inner_array = find_A_inners(n, r_inner, phi_array)...
This function calculates deflections and final kappas for a given force in a structural analysis model. It computes geometric properties (y_bar, I), maximum angles (theta_max), and stress thresholds (sigma_low), then uses a solver to determine theta and kappa distributions across n segments. The results, along with the...
def find_thetas_kappas_for_one_force(n, force, r_outer, r_inner, g_array, h_array, mu, E_linear, E_super, epsilon_low): eta = 0.35 y_bar_array = find_y_bars(n, r_outer, r_inner, g_array) I_array = find_Is(n, r_outer, r_inner, g_array, y_bar_array) theta_max_array = find_theta_max(n, h_array, r_outer, y...
def preproc(data): proc_data = [] for index, row in data.iterrows(): try: proc_data.append(' '.join(preprocess(row["articleHead"]))) except Exception: continue return pd.DataFrame(proc_data, columns=['clean_text']) def getBigram_pmi(clean_data): bigram_measures =...
The main task of the code is to extract the most relevant topic keywords from a cluster of text data using n-gram generation, noun filtering, and LDA topic modeling. It preprocesses text, identifies high PMI bigrams/trigrams, constructs a document-term matrix, trains an LDA model with 1 topic, extracts top 4 words as t...
def getTopic(cluster_data, original_data): # Preprocess - 1 clean_data = preproc(cluster_data) # Preprocess - 2 bigram_pmi = getBigram_pmi(clean_data) trigram_pmi = getTrigram_pmi(clean_data) bigrams, trigrams = get_bi_tri_grams(bigram_pmi, trigram_pmi) clean_text_w_ngrams = get_ngram(cle...
def makeMainMenu(): squarewidth = 90 pygame.draw.rect(screen,(255,255,255),(0,0,xres,yres)) menuFont = pygame.font.SysFont("ariel", 15) infolabel1 = menuFont.render("Choose a dificulty and length to start:",1,(0,0,0)) screen.blit(infolabel1,(10,10)) pygame.draw.rect(screen,(0,0,0),(10,25,squar...
The main task of the code is to run a simulation/game loop that updates game state (e.g., clockticks, cash, visitors), renders UI elements (text, progress bars, goals), and handles user interactions (mouse clicks, keyboard input) to manage resources and achieve objectives like generating visitors or money within specif...
def main(): global clockticks,visitorTarget,Screenmode pygame.font.init() x = 10 y = 10 # pygame.draw.rect(screen,(0,0,255),(50,50,50,50),1) #vertical lines #pygame.draw.line(screen,(255,0,0),(x,0),(x,yres),1) #horizontal lines #pygame.draw.line(screen,(255,0,0),(0,10),(ga...
def ImgProg(self): self.Takeimg() ref_lower = np.array([0,0,0]) ref_upper = np.array([2,2,2]) plant_lower = np.array([60, 60, 25]) plant_upper = np.array([115, 255,255]) self.Takeimg() # self.img_frame = self.CurrentImg hsv = cv.bilateralFilter...
The code initializes an object to monitor greenhouse data by reading a CSV file's line count as an ID, capturing sensor data, processing images, saving them, writing data to the CSV, and uploading images to Firebase. It sets the current date/time, processes image data, collects sensor readings, converts data to arrays,...
def __init__(self): filepath = "/home/pi/Desktop/Green House/DataMonitor.csv" with open(filepath) as file: self.ID = sum(1 for line in file) file.close() self.ImageUri = None # self.RefArea today = date.datetime.now() self.DateTime = today.strftime("%Y/...
def find_team_list(date): scoreboard = find_scoreboard(date) teams = [] for game in scoreboard['GameHeader']: winner = {'id': game['HOME_TEAM_ID'], 'gameId': game['GAME_ID']} loser = {'id': game['VISITOR_TEAM_ID'], 'gameId': game['GAME_ID']} teams.append(winner) teams.append(...
The code processes game data for a specific date by retrieving teams, finding or creating matchups, populating them with team details (ID, name, season), and saving the structured matchup data. It ensures each team's information is linked to its game, aggregates all matchups, and persists them for the given date and se...
def find_matchups_and_save(date): matchups = [] season = find_season(date) for team in find_team_list(date): matchup = find_matchup(str(team['gameId']), matchups) if matchup is None: matchup = create_matchup(team['gameId'], date) matchups.append(matchup) add_t...
def other_possible_arg(output_param: str): if output_param.startswith("fmt.Errorf"): return ["nil"] # if output_param.startswith("error"): # return ["nil"] if "errorString" in output_param: return ["nil"] if output_param == "txObj": return ["nil"] if output_param ==...
The function generates all possible test cases by varying mock function outputs based on `is_output_used`, creates new test case copies with these variations, checks for duplicates, and appends unique ones to `test_case_q` with new IDs. It leverages combinations of output possibilities to expand test coverage while avo...
def mock_other_possible_test_cases(test_case_q: List[TEST_CASE_DICT], ut_test_case_dict: UT_TEST_CASES_DICT, test_case: TEST_CASE_DICT, mock_func: MOCK_FUNC_DICT, is_output_used: List[bool]): if len(is_output_used) == 0: return test_case_q combinations: List[List[str]] = [] other_output_possibilites...
def get_func_name_from_func_definition(func_definition): return func_definition.split('(')[0].strip() def replace_input_parameters(test_case: TEST_CASE_DICT, mock_func: MOCK_FUNC_DICT, unexpected_method_call_input_params): # assuming func call will not be having more than 10 params if len(unexpected_method_...
The function identifies a mock method called more than once in a failed test case, determines the appropriate mock function based on the method name, replaces its parameters if necessary, and updates the test case with the corrected mock function to resolve the over-call error.
def called_over_1_times(ut_test_case_dict: UT_TEST_CASES_DICT, test_case_q: List[TEST_CASE_DICT],test_case: TEST_CASE_DICT, failed_test_case: str) -> TEST_CASE_DICT: failed_test_case_lines = failed_test_case.split('\n') unexpected_method_call_input_params = [] mock_func_name = "" new_mock_func: MO...
def is_slide(self, small_epsilon=False): if small_epsilon: if (abs_exclude_z(self.v) > common.SMALL_POS_EPSIL) and ( abs_exclude_z(self.u) > common.SMALL_POS_EPSIL): return True return False else: if ((abs_exclude_z(self.v) > common...
The function `update_state_collide` determines the current motion state (sliding, rolling, spinning, or stationary) of an object. It updates the `present_state` variable, resets the transition counter `t` to 0, and adjusts additional parameters like `heading_angle_changed` or `w0_vertical` based on the detected state. ...
def update_state_collide(self): if self.is_slide(): if self.present_state != SLIDING_STATE: self.previous_state = self.present_state self.present_state = SLIDING_STATE # Update Transition value self.t = 0 elif self.is_roll(): ...
def check_life_time_expire(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) < t) or (self.t > t): return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if two billiard balls will collide at a future time t by verifying their active lifetimes, ensuring they are on the table (not in pockets), calculating their future positions, and confirming their relative velocity indicates an imminent collision. It returns True if all conditions for a valid colli...
def is_real_physics_time_ball_collide(self, other, t): # Check Life time position_future_1 = self.check_life_time_expire(t) position_future_2 = other.check_life_time_expire(t) if (position_future_1 is None) or (position_future_2 is None): return False # Check whether...
def check_life_time_expire(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) < t) or (self.t > t): return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if a billiard ball will collide with a specified rail at time `t` by verifying if the ball's future position lies within the rail's collision boundaries and if the relative velocity component along the collision normal is negative, indicating an actual impact. It returns `True` if a valid collision...
def is_real_physics_time_rail_collide(self, t, rail_index): # Check Life time bt = table.BilliardTable r_future = self.check_life_time_expire(t) if r_future is None: return False # Check whether ball will be lying on the table or not if is_outside_table_area(...
def check_life_time_expire(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) < t) or (self.t > t): return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if a billiard ball will collide with a specific pocket rail at time t by calculating the future position of the ball, checking for intersection with the rail's line segment, and verifying if the relative velocity indicates an approaching collision. It returns True if a valid collision occurs, other...
def is_real_physics_time_pock_rail_collide(self, t, line_index): # Check Life time position_future = self.check_life_time_expire(t) if position_future is None: return False # Check whether ball will be lying on the table or not # if is_outside_table_area(position_fut...
def check_life_time_expire(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) < t) or (self.t > t): return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if a billiard ball will collide with a pocket corner point at a future time `t` by calculating the ball's predicted position, distance from the corner, and relative velocity. If the ball's future position lies within the pocket's radius and its velocity vector points toward the corner, it returns `...
def is_real_physics_time_pock_rail_point_collide(self, t, corner_point): # Check Life time position_future = self.check_life_time_expire(t) if position_future is None: return False # Check whether ball will be lying on the table or not # if is_outside_table_area(posi...
def check_life_time_expire(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) < t) or (self.t > t): return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if a ball will collide with a pocket at time `t` by calculating the future position, verifying proximity to the pocket's radius, and ensuring the ball's velocity direction points toward the pocket. It returns `True` if a collision occurs, otherwise `False`.)
def is_real_physics_time_pock_collide(self, t, pocket_center): # Check Life time position_future = self.check_life_time_expire(t) if position_future is None: return False # Check whether ball will be lying on the table or not # if is_outside_table_area(position_futur...
def check_life_time_expire_dynamic(self, t): if self.present_state == SLIDING_STATE: if (cal_time_slide_end(self.u0) - self.t) < t: return None else: position_future = cal_slide_posit(self.r0, self.heading_angle, ...
This function checks if two dynamic billiard balls will collide at a future time `t` by calculating their future positions, verifying they are within table/pocket boundaries, computing relative velocities, and checking if their distance is within collision range. It returns `True` if a valid collision occurs, consideri...
def is_real_physics_time_ball_collide_dynamic(self, other, t): # Check Life time position_future_1 = self.check_life_time_expire_dynamic(t) position_future_2 = other.check_life_time_expire_dynamic(t) if (position_future_1 is None) or (position_future_2 is None): return False ...
def is_roll(self, small_epsilon=False): if small_epsilon: if (abs_exclude_z(self.v) > common.SMALL_POS_EPSIL) and ( abs_exclude_z(self.u) <= common.SMALL_POS_EPSIL): return True return False else: if ((abs_exclude_z(self.v) > common...
This function manages state transitions in a dynamic system by checking the current state (e.g., sliding, rolling, spinning) and updating it based on conditions like `is_roll()`, `is_spin()`, or `is_stationary()`. When a state change occurs, it records the previous state, updates the current state, copies position/velo...
def update_state_change(self): if self.present_state == SLIDING_STATE: if self.is_roll(): self.previous_state = self.present_state self.present_state = ROLLING_STATE self.r0 = np.copy(self.r) heading_angle_changed = ((np.degrees( ...
def abs_exclude_z(vector): return np.linalg.norm(np.delete(vector, common.Z_AXIS)) def clockwise_vector(vector, heading_angle): heading_radians = np.radians(heading_angle) cos_data = np.cos(heading_radians) sin_data = np.sin(heading_radians) # if cos_data < common.POS_COSINE_EPSIL and cos_data > co...
This function calculates collision parameters for a ball's outgoing motion after impact. It computes the collision heading angle from velocity, adjusts linear and angular velocity vectors (considering spin effects), and initializes collision outcomes based on the ball's current state. If in sliding state, it computes r...
def update_outgoing_ball_collide(self, velo, angular_velo): # collide_heading_angle = ((((np.degrees(np.arctan2([velo.real[common.Y_AXIS]], # [velo.real[common.X_AXIS.real]])[0]) +360) % 360)) + 270) % 360 # collide_v = np.array([0, abs_exclude_z(velo), 0], dtype=float) # collide_w = (n...
def abs_exclude_z(vector): return np.linalg.norm(np.delete(vector, common.Z_AXIS)) def clockwise_vector(vector, heading_angle): heading_radians = np.radians(heading_angle) cos_data = np.cos(heading_radians) sin_data = np.sin(heading_radians) # if cos_data < common.POS_COSINE_EPSIL and cos_data > co...
This function calculates collision response vectors for a rail interaction by transforming incoming velocity and angular velocity into the rail's coordinate system. It computes heading angles, adjusts velocity components, and determines whether to apply collision effects based on the current sliding state. If sliding i...
def update_outgoing_rail_collide(self, velo, angular_velo): collide_heading_angle = ((np.degrees( np.arctan2([velo[common.Y_AXIS].real], [velo[common.X_AXIS].real])[0]) + 270) % 360) collide_v = np.array([0, abs_exclude_z(velo), 0], dtype=float) collide_w = np....
def prepare_eq_for_solve(self): if self.present_state == SLIDING_STATE: u_unit = self.u0_unit return (MotionFrict.slide_frict, u_unit[common.X_AXIS], u_unit[common.Y_AXIS], self.v0[common.Y_AXIS], self.r0[common.X_AXIS], self.r0[common.Y_AXIS], ...
This function calculates the earliest time of collision between a moving object and either rails or corners of a billiard table, considering friction and physics parameters. It iterates through potential collision points, solves polynomial equations (quadratic/cubic/quartic) for roots, and updates the minimum valid col...
def time_of_pock_rail_collision(self, t_smallest): t = t_smallest find_root = False friction, ux_unit, uy_unit, v, rx, ry, theta = self.prepare_eq_for_solve( ) sin_theta = np.sin(np.radians(theta)) cos_theta = np.cos(np.radians(theta)) ux_cos_minus_uy_sin = (ux_un...
def prepare_eq_for_solve_dynamic(self): if self.present_state == SLIDING_STATE: u_unit = cal_unit_vector(self.u) return (MotionFrict.slide_frict, u_unit[common.X_AXIS], u_unit[common.Y_AXIS], self.v[common.Y_AXIS], self.r[common.X_AXIS], self.r[com...
The main task of the code is to compute the time until two billiard balls collide by solving a quartic equation derived from their dynamic or static motion parameters. It accounts for friction, velocity, position, and orientation, checks collision validity, and returns the earliest collision time or a maximum timeout i...
def time_of_ball_collision(self, ball_2, t_smallest): t = t_smallest find_root = False dynamic_cal = True if (self.present_state == SPINNING_STATE) or ( self.present_state == STATIONARY_STATE): ball_t_min = ball_2.t dynamic_cal = False eli...
def cal_unit_vector(vector): magnitude = np.linalg.norm(vector) if magnitude > 0: return vector / magnitude else: return np.copy(vector) def prepare_incoming_ball_collide(self): if self.present_state == SLIDING_STATE: # return (np.concatenate((counter_clockwise_vector(np....
The code resolves a collision between two billiard balls by calculating the impulse based on their relative velocities, masses, and inertia. It updates their linear and angular velocities to simulate realistic physics, considering restitution and friction. The function returns True if a collision is processed, otherwis...
def update_ball_collide(self, other): collision_normal = self.r - other.r distance_square = collision_normal.dot(collision_normal) if distance_square <= BilliardBall.sum_r_square_epsilon: # Handle collision # Find penetration # no need because It's already perform colli...
def prepare_incoming_rail_collide(self): # if (self.present_state == SLIDING_STATE and self.allow_response_sliding): if self.present_state == SLIDING_STATE: # return (np.concatenate((counter_clockwise_vector(np.delete(self.v, common.Z_AXIS), self.heading_angle), # [0])), np.arra...
This function detects collisions between a billiard ball and table rails, calculates collision response, and updates velocities. It checks ball position against rail boundaries, determines collision side (left/right/top/bottom), computes collision point/normal, and applies impulse based on relative velocity and frictio...
def update_rail_collide(self): collision_index = None if ((self.r[common.X_AXIS] < table.BilliardTable.left_rail_r_epsil) and ((table.BilliardTable.rail_border_y_posit_upper[common.POSIT_LOWER] < self.r[common.Y_AXIS] < table.BilliardTable. rail_border_y_posit_upp...
def is_circle_line_segment_intersect(circle_center, start_line, end_line, r): line_vector = end_line - start_line relative_vector = circle_center - start_line line_vector_unit = cal_unit_vector(line_vector) project_relative_abs = np.dot(relative_vector, line_vector_unit) if project_relative_abs <= 0...
This function detects collisions between a billiard ball and pocket rails, calculates the collision normal and tangent vectors, computes the impulse based on relative velocity and physical properties, and updates the ball's linear and angular velocities post-collision using friction and restitution coefficients. It ret...
def update_pock_rail_collide(self): collision_index = None collision_point = None collision_point_adjust = None for line_index, pock_rail in enumerate( table.BilliardTable.actual_pock_rail_all): collision_point, collision_point_adjust = is_circle_line_segment_...
def get_deformability_matrix(self): data = pd.read_csv(f"{self.phys_obs_base_dir}/deformability/{self.phys_obs_csv}.csv") id_dict = {} for i, row in data.iterrows(): image_id_1 = int(row["annotation_id_0"]) image_id_2 = int(row["annotation_id_1"]) acro_id_1 ...
The main task of the code is to initialize a dataset for physical object interaction analysis. It loads material property matrices (deformability, mass, fragility), maps image/filename data to object IDs, filters valid object pairs, and prepares them for training/testing. The code structures physical object annotations...
def __init__(self, images_dir, physobs_base_dir="physobjects/annotations/crowdsourced", transform=None, train=True): self.materials_enum = {} self.images_dir = images_dir self.phys_obs_base_dir = physobs_base_dir self.phys_obs_csv = "train" if train else "test" self.tran...
def get_places(coords, type): # search requires location 'lat,long' and type loc_string = "{},{}".format(coords[0], coords[1]) query = { 'location': loc_string, 'type': type, 'radius': MAX_RADIUS, 'key': MAPS_API_KEY } # perform request response = requests.get(MA...
The code retrieves all restaurant locations for given coordinates by paginating through API results. It initializes an empty list, fetches the first page of restaurants, then loops to get and parse subsequent pages until all data is collected, finally returning the complete list of restaurant entries.
def get_restaurants(coords): restaurants = [] places, next_page = get_places(coords=coords, type='restaurant') parse_places(restaurants, places) while (next_page is not None): places, next_page = get_next_places_page(next_page) parse_places(restaurants, places) return restauran...
def get_combinations(json_files): # Load JSON data from each file and store them in a list json_data_list = [load_json_file(file_path) for file_path in json_files] # Use itertools.product to generate combinations combinations = list(product(*json_data_list)) return combinations def get_stat(df): ...
The code processes combinations of data from multiple JSON files, transforms them into a DataFrame, calculates statistics, sorts the results by archer attributes (health, defense, attack), identifies the optimal set, and optionally saves the output to a CSV file.
def main(output_file=None): json_files = [f'./rawData/{slot}.json' for slot in slots_global] combinations = get_combinations(json_files) if combinations: df = pd.DataFrame(combinations, columns = slots_global ) df = get_stat(df) df = get_set(df) df = get_cost(df) df ...
def parse_snake(self, snake_data): snake = Snake(snake_data['id']) for b in (snake_data['body'])[:-1]: snake.add_snakePart(SnakePart(b['x'], b['y'])) tail = SnakeTail(snake_data['body'][-1]['x'], snake_data['body'][-1]['y']) snake.add_snakePart(tail) ...
The main task of the code is to parse snake data from the game board, initialize snake objects, update the board with their positions, and mark cells that can be occupied by other snakes in the next move. It processes each snake's potential next moves, enabling the board to track available spaces for future actions.
def set_snakes(self): snake_datas = self.data['board']['snakes'] for snake_data in snake_datas: snake = self.parse_snake(snake_data) self.snakes.append(snake) self.update_board_with_snake(snake) for snake in self.snakes: for c in self.potential_n...
def number_of_free_cells(self, cell, direction): cells = self.cells_in_direction(cell, direction) count = 0 for c in cells: if not c.is_free(): return count else: count = count + 1 return count def is_blocked_up(self, cell): ...
The code checks if a cell is blocked in a specified direction by first verifying if there are no free cells in that direction. If so, it returns True. Otherwise, it delegates the check to direction-specific methods (e.g., is_blocked_up, is_blocked_right) to determine blocking status.
def is_blocked(self, cell, direction): if self.number_of_free_cells(cell, direction) == 0: return True if direction == Direction.up: return self.is_blocked_up(cell) elif direction == Direction.right: return self.is_blocked_right(cell) elif dir...
def takephoto(): #This creates two variables, the first one 'date' that records the exact date and time when the photo was taken and the second one 'imagePath' that records where the image should be stored to date = datetime.now().strftime("%Y_%m_%d-%I-%M-%S_%p") imagePath = r'/home/pi/photoFolder/image1.jp...
The code's main task is to detect and analyze plant positions in a tray using image processing. It captures a photo, isolates green pixels (representing plants), identifies plant locations via blob detection, determines tray size, compares detected positions with expected coordinates, and sends the status of plant posi...
def startProgram(): #This function takes no input and returns the photo taken with the camera + the datetime of when the photo was taken image, date = takephoto() #This function goes over the image, and creates a mask with only the pixels in the colour range showing, it returns the image with the islolated ...
def circle_from1(A, B): # Set the center to be the midpoint of A and B C = Point((A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 ) # Set the radius to be half the distance AB return Circle(C, dist(A, B) / 2.0 ) def is_valid_circle(c, P): # Iterating through all the points # to check whether the points...
This function computes the minimum enclosing circle (MEC) for up to three points. It returns a circle with radius 0 for a single point, a circle through two points for two points, and checks if any pair of points defines a circle enclosing all three points. If not, it constructs the MEC using all three points.
def min_circle_trivial(P): assert(len(P) <= 3) if not P : return Circle() elif (len(P) == 1) : return Circle(P[0], 0) elif (len(P) == 2) : return circle_from1(P[0], P[1]) # To check if MEC can be determined # by 2 points only for i in range(3): ...
def min_circle_trivial(P): assert(len(P) <= 3) if not P : return Circle() elif (len(P) == 1) : return Circle(P[0], 0) elif (len(P) == 2) : return circle_from1(P[0], P[1]) # To check if MEC can be determined # by 2 points only for i in range(3): ...
The code implements a recursive helper function for Welzl's algorithm to compute the **minimum enclosing circle (MEC)** of a set of 2D points. It randomly selects points, checks if they lie inside the current MEC, and recursively constructs the MEC by either including the point in the boundary set or expanding the circ...
def welzl_helper(P, R, n): # Base case when all points processed or |R| = 3 if (n == 0 or len(R) == 3) : return min_circle_trivial(R) # Pick a random point randomly idx = randint(0,n-1) p = P[idx] # Put the picked point at the end of P # since it's more efficient than #...
def compute_mean_mles(train_data, train_labels): ''' Compute the mean estimate for each digit class Should return a numpy array of size (10,64) The ith row will correspond to the mean estimate for digit class i ''' means = np.zeros((10, 64)) # Compute means for i in range(10): a...
The code implements a Gaussian classifier by computing class-specific means and covariances from training data. It evaluates model performance using conditional likelihood and classification accuracy on training/test sets. Finally, it visualizes the principal eigenvectors of each class's covariance matrix as 8x8 images...
def main(): train_data, train_labels, test_data, test_labels = data.load_all_data('data') # Fit the model means = compute_mean_mles(train_data, train_labels) covariances = compute_sigma_mles(train_data, train_labels) # Evaluation # a) part acc_train = avg_conditional_likelihood(train_data, ...
def steer(self, nearest_node, sampled_node, expand_dis=float('inf')): """ This method should return a point in the viable set such that it is closer to the nearest_node than sampled_point is. Args: nearest_node (TreeNode): nearest node on the tree to the sampled point ...
This method rewires the tree by checking if each node in the given neighborhood can be reached more cheaply from the new node. If so, it updates the node's position, cost, path, and parent. It avoids collisions and propagates cost changes to leaves for optimal path updates.
def rewire(self, new_node, neighborhood): """ This method should check for each node in neighborhood, if it is cheaper to arrive to them from new_node. If so, re-assign the parent of the nodes in neighborhood to new_node Args: new_node (TreeNode): current node ...
def sample(self): """ This method should randomly sample the free space, and returns a viable point Args: Returns: node (TreeNode): a tuple representing the sampled point """ if random.randint(0, 100) > self.goal_sample_rate: x = random.uniform(s...
This code implements the RRT (Rapidly Exploring Random Tree) algorithm to find a collision-free path from a start point to a goal. It iteratively samples random nodes, connects them to the nearest tree nodes, checks for collisions, and updates the tree by rewiring paths for optimality. The loop continues until the goal...
def planning(self): """ This method is the main RRT loop Args: Returns: path (list of [x, y]): final course """ self.tree = [self.start] for i in range(self.max_iter): rnd_node = self.sample() nearest_node = self.nearest(self....
def rows(self): return len(self.board) def cols(self): return len(self.board[0]) def play(self, row, col, piece): self.board[row][col] = piece def won(self, piece): for rowWin in range(self.rows()): # Checks every row if self.winInRow(rowWin, piece) == True: ...
The main task of the code is to find a winning move for the given `piece` by temporarily placing it on every empty spot of the board. If placing the piece in a spot results in a win, it returns that spot's coordinates as a hint. Otherwise, it removes the piece and returns (-1, -1) to indicate no valid hint.
def hint(self, piece): for rowHint in range(self.rows()): # Checks every row for columnHint in range(self.cols()): # Checks every column # Checks if a spot is empty and then plays a piece there. If, from that piece being played, the user wins, it remo...
def update_list_of_voices(self): self.mimic_native_voices = self.list_native_voices() self.mimic_dir_voices = self.list_dir_voices() self.all_mimic_voices = self.mimic_native_voices + self.mimic_dir_voices def set_voice(self, voice): if self.is_native_voice(voice): self.voice = voice else: self.voice =...
The code initializes a voice synthesis system by setting the directory for mimic voices, updating the list of available voices, selecting a default voice ('cmu_us_clb.flitevox'), and configuring the speech speed to 1.
def __init__(self): self.mimic_voices_dir = '../data/mimic_voices/' self.update_list_of_voices() self.set_voice('cmu_us_clb.flitevox') self.set_speed(1)
def new_glass(self): # get weight of the glass print("getting weight of the glass...") weight_of_glass = self.get_stable_weight(1.5) # light signalization print("started pouring fluid...") self.pump.high() start_time = now() print("waiting for input to ...
This function handles button press interactions to control a pump and glass creation. It checks for long button holds to trigger a full load, detects double-clicks to create a new glass, and uses weight sensors to fill glasses. If no activity is detected, it deactivates the pump. The function updates system messages an...
def new_round(self): # button hold / full load if self.button.value() and self.previous_button: if (self.now - self.time_of_first_interaction) > self.full_load_delay: self.pump.high() self.action_of_this_round == "full_load" self.message = "ac...
def _detect_hover(self) -> Button | Die | None: """ Sets and renders the hover text. Returns the object the cursor is currently hovering over, if any. """ hover_object = None self.hover_text = self.instruction_text # Check for hover over dice if they are on the ...
This method handles left-click interactions in a game, detecting hovered objects (Button or Die) and executing actions. It processes button clicks for "Pass," "Roll," or "Reroll," and manages die interactions based on activation states, modifying die faces, blocking, and game instructions. It updates game state by reso...
def _on_left_click(self) -> None: hover_object = self._detect_hover() # Handle Button clicked if isinstance(hover_object, Button): button = hover_object if button.text == "Pass": self._next_player_turn() elif button.text == "Roll": ...
def _detect_hover(self) -> Button | Die | None: """ Sets and renders the hover text. Returns the object the cursor is currently hovering over, if any. """ hover_object = None self.hover_text = self.instruction_text # Check for hover over dice if they are on the ...
The code runs the main game loop, handling events like quitting, mouse motion, and clicks to update game state, maintaining 60 FPS, rendering the display, and exiting properly.
def run(self) -> None: """Runs main Game loop.""" self.running = True while self.running: self.clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame....
def init(self, screen): self.recvMsgQueue = Queue(100) self.sendMsgQueue = Queue(100) self.gameServer = None self.serverRecvThread = None self.serverSendThread = None self.backgroundImg = pygame.transform.scale(pygame.image.load('images/background.jpg').convert(),(self.he...
This code implements a game loop using Pygame, handling user input for ship placement and movement, event processing (mouse clicks, keyboard input), game state updates, and rendering. It manages dragging ships, validating positions, highlighting areas, and maintaining the game window. The loop runs at a fixed FPS, proc...
def run(self): clock = pygame.time.Clock() screen = pygame.display.set_mode((self.width, self.height)) # set the title of the window pygame.display.set_caption(self.title) # stores all the keys currently being held down self._keys = dict() # call game-specific ...
def debug(x): global debugfile if debug_test_pp: print('test_pretty_print debug: ' + x) debugfile.write((x + '\n').encode('utf-8')) def ezsearch(pattern, str): x = re.search(pattern,str,re.DOTALL|re.MULTILINE) if x and len(x.groups())>0: return x.group(1).strip() return '' def read_sysin...
This code generates an HTML test report for OpenSCAD by parsing command-line arguments, reading test logs, and processing results. It saves the report locally and optionally uploads it via SCP if specified. The report includes system info, test outcomes, and build details, with debugging and dry-run support.
def main(): global builddir, debug_test_pp global maxretry, dry, include_passed project_name = 'OpenSCAD' if bool(os.getenv("TEST_GENERATE")): sys.exit(0) # --- Command Line Parsing --- if '--debug' in ' '.join(sys.argv): debug_test_pp = True maxretry = 10 if '--inclu...
def read_map(): file1 = open("map.txt") MAP = np.zeros((9,9)) Cor = dict() row=0 col=0 iin = 0 for index,i in enumerate(file1): if i=='\n': continue i = i.strip().split(' ') #print(index) if len(i)==0 : continue if inde...
The code automates playing Candy Crush by launching the game, detecting the game board state, searching for valid moves, and executing mouse clicks to perform moves. It continuously monitors the game map, presses F2 periodically, and uses keyboard/mouse input to navigate and interact with the game, aiming to automate g...
def main(): PrevMAP = None subprocess.Popen(["CandyCrush.exe"]) u_input = raw_input("Start? (y/n)\n") if u_input == 'y' or u_input == 'Y': print("Go") else: exit(1) while(1): #u_input = raw_input("next move? (y/n)\n") #print(u_input) time.sleep(2) ...
def value_max_min_array(all_info): vmin = 100000 vmax = 0 for info in all_info: for info_iter in info: vmin = min(vmin, np.min(info_iter["Value"])) vmax = max(vmax, np.max(info_iter["Value"])) return vmin, vmax def lake_plot_policy_and_value( policy, values_in, ...
This function visualizes Value Iteration results for varying epsilon thresholds on a FrozenLake map. It generates policy/value grids and reward/error curves for each epsilon, using specified map settings, slipperiness, and gamma. Plots are saved with titles indicating parameters like gamma, map name, and epsilon ranges...
def plot_e_stop_values(estop_values, suptitle, gamma, map_name, is_slippery, show_policy): map_used = maps[map_name] P, R = example.openai("FrozenLake-v1", desc=map_used, is_slippery=is_slippery) title_settings = f"{map_name} Map, Gamma:{gamma}, {'Is' if is_slippery else 'Not'} Slippery" estop_info = ...
def preprocess_input_data(input_file): input_data = pd.read_csv("data/ALL/"+input_file, sep="\t", header=0, warn_bad_lines=True, error_bad_lines=False, quoting=csv.QUOTE_NONE, encoding='utf-8') comparable_col_names = get_variable_names(input_data.columns.values, comparable=True, paired=False) input_data = ad...
The code processes multiple corpora by computing statistical results (descriptions, effects, and comparisons) for each input file, concatenating results across corpora, comparing language features, and saving aggregated output to specified directories. It handles preprocessing, feature analysis, and cross-corpus compar...
def get_statistics_for_all_corpora(result_files, type_value=""): list_lang_input = list() corpus_names = list() type_value_dir = "" if type_value: type_value_dir = type_value+"/" if not os.path.exists("data/results/"+type_value): os.makedirs("data/results/"+type_value) for f, input_file in enumerate(result_...
def stack_corpora(results_files): stacked_data, comparable_col_names, paired_col_names, corpus_name = "", "", "", "" for f, input_file in enumerate(results_files): corpus_name = input_file.split("/")[-1][:-4] input_data, comparable_col_names, paired_col_names = preprocess_input_data(input_file) if f == 0: st...
The code processes multiple corpora to compute and compare statistical features across paired and comparable columns, aggregating results into concatenated data frames. It identifies significant language differences using p-values, generates descriptive statistics, and saves outputs for cross-type analysis (e.g., domai...
def get_paired_statistics_for_crossdata(file_dict, cross_type="domain"): list_lang_input, corpus_names = list(), list() for f, corpus_name in enumerate(file_dict.keys()): print(corpus_name) stacked_data, comparable_col_names, paired_col_names, corpus_name = stack_corpora(file_dict[corpus_name]) stacked_data, co...
def get_source_id_dict(path_data): list_articles = {} for article in glob.glob(path_data + "/*.txt"): sep_article = article.split('/')[-1][:-7].split('_') list_articles.setdefault('_'.join(sep_article[0:-1]), set()).add(sep_article[-1]) # print(list_articles) return list_articles def get_ids(lang, corpus, artic...
This function aligns complex and simple sentences from German texts using alignment files, processes tokenized data, and prepares structured outputs with identifiers and features. It reads alignment pairs, joins corresponding sentences, generates unique identifiers, and optionally extracts linguistic features using spa...
def align_german_klaper(path_data, spacy_model, conllu_path, include_text=True, use_conllu=False, sep="\t", add_features=False): path_alignments = path_data + "alignments/" path_data = path_data + "tokenized/" lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() list_articles = get_source_id_dict(...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
This function aligns sentences from a corpus with turker annotations, generating identifiers and alignment data. It processes text files, extracts complex/simple sentence pairs, and optionally adds linguistic features using spaCy. Aligned results and CONLLU-formatted text are saved to the specified output path with cus...
def align_turk_corpus_cased(path_data, spacy_model, output_path, sep="\t", use_conllu=False, include_text=True, add_features=False): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() for file in os.listdir(path_data...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
This function aligns complex and simple sentences from the PACCSS corpus, extracts linguistic features using spaCy, and saves the aligned data in CONLLU format. It processes text files, generates alignment identifiers, and stores results with unique identifiers for further analysis.
def align_paccss_corpus(path_data, spacy_model, conllu_path, sep="\t", use_conllu=False, include_text=True, add_features=True): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() article_id = "x" complex_level, simpl...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
The main task of this code is to align complex and simple sentences in a Czech corpus using annotations and source sentences, generate alignment data with linguistic features via spaCy, and save results in CONLLU format. It processes TSV files, maps sentence pairs, extracts simplifications, and outputs aligned structur...
def align_czech_corpus(path_data, spacy_model, conllu_path, sep="\t", include_text=True, use_conllu=False, add_features=True): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() # article_id = "x" complex_level, simp...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
The main task of the code is to align sentences between complex and simplified versions of texts in a corpus (e.g., News-ELA) using a TF-IDF model and MASSAligner. It processes files at specified complexity levels (0-5), aligns paragraphs and sentences, extracts linguistic features with spaCy, and saves aligned data, u...
def align_newsela_corpus(path_data, spacy_model, conllu_path, sep="\t", complex_level="0", simple_level="5", use_conllu=False, include_text=True, add_features=False): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() ...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
This function aligns sentences from the Newsela 2015 corpus by parsing aligned text files, extracting linguistic features using a Spacy model, and generating CONLLU-formatted outputs. It processes article identifiers, complexity levels, and sentence pairs, appending aligned values and unique identifiers. The aligned da...
def align_newsela_15_corpus(path_data, spacy_model, conllu_path, sep="\t", include_text=True, use_conllu=False, add_features=False): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() with open(path_data + "newsela_ar...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
The function aligns complex and simple sentences from a dataset, extracting linguistic features using spaCy, and saves aligned data in CONLLU format. It processes TSV files, generates unique identifiers, and structures outputs for linguistic analysis, supporting customizable feature inclusion and format options.
def align_qats(path_data, spacy_model, conllu_path, include_text=True, add_features=True, use_conllu=False, use_assessment=False, sep="\t"): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() complex_level, simple_lev...
def get_ids(lang, corpus, article_id, par_id_complex, par_id_simple, sent_id_complex, sent_id_simple, complex_level, simple_level): alignment_id = lang + "-" + corpus + "-" + article_id + "-" + par_id_complex+"_"+par_id_simple + "-" + sent_id_complex + "_" + sent_id_simple + "-" + complex_level + "_" + simple_level c...
The function aligns sentences between complex and simple versions of texts (e.g., "wiki" vs. "viki") using TFIDF similarity and MASSAligner. It extracts aligned pairs, generates unique identifiers, adds linguistic features via spaCy, and saves results in CONLLU format. The task involves processing up to 500 files, alig...
def align_clear(path_data, spacy_model, conllu_path, include_text=True, add_features=True, sep="\t", use_conllu=False): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() complex_level, simple_level = "wiki", "viki" ...
def align_newsela_corpus(path_data, spacy_model, conllu_path, sep="\t", complex_level="0", simple_level="5", use_conllu=False, include_text=True, add_features=False): lang, corpus = path_data.split('/')[1].split("-") lang = lang.lower() aligned_sentences, list_unique_identifier, conllu_text = list(), list(), list() ...
The code processes text corpora (e.g., Newsela, Costra, Paccss) by parsing command-line arguments for input paths, output paths, and NLP models (spaCy/Stanza). It loads the specified model, identifies the dataset type from the input path, and applies corresponding alignment functions (e.g., `align_newsela_corpus`, `ali...
def main(argv): path_data, conllu_path, model_name, process_stanza = "", "", "", "" try: opts, args = getopt.getopt(argv, "f:m:o:", ["filespath=", "outputpath=", "spacymodel=", "stanza="]) except getopt.GetoptError: print('preprocess_newsela.py -f <filespath> -o <outputpath> -m <spacymodel>') sys.exit(2) for ...
def get_statistics_for_all_corpora(result_files, type_value=""): list_lang_input = list() corpus_names = list() type_value_dir = "" if type_value: type_value_dir = type_value+"/" if not os.path.exists("data/results/"+type_value): os.makedirs("data/results/"+type_value) for f, input_file in enumerate(result_...
The main task of the code is to perform statistical analysis on multiple corpora datasets, grouped by domain (news, wiki, web) and language (EN, DE, CS, IT). It processes all files in "data/ALL", generates statistics for each group, compares cross-domain and cross-lingual data, and saves results in "data/results". The ...
def main(argv): result_files = sorted(list(os.listdir("data/ALL"))) # result_files = [file for file in result_files if not "en-Newsela_2016" in file and not "es-Newsela" in file] print(result_files) if not os.path.exists("data/results"): os.mkdir("data/results") # get_feature_dict(result_files) print("do statis...
def is_terminal_node(self): return self.check_if_player_has_won(self.CPU) | self.check_if_player_has_won(self.YOU) | len(self.get_possible_moves()) == 0 def check_if_player_has_won(self, player_id): """ checks if player with player_id has won Inputs ---------- player_id ...
This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a game state. It recursively evaluates all possible moves, alternating between maximizing (CPU) and minimizing (player) strategies, and returns the best move along with its heuristic value. Terminal states are checke...
def minimax(self, depth, isMaximizing): if self.is_terminal_node(): if self.check_if_player_has_won(self.CPU): return (None, -100000000) elif self.check_if_player_has_won(self.YOU): return (None, 100000000) else: return (None, 0...
def is_terminal_node(self): return self.check_if_player_has_won(self.CPU) | self.check_if_player_has_won(self.YOU) | len(self.get_possible_moves()) == 0 def check_if_player_has_won(self, player_id): """ checks if player with player_id has won Inputs ---------- player_id ...
This function implements the Alpha-Beta pruning algorithm to determine the optimal move in a two-player game (like Connect Four). It recursively evaluates possible moves, alternating between maximizing (CPU) and minimizing (player) states. Terminal nodes return heuristic values based on win/loss conditions, while non-t...
def alphabeta(self, depth, alpha, beta, isMaximizing): if self.is_terminal_node(): if self.check_if_player_has_won(self.CPU): return (None, -math.inf) elif self.check_if_player_has_won(self.YOU): return (None, math.inf) else: re...
def __get_random_starter(self): players = [self.YOU, self.CPU] return players[int(random() * len(players))] def __init_board(self): self.board = [] for i in range(self.rows): self.board.append([self.EMPTY] * self.columns) def __print_board(self): if (self.silent): ret...
The main task of the code is to execute a game where the player and CPU alternate turns, handling input validation, updating the game state, checking for a win or draw, and returning the result as 1 (player win), -1 (CPU win), or 0 (draw). The game starts with a randomly chosen or specified player, processes moves, and...
def run(self, starter=None): """ runs the game! Inputs ---------- starter : either -1,1 or None. -1 if cpu starts the game, 1 if you start the game. None if you want the starter to be assigned randomly Output ---------- (int) either 1,0,-1. ...
def get_gradient(MC_err, theta, W): ''' Inputs: 1) gc activities 2) net mc activity, r_m 3) MC-GC network Function: gradient of the loss function w.r.t gc activations ''' grad = - np.matmul(W.T, MC_err) + theta return grad def get_loss(GC_act, odor_input, theta, W): ''' ...
The code performs gradient descent optimization to adjust the GC_act variable over 1000 iterations, minimizing the discrepancy between the odor input and the model's output (W·GC_act). It calculates the error, computes the gradient, normalizes it, and updates GC_act via a line search PGD method to reduce the loss funct...
def sniff_cycle(odor_input, GC_act, theta, W): for _ in range(1000): MC_err = odor_input - np.matmul(W, GC_act) grad = get_gradient(MC_err, theta, W) # does normalizing it make it easier to serach t? norm_grad = grad/sc.linalg.norm(grad,2) # can be swapped with oth...
def remove_overlap(self): ''' If matches overlap keep only the best ''' logging.info('Removing overlapping matches') # Sort by alignment quality self.df = self.df.sort_values(['Acc', 'Score', 'Coverage'], ascending=False) overlap_lst = [] for i in set(...
(The code processes BLAST results to identify and classify CRISPR elements into singleton repeats (SRUs) and arrays. It loads data, filters by identity/coverage, removes overlapping matches, clusters hits, and separates SRUs (single clusters) from arrays (multiple clusters). It then processes SRUs with flanking checks,...
def run(self): ''' Load the BLAST table and run the different clustering steps ''' # Load blast table and add lengths self.df = pd.read_csv(self.master.out+'blast.tab', sep='\t', header=None, names=('Repeat', 'Acc', 'Identity', 'Alignment', 'Mismatches', 'Gaps', ...
def resample(self): # sample control noise vectors self.noise = np.random.multivariate_normal(mean=self.noise_mu, cov=self.noise_sigma, size=(self.K, self.N)) def compute_sample_costs(self): # calculate the total costs corresponding to sampled trajectories for k in range(self.K): ...
This method performs a full iteration of a control process by updating the control vector based on the current state and input, computing associated costs, and returning the computed control vector while preparing for the next iteration through a circular shift.
def step(self,x0,u_new=None): # do a full iteration of this process and return control vector self.cost_total[:] = 0 self.x0 = np.copy(x0) self.resample() if u_new is None: self.compute_sample_costs() else: self.u_vec = np.copy(u_new) s...
def send_mt_messages(self): smses = get_mt_messages_to_send(limit=100, backend=self.backend) submit_sm_resps = [] for sms in smses: params = {**self.submit_sm_params, **sms["params"]} pdus = self.split_and_send_message(sms["short_message"], **params) # Create ...
This code implements a listener loop for handling SMPP protocol communication. It continuously monitors a socket and PostgreSQL connection for incoming data, sends up to 100 messages on startup, handles timeouts by sending enquire_link PDUs, processes received data, and gracefully exits on signal receipt while maintain...
def listen(self, ignore_error_codes=None, auto_send_enquire_link=True): self.logger.info("Entering main listen loop") # Look for and send up to 100 messages on start up self.send_mt_messages() while True: # When either main socket has data or _pg_conn has data, select.select ...
def _check_keydown_events(self,event): """Responds to the pressing the keys...""" if event.key == pygame.K_RIGHT: self.ship.right_movement_flag = True elif event.key == pygame.K_LEFT: self.ship.left_movement_flag = True elif event.key == pyg...
This function processes user input events in a Pygame game. It checks for quit requests, key presses/releases, and mouse clicks. When the window is closed, it exits the game. Key events trigger methods to handle input, while mouse clicks check if the play button is pressed, updating game state accordingly.
def _check_events(self): """for responding the events.""" for event in pygame.event.get(): """Analizing the events from the user.""" # When player wants to terminate the game------- if event.type == pygame.QUIT: sys.exit() ...
def _check_fleet_edge(self): '''Checking hitting of alien with edge...''' # .sprites() for making it list maybe.... for alien in self.aliens.sprites(): if alien.check_edge(): self._change_direction() break def _check_alien_in_bottom(self): """C...
This method updates the alien fleet's position by checking edges, updating their movement, detecting if any alien reaches the bottom (triggering game-ending conditions), and checking for collisions between the player's ship and aliens. If a collision occurs, it initiates the ship-hit response, such as reducing lives or...
def _update_alien(self): """For updating the position of the alien fleet.""" self._check_fleet_edge() self.aliens.update() # When alien reaches the bottom.... self._check_alien_in_bottom() # When the ship hit the alien.... if pygame.sprite.spritecollideany(self....
def _check_events(self): """for responding the events.""" for event in pygame.event.get(): """Analizing the events from the user.""" # When player wants to terminate the game------- if event.type == pygame.QUIT: sys.exit() ...
The code runs the game loop, continuously checking for events, updating the ship, bullets, and aliens when the game is active, and rendering the screen to maintain smooth gameplay and responsiveness.
def run_game(self): """For running the game.""" while 1: """For the smooth movement of the screen.""" """This loop keeps running even if u don't do anything""" self._check_events() # if block execute only when game is active.... ...
def check(self) -> dict: # checking if # we have registered the domain already # if the domain is available # if the relevant domain config has been changed self.nameservers = self._build_nameservers(ns_list=self.module.params['nameservers']) # get existing domain...
The code validates domain registration parameters by checking price limits, premium status, and availability. If valid, it registers or updates the domain, adding errors for exceeding max price, disallowed premium domains, or unavailability. It returns a result dict indicating success/failure and any errors.
def set(self) -> dict: # run 'check-mode' tasks to find out if the state has changed self.check() # run action if check succeeded and action is required if not self.result['failed'] and self.result['changed']: if self.module.params['max_price'] is not None and self.result['p...
def parse_user_input(user_input): """ parses user input and returns the response from the model """ prompt = parse_input(user_input) print(f"prompt: {prompt}") response = get_response(prompt) if response.ok: print(response.json()) return json.loads(response.json()["choices"][0]["mes...
The main task of the code is to determine the type of task from a user prompt (e.g., location prediction/recommendation) and route it to the appropriate function. It parses the input, checks the task name, and returns results from specialized functions or handles undefined tasks via a generic response.
def ask_GPT(prompt): parsed_prompt = parse_user_input(prompt) print(f"{parsed_prompt=}") task_name = parsed_prompt.get("task") print(task_name) if task_name == "location_prediction": return task_name, get_location_opinion(parsed_prompt) elif task_name == "location_recommendation": ...
def fast_tut(): r = RES["fast_tutorial.py"] normal = bilby.gw.result.CBCResult.from_json(r[0]) multi = bilby.gw.result.CBCResult.from_json(r[1]) samples_list = [normal.posterior, multi.posterior] param = ['mass_ratio', 'chirp_mass', 'luminosity_distance', 'theta_jn'] + [ "log_likelihood"] ...
The main task of the code is to sequentially execute multiple functions—fast_tut(), bns(), bbh(), gw150914(), multid(), and oned_gauss()—likely performing distinct operations such as simulations, data processing, or model evaluations, though their specific purposes remain undefined by their names.
def main(): fast_tut() bns() bbh() gw150914() multid() oned_gauss()
def createFolder(foldername): try: #Create Directory os.mkdir(foldername) print("Directory " , foldername , "created! ") except FileExistsError: print("Directory" , foldername , "already exists!") def findPasswordLine(inputSource): print('--locals-{}--'.format(locals())) ...
The main task of the code is to process Excel (.xlsx) files from an input directory by copying them to a temporary directory, extracting their internal XML worksheets, modifying the XML content (likely related to password protection), re-packaging the modified XML into new Excel files, and saving them to an export dire...
def main(rimport,rtemp,rexport): print(locals()) listOfFile = os.listdir(rimport) dst_exp_dir = None for file in listOfFile: # Copy file to work with if '.xlsx' not in file: continue src_dir = os.path.join(rimport, file) dst_temp_dir = os.path.join(rtemp, f'te...
def reppydirs(pyimport, pyexport): # Get current workdir global reppytemp, workindir, reppyimport, reppyexport workindir = os.getcwd() # create Required Folders reppyimport = os.path.join(workindir, pyimport) reppytemp = os.path.join(workindir, 'temp') reppyexport = os.path.join(workindir, p...
The function `removePassword` attempts to process files by calling `reppydirs` and then executes the `main` function with specific parameters. If successful, it returns the `main` result and an empty exception. If an error occurs, it captures the exception, prints the error message, cleans up temporary files, and retur...
def removePassword(pyimport, pyexport): exception = '' try: reppydirs(pyimport, pyexport) return main(reppyimport, reppytemp, reppyexport), exception except Exception as ex: message = 'Exception raised: {}'.format(ex) traceback.print_exc() cleanupTemp(reppytemp) ...
def remake_main(path:str,variables:str,function_name:str): variables =ast.literal_eval(variables) main_body = main_skeleton() main_body.add_variables(function_name,variables) main_body.change_function(function_name) main_body.add_includes(['#include "'+function_name+'.cu"']) main_body.save_main(...
The main task of the code is to benchmark CUDA kernel execution times across multiple configurations. It reads kernel paths from a CSV, processes each by generating/test-running CUDA code, records runtime metrics, and aggregates results into a CSV file. The script tracks progress, handles existing results, and estimate...
def main(): device_id=int(sys.argv[1]) timeout=str(sys.argv[2]) matrix_len=str(sys.argv[3]) flags=str(sys.argv[4]) data_path = "./data/" results_path = "./results/" runs = pd.read_csv(data_path+'kernel_list.csv') runtimes_path = results_path+"runtimes_temp_"+str(device_id)+".csv" run...
def getEndTile(self, side: Orientation) -> Tile: """Return the leftmost or rightmost value in the snake dict. Args: side (Orientation): Which end of the snake to return its value (Tile). Returns: Tile: The Tile contained within the leftmost or rightmost item in the snak...
This method adds a tile to the left or right end of a snake, ensuring compatibility by rotating the tile to match adjacent pips. It checks validity, handles exceptions, updates the snake's tile dictionary, and maintains order by sorting the dictionary after insertion.
def addTile(self, tile: Tile, side: Orientation): """Add a tile to the left or right side of the snake. Args: tile (Tile): The Tile instance to add to the snake. side (Orientation): The side of the snake to add to. Left or right. """ assert side in [Orie...
def getSubPhase(): time_activated = GROWTH_PLAN['Item']['TimeActivated'] current_time = datetime.utcnow().timestamp() current_time = str(current_time) needed_day = float(current_time) - float(time_activated) needed_day = int(needed_day / 86400) phases = GROWTH_PLAN['Item']['activeGrowthPlan']['p...
The function `applyGrowthPlan` checks if a growth phase is initiated, determines the current sub-phase, updates the active sub-phase if it differs, and applies environmental handling (soil humidity, UV, temperature) for the current sub-phase. It logs errors if sub-phase data is missing and informs when a new phase star...
def applyGrowthPlan(): if measurements["isInitiated"]: subPhase = getSubPhase() if(subPhase == None): logger.error("Failed To read Subphase values. Skipping check.") return if(activeSubPhase["subPhase"]["name"] != subPhase["name"]): activeSubPhase["subPhas...
def plurality(self, sentences): """ Calculates the most popular goal value :param sentences: :return: """ p = AttributeCalculator.get_max_key(self.vals[self.goal], key=lambda x: self.sentences_same_attribute_value(self.goal, x, ...
This function trains a Decision Tree by recursively splitting data based on the attribute with the highest information gain. It creates nodes and subtrees until stopping conditions are met: if no sentences remain, it returns the majority class of parent sentences; if no attributes remain, it returns the majority class ...
def train_dt(self, sentences, attributes, tree_depth, parent_sentences=()): """ Training algorithm for Decision Tree :param sentences: :param attributes: :param tree_depth: :param parent_sentences: :return: """ if len(sentences) <= 0: r...
def read_cache(cache_path: Path) -> Union[dict, list]: return json.loads(cache_path.read_text(encoding="utf-8")) def get_leaderboards( quick: bool = False, ) -> dict[LeaderboardKey, list[LeaderboardPlayer]]: leaderboards = {} i = 0 logger.info("Scraping leaderboards...") out = [] for key in ...
The code fetches PUBG leaderboards, summarizes player ranks, caches results if enabled, and writes data to Redis. It uses a cache directory for storage, skips fetching if cache exists (unless 'quick' is True), and converts structured data to JSON before Redis storage.
def main( cache_dir: Optional[Path], use_cache: bool, quick: bool, ) -> None: """Fetch and summarize PUBG leadersboards and write them to Redis""" cache_dir = Path(cache_dir) cache_dir.mkdir(parents=True, exist_ok=True) leaderboards_cache = cache_dir / "leaderboards.json" if not quick an...
def read_entropy(L,T,t_scr,g,theta,BC,root_direc): file_dir = get_filename(L,T,t_scr=t_scr,p=theta,g=g,BC=BC,root_direc=root_direc) file_dir = file_dir+'/T='+str(T)+'_tscr='+str(t_scr)+'_p='+str(theta)+'_BC='+BC+'/indiviudal_files/' entropy_list = [] for filename in os.listdir(file_dir): with op...
The code analyzes and visualizes the time evolution of subsystem entropy $ S_A(t) $ for varying system sizes $ L $, computes the decay rate of the entropy slope, and saves plots showing $ S_A(t) $ vs. $ t/L $ and the decay rate vs. $ L $. It processes entropy data, fits logarithmic trends, and generates log-scaled figu...
def save_S_vs_t(g,theta,L_list,BC,root_direc,A=0,depth=4,scr_depth=1): pl.figure(1) slope = [] for L in L_list: T = int(depth*L) t_scr = int(scr_depth*L) entropy = read_entropy(L,T,t_scr,theta,BC=BC,root_direc=root_direc) ydata = np.average(entropy[:,:,A],axis=0) err ...
def format2c(value) -> str: if isinstance(value, Expression): return expr.expr2str(value) elif isinstance(value, Token): return value.token elif isinstance(value, Array): return array2c(value) elif isinstance(value, IndexedValue): return indexed2c(value) elif isinstan...
The code generates C code from a structured list of actions, handling variable declarations, function calls, mathematical operations, conditional statements, loops, and functions. It formats variables, processes arrays, and constructs code blocks for each action type. If `wrap=True`, it wraps the generated code in a `m...
def codegen(actions: list[Action], wrap = True) -> str: code = "" funccode = "" variables = [] idx = 0 while idx < len(actions): el = actions[idx] # element need = el.args if el.type == ActionType.ASSIGNATION: vvalue = need.value vvalue = format2c(...
def _WriteXmlTag(self, tag): if xml: if tag[1] == '/': self.xmlIndent -= 1 self.xmlOutputFile.Write(' ' * self.xmlIndent) self.xmlOutputFile.Write(tag) if '/' not in tag: self.xmlIndent += 1 def _ExpectKeyword(self, keywords): ...
This code compiles class variable declarations ('static' or 'field') by parsing type, variable names, and scope, generating XML tags while defining symbols in the symbol table. It handles multiple variables separated by commas, tracks tokenizer position, and ensures proper syntax with semicolons.
def _CompileClassVarDec(self): """ Compiles <class-var-dec> := ('static' | 'field') <type> <var-name> (',' <var-name>)* ';' ENTRY: Tokenizer positioned on the initial keyword. EXIT: Tokenizer positioned after final ';'. """ self._WriteXmlTag('<classVarDec>\n...
def _WriteXmlTag(self, tag): if xml: if tag[1] == '/': self.xmlIndent -= 1 self.xmlOutputFile.Write(' ' * self.xmlIndent) self.xmlOutputFile.Write(tag) if '/' not in tag: self.xmlIndent += 1 def _MatchSymbol(self, symbols): ...
The main task of the code is to compile a parameter list by parsing type-variable pairs, adding each parameter to the symbol table with kind SYMK_ARG, and generating XML output. It processes parameters separated by commas, stops at a closing parenthesis, and writes the corresponding XML tags for the parameter list.
def _CompileParameterList(self): """ Compiles <parameter-list> := ( <type> <var-name> (',' <type> <var-name>)* )? ENTRY: Tokenizer positioned on the initial keyword. EXIT: Tokenizer positioned after <subroutine-body>. """ self._WriteXmlTag('<parameterList>\n...
def _WriteXmlTag(self, tag): if xml: if tag[1] == '/': self.xmlIndent -= 1 self.xmlOutputFile.Write(' ' * self.xmlIndent) self.xmlOutputFile.Write(tag) if '/' not in tag: self.xmlIndent += 1 def _ExpectKeyword(self, keywords): ...
The main task of the code is to compile a variable declaration statement, handling multiple variables separated by commas. It parses the 'var' keyword, variable type, and names, adds each variable to the symbol table, and generates corresponding XML output. The tokenizer is advanced through the input tokens, ensuring p...
def _CompileVarDec(self): """ Compiles <var-dec> := 'var' <type> <var-name> (',' <var-name>)* ';' ENTRY: Tokenizer positioned on the initial 'var'. EXIT: Tokenizer positioned after final ';'. """ self._WriteXmlTag('<varDec>\n') storageClass ...
def get_wtn_issuer(company): return { "Name": company.name, "NIPT": company.vat, "Address": company.street, "City": company.city } def get_wtn_carrier(self): for record in self: partner = record.partner_id if not partner.id: self.er...
This function sends WTN (Waybill Tracking Number) data to a Profisc API endpoint. It constructs a JSON payload with header, issuer, carrier, and line items from the record, then posts it to the configured API URL. On success, it updates FISC records; on failure, it logs errors and raises exceptions. The process is skip...
def send_to_profisc(self): for record in self: if record.profisc_wtn_type == 'n_a': return request_manager = self.env['request.manager'] issuer = get_wtn_issuer(record.location_id.company_id) carrier = self.get_wtn_carrier() wtn_lines...
def retune_hyperparams( X_train, y_train, multi: bool, num_folds=5, n_hypercube_points=HYPERCUBE_POINTS ): """ Retune the model hyper-parameters by searching over a Latin Hyper-cube. Each candidate set of hyper-parameters is evaluated using a cross-validation estimate of the F0.5 score. Args: ...
The function trains a LightGBM model for a specified outcome variable, supporting binary/multi-class classification. It uses predefined, retuned, or previously saved hyperparameters based on the `hyperparam_choice` argument. After parameter selection, it trains the model on combined training/test data, calculates evalu...
def train_gbm( X_train, y_train, X_test, y_test, outcome_var, multi: bool, hyperparam_choice: HyperParameterChoice, ): """ Train the LightGBM model with the option of retuning hyper-parameters. Args: X_train: A dataframe containing the training features and UPN's. ...
def get_graphname(query): response_by_llm=get_graphname_llm(query) print("response_by_llm:",response_by_llm,"_________________") graph_name_by_script=graph_name_script(query) print("graph_name_by_script:",graph_name_by_script,"__________") final_graphname=get_final_graphname(response_by_llm,graph_na...
The function generates or retrieves a SQL query based on a graph name derived from the user prompt, applies filters by modifying the query with WHERE clauses, and returns the updated query along with the table name and graph name. It uses either a template with an LLM chain for dynamic query generation or a predefined ...
def get_sql_query(user_prompt, filter): graph_name = get_graphname(user_prompt) print("hi i am in the get_sql_query",graph_name) if graph_name == "None": return "Invalid input" else: #print("i am in get_sql_query") #print(graph_attributes_dict[graph_name]) if("tem...
def find_entry_metadata(entry): try: arxiv_id = entry.find("{http://www.w3.org/2005/Atom}id").text.split('/abs/')[-1] title = entry.find("{http://www.w3.org/2005/Atom}title").text #DOI doi = None mo_da_one_doi = [] for arxiv in entry.findall(".//{http://arxiv.org/sch...
The main task of the code is to process XML entries by extracting metadata, downloading associated PDF and LaTeX files for each entry, and compiling the results into a list of rows. It handles errors during metadata extraction and file downloads, logging issues while continuing processing. Each valid entry's arXiv ID, ...
def iterate_entries(root): rows = [] try: for entry in root.findall(".//{http://www.w3.org/2005/Atom}entry"): metadata = find_entry_metadata(entry) if not metadata: continue if (arxiv := metadata['arxiv_id']) is None: logging.error(f"Er...
def isCoordValidInWorkSpace(x, y, res): # Checking bounds on the workspace flag = True key = 0 if x < 0 or x > 1110 or y < 0 or y > 1010: flag = False # Checking if coord is valid w.r.t obstacle space if flag: if obstacleSpace[int(x/res), int(y/res)] == 0.0: flag = False key = 1 return flag, key def p...
The code implements A* path planning for a TurtleBot3 robot in a grid-based environment. It reads start/end points, validates them against obstacles/workspace boundaries, converts coordinates to grid cells, and executes A* to find a collision-free path. The path is visualized and published for the robot to follow, inco...
def main(args): # Read arguments provided from launch file using myargv rosArgs = rospy.myargv()[1:] # Define parameters resolution = 1.0 # every grid of the workspace is of 1cm in length and width startPoint = (float(rosArgs[0])*100, float(rosArgs[1])*100) endPoint = (float(rosArgs[2])*100, float(rosArgs[3])*...
def get_object(self, pk): try: return Game.objects.get(pk=pk) except Game.DoesNotExist: raise Http404 def change_players_state(game_obj, current_player, state): for player in game_obj.players.all(): if player != current_player: player.state = state ...
The code handles a player's move in a turn-based game by validating row/column inputs, checking game status, and updating player/game states. It ensures the player is in the 'ready' state, processes the move, and toggles states between 'ready' and 'wait' for turn progression.
def post(self, request, *args, **kwargs): row = kwargs.get('row', None) column = kwargs.get('column', None) if not (row in range(0,3) and column in range(0,3)): return Response("Invalid value for row or column", status=status.HTTP_400_BAD_REQUEST) current_player_id =...
def _estimate_diff_sigmas(self, j_ising: np.ndarray, h_ising: np.ndarray, data_mean: np.matrix) -> np.matrix: """ Estimates the difference between the mean spin w.r.t boltzmann and the empirical mean spin (...
The code estimates the Ising model parameters h (magnetic field) and J (interaction matrix) from binarized data using an iterative optimization method inspired by Ezaki (2017). It maximizes pseudo-likelihood through updates of h and J with L1 sparsity constraints, stopping when the error falls below a threshold or afte...
def _estimate_archetype(self, iteration_max: int, delta_t: float, permissible_error: float, estimate_h: bool, sparsity: float) -> None: """ Estimation of h and J in...
def _estimate_diff_si(self, data_mean: np.matrix, beta: float) -> np.matrix: """ Computes the difference between the model mean value Si (or h) and the data mean for each iteration of the the Ising parameters. Used in Equation 10 of TN0150. """ m...
The code estimates Ising model parameters (h and J) for a personalized iNeT by searching optimal beta values. It calculates errors between data statistics and model predictions for each beta, selects the beta minimizing error, scales archetype parameters by this beta, and updates the model's parameters and error metric...
def _estimate_h_j(self, betas: np.ndarray) -> None: """ Estimation of the Ising parameters using an archetype. Starting from an archetype iNeT, we fit a parameter beta (equal to the inverse temperature, 1/T) that makes the resulting scaled iNeT from the archetype be the best cand...
def _estimate_energy(self, betas: np.ndarray) -> None: """ Estimation of the Ising energy using an archetype. Starting from an archetype iNeT, we fit a parameter beta (equal to the inverse temperature, 1/T) that makes the resulting scaled iNeT from the archetype be the best candi...
The code's main task is to execute the `itailor` algorithm for either building an archetype model or personalizing it for individual subjects. When using the "archetype" method, it estimates Ising model parameters (h_ising, j_ising) from binarized data across all subjects. For "personalized_H" and "personalized_h_j", i...
def run(self, method: str, params: dict, betas: np.ndarray = None) -> None: """ Runs the itailor to either build an archetype model or to find the personalized temperature that best explains the data of each subject given an archetype, depending on the...
def get_leaf(self, targets): # Obtain the leaf as the mean of the targets return np.mean(targets) def get_best_split(self, X, y): """ Obtain the best splitting point and resulting children for the data set X, y Args: X, y (numpy.ndarray, data set) criterion (gini or entropy...
This function recursively splits a decision tree node into left and right children, checking constraints like maximum depth and minimum samples per node. It creates leaf nodes when splitting isn't possible, using best splits to further divide nodes until termination conditions are met.
def split(self, node, depth): """ Split children of a node to construct new nodes or Args: node (dict, with children info) max_depth (int, maximal depth of the tree) min_samples_split (int, minimal samples required to further split a child) depth (int, current depth o...
def get_all_parameters(ssm_client): parameters = [] for page in get_paginated_parameters(ssm_client)['Parameters']: try: get_param = get_parameter(page['Name']) parameters.append(get_param) except BaseException as ex: parameter_name = "Missing Name" ...
The code synchronizes parameters between two SSM clients. It updates all parameters from the source client and deletes parameters from the target client that are not present in the source and have replication tags.
def sync_all_parameters(): source_names = [] for param in get_all_parameters(ssm_source_client): source_names.append(param.Name) update_parameter(param) for param in get_all_parameters(ssm_target_client): if param.Name not in source_names and param.has_replication_tags(): ...
def get_event_detail(event): validate_configuration(event) name = event['detail']['name'] operation = "" if "operation" in event['detail']: operation = event['detail']['operation'] return name, operation def sync_all_parameters(): source_names = [] for param in get_all_parameters(...
The code handles parameter operations based on event details. It syncs and replicates all parameters if the name is "all", updates or creates a parameter if the operation is "update" or "create", and deletes a parameter if the operation is "delete". It returns a success response with a 200 status code upon completion.
def handle(event, context): name, operation = get_event_detail(event) if name == "all": sync_all_parameters() replicate_all_secrets() elif operation in ["update", "create"]: parameter = get_parameter(name) update_parameter(parameter) elif operation == "delete": ...
def assert_200_request_to(url): assert_200(requests.get(url)) def get_polls_url_detail(question_id): return get_polls_url() + str(question_id) + '/' def get_polls_url_results(question_id): return get_polls_url() + str(question_id) + '/results' def get_polls_url_vote(question_id): return get_polls_url() ...
The code tests that accessing specific endpoints for polls (detail, results, vote) returns a 200 OK status for question IDs 2020 and 2021, ensuring proper API functionality.
def test_get_question(self): for question_id in {2020, 2021}: assert_200_request_to(get_polls_url_detail(question_id)) assert_200_request_to(get_polls_url_results(question_id)) assert_200_request_to(get_polls_url_vote(question_id))
def build_data_mat(data): """Build C_mat and datamask for the given data :param data: A dictionary {user_id: list, question_id: list, is_correct: list} """ C_mat = np.zeros((N_STUDENTS, N_QUESTIONS)) data_mask = np.zeros((N_STUDENTS, N_QUESTIONS)) users = data["user_id"] questions = da...
The main task of the code is to implement and evaluate an Item Response Theory (IRT) model by tuning hyperparameters (learning rate and iterations), training the model on training data, evaluating validation and test accuracies, and visualizing training curves (accuracy and log-likelihood) and response probabilities. I...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### ...
def build_data_mat(data): """Build C_mat and datamask for the given data :param data: A dictionary {user_id: list, question_id: list, is_correct: list} """ C_mat = np.zeros((N_STUDENTS, N_QUESTIONS)) data_mask = np.zeros((N_STUDENTS, N_QUESTIONS)) users = data["user_id"] questions = da...
The code implements an Item Response Theory (IRT) model to predict student responses to questions. It loads training, validation, and test data, initializes parameters (theta for students, beta for questions, alpha for discrimination), and groups students/questions by metadata (age, appearance frequency). It trains sep...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### ...
def get_exchange_rate(path=None): date_to_use = get_date_to_use() if path is None: file_name = "exchange_rates.json" path = f"app/{file_name}" if os.path.exists(path): with open(path, "r") as file: exchange_rates = json.load(file) else: exchange_rates = {} ...
The main task of the code is to handle user transactions by updating their balance and transaction history based on POST requests. It retrieves the user's balance, exchange rate, and transactions, processes payment or deposit actions, updates the balance with error handling, and renders the index page with real-time da...
def index(): exchange_rate = get_exchange_rate() user_email = current_user.id balance = get_balance(user_email) transactions = get_transactions(user_email) err = "" if request.method == "POST": amount = float(request.form["amount"]) currency = request.form["currency"] ...