dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def add_symbol(self, instruction): if instruction[2] in self.mapper: self.units[instruction[0]] = instruction[2] return instruction[0] + ' is ' + instruction[2] + ' in Roman Numbers' else: return self.error_msj def add_conversion(self, instruction): if len(ins...
This function decodes user instructions to perform unit or credit conversions. It splits the input, checks keywords like 'is', 'Credits', 'much', or 'many', and delegates to appropriate methods (add_symbol, add_conversion, convert_units, convert_credits). It returns formatted conversion results or error messages based ...
def instruction_decoder(self, instruction): instruction = instruction.split() if len(instruction) < 3: return self.error_msj if instruction[1] == 'is': return self.add_symbol(instruction) elif instruction[-1] == 'Credits': return self.add_conversion(in...
def isdigit(n): """ checks if a str is a digit """ for c in n: if not (ord(c) >= 48 and ord(c) <= 57): return False return True def restrict(board, row, col): """restict areas covered by queen""" # horizontal for i in range(len(board[row])): if board[row][i] ...
The main task of the code is to solve the N-Queens problem by validating input N (must be ≥4), initializing chessboards with queens in each column of the first row, applying constraints, generating solutions via backtracking, and printing optimal solutions. It checks command-line arguments, ensures N is a valid integer...
def main(): """Program entry point""" argc = len(sys.argv) if argc != 2: print("Usage: nqueens N") sys.exit(1) N = sys.argv[1] if not isdigit(N): print("N must be a number") sys.exit(1) n = int(N) if n < 4: print("N must be at least 4") sys....
def hexagrid_size_to_rows_cols (size, gap, radius): inner_horizontal = size [X] - hexagrid_overlap_horizontal (gap, radius) inner_vertical = size [Y] - hexagrid_overlap_vertical (gap, radius) cols = math.ceil (inner_horizontal / hexagrid_spacing_horizontal (gap, radius)) rows = math.floor (math.ceil (...
This function generates a 3D model of a lower holder component by combining hexagonal grid structures, cylindrical bends, and hooked parts. It calculates geometric parameters, positions hexagonal inserts with offsets, creates a bent back section, and attaches a hooked mechanism. The final output is a union of these ele...
def holder_lower (): back_rows, back_cols = hexagrid_size_to_rows_cols ((BACK_WIDTH, BACK_WIDTH, 0), HEX_GAP, HEX_RADIUS) back_size = size_to_hexagrid_size ((BACK_WIDTH, BACK_WIDTH, BACK_THICKNESS), HEX_GAP, HEX_RADIUS) body_hex_gap = 3*HEX_GAP + 2*INSERT_SLACK body_hex_radius = HEX_RADIUS - (INSERT_S...
def hexagrid_size_to_rows_cols (size, gap, radius): inner_horizontal = size [X] - hexagrid_overlap_horizontal (gap, radius) inner_vertical = size [Y] - hexagrid_overlap_vertical (gap, radius) cols = math.ceil (inner_horizontal / hexagrid_spacing_horizontal (gap, radius)) rows = math.floor (math.ceil (...
The main task of the code is to generate a 3D hexagonal grid-based holder structure with sloped sections and attached walls. It calculates grid dimensions, constructs a hexagonal back panel, creates a sloped transition using transformations, and adds rounded walls on the right and bottom edges. The final output combine...
def holder_upper (): back_rows, back_cols = hexagrid_size_to_rows_cols ((BACK_WIDTH, BACK_HEIGHT, 0), HEX_GAP, HEX_RADIUS) back_size = size_to_hexagrid_size ((BACK_WIDTH, BACK_HEIGHT, BACK_THICKNESS), HEX_GAP, HEX_RADIUS) wall_ratio = BACK_SLOPE / back_size [X] wall_angle = math.atan (wall_ratio) w...
def hexagrid_pierced_slab (size, gap, radius, rim): piercing_spacing_vertical = hexagrid_spacing_vertical (gap, radius) piercing_spacing_horizontal = hexagrid_spacing_horizontal (gap, radius) cols = int (size [X] // piercing_spacing_horizontal) + 2 rows = int (size [Y] // piercing_spacing_vertical) + ...
The code defines a function `holder_lower` that constructs a 3D model of a lower structural component, combining geometric shapes like cubes and hexagonal slabs. It assembles stands, folds, ridges, screw holes, pin holes, and cutouts, then combines these elements while subtracting specified holes and cutouts to form a ...
def holder_lower (): back = hexagrid_pierced_slab ((PLUG_WIDTH + GAP_WIDTH, BOTTOM_BODY_HEIGHT, BACK_THICKNESS), HEX_THICKNESS, HEX_RADIUS, HEX_RIM) stand_left_bottom = translate ((0, 0 - RUNG_OVERLAP, 0)) (cube ((STAND_SIZE, STAND_SIZE + RUNG_OVERLAP, GAP_DEPTH))) stand_right_bottom = translate ((PLUG_WI...
def hexagrid_pierced_slab (size, gap, radius, rim): piercing_spacing_vertical = hexagrid_spacing_vertical (gap, radius) piercing_spacing_horizontal = hexagrid_spacing_horizontal (gap, radius) cols = int (size [X] // piercing_spacing_horizontal) + 2 rows = int (size [Y] // piercing_spacing_vertical) + ...
The main task of the code is to generate a 3D model for an upper holder component, combining structural elements like hexagonal back panels, vertical stands (bottom and top), a folded wall, screw holder, and pin holes. It constructs and positions geometric shapes (cubes, hexagons) using translation and union operations...
def holder_upper (): back = hexagrid_pierced_slab ((PLUG_WIDTH + GAP_WIDTH, TOP_BODY_HEIGHT, BACK_THICKNESS), HEX_THICKNESS, HEX_RADIUS, HEX_RIM) stand_left_bottom = translate ((0, 0, 0)) (cube ((STAND_SIZE, STAND_SIZE, GAP_DEPTH))) stand_right_bottom = translate ((PLUG_WIDTH - STAND_SIZE, 0, 0)) (cube ((...
def read_lines_zst(file_name): with open(file_name, 'rb') as file_handle: buffer = '' reader = zstandard.ZstdDecompressor(max_window_size=2**31).stream_reader(file_handle) while True: chunk = read_and_decode(reader, 2**27, (2**29) * 2) if not chunk: break lines = (buffer + chunk).split("\n") fo...
The main task of the code is to filter and transform JSON data from an input file into a specified output format (zst, txt, or csv), applying criteria such as date ranges, field-value matches (exact or substring), and submission status. It processes each line, skips non-matching entries, logs progress, and writes valid...
def process_file(input_file, output_file, output_format, field, values, from_date, to_date, single_field, exact_match): output_path = f"{output_file}.{output_format}" is_submission = "submission" in input_file log.info(f"Input: {input_file} : Output: {output_path} : Is submission {is_submission}") writer = None if...
def myRF(self,M,feature_unique_values): samples = self.training_data if self.bin_classification: classes = self.training_classes else: classes = self.training_prices # array to store trees random_forest = [] training_smap...
The code processes data by splitting it into training and validation sets, trains a random forest model with M trees, validates the model, applies linear regression on the forest's predictions, and calculates evaluation metrics (RMSE and SMAPE) for the validation set.
def process(self): # opening and reading data from data file feature_unique_values,bin_classes,data = self.preProcessor.getCategoricalData() data = np.array(data) # random shuffle data np.random.seed(0) np.random.shuffle(data) # splitting training and validation...
def active_change(self) -> None: if self.active_change_callback: self.active_change_callback() def step(self) -> None: """ Performs one single mouse operation of the drawing sequence. Automatically rolls over to the next contour if the current one is exhausted. """ ...
The main task of the code is to repeatedly execute the `step()` method at fixed time intervals defined by `DrawingParameters.sleep_between_action`, continuing until all contours are completed. The loop maintains an active state, pauses between steps, and terminates by deactivating the state and printing "Done drawing."...
def thread_loop(self) -> None: """ Continually calls step in fixed time intervals (DrawingParameters.sleep_between_action). Terminates once all contours are finished """ self.active = True self.active_change() self.exit = False while not self.exit: ...
def draw_start_board(width = cfg.width, height = cfg.height, x_offset = cfg.x_offset, y_offset = cfg.y_offset, color = cfg.start_color): image, draw = draw_clean_board(width, height) add_tiles(TileSet([Tile(1, 0, (0, 3)), Tile(2, 0, (0, 3))]), draw, x_offset = x_offset, y_offset = y_offset, height = height, col...
The function generates a visual representation of a winning game board by initializing a board with specified dimensions and offsets, highlighting the 'done_state' with white tiles, and filling predefined squares to indicate the winning configuration. It returns the modified image and drawing context for rendering.
def draw_winning_board(highlight_state = done_state, width = cfg.width, height = cfg.height, x_offset = cfg.x_offset, y_offset = cfg.y_offset): image, draw = draw_start_board(width, height, x_offset, y_offset) add_state_tiles(highlight_state, draw, color = (255, 255, 255, 255)) draw = fill_squares(draw, [(0...
def css_hex(self, explicit_alpha: bool = False) -> str: """Get the color as a CSS hexadecimal color value. Parameters ---------- explicit_alpha : bool, default: False If True, an alpha channel is added if it is not already present. Returns ------- st...
This method converts a color to a CSS-formatted string based on the specified system (hex, rgb, hsl, hwb), with options to control decimal precision, percentage notation, hue units, and alpha channel inclusion. It delegates to specialized methods for each system, ensuring the output adheres to CSS standards while respe...
def css( self, system: _Literal["hex", "rgb", "hsl", "hwb"], decimals: int = 2, percent: bool = False, hue_unit: _Literal["deg", "grad", "rad", "turn"] = "turn", hue_wrap: bool = False, explicit_alpha: bool = False, ) -> str: """Get the color as a CSS ...
def rgb(self, ubyte: bool = False, explicit_alpha: bool = False) -> _np.ndarray: """Get the color as an RGB(A) array. Parameters ---------- ubyte : bool, default: False If True, the values are returned as unsigned bytes (uint8) in the range [0, 255] instead of th...
The main task of the code is to retrieve color component values in a specified coordinate system (e.g., RGB, HSL, HSV, HWB) as a NumPy array. It allows customization of hue units, alpha channel inclusion, and output format (float or unsigned byte). The function delegates to internal methods for each color system and re...
def array( self, system: _Literal["rgb", "hsl", "hsv", "hwb"], hue_unit: _Literal["deg", "grad", "rad", "turn"] = "turn", hue_wrap: bool = False, explicit_alpha: bool = False, ubyte: bool = False, ): """Get the color component values in the specified coordinat...
def solve_narrow(self, result): A = result["loss"] c = 2 A1 = A + 1 a = [0.25 * A1, 0.25 * A1, A1, 0.25 * A1, 0.2 * A1, 0.2 * A1] return self.spsa(A, a, c, result["values"], iters=500) def solve_wide(self): A = 5 c = 15 a = [60, 180, 18000, 600, 1.2, 1.2] ...
The code iteratively optimizes a model's parameters by alternating between solving a wide and narrow version of the problem. It updates the current result if the new loss is lower, stopping early if the loss drops below 1. Finally, it returns the optimized values, loss, and a processed version of the values using the c...
def solve(self): curr_result = {"loss": float("inf")} for i in range(100): if curr_result["loss"] < 1: break new_result = self.solve_narrow(self.solve_wide()) if new_result["loss"] < curr_result["loss"]: curr_result = new_result ...
def open_hid_device(vendor_id, product_id, serial_number): try: device_info = None devices = hid.enumerate() for info in devices: if info['vendor_id'] == vendor_id and info['product_id'] == product_id and info['serial_number'] == serial_number: device_info = info ...
This function performs integrity verification by sending a C1 command and receiving a C2 response via a USB HID device. It transitions through states (SEND_C1 → RECV_C2 → FINISH) to validate data integrity, returning SUCCESS if all steps complete successfully or FAIL if any step fails.
def integrityVerifyHandle(): global usb_hid integrityVerifyState = INTERGRITY_VERIFY_SEND_C1 usb_hid = open_hid_device(vendor_id, product_id, serial_number) while integrityVerifyState != INTERGRITY_VERIFY_FINISH: if integrityVerifyState == INTERGRITY_VERIFY_SEND_C1: if SUCCESS == int...
def integrityVerifyHandle(): global usb_hid integrityVerifyState = INTERGRITY_VERIFY_SEND_C1 usb_hid = open_hid_device(vendor_id, product_id, serial_number) while integrityVerifyState != INTERGRITY_VERIFY_FINISH: if integrityVerifyState == INTERGRITY_VERIFY_SEND_C1: if SUCCESS == int...
The code executes a sequence of security protocol steps: integrity verification, mutual authentication, key exchange, and application startup. It transitions through states until completion, returning SUCCESS if all steps succeed or FAIL if any step fails.
def coreRun(): global r ret = SUCCESS state = INTERGRITY_VERIFY while state != FINISH: if state == INTERGRITY_VERIFY: if SUCCESS == integrityVerifyHandle(): state = MUTAL_AUTHENCATION else: ret = FAIL elif state == MUTAL_AUTHENCATI...
def theory_transfer_frame(Q,position): print("theory_transfer_frame Q" , Q) print("theory_transfer_frame position", position) in_quan_x = Q[0] in_quan_y = Q[1] in_quan_z = Q[2] in_quan_w = Q[3] in_quan = [in_quan_w,in_quan_x,in_quan_y,in_quan_z] in_rot_matrix = quaternion_ro...
The main task of the code is to compute and compare theoretical and physical transformation frames, broadcast them as TFs for visualization, and calculate positional and angular errors between the two. It iterates through input data, constructs transformation matrices, extracts translation/rotation values, publishes TF...
def main(self): frame_to_view=3 theory_transfer_frames = [[]] for i in range(len(quan_test_xyzw)): i +=1 if i == len(quan_test_xyzw): break # theory_transfer_frames = np.append(theory_transfer_frames,theory_transfer_frame(quan_test_xyzw[i],post...
def theory_transfer_frame(Q,position): print("theory_transfer_frame Q" , Q) print("theory_transfer_frame position", position) in_quan_x = Q[0] in_quan_y = Q[1] in_quan_z = Q[2] in_quan_w = Q[3] in_quan = [in_quan_w,in_quan_x,in_quan_y,in_quan_z] in_rot_matrix = quaternion_ro...
The main task of the code is to compute and compare theoretical and physical transformation frames for robotic systems. It generates transformation matrices from test data, broadcasts them as ROS transforms for visualization, and calculates positional (distance) and angular (orientation) errors between the theoretical ...
def main_post(self): frame_to_view=5 theory_transfer_frames = [[]] for i in range(len(quan_test_xyzw)): i +=1 if i == len(quan_test_xyzw): break # theory_transfer_frames = np.append(theory_transfer_frames,theory_transfer_frame(quan_test_xyzw[i]...
def dot_product(self,x, y): return sum([x[i] * y[i] for i in range(len(x))]) def norm(self, x): return sqrt(self.dot_product(x, x)) def normalize(self,x): return [x[i] / self.norm(x) for i in range(len(x))]
This function projects a vector `x` onto a plane with normal vector `n` by subtracting the component of `x` in the direction of `n`, resulting in the orthogonal projection of `x` onto the plane perpendicular to `n`.)
def project_onto_plane(self,x, n): d = self.dot_product(x, n) / self.norm(n) p = [d * self.normalize(n)[i] for i in range(len(n))] return [x[i] - p[i] for i in range(len(x))]
def convert_depth_frame_to_pointcloud(self, depth_image, camera_intrinsics ): """ Convert the depthmap to a 3D point cloud Parameters: ----------- depth_frame : rs.frame() The depth_frame containing the depth map camera_intrinsics : The int...
The code tracks a hand using depth and color cameras by aligning frames, removing background, detecting blue regions via HSV thresholding, calculating 3D coordinates, and determining orientation. It computes a hand pose (position/rotation) using image processing and publishes the result if the detected hand size matche...
def handtracker_callback(self): try: print("___________Beginning________________") frames = self.pipeline.wait_for_frames()# Get frameset of color and depth # frames.get_depth_frame() is a 640x360 depth image # Align the depth frame to color frame ...
def goodness(v, e, n): global S return(-n * getBCVal(e, S[v]) / S[v]) def getBC(e, size): global BestCache for cc in BestCache[e]: if remaining_size(cc[0]) >= size: return(cc[0]) return(-1) def addVideo(v, BC): if v in CachedVideos[BC]: return for e in Endpoints[B...
The function `processQ()` processes a request from a priority queue (RH) by checking if the "goodness" metric of a video (`v`) has changed. If it has, the updated value is pushed back into the queue. It then calculates a "BC" value for the video, verifies consistency with a `CVE` dictionary, and triggers video processi...
def processQ(): req = heapq.heappop(RH) v = req[2] e = req[3] n = req[4] g = req[0] g2 = goodness(v, e, n) if g2 != g: heapq.heappush(RH, (g2, req[1], v, e, n)) return BC = getBC(e, S[v]) if BC < 0: return if (e, v) in CVE.keys(): if BC != CVE[(e,...
def read_file(filename): inp = open(filename, 'r') global V, E, R, C, X [V, E, R, C, X] = get_arr(inp) global S S = get_arr(inp) global CachedVideos, Endpoints for c in range(C): CachedVideos[c] = [] Endpoints[c] = [] global BestCache BestCache = [0] * E for e...
The main task of the code is to process an input file, execute a loop that profiles the 'processQ()' function while managing data structures (RH, CVE), and output results to a file. It validates command-line arguments, reads input, prints states, runs iterative processing with performance profiling, and writes the fina...
def main(): if len(sys.argv) < 3: sys.exit('Usage: %s input.in output.out'.format(sys.argv[0])) read_file(sys.argv[1]) print("Reading done") printState() i = 0 while len(RH) > 0: print(i, len(RH), len(CVE)) cProfile.run('processQ()') i += 1 printState() ...
def process_data(self, sender_id, buff_data): # self.lock.acquire() data_vals = buff_data.data for scan in data_vals: self.karto_pub.publish(scan) for rid in self.candidate_robots: if rid != sender_id: self.add_to_file(rid, data_vals) def push_mess...
This function processes incoming buffered data from candidate robots. If the sender is a candidate robot, it processes the data, logs receipt, and if the robot is a base station, triggers rendezvous point sharing after collecting initial data from all candidates. Once all data is received, it fetches and publishes rend...
def buffered_data_callback(self, buff_data): sender_id = buff_data.msg_header.header.frame_id if sender_id in self.candidate_robots: self.process_data(sender_id, buff_data) pu.log_msg(self.robot_id, "Received data from: {}".format(sender_id), 1-self.debug_mode) if sel...
def create_buff_data(self, rid, is_alert=0, is_home_alert=False): message_data = self.load_data_for_id(rid) if is_home_alert: message_data = message_data + self.load_data_for_id(self.parent_robot_id) buffered_data = BufferedData() buffered_data.msg_header.header.stamp.secs =...
The main task of the code is to send buffered data to a parent robot via a service call, process the received response, log the interaction, and subsequently delete the data associated with the parent robot's ID.
def share_data_with_parent(self): parent_data = self.create_buff_data(self.parent_robot_id) new_data = self.shared_data_srv_map[self.parent_robot_id](SharedDataRequest(req_data=parent_data)) self.process_parent_data(new_data) pu.log_msg(self.robot_id, "received a response", self.debug_mo...
def get_close_devices(self): robots = [] devices = [] try: ss_data = self.signal_strength_srv(HotSpotRequest(robot_id=str(self.robot_id))) data = ss_data.hot_spots signals = data.signals for rs in signals: robots.append([rs.robot_id...
The code handles robot movement status updates by checking if the current goal status (active/aborted) matches specific IDs related to exploration or rendezvous tasks. If the robot is near a parent device and the status indicates completion or failure, it stops movement, records its position, and sends coordination sig...
def move_status_callback(self, data): id_4 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, FROM_EXPLORATION) id_1 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, TO_RENDEZVOUS) id_0 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, TO_FRONTIER) if ...
def rotate_robot(self): deg_360 = math.radians(360) if self.robot_pose: while self.robot_pose[2] < deg_360: self.move_robot((0, 1)) def move_robot_to_goal(self, goal, direction=1): id_val = "robot_{}_{}_{}".format(self.robot_id, self.goal_count, direction) mov...
This callback function handles navigation status updates for a robot, retrying failed movements to rendezvous points with fallback strategies, logging successes/failures, and transitioning between exploration and rendezvous states. It manages attempt limits, updates failed points, selects alternative goals, and trigger...
def move_result_callback(self, data): id_4 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, FROM_EXPLORATION) id_1 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, TO_RENDEZVOUS) id_0 = "robot_{}_{}_{}".format(self.robot_id, self.goal_count - 1, TO_FRONTIER) if ...
def assess_techniques(self, responseTechniques): #Prepare to do assessments for technique in responseTechniques: #Check if there are any un-assessed techniques if not responseTechniques[technique]['is_assessed']: techniquesForAssessment.append(technique) #If there were no techniq...
The code processes evaluation requests by parsing attack details and response techniques from incoming data, monitoring log files for updates, assessing suitable techniques based on system specifications, saving results to a database, and ultimately determining the optimal response technique to send as an update messag...
def evaluation_requested(self, data): message = pickle.loads(data).split('!.!') self.attackDetails = message[0] self.responseTechniqueApplied = message[1] print('Evaluation requested by ID: {} for {}. The applied response technique is: {}.'.format(str(self.id), self.attackDetails, self.responseTechnique...
def init_message_received(self, data): print('init message received!') self.specifications = pickle.loads(data) self.softwareVersion = self.specifications["software_version"] self.hardwareSpecifications = self.specifications["hardware_specifications"] self.vin = self.specifications["vin"] self...
The code processes incoming byte data by splitting it into individual messages using a delimiter. It identifies message types (init, ACK, message, log, evaluation request) and routes them to corresponding handler functions after removing their prefixes. It also validates collaborative system status before handling eval...
def filter_data(self, data): #Analyze the data, it might have multiple messages stacked together data = data.split(b'!:END:!') #Loop through the messages, skipping last element that returns an empty byte string for message in data[:-1]: #If an init message is received if b'!:init:!' in m...
def get_BD(alphaD, m_be, m_bp): """ !!! Double-check """ mu_D = m_be * m_bp/(m_be + m_bp) return 1/2*alphaD**2 * mu_D def dark_alpha_recomb(T_DM, alphaD, m_be, m_bp, xi): mu_D = m_be*m_bp/(m_be+m_bp) B_D = get_BD(alphaD, m_be, m_bp) fudge_fac = 1.14 conversion_fac = (phys.hbar * phys.c)**2 *...
The function `Gam_pi` calculates the rate of a dark matter recombination or ionization process, combining parameters like binding energy, number density, and temperature. It derives terms for optical depth, recombination rates, and suppression factors, then returns a scaled result involving the product of these factors...
def Gam_pi(x_be, T_DM, rs, alphaD, m_be, m_bp, xi): B_D = get_BD(alphaD, m_be, m_bp) T_D = xi * phys.TCMB(rs) m_D = m_be + m_bp - B_D mu_D = m_be*m_bp/m_D n_D = phys.rho_DM/m_D * rs**3 denom = (3/2 * T_DM * n_D * (1+x_be)) # Calculate x_2s using Hyrec's steady stateassumption # Lya_...
def get_x(y): return 0.5 + 0.5*np.tanh(y) def d_x_be_Saha_dz(rs, alphaD, m_be, m_bp, xi): """`z`-derivative of the Saha equilibrium ionization value. Parameters ---------- rs : float The redshift in 1+z. species : {'singlet', 'triplet'} Returns ------- float ...
The function `dybe_dz` calculates a recombination/ionization rate in a cosmological context, using either the Saha approximation (for high ionization fractions and large rs) or a more detailed dark matter model involving Peebles' equations. It returns a weighted derivative of the ionization fraction with respect to red...
def dybe_dz(y_be, log_T, rs): #rs = np.exp(logrs) T = np.exp(log_T) x_be = get_x(y_be) xD = 1 - x_be if x_be > 0.999 and rs > 2000: # Use the Saha value. dxdz = d_x_be_Saha_dz(rs, alphaD, m_be, m_bp, xi) return...
def get_x(y): return 0.5 + 0.5*np.tanh(y) def norm_compton_cooling_rate(x_be, T_DM, rs, alphaD, m_be, m_bp, xi): """ Gamma_c where dlogT_DM/dt = Gamma_c (T_D - T_DM), in 1/s """ T_D = xi*phys.TCMB(rs) pre = 64 * np.pi**3 * alphaD**2 / 135 * T_D**4 * x_be/(1+x_be) mass = (1 + (m_be/m_bp)*...
This function computes the derivative of the logarithm of dark matter temperature (log_TDM) with respect to redshift (z) by summing contributions from adiabatic expansion, Compton cooling, Rayleigh scattering, and bremsstrahlung processes. It calculates cooling/heating rates using physical models, combining terms like ...
def dlogTDM_dz(y_be, log_TDM, rs): #rs = np.exp(logrs) T_DM = np.exp(log_TDM) x_be = get_x(y_be) eps = 1-T_DM/T_D # Cooling rate due to adiabatic expansion adia = 2/rs #Compton comp = phys.dtdz(rs) * norm_compton_coolin...
def encode(self): with tf.variable_scope("embedding_layer"): pad_word_embedding = tf.zeros([1, self.word_embedding_dim]) # this is for the PAD symbol self.word_embeddings = tf.concat([pad_word_embedding, tf.get_variable('W_train', shape=[sel...
The main task of the code is to construct a sequence-to-sequence model's computation graph. It encodes input data, initializes decoder components for training (if in "train" mode), and connects encoder outputs to the decoder. The function also sets up an optimizer for training. The graph handles both encoding and decod...
def _build_graph(self): encoder_outputs, encoder_state, source_sequence_length = self.encode() if self.mode == "train": self._init_decoder_train_connectors() self.decode(encoder_outputs=encoder_outputs, encoder_state=encoder_state, source_sequence_length=source_sequence_length) ...
def is_weight(w): """Whether w is a weight, not a mobile.""" return is_leaf(w) def size(w): """Select the size of a weight.""" return label(w) def end(s): """Select the mobile or weight hanging at the end of a side.""" return branches(s)[0] def sides(m): """Select the sides of a mobile.""" ...
The function `total_weight(m)` calculates the total weight of a mobile or a single weight. If `m` is a weight, it returns its size. If `m` is a mobile, it recursively sums the total weights of all its components by processing each side's end. This ensures the cumulative weight of the entire structure is computed accura...
def total_weight(m): """Return the total weight of m, a weight or mobile. >>> t, u, v = examples() >>> total_weight(t) 3 >>> total_weight(u) 6 >>> total_weight(v) 9 """ if is_weight(m): return size(m) else: return sum([total_weight(end(s)) for s in sides(m)])
def mobile(left, right): """Construct a mobile from a left side and a right side.""" return tree(None, [left, right]) def side(length, mobile_or_weight): """Construct a side: a length of rod with a mobile or weight at the end.""" return tree(length, [mobile_or_weight]) def weight(size): """Construct...
The code constructs example mobile structures with nested components, returning three mobiles (t, u, v) built using recursive side-weight configurations for testing or demonstration purposes.
def examples(): t = mobile(side(1, weight(2)), side(2, weight(1))) u = mobile(side(5, weight(1)), side(1, mobile(side(2, weight(3)), side(3, weight(2))))) v = mobile(side(4, t), side(2, u)) return (t, u, v)
def is_weight(w): """Whether w is a weight, not a mobile.""" return is_leaf(w) def sides(m): """Select the sides of a mobile.""" return branches(m) def end(s): """Select the mobile or weight hanging at the end of a side.""" return branches(s)[0] def total_weight(m): """Return the total weigh...
The function checks if a mobile structure is balanced by recursively verifying each component's balance and ensuring the torque (weight × length) on both sides is equal. It returns `True` if all parts are balanced and torques match, otherwise `False`.
def balanced(m): """Return whether m is balanced. >>> t, u, v = examples() >>> balanced(t) True >>> balanced(v) True >>> w = mobile(side(3, t), side(2, u)) >>> balanced(w) False >>> balanced(mobile(side(1, v), side(1, w))) False >>> balanced(mobile(side(1, w), side(1, v)...
def total_weight(m): """Return the total weight of m, a weight or mobile. >>> t, u, v = examples() >>> total_weight(t) 3 >>> total_weight(u) 6 >>> total_weight(v) 9 """ if is_weight(m): return size(m) else: return sum([total_weight(end(s)) for s in sides(m)])...
The function `with_totals` creates a new mobile where each node's label is replaced with the total weight of the corresponding subtree, without modifying the original mobile. It recursively computes total weights for each branch, constructs a new tree with these totals as labels, and ensures the original mobile remains...
def with_totals(m): """Return a mobile with total weights stored as the label of each mobile. >>> t, _, v = examples() >>> label(with_totals(t)) 3 >>> print(label(t)) # t should not change None >>> label(with_totals(v)) 9 >>> [label(end(s)) for s in sides(w...
def change_val(self, c, change, sleep_time=0.02, ignore_range=False): final_val = pi.get_servo_pulsewidth(c) + change return self.set_val(c, final_val, sleep_time, ignore_range) def disarm(self): self.set_val(self.thr, self.zeros["thr"]) pi.set_servo_pulsewidth(self.thr, 500) pi....
This code processes user inputs to control hardware parameters, adjusting throttle (thr), elevator (ele), and aileron (ail) values via key commands. It arms/disarms the system with '1'/'2', resets to default positions with '0', and modifies values incrementally. The `change_val` method adjusts parameters, while `pi.set...
def control(self, inp): if inp == "w": print("thr", self.change_val(self.thr, 15)) elif inp == "s": print("thr", self.change_val(self.thr, -15)) elif inp == "2": print("DISARMED") self.disarm() elif inp == "1": print("ARMED") ...
def nearest_neighbor(self, fx, fy, image):#inter i = image.shape[0] j = image.shape[1] resampled = np.zeros((round(i * fy), round(j * fx), 3), image.dtype) for r in range(resampled.shape[0]): for c in range(resampled.shape[1]): index_row = math.floor(r / fy) ...
This function scales an image using specified interpolation methods (nearest-neighbor, bilinear, bicubic, or Lanczos4) based on given scaling factors fx and fy. It returns the scaled image or an error message for unrecognized interpolation names.
def scale(self, fx, fy, interpolation, image):#inter result = None if (interpolation == "neighbor"): result = self.nearest_neighbor(fx, fy, image) elif (interpolation == "bilinear"): result = self.bilinear(fx, fy, image) elif (interpolation == "bicubic"): ...
def test(self, image):#inter return image def scale(self, fx, fy, interpolation, image):#inter result = None if (interpolation == "neighbor"): result = self.nearest_neighbor(fx, fy, image) elif (interpolation == "bilinear"): result = self.bilinear(fx, fy, image) ...
The main task of the code is to perform image transformations based on the input method. The function acts as a dispatcher, calling specific transformation methods (e.g., scale, rotate, affine) according to the input's `method` parameter, using provided parameters like coordinates, scaling factors, or rotation values. ...
def trans(self, input): """the only function the GUI calls performs transformation based on input variables returns resulting image""" method = input.method image = input.image result = None print("for recheck") print(input.x) print(input.y) ...
def _original_generate(self, length, prompt="\n"): ''' Generates a text of 'length' tokens which begins with 'prompt' token if given one. Args: length: length of the text to be generated prompt: starting tokens) (default: "\n") Returns: A string containing the g...
The code generates text using a hybrid approach that combines a Markov model with POS tagging to enhance syntactic correctness while preserving semantic coherence. It first generates text, then iterates through n-grams, checking if their POS tags align with predefined transitions. If mismatches occur, it corrects succe...
def _hybrid_generate(self, length, prompt="\n"): ''' Generates texts using a hybrid approach between POS tagging and our original MarcovModel text generation appraoch. pos tags to words (self.pos_to_token_transitions) pos tags to pos tags (self.transitions) pos mode generates more syntactically co...
def _hybrid_train(self): self._pos_train() self._word_train() def _pos_train(self): ''' Trains the model based on pos_tag - pos_tag transitions aka. populates the transitions dictionary based on this scheme. ''' ''' POPULATING POS_TO_POS DICTIONARY portion ''' self.tokens = sel...
The code trains a language model by populating an n-gram transitions dictionary and calculating an authorship estimator. It processes a corpus, truncates it (with special handling for Shakespeare's works), splits data into training and estimation sets, selects training methods based on model type (hybrid/POS/word), and...
def train(self): ''' Populates 'transitions' dictionary of n-grams, where n is the given order of the model. In addition, calculates authorship_estimator (aka mean and stdev of likelihoods for the second half of the model). ''' split_corpus = self.corpus.split("\n") # If the corpus is william shake...
def _hybrid_generate(self, length, prompt="\n"): ''' Generates texts using a hybrid approach between POS tagging and our original MarcovModel text generation appraoch. pos tags to words (self.pos_to_token_transitions) pos tags to pos tags (self.transitions) pos mode generates more syntactically co...
This code generates text using a statistical language model, selecting between hybrid, position-adapted, or original generation methods based on the instance's 'hybrid' and 'pos' attributes. The method accepts 'length' and 'prompt' parameters, defaulting to a newline prompt, and delegates generation to the appropriate ...
def generate(self, length, prompt="\n"): ''' Generates text based on the statistical language model. ''' if self.hybrid: return self._hybrid_generate(length, prompt) elif self.pos: return self._adapted_pos_generate(length, prompt) else: return self._original_generate(length, pr...
def _hybrid_train(self): # train using pos method nlp = spacy.load("en_core_web_sm") nlp.max_length = len(self.corpus) with nlp.select_pipes(enable=["tok2vec", "tagger"]): self.tokens = nlp(self.corpus) self._pos_train() # train using word method self.tokens = self._tokenize(self.corp...
The code's main task is to build an n-gram language model by populating a 'transitions' dictionary from a processed corpus, while calculating an authorship estimator. It first splits the corpus, reduces its size for efficiency (especially for large datasets like Shakespeare's works), then trains using word, POS, or hyb...
def train(self): ''' Populates 'transitions' dictionary of n-grams, where n is the given order of the model. In addition, calculates authorship_estimator (aka mean and stdev of likelihoods for the second half of the model). ''' split_corpus = self.corpus.split("\n") # If the corpus is william shake...
def createNewBoard(board): new_board = [] for j in board: if j < 15: if j % 10 == 1: new_board.append(8) elif j % 10 == 2: new_board.append(9) elif j % 10 == 3: new_board.append(10) else: new_...
The main task of the code is to implement a Q-learning agent that determines the optimal action (suit) to pick from a 4x4 card board using reinforcement learning. When `status=True`, it processes a given board, trains the Q-table via epsilon-greedy policy, and returns the predicted optimal action. When `status=False`, ...
def main(status = False, board = []): if status == True: positions_array = createNewBoard(board) # print("This is the new board: ", positions_array) board = [] # Empty board j = 0 while j < 13: board.append([positions_array[j], positions_array[j + 1], positions_a...
def generateActions(self): # For each cell populate the unique valid actions. for i in range(0,4): for j in range(0,4): #current position a,b = i,j # possible swappable positions # Top Left c,d = i-1,j-1 ...
This code initializes a game environment for a turn-based strategy game, setting up the board, action space, and loading a pre-trained model for the agent. It defines the game state representation, action mappings, and initializes the AI model for decision-making.
def __init__(self, model_path): """This constructor sets up the Game Object. Arguments: model_path: refers to the path to the weights of Agent Gold. """ # pieces are represented in phase II format where # positive numbers are of the Agents, negative numbers a...
def _rename_file(self, file: str) -> None: """Rename file and add one to global counter. Args: file (str): file name without path """ old_file = f"{self.filepath}/{file}" new_file: str = self.conform_filepath(file) os.rename(old_file, new_file) def add_one_it...
The function processes each file in the input iterable by renaming them individually, tracks the total number of items processed, and returns the final result of the renaming operation.
def iterate_filtered_files(self, filter_items: Iterable[Path]) -> str: """Iterate through an iterable with all files you want to rename. Args: filter_items (Iterable[Path]): Iterable Returns: str: final result from operation """ files: list[str] = [x.nam...
def set_item_present(boolean): global item_present item_present = boolean def set_employee(employee_object): global employee employee = employee_object def find_name_from_database(text): global employees_found split_text = text.split(" ") proper_name = text new_name = "" for name in ...
The code repeatedly checks if an item is present in an image, uses OCR to extract text from the image, processes the text to identify an employee from a database, and updates the item's presence status. It increments a counter on successful detection and resets it if the item isn't found, looping until a stop event is ...
def run(self): global try_counter global image_to_text global cv_image while not self._stopevent.isSet( ): print(image_to_text) if image_to_text != 0: if segmentation.check_if_item_present(cv_image): try_counter += 1 ...
def exception_handle(sock): print('The IRC Server is Not Responding') quit_procedure(sock) exit() def join_multiple_rooms_procedure(h_socket, command): rooms = command[1:] for room in rooms: if room in room_list: print(f'Already in room: {room}') continue if len(room) ...
This code defines a command handler function for an IRC-like client application. It processes user input commands such as joining/exiting rooms, sending messages, listing room members, handling files, and managing secure communications. The function validates command arguments, interacts with a server socket, manages r...
def s_handler(h_socket,user_name): global error_count while True: enter_input = input('%s:\n' %(user_name)) input_split = enter_input.split(' ') functionality = input_split[0] if functionality == 'join-room': if len(input_split) < 2 or len(input_split[1].strip()) == 0: print('Argument_Error1: Command h...
def normed_u_dist(net, hex_grid=False): """ Normalize the unified (aka averaged) distances of each cell to a number in [0,1]. """ normed_u_dist = [] for row in range(net.shape[0]): u_row = [] for col in range(net.shape[1]): u_row.append(get_unified_distance(row, col, net,...
This function generates cell shapes (square, hexagonal, or circular) from a grid network, assigning colors based on input data or normalized distances, and returns them as structured coordinates with metadata for visualization.
def get_cell_shapes(net, data, udist=True, dim_index=-1, colormap=default_colormap, out_stand=False, hex_grid=False, as_circles=False, s=2): """ Get the cell shapes from a grid network. """ rows = net.shape[0] cols = net.shape[1] if udist==True: u_dist = normed_u_dist(net, hex_...
def get_meta_descriptions(website_url): base_dir = os.path.dirname(os.path.realpath(__file__)) filename = f"meta_descriptions/{get_filename(website_url, suffix='meta_descriptions')}" file_path = os.path.join(base_dir, filename) if os.path.exists(file_path): with open(file_path, 'r') as f: ...
The code creates a Streamlit web app for SEO analysis. It accepts a website URL, fetches SEO data (meta descriptions, warnings, keyword frequencies, and image details), and displays results: warning messages, generated meta descriptions, keyword frequency charts, and image comparisons with AI-generated alt text. The pr...
def app(): with st.container(): st.title = 'Macaws SEO Tool' website = st.text_input(placeholder='Enter your website eg. http://example.com', label='Website') submit_btn = st.button(label='Submit') if submit_btn: with st.spinner('Loading website data. This might take a wh...
def replace_comma_tokens(value): return value.replace("(c)", ",") def extract_foreach_values(list_string, cursor): list_string = list_string.replace('["', "") list_string = list_string.replace('"]', "") values = list_string.split('", "') unique_values = [] for value in values: if value ...
This function processes a CSV row to insert data into a database table, mapping CSV columns to database columns, cleaning values (e.g., handling commas, special characters, encoding), validating uniqueness, and handling 'foreach' fields to generate multiple inserts. It ensures data consistency, skips duplicates for uni...
def insert_new_entry(row, table_name, cursor): table_name = table["name"] table_mappings = table["mappings"] foreach_values = None foreach_column = None table_column_to_csv_value = {} for table_mapping in table_mappings: # From the table field we want to get, find the associated CSV v...
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def set_to_review(self): self.stage = "Review" def set_to_easy_graduating_interval(self): self.interval = self.easy_graduating_interval self.clip_interval() def set_next_review_date_to_interval(s...
The `learn_easy` method updates the learning process for an easy item by adding a guess to the history, marking it for review, setting its graduating interval for easy items, and scheduling the next review date based on that interval. This ensures the item is appropriately spaced for future review, reinforcing retentio...
def learn_easy(self): self._cond_add_guess_to_history("easy") self.set_to_review() self.set_to_easy_graduating_interval() self.set_next_review_date_to_interval()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def clip_interval(self): self.interval = min(self.interval, self.max_interval) def set_next_review_date_to_interval(self): self._next_review_date = datetime.now() + timedelta(days=self.interval)
This method adjusts the review interval for an "easy" response in a spaced repetition system. It calculates a new interval based on the current interval, ease factor, and a bonus, ensures the interval increases, clips it to valid limits, updates the next review date, and increments the ease factor to encourage longer f...
def review_easy(self): self._cond_add_guess_to_history("easy") interval = self.interval * (self.ease * self.easy_bonus) next_int = math.ceil(interval) if next_int == self.interval: next_int += 1 self.interval = next_int self.clip_interval() self.set_next_review_date_to_interval() ...
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def clip_interval(self): self.interval = min(self.interval, self.max_interval) def set_next_review_date_to_interval(self): self._next_review_date = datetime.now() + timedelta(days=self.interval)
This method handles the relearning process for an "easy" item by updating the history with the guess, transitioning the stage to "Review", setting the interval to the easy graduating interval, clipping the interval to valid bounds, and scheduling the next review date based on the adjusted interval.
def relearn_easy(self): self._cond_add_guess_to_history("easy") self.stage = "Review" self.interval = self.easy_graduating_interval self.clip_interval() # Ambitious easy graduating interval :) self.set_next_review_date_to_interval()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def is_ready_to_graduate_learn(self) -> bool: return self.step == len(self.learning_steps) - 1 def set_to_review(self): self.stage = "Review" def set_to_graduating_interval(self): self.interval =...
This code handles the learning process when a "good" guess is made. It updates the history, checks if the item is ready to graduate from learning, and transitions to review mode with interval scheduling if ready. If not, it increments the learning step and schedules the next review based on the current step.
def learn_good(self): self._cond_add_guess_to_history("good") if self.is_ready_to_graduate_learn(): self.set_to_review() self.set_to_graduating_interval() self.set_next_review_date_to_interval() else: self.step += 1 self.set_next_review_date_to_learning_step()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def clip_interval(self): self.interval = min(self.interval, self.max_interval) def set_next_review_date_to_interval(self): self._next_review_date = datetime.now() + timedelta(days=self.interval)
This function adjusts the review interval for a card marked as "good" by calculating a new interval using the current interval and ease factor, ensuring the interval is sufficiently increased, clipping it to valid bounds, and scheduling the next review date accordingly.
def review_good(self): self._cond_add_guess_to_history("good") interval = self.interval * self.ease next_int = math.ceil(interval) if next_int == self.interval: next_int += 1 self.interval = next_int self.clip_interval() self.set_next_review_date_to_interval()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def is_ready_to_graduate_relearn(self) -> bool: return self.step == len(self.relearning_steps) - 1 def set_to_review(self): self.stage = "Review" def set_next_review_date_to_interval(self): self....
This method handles the relearning process when a "good" guess is recorded. It checks if the item is ready to graduate from relearning; if so, it transitions to the review phase and schedules the next review interval. If not, it increments the relearning step and adjusts the next review date accordingly, managing the s...
def relearn_good(self): self._cond_add_guess_to_history("good") if self.is_ready_to_graduate_relearn(): self.set_to_review() self.set_next_review_date_to_interval() else: self.step += 1 self.set_next_review_date_to_relearning_step()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def has_only_one_learning_step(self) -> bool: return len(self.learning_steps) == 1 def set_review_date_to_one_card_hard_delay_learning(self): """ Sets delay for when there is only one card and recall...
This method adjusts the review date for a learning card based on its difficulty and learning step. It adds a "hard" guess to the history, then sets the next review date: either a fixed delay for single-step learning, an average of the first two steps for initial learning, or a dynamic date for subsequent steps.
def learn_hard(self): self._cond_add_guess_to_history("hard") if self.has_only_one_learning_step(): self.set_review_date_to_one_card_hard_delay_learning() elif self.is_first_step(): self.set_review_date_to_average_of_first_two_steps_learn() else: self.set_next_review_date_to_learning_s...
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def clip_interval(self): self.interval = min(self.interval, self.max_interval) def set_next_review_date_to_interval(self): self._next_review_date = datetime.now() + timedelta(days=self.interval)
This method adjusts parameters for a "hard" card review in a spaced repetition system. It logs the difficulty, increases the review interval using a modifier, ensures the interval stays within bounds, reduces the ease factor (making future reviews harder), and updates the next review date based on the adjusted interval...
def review_hard(self): self._cond_add_guess_to_history("hard") self.interval *= math.ceil(self.hard_interval_modifier) self.clip_interval() self.ease = max(self.ease - 0.15, 1.3) self.set_next_review_date_to_interval()
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def has_only_one_relearning_step(self) -> bool: return len(self.relearning_steps) == 1 def set_review_date_to_one_card_hard_delay_relearning(self): """ Sets delay for when there is only one card and ...
This method adjusts the review date for a "hard" relearning scenario by conditionally setting the next review date based on the current relearning step. It adds a "hard" guess to history, checks if it's the first or only relearning step, and applies different delay strategies accordingly: a fixed hard delay for single ...
def relearn_hard(self): self._cond_add_guess_to_history("hard") if self.has_only_one_relearning_step(): self.set_review_date_to_one_card_hard_delay_relearning() elif self.is_first_step(): self.set_review_date_to_average_of_first_two_steps_relearn() else: self.set_next_review_date_to_re...
def _cond_add_guess_to_history(self, rating): if self.keep_history: self._add_guess_to_history(rating) def clip_interval(self): self.interval = min(self.interval, self.max_interval) def set_to_relearning(self): self.stage = "Relearning" def set_next_review_date_to_relearning_step(self): self._next...
The method `review_again` adjusts review parameters after a card is reviewed again. It updates the card's difficulty (ease) by reducing it, recalculates the review interval using a modifier and minimum threshold, clips the interval to valid bounds, resets the review step, marks the card for relearning, and schedules th...
def review_again(self): self._cond_add_guess_to_history("again") self.ease = max(self.ease - 0.20, 1.3) self.interval = math.ceil(max(self.interval * self.new_interval_modifier, self.lapse_minimum_interval)) self.clip_interval() self.step = 0 self.set_to_relearning() self.set_next_review_dat...
def learn_easy(self): self._cond_add_guess_to_history("easy") self.set_to_review() self.set_to_easy_graduating_interval() self.set_next_review_date_to_interval() def review_easy(self): self._cond_add_guess_to_history("easy") interval = self.interval * (self.ease * self.easy_bonus) next_int ...
The main task of the code is to determine the appropriate action based on the `self.stage` attribute. If the stage is "Learning", it calls `learn_easy()`; if "Review", it calls `review_easy()`; if "Relearning", it calls `relearn_easy()`. For any other stage, it raises a `NotImplementedError`. This method acts as a disp...
def easy(self): match self.stage: case "Learning": self.learn_easy() case "Review": self.review_easy() case "Relearning": self.relearn_easy() case _: raise NotImplementedError()
def learn_good(self): self._cond_add_guess_to_history("good") if self.is_ready_to_graduate_learn(): self.set_to_review() self.set_to_graduating_interval() self.set_next_review_date_to_interval() else: self.step += 1 self.set_next_review_date_to_learning_step() def review...
The code defines a method `good` that delegates tasks based on the `self.stage` attribute. It uses a `match` statement to determine the stage: if "Learning", it calls `learn_good`; if "Review", it calls `review_good`; if "Relearning", it calls `relearn_good". For any other stage, it raises a `NotImplementedError`. The ...
def good(self): match self.stage: case "Learning": self.learn_good() case "Review": self.review_good() case "Relearning": self.relearn_good() case _: raise NotImplementedError()
def learn_hard(self): self._cond_add_guess_to_history("hard") if self.has_only_one_learning_step(): self.set_review_date_to_one_card_hard_delay_learning() elif self.is_first_step(): self.set_review_date_to_average_of_first_two_steps_learn() else: self.set_next_review_date_to_learning_s...
The code defines a method `hard()` that executes different actions based on the `self.stage` value. If the stage is "Learning", it calls `learn_hard()`; if "Review", it calls `review_hard()`; if "Relearning", it calls `relearn_hard()`. For any other stage, it raises a `NotImplementedError`. The main task is to handle s...
def hard(self): match self.stage: case "Learning": self.learn_hard() case "Review": self.review_hard() case "Relearning": self.relearn_hard() case _: raise NotImplementedError()
def learn_again(self): self._cond_add_guess_to_history("again") self.step = 0 self.set_next_review_date_to_learning_step() def review_again(self): self._cond_add_guess_to_history("again") self.ease = max(self.ease - 0.20, 1.3) self.interval = math.ceil(max(self.interval * self.new_interval_modif...
The code defines a method `again` that determines the current stage of a process and triggers corresponding actions: `learn_again()` for "Learning" stage, `review_again()` for "Review", `relearn_again()` for "Relearning", and raises an error for unspecified stages. Its main task is to orchestrate repeated actions based...
def again(self): match self.stage: case "Learning": self.learn_again() case "Review": self.review_again() case "Relearning": self.relearn_again() case _: raise NotImplementedError()
def IsThereNeighboors(assignments): for assignment in assignments: qnt_setslots = 0 for i in range(0,len(assignment.periods)): qnt_setslots = qnt_setslots + len(assignment.periods[i].available) if qnt_setslots > assignment.qnt_week: return True return F...
The function performs optimization on assignments using a tabu search algorithm. It checks if neighbors exist; if so, it runs the tabu search multiple times with specified parameters to find the best solution. If no neighbors are present, it generates an initial solution. The main task is to determine the optimal assig...
def runOptimizationProgram(assignments, max_iterations, tabu_list_size, num_runs): if IsThereNeighboors(assignments): best_solution = RunTabuMultipleTimes(assignments, max_iterations, tabu_list_size, num_runs) else: best_solution = GenerateInitialSolution(assignments) return best_solut...
def validate_setting(self): # validate mandatory settings for attr in self.mandatory: if not attr in self.user_settings or not self.user_settings.get(attr): raise ImproperlyConfigured("SeynseLogger setting: %r is mandatory" % attr) # ImproperlyConfigured ...
This method initializes a logger configuration by setting user-specific settings, default values, and mandatory parameters. It validates the settings, initializes logger formatters, retrieves a handler and logging format, and prepares a global dictionary for logging. The order of operations ensures dependencies are met...
def __init__(self, user_settings=None, defaults=None, mandatory=None): # Initialises logger properties, as later one's depends on # previous one's so don't change the order. self.user_settings = user_settings or {} self.defaults = defaults or {} self.mandatory = mandatory or ()...
def wr16(self, reg_addr, data): buffer = [data & 0xFF, (data & 0xFF00) >> 8] buffer.append(self.crc([self.i2c_addr << 1, reg_addr] + buffer)) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, buffer) def read_current_and_voltage(self): # 4096 is there becacause division by pow of two is simplier and result...
The main task of the code is to configure hardware measurement parameters (sample rate, digital filter, and measurement modes for current/voltage) by validating inputs, setting register values, and initializing the device. It ensures valid configurations, updates control registers, and discards initial invalid readings...
def configure(self, sample_rate_khz=15, digital_filter=1, measure_current=True, measure_voltage=False): if measure_current == False and measure_voltage == False: self.mode = (False, False) self.wr16(0x00, 0x0060) return if measure_current == True and measure_voltage == True: if sample_rate_khz != 0.5: ...
def greedy(self, player, id, positive, prev_action, prev_cards): #This is a greedy search algorithm. #We find the cards with least utility under negative play #return a list of card index. Card is 1 indexed cur_card_list = player.hand.hand legal_actions = self.legal_actions(cur_c...
The function `AI_play` determines the optimal cards for an AI player to play based on their ID (using a greedy algorithm for ID 1 or A* search otherwise). It processes the player's hand, previous game actions, and context (e.g., positive/negative turn) to select valid cards. The chosen cards are converted to 1-indexed ...
def AI_play(self, player, id, positive, prev_action, prev_cards): ''' AI is required here. Ai methods should be in manager.py or player.py? return a list of card index. Card is 1 indexed player.hand: Hand [H5 BJoker RJoker] -> [1, 2, 3] play card BJoker RJoker -> return...
def getIntersectionTime_new(Origin, Direction, OS_Speed): gamma = sqrt(OS_Speed ** 2 + 1) / (OS_Speed ** 2 + 1) c2 = 1 - gamma ** 2 * np.dot(Direction, Direction) c1 = -gamma ** 2 * np.dot(Direction, Origin) c0 = -gamma ** 2 * np.dot(Origin, Origin) delta = c1 ** 2 - c0 * c2 if c2 != 0: ...
The code simulates and visualizes the interception of a Target Ship (TS) and Observer Ship (OS) using multiple methods. It generates random configurations until valid intersections occur, then plots 3D paths and 2D distance analysis. It compares new, brute-force, and old methods for interception calculations, highlight...
def main(): # Create a figure with two subplots fig = plt.figure(figsize=(10, 5)) # Add the first subplot (3D plot) ax = fig.add_subplot(121, projection='3d') # Add the second subplot (2D plot) ax2 = fig.add_subplot(122) # Pick random configuration until it finds desired one while (1): ...
def detector_to_angle(self, detec_pos=None, standard_format=False): """ Given detector position in x,y,z, we calculate the corresponding gamma and delta angles accordingly. This allows us to convert xpp's robot arm movements to what would be the gamma and delta angle movement of a typical 6 circle diffractomete...
The main task of the code is to move a detector to a new position and orientation by updating its axis positions (incident, horizontal, vertical) and Euler angles (alpha, beta, gamma), while converting user-defined input to a standard format. It checks if the new position is within allowed limits, updates the diffracto...
def move(self, detec_pos, detec_orien = None, standard_format=False): """ Moves the detector to a new incidentAxisPos, horizontalAxisPos, virticalAxis pos position and changes the Euler angles. Parameters: detec_pos (array) - x,y,z detec_orien (array) - alpha, beta, gamma standard_format (boolean) - if the ...
def _get_actual_detec_pos(self, detec_pos=None): """ Given a detector position in the detector's frame of reference, applies the neccesary offsets to move into the goniometer's frame of reference. """ # If not given a detec_pos, then we use the current detector pos if detec_pos is None: detec_pos = (self...
This function generates a 2D matrix of 3D coordinates (x,y,z) for each detector pixel based on its position, orientation, and pixel geometry. It applies rotation matrices derived from Euler angles, translates coordinates to the detector's actual position, and optionally applies user-defined transformations (e.g., hkl, ...
def create_from_xyzMatrix(self, detec_pos=None, detec_orien=None, furtherTransformation=None): """ Using detector position and orientation we create a 2D matrix of x,y,z values corresponding to each detector pixel. We can also optionally pass a function which will apply various transformations to the xyzMatrix....
def set_crop_boundary(self, new_crop_boundary=False): """ Sets a new crop bounary for the detector. We pass it through this method to check that the boundary is actually within the detector. """ # If a new crop boundary is not given to us, we set the crop_boundary back to default if new_crop_boundary is Fa...
The code generates a 3D plot visualizing a detector's orientation and position by displaying its coordinate axes, full and cropped regions, and adjusting axis scaling for accurate representation. It aids in verifying the detector's alignment and spatial configuration.
def plot(self, points=False, title=""): """ Plots a rectangular frame representing the detector and its orientation. This is helpful for testing that the detector is in the desired orientation. """ # Create figure fig = plt.figure() ax = plt.axes(projection='3d') # Plot the origin and the unit vectors ...
def clrscr() -> None: """ Clears the console screen using the appropriate command based on the OS. """ print("\033c", end="", flush=True) def slow_print( text: str, speed: int = 5, sleepfor: int = 0, newlineend: bool = True, clear: bool = False ) -> None: for char in text...
The main task of this code is to allow users to select a character from available options based on their stats and save states. It displays character details, checks eligibility, handles menu navigation, and initiates the story with confirmation for overwriting existing saves. The loop ensures valid input and provides ...
def character_selector() -> None: while True: clrscr() characters_stats = process_directory() formatted_characters = compare_stats() available_characters = [] slow_print("Available Characters:\n") for idx, character_name in enumerate(characters_stats.keys(), start=1...
def clrscr() -> None: """ Clears the console screen using the appropriate command based on the OS. """ print("\033c", end="", flush=True) def slow_print( text: str, speed: int = 5, sleepfor: int = 0, newlineend: bool = True, clear: bool = False ) -> None: for char in text...
The function `available_options` displays or triggers actions based on the `selector` parameter. For "main", it lists menu options with indices; for "activities", it checks activities; for "character_selection", it initiates character selection. Its primary task is to present user options or delegate to specific functi...
def available_options(self, selector: str = "main") -> None: clrscr() if selector == "main": menu = [f"{menu_option} [{idx}]" for idx, menu_option in enumerate( self.menu_options.keys(), start=1 ) ] slow_print("\n".join(menu), speed...
def available_options(self, selector: str = "main") -> None: clrscr() if selector == "main": menu = [f"{menu_option} [{idx}]" for idx, menu_option in enumerate( self.menu_options.keys(), start=1 ) ] slow_print("\n".join(menu), speed...
The main task of the code is to present a menu interface, validate user input choices, and execute corresponding functions. It repeatedly displays available options, checks if the input is a valid digit within predefined choices, and invokes the associated function when a valid selection is made, ensuring error handlin...
def mainmenu(self) -> None: while True: self.available_options() slow_print("\nWhat are you picking? ", newlineend=False) choice = input() if not choice.isdigit(): clrscr() slow_print("Invalid option!", sleepfor=2) ...
def make_spectrogram(audio): fft = torch.rfft(audio, signal_ndim=1) fft_squared = fft * fft return torch.sqrt(fft_squared[..., -1] + fft_squared[..., -2]).float() def run_round(model, patch_spectrogram, iterations, verbose=False): n_samples = int(SIGNAL_RATE * SECONDS) t = torch.linspace(0, SECONDS,...
The function optimizes a neural network model by iteratively training it on a spectrogram derived from audio data (`patch_y`), using multiple rounds of training (`rounds`) with specified iterations. It tracks the best model configuration based on loss values, refines it further, and returns the minimal loss and associa...
def find_parameters(model, patch_y, iterations=500, rounds=3): patch_spectrogram = make_spectrogram(patch_y) best = None best_model = None for round_idx in range(rounds): print(f'/// Round {round_idx} \\\\\\') model.restart() model, loss = run_round(model, patch_spectrogram, iter...
def add_attr(element, element_dict): """ This function formats the element_dict by adding the attributes as per the correct schena. Argument: element_dict (dict): element_dict from add_all function element (n/a): xml element Returns: element_dict (dict): formatted element dictionary """ attri...
The main task of the code is to update an element dictionary by adding attributes, tags, types, and nd-members from the input element. It initializes an empty dictionary, sequentially updates it using four helper functions, and returns the modified dictionary containing aggregated element properties.
def add_all(element): """ This function adds all values Argument: element_dict (dict): calculated in shape_element function node_refs (list): calculated in shape_element function member_refs (list): calculated in shape_element function Returns: element_dict (dict): updated element_dict """ eleme...
def _verify_has_errors(self): has_error = False if self._has_high_frequency(): self._violations.append("high-frequency-small-interval") has_error = True if self._has_doubled_transaction(): self._violations.append("doubled-transaction") has_error =...
This method checks if an operation's amount meets a predefined limit. If the amount is below the limit, it applies a discount (if no existing errors) or logs an "insufficient-limit" violation. It updates the operation status based on error presence, ensuring compliance with system constraints.
def _verify_difference(self, operation): has_error = self._verify_has_errors() self._set_status_operation(has_error) if operation.get('amount') < self._limit: self._discount_difference(operation.get('amount')) if not has_error else None else: self._set_status_oper...
def translate_operation(operation): json_operation = json.loads(operation) return json_operation.get('transaction', '') def _verify_operation(self, operation): self.actual_operation = operation self.last_operations.append(self.actual_operation) self._historic.append(self.actual_o...
The main task of the code is to process an operation by translating it using `translate_operation`, verifying it with `_verify_operation`, and returning the JSON-formatted body via `json_body()`. This function ensures the operation is correctly translated and validated before outputting structured data.
def check_operation(self, operation): operation = self.translate_operation(operation) self._verify_operation(operation) return self.json_body()
def register(self, name: str): """ Create payload for register method and send request to server. Sending request is handled on a new thread. """ if (name == ""): self.print_log("Name cannot be empty") return if (self.client_name != ''): ...
This code creates a GUI for a client program using Tkinter, enabling user interaction through input fields, buttons, and a log display. It sets up a window with fields for name, file names, host, and port, along with buttons for actions like Register, Publish, Download, and Connect. The log text area displays messages,...
def gui(self): """ Function to create the GUI for the user to interact with including all entry fields, buttons and log text field """ window = tk.Tk() window.geometry("1200x900") window.title("COEN366 - Networking Project : Client Program") window.resizable(False...
def battery_level(self): """ Return the battery level. The battery level is updated when reading the firmware version. This is done only once every 24h """ self.firmware_version() return self.battery def fill_cache(self): firmware_version = self.firmware_...
The main task of the code is to retrieve a monitored parameter value from a Mi Flora sensor, prioritizing cached data if available and not expired. If caching is disabled or data is stale, it fetches fresh data via Bluetooth. Special handling exists for battery parameters, and the method ensures thread-safe cache updat...
def parameter_value(self, parameter, read_cached=True): """ Return a value of one of the monitored paramaters. This method will try to retrieve the data from cache and only request it by bluetooth if no cached value is stored or the cache is expired. This behaviour can b...
def move_right_face(front_face): old_cube = copy.deepcopy(cube) back_face = get_back_face(front_face) right_face = get_right_face(front_face) # Update top yellow face . front face comes to top yellow face cube[0][2] = old_cube[front_face][2] cube[0][5] = old_cube[front_face][5] cube[0][8] =...
The code performs a sequence of moves on a Rubik's cube's front face using the right-hand rule: rotating the right face, then the upper face, followed by their inverse rotations. This sequence manipulates the cube's state to align pieces during solving.
def perform_right_hand_rule(front_face): move_right_face(front_face) move_upper_face(front_face) move_right_face_inverse(front_face) move_upper_face_inverse(front_face)
def move_left_face_inverse(front_face): move_right_face(front_face) move_right_face(front_face) move_right_face(front_face) def move_upper_face_inverse(front_face): move_upper_face(front_face) move_upper_face(front_face) move_upper_face(front_face) def move_left_face(front_face): set_front_f...
The code performs a sequence of four moves on a Rubik's Cube's front face using the left-hand rule: first rotating the left face inversely, then the upper face inversely, followed by rotating the left face and upper face normally. This sequence is likely part of an algorithm to manipulate cube pieces during solving, al...
def perform_left_hand_rule(front_face): move_left_face_inverse(front_face) move_upper_face_inverse(front_face) move_left_face(front_face) move_upper_face(front_face)
def check_IF_validity(FS, IF): # firstly check if given Internal File name is valid if ((IF[0] == "/") or (IF[0] == ".")): sys.exit(f"Invalid Internal File name.\nExit Code: {ONE}") Lines = read_FS(FS) # check for every line in the FS, return True if file exists for line in Li...
The function copies content from an external file (EF) into a virtual file system (FS) at a specified internal file path (IF). It first checks if IF exists in FS: if so, it clears the existing content; if not, it creates required directories. It then appends EF's content to FS, formatting it with "@IF" headers and spli...
def FS_copyin(FS, EF, IF): # when the given internal file already exists, we comment all of its content and replace it with new one if (check_IF_validity(FS, IF)): delete_FS_file_content(FS, IF) else: create_intermediate_directories(FS, IF) # when the Internal file is a ne...
def check_ID_validity(FS, ID): if (ID.isalnum()): return True elif ("/" in ID): return True else: sys.exit(f"Invalid directory name! Please use standard characters.\nExit Code: {ONE}") def exists_ID(FS, ID): Lines = read_FS(FS) # if the directory does not exist, return t...
The main task of the code is to create a directory in a file system (FS) while validating the directory ID's format (no leading/trailing slashes) and ensuring it doesn't already exist. If valid and non-existent, it creates intermediate directories, writes the new directory entry to the FS file, and confirms success. If...
def FS_mkdir(FS, ID): # check if given directory ID is valid if (check_ID_validity(FS, ID)): if (ID[0] == "/") or (ID[LAST_ELEMENT] == "/"): sys.exit(f"Invalid directory name.\nPlease don't use '/' at the start or end.\nExit Code: {ONE}") # ensure that ID does not alre...
def check_FS_validity(FS): split_string = FS.split(".") if (split_string[LAST_ELEMENT] != "notes"): sys.exit(f"Error! Invalid File System extension.\nExit Code: {ONE}") Lines = read_FS(FS) if (Lines[0] != "NOTES V1.0\n"): sys.exit(f"Error! Valid NOTES version not present.\nExit...
The main task of the code is to act as a command-line interface for a virtual file system (FS), executing operations like listing files, copying data, creating/removing directories/files, and defragmenting based on user input. It parses command-line arguments, validates the FS, and delegates tasks to corresponding func...
def main(): command = sys.argv[ONE] FS = sys.argv[TWO] check_FS_validity(FS) if (command == "list"): FS_list(FS) elif (command == "copyin"): EF = sys.argv[THREE] IF = sys.argv[FOUR] FS_copyin(FS, EF, IF) elif (command == "copyout"): IF ...
def do_train(s: sampler.SamplerThread, opts): try: optimizer = train(s, opts) except Exception as e: print('... stopping on exception:', e) s.cancel() s.join() raise s.cancel() s.join() print('... done training') return optimizer def load_model(opts): ...
The main task of the code is to train and evaluate a machine learning model using the l2d2 library. It parses command-line options for training parameters (epochs, data paths, model saving/loading), loads x86 data, initializes a data sampler thread, trains a model if specified, loads a pre-trained model otherwise, retr...
def main(): import optparse import queue from l2d2 import ingest from l2d2 import options parser = optparse.OptionParser() parser.add_option('--epochs', type=int, default=32, help='Number of iterations through the training data ' 'before complet...
def center_all_centroids(datapoints, centroids): changed = True tmp_dp = datapoints tmp_cents = centroids while (changed): tmp_dp = assign_centroid(tmp_dp, tmp_cents) tmp = center_single_centroid(tmp_dp, tmp_cents) tmp_cents = tmp[0] changed = tmp[1] return tmp_dp, tm...
The code implements a modified K-means clustering algorithm that dynamically adds centroids by iteratively selecting the data point farthest from existing centroids. It initializes with one centroid, then expands clusters by appending new centroids in each iteration, recalculating cluster assignments and centroids. The...
def k_means(datapoints): clusters = list() first_cluster = [datapoints[0][0], datapoints[0][1], 0] clusters.append(first_cluster) clusters = center_all_centroids(datapoints, clusters)[1] wcss_1 = 0 wcss_2 = wcss(datapoints, clusters) diff = wcss_2 print('WCSS_1: %f WCSS_2 %f DIFF: %f' % ...
def read_img(self, filename): img = Image.open(filename) # scale 0~255 to 0~1 np_img = np.array(img, dtype=np.float32) / 255. return np_img def read_cam(self, pose_filename, K_filename): extrinsics = self.read_pkl_array(pose_filename) intrinsics = self.read_pkl_array(K_fi...
The main task of this code is to load and preprocess multi-view stereo (MVS) data for a given scene configuration. It retrieves images, camera intrinsics/extrinsics, and depth maps from specified views, scales/aligns them to a standard resolution, constructs projection matrices, and generates multi-scale versions for d...
def __getitem__(self, idx): global s_h, s_w meta = self.metas[idx] scan, subname, ref_view, src_views = meta # use only the reference view and first nviews-1 source views view_ids = [ref_view] + src_views[:self.nviews - 1] imgs = [] imgs_seg = [] depth_va...
def difference(self, category = None): # if no category is specified, return total size-hits if category is None: _total_diff = self.size() - self.agreement() return _total_diff # if category is specified: return size-2*hits for that category else: ret...
The function calculates the total shift by summing the difference between the difference, quantity, and exchange values across all categories (excluding the last), then dividing by two. If a specific category is provided, it returns the adjusted shift value for that category by subtracting quantity and exchange from th...
def shift(self, category = None): if category is None: # loop each category total_shift = 0 for i in range(len(self.df_row_col_sums)-1): total_shift += (self.difference(i) - self.quantity(i) - self.exchange(i, Total = True)) return total_shift/2 ...
def conf_mat(map1, map2): """This function computes the confusion matrix of two maps.""" # change array to lists as confusion matrix library doesn't work on arrays list1 = np.ndarray.tolist(map1) list2 = np.ndarray.tolist(map2) # turn list of lists into single list and compute confusion matrix l...
This function calculates Pontius' metrics (2014) by loading two raster maps, generating a confusion matrix, converting it to a DataFrame, and using the pontiPy library to compute Overall Accuracy (OA), Total Disagreement (OD), Overall Agreement (OAD), and Overall Quantity Difference (OQD). It returns map identifiers, O...
def calc_multi(pair_id, class1=22): """This function is the basis for calculating Pontius' metrics (2014), starting off by computing the confusion matrix for two provided maps and ending with the Total Disagreement if it is assigned to be calculated.""" map1 = pontius_pairs[pair_id][0] map2 = pontius_p...
def get_offer_by_id(self, offer_id): for offer in self.offers: if offer.uuid == offer_id: return offer return None def __remove_offer_by_id(self, offer_id: str): for offer in self.offers: if offer.uuid == offer_id: self.offers.remove(offer)...
This method processes transaction requests to exchange products. If in "D" mode, it checks if a peer's offer can be exchanged, adjusts the offer's amount or removes it, and records the trade. In "O" mode, it does the same for a demand. It updates trade history and returns "TD" on success, "TN" otherwise.
def handle_transaction_request(self, request: TransactionRequest): if request.mode == "D": # check if peer have the exchange product in any offer to_offer = self.get_offer_by_id(request.offer_demand_uuid) if to_offer.offered_product.can_be_exchanged_with(request.exc_product):...
def list_source_file_paths(base_path: Path) -> list[str]: """List source files in unit test. Args: base_dir (Path): Base directory. Returns: list[str]: Paths of source files. """ source_files = list_source_files(base_path) return sorted( [ str(source_file.r...
The main task of the code is to process source files from multiple directories specified in SOURCE_PATHS. For each directory, it lists all source file paths, then generates Unity source files and CMake variable files to organize and configure build settings. This automates the creation of project structure files for co...
def main(): """Main function""" for base_path in SOURCE_PATHS: file_paths = list_source_file_paths(base_path) write_unity_source(base_path, file_paths) write_cmake_var_file(base_path, file_paths)
def guess_file(fn): 'returns file type' if is_bam(fn): return 'BAM' else: return guess_text_file_type(fn) def get_filename_without_extension(file_path): file_basename = os.path.basename(file_path) filename_without_extension = file_basename.split('.')[0] return filename_without_e...
The code splits genomics data (FASTQ, BAM, etc.) into multiple files based on user-specified parameters: number of files (`-n`), records per file (`-l`), or chromosome-based splitting (`-c`). It handles paired-end reads, detects file types, and outputs files with a customizable prefix and directory. The script ensures ...
def main(): parser = argparse.ArgumentParser(description=""" General utility for splitting genomics data into multiple files.""") parser.add_argument('-i', '--input', help = """input file, set to - to read from stdin, if paired end fastq reads th...
def get_queen_energy_status(self, obs): queens = self.get_units_by_type(obs, units.Zerg.Queen) if len(queens) > 0: queen_energy = [unit.energy for unit in queens] queen = np.argmax(queen_energy) queen_energy = queens[queen].energy return queen_energy, len(...
The code converts game observations into a structured state vector for a neural network by extracting key game metrics like resources, supply, worker counts, queen status, and predicted enemy strategy, then reshaping them into a normalized array for model input.
def build_state(self, obs): self.minerals = obs.observation.player.minerals self.gas = obs.observation.player.vespene self.supply = obs.observation.player.food_used self.supply_cap = obs.observation.player.food_cap self.army_supply = obs.observation.player.food_army self....
def build_state(self, obs): self.minerals = obs.observation.player.minerals self.gas = obs.observation.player.vespene self.supply = obs.observation.player.food_used self.supply_cap = obs.observation.player.food_cap self.army_supply = obs.observation.player.food_army self....
The code processes an observation to update the agent's internal state, calculates an adjusted reward by subtracting penalties for overproduction, selects an action using a choice mechanism based on the current state and unit map, and returns the action. It maintains historical states, tracks game progress, and adjusts...
def step(self, obs): super(honoursAgent, self).step(obs) self.game_result = obs.reward self.build_state(obs) reward = obs.observation.score_cumulative[0] # remove in full release self.reward_debug = reward units_map = self.populate_map(obs) num...
def get_segmentation(self, img): im = img_as_ubyte(img) panoptic_seg, segment_info = self.predictor(im)["panoptic_seg"] return panoptic_seg, segment_info def identify_candidates(self, panoptic_seg, segments_info): potential_mask_ids = [] for segment in segments_info: ...
The code generates augmented object masks from an image's panoptic segmentation by identifying potential candidates, applying scaling, flipping, and shifting transformations, and filtering masks based on area thresholds. It handles both "soft" (single mask) and "rigid" (scene object-based) modes, returning augmented ma...
def get_masks(self, im, return_panoptic=False): panoptic_seg, segments_info = self.get_segmentation(im) potential_mask_ids = self.identify_candidates(panoptic_seg, segments_info) panoptic_seg_scaled = self._prepare_mask(panoptic_seg.detach().cpu().numpy()) downsampled = self.downsample_...
def get_segmentation(self, img,dilated_mask=True): im = img_as_ubyte(img) pred_results = self.predictor(im) instances = pred_results["instances"] masks_set, new_instances = self.identify_candidates(instances) for i, mask in enumerate(masks_set): mask = mask.astype(np....
The code generates a foreground mask by randomly selecting and combining instance masks from segmentation results, ensuring their combined area doesn't exceed a threshold, then returns the binary mask and a visualization of the selected instances.
def get_fg_mask(self,im): masks_set, instances = self.get_segmentation(im) if masks_set == []: return None, None target_idxs = [] mask = np.zeros(shape=im.shape[:2]) max_objs = min(self.max_obj_num,len(masks_set)) objs_num = np.random.randint(1,max_objs) if m...
def di(sect, ybar): ''' Return the distance from the centroid of the section to the centroid of the shape''' di = yi(sect) - ybar return di def ybar(dim): ''' Return the location of the centroid of the shape''' sum1 = 0 for sect in range(len(dim)): sum1 += yi(dim[sect]) * area(dim[sect])...
The code calculates the total moment of inertia (I) for a composite shape by summing individual section moments and applying the parallel axis theorem. It iterates through each dimension segment, computes the distance from the centroid (ybar), area (area), and section's moment of inertia (I0), then accumulates the tota...
def moment_of_I(dim): ''' Return the I of a given shape''' I_tot = 0 for sect in range(len(dim)): d = di(dim[sect], ybar(dim)) Ai = area(dim[sect]) I = I0(dim[sect]) I_tot += (Ai * (d**2)) + I return I_tot
def ybar(dim): ''' Return the location of the centroid of the shape''' sum1 = 0 for sect in range(len(dim)): sum1 += yi(dim[sect]) * area(dim[sect]) ybar = sum1 / A_tot(dim) return ybar def di(sect, ybar): ''' Return the distance from the centroid of the section to the centroid of the sh...
This function calculates the first moment of area $ Q $ at the neutral axis ($ y_{\text{bar}} $) for determining maximum shear stress ($ \tau_{\text{max}} $) in a beam's cross-section. It iterates through each section in the input geometry, summing contributions from areas below $ y_{\text{bar}} $, adjusting for partia...
def Q_max(dim): '''return the Q at y bar for calculating tau max''' # calculates Q from the bottom y = ybar(dim) Qmax = 0 for sect in dim: top = sect[2] + sect[1] if top <= y: Qmax += abs(di(sect, y)) * area(sect) elif sect[2] < y and top > y: d_n...