dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def check_categorical_numerical(self, plots): plotable = True categorical = None order = None for plt in plots: # exclude plots like vlines, which don't have y data if len(plt['ys']) != 0: if categorical == None: # define y_cate...
This function renders a customizable plot with numerical or categorical y-axes, applying user-defined limits, decimal formatting, and labels. It handles multi-y-axis configurations, calculates plot dimensions, draws axes, ticks, and data points, and returns a py5_graphics object if requested, or updates the plot direct...
def show(self, x_decimals=None, title=None, xlabel=None, ylabel=None, y_decimals=None, ylimit=(None, None), to_py5image=False, y_decimals_1=None, ylimit_1=(None, None), empty_warning=True, show_outline=False, show_helper_lines=False): """If to_py5image=True, this function will not dra...
def construct_total_order(partial_order): total_order = [] i = 0 for step in partial_order['steps']: if len(total_order) < 2: total_order.append(step['step_id']) continue if step['step_id'] in total_order: continue predecessors = get_recursive_pred...
The main task of the code is to construct a Gantt chart plan by inserting tasks into a database with calculated start/end times, ensuring steps fit within the overall duration. It schedules steps with random start times, tracks dependencies, and inserts tasks/effects/links, returning True if successful or False if the ...
def construct_gantt_total_order_plan(partial_plan, initial_action): initial_task = db.tasks.find_one({'action': str(initial_action)}) goal_task = db.tasks.find_one({'action': "2"}) start = datetime.strptime(initial_task['end_date'], '%Y-%m-%d %H:%M') end = datetime.strptime(goal_task['start_date'], '%Y...
def parse_conditions(conditions): condition_objects = conditions.split("; ") conditions = [] for condition_object in condition_objects: if condition_object == '': continue condition_value = condition_object.split(" = ") if len(condition_value) != 2: continue ...
The main task of the code is to generate a Gantt chart plan by planning a sequence of actions from an initial state to a goal state. It retrieves database actions, filters used ones, constructs steps and goals, applies a partial-order planner, and returns a total-order Gantt plan if successful, otherwise False.
def plan_gantt_actions(initial_action): causal_links = [] ordering_constraints = [] steps = [] goals = [] actions = [] db_actions = db.actions.find() # handling recalculation db_current_tasks = db.tasks.find() used_actions = [] for task in db_current_tasks: action = int(...
def get_recursive_effects(task_id): effects = [] current_task_id = int(task_id) while True: if current_task_id == 1: break last_link = db.links.find_one({'target': current_task_id}) predecessor = db.tasks.find_one({'task_id': last_link['source']}) predecessor_effe...
The main task of the code is to update a task's details in a database, including handling failure states, managing preconditions/effects, and ensuring data consistency. It acquires a semaphore for concurrency, checks form inputs to determine task failure status, updates task fields (text, dates, progress, etc.), modifi...
def update_task(task_id): sem.acquire() task_checkboxes = request.form["failed"] task_failed = "step_failed" in task_checkboxes print(task_failed, flush=True) color = 'rgb(61,185,211)' fail_will_be_handled = False if task_failed: color = 'rgb(245, 66, 87)' preconditions = "" ...
def dw(inp,trainning,nLay): """ This is the Dw block as defined in the Fig. 1 of the MoDL paper It creates an n-layer (nLay) residual learning CNN. Convolution filters are of size 3x3 and 64 such filters are there. nw: It is the learned noise dw: it is the output of residual learning after addin...
This function constructs a neural network model by iteratively applying complex-to-real conversions, gradient-based operations (AG/MG), and layer-wise computations. It processes inputs (atb, mask, mu, sig) through K layers, generating intermediate outputs (dc, dw) and updating parameters using specified gradient method...
def makeModel(atb,mask,mu,sig,training,nLayers,K,gradientMethod): """ This is the main function that creates the model. """ # mask = tf.constant(mask,dtype = tf.complex64,name = 'mask') out={} atb = atb[0,:,:,:] mask = mask[0,:,:,:] sig = sig[0,:,:,:] mu = mu[0,:,:,:] # print(a...
def dw(inp,trainning,nLay): """ This is the Dw block as defined in the Fig. 1 of the MoDL paper It creates an n-layer (nLay) residual learning CNN. Convolution filters are of size 3x3 and 64 such filters are there. nw: It is the learned noise dw: it is the output of residual learning after addin...
This function constructs a neural network model by iteratively processing input data through multiple layers (K iterations). It applies gradient-based updates (AG/MG methods) to refine outputs, using parameters like mask, mu, and sig. The model computes intermediate results ('dc', 'dw') and returns them in a dictionary...
def makeModel(atb,mask,mu,sig,training,nLayers,K,gradientMethod): """ This is the main function that creates the model. """ # mask = tf.constant(mask,dtype = tf.complex64,name = 'mask') out={} out['dc0']=c2r(atb) with tf.name_scope('myModel'): with tfv.variable_scope('Wts',reuse=tf...
def _is_packet_limit_reached(self) -> bool: return self.packet_limit is not None and len(self.items) >= self.packet_limit def flush(self, reason): _log(self.env.now, self.name, f"Flushing {len(self.items)} packets") self.interrupt_trace.append((self.env.now, [packet.ip for packet in self.items],...
The code handles adding a packet to a buffer, checks if the packet limit is reached, and flushes the buffer if necessary. It also resets a packet timer when a time limit is set, initiating a process to manage timing constraints. The method ensures compliance with both packet count and time-based thresholds, maintaining...
def put(self, packet: Packet): """Overwrite: After putting we check if the buffers packet limit was reached and flush if so""" super().put(packet) if self._is_packet_limit_reached(): self.flush("packet_limit") if self.packet_time_limit is not None: self._reset_pac...
def connection_possible(self): """ Check if the connection to the Run Registry is possible. Example: >>> client = RunRegistryClient() >>> client.connection_possible() True :return: True when connection to Run Registry was successful """ if self._...
The `execute_query` method executes arbitrary SQL queries with constraints on table references, aliases, and parameter types. It checks connection validity, generates a query ID, handles pagination for large results, and returns JSON data based on the query. Parameters include the SQL string and optional media type, wi...
def execute_query(self, query, media_type=None): """ Executes an arbitrary SQL query GET: /query/{query_id} Limitations: - tables referred by namespace.table - all tables used must have the unique alias in a query - only tables that share the same connection ...
def __clock_sleep(self): time.sleep(self.__get_clock()) def __laser_matrix_processing(self): """get laser data from node""" return [self.node_.sensor.laser_scan_ranges_front(), self.node_.sensor.laser_scan_ranges_left(), self.node_.sensor.laser_scan_ranges_right()...
The main task of the code is to execute a control loop that processes laser sensor data from multiple directions, updates system modes and movement supervision, logs information, and maintains a previous mode state. It periodically sleeps, retrieves and processes sensor data, supervises operational modes, manages movem...
def __loop_callback_(self): """planner loop""" self.__clock_sleep() self.laser_data_front_, \ self.laser_data_left_, \ self.laser_data_right_, \ self.laser_data_view_left_, \ self.laser_data_view_front_, \ self.laser_data_view_right_ = self.__laser_matrix...
def DetectScreenOnPosition(self): self.ImageProcessing.original_image = self.TakePicture() self.ImageProcessing.DetectScreen(False) if self.ImageProcessing.screenmode != 0: txt = "Screen detected, screen mode is " + str(self.ImageProcessing.screenmode) result = True ...
This function navigates a robot to locate a screen by executing a predefined movement sequence. It checks for screen detection at each position, processes the screen data (specifically for silver screens), and sends results to a robot if successful. If the screen isn't found, it updates status and returns to the origin...
def FindAndReadScreen(self): # takes picture and searches for screen movement_to_find_screen = [['up', self.searchingstep], ["right", self.searchingstep], ["down", self.searchingstep], ["down", self.searchingstep], ["left", self.searc...
def get_default_ts(self): """ This fun helps to return next day date from today in Y/m/d format :rtype: str """ self.log.debug("get_default_ts") return (datetime.now() + timedelta(days=1)).strftime("%Y/%m/%d") def get_oldest_date(self, ts): """ This fun...
The main task of the code is to retrieve email messages from a specified date, update the last known message timestamp, and fetch new messages since the last check. It uses a disk-based dictionary to track the latest message timestamp, adjusts the retrieval start date based on this value, and executes two history fetch...
def start(self): self.log.debug("start") # Gets next day date from current date as before_ts in 'yr/m/d' format # and check for last_msg_ts key in diskdict file before_ts = self.get_default_ts() last_msg_ts = self.dd.get("last_msg_ts", 0) # If any messages present in di...
def scale_image(self, in_file, out_file, size): if self._sticker_has_animation: ffmpeg.input(in_file, f="apng").filter( "scale", w=f"if(gt(iw,ih),{size},-1)", h=f"if(gt(iw,ih),-1,{size})" ).output(out_file, pix_fmt="rgba", f="apng").run(quiet=True) else: ...
The code processes tasks from a queue by applying a sequence of image operations (scaling, overlaying, alpha removal, format conversion) to input images, generating intermediate files, and saving the final output. It handles errors during ffmpeg processing, logs exceptions, and ensures tasks are marked as completed in ...
def run(self): while not self.queue.empty(): try: task: ProcessTask = self.queue.get_nowait() except queue.Empty: continue self._current_sticker_id = str(task.sticker_id) try: curr_in = task.in_img fo...
def helper__get_week_dates(): # Get datetime objects for start/end dates of week date = datetime.today() iso_week_date = date.strftime('%V') # Week starts on Sunday if date.strftime("%A") == 'Sunday': iso_week_date = int(iso_week_date) + 1 week_start = date.strptime(f"{date.strftime(...
The main task of the code is to generate a webpage displaying the latest Wordle submissions, current weekly champion, and related statistics. It calculates today's puzzle number, retrieves recent submissions, determines weekly dates, identifies weekly champions, and prepares context data for rendering a template showin...
def index(request): WORDLE_PUZZLE_NUM_TODAY = (datetime.today() - WORDLE_START_DATE).days latest_submission_list = WordleSubmission.objects.filter(wordle_number = WORDLE_PUZZLE_NUM_TODAY).order_by('-date_submitted') submitters = Submitter.objects.all().order_by('name') week_start, week_finish, week_num ...
def rangeOfNthSequence(mafLines, n): """Get the range of lines associated with the Nth sequence.""" start = indexOfNthSequence(mafLines, n) stop = start + 1 while stop < len(mafLines): line = mafLines[stop] if line[0] not in "qi": break stop += 1 return start, stop def isCano...
This function rearranges sequences in a MAF file by rotating them such that the nth sequence becomes the first, adjusts orientation if necessary, and prints the modified MAF content.
def swapOneMaf(opts, mafLines): start, stop = rangeOfNthSequence(mafLines, opts.n) mafLines[1:stop] = mafLines[start:stop] + mafLines[1:start] if not isCanonicalStrand(mafLines[1]): mafLines = flippedMaf(mafLines) for i in mafLines: print(i, end="") print()
def find_comparable_kmers(df_with_occurances,kmer,allowed_deviation=0.1,excluded=[]): occ=df_with_occurances[df_with_occurances.kmer==kmer].occurrence occ=int(occ) possible_kmer=df_with_occurances[(df_with_occurances.kmer!=kmer)&(df_with_occurances.occurrence<(occ+allowed_deviation*occ))&(df_with_occurances...
This function compares k-mers with their comparable counterparts by calculating Cohen's D effect sizes between correlation matrices and performing GO term analyses to identify functional differences. It generates directories for each k-mer, computes statistical comparisons, and outputs results as CSV files and GO annot...
def kmer_vs_comp_kmer(kmers,df_occurence,genes,df_corr, pdf="",out_dir="", fasta_file=""): bins=np.linspace(-1,1,41) #pp=PdfPages(pdf) all_pos_kmers=[find_comparable_kmers(df_occurence,kmer,excluded=kmers) for kmer in kmers] for count,kmer in enume...
def newton_direction(A, x, b, P, q, t): return - np.matmul(np.linalg.pinv(objective_hessian(A, x, b, P, q, t)), objective_grad(A, x, b, P, q, t)) def newton_stopping_criterion(newton_step, A, x, b, P, q, t): return abs(np.matmul(np.matmul(newton_step.T, objective_hessian(A, x, b, P, q, t)), newton_step)) def ba...
(The code implements Newton's method for solving an optimization problem, iteratively updating the solution $ x $ using a backtracking line search to determine the step size. It computes the Newton direction at each iteration and halts when the stopping criterion (related to the Newton step's norm) falls below a thresh...
def newton_method(A, x0, b, P, q, t): newton_step = newton_direction(A, x0, b, P, q, t) epsilon = 20 x = x0 iteration = 0 while newton_stopping_criterion(newton_step, A, x, b, P, q, t)/2 > epsilon: step_size = backtracking_line_search(A, x, b, newton_step, P, q, t) x = x + step_si...
def r_dual(A, x, b, P, q, lam): return quadratic_grad(A, x, b) + np.matmul(P.T, lam) def quadratic_hessian(A): return A def r_cent(x, P, q, lam, t): return - np.matmul(np.diag(np.reshape(lam, -1)), (np.matmul(P, x) - q)) - np.ones([np.shape(P)[0], 1]) / t def line_search(A, x, b, P, q, lam, delta_x, delta_l...
The function implements a **primal-dual interior-point method** for solving a convex optimization problem. It iteratively updates primal variables `x` and dual variables `lam` using Newton steps, tracking duality gaps and residuals. The algorithm computes search directions via a linear system involving the Hessian and ...
def primal_dual_interior_point(A, x, b, P, q, lam, mu): duality_gaps = [] r_feas = [] iterations = [] m, n = np.shape(P) iteration = 0 while True: iteration += 1 iterations.append(iteration) etta = - np.matmul((np.matmul(P, x) - q).T, lam)[0, 0] t = mu * m / et...
def calculate_pauli_hamiltonian(molecule_name, distance ,map_type = 'parity'): if molecule_name =='H2': freeze_list = [] remove_list = [] molecular_coordinates = "H 0 0 0; H 0 0 " + str(distance) elif molecule_name == 'LiH': freeze_list = [0,6] remove_list = [4,8] ...
The function processes a molecular Hamiltonian by calculating its Pauli terms, optimizing measurements, grouping Pauli operators, selecting an ansatz based on orbital/particle counts, and returning the grouped Hamiltonian with ansatz details for quantum computation.
def main(molecule_name: str ,distance: float ,n: int , m: int , ansatz: str) : """ n(int): number of orbitals m(int): number of particles distance(int): interatomic distance ansatz(str): value should be 'simple' or 'num_particle_preserving' """ pauli_ham_dict = calculate_pauli_hami...
def actualizar_ventana(self): """Actualizar imagenes en la ventana y mostrar ventana actual.""" self.ventana.blit(self.config.bg_menu,(0,0)) # pygame.Rect(415, 353, 350, 200) # pygame.draw.rect(self.ventana,(0,0,0),(415, 353), 350, 200) # Redibuja el fondo del juego ACTI...
The code runs the main game loop, updating the window, handling events, and managing AI moves when in AI mode. It checks for win conditions and stops the game if active, maintaining a 60 FPS frame rate.
def run_game(self): # Bucle principal del juego while not self.game_over: self.actualizar_ventana() self.revisar_eventos() if (self.game_mode == "ai" and self.player_current == 1) and self.board.get_empty_cell()!=[]: self.ia_move() if self...
def checkToken(request): token = request.headers.get('Authorization') if(token == 'Bearer hWd3uNMVpjaRAbPs9Nt3'): return True return False def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sql.connect(DATABASE) return db def refresh_device_session...
This function adds or updates a device in the database based on provided JSON data. It checks the user's token, verifies device existence, inserts new records or updates existing ones, handles errors, commits changes, and returns the device details in JSON format.
def add_device(): if not checkToken(request): app.logger.debug("Token is invalid") abort(404) try: username = session.get('username') data = request.json db = get_db() cur = db.cursor() cur.execute("SELECT * FROM device WHERE username=? AND devId=?", (user...
def checkToken(request): token = request.headers.get('Authorization') if(token == 'Bearer hWd3uNMVpjaRAbPs9Nt3'): return True return False def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sql.connect(DATABASE) return db def un_subscribe(devId): ...
The function deletes a device from the database based on `devId` and the current user's username after validating the token. It checks for the device's existence, executes deletion, commits changes, unsubscribes the device, refreshes sessions, and returns `devId` on success. Errors trigger rollback and logging, returni...
def delete_device(devId): if not checkToken(request): app.logger.debug("Token is invalid") abort(404) try: username = session.get('username') db = get_db() cur = db.cursor() cur.execute("SELECT * FROM device WHERE devId=? AND username=?", (devId,username)) ...
def loadjobs(self): self.log_msg("Load JOBS from DB ...") cur = self.db.cursor() cur.execute("SELECT * FROM timer") rows = cur.fetchall() for row in rows: self.schedulejob(row[0], row[1], row[2], row[3], row[4]) return True def run_schedule(self): whil...
The code repeatedly attempts to load and execute scheduled jobs up to three times, with a 10-second delay between attempts. It logs any exceptions during execution and increments a counter (rc) until it reaches 3, then returns the counter value.
def run(self): rc = 0 while rc < 3: try: # if not self.schedulejob(): # rc = 3 if self.loadjobs(): self.run_schedule() time.sleep(10) except Exception as e: self.log_msg(st...
def get_UA(maxValence_list, valence_list): """ """ UA = [] DU = [] for i, (maxValence, valence) in enumerate(zip(maxValence_list, valence_list)): if not maxValence - valence > 0: continue UA.append(i) DU.append(maxValence - valence) return UA, DU def BO_is_OK(...
The function `AC2BO` generates a valid bond order (BO) matrix from an adjacency matrix (AC) of a molecular graph, considering atomic valences, charge, and unsaturation constraints. It iterates through possible valence combinations, checks bond validity, and returns the optimal BO matrix meeting criteria like charge bal...
def AC2BO(AC, atoms, charge, allow_charged_fragments=True, use_graph=True): """ implemenation of algorithm shown in Figure 2 UA: unsaturated atoms DU: degree of unsaturation (u matrix in Figure) best_BO: Bcurr in Figure """ global atomic_valence global atomic_valence_electrons ...
def xyz2AC(atoms, xyz, charge, use_huckel=False): """ atoms and coordinates to atom connectivity (AC) args: atoms - int atom types xyz - coordinates charge - molecule charge optional: use_huckel - Use Huckel method for atom connecitivty returns ac - atom c...
The main task of the code is to generate RDKit mol objects from atomic coordinates and types by determining atom connectivity, assigning bond orders, incorporating charge information, and embedding chiral/stereochemistry details. It uses methods like Huckel or graph-based connectivity prediction, handles charged fragme...
def xyz2mol(atoms, coordinates, charge=0, allow_charged_fragments=True, use_graph=True, use_huckel=False, embed_chiral=True, use_atom_maps=False): """ Generate a rdkit molobj from atoms, coordinates and a total_charge. args: atoms - list of atom types (int) coordinat...
def _det_m(self, word): """ Determinse the number of {m} or the number of times the grouping CV repeats in the word. If there's less than one CV between the first consonant and last vowel, the number is 0. Examples: * Tree, by: m = 0 * Trouble, oats, trees, ivy: m = 1 * T...
This function implements the first step of the Porter stemming algorithm, which reduces plurals and past participles by removing suffixes like 'sses', 'ies', 's', 'eed', 'ed', and 'ing'. It applies conditional rules to adjust the stem, including adding 'e' or removing letters based on vowel/consonant checks, and conver...
def _porter_step_1(self, word): """ First step of the algorithm. Deals with plurals and past participles. Parameters ---------- word: str The word to be stemmed. """ stem = word stepb2 = False #Step 1a if stem.endswith('sses'):...
def _det_m(self, word): """ Determinse the number of {m} or the number of times the grouping CV repeats in the word. If there's less than one CV between the first consonant and last vowel, the number is 0. Examples: * Tree, by: m = 0 * Trouble, oats, trees, ivy: m = 1 * T...
This function performs the final two steps of the Porter stemming algorithm to further reduce a word stem. It removes trailing 'e's under specific conditions (5a) and trailing 'l's if preceded by a vowel (5b), based on vowel count and suffix checks. The goal is to finalize the stem by trimming unnecessary letters accor...
def _porter_step_5(self, stem): """ The last step of the algorithm. Tides up what is left. Parameters ---------- stem: str The stem to be further stemmed. """ temp = stem #Step 5a if self._det_m(temp)>1 and temp.endswith('e'): ...
def _porter_step_1(self, word): """ First step of the algorithm. Deals with plurals and past participles. Parameters ---------- word: str The word to be stemmed. """ stem = word stepb2 = False #Step 1a if stem.endswith('sses'):...
The main task of the code is to perform stemming on a given word using the Porter stemmer algorithm. It converts the input to lowercase, handles Token objects by extracting their text, and sequentially applies five Porter stemming steps to reduce the word to its stem form, returning the processed result.
def Pstem(self, word): """ Applies stemming to a word. Parameters ---------- word: str or Token The word or Token word to be lemmatized. """ if isinstance(word, Token): word = word.get() stem = word.lower().strip() stem = s...
def get_playback_time(date: datetime.datetime) -> list[any]: if (is_morning(date)): return MORNING elif (is_afternoon(date)): return AFTERNOON elif (is_nigth(date)): return NIGHT def filter_by_day(current_date: datetime, data: list[any]) -> list[any]: result = [] for row in d...
The function generates a personalized playlist based on user playback history or favorites, using a recommendation system. It checks for existing playbacks, filters by time, identifies frequent tracks, and creates a playlist with the top songs. If no playbacks exist, it defaults to favorite tracks. It ensures uniquenes...
def create_custom_playlist(id, amount_songs: int = 10) -> list[int] | str: """Creates a new playlist automatically generated either based on playbacks or preferred tracks""" # date_now = datetime.datetime(2023, 3, 10, 18, 0, 0) # debug date date_now = datetime.datetime.now() playback_time = get_playback...
def relieve_stance(jds: List[Dict]) -> List[Dict]: jds = copy.deepcopy(jds) label_map = { 'strongly_supporting': 'supporting', 'supporting': 'supporting', 'no_position_or_mixed_position': 'no_position', 'not_supporting': 'not_supporting', 'opposing': 'not_supporting', ...
The main task of the code is to evaluate the performance of a system's predictions against gold-standard labels by reading JSON-line files, optionally converting 5-class stance labels to 3-class labels, and computing document, overlap, and strict F1 scores. The results are then printed as a JSON-formatted summary.
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-g", type=str, help="The gold jsonline file", ) parser.add_argument( "-s", type=str, help="The system prediction jsonline file", ) parser.add_argument( "--relieve_stance",...
def back_until_ball_visible(car): ball_x = ball_pos_in_cam(car) while ball_x == 0: drive(car, False, 0) ball_x = ball_pos_in_cam(car) def turn_backwards(car, mask_func): ball_x = ball_pos_in_cam(car) gate_x = gate_pos_in_cam(car, mask_func) if ball_x < gate_x - EPSILON_2: for _ in range(FEW_STEPS_...
The code's main task is to guide a car to move a ball between two bars and drive it through a gate. It involves backing up to locate the ball, aligning it between bars using color masks (blue), adjusting orientation, and finally driving forward into a green-masked gate. The process combines object detection, alignment,...
def move_a_ball(car): back_until_ball_visible(car) turn_backwards(car, mask_blue) back_until_ball_between_bars(car, mask_blue) find_a_ball(car) turn_to_object(car, ball_pos_in_cam) turn_backwards(car, mask_blue) back_until_ball_between_bars(car, mask_blue) find_a_ball(car) forward_until_gate_not_...
def convertFileToDictionary(file): dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), file) file = open(dir, "r") CFG = {} baris = file.readline() while baris != "": head, body = baris.replace("\n", "").split(" -> ") if head not in CFG.keys(): CFG...
The code converts a Context-Free Grammar (CFG) into Chomsky Normal Form (CNF) by: (1) introducing a new start symbol if needed, (2) removing unit productions, (3) splitting long productions into binary rules using intermediate symbols, and (4) replacing adjacent terminals with new non-terminals. The result is a grammar...
def CFG_to_CNF(file): CFG = convertFileToDictionary(file) # Langkah Pertama: jika ada Start Symbol 'S' di bagian kanan panah, maka menambahkan production symbol baru yaitu S' CFG = startProduction(CFG) # Kedua: Remove unit productions pada grammar. CFG = removeUnitProduction(CFG) # Ketiga: Re...
def dilate(current_vertex,k): current_vertex *= k return current_vertex def translate(current_vertex,dx,dy,dz): for a in current_vertex: a += [dx,dy,dz] return current_vertex def shear(current_vertex,axis,k1,k2): ## Inisialisation Zero Matrix s = (3,3) shear_matrix = np.zeros(s) shear_matrix[0][0] = 1 shear_...
This code applies geometric transformations to a vertex based on the given command, such as dilation, translation, shear, stretch, reflection, or rotation. It routes the command to the appropriate function, handling 2D/3D cases and custom operations, then returns the transformed vertex.
def action_command(current_vertex,command): if(command[0] == 'dilate'): current_vertex = dilate(current_vertex,float(command[1])) elif(command[0] == 'translate'): if(dimensi == 2): current_vertex = translate(current_vertex,float(command[1]),float(command[2]),float(0)) else: current_vertex = translate(curr...
def time_start(self, fn, point): self.timers.setdefault(fn, {'start':0, 'finish':0}) self.timers[fn][point] = time.time() def getAllSimData(self): """ Gets all data from sim in one call """ self.time_start("getAllSimData", "start") self.car_state = self.client...
This function applies user-provided vehicle controls (steering, throttle, brake) to a simulation, updates the vehicle's state, and renders nearby checkpoints. It bypasses automatic control calculations, directly sending input controls to the simulation client while logging timing metrics for performance tracking.
def step(self, steering=0, throttle=0, brake=0): self.time_start("step", "start") if not MANUAL_DRIVING: #self.simContinueForTime(0.3) pass self.getAllSimData() car_controls = fsds.CarControls() #target_speed = 10 #car_controls...
def sorted_search(root: Path, components: tuple[str, ...]) -> list[tuple[Path, Mapping]]: return sorted(search(root, components), key=get_search_result_key) def get_student(mapping: Mapping) -> Student: return STUDENT_JOINER.join(mapping.get(GROUP, ()) + mapping[STUDENT]) def get_problem(mapping: Mapping) -> Pr...
The code analyzes code submissions by extracting n-grams from files, grouping them by student and problem, comparing submissions for similarities using n-gram overlaps, and returning an analysis object with statistics on submissions, problems, students, and matching pairs based on common tokens.
def analyze(root: Path, components: tuple[str, ...], min_n: int, max_n: int, min_ratio: float, max_clique: int, tracker: ProgressTracker) -> Analysis: tracker('Discovering submissions...') submissions = sorted_search(root, components) ngrams_by_group: defaultdict[Ngram, set[Group]] = defaultdict...
def process_module(base_name, dry, path, pw, url, user, status_data:Data): url += '/' + path.name logger.debug('url: %s', url) jcr_primary_type = 'pant:module' data = _generate_data(jcr_primary_type, base_name, path.name, asccidoc_type='nt:file') # This is needed to add a new module version, otherwi...
The function processes files (modules, resources, assemblies) by constructing a Pantheon API URL, skipping hidden folders, and using type-specific handlers (process_module, process_resource, process_assembly) to upload content via the sling API. It updates status data with upload type and publishing status, ensuring pr...
def process_file(path, filetype, server, sandbox, repository, directory, dry, user, pw, should_publish, status_data:Data): """ Processes the matched files and upload to pantheon through sling api call Paramters: path (string): A file path filetype (string): A type of file(assemblies [someday], modu...
def create_args(): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description='''\ Red Hat bulk upload module for Pantheon 2. This tool will scan a directory recursively and upload relevant files. Both this pantheon-uploader and Pantheon 2 are ALPHA software and features ma...
The main task of the code is to parse command-line arguments, configure logging, and initiate a process using parameters like user credentials, server details, directory paths, and operational flags (e.g., dry run, sandbox mode). It prepares environment settings and launches a process for repository operations, likely ...
def main(): # global pw, config args = create_args() user = args.user directory = args.directory if args.directory else os.getcwd() attrFile = args.attrFile dry = args.dry pw = args.password server = args.server logStr = 'DEBUG' if args.verbose is not None else 'WARNING' nume...
def activity_duration_per_unit(self): """Compute actual duration per unit""" adpu = [mhpu / (mpg * self.hours_per_day) for mhpu, mpg in zip(self.man_hours_per_unit, self.men_per_gang)] return [round(x, 2) for x in adpu] def start_first_to_start_last(self): """Docstring""...
The code computes start and end times for the first and last sections of activities, adjusting for buffer time based on changes in output rates. It iterates through activities, updating four lists (start_first, end_first, start_last, end_last) by inserting calculated values. The function returns these rounded lists to ...
def compute_plot_points(self): """Compute four last columns concurrently. First section start and end""" start_first = [1] end_first = [self.activity_duration_per_unit()[0]] start_last = [self.start_first_to_start_last()[0]] end_last = [start_last[0] + end_first[0]] for...
def theoretical_gang_size(self): """Compute theoretical gang sizes""" theo_g_size = [(self.productivity_rate*each) / (self.hours_per_day*self.days_per_week) for each in self.man_hours_per_unit] return [round(x, 2) for x in theo_g_size] def actual_gan...
The main task of the code is to structure multiple attributes of an object into a tabular format by zipping corresponding data lists into rows of values. Each row contains activity names, man-hours, personnel data, and time/output metrics, creating a structured 2D list for organized data presentation or processing.
def arrange_values(self): """Arrange the values in tabular format""" values = [ [a, b, c, d, e, f, g, h, i, j, k, l] for a, b, c, d, e, f, g, h, i, j, k, l in zip(self.activity_names, self.man_hours_per_unit, sel...
def start_on_first_section(self): """Start on first section for activity""" return self.compute_plot_points()[0] def end_on_first_section(self): """End on first section for activity""" return self.compute_plot_points()[1] def start_on_last_section(self): """Start on last section ...
The main task of the code is to generate labeled data points for plotting by combining activity names with their start and end positions on both the first and last sections. It creates tuples containing these values for visualization, using zip to align corresponding elements from multiple lists.
def plot_points_with_labels(self): """Generate points to be used for the plot. Points used in plotting are: Start on first section, End on first section, Start on last section, End on last section """ return [(a, b, c, d, e) for a, b, c, d, e in zip(self.activity_names, ...
def get_balanced_df(df, sample_num = 100): sample_df = df.groupby(['country','topic']).sample(sample_num,random_state = RANDOM_SEED) return sample_df def get_counrty_test(df): countries = list(df.country.unique()) train_size = 1 - (TEST_RATIO + DEV_RATIO) countries_train, countries_test = train_tes...
This function loads and prepares training/test datasets for model evaluation, applying balancing, topic filtering, and strategy-based splits (country/topic/random). It returns processed datasets with tokenized data and saves evaluation pairs for analysis.
def load_dataset(tokenizer,dataname_train, data_name_test,data_class, data_source_type = 'from_people', sample_num = 100, ): df = pd.read_csv(f'data/finetuning/{dataname_train}_{data_source_type}.csv') cross_test_df = pd.read_csv(f'data/finetuning/{data_name_test}_{data_source_type}.csv') ...
def compare_gpt3_prompts_mort_user_study_token_pairs(user_study = 'globalAMT', style = 'mv_at_end'): from src.probing_experiments.compare_prompt_responses.compare_gpt2 import\ gpt2_mort_prompts_multiple_tokens as gpt3_mort_prompts_multiple_tokens prompts = gpt3_mort_prompts_multiple_tokens(include_ato...
The main task of the code is to evaluate and compare GPT-3's performance across multiple datasets (Pew, WVS) and user studies by analyzing token pairs, prompting strategies, and cultural contexts. It executes repeated experiments to assess model behavior, focusing on probabilistic outputs (PROBS) and question-answering...
def compare_gpt3(): store_small_pew() #GPT3-PROBS compare_gpt3_prompts_mort_user_study_token_pairs() compare_gpt3_pew_token_pairs(prompt_mode = 'in') compare_gpt3_wvs_token_pairs(prompt_mode = 'in') #GPT3-QA universal_gpt3_pew(repeat=GPT3_REP) compare_gpt3_pew(repeat = GPT3_REP, culture...
def compare_gpt2_pair_prompts_mort_user_study(style = 'mv_at_end',modelname = 'gpt2', model = None, tokenizer = None, use_cuda = True): prompts = gpt2_mort_prompts_multiple_tokens(include_atoms= True) prompts = get_user_study_scores(prompts, user_study = 'globalAM...
The main task of the code is to compare GPT-2 variants (small, medium, large) across datasets (Pew, WVS) using prompt-based token pair analysis. It evaluates model performance on cultural and survey data with CUDA acceleration, analyzing responses in 'in' prompt mode for each model variant.
def compare_gpt2s(): store_small_pew() model_names = ['gpt2', 'gpt2-medium','gpt2-large'] for mn in model_names: compare_gpt2_pair_prompts_mort_user_study(style='mv_at_end', modelname=mn) compare_gpt2_wvs_token_pairs(COUNTRIES_WVS_W7,model_name= mn, use_cuda=True, prompt_mode='in') c...
def k_starting_centers(self, distances_copy, center_arr, i, k): ''' Choose k starting centers by starting with a random location and choosing next center to be the furthest location from the current center. Following centers will be chosen to be the furthest location from all previously chosen c...
The function performs k-medians clustering to group data points into k clusters by iteratively refining cluster centers. It initializes centers, assigns points to clusters, computes intra-cluster distances, and updates centers until convergence (based on epsilon or iteration limit). It returns the optimal cluster confi...
def k_medians_clustering(self, centers_dict=None, prev_totalsum=0, curr_totalsum=math.inf, i=1, epsilon=0.5, k_centers=[]): ''' Perform k_medians_clustering to group homes into k clusters with the following steps: 1. At the first iteration, generate the initial k centers (look at k_starting_cent...
def slice_mesh_into_layers(mesh, layer_height): # Translate the mesh so that the bottom middle of the bounding box is centered at the origin # First center mesh mesh.vertices -= mesh.center_mass # Then raise the mesh so that the bottom of the bounding box is at z=0 min_point = min(mesh.bounding_b...
This function converts a 3D mesh model into 2D layer paths for slicing. It loads a mesh, slices it into horizontal layers based on the specified height, generates offset contours for each layer, creates a connected path structure using spanning trees, and returns a list of connected 2D paths representing each layer. Th...
def model_to_layer_paths(model_filepath, layer_height): # Load the mesh using trimesh mesh = trimesh.load_mesh(model_filepath) #mesh.apply_scale(3) # Config settings contour_offset = 7 turtle.pensize(1) turtle.speed(4) # -Slicing process-: # Generate each of the layers layers...
def alreadyNotDownloaded(fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): return True data = fp.read() ...
The function `gdurls` processes a list of URLs to download files, managing filenames, storage paths, and ensuring single downloads. It generates unique filenames from URLs, creates a directory structure, checks if files are already downloaded using an MD5 hash of URL identifiers, and triggers a helper function for down...
def gdurls(urls,dirpath='',file2dnames = None,ids='',connections=4): if len(urls) == 0: print("no urls to do anything") return temp = Path(dirpath).parent / re.sub('[^0-9a-zA-Z\. -]+', '_', Path(dirpath).name) dirpath = str(temp) if file2dnames is None: file2dnames = [re.search...
def closest_idx_baseline(self,baseline_lim_1,baseline_lim_2): baseline_indices=[] baseline_indices.append(self.closest_idx_fcn(self.transient_axis,baseline_lim_1)[0]) baseline_indices.append(self.closest_idx_fcn(self.transient_axis,baseline_lim_2)[0]) self.baseline_indices=baseline_indic...
The function updates data by performing baseline correction, integration, and trace adjustments. If in 'T' mode, it identifies baseline and integration indices, applies corrections, modifies the x-axis using a math string, sets active integration data, and adjusts the number of traces based on input parameters.
def update_data_fcn(self,bl1,bl2,il1,il2,mathstring,first_trace_in=str(0),last_trace_in=str(-1)): if self.I_or_T=="T": self.closest_idx_baseline(bl1,bl2) self.apply_baseline_correction() self.closest_idx_integration(il1,il2) #update_fourer self.do_integratio...
def get_dropped_fov_counts(self, gene='', dic=False): """ Get the number of unique dropped FOVs. If a gene is specified, gets the number of dropped FOVs for specified gene. If dic=True return a dictionary of genes and dropped FOV counts Args: gene (str) [default='']: If spec...
The function generates a summary of dropout statistics for an experiment, calculating and displaying percentages of dropped fields of view (FOVs), affected genes, average dropouts per gene, and false positives. It prints the summary and optionally returns it as a string if return_summary is True.
def dropout_summary(self, return_summary=False): """ Prints a summary of the dropout for the experiment Args: return_summary (bool) [default=False]: if True, returns the summary as a string """ summary = f"{self.get_dropped_fov_counts()} unique FOVs were drop...
def get_considered_gene_counts(self, fov=-1, dic=False): """ Get the number of genes with at least 1 FOV considered for dropout. An FOV is considered for dropout only if its 4 cardinal neighbors average at least 100 transcripts. If an FOV is specified, get the number of genes for which the FOV w...
The code generates heatmaps visualizing five metrics related to gene dropout and false positives across fields of view (FOVs): genes considered, genes dropped, dropout rate (dropped/considered), false positive counts, and false positive rate (false positives/considered). It uses color-coded rectangles scaled by the vir...
def draw_total_dropout_map(self, out_file=''): """ Draws heatmaps of number of genes considered for dropout per FOV and number of genes dropped out per FOV Args: out_file (str) [default='']: If specified, the function will output the plot to the specified path and close """ ...
def find_fovs(self): """ Creates a dataframe to store information about FOVs and reads in preliminary information for each Also creates a dataframe which stores per-fov transcript counts for every gene Sets: self.fovs (dataframe): dataframe of all FOVs and their metadata ...
This function executes a pipeline for dropout detection in a merscope experiment. It creates FOV tables, identifies on-tissue FOVs using masks, calculates neighbors, detects dropouts via transcript thresholds, loads a codebook, and identifies false positives. The process analyzes spatial transcriptomic data to flag und...
def run_dropout_pipeline(self, mask_out_dir, codebook_path, threshold=0.15): """ Runs all the steps necessary for dropout detection Args: mask_out_dir (str/path): the output directory for the tissue mask information (used to find on-tissue FOVs) codebook_path (st...
def getScore(self, vertical): return len(list(self.legal_moves(vertical))) - len(list(self.legal_moves(not vertical))) def game_over(self, vertical=True): for i in range(len(self.board)): for j in range(len(self.board[i])): if self.is_legal_move(i, j, vertical): ...
This function implements the max-value step of alpha-beta pruning in a game-playing algorithm. It evaluates all possible moves for the current player, recursively calling min_value to determine the best outcome. The function tracks the maximum score (max_v) and corresponding move (this_move), using alpha-beta pruning t...
def max_value(self, player, alpha, beta, depth, limit): if depth >= limit: DominoesGame.states += 1 return ((0, 0), self.getScore(player)) if self.game_over(player): DominoesGame.states += 1 return ((0, 0), self.getScore(player)) max_v = -99999999...
def getScore(self, vertical): return len(list(self.legal_moves(vertical))) - len(list(self.legal_moves(not vertical))) def game_over(self, vertical=True): for i in range(len(self.board)): for j in range(len(self.board[i])): if self.is_legal_move(i, j, vertical): ...
This function implements the minimax algorithm with alpha-beta pruning for a game, determining the optimal move for the current player by evaluating all possible moves. It selects the move with the minimum score from child nodes, updates alpha/beta values for pruning, and returns the best move and its score. The functi...
def min_value(self, player, alpha, beta, depth, limit): if depth >= limit: DominoesGame.states += 1 return ((0, 0), self.getScore(player)) if self.game_over(not player): DominoesGame.states += 1 return ((0, 0), self.getScore(player)) min_v = 99999...
def save_sentences(filename): print("saving sentences ...") dirnames = ["G:\\Paper_All\\Code\\data\\sick\\SICK_train.txt", "G:\\Paper_All\\Code\\data\\sick\\SICK_test_annotated.txt", "G:\\Paper_All\\Code\\data\\sick\\SICK_trial.txt"] with open(filename,"w") as f: for file in dirnames: OutData = pd.read_...
The code saves sentences to a file if it doesn't exist, trains a Word2Vec model if the model file is missing, then evaluates the model on three SICK datasets by calculating metrics (valA, valB) for each file and printing the results.
def main(): save_file = "sentences.txt" if not os.path.exists(save_file): save_sentences(save_file) if not os.path.exists("word2vec.pt"): train_model(save_file) dirnames = ["G:\\Paper_All\\Code\\data\\sick\\SICK_train.txt", "G:\\Paper_All\\Code\\data\\sick\\SICK_test_annotated.txt", "G:\\Paper_All\\Co...
def parse(csv_file): with open(csv_file,"r") as election_data: # Parses file as a lot of dictionaries, with the column headers as keys row_dicts = csv.DictReader(election_data) # Puts the dictionaries together as a list of dictionaries; each dictionary has a "Ballot ID" a "County" and a "Ca...
The main task of the code is to process election data from a CSV file by parsing it, calculating total votes and identifying the winner, then displaying the results in the terminal and writing them to a text file. It formats and outputs detailed vote percentages, counts, and the winner's name in a structured report.
def run_calculations(csv_file): # Parses csv file parsed, ballot_key, county_key, candidate_key = parse(csv_file) # Performs calculations total_votes = find_total_votes(parsed) votes, winner = find_winner(parsed) # Prints everything to the terminal print("Election Results") print("----...
def find_months(csv_file): # Parses the csv file parsed, month_key, profit_key = parse(csv_file) # Returns the number of dates in the file return len(parsed) def find_total(csv_file): # Parses the csv file parsed, month_key, profit_key = parse(csv_file) # Sets up a counter to hold all of t...
The code processes a CSV file to calculate financial metrics including total months, total profit/loss, average change, greatest increase, and greatest decrease. It prints these results to the terminal and writes them to a text file for analysis.
def run_calculations(csv_file): # Performs all calculations and sets each required number equal to a variable months = find_months(csv_file) total = find_total(csv_file) average_change = find_average_change(csv_file) date_max, greatest_increase = find_greatest_increase(csv_file) date_min, great...
def hold(): var_get() hands[hand_number].status = "Inactive" widgets[hand_number * 3]["state"] = DISABLED widgets[hand_number * 3 + 1]["text"] = hands[hand_number].second_value var_check() def dealer_play(): global balance, frame_player, frame_dealer, button_bid, button_hit, button_hold, button_...
The function checks the values of a hand in a game (likely Blackjack), updates the UI to reflect the hand's status (e.g., "21" for blackjack, busts, or paired values), and triggers subsequent actions like holding, dealer play, or validation based on the evaluated values.
def check_values(): temp = hands[hand_number].first_value temp1 = hands[hand_number].second_value if temp == 21 or temp1 == 21: hands[hand_number].status = "Inactive" widgets[hand_number * 3 + 1]["text"] = "21" hold() elif temp > 21: widgets[hand_number * 3 + 1]["text"] =...
def var_get(): global hand_number hand_number = var.get() def show_card(): z = math.floor((len(hands[hand_number].cards_in_hand) - 1) / 4) widgets[hand_number * 3 - 1].create_image(40 + 40 * (len(hands[hand_number].cards_in_hand) - 1 - 4 * z), 50 + 75 * z, i...
The code defines a function `hit_button()` that performs actions in a card game: retrieves variables, adds a card to the current hand, displays updated cards, and checks if the hand value exceeds 21 (bust). Its main task is to handle the "hit" action in a game like Blackjack, updating the player's hand and validating t...
def hit_button(): var_get() hands[hand_number].hit() show_card() check_values()
def var_get(): global hand_number hand_number = var.get() def show_card(): z = math.floor((len(hands[hand_number].cards_in_hand) - 1) / 4) widgets[hand_number * 3 - 1].create_image(40 + 40 * (len(hands[hand_number].cards_in_hand) - 1 - 4 * z), 50 + 75 * z, i...
The function `double_button` handles a "double" action in a card game, validating if the player has exactly two cards and sufficient balance. If valid, it updates the bid, deducts the bid amount from the balance, disables the button, marks the hand as inactive, and triggers subsequent game logic like showing cards and ...
def double_button(): global balance var_get() if len(hands[hand_number].cards_in_hand) == 2: if balance < hands[hand_number].actual_bid: m.showwarning(message="You can't do this") return else: m.showwarning(message="You can't do this") return hands[han...
def print_menu() -> (): print(''' Would you like to: 1) Create an account 2) Authenticate 3) Generate random accounts 0) Exit ''') def create_account(is_automated: bool = False, username: str = "", password: str = "", min_password_size: int = MIN_PASSWORD_S...
The main task of the code is to run a menu-driven application that allows users to create accounts, authenticate existing accounts, generate random accounts, or exit. It uses a loop to repeatedly display a menu, validate user input (0-3), and execute corresponding functions. The loop terminates when the user selects op...
def main() -> (): is_running = True while is_running: # Prompt for user option, 1-3 print_menu() menu_option = get_valid_integer("Please select a menu option", 0, 3) if menu_option == 1: # Option 1 is to create an account create_account() elif menu_option =...
def extract_submission_info(contents: str) -> str: namespaces = { 'http://www.sec.gov/edgar/common/': None, # skip this namespace } xml = contents[1].split('</XML>')[0].strip() return strip_ns(xmltodict.parse(xml, process_namespaces=True, namespaces=namespaces))['edgarSubmission'] def extract_in...
The code extracts structured financial data from XML-formatted text, parsing submission details (CIK, manager info, report period) and investment data, then filters/formatting them into a list of dictionaries for structured output.
def extract_dicts(txt: str) -> List[Dict]: contents = txt.split('<XML>') submt_dict = extract_submission_info(contents) mng_cik = submt_dict['headerData']['filerInfo']['filer']['credentials']['cik'] mng_name = submt_dict['formData']['coverPage']['filingManager']['name'] try: mng_address = ",...
def parse_args(): parser = argparse.ArgumentParser( description='download 10k filings and pull text from sections 1,1A, 7, and 7A from 10-ks and save as json', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-s', '--start-date', default='2022-01-01', help='Start date...
The code pulls 10-K form URLs from the SEC website for companies listed in an input CSV file, using CIK identifiers and specified date ranges. It processes each CIK, collects URLs, filters non-empty results, and saves the output as a CSV file with exploded URLs. The task involves parsing arguments, connecting to SEC's ...
def main() -> int: args = parse_args() start_date = datetime.datetime.strptime(args.start_date, '%Y-%m-%d').date() end_date = datetime.datetime.strptime(args.end_date, '%Y-%m-%d').date() user_email = args.user_email user_name = args.user_name input_file = args.input_file output_file = args.o...
def parse_args(): parser = argparse.ArgumentParser( description='download 10k filings and pull text from sections 1,1A, 7, and 7A from 10-ks and save as json', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-t', '--temp-directory', required=False, default='data/temp...
The main task of the code is to download and process SEC 10-K filings from URLs in a CSV file. It parses input arguments, reads company URLs, creates necessary directories, iterates through each URL to download filings, and converts raw data into structured JSON files in the output directory. Temporary files are delete...
def main() -> int: args = parse_args() temp_dir = args.temp_directory output_dir = args.output_directory user_email = args.user_email user_name = args.user_name print('Pulling urls...') url_df = get_cik_url_df(args.input_file) print(f'Found {url_df.shape[0]:,} companies to pull filings...
def parse_args(): parser = argparse.ArgumentParser(description='format raw form13s from EDGAR SEC into a csv for graph loading', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input-directory', required=False, default='data/form13-raw/',...
The main task of the code is to process filings data from an input directory by parsing, aggregating, and optionally filtering it based on specified parameters. It saves the processed data to a CSV file, reports parsing failures, and returns 0 to indicate successful execution.
def main() -> int: args = parse_args() filings_df, failures = parse_from_dir(args.input_directory) stg_df = aggregate_data(filings_df) if args.top_periods is not None: stg_df = filter_data(stg_df, args.top_periods) stg_df.to_csv(args.output_file, index=False) print(f'===== Had {len(failu...
def monte_carlo(key2test, prev, eg_df, U, E): Nsam = 1000000 tval = stats.norm.ppf(1-prev[0], loc=0, scale=1) for k in key2test: # Generate liabilities genliab = stats.norm.rvs(loc=0, scale=np.sqrt(U), size=Nsam) envliab = stats.norm.rvs(loc=0, scale=np.sqrt(E), size=Nsam) l...
The GHK algorithm estimates posterior genetic liability scores (EG) and standard errors (G_SE) for traits using Monte Carlo simulation and covariance decomposition. It handles multiple traits by decomposing genetic (U) and environmental (E) covariances, with retries for error resilience. The function logs results and r...
def ghk_algorithm( log, U, E, prev, key2test, N_samp=100000, ncores=1): """ U: genetic covariance tval: inverse cdf of prevalence """ log.log('\nRunning GHK algorithm...\n') N = N_samp ns = len(prev) if np.sum(prev < 0.01) > 0: warnings.warn( 'The...
def welcome_page(): st.title("Welcome to Hopify") image_path = "Hopify.jpg" # Replace with the actual path to your image file st.image(image_path, use_column_width=True) access_token = get_access_token() if access_token: user_data = sp.current_user() client_id = user_data['id'] ...
The main task of the code is to create a Streamlit web app with a sidebar navigation system that allows users to access three pages: a welcome page, a "Discover new songs" page, and a "Songs you may like" page. The app authenticates with Spotify using an access token, retrieves user data, and displays personalized musi...
def main(): # Add content for the Home page if needed st.sidebar.title("Navigation") app_page = st.sidebar.selectbox("Go to", ("Welcome", "Discover new songs","Songs you may like")) if app_page == "Welcome": welcome_page() elif app_page == "Discover new songs": ...
def fullpageSnapshot(self, filename=time.time()): ''' This function will take entire screenshot. :param filename: file to save screenshot image (optional) :return: fullpage screenshot image object and image name ''' try: logging.info("full screenshot method ...
This function automates image processing and text extraction for object localization. It validates inputs, resizes/enhances cropped images, extracts text, and returns either XPath objects or coordinates based on the 'flag' parameter. Key steps: input validation, image cropping/enhancement, text extraction, and coordina...
def fullAutomationMode(self, dimensions=[0, 0, 0, 0], resize_size=5, enhance_by=30.0, flag='objects'): ''' This is full automated function in which all the config is taken from config file and object is located :param dimensions: dimensions to be worked on (top left x co-ordinate,top left y co-...
def all_performers(): all_perf = [problem_performers(prob) for prob in range(count_problems())] return list(set(list(itertools.chain.from_iterable(all_perf)))) def had_success(performer, prob): return performer in set(problem_performers(prob=prob)) def count_problems(inp="single_problem_data.pickle"): s...
This function generates a DataFrame where each row represents a performer and each column indicates whether they succeeded on a specific problem, using boolean values derived from the `had_success` function.
def df_performer_succeeded(): all_perf = all_performers() performer_successes = {} for performer in all_perf: performer_successes[performer] = [had_success(performer, prob) for prob in range(count_problems())] return pd.DataFrame(performer_successes)
def count_problems(inp="single_problem_data.pickle"): sp = define_sp(inp) return len(sp) def problem_name(prob=0): return single_problems[prob]['type'] def problem_keywords(prob=0): return single_problems[prob]['keywords'] def problem_in_categories(prob): cats = set() for cat, kws in category_to...
The function `in_categories_df` generates a DataFrame containing problem details (name, keywords, categories, and category count) for all problems, excluding those with exactly one category. It iterates through problems, collects metadata, converts category sets to strings, counts categories, and filters the final Data...
def in_categories_df(): name_col = [] keyw_col = [] cats_col = [] ncats_col = [] for prob in range(count_problems()): name_col.append(problem_name(prob)) keyw_col.append(problem_keywords(prob)) set_of_cats = problem_in_categories(prob) cats_col.append(str(set_of_cats)...
def get_int_matrix() -> list: str_matrix = [] for entry in entries: if entry.get() == "": str_matrix.append("0") else: str_matrix.append(entry.get()) matrix = [] while len(str_matrix) != 0: matrix.append(str_matrix[:num_of_columns]) str_matrix = str_matrix[num_of_columns:] int_matrix = [] for ...
The function converts a matrix into its Reduced Row-Echelon Form (RREF) using fraction arithmetic. It scales rows to normalize pivot elements, eliminates entries above and below pivots through row operations, and ensures each leading entry is 1 while all other entries in its column are 0. The process involves nested lo...
def rref() -> list: int_matrix = get_int_matrix() if int_matrix == None: return rearrange(int_matrix) for i in range(len(int_matrix)): for j in range(i + 1, len(int_matrix)): n = i while True: try: if calculate_fraction(int_matrix[i][n]) == 0: n += 1 continue break exce...
def get_int_matrix() -> list: str_matrix = [] for entry in entries: if entry.get() == "": str_matrix.append("0") else: str_matrix.append(entry.get()) matrix = [] while len(str_matrix) != 0: matrix.append(str_matrix[:num_of_columns]) str_matrix = str_matrix[num_of_columns:] int_matrix = [] for ...
The main task of the code is to convert a given integer matrix into its row echelon form using fraction arithmetic and Gaussian elimination. It performs row operations to ensure each leading entry (pivot) is to the right of the one above, eliminating entries below each pivot by scaling and adding rows, while maintainin...
def echelon_form() -> list: int_matrix = get_int_matrix() if int_matrix == None: return rearrange(int_matrix) for i in range(len(int_matrix)): for j in range(i + 1, len(int_matrix)): n = i while True: try: if calculate_fraction(int_matrix[i][n]) == 0: n += 1 continue break ...
def get_int_matrix() -> list: str_matrix = [] for entry in entries: if entry.get() == "": str_matrix.append("0") else: str_matrix.append(entry.get()) matrix = [] while len(str_matrix) != 0: matrix.append(str_matrix[:num_of_columns]) str_matrix = str_matrix[num_of_columns:] int_matrix = [] for ...
The code computes the inverse of a given integer matrix. It first checks if the matrix is non-singular (determinant ≠ 0). If singular, it returns an error. Otherwise, it constructs the cofactor matrix by calculating determinants of submatrices, applies sign adjustments based on position, transposes the cofactor matrix ...
def inverse() -> list: int_matrix = get_int_matrix() if int_matrix == None: return determinant = calculate_determinant(int_matrix) if calculate_fraction(determinant) == 0: print("The inverse of this matrix does not exist.\n") return cofactor_matrix = [] for i in range(num_of_rows): tmp_cofactor_matri...
def rref() -> list: int_matrix = get_int_matrix() if int_matrix == None: return rearrange(int_matrix) for i in range(len(int_matrix)): for j in range(i + 1, len(int_matrix)): n = i while True: try: if calculate_fraction(int_matrix[i][n]) == 0: n += 1 continue break exce...
The function `decide_function` determines which matrix operation to execute based on the selected mode from a combobox. It performs RREF, Echelon Form, determinant, transpose, or inverse operations, prints the result matrix (if valid), and handles errors by returning early if matrix generation fails.
def decide_function(): if "RREF" in mode_combobox.get(): matrix = rref() if matrix == None: return print("RREF =\n") print_matrix(matrix) elif "Echelon Form" in mode_combobox.get(): matrix = echelon_form() if matrix == None: return print("Echelon Form =\n") print_matrix(matrix) elif mode_...
def get_issues(sprint, search=None): # """ # TODO - Check data retrival at edge cases. Total == Max Results # """ url = 'https://fullprofile.atlassian.net/rest/api/2/search' if search == "stories": querystring = { "jql": "project = ADS AND sprint = " + str(sprint) + " AND typ...
The main task of the code is to initialize sprint data management by loading or fetching stories, subtasks, and sprint history, either from local files in offline mode or via API calls. It processes the data, validates it, and returns structured results along with sprint metadata, while allowing debug logging for speci...
def start(sprint): global SPRINT_LOG SPRINT_LOG = {} global DEBUG DEBUG = { 'changelog': False, 'burndown': False, 'defects': False, 'sprint_summary': False, } OFFLINE_MODE = False if OFFLINE_MODE: with open('stories.pkl', 'rb') as f: s...
def file_exists(file_path: str) -> bool: """This function check if a file exists in a given path""" return os.path.exists(file_path) def get_soup_from_file(file_path: str) -> BeautifulSoup: """Load HTML file and return a BeautifulSoup object""" html = get_html_from_file(file_path) soup = BeautifulSo...
This function either loads an existing HTML file or downloads it from a given URL using proxies if enabled, then saves the parsed HTML (BeautifulSoup object) to the specified file path for future use, returning the parsed HTML content.
def download_or_load_soup( url: str, file_path: str, use_proxies: bool = True ) -> BeautifulSoup: """Download HTML file or load HTML file""" if file_exists(file_path): soup = get_soup_from_file(file_path) else: soup = get_soup_from_url(url, use_proxies=use_proxies) save_soup_to_f...
def estimate_tempo_from_mode(note_spacings): mode_spacing = stats.mode( np.around(note_spacings[2:], 1)) # gives mode (most common) value from note_spacing array after round to 1 dp) mode_array = [] lim = 0.1 # since use 1 dp this should be fine - acceptable error on the mode that you'll accept fo...
The code analyzes musical rhythm by converting JSON note data into a notes object, estimating tempo, optimizing it if user-provided tempo is absent, and generating rhythm metrics like beat alignment, note delays, histogram distributions, and summary text for visualization and analysis.
def generate_rhythm_analysis(new_notes_json, tempo): # convert new_notes_json back to notes object new_notes_dict = json.loads(new_notes_json) new_notes = notes(new_notes_dict['time'], new_notes_dict['freq'], new_notes_dict['amp'], new_notes_dict['spacing']) # find the smallest devisions and estimated ...
def threshold_function(array, fraction, avg_size): array = array[array > 0] array = np.sort(array) # sort into descending order min_avg = np.mean(array[0:avg_size]) max_avg = np.mean(array[-avg_size:-1]) return fraction * (max_avg - min_avg) def peaks_over_threshold(wav_array, threshold, sample_rat...
The code processes an audio file to detect note onsets, analyze rhythm, and estimate tempo. It reads audio data, sets time axes, determines amplitude thresholds, identifies peaks, and locates note onsets. It then estimates tempo from onset spacing, refines rhythm analysis, and returns detected onsets for user adjustmen...
def process_audio_file(f, tempo): wav_data = wavio.read(f) print('wavio read') time_int = 1 / wav_data.rate # rounding makes time inaccurate of course time = np.linspace(0, time_int * (len(wav_data.data) - 1), num=len( wav_data.data)) # time axis for wav_data.data. Remember (stop) total time n...
def get_api_list(self): """Returns the APIs which need to be called in this interval.""" api_list = [] for api_detail in APIS: if self.count == 0 or self.count % api_detail.get("interval_offset", 1) == 0: api_list.extend(api_detail.get("api_list", [])) return ...
The code's main task is to manage API interactions for monitoring Dell EMC Isilon systems. It retrieves an API list, handles authentication (resetting every 30 checks or every 7th check), sets cluster names, updates a Datadog gauge metric with tags, and ingests data for dashboards. The method ensures periodic authentic...
def check(self, instance): """Get the list of APIs to hit.""" api_list = self.get_api_list() self.count += 1 if self.count > 30: self.count = 1 if not self.is_authenticated or self.count % 7 == 0: self.authentication() if self.is_authenticated: ...
def DijkstraWithRandomEventTest(graph, event_number, missing_edge_to_add): # Dijkstra’s SSSP algorithm static_computing_time_list = [] # new local graph instance foreach experiment localGraph = copy.copy(graph) # DynDijkstra’s SSSP algorithm dynamic_computing_time_list = [] # new local grap...
This code tests Dijkstra's algorithm on BAG graph structures, comparing static and dynamic performance under random edge removals. It processes multiple graphs, calculates path cost averages/variances, and stores results in maps keyed by node/edge counts. The loop iterates through BAGs, runs Dijkstra tests, and saves s...
def test_Dijkstra_on_BAGs(): parser = graphParser.file_Parser() map_result_by_node = {} map_result_by_edge = {} dyn_map_result_by_node = {} dyn_map_result_by_edge = {} while(True): response = parser.getNextBAG() if(response[0] == "no_more_graphs" or response == "not_exist"): ...
def DijkstraWithRandomEventTest(graph, event_number, missing_edge_to_add): # Dijkstra’s SSSP algorithm static_computing_time_list = [] # new local graph instance foreach experiment localGraph = copy.copy(graph) # DynDijkstra’s SSSP algorithm dynamic_computing_time_list = [] # new local grap...
This code tests Dijkstra's algorithm on Erdős–Rényi graphs (ERGs), comparing static and dynamic performance. It parses graphs, runs Dijkstra with random edge removals, calculates average path weights and variances, and stores results for analysis. The loop processes multiple graphs, saving static and dynamic results se...
def test_Dijkstra_on_ERGs(): parser = graphParser.file_Parser() map_result_by_node = {} map_result_by_edge = {} dyn_map_result_by_node = {} dyn_map_result_by_edge = {} avg_map = {} dyn_avg_map = {} while(True): response = parser.getNextERG() if(response[0] == "no_mor...
def setLogging(args): log_level = LOG_LEVELS.index(DEFAULT_LOG_LEVEL) for adjustment in args.log_level or (): log_level = min(len(LOG_LEVELS) - 1, max(log_level + adjustment, 0)) log_level_name = LOG_LEVELS[log_level] global log log = logging.getLogger(__name__) shell_handle...
The main task of the code is to count objects in images using a template, either processing a single image-file pair or an entire folder of images. It sets up directories, validates input files, and executes object counting in "Single File Mode" or "Folder Mode" based on command-line arguments, outputting results to sp...
def main(args): setLogging(args) log.info("[bold purple]Object Counter © Stefan Knaak - E-Shelter Security. [/]", extra={"markup": True}) #Folders cwd = os.getcwd() global stacks_path, needle_path, output_path, csv_path stacks_path = export.checkInputFolderPath(args.stacksfolder, "stac...
def stop(self): self.stop_timer() self.set_state(self.STATE_STOPPED) self.set_power(OFF, OFF) self.eta = 0 def start_timer(self): # https://micronote.tech/2020/02/Timers-and-Interrupts-with-a-NodeMCU-and-MicroPython/ if self.on_time == 0: LCD.show_message('ON ...
This code handles events by updating object states, timing, and power settings. It processes 'online_changed', 'offline_changed', 'start_on', 'start_off' to manage operational states, triggers 'stop', 'restart', 'reset', 'reboot' actions, and calls 'update_handler' for 'next' events, coordinating system behavior throug...
def receive(self, event, *args): if event == 'online_changed': self.on_time = args[0] elif event == 'offline_changed': self.off_time = args[0] elif event == 'stop': self.stop() elif event == 'start_on': if self.start_timer(): ...
def countdown_clock(): time_now = datetime.datetime.now() cc = int(input("How many minutes until alarm? ")) global new_time time_change = datetime.timedelta(minutes = cc) new_time = time_now + time_change print(f'Alarm will activate at {new_time}. Please wait.') clock_process() def alarm_cl...
The main task of the code is to prompt the user to select between a countdown clock (input '1') or an alarm clock (input '2'), validate the input, and return the corresponding function. If invalid input is detected, it recursively re-prompts until a valid choice is made.
def clock_type(): valid_inputs2 = ["1", "2"] clock_choice = input("Please select clock format. Press '1' for countdown or '2' to set time: ").lower() if clock_choice not in valid_inputs2: print("Error: Please choose between 1 or 2") return clock_type() if clock_choice == str("1"): ...
def kernel_spectrum_from_feat(feat, Y: dict, cent=False, **kwargs): assert type(Y) is dict, "labels should be provided as a dict (e.g. {'classes': classes})" P, N = feat.shape for y in Y.values(): assert y.shape[0] == P, "labels should have same sample size" # Center feats and targets if ...
The function `get_spectral_properties` computes key spectral properties of neural network layer activations, including eigenvalues, weights, cumulative power, effective dimensions, and related metrics. It processes both centered and uncentered data, returning a list of dictionaries containing these metrics for analysis...
def get_spectral_properties(layer_act): # Compute # - Spectrum and weights # - Cumulative power # - Effective dimensions metric_keys = ['eigs', 'weights', 'orkhs_power', 'cum_powers', 'e...
def initialize(self): self.parser.add_argument( 'configs', nargs='*', default=None, help='Optional list of yaml config files with argument specifications.' ) # Data self.parser.add_argument( '--data_dir', ...
The main task of the code is to parse command-line arguments and merge them with YAML configuration files, prioritizing command-line overrides. It reads YAML files, converts nested dictionaries to JSON, handles boolean flags (e.g., 'no_'), and updates the argument object with the combined configurations. The result is ...
def parse(self): if not self.initialized: self.initialize() args = self.parser.parse_args() for config in args.configs: if config is not None: # get commands from command line override_args = argv_to_vars(sys.argv) # load...
def check_username_exists(username): with open('password_hash_log.txt', 'r') as file: for line in file: if f"Username: {username}" in line: return True return False def create_login_window(): login_window = tk.Toplevel() login_window.title("Enter Password") passw...
The main task of the code is to check if a username already exists. If it does, it informs the user and opens a login window. If not, it generates a password hash, updates the hash display, and shows a hash window while hiding the hash button.
def check_existing_username(): username = eUsername.get() if check_username_exists(username): messagebox.showinfo("Username Exists", "Username already exists. Please enter your password.") create_login_window() else: hash_value = generate_password_hash() if hash_value: ...
def getTimePartition(lotraj, numtimepartitions): mergedTimeCol = np.array([]) for traj in lotraj: mergedTimeCol = np.append(mergedTimeCol, traj[:,0]) percentiles = np.linspace(0, 100, numtimepartitions+1)#[10,20,30,40,50,60,70,80,90] splitPoints = np.unique(np.percentile(mergedTimeCol, perce...
This function prepares trajectory data by calculating total time, partitioning trajectories into time segments, computing an initial parameter F0, merging trajectory data, and determining variable partitions. It returns trajectory endpoints, merged data, time partitions, F0, and variable splits for subsequent analysis.
def dataPrep(delta, lotraj, numtimepartitions, numvarpartitions, cat): TOTALTIME = 0.0 for traj in lotraj: TOTALTIME += traj[-1,0] - traj[0,0] tpart = getTimePartition(lotraj, numtimepartitions) F0 = np.log(np.sum(delta)/TOTALTIME) #start = time.time() trajEndPoints, mergedData, mergedDT...
def dataPrep(delta, lotraj, numtimepartitions, numvarpartitions, cat): TOTALTIME = 0.0 for traj in lotraj: TOTALTIME += traj[-1,0] - traj[0,0] tpart = getTimePartition(lotraj, numtimepartitions) F0 = np.log(np.sum(delta)/TOTALTIME) #start = time.time() trajEndPoints, mergedData, mergedDT...
This function performs cross-validation for a tree ensemble model by iterating over specified hyperparameters (maxsplits, numtrees) and evaluating log-likelihood on test folds. It prepares training/test data, trains models with varying splits and tree counts, computes log-likelihoods, and returns an averaged table of r...
def cv(delta, lotraj, nfolds = 5, maxsplits=[2,3,4], numtrees=[10,50,100,200], numtimepartitions=50, numvarpartitions=50, shrink=0.1, GlobalPartition = True, verbose=0, cat = None): maxTrees = np.max(numtrees) from sklearn.model_selection import StratifiedKFold skf = StratifiedKFold(n_splits=nfolds) X =...
def create_listbox(self): lb = tk.Listbox(self.root, height=20) for i, path in enumerate(img_paths): lb.insert(i, path) lb.pack(fill='x') lb.bind('<<ListboxSelect>>', lambda x: self.load_img()) return lb def create_status_lbl(self): status_lbl = tk.Label(self....
This code initializes a GUI application for butterfly background inspection using Tkinter. It sets up a window with a listbox, status label, and save button, loads image paths, and prepares components for displaying and interacting with images. The main task is creating an interface to inspect and manage butterfly back...
def __init__(self, paths): self.paths = paths self.panel = None self.panel_larger = None self.cur_path = None self.cur_img = None self.root = tk.Tk() self.root.title("Butterfly Background Inspection") self.root.geometry("800x800") self.lb = self.cr...
def make_dir(path): try: os.mkdir(path) except: pass def random_noise(batch_size, zdim): return np.random.uniform(-1, 1, [batch_size, zdim]).astype(np.float32) def save_img(contents, names=["", "", ""], savename=""): num_cont = len(contents) plt.figure(figsize=(5*num_cont+2, 5)) for i in ran...
The code trains a neural network for image restoration using a dataset, performing batch-wise training over specified epochs. It generates random noise, processes input images through the network, and saves intermediate results (input, restored images, and difference maps) for visualization. The loop iterates through t...
def training_izi(neuralnet, dataset, epochs, batch_size, normalize=True, iteration=0): print("\nTraining izi to %d epochs (%d of minibatch size)" %(epochs, batch_size)) make_dir(path="training") result_list = ["restoration"] for result_name in result_list: make_dir(path=os.path.join("training", result...
def check_slope(point): lineA = [(0,1),(0,0)] angleA = ang(point,lineA) return angleA < slope or (90 - angleA) < slope def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]...
This code captures mouse-dragged regions from an image, applies edge detection, identifies line intersections using Hough transforms, validates geometric configurations, and saves the processed ROI with calculated coordinates. It handles cropping, image analysis, and coordinate calculation for structured output.
def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, finished, slope, cropping, coords # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2...
def Milestone3_Get_VisualAnalytics(OpenAQDataset, OpenAQStation): OpenAQdfDataset = [] for OpenAQdatasetGraph in OpenAQDataset: if(OpenAQdatasetGraph[0] == OpenAQStation): OpenAQdfDataset = OpenAQdatasetGraph return OpenAQdfDataset def Milestone2_OpenAQStati...
The main task of the code is to perform quality control (QC) on OpenAQ station data by iterating through unique stations, preparing datasets, and applying QC parameters from a YAML file. It processes each station's data using the Pecos framework, filtering and combining datasets for visual analytics, then invoking a QC...
def Milestone3_Pecos_Complete_QC_QualityControl_OpenAQStation(OpenAQStation, OpenAQDataset_VisualAnalytics_iteration, OpenAQStationunique, OpenAQDataset, yaml_include): iteration = 0 OpenAQSearchCriteria = "" for OpenAQunique in OpenAQStationunique: print(OpenAQunique) ...
def theta_element(y,h): n,d = y.shape z = tf.constant(h/2)*tf.cumsum(y[1:n],axis=0) + tf.constant(h/2)*tf.cumsum(y[0:n-1],axis=0) xint = tf.concat([tf.zeros((1,d)),z],axis=0) return xint def sliceF(xmid,xint,libGPU,q,nlen,dims,Xi): Fbward = tf.zeros_like(xmid) Ffward = tf.z...
The code performs parameter estimation in a dynamic system using ISINDy, optimizing variables Xi and noisevar via gradient descent. It computes forward/backward prediction errors and state variable discrepancies, combining them into a loss function. The function returns the total loss, with gradients applied to update ...
def onestep_ro_ISINDy(yobs,yfward,ybward,noisevar,Xi,eta,weights,h,q,nlen,dims, optimizer,libGPU,n_train): with tf.GradientTape() as g: # get the initial condition guess, we estimate by ISINDy x = tf.constant(yobs,dtype=tf.dtypes.float32) xhat = tf.math.su...
def get_most_recent(key): """ Gets the most recent Data Object for a key. :param key: :return: """ max = {'updated': '01-01-1965 00:00:00Z'} for version in data_objects[key].keys(): data_object = data_objects[key][version] if parse(data_object['updated']) > parse(max['updated...
The function updates a data object by creating a new version with the latest data, preserving the original creation timestamp, and handling versioning by either using a provided version or generating a new one if needed, returning a success response with the updated data object ID and 200 status.
def UpdateDataObject(**kwargs): """ Update a Data Object by creating a new version. :param kwargs: :return: """ data_object_id = kwargs['data_object_id'] body = kwargs['body']['data_object'] # Check to make sure we are updating an existing document. old_data_object = get_most_recent...
def get_most_recent_bundle(key): """ Returns the most recent bundle for the given key. :param key: :return: """ max = {'updated': '01-01-1965 00:00:00Z'} for version in data_bundles[key].keys(): data_bundle = data_bundles[key][version] if parse(data_bundle['updated']) > pars...
The main task of the code is to update an existing Data Bundle by upserting new metadata, preserving the original document's ID and creation timestamp while handling versioning. It checks for existing versions, generates a new timestamp if needed, and stores the updated document in the data_bundles dictionary with the ...
def UpdateDataBundle(**kwargs): """ Updates a Data Bundle to include new metadata by upserting the new bundle. :param kwargs: :return: """ data_bundle_id = kwargs['data_bundle_id'] body = kwargs['body']['data_bundle'] # Check to make sure we are updating an existing document. ol...
def slowprint(s): for c in s + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(1./10) def path1(): slowprint('Het is niet veilig in je land meer, je moet zo snel mogelijk het land verlaten') slowprint('Hoe ga je het land verlaten? Vertrek je met het vliegtuig of met de boot?') answer1 = inpu...
The code prompts the user for their name and reason for leaving a country (war or seeking work), then directs them to different paths (path1() or path2()) based on their input, with an error message for invalid responses.
def Choices(): slowprint('Hallo, wat is je naam ook alweer?') name = input() slowprint('Hallo ' + name + ', ik heb vernomen dat je het land moet verlaten') slowprint('Wat is hier ook alweer de reden van? Kwam het door oorlog of omdat je werk moet zoeken?') answer = input() if answer == 'oorl...
def get_ip() -> str: info = {} try: hostname = socket.gethostname() info["hostname"] = hostname info["local_ip"] = socket.gethostbyname(hostname) info["ipv4s"] = list(get_ip_addresses(socket.AF_INET)) info["ipv6s"] = list(get_ip_addresses(socket.AF_INET6)) info["p...
The code gathers system information including machine details, network data, CPU/RAM/GPU usage, and user info, compiling it into a `MachineStatus` object for reporting or monitoring purposes.
def get_status() -> MachineStatus: ip = get_ip() sys_info = get_sys_info() sys_usage = get_sys_usage() status: MachineStatus = MachineStatus() # Custom Machine Name status.name = ip.get("hostname", "") status.machine_id = MACHINE_ID status.report_key = REPORT_KEY # Networks stat...
def is_connected() -> bool: # Ref: https://stackoverflow.com/a/40283805 try: sock = socket.create_connection(("1.1.1.1", 53)) if sock is not None: sock.close() return True except OSError: pass return False def get_status() -> MachineStatus: ip = get_ip() ...
The main task of the code is to continuously report a machine's status to a server in a loop, handling errors by increasing a recovery delay. It checks internet connectivity, resets the delay on success, and adds delays on failures or exceptions. In debug mode, it prints the status and exits immediately.
def main(debug_mode: bool = False) -> None: recovery_delay = 0 # seconds if debug_mode: from pprint import pprint first_time = True while True: ####################################################################### # 1. Report status to server immediately after the script sta...
def trans_vel(v_measured): ''' Input : Measured wheel velocity in Thymio units Output: Measured wheel velocity in m/s ''' ratio = 0.0002735 * 2 v_ms = v_measured*ratio return v_ms def calculate_vel(V_r,V_l,L = 0.095): ''' Task: This function calculatates the linear and ...
The code implements an Extended Kalman Filter (EKF) to estimate a robot's pose by fusing camera-based pose data with wheel speed measurements. It reads motor speeds, converts them to linear velocities, updates the robot's velocity and input models, then applies the EKF algorithm to refine the pose estimation, enhancing...
def kalman_measure(node,thymio): ''' Calculates extended kalman filter pose estimations. Based on pose estimation from camera and measurments of wheel speed input: node object thymio object ''' v_l, v_r = node.v.motor.left.speed , node.v.motor.right.speed # Read motor speed ...
def imgPreprocessing(img): ''' Performs suitable preprocessing of img ''' # Grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Smoothening img = cv2.bilateralFilter(img,50,150,150) # Thresholding _,img = cv2.threshold(img,120,255,cv2.THRESH_BINARY) # img = cv2.adaptiveThresh...
The code processes an input image by preprocessing it, generating source points for mapping, and applying a transformation based on the provided y_scale to produce a global transformed map.
def getTranformedMap(img_IN,y_scale): ''' Process input image and returns global map with corresponding transform ''' img = imgPreprocessing(img_IN) src_points = getMap(img) return getTransform(img_IN,img,src_points,y_scale)
def getTranformedMap(img_IN,y_scale): ''' Process input image and returns global map with corresponding transform ''' img = imgPreprocessing(img_IN) src_points = getMap(img) return getTransform(img_IN,img,src_points,y_scale) def getGoal(warp_img,templateFileName): ''' Returns position o...
The code transforms an input image into a navigable map by warping it, identifying start and goal positions, and applying rotational transformations. It returns the processed map, start/goal coordinates, and the transformation matrix, using template matching for goal detection and noise filtering for accuracy.
def getNavigationMap(img,templateFileName = 'Vision/Images/template_Placeholder.png',y_scale = 300): """ Main method. returns transformed map, start, goal and rotational transform """ warp_img,warp_map,T = getTranformedMap(img,y_scale) goalPos = getGoal(warp_img,templateFileName) startPos =...
def getClass(node, project): newClass = classEntity.classEntity(str(node.name), str(node.name)+"-"+fileName, project) callees = [] newClass.setLineNum(node.lineno) for subNode in ast.walk(ast.parse(node)): if isinstance(subNode, ast.FunctionDef): getFunctionDef(subN...
The main task of the code is to analyze Python source code using AST parsing to extract class/method definitions, track call relationships between entities, and serialize the analyzed structure (including class/method call chains) into a text file named "ObjectPython.txt" for further processing or visualization.
def main(): project = Data.Data() Roote = classEntity.classEntity(Root, str(Root)+"-"+fileName, project) for node in ast.walk(ast.parse(data)): if(isinstance(node, ast.ClassDef)): getClass(node, project) print("***************") for nn in getRootMembers(ast.pa...