dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def segments(self, depth_map): not_in_touch = np.copy(depth_map) not_in_touch[not_in_touch < self.max_depth] = 0.0 not_in_touch[not_in_touch >= self.max_depth] = 1.0 in_touch = 1 - not_in_touch return not_in_touch, in_touch def protrusion_map(self, original, not_in_touc...
The code generates a realistic 3D rendering of an object using depth maps, applying elastic deformation, texture noise, shadow overlays, and Phong lighting. It segments depth into contact/non-contact regions, computes protrusion depth, applies elastic deformation, adds texture, overlays internal shadows, calculates tan...
def generate(self, obj_depth, return_depth=False): not_in_touch, in_touch = self.segments(obj_depth) protrusion_depth = self.protrusion_map(obj_depth, not_in_touch) elastomer_depth = self.apply_elastic_deformation(protrusion_depth, not_in_touch, in_touch) ...
def hoho(self, player=0): # Returns the list of gems in the first three home holes if player == 0: return [self.holes[0].nop,self.holes[1].nop, self.holes[2].nop] return [self.holes[6].nop,self.holes[7].nop, self.holes[8].nop] def sweep(self): status = False ...
This code simulates a turn-based game where a player moves through holes to collect pearls, with conditions to end the game when reaching the home base or collecting gems. It iterates through moves, checks for special hole states, and terminates after a set number of rounds or when the game concludes.
def iter(self, player=0, hole=0, rounds=10): # === gogo = True ctr = 0 base = False cleaned = False # rounds is for testing purposes only, to avoid deadlock in loop # print(hole) if hole is None: pearls_in_holes = self.hoho(player=player) ...
def grounded_sphere_potential_with_a_box_inside(x,y,z,R,h,f): ''' gets coordinates, radius of sphere ,half_width of box and a function on the box returns 1) the potential at the point in the first argument 2) if the point belongs to the boundary ''' ''' if on_box(x,y,z,h): print(...
The code solves a 3D electrostatic potential problem using an iterative method, computing the electric field and charge density for different charge configurations (q='2', '3a', '3b', '4') within a grounded sphere with a box. It initializes the potential, iterates until convergence, and visualizes 3D/2D potential, char...
def hw5(N,q='2',initial=0): Nx,Ny,Nz=N,N,N half_width_of_box=1.5 L=3.3 R=sqrt(10) dx=L/N print(f'dx is {dx}') if q=='2' or q=='4': f=lambda x,y,z:1 rho = lambda x,y,z:0 if q=='3a': f = lambda x,y,z:1/np.sqrt(x**2+y**2+z**2) if (x,y,z)!=(0,0,0) else 1/np.sqrt(0.75*...
def harmonic_oscilator(_,x0,k=3): return -k*x0 def euler_method(ode,initial_conditions,dt,nsteps): nsteps=nsteps+1 n= len(initial_conditions) solution= [[] for i in range(nsteps)] solution[0]=[*initial_conditions,ode(0,*initial_conditions)] for i in range(1,nsteps): for j in range(1,n+1)...
The code solves the harmonic oscillator ODE using specified numerical methods (Euler, super Euler, RK2, RK4) or plots the analytical solution. It configures time steps and integration parameters uniquely for each method, computes the numerical solution, and visualizes results against the analytical solution (cos(t)). T...
def q3_harmonic_oscilator(method): ode = lambda t,x,v: harmonic_oscilator(t,x,1) nsteps=int(1e5) dt=1e-2 if (method=='euler'): nsteps=3968 dt=2*np.pi/nsteps solution =np.array(euler_method(ode,[1,0],dt,nsteps)) if (method=='super_euler'): nsteps=3968 dt=2*np....
def euler_method(ode,initial_conditions,dt,nsteps): nsteps=nsteps+1 n= len(initial_conditions) solution= [[] for i in range(nsteps)] solution[0]=[*initial_conditions,ode(0,*initial_conditions)] for i in range(1,nsteps): for j in range(1,n+1): solution[i].insert(0,taylor(dt,soluti...
The code compares numerical solutions of a free-fall ODE using Euler, super Euler, RK2, RK4 methods against an analytical solution. It generates time arrays, computes analytical results via 1-0.5*9.8*t², and applies specified numerical methods to solve the ODE with initial conditions [1,0]. Results are plotted against ...
def q3_free_fall(method): ode = free_fall nsteps=int(1e4) dt=1e-4 t_arr = np.array([i*dt for i in range(nsteps+1)]) analytical= 1-0.5*9.8*t_arr**2 if (method=='euler'): solution =np.array(euler_method(ode,[1,0],dt,nsteps)) if (method=='super_euler'): solution =np.array(super_...
def get_img_label(self, window): return tk.Label(window) def get_status_label(self, window): return tk.Label(window, text="", font=("Helvetica", 16)) def update_webcam_feed(self): ret, frame = self.cap.read() if ret: most_recent_capture_arr = frame img_ = cv2.cvtC...
The code initializes a GUI for a Face Recognition Attendance System, setting up a Tkinter window with a background image, webcam feed display, status labels, and buttons for user registration, attendance tracking, QR code scanning, and WhatsApp status updates. It also prepares directories for storing user data, QR code...
def __init__(self): self.main_window = tk.Tk() self.main_window.geometry("1200x600+350+100") self.main_window.title("Face Recognition Attendance System") background_image = Image.open("background_image.png") background_photo = ImageTk.PhotoImage(background_image) self.ba...
def _gen_starting_points(self): speed_groups = defaultdict(list) for y in range(2, self.H - 2): for x in range(self.W): v = self.U[y][x] ** 2 + self.V[y][x] ** 2 if v < self.min_value: self.U[y][x], self.V[y][x] = 0, 0 c...
The code converts grid points into GeoJSON features by iterating over starting points in descending speed order, checking if pixels are free, generating and smoothing lines, then creating Feature objects with unique IDs. These features are collected into a FeatureCollection and returned as a GeoJSON structure.
def to_geojson(self): # Iterate over all grid points descending order of speed and try to start a line there idx = 0 features = [] for x, y in self._gen_starting_points(): if self._is_pixel_free(x, y): line = self._get_line(x, y) if line: ...
def retrieve_data(soup): """ [Retrieves the relevant data for a TripAdvisor attraction page and returns it as a dictionary. Parameters] param: soup (BeautifulSoup) - A BeautifulSoup object representing the HTML of the attraction page. Returns (dict) - A dictionary containing the name, rating, and ot...
The function scrapes TripAdvisor attraction URLs in batches using asynchronous requests, parses HTML to extract statistical data, compiles results into a DataFrame, and sorts entries by city and TripAdvisor rank. It handles request errors retrying until successful, then updates the DataFrame with parsed data, including...
def attractions_data(urls, ranks, batch_size): """ param: lst (list)- a list of urls of tourist attraction webpages from tripadvisor.com param: batch_size (int) - the number of urls to get a response from in an asynchronous grequests get() function. return: data_df (pandas.DataFrame) - contains all the ...
def get_response_then_get_soup(url): """ Param: url (str) url from a tripadvisor webpage. Returns: a soup object of the BeautifulSoup library. [Motivation: Often, getting a response from a website using the grequests library can take a long time. It is more efficient to try again after a certai...
The function gathers a specified number of top attraction URLs from TripAdvisor by iterating through pages, extracting links from each, and collecting them until the desired count is reached. It starts with the homepage URL, processes each page's links, and navigates to subsequent pages if needed, handling errors durin...
def get_all_top_links(url, num_attractions): """ param: url (str) - the url for the homepage of top attractions for a particular city on tripadvisor.com param: num_attractions (int) - the number of attraction-urls to gather starting from the homepage and continuing on to the next page (and the ext p...
def get_name(schema, values): return get_property_value(schema, values, 'NAME') def get_namespace(schema, values): return get_property_value(schema, values, 'NAMESPACE') def inject_deployer_image_properties(values, schema, deployer_image): for key in schema.properties: if key in values: continue if ...
The function processes a schema and input values to generate Kubernetes manifests. It injects deployer image properties, provisions secrets, service accounts, and storage classes from storage or templates, merges user-provided and generated parameters, and constructs deployer manifests. The output is a list of manifest...
def process(schema, values, deployer_image, deployer_entrypoint): props = {} manifests = [] app_name = get_name(schema, values) namespace = get_namespace(schema, values) # Inject DEPLOYER_IMAGE property values if not already present. values = inject_deployer_image_properties(values, schema, deployer_image)...
def move(self, move_vector): self.body = np.append([self.body[0] + move_vector], self.body, axis=0) self.body = self.body[:self.snake_length] self.reward = 0 # Reward given for moving towards and away from the food if np.linalg.norm(self.body[1] - self.food) < np.linalg.norm(sel...
The code processes a movement action to update the snake's direction and position, checks for collisions with walls or itself, and returns the new game state, completion status, and reward. It implements directional control logic based on the snake's current movement direction and action input (forward, left, right tur...
def step(self, _action): # Traditional Controls '''if ((abs(_action - self.previous_action) == 1) and (_action + self.previous_action != 3)): self.dead() if _action == 0: # Move Up self.move([0, -10]) elif _action == 1: # Move Down self.move([0, 10]) ...
def count_stones(board): nred = 0 nblue = 0 n = len(board) for i in range(n): for j in range(n): if board[i][j] == 'R': nred+=1 elif board[i][j] == 'B': nblue+=1 return nred, nblue def pad_board(board, n): # Pad top and bottom with Red padded_board = ['R' f...
The function determines the game status by checking if the number of red and blue stones is valid, then analyzing board paths for Blue or Red to win. If Blue has a connected south-north path with equal or more stones, Blue wins. Similarly, if Red has a connected west-east path with equal or more stones, Red wins. Other...
def game_status(n, board): num_red, num_blue = count_stones(board) if abs(num_red - num_blue) > 1: return "Impossible" padded_board = pad_board(board, n) m = n+2 south_path = blue_path_south(padded_board, m) if south_path: north_path = blue_path_north(padded_board, m) ...
def _convert_input_weights(self, weights, fix_input=True): """ Check the portfolio weights are valid, and convert from Pandas Series to Numpy array. :param weights: Pandas Series with portfolio weights. :param fix_input: Boolean whether to fix NaN and in...
The code adjusts input portfolio weights to satisfy group constraints without increasing them. It lowers weights iteratively until constraints are met, validates results, and returns adjusted weights as a Pandas Series (or DataFrame with logs). It handles input checks, ensures weight consistency, and enforces group lim...
def constrain_weights(self, weights_org, fix_input=True, log=False, max_iter=100, tol=1e-6): """ Adjust the input weights so all the group-constraints are satisfied. This will only lower the portfolio weights and not increase them. The validity of the results a...
def GetRegionWithoutStart(region: str, length) -> str: """ Get the region without the start codon """ #loop until you reach a region without a stop codon in it i = 0 while True: if i + length >= len(region): raise Exception("Could not find a region without a stop codon") ...
The main task of the code is to generate an shRNA stem sequence by extracting a target region, creating its complementary strand, and inserting a GHG mismatch motif. It constructs the final RNA structure by combining fixed sequences, the modified stem, a loop, the complementary strand, and additional randomized or fixe...
def GenStem(StemSize: int, Target: str) -> str: """ Generate an shRNA stem """ Stem = GetRegionWithoutStart(Target, StemSize) StemComplement = GetComplement(Stem) # now add the GHG mismatch motif i = 0 while True: if i + 2 >= len(Stem): raise Exception("Could not cre...
def LocalExpressionInCells(record, innercode): B_LongumPromoter(record, lambda record, innerode=innercode: (human.KozakSequence(record), Gil.AminoSequence(record, 'gggxxxxx', Gil.HumanCodons), innercode(record)) ) def ShineDalgarnoSeq(record): record.seq += 'AGAAAGGAG' def AddStr(re...
The code modifies a biological record to enable quorum detection by applying three operations: identifying Shine-Dalgarno sequences, appending a specific nucleotide sequence ('AATAAACAA'), and processing LuxR-related elements. This prepares the record for quorum-sensing mechanisms in synthetic biology or genetic engine...
def AllowQuorumDetection(record): LocalExpressionInCells(record, lambda record:( ShineDalgarnoSeq(record), AddStr(record, 'AATAAACAA'), LuxR(record) ))
def LocalExpressionInCells(record, innercode): B_LongumPromoter(record, lambda record, innerode=innercode: (human.KozakSequence(record), Gil.AminoSequence(record, 'gggxxxxx', Gil.HumanCodons), innercode(record)) ) def ShineDalgarnoSeq(record): record.seq += 'AGAAAGGAG' def AddStr(re...
The code's main task is to modify a biological record by adding a Shine-Dalgarno sequence, a specific DNA string ('AATAAACAA'), and LuxI gene components, likely for quorum sensing in synthetic biology. It uses `LocalExpressionInCells` to apply these transformations, enabling cellular communication or gene expression re...
def SendQuorumSignal(record): LocalExpressionInCells(record, lambda record:( ShineDalgarnoSeq(record), AddStr(record, 'AATAAACAA'), LuxI(record) ))
def LocalExpressionInCells(record, innercode): B_LongumPromoter(record, lambda record, innerode=innercode: (human.KozakSequence(record), Gil.AminoSequence(record, 'gggxxxxx', Gil.HumanCodons), innercode(record)) ) def ShineDalgarnoSeq(record): record.seq += 'AGAAAGGAG' def AddStr(re...
The main task of the code is to process a biological record by applying the `innercode` function after modifying it with the Shine-Dalgarno sequence and an additional string ('AATAAACAA'). This involves adding specific sequences to the record and then executing the `innercode` function on the modified data, likely for ...
def LocalExpressionInCells_SD(record, innercode): LocalExpressionInCells(record, lambda record, innerode=innercode: ( ShineDalgarnoSeq(record), AddStr(record, 'AATAAACAA'), innerode(record) ))
def energy_matrices(x, dim=2, helmert=None): """Compute the coupling and bending energy matrices""" if helmert is None: k = x.shape[-2] helmert = helmert_mat(k, dtype=x.dtype) s_x = coupling(x, dim, helmert) s_inverse = torch.linalg.inv(s_x) x_h = helmert @ x x_s = transpose(x_h)...
The function computes a metric matrix combining affine and bending energy terms for a shape. It calculates coupling and bending matrices via energy_matrices, derives an affine component from the coupling matrix, scales the bending matrix with a mu value, and sums both components to form the final metric matrix, used in...
def metric_matrix(x, dim=2, rho=1., helmert=None, muvalue=0.013): """Compute the metric matrix at a shape.""" coupling_matrix, bending_matrix = energy_matrices(x, dim=dim, helmert=helmert) affine = transpose(coupling_matrix) @ coupling_matrix / 2 bending = mu(x, dim=dim, rho=rho,value=muvalue)[..., None...
def GetHitList(cnt,details): HitList = [] for d in details: PersonalScore = 0 Score = 0 try: PersonalScore = cnt[d[0]] Score = cnt[d[0]] except: pass EmployeeList = GetEmployees(d,details) for e in EmployeeList: try...
This function analyzes user roles by processing input data (er, jr, cnt) to generate role-specific breakdowns. It creates Excel sheets for organizational and link data per role, saves intermediate results as pickles, and groups link statistics by API/Site URLs.
def GetRoleBreakdown(er,jr,cnt): roles = list(set([e[1] for e in er])) fname = str('Datasets\\roles_analysis.xlsx') with pd.ExcelWriter(fname, datetime_format='MM-DD-YYYY') as writer: for r in roles: print(r) dpickle = str('Datasets\dlist - '+r) cntpickle = str('D...
def GetHitList(cnt,details): HitList = [] for d in details: PersonalScore = 0 Score = 0 try: PersonalScore = cnt[d[0]] Score = cnt[d[0]] except: pass EmployeeList = GetEmployees(d,details) for e in EmployeeList: try...
The main task of the code is to analyze user roles by processing input data (er, jr, cnt), generate role-specific datasets, and save structured analysis results (e.g., organization links, API/site URL statistics) into Excel sheets and pickle files for further use. It filters, groups, and visualizes data per role, creat...
def GetRoleBreakdown(er,jr,cnt): roles = list(set([e[1] for e in er])) fname = str('Datasets\\roles_analysis.xlsx') with pd.ExcelWriter(fname, datetime_format='MM-DD-YYYY') as writer: for r in roles: print(r) dpickle = str('Datasets\dlist - '+r) cntpickle = str('D...
def submit_id_mapping( ids: list[str], taxId: str = None, from_db: str = None, to_db: str = None, ): """! Submit the id mapping job to the UniProt ID mapping API. @param form_db Define the db the ids come from. @param to_db Define the db to which the ids should be mapped on. @param i...
This function maps biological identifiers between databases (e.g., Ensembl to UniProtKB) by submitting a mapping job, checking its status, retrieving results via a URL, and returning the mapped identifiers. It handles cross-database ID conversion for proteomics/genomics data, with optional taxonomic filtering.
def query_from_to( ids: list[str], taxId: str = None, from_db: str = None, to_db: str = "UniProtKB" ): job_id = submit_id_mapping( from_db=from_db, to_db=to_db, ids=ids, taxId=taxId, ) if check_id_mapping_results_ready(job_id): link = get_id_mapping_results_link(j...
def execute_db_query(query): db = mysql.connector.connect(host="localhost", user="root", passwd="root", db="hotelBooking") cur = db.cursor() cur.execute(query) results = [] for row in cur.fetchall(): ...
The main task of the code is to manage a hotel booking dialog by handling search operations, resolving conflicts (e.g., room, dates, city), updating the dialog state dynamically, and rendering appropriate responses using templates. It processes user inputs for city, address, stars, and booking parameters, adjusts state...
def execute_do_not_know(dialog_state): if dialog_state.get('operation') == 'search': if dialog_state.get('operation_search') == 'select_city': res = execute_db_query(queries.get_cities(dialog_state.get('city'))) dialog_state = update_dialog_state(session, {'city': res[0][0]}) ...
def update_dialog_history(session, request, dialog_history_attribute_name='dialog_history'): dialog_history = session.attributes.get(dialog_history_attribute_name) if dialog_history is None: dialog_history = [] dialog_turn = {"intent": request.get('intent'), "type": request.get(...
This function determines user intent by processing ordinal numbers or hotel names, updates dialog states, and either books a hotel or performs a search. It checks conditions like city selection, hotel ID lookup, or direct hotel name input, then executes corresponding database queries, updates session data, and returns ...
def select_intent(ordinal_number, hotel_name): update_dialog_history(session, request) dialog_state = update_dialog_state(session, {}) hotels = dialog_state.get('hotels') if dialog_state.get('operation_search') == 'select_city': res = execute_db_query(queries.get_cities(dialog_state.get('city'))...
def update_dialog_history(session, request, dialog_history_attribute_name='dialog_history'): dialog_history = session.attributes.get(dialog_history_attribute_name) if dialog_history is None: dialog_history = [] dialog_turn = {"intent": request.get('intent'), "type": request.get(...
The main task of the code is to handle a hotel booking request by updating the dialog state with user-provided parameters, validating the city-region combination, executing the booking operation, and returning a response message. It integrates user inputs into a structured dialog state, checks if the city exists in the...
def received_book_hotel(hotel_name, stars, number_room, arrival_date, departure_date, number_people, address, city, country, region): update_dialog_history(session, request) dialog_history = update_dialog_history(session, request) dialog_state = update_dialog_state(session, {"hotel_name": '', ...
def update_dialog_history(session, request, dialog_history_attribute_name='dialog_history'): dialog_history = session.attributes.get(dialog_history_attribute_name) if dialog_history is None: dialog_history = [] dialog_turn = {"intent": request.get('intent'), "type": request.get(...
This function processes hotel booking-related input parameters, updates the dialog state with non-empty values, formats city-region combinations, and triggers search/booking operations. It checks for existing state values, updates session data, and returns appropriate responses based on the 'operation' flag, handling e...
def received_information(hotel_name, stars, number_room, arrival_date, departure_date, number_people, address, city, country, date, number, region): update_dialog_history(session, request) dialog_history = update_dialog_history(session, request) dialog_state = update_dialog_state(se...
def update_dialog_history(session, request, dialog_history_attribute_name='dialog_history'): dialog_history = session.attributes.get(dialog_history_attribute_name) if dialog_history is None: dialog_history = [] dialog_turn = {"intent": request.get('intent'), "type": request.get(...
The function handles a "do not know" scenario in a dialogue system by updating conversation history, adjusting dialog state, generating a response message, repeating it in the state, and returning a question based on the message to prompt user input.
def do_not_know(): update_dialog_history(session, request) dialog_state = update_dialog_state(session, {}) msg = execute_do_not_know(dialog_state) dialog_state = update_dialog_state(session, {'repeat': msg}) return question(msg)
def update_dialog_state(session, slots, reset=False, dialog_state_attribute_name='dialog_frame'): dialog_state = {} if not reset: dialog_state = session.attributes.get(dialog_state_attribute_name, {}) for slot_name, slot_value in slots.items(): if slot_value is not None: ...
This function manages a dialog system for handling booking and search operations. It updates the dialog state based on user input, checks for conflicts (e.g., room availability, dates, location), and generates appropriate responses (e.g., prompts, confirmations, or error messages). It transitions between operations lik...
def received_affirm(): b = True dialog_state = update_dialog_state(session, {}) if dialog_state.get('operation') == 'new_booking': dialog_state = update_dialog_state(session, {}, reset=True) msg = render_template('welcome') elif dialog_state.get('operation') == 'book': if dialo...
def update_dialog_history(session, request, dialog_history_attribute_name='dialog_history'): dialog_history = session.attributes.get(dialog_history_attribute_name) if dialog_history is None: dialog_history = [] dialog_turn = {"intent": request.get('intent'), "type": request.get(...
The main task of the code is to handle user denial or conflict scenarios in a hotel booking system by updating dialog states, resolving conflicts (e.g., room numbers, dates, city), executing booking or search operations, and generating appropriate responses like restarts, error messages, or prompts. It transitions betw...
def received_deny(): dialog_history = update_dialog_history(session, request) dialog_state = update_dialog_state(session, {}) if dialog_state.get('operation') == 'new_booking': msg = render_template('utter_goodbye') elif dialog_state.get('operation') == 'book': if dialog_state.get('ope...
def __find_solutions(self): ival: Interval = self._intervals[self._intervals_len - 1].item() self._first_segment: cython.bint = True curr_segments_pointer: cython.int = self._ds_stack_indices[self._intervals_len] prev_segments_pointer: cython.int = self._ds_stack_indices[ se...
The code manages intervals to explore feasible solutions, backtracking by removing or replacing intervals when infeasible, using lexicographic order to generate next intervals, and updating components in a constraint system. It checks for unsatisfiable cores and adds valid components to a structure, returning whether s...
def __next(self, curr_is_feasible: cython.bint): if self._intervals_len == 0: # initial values self._intervals[self._intervals_len] = (0, self._initial_interval_endpoint) self._intervals_len += 1 self.__find_solutions() self.__add_component_to_wppsc() ...
def add_train_label_noise(self, percentage=10): noisy_data = [list(sample) for sample in self.training_data] label_ids = np.random.choice(len(self.training_data), size=round(len(self.training_data)*(percentage/100)), replace=False) rand_labels = np.random.choice(10, size=round(len(self...
This function evaluates the impact of label noise in training data on a model's ability to detect noisy examples. It iterates over specified noise percentages, introduces synthetic label noise, reinitializes the model, trains it, and calculates the percentage of correctly identified noisy examples. Results are collecte...
def label_noise( self, model, model_type='lr', percentages=None, device=None ): self.model_type = model_type model_noisy_examples_percentages = [] train_noise_percentages = [] for percentage in percentages: print(f"Training ...
def find_one_by_origin(self, origin): """searchs a single origin of a digital account """ origin_hash = self.__key_hash(origin) try: return self.__construct_creds(self.cipher[origin_hash]) except KeyError: return None def __key_hash(self, string): """creates binary rep of a string, reverses that bina...
The code creates a new encrypted digital account entry by checking if an account with the same origin exists. If not, it encrypts the origin, username, and password, stores them in a cipher dictionary with a hashed key, updates the hash structure, and returns True upon successful creation.
def create(self, data): """creats new bytes tuple for a new digital account and dumps in main cipher file storage """ already_exists = self.find_one_by_origin(data['origin']) if already_exists: return None self.cipher[self.__key_hash(data['origin'])] = self.__encrypt_blob(data['origin'], data['username'...
def find_one_by_origin(self, origin): """searchs a single origin of a digital account """ origin_hash = self.__key_hash(origin) try: return self.__construct_creds(self.cipher[origin_hash]) except KeyError: return None def __key_hash(self, string): """creates binary rep of a string, reverses that bina...
The function updates an existing account's data by modifying its properties and re-encrypting the updated information in a cipher. It retrieves the account via `origin`, applies changes from `data`, re-encrypts the account's details, updates the hash structure, and returns `True` on success or `False` if the account is...
def update_account(self, origin, data): account = self.find_one_by_origin(origin) if account: for prop in data: account[prop] = data[prop] self.cipher[self.__key_hash(origin)] = self.__encrypt_blob(origin, account['username'], account['password']) self.__update_hash() return True return False
def _extend_title(self, title: str, node: DocNode) -> str: return title + " {#" + node.qualname + "}" if self.anchor_extend else title def get_description(docstring: Docstring) -> List[str]: """Get description form a Docstring object. Args: docstring: A Docstring object. Returns: A...
The main task of the code is to generate a markdown-formatted documentation string from a FunctionNode, including the function's name, signature, docstring, parameters, return types, exceptions, and examples. It constructs titles, formats arguments, handles async/lamba flags, and assembles all elements into a cohesive ...
def build_function( self, node: FunctionNode, *, level: int = 1, kind: str = "function", ignore_first_arg: bool = False, **kwargs, ) -> str: """Build markdown string from a FunctionNode. Args: node: A FunctionNode. leve...
def step(self, frame): self.cur_frame = frame self.find_laser_coms() def draw_mask(self): self.cur_frame = cv2.bitwise_and(self.cur_frame, self.cur_frame, mask=self.cur_mask) def draw_laser_coms(self): for i, mass_px in enumerate(self.cur_coms): h = int(mass_px) ...
This code captures video from a camera, processes frames in real-time to estimate distances using a laser setup, and allows user calibration by capturing slope-intercept data at specified distances. It uses OpenCV for frame processing, drawing masks, laser points, and distance calculations, saving calibration data when...
def run_windowed(self): self.cap = cv2.VideoCapture(self.camera_id) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 10000) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 10000) self.actual_frame_height = float(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) calibration_data = [] calibrate_ste...
def displayMenu(self): print("Dataman Main Menu") print("1.Answer Checker") print("2.Memory Bank ") print("3.Number Guesser ") print("5.Exit") def answerChecker(self): #Show player the format of the problem print("Format is: 1 + 2 = 3") issueBreed...
This method displays a menu, processes user choices by executing corresponding actions (answerChecker, MemoryBankMenu, GuessNumber), and controls UI flow. It loops until the user selects 'Quit' (option 5), returning False to exit, or returns True for other valid choices, with error handling for invalid inputs.
def menu(self): QUIT_CHOICE = 5 choice = 0 while choice != QUIT_CHOICE: self.displayMenu() choice = int(input("Make A Selection: ")) if choice == 5: # Exit return False # UI is finished i...
def ReadData(self): n = int(input()) self._data = [int(s) for s in input().split()] assert n == len(self._data) def GenerateSwaps(self): n= int( np.log2( len( self._data))) for i in range( n, -1, -1): self.SiftDown( i) def WriteResponse(self): print(len(self._swaps)) for swap i...
The main task of the code is to process data by reading input, generating potential swaps or permutations, and then writing the computed results to a response. The method sequentially executes three key operations: data loading, swap generation, and output writing, likely for solving a problem involving rearrangements ...
def Solve(self): self.ReadData() self.GenerateSwaps() self.WriteResponse()
def read_data(self): self.num_workers, m = map(int, input().split()) self.jobs = list(map(int, input().split())) assert m == len(self.jobs) def assign_jobs(self): self.assigned_workers = [] self.start_times = [] self.job_heap= [ 0] * self.num_workers self.worker_...
The code processes input data, assigns tasks or jobs, and generates a response or output. The main task involves reading data, distributing assignments, and writing the final result.
def solve(self): self.read_data() self.assign_jobs() self.write_response()
def _initialize_dynamic_model(self): """ Initialize the model of biomass growth and substrate accumulation """ t = cs.SX.sym('t') # not really used. x = cs.SX.sym('x', self.nx) # External metabolites vb = cs.SX.sym('v', self.nx) # fluxes across the boundary x...
The main task of the code is to initialize a collocation framework by configuring dynamic models, polynomial coefficients, variables, and polynomial constraints. The `setup` method prepares the computational structure for collocation methods, likely used in optimization or differential equation solving, by calling priv...
def setup(self, **variable_args): """ Set up the collocation framework """ self._initialize_dynamic_model() self._initialize_polynomial_coefs() self._initialize_variables(**variable_args) self._initialize_polynomial_constraints()
def E_step(self, hypothesis, bags, y): p = [] for bag in bags: dist = self.distance(hypothesis, bag) p.append(bag[np.argmax(dist)]) return np.array(p) def maximize_DD(self, hypothesis, instance, instance_target): ''' maximize DD with gradient descent ...
The main task of the code is to iteratively optimize a hypothesis by selecting top 5 positive training bags, refining them through E-step and maximize_DD iterations, and minimizing prediction error on training data. It tests hypotheses, updates parameters, and retains the best-performing model with lowest error.
def fit(self, training_bags, training_target): self.feature_num = len(training_bags[0][0]) pos_ind = np.where(np.array(training_target) == 1)[0] bags_selected = pos_ind.argsort()[-5:][::-1] pos_bags = [training_bags[bag_selected] for bag_selected in bags_selected] min_error = flo...
def returnContionalTransactions( pointerTable): conditional_txns = [] current = pointerTable[1] while current!=None: line = [] parent = current.parent while parent.parent != None: line.append(parent.name) parent = parent.parent line = line[::-1] ...
The function `returnFrequentSet` recursively extracts frequent itemsets from an FP-Tree by traversing nodes, combining current items with parent sets, and generating conditional trees. It sorts items by support count, builds subtrees for conditional transactions, and aggregates results to return all frequent itemsets m...
def returnFrequentSet(tree:treeNode, pointerTable, minSupportCount,parent=None): if len(list(tree.children.keys())) == 0: return None result = [] sorted_items = sorted( pointerTable.keys(), key=lambda k: pointerTable[k][0] ) for item in sorted_items: fqset = set() i...
def get_tasklist(): """ Used to retrieve and parse tasklist to monitor """ return os.popen("tasklist").read().split("\n") def ombi_search(tasklist): """ Searches tasklist for ombi and starts if its not running """ running = False pid_regex = r".+\.exe\s+([0-9]+)\s+\w+" pid = "N/A" for row in...
The code monitors and maintains Plex's operation by restarting it if it stops, checks OMBI status, and handles interruptions. It ensures Plex remains running, logs status changes, and exits gracefully on user interruption.
def main(): # initial check global VPN_ON global OMBI_ON global OMBI_CHECK tasklist = get_tasklist() OMBI_ON = ombi_search(tasklist)[0] VPN_ON = False running = check_plex() while not running: start_plex() time.sleep(60) print("{0}: \n\t****Plex Started****\n"...
def route_with_least_stops(sorted_route_dict): logging.info("Subway route with the least number of stops: " + str(list(sorted_route_dict.keys())[0])) logging.info("Stops: " + str(len(list(sorted_route_dict.values())[0])) + "\n") def sort_route_stops(): # https://www.freecodecamp.org/news/sort-dictionary-by...
The main task of the code is to process and analyze route data by sorting routes based on stops, identifying routes with the least and most stops, printing all connecting routes, and logging the execution time. It measures performance by timing the operations and outputs results for analysis.
def main(): start = time.time() route_with_least_stops(sort_route_stops()) route_with_most_stops(sort_route_stops()) print_all_routes_of_connecting_stops() end = time.time() logging.info("Run time: " + str(end - start))
def _fix_height(self, node): node.height = 1 + max(self._height(node.left), self._height(node.right)) def _balance(self, node): if not node: return 0 return self._height(node.left) - self._height(node.right) def _right_rotate(self, node): new_root = node.left node.lef...
This function recursively inserts a key into an AVL tree, maintaining balance via rotations. It checks for Left-Left, Right-Right, Left-Right, and Right-Left cases, applying corresponding rotations to ensure the tree remains height-balanced after insertion.
def _insert_recursive(self, node, key): if not node: return TreeNode(key) if key < node.key: node.left = self._insert_recursive(node.left, key) else: node.right = self._insert_recursive(node.right, key) self._fix_height(node) balance = self....
def _parse_vcf(self): for record in self.reader: data = { 'chrom': record.CHROM, 'pos': record.POS, 'ref': record.REF, 'alt': record.ALT, 'qual': record.QUAL, 'id': record.ID, 'filter': ...
The code processes structural variant calls from VCF data by parsing records, grouping BNDs, filtering low-quality entries, and yielding processed results. It handles Lumpy-specific unmatched records (length 1) separately, applying caller-specific processing logic. The core task is filtering and transforming BND calls ...
def fetch(self): records = self._parse_vcf() records = self._group_bnds(records) records = self._filter_low_qual_calls(records) for record in records: if len(record) == 1 and self.caller == 'lumpy': yield self._process_lumpy_unmatched_record(record) ...
def parseDoubleList(l:str): #List of [Name, IP address, TCP socket#, list of available files] reg = r"([\w ]*)\s*,\s*([\d\.]*)\s*,\s*(\d+)\s*,\s*(\(.*?\)),?" matches = re.findall(reg, l) matches = [list(e) for e in matches] #each element is (Name, IP address, TCP socket#, list of available file...
The main task of the code is to test and demonstrate the parsing and serialization of command strings using `parseDoubleList`, `parseServerMessage`, and `serializeCommand` functions. It processes structured command data, prints parsed results, and verifies serialized outputs for RETRIEVE and RETRIEVE-INFOT commands, en...
def mp_tests(): cmd = parseDoubleList("RETRIEVE, 0, [Alex L, 127.0.0.1, 6001, (A Long Journey, Mechanics, Economics 101 ), Michael, 127.0.0.1, 6001, (File 1, File 2, File 3), Leonard, 127.0.0.1, 6001, (File 1, File 2, File 3)]") cmd = parseServerMessage("RETRIEVE, 0, [Alex L, 127.0.0.1, 6001, (A Long Journey, ...
def execServerCommand(self, cmd: list): client = self sock = self.svsock print(f"Executing sv:{cmd}") resp = None command = cmd[0] rq = cmd[1] if command == "REGISTER": resp = sendServerCommand(cmd, sock) if resp ...
The code executes a download command by authenticating with provided credentials, connecting to a remote server via socket, and transferring a file in chunks. It handles both direct command parameters and file search for IP/TCP details, decrypts received data, writes it to a local file, and manages errors or authorizat...
def execDownloadCommand(self, cmd: list): client = self svsock = self.svsock fileEnd = False downloadAuthorized = False clUsername = "" clPassword = "" #DOWNLOAD, 0, Filename, (optional) ip, (optional) tcp print("Executing cl:", cmd) if cmd[0] ==...
def get_annotations_from_xml(variant, spdi_representation): if(is_present_xml(variant, 'transcriptchange') and is_present_xml(variant.get('transcriptchange'), 'change') and is_present_xml(variant.get('transcriptchange'), 'transcript')): dna_change = (f'{variant.get("transcriptchange").get("tra...
The function `get_annotations` generates a structured annotation dictionary for a genetic variant by prioritizing data from the `annotations` DataFrame, falling back to XML or VCF formats if needed. It constructs DNA and amino acid change strings using fields like `cHGVS` and `pHGVS`, defaulting to `spdi_representation...
def get_annotations(record, annotations, spdi_representation, vcf_type, xml): if annotations is None: if xml: return get_annotations_from_xml(record, spdi_representation) if vcf_type is not None: return get_annotations_from_vcf( record, spdi_representation, vc...
def compute_full_grads (A, x, b, la,n_workers): grad_ar = np.zeros((n_workers, x.shape[0])) for i in range(n_workers): grad_ar[i] = logreg_grad(x, A[i], b[i], la).copy() return grad_ar def stopping_criterion(sq_norm, eps, it, Nsteps): #return (R_k > eps * R_0) and (it <= Nsteps) return (it <...
The main task of the code is to perform a biased distributed gradient descent algorithm (ef21_fg) with adaptive gradient estimation, tracking metrics like communication rounds, gradient norms, bit transmissions, and comparison counts during optimization. It iteratively updates model parameters using a computed gradient...
def ef21_fg(x_0, A, b, A_0, b_0, stepsize, eps,la,k, n_workers, experiment_name, project_path, dataset, Nsteps=100000): print(f"biased_diana_gd_nw-{n_workers}_k-{k}") dim = x_0.shape[0] g_ar = compute_full_grads(A, x_0, b, la, n_workers) g = np.mean(g_ar, axis=0) sq_norm_ar = [np.linalg.norm(x=g, o...
def display_health(self): """display health function""" if self._health % 2 == 0: print("Health: " + ("{}" * int(self._health / 10)), str(self._health), "\n") else: num = self._health - 5 print("Health: " + ("{}" * int(num / 10)) + "{", str(self._health), "\n"...
The main task of the code is to display a healing menu when the player's health is below the maximum (HEALTH). It shows health status, inventory, and checks for heal items. If health is already at or above HEALTH, it prints a message restricting further healing. The loop breaks after processing, ensuring healing only o...
def healmenu(self): """heal menu function""" while self.health < HEALTH: print("\n------------------------Healing Menu-------------------------\n") self.display_health() self.displayinventory() self.check_heal_item() break else: ...
def display_energy(self): """display energy function""" if self._energy % 2 == 0: print("Energy: " + ("<>" * int(self._energy / 10)), str(self._energy), "\n") else: num = self._energy - 5 print("Energy: " + ("<>" * int(num / 10)) + "<", str(self._energy), "\n"...
The main task of the code is to manage an energy menu system that checks if the player's energy is below a threshold (ENERGY). If so, it displays the energy status, inventory, and checks for energy-related items. If energy exceeds the limit, it alerts the user. The loop breaks after one iteration, suggesting a potentia...
def energymenu(self): """energy menu function""" while self.energy < ENERGY: print("\n----------------------Energizing Menu------------------------\n") self.display_energy() self.displayinventory() self.check_energy_item() break else: ...
def delay_print(self, string): """delay print function""" sp = self.SPEED for char in string: print(char, end="", flush=True) time.sleep(sp) print("\n", end="") def progression(self): """level progression function""" if self.experience >= 25 * self...
The code implements a battle mechanic where the player fights an enemy. It uses random values to determine success/failure, awarding health, XP, and items on victory or deducting health on defeat. Energy is consumed in both cases, with status updates displayed afterward.
def fight(self): """fight mechanic function""" self.delay_print("\nYou chose to fight...an enemy approaches.") self.delay_print("A battle breaks out!\n") print("\n-------------------------------------------------------------\n") time.sleep(self.SPEED * 40) energyuse = ran...
def playerinventory(self): """inventory menu function""" self.displayinventory() playerchoice = input("Press enter to return to game\n") if playerchoice == "": return def stats(self): """stats menu function""" self.displaystats() playerchoice = input("...
This code defines an 'options' menu function that displays available actions (inventory, stats, heal, etc.) and processes user input to trigger corresponding methods like playerinventory() or stats(). It uses a loop with a match statement to handle selections, ensuring valid inputs execute the right actions while inval...
def options(self): """options menu function""" print("Options:\n") print("(i)nventory", "(s)tats", "(h)eal", "(e)nergize", "(g)ame speed", "(r)ules", "(q)uit\n", sep="\n") while True: playerchoice = input("-------> ") match playerchoice: case "i" |...
def fight(self): """fight mechanic function""" self.delay_print("\nYou chose to fight...an enemy approaches.") self.delay_print("A battle breaks out!\n") print("\n-------------------------------------------------------------\n") time.sleep(self.SPEED * 40) energyuse = ran...
This function presents a player with the choice to either fight or retreat in a game scenario. It uses a loop to repeatedly prompt the user until a valid input ('f'/'F' for fight or 'r'/'R' for retreat) is received. Invalid inputs trigger an error message and re-prompting. Valid choices trigger corresponding methods (f...
def fightretreat(self): """fight or retreat sequence""" while True: playerchoice = input("(f)ight or (r)etreat? \n\n") match playerchoice: case "f" | "F": self.fight() case "r" | "R": self.retreat() ...
def delay_print(self, string): """delay print function""" sp = self.SPEED for char in string: print(char, end="", flush=True) time.sleep(sp) print("\n", end="") def progression(self): """level progression function""" if self.experience >= 25 * self...
The code simulates a walking mechanic in a game where the character either gains experience and consumes energy with a random chance, or encounters an enemy. The loop continues until energy depletes, triggering a "no energy" message.
def walk(self): """walk mechanic function""" while self.energy > 0: if randomperc() <= walkchance: experiencegain = random.randint(0, 10) self.delay_print(f"You safely walked forward. +{experiencegain} XP") self.experience += experiencegain ...
def _get_template(self) -> Template: template_path = str( Path(self.project_path) / "templates" / "template.md" ) with open(template_path) as f: return Template(f.read()) def _prepare_output_dataframe(self, results: pd.DataFrame) -> pd.DataFrame: # date truncate ...
The main task of the code is to generate a markdown file from input data by retrieving a template, preparing the dataframe, generating output tables, and combining them into a markdown file using the template.
def generate(self, results: pd.DataFrame) -> None: # get the markdown template tmpl = self._get_template() # prepare the dataframe according to the given parameters self._prepare_output_dataframe(results) # prepare data tables output_tables = self._get_output_tables(res...
def __init(self): for i in range(1, self.nodes + 1): self.visited[i] = False self.leaderOf[i] = -1 self.finishingTimeOf[i] = 0 def __findSCCs(self, graph): self.finishingTime = 0 self.leaderNode = None for i in range(self.nodes, 0, -1): ...
This code identifies strongly connected components (SCCs) in a directed graph using Kosaraju's algorithm. It first processes the reversed graph to determine node finishing times, then runs a second pass on the original graph (ordered by these times) to identify SCCs. The method returns leaders (nodes initiating SCCs) a...
def findStronglyConnectedComponents(self, graph): self.__init() self.__findSCCs(self.reversedGraph) # perform the 1st run on the reversed graph self.__reset() finishingTimesGraph = self.__createGraphFromFinishingTimes(graph) # perform the 2nd run on the original graph where the ...
def get_move(): """This function returns data about the current state of the game based on the global turn variable.""" if turn % 2 == 0: color = (0, 0, 0) # color to be used piece = 2 # current player's piece king = 4 # current player's piece (king) word = 'BLACK' # word to ...
This function determines the game's outcome by checking if any moves remain (if none, the current player loses), evaluating if either player has collected 12 pieces (winning condition), or if both have 11 pieces (tie). It updates global variables `winner` and `game_over`, displays results if applicable, and returns the...
def check_winner(array): """This function evaluates whether there are any moves to be made. If there arent then player loses. It also checks to see whether all of the pieces have been collected or whether game will end in tie.""" global winner, game_over color, piece, king, word, turned, king_turn = get...
def get_move(): """This function returns data about the current state of the game based on the global turn variable.""" if turn % 2 == 0: color = (0, 0, 0) # color to be used piece = 2 # current player's piece king = 4 # current player's piece (king) word = 'BLACK' # word to ...
This function identifies and visualizes potential moves in a board game. It retrieves game state data, checks valid moves for a highlighted piece, filters out non-capture moves if captures exist, and draws highlighted options using Pygame. Global variables track moves and captures, with visual cues indicating available...
def get_options(array, y, x, state): """Function that obtains and paints all of the potential options while also setting a global variable to a list of all the options""" global highlighted, options, switches color, piece, king, word, turned, king_turn = get_move() # gets essential game data highl...
def build_board(): """Function that builds the board/model that will be altered throughout the game""" draw_board_raw() # calls function to draw background graphics for initial board board = [] # builds the board/model that will be modified throughout the game for i in range(6): # creates a 7x6 gri...
The main task of the code is to initialize a Connect4 game by loading user session data, configuring game parameters (mode/difficulty), creating or resuming a game board based on logged-in user data, and launching the gameplay loop. It handles both new game creation and resumption of existing games through pickle data ...
def main(pg): """Function called to get everything ready for game. Sets variables from data and builds board before calling playing_game function to commence game play.""" global screen, logged_in, mode, difficulty pickle_in_logged_in = open("logged_in", "rb") # pickle in the data from file regarding w...
def get_move(): """This function references the global variable 'turn' to determine data about current turn and their data.""" if turn % 2 == 0: # if the global turn variable is odd then its player 2's turn color = (0, 0, 0) piece = 2 word = 'BLACK' else: # or else its player1's tu...
The main task of the code is to update the game board's visual representation by rendering pieces, highlighting valid moves with gray circles, displaying the number of pieces each move would add, handling turn skips when no moves are available, and checking for a winner. It also updates the display to reflect game stat...
def update_board(board): """This function acts as the viewing modeler by accepting the board and painting its changes throughout the game. It also updates the piece counters at the the bottom of the screen""" global neighbors, sandwiches, turn, previous_state for i in range(8): # iterates through list...
def check_winner(board): """Function that checks if the board has a winner by seeing if there are any available spots or if there are no neighbors and the previous turn there were no neighbors (stalemate).""" global winner, game_over, turn p1_pieces, p2_pieces = count_pieces(board)[0], count_pieces(boa...
The main task of the code is to implement the minimax algorithm with alpha-beta pruning to determine the optimal column for the AI to place its piece in a game, evaluating board states recursively up to a specified depth. It alternates between maximizing the AI's score and minimizing the opponent's score, pruning unnec...
def minimax(board, depth, alpha, beta, maximizingPlayer): """Function used to determine which column the AI should place their piece in. For any given board, it creates a copy and then deepens until specified depth (2, 4, 6). After reaches max depth it starts to build its way back up (out of the...
def check_winner(array): """This function evaluates whether there are any moves to be made. If there arent then player loses. It also checks to see whether all of the pieces have been collected or whether game will end in tie.""" global winner, game_over color, piece, king, word, turned, king_turn = get...
The code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for an AI in a turn-based game (likely Connect Four). It recursively evaluates all possible moves up to a specified depth, prioritizing maximizing the AI's score (when `maximizingPlayer=True`) or minimizing the opponent's sc...
def minimax(board, depth, alpha, beta, maximizingPlayer): """Function used to determine which column the AI should place their piece in. For any given board, it creates a copy and then deepens until specified depth (2, 4, 6). After reaches max depth it starts to build its way back up (out of the...
def get_collected(array): """This function counts the number of pieces each player has collected at the begining of the game (if game is resumed) instead of saving data to account.""" p1_pieces, p2_pieces = 0, 0 # set pieces counters to zero prior to counting for i in range(8): # draws board accordin...
The function 'playing_game' manages the core game loop, handling user input, turn progression, AI moves, and board updates. It processes events like mouse clicks and key presses, checks for a winner, updates the game state, and coordinates interactions between game elements. It also manages player turns, validates move...
def playing_game(board): """This function is called to commence the game and handles all interactions with the screen. It redirects events to their relevant functions. This is the brain of the game that re-formats and redirects data to be used in a meaningful manner.""" global turn, options, p1_collecte...
def update_board(board): """This function acts as the viewing modeler by accepting the board and painting its changes throughout the game. It also updates the piece counters at the the bottom of the screen""" global neighbors, sandwiches, turn, previous_state for i in range(8): # iterates through list...
This function manages the Othello game loop, handling user input, AI moves, board updates, and game state transitions. It processes events like mouse clicks for player moves, triggers AI decisions on its turn, updates the display, checks for game over conditions, and saves progress before exiting. It coordinates intera...
def playing_game(board): """This function is called to commence the game and handles all interactions with the screen. It redirects events to their relevant functions. This is the brain of the game that re-formats and redirects data to be used in a meaningful manner.""" global winner, turn, game_over, c...
def make_fonts_global(): """This font instantiates the font options as global variables to be used throughout the program.""" global font65, font80, font50 pg.font.init() font65 = pg.font.SysFont('Comic Sans MS', 65) font80 = pg.font.SysFont('Comic Sans MS', 80) font50 = pg.font.SysFont('Comic S...
The main task of the code is to initialize and start a checkers game by loading saved game data, setting global variables (screen, logged_in, mode, difficulty), reconstructing the game board from stored data or generating a new one, and launching the game loop via the playing_game function. It handles both new and resu...
def main(pg): """This is the main function that is called to start/restart checkers. It designates essential global variables and opens up the game data from files. It then commences the game by calling the playing_game function""" global screen, logged_in, mode, difficulty pickle_in_logged_in = open("...
def make_fonts_global(): """Function that makes all of the fonts into global variables.""" global font70, font50, font65, font27 font70 = pg.font.SysFont('Comic Sans MS', 70) font50 = pg.font.SysFont('Comic Sans MS', 50) font65 = pg.font.SysFont('Comic Sans MS', 65) font27 = pg.font.SysFont('Com...
The main task of the code is to initialize and start the Othello game by loading user data, setting global variables (screen, mode, difficulty), reconstructing the game board from saved progress or creating a new one, and launching the game loop via `playing_game(board)` to enable gameplay.
def main(pg): """This is the main function that is called to start/restart othello. It designates essential global variables and opens up the game data from files. It then commences the game by calling the playing_game function""" global screen, logged_in, mode, difficulty pickle_in_logged_in = open("l...
def is_cd_cmd(line): matches = re.findall("(\$ cd )([a-zA-Z\.\/]+)", line) return False if len(matches) == 0 else matches[0][1] def go_to_path(path, fs): # ['/', 'a', 'b'] -> /a/b if path[0] == "/": if len(path) == 1: return fs else: return go_to_path(path[1:], fs...
The function reconstructs a file system hierarchy from command-line logs by processing 'cd' commands to navigate directories, creating new directories, and adding files with their sizes. It maintains a navigation path to track the current directory, updates the file system structure (fs) with directories and files, and...
def reconstruct_fs(): navigation = [] for l in content: line = l.replace('\n', '') if is_cd_cmd(line): dir_name = is_cd_cmd(line) if ( dir_name == ".." ): navigation = navigation[:len(navigation)-1] elif len(fs) == 0: # empty fs...
def get_flux(self, pix_col, pix_row, herschelBand, galaxyName, sampleName): row = self.data['Object Name'] == galaxyName img_path = copy.deepcopy(self.data[herschelBand][row].values[0]) img = fits.open(img_path, memmap=False) # get clicked image try: header ...
The code fits observed flux data from Herschel bands to a greybody model, estimating parameters like temperature (T) and N_H2 column density. It converts flux units, performs non-linear regression using differential evolution, generates model predictions (Planck curves and TolTEC fluxes), and returns results or None on...
def fit(self, pix_row, pix_col, herschelBand, galaxyName, sampleName, time_hours, area_deg2, atmFactor, beta): ''' Get flux and fit it with greybody ''' self.beta = beta self.herschelBand = herschelBand map_flux = self.get_flux(pix_col, pix_row, herschelBand, galaxyName, ...
def fit(self, pix_row, pix_col, herschelBand, galaxyName, sampleName, time_hours, area_deg2, atmFactor, beta): ''' Get flux and fit it with greybody ''' self.beta = beta self.herschelBand = herschelBand map_flux = self.get_flux(pix_col, pix_row, herschelBand, galaxyName, ...
The main task of the code is to generate and update a fit plot, TolTEC map, and parameter table in a Dash application based on user inputs and fitting results. It processes Herschel and TolTEC data, calculates fit parameters, and dynamically updates visualizations and tables to reflect the current analysis state, handl...
def update_fit(self, galaxyName, sampleName, herschelBand, herschelClickData, sample, toltecBand, time_hours, area_deg2, atmFactor, beta, options): # , map_type ''' Updates fit figure, toltec figure, and table based on inputs from Dash page ''' #Make sure wavlength is a float ...
def save_db(log): # sqlite db conn = create_connection() c = conn.cursor() # Create table sql = '''INSERT INTO log(datetime, command, device, response) VALUES(?, ?, ?, ?) ''' c.execute(sql, log) # Save (commit) the changes conn.commit() conn.close() return 'Added log' de...
This function handles temperature data retrieval and control. For GET requests, it returns current temperature in Celsius, Fahrenheit, and Kelvin, logging the data. For other requests, it adjusts temperature based on 'mode', checks system status, updates logs, and executes temperature control. The core tasks are: loggi...
def temperature(mode): if request.method == 'GET': json = { "c": round(sensor.get_temperature()), "f": round(sensor.get_temperature(W1ThermSensor.DEGREES_F), 2), "k": round(sensor.get_temperature(W1ThermSensor.KELVIN), 2) } save_db((datetime.datetime.now(...
def check_status(): # sqlite db conn = create_connection() c = conn.cursor() # Create table sql = '''SELECT running FROM status WHERE id = 0''' c.execute(sql) res = c.fetchone()[0] # Save (commit) the changes conn.commit() conn.close() return res def save_status(running): ...
The main task of the code is to execute a heating process based on a specified mode for a given duration. It checks system status, sets the temperature, monitors elapsed time, and toggles a switch. If the mode is invalid, it returns an error. Upon completion, it logs the operation details to a database and resets syste...
def heat(mode, duration): status = check_status() if status == 1: save_status((0, 0)) time.sleep(1) if mode in modes: set_temperature(mode) else: return 'Temperature mode not found: ' + mode start_time = time.time() end_time = time.time() flip_switch(1) w...
def read_input(): input = {} file = open(sys.argv[1], "r") for line in file: line = line.strip() # Split the line by tab character tokens = line.split('\t') # Further split each token by space and flatten the list split_tokens = [item for token in tokens for item in...
The code reads input parameters, extracts scene data (spheres, lights, background, ambient), and renders a 3D image using ray tracing. It then saves the output as a PPM file named based on the input's "OUTPUT" field.
def main(): input = read_input() spheres = get_spheres(input) lights = get_lights(input) H = float(input["TOP"]) W = float(input["RIGHT"]) N = float(input["NEAR"]) bg = [float(bg_color) for bg_color in input["BACK"]] ambient = [float(a_color) for a_color in input["AMBIENT"]] image ...
def difficult_words(text): words = [] sentences = break_sentences(text) for sentence in sentences: words += [str(token) for token in sentence] diff_words_set = set() for word in words: syllable_count = syllables_count(word) if word not in easy_word_set and syllable_count >=...
The function calculates the Gunning Fog index, a readability score estimating the grade level needed to understand a text. It combines the percentage of difficult words (adjusted by 5) and average sentence length, weighted by 0.4, to determine the readability grade.
def gunning_fog(text): per_diff_words = (difficult_words(text) / word_count(text) * 100) + 5 grade = 0.4 * (avg_sentence_length(text) + per_diff_words) return grade
def word_count(text): sentences = break_sentences(text) words = 0 for sentence in sentences: words += len([token for token in sentence]) return words def difficult_words(text): words = [] sentences = break_sentences(text) for sentence in sentences: words += [str(token) for to...
This function calculates the Dale-Chall readability score for a given text by analyzing the percentage of easy words, average sentence length, and applying a correction factor. It returns the rounded score to assess text complexity for readability analysis.
def dale_chall_readability_score(text): words = word_count(text) count = word_count - difficult_words(text) if words > 0: per = float(count) / float(words) * 100 diff_words = 100 - per raw_score = (0.1579 * diff_words) + \ (0.0496 * avg_sentence_length(text)) if ...
def get_save_dir(self): return f'{self.save_dir}{os.sep}{self.get_user()}@{self.get_project_name()}' def get_jobs_attributes(self): if self.jobs_attributes is None: self.jobs_attributes = [job.attributes for job in self.get_jobs()] return self.jobs_attributes def jobs_information_csv...
The main task of the code is to analyze a project by saving GitLab CI/CD job data. It creates a directory, stores detailed job attributes in a JSON file, and generates a CSV summary of the job information for further analysis.
def analise_project(self): # Prepare the folder where we gonna download them Path(self.get_save_dir()).mkdir(parents=True, exist_ok=True) # Saving the complete jobs information with open(f'{self.get_save_dir()}{os.sep}repo-data-jobs-gitlab-ci.json', 'w', encoding='utf-8') as f: ...
def get_jobs_attributes(self): if self.jobs_attributes is None: self.jobs_attributes = [job.attributes for job in self.get_jobs()] return self.jobs_attributes def get_jobs(self): if self.jobs is None: self.jobs = self.project.jobs.list(all=True) if self.thres...
The code downloads job logs by retrieving job attributes and traces, validates metadata (commit/pipeline IDs), and saves each valid trace as a UTF-8 log file with a filename combining pipeline ID, commit SHA, and job ID in the specified directory.
def download_logs(self): jobs_attributes = self.get_jobs_attributes() jobs_trace = [job.trace() for job in self.get_jobs()] for trace, attribute in zip(jobs_trace, jobs_attributes): job_id = attribute['id'] if attribute['commit'] is N...
def get_data_parsed(self, force=False): if self.df_parsed is None or force: self.df_parsed = self.filter_data(self.get_data()) # Select the columns self.df_parsed = self.df_parsed[['job_id', 'job_name', 'sha', 'pipeline_id_y', 'la...
The main task of the code is to process and save filtered data and engineered features for each variant. It reads parsed data, cleans job names, iterates over variants, creates directories, filters dataframes per variant, exports filtered data to CSV, applies feature engineering, and saves engineered features to CSV, u...
def extract_by_variant(self): print("Reading data") df = self.get_data_parsed() variants = self.get_variants() print("Ok, parsing variants...") df2 = df.copy() df2['job_name'] = df2['job_name'].apply(lambda x: x.translate({ord(c): "_" for c in "!#$%^&*()[]{};:,.<>?|`~=+"...
def sign(self, num: int): if num > 0: return 1 else: return -1 def turn(self, direction: str = "right", turns: int = 1): for _ in range(turns): self.queue_instruction(f"turtle.turn{direction.capitalize()}()") def abs(self, num: int): if num > 0: ...
The code navigates a turtle to specified 3D coordinates by adjusting its orientation and position. It checks if the turtle is already at the target (x,y,z), returning True. If not, it corrects the x-axis by turning based on offset signs and direction, then moves forward. It adjusts the z-axis similarly before moving. F...
def go_to(self, x, y, z) -> bool: # reutrns true if the turtle is at the specified coordinates if self.x == x and self.y == y and self.z == z: return True # checks if the x value of the turtle is correct, and moves accordingly if not if self.x != x: if self.sign...
def up(self, dig: bool = False): if dig: self.dig("up") self.queue_instruction("turtle.up()") def turn(self, direction: str = "right", turns: int = 1): for _ in range(turns): self.queue_instruction(f"turtle.turn{direction.capitalize()}()") def down(self, dig: bool = False...
This code controls a mining entity's movement based on vertical positioning. It adjusts the entity's position by moving up/down and turning when not at the target y-level. When at the target level, it initiates a mining operation by recording start coordinates and fuel. If returning is True, it navigates back to the st...
def mine(self, yval: int = 0, yoffset: int = 0, returning: bool = False): if self.y < yval + yoffset: self.up(True) self.turn(turns=4) elif self.y > yval + yoffset: self.down(True) self.turn(turns=4) else: if not self.is_deep: ...
def getListOfAbsoluteLinksFromPropertySearchWebsite(urlFromSearchPropertyPage): bs4objectSearchPropertyPageHeadless = getSoupObjectFromHeadlessBrowser(urlFromSearchPropertyPage); listOfRelativeLinks = findAllTagsFromSoupObjectGivenTagTypeAndClass(bs4objectSearchPropertyPageHeadless, 'a', ...
The code scrapes property data from multiple websites by extracting links, parsing individual property pages with BeautifulSoup, and formatting details like price, area, and amenities. It then creates database objects for locations, contacts, property types, and extras, inserting them into related tables while managing...
def scrapeAndCreateObjects(listOfAllLinksOfPropertySearchWebsitesGivenANumber): for link in listOfAllLinksOfPropertySearchWebsitesGivenANumber: # we find a way to select all links of every property on the Property Search Website listOfAbsoluteLinks = getListOfAbsoluteLinksFromPropertySearchWebsite(...
def parse_arguments(args): parser = argparse.ArgumentParser(description='plot polynomial') parser.add_argument('start', type=float, help='first value in domain') parser.add_argument('end', type=float, help='last ...
The code trains a simple neural network with one hidden layer using the specified parameters, saves the trained model and training data (loss and prediction histories) via pickling, and optionally logs the model graph to TensorBoard.
def main(): args = parse_arguments(sys.argv[1:]) if have_tensorboard and args.tensorboard: writer = SummaryWriter() model = torch.nn.Sequential( torch.nn.Linear(1, args.num_hidden_layer_nodes), torch.nn.Tanh(), torch.nn.Linear(args.num_hidden_layer_nod...
def parse_grid_settings(self): """ Parses the settings defined in the init function to generate some parameters to improve quality of life """ self.grid_left = self.h_padding_grid self.grid_right = self.WIDTH - self.h_padding_grid self.grid_top = self.STATUS_HEIGHT ...
The main task of the code is to initialize a game window by parsing grid settings, drawing the game grid, updating the status area with initial parameters, and rendering the scoreboard based on the provided game state. It sets up the visual components of the game interface using the game_state data to reflect the curre...
def init_window(self, game_state): """ Initializes the window with the grid and status """ self.parse_grid_settings() self.draw_grid() self.draw_status(1, 0, None, game_state.first_player_uses) self.draw_scoreboard(game_state)
def input(self, x): # [batch, seq, dim] projected = self.input_proj(x) # [batch, seq, mp, dim//mp] projected = maybe_shard(projected, P("dp", None, "mp")) mp_split = jnp.reshape(projected, projected.shape[:-1] + (self.mp_num, -1)) mp_split = maybe_shard(mp_split, P("dp",...
This code processes input tensor `x` through a transformer-like block. It normalizes `x`, splits it into query (q), value (v), key (k), and feed-forward (ff) components. A causal mask is generated and combined with `attn_bias` to prevent future-sequence leakage. Self-attention is applied with masked attention, followed...
def __call__(self, x, attn_bias): x = self.norm(x) q, v, k, ff = self.input(x) # head_print("x.shape", x.shape) # head_print("attn_bias.shape", attn_bias.shape) seq_len = x.shape[1] causal_mask = np.tril(np.ones((seq_len, seq_len)))[None, :, :] bias = -1e10 * ...
def input(self, x): # [batch, seq, dim] projected = self.input_proj(x) # [batch, seq, mp, dim//mp] projected = maybe_shard(projected, P("dp", None, "mp")) mp_split = jnp.reshape(projected, projected.shape[:-1] + (self.mp_num, -1)) mp_split = maybe_shard(mp_split, P("dp",...
This function decodes one token in an autoregressive sequence model by applying self-attention with a causal mask, updating key-value caches, and combining outputs via a GLU feed-forward network. It normalizes input, projects to query/key/value heads, appends new KV pairs to the state, applies attention with masked bia...
def decode_once(self, decode_state, x, attn_bias): x = self.norm(x) assert x.shape[0] == 1 q, v, k, ff = self.input(x) # add new kv to end v = jnp.concatenate((decode_state["v"], v), axis=1)[1:] k = jnp.concatenate((decode_state["k"], k), axis=1)[1:] tokens_de...
def input(self, x): # [batch, seq, dim] projected = self.input_proj(x) # [batch, seq, mp, dim//mp] projected = maybe_shard(projected, P("dp", None, "mp")) mp_split = jnp.reshape(projected, projected.shape[:-1] + (self.mp_num, -1)) mp_split = maybe_shard(mp_split, P("dp",...
The code initializes a decoder's state by applying self-attention with causal masking and position bias, combining attention and feed-forward outputs, and returning the result along with intermediate states for autoregressive generation. It masks future tokens, adjusts attention bias, and prepares outputs for subsequen...
def get_init_decode_state(self, x, given_length, attn_bias): x = self.norm(x) q, v, k, ff = self.input(x) full_length = x.shape[1] masked_tokens = full_length - given_length causal_mask = np.tril(np.ones((full_length, full_length))) bias = -1e10 * (1. - causal_mask) ...
def get_file_metadata_by_query(self, query: str) -> list: """ Returns a list of responses based on the query. :param query: str - query string to query the Drive API. :return: list of responses. """ assert self.drive_service is not None result = list() try...
The main task of the code is to search for a Google Drive folder by name (with exact or subset matching) and retrieve its ID along with its child contents, including items in the Trash. It constructs a query based on the provided parameters, fetches metadata, processes results, and returns a structured dictionary conta...
def get_folder(self, folder_name: str, is_name_subset: bool = False): """ Fetches a dict of a given folder's ID and the children contained inside (if present), even the ones in "Trash". :param folder_name: str - name of the folder as saved in the Drive. :param is_name_subset: boo...
def get_file_metadata_by_query(self, query: str) -> list: """ Returns a list of responses based on the query. :param query: str - query string to query the Drive API. :return: list of responses. """ assert self.drive_service is not None result = list() try...
The main task of the code is to convert a Google Sheets file from a specified folder into a dictionary of DataFrames, where each key is a sheet name and the value is the corresponding data. It retrieves the file via Google Drive API, filters by folder and file name, extracts spreadsheet content, and processes sheets us...
def handle_inputs(self, folder, file_name="inputs", num_cols=-1, start_col=0): """ Converts Google Sheets file with `file_name` from a folder `user` into a dict of sheet-values. :param folder: str - name of the folder containing the file. :param file...
def select(node): while node.children: if not all(child.visits for child in node.children): # If any child has not been visited, visit it return expand(node) else: node = max(node.children, key=ucb) return node def expand(node): # Generate all possible chi...
The code implements Monte Carlo Tree Search (MCTS) to determine the optimal next move in a game. It iteratively selects nodes, expands the tree, simulates outcomes, and backpropagates results to update node values. After specified iterations, it returns the state of the child node with the highest visit count, represen...
def mcts(root_state, iterations): root = Node(root_state) for _ in range(iterations): selected_node = select(root) expanded_node = expand(selected_node) simulation_result = simulate(expanded_node) backpropagate(expanded_node, simulation_result) best_child = max(root.childre...
def start_game(): press_play() if pyautogui.pixel(849,442)[0] == 227: press_yes() time.sleep(2) else: press_next() time.sleep(.3) press_skip() time.sleep(.3) press_next() time.sleep(2) def wait_until_round_starts(): while True: if p...
The main task of the code is to determine the current stage of a game using pixel color checks via pyautogui, then execute corresponding stage-specific functions (play_stage_1/2/3) based on detected screen states. It first checks for the start screen, initiates gameplay, and then identifies the current round stage (1-3...
def main(): if pyautogui.pixel(1342, 109) == (254, 203, 0): print("We are at start screen") start_game() wait_until_round_starts() if pyautogui.pixel(186, 73)[0] == 151: print("in middle of round on stage 1") play_stage_1() play_stage_2() ...
def aggregate(self, clf, request): if request.path and utils.top_path(request.path): self.increment(self.paths, utils.top_path(request.path)) if clf.status: self.increment(self.codes, clf.status) if clf.auth_user and clf.auth_user != '-': ...
This method processes events by aggregating classifier and request data into statistics, maintaining a circular buffer for event rate tracking. For timer events, it generates 10s statistics and checks for alerts. It handles EVENT_LOG and EVENT_TIMER specifically, with warnings for unexpected events.
def __call__(self, event, parameter): if event == EVENT_LOG: clf = parameter['clf'] request = parameter['request'] # Keeps overall statistics self.aggregate(clf, request) # Keeps the circular buffer of events per second self.add_to_time_...
def getTransactionsFromNd(self, nd: dict): resultMap = {} # Map of id to items for i in nd.keys(): for j in nd[i]: if j in resultMap: resultMap[j].append(i) else: resultMap[j] = [i] return resultMap def populate_...
The code computes frequent itemsets using the LCM algorithm. It filters nodes by minimum support (`minSup`), sorts items, generates transactions, and employs backtracking to explore itemset combinations. Results are deduplicated, sorted by length (descending), and returned. The core task is **identifying all frequent i...
def lcm(self, nodes: dict, minSup: int): nd = copy.deepcopy(nodes) for key in nodes.keys(): if len(nodes[key]) < minSup: nd.pop(key, None) print(nd) allItems = list(nd.keys()) allItems.sort() print(allItems) print(self.getTransactionsFr...
def create_text(text, fonts, size, color): global _cached_text key = '|'.join(map(str, (fonts, size, color, text))) image = _cached_text.get(key, None) if image == None: font = get_font(fonts, size) image = font.render(text, True, color) _cached_text[key] = image return image...
The function `LevelInfoUpdate` renders game statistics (level, lives, ammo, bombs) and credits on the screen using Pygame, positioning text and icons within a defined area. It dynamically displays current level, lives, and inventory items, arranging ammo/bomb icons in rows, and adds author info and version at the botto...
def LevelInfoUpdate(): label = create_text('Level',font_preferences,32,(255,255,0)) screen.blit(label, (scorearea['x'] + scorearea['w'] // 2 - label.get_width() //2,30)) label = create_text(str(GameVars.LEVEL),font_preferences,32,(255,255,255)) screen.blit(label, (scorearea['x'] + scorearea['w'] // 2 ...
def GenerateBricks(): # First populate possible bricks possiblebricks = [] for j in range(len(GameVars.LEVELOPTS[1])): for i in range(GameVars.LEVELOPTS[1][j][1]): possiblebricks.append(GameVars.LEVELOPTS[1][j][0]) b = [] cols = GameVars.LEVELOPTS[0][0] rows = GameVars.LEVEL...
This function renders the game screen based on the current game state, updating visual elements like the board, ball, bricks, ammo, and bomb. It displays appropriate messages for game states such as "NEW," "SERVE," "LEVELUP," or terminal states like "GAMEWON" and "GAMEOVER," including high scores and user prompts. It a...
def setScreen(): global Bricks # blit background screen.blit(backdrop,backdropbox) if GameVars.GAMESTATE != GameStates.GAMEOVER and GameVars.GAMESTATE != GameStates.GAMEWON and GameVars.GAMESTATE != GameStates.PLAYERHIGHSCORED: # blit board board.update(screen) # blit ball b...
def addJs(x,y,st): if x not in js[st]: js[st][x] = [] js[st][x].append(y) def upAddSp(x,k,z): js['adds'][x][k] = int(z) def subIt(ls): sub = int(ls[0]) for i in range(1,len(ls)): sub -= int(ls[i]) return sub def addAll(): add = 0 for i in range(0,len(js['names'])): ...
This function processes a list of string-formatted data entries, parsing JSON values and organizing them into a structured dictionary. It iterates through keys and values to populate 'names' and 'adds' fields, ensuring all entries are tracked in 'have' via repeated checks and updates. The core task involves parsing, ca...
def getTraff(obj1): names = [] for i in range(0,len(obj1)): js[str(obj1[i].split(':')[0])] = json.loads(obj1[i].split(':')[1]) for key, value in js.items(): names.append(str(key)) js['have'],js['names'],js['adds'] = [],names,{} for j in range(0,len(js['names'])): na = js['nam...
def send(command): # little endian (<) ser.write(struct.pack("<B", command)) ser.flush() def get_response_data(): # Get the response header, should be Header.SIZE bytes header = Header() data = ser.read(Header.SIZE) if len(data) != Header.SIZE: log.error(f"Read {len(data)}/{Header.S...
The main task of the code is to request battery information by sending a BATTERY command, validate the response, and return a Battery object populated with parsed payload data if successful.
def battery(): log.debug("BATTERY") send(Command.BATTERY) response = get_response_data() if response is None or response.header.status != Status.SUCCESS: abort(ERROR) battery = Battery() battery.unpack(response.payload) return battery
def ping(): log.debug("PING") send(Command.PING) response = get_response_data() if response is None or response.header.status != Status.SUCCESS: log.error("Received invalid ping response") return False log.success("Received valid ping response") return True def abort(result): ...
The main task of the code is to establish a serial link by repeatedly attempting to ping a device. If pinging fails, it logs warnings, resets the device, and retries up to a maximum limit (MAX_RETRIES). If all attempts fail, it aborts with an error. Upon successful ping, it logs a success message, indicating the serial...
def handshake(): log.info("Initiating handshake") tries = 0 while not ping(): tries += 1 log.warning(f"Ping attempt {tries} failed") if tries > MAX_RETRIES: log.error(f"Failed to establish serial link") abort(ERROR) log.info("Resetting Fusion") ...
def send(command): # little endian (<) ser.write(struct.pack("<B", command)) ser.flush() def get_response_data(): # Get the response header, should be Header.SIZE bytes header = Header() data = ser.read(Header.SIZE) if len(data) != Header.SIZE: log.error(f"Read {len(data)}/{Header.S...
The main task of the code is to execute a sample command, send it, retrieve and validate the response, and return parsed sensor data if successful. It logs a debug message, sends the command, checks the response status, aborts on failure, and returns parsed data upon success.
def sample(): log.debug("SAMPLE") send(Command.SAMPLE) response = get_response_data() if response is None or response.header.status != Status.SUCCESS: abort(ERROR) return parse_sensor_data(response.payload)
def send(command): # little endian (<) ser.write(struct.pack("<B", command)) ser.flush() def get_response_data(): # Get the response header, should be Header.SIZE bytes header = Header() data = ser.read(Header.SIZE) if len(data) != Header.SIZE: log.error(f"Read {len(data)}/{Header.S...
The function `burst()` requests a burst of sensor samples if the pending count is below the burst size, sends a command, processes the response, validates success status, parses sensor data, updates the pending count, and returns the parsed sensor data or aborts on errors.
def burst(): global pending if pending < BURST_SIZE: log.debug(f"Requesting {BURST_SIZE} sensor samples") log.debug("BURST") send(Command.BURST) pending += BURST_SIZE response = get_response_data() if response is None or response.header.status != Status.SUCCESS: ...
def abort(result): close() log.success("Ending program") exit(result) def purge(): while True: size = len(ser.read(PURGE_SIZE)) if size == 0: break log.info(f"Discarding {size} B of remnant data") ser.reset_input_buffer() ser.reset_output_buffer() log.suc...
The code opens a serial port with specified parameters, handles exceptions, sets up a signal handler for Ctrl+C, purges data, logs success, and initiates a handshake if synchronization is enabled.
def open(port, sync = True): global ser try: ser = serial.Serial( port=port, baudrate=BAUDRATE, stopbits=serial.STOPBITS_ONE, timeout=TIMEOUT_S, bytesize=serial.EIGHTBITS ) except Exception as e: log.error(f"Error opening se...
def get_buggy_methods(self, submission): buggy_methods = [] with open(self.method_coverage_json) as f: data = json.load(f) for method, coverage in data[submission].items(): if coverage["num"] > 0: buggy_methods.append(method) return buggy_methods d...
The main task of the code is to generate intermediate submissions by isolating and fixing individual buggy methods in a given submission. It creates a directory for each submission, identifies buggy methods, and for each, copies the submission, replaces tests, injects the correct method, and updates the intermediate to...
def create_intermediates(self, submission): intermediate_submission = self.intermediates_path / submission if not intermediate_submission.exists(): os.mkdir(intermediate_submission) buggy_methods = self.get_buggy_methods(submission) # self.count_purged_solutions += len(buggy_...