dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def deal_hand(n): """ Returns a random hand containing n lowercase letters. ceil(n/3) letters in the hand should be VOWELS (note, ceil(n/3) means the smallest integer not less than n/3). Hands are represented as dictionaries. The keys are letters and the values are the number of times the p...
The main task of the code is to allow a user to play a series of hands in a word game, accumulating total scores. It lets users substitute one letter once per game and replay a hand once, retaining the higher score between the original and replayed attempts. The function handles input for the number of hands, manages s...
def play_game(word_list): """ Allow the user to play a series of hands * Asks the user to input a total number of hands * Accumulates the score for each hand into a total score for the entire series * For each hand, before playing, ask the user if they want to substitute one letter ...
def randomstring(N=10,chars=string.ascii_letters+string.digits): return ''.join(random.choice(chars) for _ in range(N)) def findpath(filetype,sidpath,composition): from app import app app.logger.debug(' inside findpath') elements=sidpath.split("/") elements=[el.lower().replace("_"," ") for el i...
The main task of the code is to batch upload EHR compositions (XML/JSON/FLAT JSON) to an OpenEHR server, creating EHRs if needed, validating data, and returning detailed success/failure statuses including EHR/composition IDs. It handles file parsing, EHR ID generation, server communication, error logging, and post-uplo...
def postbatch1(client,auth,hostname,port,username,password,uploaded_files,tid,check,sidpath,snamespace,filetype,myrandom,comps,inlist): from app import app client.auth = (username,password) app.logger.debug('inside postbatch1') ehrslist=[] number_of_files=len(uploaded_files) if(inlist==True): ...
def _community_inverse_permute(self, node_features, community_belong_list): """ Calculate permutation inversion vector and order community_belong_list, e.g. for community_belong_list ([2, 0, 1], [0, 1, 2]) get vector [1, 2, 0] to order community_belong_list to ([0, 1, 2], [1, 2, 0]) ...
The code computes triplet loss components for nodes based on their community representations. It calculates distances between node features and community means, derives positive (in-community) and negative (out-of-community) distances, and computes mean and hard-negative triplet losses. It also calculates variance of n...
def forward(self, node_features, community_belong_list): # # Step 1: order communities, calculate its representations # permute_community_belong_list = self._community_inverse_permute(node_features, community_belong_list) #calculate community sum representation ...
def top_key(queue): queue.sort() if len(queue) > 0: return queue[0][:2] else: return (float('inf'), float('inf')) def calculate_key(spot, current, k_m): k1 = min(spot.g, spot.rhs) + h(spot.get_pos(), current.get_pos()) + k_m k2 = min(spot.g, spot.rhs) return (k1, k2) def update_v...
This function calculates the shortest path from 'start' to 'end' using a priority queue, adjusting node costs (g and rhs) and propagating updates to neighbors. It iteratively processes nodes, updating their states and re-evaluating keys until the optimal path is found, with visualization via 'draw()' and constraints go...
def calc_shortest_path(draw, queue, start, end, k_m): while (start.rhs != start.g) or \ (top_key(queue) < calculate_key(start, start, k_m)): # print(graph.graph[s_start]) # print('topKey') # print(topKey(queue)) # print('calculateKey') # print(calculateKey(graph, s_...
def next_in_shortest_path(current): min_rhs = float('inf') next = None if current.rhs == float('inf'): print('You are stuck!') else: for neighbor in current.neighbors: # print(i) child_cost = neighbor.g + h(current.get_pos(),neighbor.get_pos()) # print...
This function navigates from a current position toward a goal, checking if the next step in the shortest path is obstructed. If an obstacle is encountered, it halts, scans the environment, updates the movement cost (k_m) using a heuristic, and replans the path. It returns the new position and updated cost, or 'goal' if...
def move_and_rescan(draw, queue, current, end, scan_range, k_m): if(current == end): return 'goal', k_m else: last = current new = next_in_shortest_path(current) if(new.is_object() or new.is_barrier()): # just ran into new obstacle print("obstacle") ...
def folium_map_default(bbox, zoom_start=None, location=None, **kwargs): """ Sensible defaults for a folium map based on the bounding box of the image to be shown. """ if zoom_start is None: zoom_start = zoom_from_bbox(bbox) if location is None: location = center_of_bbox(bbox) kw...
This function generates an interactive folium map from an xarray Dataset containing a single time observation. It applies OWS styling, adds controls (fullscreen/layers), and overlays geospatial data as an image. The map's initial view is set using the dataset's bounding box, zoom level, or specified location. Returns t...
def folium_map(data, ows_style_config=None, enable_fullscreen=True, enable_layers_control=False, zoom_start=None, location=None, **folium_map_kwargs): """ Puts an xarray Dataset with a single observation in time on to ...
def folium_dualmap_default(bbox, zoom_start=None, location=None, **kwargs): """ Sensible defaults for a folium dual map based on the bounding box of the image to be shown. """ if zoom_start is None: zoom_start = zoom_from_bbox(bbox) if location is None: location = center_of_bbox(bbox...
(The function creates a dual-map interface using Folium to display and compare two xarray datasets side-by-side. It overlays each dataset as an image layer with customizable OWS styles, enables optional controls like fullscreen and layers, and returns the configured Folium map for visualization. The map's zoom level, l...
def folium_dual_map(left_data, right_data, left_ows_style=None, right_ows_style=None, enable_fullscreen=False, enable_layers_control=False, zoom_start=None, location=None, ...
def ipyleaflet_map_default(bbox, zoom=None, center=None, **kwargs): """ Sensible defaults for a ipyleaflet map based on the bounding box of the image to be shown. """ import ipyleaflet if zoom is None: zoom = zoom_from_bbox(bbox) if center is None: center = center_of_bbox(bbox) ...
The function creates an interactive ipyleaflet map to visualize an xarray Dataset, applying OWS styling and optional controls (fullscreen, layers). It adds the dataset as an image overlay, centers the map on the data's bounds, and returns the configured map instance for display.
def ipyleaflet_map(data, ows_style_config=None, enable_fullscreen=True, enable_layers_control=False, zoom=None, center=None, **ipyleaflet_map_kwargs): """ Puts two xarray datasets side-by-side for c...
def print_flush(s): print(s, flush=True) def run_benchmark(cmd, wid, active_jobs): with active_jobs.get_lock(): active_jobs.value += 1 # hack for darknet workloads. not sure, but i think using the shell=True # for old workloads may not be right, so using this only for the 2 cases # where it ...
The function processes tasks from a queue by fetching benchmark commands, executing them, tracking execution time and progress, updating job counters, and returning status ('DONE' or 'CONT') based on completion or dynamic job pressure adjustments. It handles queue emptiness, exceptions, and signals experiment completio...
def do_work(q, active_jobs, jobs_processed, wid, experiment_start_time, jp_lock, jp_cond): try: idx, benchmark_cmd = q.get(block=True, timeout=1) print_flush('Worker {}: {} {}'.format(wid, idx, benchmark_cmd)) bmark_start_time = time.time() run_benchmark(benchmark_cmd, wid, active_jo...
def print_flush(s): print(s, flush=True) def do_work(q, active_jobs, jobs_processed, wid, experiment_start_time, jp_lock, jp_cond): try: idx, benchmark_cmd = q.get(block=True, timeout=1) print_flush('Worker {}: {} {}'.format(wid, idx, benchmark_cmd)) bmark_start_time = time.time() ...
The `worker_main` function manages a worker thread's lifecycle, processing tasks from a queue. It continuously calls `do_work` to handle jobs, using synchronization primitives (`jp_lock`, `jp_cond`) to coordinate with other workers. Depending on `do_work`'s return value (`DONE`, `WAIT`, or `CONT`), it either exits, pau...
def worker_main(q, active_jobs, jobs_processed, wid, experiment_start_time, jp_lock, jp_cond): print_flush('Worker {}: Starting'.format(wid)) while True: next_step = do_work(q, active_jobs, jobs_processed, wid, experiment_start_time, jp_lock, jp_cond) if next_step == 'DONE': print_fl...
def get_user_card(self, user_id: int, card_id: int) -> Optional[Dict[str, Any]]: """Retrieve a single card registered by a user. :param user_id: ID of user retrieving the card. :param card_id: ID of card be retrieved. """ cards = self.get_user_cards(user_id) if not cards...
This function attempts to capture a payment using a user's card by generating a secure token, preparing transaction data, and sending a charge request. It retrieves the user's card, creates an MD5 token for authentication, constructs payment details including amount, installments, and currency (PYG), and sends the requ...
def charge_card( self, user_id: int, card_id: int, tx: Transaction, amount: Decimal, description: str, installments: Optional[int] = None, additional_data: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Attempts to capture a payment. ...
def quaternion2euler(x, y, z, w): ''' Convert quaternion to euler angles parameters: x, y, z, w (float): quaternion output: roll, pitch, yaw (float): euler angles [rad] ''' ysqr = y * y t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + ysqr) X = np.arctan2(...
This callback processes the robot's pose and laser scan data to update the occupancy grid map. It converts the robot's orientation quaternion to Euler angles, stores position and yaw, and triggers map updates when both pose and scan data are available.
def robot_pose_callback(self, msg): '''Callback function for the robot pose subscriber ''' roll, pitch, yaw = quaternion2euler(msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w) self.x = np.array([[msg.position.x], [msg.position.y], [yaw]]) if self.x is n...
def _read_program(self): var_storage = self._device_manager.get_device_client("variable_storage",1) program = var_storage.getf_variable_value("program", self._current_program) assert program.datatype == "tech.pyri.program_master.PyriProgram", "Requested variable is not a program!" return...
This method initializes and starts program execution by checking preconditions (not already running/error-free), reading the program, setting internal state flags, and invoking the first step of the program.
def run(self): with self._lock: if self._running or self._stepping: raise RR.InvalidOperationException("Already running") if self._error: raise RR.InvalidOperationException("Errors must be cleared before running") program = self._...
def _read_program(self): var_storage = self._device_manager.get_device_client("variable_storage",1) program = var_storage.getf_variable_value("program", self._current_program) assert program.datatype == "tech.pyri.program_master.PyriProgram", "Requested variable is not a program!" return...
The main task of the code is to initiate the execution of a single program step in a controlled state machine. It ensures the system is not already running or paused, clears prior errors, identifies the current step, updates internal state flags, and triggers the execution of that step while maintaining thread safety t...
def step_one(self): with self._lock: if self._running or self._stepping: raise RR.InvalidOperationException("Already running") if self._error: raise RR.InvalidOperationException("Errors must be cleared before stepping") program = ...
def _read_program(self): var_storage = self._device_manager.get_device_client("variable_storage",1) program = var_storage.getf_variable_value("program", self._current_program) assert program.datatype == "tech.pyri.program_master.PyriProgram", "Requested variable is not a program!" return...
This function determines the next step in a program execution based on the current step's result. It handles transitions between steps, default fallbacks, error states, and program termination by evaluating the next step's operation code (op_code), updating internal state flags, and delegating to specific handler metho...
def _move_next_step(self, step, res): program = self._read_program() if res is None: res = "DEFAULT" all_nxt = dict() for nxt1 in step.next: all_nxt[nxt1.result.lower()] = nxt1 nxt = all_nxt.get(res.lower(),None) if nxt is None: ...
def check_tool_viability(task: str) -> str: """ This function checks the viability of a task with the available tools. It runs the AI bot with the instruction "Can {task} be successfully completed by the following tools: {tools_available}?" and returns the result in JSON format. Parameters...
The main task of the code is to process a user task by checking if a viable tool exists. If available, it executes the task using the tool; if not, it generates new tools, loads them, and re-runs the task with the updated tools. The function handles errors during tool viability checks, tool execution, and new tool gene...
def process_user_task(task: str) -> str: try: tool_viability = check_tool_viability(task) tool_viability_dict = json.loads(tool_viability) except Exception as e: logging.error(f"Error occurred while checking tool viability: {e}") return f"Error occurred while checking tool viabil...
def _change_notepad( self, button: QPushButton, save_old: bool = True ) -> None: if save_old: self._mn_manager.update_notepad_content( self.text_box.toPlainText(), index=self.main_notepad_index ) no...
This function creates a notepad button with customizable text, connects it to interaction handlers for clicks and right-clicks, adds it to a UI layout, enables a text box if inactive, registers the notepad in a manager, and triggers an update to synchronize button states. It also manages text clearing behavior based on...
def create_notepad_button( self, button_name: str, text: str = "", first_button: bool = False ) -> None: new_button = QPushButton(button_name) new_button.clicked.connect(lambda: self._change_notepad(new_button)) new_button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu...
def resolve_inputs(tx_cbor: str) -> tuple[list[tuple[str, int]], list[dict]]: """Resolves the inputs and the inputs outputs for some given tx cbor. The returned values are not in any specific ordering. Args: tx_cbor (str): The transaction cbor Raises: KeyError: The inputs, collateral, ...
The function processes a transaction's CBOR data to simulate its execution on a specified network. It resolves transaction inputs, queries output details via Koios, constructs CBOR representations of inputs/outputs, and uses the Aiken tool to simulate the transaction, returning CPU/memory metrics or an empty dict if si...
def from_cbor(tx_cbor: str, network: bool, debug: bool = False, aiken_path: str = 'aiken') -> list[dict]: """Simulate a tx from tx cbor for some network. Args: tx_cbor (str): The transaction cbor. network (bool): The network flag, mainnet (True) or preprod (False). debug (bool, optional...
def mod_exp(a, b, n): # print(a,b,n) a,b,n = int(a), int(b), int(n) return pow(a,b,n) def hash_md(pks, msg, t=100): p = pks['prime'] n = pks['n'] b = bin(msg)[2:] mk = wrap(b, n) # t= rd.randint(2,p-1) for m in mk: t = hash(pks, m, t) # print(t) return t def hash(...
This function generates a digital signature using a cryptographic algorithm. It computes a random value 'r', calculates 't' as g^r mod p, hashes the message with 't' (using MD5 or another hash), and combines the hash with the private key 'x' to form 'z'. The signature includes 't' and 'z' for verification.
def sign(pks, msg, x,md=True): p = pks['prime'] g = pks['gen'] r = randint(2, p-1) t = mod_exp(g, r, p) if md: c =hash_md(pks,msg,t) else: c = hash(pks, msg, t) z = c*x +r signature = {'t': t, 'z': z} return signature
def hash(pks, x, y): k = 123142124 g = pks['prime'] p = pks['gen'] z = mod_exp(g, k, p) return (mod_exp(g, x, p) * mod_exp(z,y,p)) % p def hash_md(pks, msg, t=100): p = pks['prime'] n = pks['n'] b = bin(msg)[2:] mk = wrap(b, n) # t= rd.randint(2,p-1) for m in mk: t...
The main task of the code is to verify a digital signature using a cryptographic scheme. It checks if the equation mod_exp(g, z, p) equals (mod_exp(y, c, p) * t) mod p, where c is a hash of the public key, message, and signature component t. This ensures the signature's validity by confirming consistency between the pu...
def verifier(pks, signature, msg): t = signature['t'] z = signature['z'] c = hash(pks, msg, t) p = pks['prime'] g = pks['gen'] y = pks['y'] c = hash_md(pks, msg, t) return mod_exp(g,z,p) == (mod_exp(y, c, p) * t)%p
def names_a_directory(path): # type: (str) -> bool """Return True if the given path names a directory vs. a file (even on GCS, existing or yet to be created) by checking if the path ends with a '/'. """ return path.endswith(os.sep) def download_file(self, sub_path, local_path): # type: (str,...
The function `download_tree` downloads files and directories from a storage system, starting with the specified `sub_path` prefix, to a local directory (`local_prefix`) while preserving their relative structure. It handles both files and directories, creating local directories as needed, and returns `True` if all downl...
def download_tree(self, sub_path, local_prefix): # type: (str, str) -> bool """Download all files and directories that begin with the sub_path prefix (within the storage_prefix) to their same relative paths in local_prefix, making directories if needed. Return True if successful...
def new_instance(): clear() # function creates a new instance and returns the public IP inst_ip = create_instance() time.sleep(15) # .py file that is copied to instance is run remotely through ssh run_check_webserver(inst_ip) def new_bucket(): add_header("Creating Bucket") # a while loop...
The main task of the code is to provide a menu-driven interface for managing cloud instances and buckets. It allows users to create instances and buckets, check webserver status on instances, upload files to buckets, and exit. The script handles user input validation, interacts with cloud resources, and includes error ...
def main(): valid_key() while True: menu = open('menu.txt', 'rU') print(menu.read()) menu_in = input_int("> ", 6) #------------------------------------------------------------------------# # Option 1: CREATE INSTANCE AND BUCKET # When instance is made, ch...
def find_square_corners(potential_squares): corner_points = [] for square in potential_squares: corners = [] for point in square: x, y = point[0] corners.append((x, y)) corner_points.append(corners) return corner_points def filter_square_corners(corner_points)...
The code processes an image of a scorecard to detect and extract digit information by identifying potential squares (representing cells), constructing a hierarchy of nested rectangles, and recognizing digits within specific regions. It highlights page boundaries, separates digits, handles errors, and prints the extract...
def main(): # code from chatgpt, don't tell anyone ;) # Load the image image_path = "./examples/images/scorecard1.png" image = cv2.imread(image_path) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply Gaussian blur to reduce noise blurred = cv2.Gaus...
def detect_labels_local_file(photo, confidence_threshold=60): client = boto3.client("rekognition", region_name="us-west-1") with open(photo, "rb") as image: response = client.detect_labels(Image={"Bytes": image.read()}) print("Detected labels in " + photo) positiveLabels = [] for label in ...
The code captures a video frame as a screenshot, detects labels and facial features using local functions, generates a descriptive prompt from detected details, and uses OpenAI's API to create a text response. It cleans the output, converts it to speech, and prints results. The main task involves image analysis, AI-dri...
def capture_screenshot(frame): global context global facial_features_prompt # Save the frame as a screenshot image photo = "screenshot.jpg" cv2.imwrite(photo, frame) labels, positiveLabels = detect_labels_local_file(photo) print("Number of labels detected: " + str(len(labels))) context...
def convert_date(date_string): date_string = datetime.strptime(date_string, '%Y-%m-%d') return date_string def wager_success(user_pk, conn, cursor): user_data = get_user_data(user_pk, cursor) # Get required user data wager = user_data["Wager"] coins = user_data["Coins"] # Give coins t...
The main task of the code is to determine if a user's exercise streak has been maintained or broken since their last wager. It checks database records for the user's wager history, current streak, and exercise plan days. If the streak has decreased, the wager fails; if the streak has sufficiently increased, the wager s...
def check_wager(user_pk, conn, cursor): db_command = f"SELECT StreakAtTimeOfWager, WagerDate FROM WagerInfo WHERE UserPK = {str(user_pk)}" cursor.execute(db_command) # If the wager record does not exist. Create one. Wager has not failed. try: streak_at_time_of_wager, wager_date = cursor.fetchone...
def getRow(name:str="variable",default:str="0",columnSize=[100,200],rowSize=30,fontSize:int=15): horizontalStackPanel = QHBoxLayout() label = getLabel(name,columnSize[0],rowSize,fontSize) editor = getEditor(columnSize[1],rowSize,fontSize) setStringToEditText(editor,str(default)) horizontalStackPanel...
The code generates a UI form with input fields, a result field, and a submit button. It creates vertical layouts for each form element, stores references in a dictionary, and returns the structured UI components for further use in an application.
def makeAForm(items): ui_rows = [] columnSize = [500,500] rowSize = 40 form_controls = {} for item in items : data_row = getRow(name=item.display_data,default=item.default_value,columnSize=columnSize,rowSize=rowSize,fontSize=12) form_controls[item.variable_name] = data_row[1] ...
def formatFloat(args, f): d = (Decimal(f) / Decimal(args.str_precision)).quantize(1) * Decimal(args.str_precision) return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() def toolPixels(args, diameter): pixel_diameter = int(diameter / args.precision) edge = pixel_diameter * pixel_diamet...
The code generates G-code commands for CNC tool paths, managing layer depth constraints by distributing cut planes across specified depths. It prepares tool geometry, calculates coordinates, and iterates over planes to produce milling instructions, ensuring adequate spacing between cuts. Finally, it outputs movement co...
def generateCommands(target, state, padding, args, diameter, out): planes = list(range(0, args.planes)) cut_early = [] cut_late = [] last_cut = 0 next_cut = 0 for plane in planes: z = (plane + 1) * (args.depth / args.planes) if z - last_cut < args.cutdepth: pass ...
def get_env_variables(): global CONFIG_DIR CONFIG_DIR = os.environ["CONFIG_DIR"] cconfigparser = configparser.RawConfigParser() configFilePath = CONFIG_DIR + '/epic_capri_accesspoints_api.conf' cconfigparser.read(configFilePath) global INPUT_DIR INPUT_DIR = os.environ["INPUT_DIR"] global OUTPUT_DIR OU...
The main task of the code is to fetch environment variables, open a log file, and retrieve "Epic Pull" data for access points, with error handling and logging. It uses global variables to track messages, attempts critical operations in try blocks, logs errors, and exits on failures. The `get_env_variables()` and `get_e...
def main(): global msg global fh try: msg = "Attempting to fetch Environment Variables" get_env_variables() fh = open(LOGFILE,'a+') except Exception as E1: log_info("Unable to onboard Environment Variables-%s"%(E1)) sys.exit(1) try: msg = "Attempting to Open Logfile" log_info(msg) ...
def _console_section(title: str, description: str = None): CONSOLE.rule(f"[bold]{title}") if description is not None: _console_print(f"[dim]{description}") def archiver_analyze(root_path: str, days: int) -> Dict[str, ArchivePath]: _console_section( "Directory Analysis", f"Scanning fo...
The code archives files by analyzing, transferring, uploading to a specified bucket, and cleaning up after successful uploads, using a configuration file to determine parameters like retention days and target storage.
def archive_app(): root_path = "." _console_section( "Configuration", f"This is the current configuration for px-archiver at this directory {os.getcwd()}. " f"You can edit this configuration at {CONFIG_FILE}.", ) bucket, days = load_config(CONFIG_FILE) # Analyze which files...
def generate_test_files(): _console_print(f"Generating test files in {os.getcwd()}!") generate_test_set(os.getcwd()) def configure(): load_config(CONFIG_FILE) def archive_app(): root_path = "." _console_section( "Configuration", f"This is the current configuration for px-archiver at...
The code defines a `main()` function that uses `argparse` to handle command-line arguments. It processes two flags: `--generate` (creates random text files) and `--config` (shows/creates config). Depending on the arguments, it calls `generate_test_files()`, `configure()`, or `archive_app()` to execute specific tasks. T...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--generate", action="store_true", help="Generates some random text files in this directory.", ) parser.add_argument( "--config", action="store_true", help="Shows (or creates) the current config." ...
def _get_ins_d(subject_str, query_str, subject_match_start_pos): ins_d = dict() for idx in _get_char_idxs_in_str(subject_str, BLAST_INDEL_CHAR): pos = idx + subject_match_start_pos ins_d[pos] = query_str[idx] return ins_d def _get_consecutive_pos_l(pos_l): cnsc_pos_l = [] for k, g in...
This function processes pangenome alignments to identify amino acid variants (insertions, deletions, substitutions) in core genes by parsing BLAST XML files. It extracts mutation details from alignments, compiles them into a structured DataFrame, and saves the results as a CSV file in the specified alleleome directory.
def generate_amino_acid_vars( pangenome_alignments_dir_path, alleleome_dir_path, pangene_summary_csv=None ): try: logging.info( "Starting generate_amino_acid_vars in generate_amino_acid_variants" ) pangenome_alignments_dir_path = Path(pangenome_alignments_dir_path) al...
def move_to_object(self, color, goal_dist=0.20, next_status=MOVED_TO_BEAR): """ Move to a dumbbell based on color """ # Do nothing if there are no images if len(self.image) == 0: print("-- Have not got the image --") return # Do nothing if there are no scan data...
The code defines a ROS node's main loop that controls a robot's behavior based on its status. It identifies the current bear color, transitions through states (e.g., moving to a bear, lifting it, moving to a supporter), and executes corresponding actions like navigation and manipulation. The loop runs at 5Hz, checking ...
def run(self): r = rospy.Rate(5) while not rospy.is_shutdown(): if self.bear_status['bear_red'] == 0: self.curr_color = 'bear_red' elif self.bear_status['bear_white'] == 0: self.curr_color = 'bear_white' else: self.cur...
def rf24_flush(): rf24_cs(0) rf24_command(0b11100010) # Flush RX rf24_cs(1) rf24_cs(0) rf24_command(0b11100001) # Flush TX rf24_cs(1) def rf24_reg_write(reg, value): rf24_cs(0) rf24_command(0x20 | reg) rx = rf24_writebyte(value) rf24_cs(1) def rf24_reg_read(reg): rx = 0 r...
This function initializes an RF24 module for receive mode by clearing status flags, configuring register settings to enable reception, activating the chip enable pin, and adding a short delay for stabilization.
def rf24_powerup_rx(): global rf24_status rf24_flush() rf24_reg_write(0x07, rf24_status & 0b01110000) #clear status rf24_reg_write(0x00, (rf24_reg_read(0x00) & 0b11111100) | 0b00000011) rf24_ce(1) time.sleep(0.005)
def rf24_flush(): rf24_cs(0) rf24_command(0b11100010) # Flush RX rf24_cs(1) rf24_cs(0) rf24_command(0b11100001) # Flush TX rf24_cs(1) def rf24_reg_write(reg, value): rf24_cs(0) rf24_command(0x20 | reg) rx = rf24_writebyte(value) rf24_cs(1) def rf24_reg_read(reg): rx = 0 r...
This function initializes an RF24 module for transmission by resetting its state, configuring registers to set transmit mode, enabling the CE pin, and introducing a delay to ensure proper power-up sequence.
def rf24_powerup_tx(): global rf24_status rf24_flush() rf24_reg_write(0x07, rf24_status & 0b01110000) #clear status rf24_reg_write(0x00, (rf24_reg_read(0x00) & 0b11111100) | 0b00000010) rf24_ce(1) time.sleep(0.005)
def rf24_reg_write(reg, value): rf24_cs(0) rf24_command(0x20 | reg) rx = rf24_writebyte(value) rf24_cs(1) def rf24_reg_read(reg): rx = 0 rf24_cs(0) rf24_command(reg) rx = rf24_readbyte() rf24_cs(1) return rx def rf24_ce(lev): GPIO.output(rf24_cePin, lev) time.sleep(rf24_s...
The code puts the RF24 module into power-down mode by clearing specific bits in the configuration register and disabling the chip enable, conserving power while maintaining configuration settings.
def rf24_powerdown(): rf24_reg_write(0x00, rf24_reg_read(0x00) & 0b11111100) rf24_ce(0)
def find_sketch_threshold(image, white_space_val = 245, fill_space_val = 10, fill_space_threshold = 0.03): ''' Takes in an image and creates a sketch of detail level specified by fill_space_threshold. Returns None if no suitable sketch found, otherwise returns an image of a sketch. image: PIL.Image...
The function preprocesses an image by converting it to grayscale, generating a sketch using a fill space threshold, resizing both the image and sketch to 256x256 pixels, and concatenating them horizontally to form a paired image-sketch output for model input.
def preprocess_and_create_sketch(image_file, fill_space_threshold = 0.03): ''' Applies all preprocessing steps to a single image file, in preparation for use in models. Returns a concatenated image, containing processed image and its sketch. image_file: str, path to image to process. fill_space...
def presolve_sanity_check ( teams_dict, strict_circle=True ): """ Make sure that the data is formatted correctly, and that a circle of parity is possible. If 1 or more teams do not have a win/loss, then a circle is NOT possible """ for team in teams_dict.values(): # how should we do this check? make sure team ...
The main task of the code is to find a Hamiltonian cycle (a circular path visiting every node exactly once) in an NFL teams graph, where nodes represent teams and edges represent win/loss relationships. It retrieves graph data, performs sanity checks, uses brute-force to compute the cycle, and validates the result as a...
def main ( args ) : # invoke the main function in nfl_results to get a dict # dict contains graph nodes - representing teams, # each with references (vertices) to other teams that they beat/lost to teams_dict = nfl_results.main ( args[1] ) pprint ( teams_dict ) # do a sanity check first try: presolve_sanit...
def display_blank(self): for i in range(len(self.item_selectors)): self.containerScr.addstr(self.item_selectors[i].y,self.item_selectors[i].x," ",self.attr) self.containerScr.refresh() self.refreshAll() def activate(self): self.active = True self.attr = ...
This code removes items from a list based on given IDs by clearing their windows and updating the item list. It filters out items with IDs in `item_ids`, refreshes the display, resets selection, and deactivates the selector to reflect changes.
def remove_items(self,item_ids): self.display_blank() new_item_list = [] for i in range(len(self.item_selectors)): if self.item_selectors[i].id in item_ids: self.item_selectors[i].window.clear() self.item_selectors[i].window.refresh() else:...
def deactivate(self): self.active = False self.attr = curses.A_NORMAL self.display() def display(self): for i in range(len(self.item_selectors)): if i == self.selection: self.containerScr.addstr(self.item_selectors[i].y,self.item_selectors[i].x,self.selected...
This method processes keyboard inputs to navigate and interact with a selectable list. When active, it handles left key to deactivate the current selector, updates selection, and refreshes the display. For other keys, it delegates to the selected item's get_choice method. When inactive, it allows up/down navigation and...
def get_choice (self,key): if self.active_selector: if key == curses.KEY_LEFT: self.deactivate() self.active_selector = False self.item_selectors[self.selection].deactivate() self.display() self.refreshAll() ...
def _next (self): self.selection = (self.selection + 1) % len(self.items) self.index = 0 self.build() def _previous (self): self.selection -= 1 if self.selection < 0: self.selection = len(self.items) - 1 self.index = 0 self.build() def build (self): s...
This code handles user input in a terminal-based interface using the `curses` library. It processes arrow key inputs to navigate through options: UP/Down keys trigger `_next()`/`_previous()` methods for selection changes, while the RIGHT key increments the index and rebuilds the interface. The function only acts if `se...
def get_choice(self, key): if self.active: if key == curses.KEY_UP: self._next() if key == curses.KEY_DOWN: self._previous() if key == curses.KEY_RIGHT: self.index += 1 self.build()
def decode_ber(self, token): if token[3] in self.vowels: if self.search_kbbi(token[-len(token)+2:]) or self.search_kbbi(self.decode_suffix(token[-len(token)+2:])): return token[-len(token)+2:] elif self.search_kbbi(token[-len(token)+3:]) or self.search_kbbi(self.decode_su...
The function `decode_prefix` identifies the prefix of a given token and routes it to the corresponding decoding method (e.g., `decode_ber`, `decode_ter`, etc.) based on specific character patterns. If no matching prefix is found, it returns the original token unchanged.
def decode_prefix(self, token): if token[:3] == 'ber': return self.decode_ber(token) elif token[:3] == 'ter': return self.decode_ter(token) elif token[:2] == 'me': return self.decode_me(token) elif token[:2] == 'pe': return self.decode_pe(t...
def search_kbbi(self, token): for elm in self.kbbi: if token == elm[0]: return True return False def remove_inflectional_suffix(self, token): if token[-3:] in self.inflectional_suffix_3: if self.search_kbbi(token[:-3]): return token[:-3] ...
The main task of the code is to perform morphological stemming on a token by checking if it exists in the KBBI dictionary. If not, it iteratively removes inflectional/derivation suffixes, prefixes, and decodes prefixes up to three times, returning the first valid singular form found in KBBI. If no matches are found aft...
def stemming_singular(self, token): if self.search_kbbi(token): return token if self.search_kbbi(self.remove_inflectional_suffix(token)): return self.remove_inflectional_suffix(token) if self.search_kbbi(self.remove_derivation_suffix(token)): return self.rem...
def _append_markdown_content(self, node, content: str): """Parse Markdown `content` and append it to docutils `node`""" document = make_document(parser_cls=self.parser) self.parser.parse(content, document) for child in document: node += child def _get_operation_request_node( ...
This function processes OpenAPI operation specifications to generate structured documentation nodes. It handles both standard operations and action-based endpoints by extracting operation details, generating unique identifiers, and constructing collapsible sections with headers, descriptions, and request/response nodes...
def _get_operation_nodes(self, spec, path, method, operation_spec): """Process OpenAPI operation""" # We might want to have multiple separate entries for single url # (a.k.a. actions) operation_specs = [] if not path.endswith("/action"): body = ( opera...
def _get_spec(abspath, encoding): with open(abspath, "rt", encoding=encoding) as stream: # It is important to use ruamel since it goes for YAML1.2 which # properly understands quotes for nova boolean enum values yaml = YAML(typ="safe") return yaml.load(stream) def normalize_spec(spec...
This code processes an OpenAPI specification file by resolving its path, setting a URI for reference resolution, tracking it as a dependency, reading the spec with appropriate encoding, normalizing its structure, and generating document nodes for headers and API groups. The result is a list of parsed nodes for inclusio...
def run(self): relpath, abspath = self.env.relfn2path( directives.path(self.arguments[0]) ) # env = self.state.document.settings.env # URI parameter is crucial for resolving relative references. So we # need to set this option properly as it's used later down the ...
def load_results(results_path: Path) -> pd.DataFrame: res = pd.read_csv(results_path / "results.csv") res["dataset_name"] = res["dataset"].str.split(".").str[0] res["overall_time"] = res["execute_main_time"].fillna(0) + res["train_main_time"].fillna(0) res["algorithm-index"] = res.algorithm + "-" + res....
The code defines a `render` method that creates a Streamlit UI for selecting experiment results and dataset directories. It validates inputs, loads results data, and generates summaries (overall, error, quality, runtime) and plots using methods like `_overall_results` and `_plot_experiment`. The main task is to visuali...
def render(self): st.title(self.name) files = Files() col1, col2 = st.columns(2) with col1: results_dir = st.text_input( "Choose experiment run results parent folder", placeholder="/home/user/results", value=files.results_fold...
def api_limit_warning(): print() print('Warning: Rate limits exist for GitHub API') print('To avoid 403 Error/ rate limit exceeded, it is recommended to limit your') print('repository pull request to the 10 most recent pulls. How would you like to ') print('proceed?') while True: print("...
The main task of the code is to provide a menu-driven interface for GitHub data analysis, allowing users to collect repository data, view repositories, generate visualizations, calculate correlations, access user profiles, or exit the program, with input validation to ensure valid selections within the specified range.
def main_menu(): while True: print("\nGitHub Data Analysis") print("1. Collect data for a specific repository") print("2. Show all repositories") print("3. Create visualizations") print("4. Calculate correlations") print("5. User Profile") print("6. Exit") ...
def first(s): """Return the first element of a linked list s.""" assert is_link(s), "first only applies to linked lists." assert s != 'empty', "empty linked list has no first element" return s[0] def rest(s): """Return the rest of the elements of a linked list s.""" assert is_link(s), "rest only...
This function recursively retrieves the ith element from a linked list structure, starting from index 0. It uses base case handling for i=0 and recursive calls with rest(s) and i-1 to traverse deeper into the list until reaching the target index.
def getitem_link_recursive(s, i): if i == 0: return first(s) return getitem_link_recursive(rest(s), i-1)
def link(first, rest): """Construct a linked list from its first element and the rest.""" assert is_link(rest), "rest must be a linked list." return [first, rest] def first(s): """Return the first element of a linked list s.""" assert is_link(s), "first only applies to linked lists." assert s !=...
The function `extend_link` recursively concatenates two linked lists `s` and `t`, returning a new list containing all elements of `s` followed by those of `t`. If `s` is empty, it directly returns `t`. Otherwise, it constructs a new link using the first element of `s` and recursively extends the rest of `s` with `t`, e...
def extend_link(s, t): """Return a list with the elements of s followed by those of t.""" if s == 'empty': return t else: return link(first(s), extend_link(rest(s), t))
def is_link(s): """S is a linked list if it is empty or a (first, rest) pair.""" return s == 'empty' or (len(s) == 2 and is_link(s[1])) def link(first, rest): """Construct a linked list from its first element and the rest.""" assert is_link(rest), "rest must be a linked list." return [first, rest] d...
This function applies a given function `f` to each element of a linked list `s`, recursively constructing a new linked list with the transformed elements. It checks if `s` is empty, returning it as-is, otherwise applies `f` to the first element and recursively processes the rest of the list.
def apply_to_all_links(f, s): """Apply f to each element of s.""" assert is_link(s) if s == 'empty': return s else: return link(f(first(s)), apply_to_all_links(f, rest(s)))
def is_link(s): """S is a linked list if it is empty or a (first, rest) pair.""" return s == 'empty' or (len(s) == 2 and is_link(s[1])) def rest(s): """Return the rest of the elements of a linked list s.""" assert is_link(s), "rest only applies to linked lists." assert s != 'empty', "empty linked li...
This function filters elements of a linked list `s` by retaining only those elements for which the predicate function `f` returns `True`. It recursively processes the list, checking each element and constructing a new linked list with elements that satisfy the condition.
def keep_if_links(f, s): """Return a list with elements of s for which f(e) is true.""" assert is_link(s) if s == 'empty': return s else: kept = keep_if_links(f, rest(s)) if f(first(s)): return link(first(s), kept) else: return kept
def rest(s): """Return the rest of the elements of a linked list s.""" assert is_link(s), "rest only applies to linked lists." assert s != 'empty', "empty linked list has no rest." return s[1] def first(s): """Return the first element of a linked list s.""" assert is_link(s), "first only applies...
The main task of the code is to recursively concatenate elements of a linked list `s` into a string, separating each element with the provided `separator`. It handles empty lists by returning an empty string, single-element lists by returning that element as a string, and recursively combines the first element with the...
def join_links(s, separator): """Return a string of all elements in s separated by separator.""" if s == 'empty': return "" elif rest(s) == 'empty': return str(first(s)) else: return str(first(s)) + separator + join_links(rest(s), separator)
def tree(root_label, branches=[]): for branch in branches: assert is_tree(branch), 'branches must be trees' return [root_label] + list(branches) def label(tree): return tree[0]
The code defines a recursive function `fib_tree(n)` that constructs a binary tree representing the nth Fibonacci number. Each node's label is the sum of its children's labels, mirroring the Fibonacci recurrence relation. Base cases return single-node trees with labels 0 or 1. The function builds the tree by recursively...
def fib_tree(n): if n == 0 or n == 1: return tree(n) else: left, right = fib_tree(n-2), fib_tree(n-1) fib_n = label(left) + label(right) return tree(fib_n, [left, right])
def link(first, rest): """Construct a linked list from its first element and the rest.""" assert is_link(rest), "rest must be a linked list." return [first, rest] def apply_to_all_links(f, s): """Apply f to each element of s.""" assert is_link(s) if s == 'empty': return s else: ...
This function generates all integer partitions of n using parts no larger than m, represented as linked lists. It recursively constructs partitions by either including the part m (adding m to partitions of n−m) or excluding m (using partitions of n with max part m−1), combining both results into a linked list of all va...
def partitions_link(n, m): """Return a linked list of partitions of n using parts of up to m. Each partition is represented as a linked List. """ if n == 0: return link('empty', 'empty') # a list containing the empty partition elif n < 0 or m == 0: return 'empty' else: us...
def partitions_link(n, m): """Return a linked list of partitions of n using parts of up to m. Each partition is represented as a linked List. """ if n == 0: return link('empty', 'empty') # a list containing the empty partition elif n < 0 or m == 0: return 'empty' else: us...
The code generates all possible partitions of integer n into m parts, formats each partition by joining elements with " + ", and prints each formatted partition on a new line.
def print_partition_link(n, m): lists = partitions_link(n,m) strings = apply_to_all_links(lambda s: join_links(s, " + "), lists) print(join_links(strings, "\n"))
def reset(self, initial_state): self.close_list = PriorityQueue() self.open_list = PriorityQueue() self.puzzle = XPuzzle(self.rows, self.columns, initial_state) self.initial_state = (0,copy.deepcopy(self.puzzle.arr),0,0,0,0, None, 0) self.is_goal_state = False self.ignore...
The code executes A* search algorithms with multiple heuristics on input problems, tracking solution paths, search spaces, and performance metrics (cost, time, node counts). It iterates through each input and heuristic, runs the search (with timeout handling), records results in files, and stores analysis data. The goa...
def run_algo(self): for input_i, x in enumerate(self.inputs): for h in self.heuristics: print('Computing', str(x), h) self.reset(x) self.heuristic = h start = time.time() chosen_state = self.init...
def initialize_txt_files(self): uniform_cost_search_file = open(self.id+"_gbfs_h1_search.txt", "w") uniform_cost_search_file.write("0 0 0 " + self.initial_state + "\n") uniform_cost_search_file.close() uniform_cost_solution_file = open(self.id+"_gbfs_h1_solution.txt", "w") unifor...
This code implements a greedy best-first search algorithm to find a solution path from an initial state to one of two goal states. It logs the search process, tracks time limits, and returns statistics like total cost, solution existence, path length, and execution time. The algorithm uses a priority queue to explore n...
def run(self, log_to_csv = True): print('start algo for: ' + self.initial_state) self.initialize_txt_files() start = time.time() goal_state_1 = self.calculate_goal_state_1() goal_state_2 = self.calculate_goal_state_2() search_count = 0 # nodes that need to be visi...
def _mc_forwards(self, x, threshes, n_forwards): """ Compute n_forwards forward passes through network with dropout and returns stacked predictions. Used for Vandal et al """ results = list() for _ in range(n_forwards): bin_pred, gpd_pred, lognorm_pred = self....
This function computes statistics for a zero-inflated lognormal distribution using Monte Carlo simulations. It calculates mean (mu) and standard deviation (sigma) parameters from predicted values, derives first and second moments, and returns bin-averaged probabilities, a constant variance placeholder, and lognormal di...
def compute_mc_stats(self, x, threshes, n_forwards): """ Computes mus and sigmas of zero-inflated lognormal Used for Vandal et al """ preds = self._mc_forwards(x, threshes, n_forwards) non_zeros = 1 - preds[:, :, 0] mus = preds[:, :, 2] sigs = preds[:, :, ...
def compute_zero_prob(self, pred): """ Computes predicted probability of 0 rainfall Parameters: pred - list of tensors, list of mixture model parameters Returns: bin_pred - array, probability of 0 rainfall """ bin_pred, gpd_pred, norm_pred = self....
The function computes predicted probabilities for three classes (zero, moderate, excess) using input parameters and thresholds. It returns these probabilities as a list of arrays or a stacked array based on the 'aslist' flag, leveraging helper methods for individual class probability calculations.
def compute_all_probs(self, pred, threshes, aslist): """ Compute the predicted probability of each of the 3 classes (zero, non-zero non-excess, and excess) Parameters: pred - list of tensors, list of mixture model parameters threshes - tensor, thresholds aslist - boolean,...
def compute_all_probs(self, pred, threshes, aslist): """ Compute the predicted probability of each of the 3 classes (zero, non-zero non-excess, and excess) Parameters: pred - list of tensors, list of mixture model parameters threshes - tensor, thresholds aslist - boolean,...
The function computes classification evaluation metrics, including Brier scores for three rainfall classes, accuracy, F1 scores (micro/macro), and AUC (macro OVO/ROV). It converts model outputs and targets into class labels using thresholds, then calculates metrics to assess prediction performance across different clas...
def compute_class_metrics(self, y, pred, threshes): """ Computes various metrics related to the predicted class labels Parameters: y - tensor, target variable pred - list of tensors, list of mixture model parameters threshes - tensor, thresholds Returns: ...
def split_pred(self, pred): """ Just splits a list of predictions up into the constituent parts Returns: bin_pred - tensor, bin_pred[:, 0] is probability of 0 rainfall and bin_pred[:, 1] is probability of excess rainfall given non-zero rainfall gpd_pre...
The function `compute_metrics` calculates multiple evaluation metrics for a model's predictions, including negative log-likelihood (NLL), mean squared error (MSE), Brier scores for different rainfall classes, accuracy, F1 scores (micro/macro), and AUC (macro OVO/OVR). It combines NLL and MSE into a weighted loss, incor...
def compute_metrics(self, y, pred, threshes): """ Computes a wide range of evaluation metrics Parameters: y - tensor, target variable pred - list of tensors, list of mixture model parameters threshes - tensor, thresholds Returns: loss - scalar, th...
def print_blocks(block_name, block_type, instance_type, num_blocks, stage_num, type='biquad'): #For each block in the filter, print the block info and corresponding ports for block in range(num_blocks): if type == 'fir': print(' <block name="{bname}{stage}" type="{btype}" instance...
This function generates a digital filter's hardware description by printing blocks (adders, multipliers, delays) and their connections for multiple stages. It creates a biquad filter structure with 4 adders, 5 multipliers, and 2 delays per stage, connecting them via specified ports. It also sets constant inputs for cer...
def print_biquad_one(num_stages, coeff_file): for stage in range(num_stages): #Print blocks (4 add, 5 mult, 2 delay per stage) #Current defaults are generic_add and generic_mul print_blocks('add_a', 'add', 'generic_add', 2, stage) print_blocks('add_b', 'add', 'generic_add', 2, ...
def print_blocks(block_name, block_type, instance_type, num_blocks, stage_num, type='biquad'): #For each block in the filter, print the block info and corresponding ports for block in range(num_blocks): if type == 'fir': print(' <block name="{bname}{stage}" type="{btype}" instance...
The code generates a biquad filter structure with multiple stages by instantiating add, multiply, and delay blocks, connecting internal signals, and linking stages. It creates signal connections for feedback and feedforward paths, handles coefficient storage via `print_coeffs`, and defines input/output ports. The funct...
def print_biquad_two(num_stages, coeff_file): for stage in range(num_stages): #Current defaults are generic_add, generic_mul, generic_delay print_blocks('add', 'add', 'generic_add', 4, stage) print_blocks('mul_a', 'mul', 'generic_mul', 3, stage) print_blocks('mul_b', 'mul', 'ge...
def print_blocks(block_name, block_type, instance_type, num_blocks, stage_num, type='biquad'): #For each block in the filter, print the block info and corresponding ports for block in range(num_blocks): if type == 'fir': print(' <block name="{bname}{stage}" type="{btype}" instance...
This function generates a FIR filter structure with specified stages, creating interconnected blocks (multipliers, adders, delays) and defining input/output ports. It prints hardware configuration details, connects stages, outputs coefficients from a file, and adds a constant zero input for the first adder block.
def print_fir(num_stages, coeff_file): #First mul block print_blocks('mul_b', 'mul', 'generic_mul', 1, 0, 'fir') print_cxn('mul_b', 'Z', 'add', 'A_input', 1, "nextstage", "fir") print('\n') #Print blocks (1 add, 1 mul, 1 delay per stage) for stage in range(1, num_stages+1): print_bloc...
def prepareData(filename, fitOrder, newColumnNames): global DATA csv = pd.read_csv(filename) # print(csv.head()) csv.iloc[:, 1] = csv.iloc[:, 1].interpolate(method='polynomial', order=fitOrder) for i in range(1, len(csv)): if math.isnan(csv.iloc[i, 2]): csv.iloc[i, 2] = (1 - c...
The main task of the code is to predict population trends using polynomial and XGB regression models on U.S. demographic data (birth/death rates, fertility, migration, etc.), prepare and analyze datasets, generate visualizations, and compile results into an HTML report. It processes multiple CSV files, fits models for ...
def main(): global DATA print("Population Prediction") filename = './Data/USA/{}.csv' polyFitOrder = 2 prepareData(filename.format('USA-Birthrate'), polyFitOrder, ['date', 'Births', 'BirthChangePercent']) prepareData(filename.format('USA-DeathRate'), polyFitOrder, ['date', 'Deaths', 'Death...
def construct_graph(dataset, args, celltype_key, name=""): """ Function which adds spatial connectivity information to the anndata-dataset. It also calculates and plots an interaction matrix. Parameters: -dataset (anndata): Squidpy/scanpy dataset. -args (argparse.Namespace): User CL arg...
The main task of the code is to apply a GNN model to a spatial transcriptomics dataset to predict gene expression patterns, evaluate model performance using R² scores and error metrics, and generate visualizations of true/predicted expression distributions, gene-specific errors, and cell-type-level predictions. The fun...
def apply_on_dataset(model, dataset, name, celltype_key, args, discriminator=None, ligrec=False, device='cuda'): """ Function that applies the GNN-model on the entire specified dataset. Parameters: -model (PyG model): GNN-model to use -dataset (anndata): Squidpy/Scanpy dataset to apply the ...
def check_for_repository(path): return run_cli('git status', cwd=path) != '' def _build_changes(self): rebuilt_index = self._rebuild_index() index = self._build_index() paths = {*rebuilt_index.keys(), *index.keys()} additions = [] updates = [] removals = [] # unchanged = [] for path in paths: if pa...
The code encrypts files in a Git repository by validating the repository structure, generating encryption keys, processing additions/updates (encrypting and storing files in a secrets directory), and removing secrets for deleted files. It ensures proper directory setup, handles file operations, and manages cryptographi...
def encrypt(self): if not self._repository.is_dir(): raise NotADirectoryError('There is no repository at the supplied path!') if not check_for_repository(self._repository): raise FileNotFoundError('There is no Git repository in that directory!') if not self._secrets.is_dir(): print('[i] Creating the se...
def get_future_predicted_dates(predicted_dates): """ From the predicted dates list provided by BOS filter out the dates that are in the past. This won't be an issue for keep up jobs but when we catch-up or gap fills we are not interested in creating acquisitions from the past with status PREDICT...
The function generates metadata and datasets for predicted acquisitions by extracting and modifying fields from an input record. It constructs metadata including acquisition details, satellite info, and timestamps, then creates a folder structure with a .met.json file and associated dataset files. If a folder already e...
def make_predicted_datasets(record): """ Creating the dataset for predicted acquisitions This contains a subset of the metadata fields as seen in acquired acquisitions :param record: :return: """ predicted_dates = sorted(record["properties"]["predicted"].split(",")) predicted_dates = get...
def not_raw(product_name): """ Check if the product is of type RAW we check for this because we are not interested in creation and ingestion of a RAW dataset. :param product_name: :return: """ match = re.search(r'([\w.-]+)_([\w.-]+)_([\w.-]+)__([\d])([\w])([\w.-]+)', product_name) if...
The function processes BOS acquisition records to create archived/planned acquisitions. It checks if the product is not RAW and not a past planned acquisition. If valid, it generates MET files, dataset files, and predicted datasets using helper functions when "predicted" data is present.
def create_product(record): """ For every acquistion from BOS, create an archived / planned acquistions If the predicted dates are provided then create the predicted acquisitions :param record: :return: """ product_name = record["properties"]["identifier"] # original acq name status = re...
def key_is_file_on_s3( key: str, bucket: S3Bucket = None, client: S3Client = None, ) -> bool: """Check if a key is a file on S3, returns false if it is a folder. Raises an error if the key does not exist.""" bucket = bucket or S3MPConfig.bucket client = client or S3MPConfig.s3_client if not...
This function downloads an S3 object to a local path, recursively handling directories by iterating over sub-keys and downloading each file individually with configured callbacks and transfer settings.
def download_key( key: str, local_path: Path, bucket: S3Bucket = None, client: S3Client = None, ) -> None: """Download a key from S3.""" bucket = bucket or S3MPConfig.bucket client = client or S3MPConfig.s3_client if key_is_file_on_s3(key, bucket, client): local_path.parent.mkdir...
def key_exists_on_s3( key: str, bucket: S3Bucket = None, client: S3Client = None, ) -> bool: """Check if a key exists on S3.""" bucket = bucket or S3MPConfig.bucket client = client or S3MPConfig.s3_client res = s3_list_single_key(key, bucket, client) return "Contents" in res or "CommonPr...
The main task of the code is to delete an S3 key (object or directory) by checking its existence, determining if it's a file or directory, and either removing the object directly or recursively deleting its child keys. It uses default S3 bucket/client configurations if not provided and ensures operations are only perfo...
def delete_key_on_s3( key: str, bucket: S3Bucket = None, client: S3Client = None, ) -> None: """Delete a key on S3.""" bucket = bucket or S3MPConfig.bucket client = client or S3MPConfig.s3_client if not key_exists_on_s3(key, bucket, client): return if key_is_file_on_s3(key, bucke...
def evaluate_position(board: chess.Board): # collect material of players white_material = 0 black_material = 0 white_pawns = board.pieces(chess.PAWN, chess.WHITE) white_knights = board.pieces(chess.KNIGHT, chess.WHITE) white_bishops = board.pieces(chess.BISHOP, chess.WHITE) white_rooks = bo...
This function evaluates a chess board state using the minimax algorithm with alpha-beta pruning. It recursively explores legal moves up to a specified depth, assessing positions by checking for repetitions, checkmates, and applying heuristic evaluations. The alpha-beta pruning optimizes performance by eliminating branc...
def evaluate_board(board: chess.Board, depth: int, alpha: int, beta: int): # return if max depth reached if depth == 0: evaluation = evaluate_position(board) return evaluation if board.is_repetition(3): return 0 moves = board.legal_moves if moves.count() == 0: if b...
def fwp(self,open=None, close=None): if self.model is None: raise Exception("no prediction network") if open is None or close is None: open, close = self.getData() prediction = self.model.predict(self.scaleData(open,close)) return reshape(prediction,(sel...
This code determines trading actions based on predictions and state: if the prediction indicates a downward trend (value < 0.5) and the state isn't 0, it triggers a short position; if the prediction indicates an upward trend (value > 0.5) and the state isn't 1, it triggers a long position; otherwise, it returns no acti...
def iter(self,open=None,close=None): prediction = self.fwp(open,close) if self.state != 0 and prediction[-self.predLen-1] < 0.5: return self.short(close) elif self.state != 1 and prediction[-self.predLen-1] > 0.5: return self.long(close) else: return...
def fwp(self,open=None, close=None): if self.model is None: raise Exception("no prediction network") if open is None or close is None: open, close = self.getData() prediction = self.model.predict(self.scaleData(open,close)) return reshape(prediction,(sel...
This code determines trading actions based on predictions. It checks the current state and predicted value: if state ≠ 0 and prediction < 0.5, it triggers a short position; if state ≠ 1 and prediction > 0.5, it triggers a long position. Otherwise, it returns no action. The function uses forward prediction results to ma...
def iter(self,open=None,close=None): prediction = self.fwp(open,close) offset = -0 if self.state != 0 and prediction[-self.predLen+offset] < 0.5: return self.short(close) elif self.state != 1 and prediction[-self.predLen+offset] > 0.5: return self.long(close) ...
def get_croppping_dim(): # crop from top and bottom # return (70, 20) return (40, 20) def get_target_size(): return (66, 200) def complex_model(input_dim, conv_activation='relu', fcn_activation='relu', dropout_prob=0.5, use_bn=False): image_input, image_branch = create_image_branch(input_dim, conv_a...
The main task of the code is to train a neural network model for steering and speed prediction using diverse driving data from multiple tracks. It loads data from specified directories, configures a complex model with ReLU activation, dropout, and no batch normalization, compiles it with Adam optimizer and MSE loss for...
def main(): data_dirs = [ 'data/udacity-origin-data/', # 'data/gathering1/track1-lap1/', # 'data/gathering1/track1-lap2-throttle/', # 'data/gathering1/track2-lap1/', # 'data/gathering1/track2-lap2/', # 'data/gathering1/track2-lap3/', # 'data/gathering1/track2...
def create_image_branch(input_dim, conv_activation, fcn_activation, dropout_prob, use_bn): image_input = Input(shape=input_dim, name='image_input') x = image_input # Normalization - centered around zero with small standard deviation x = Lambda(lambda x: x / 127.5 - 1.0, name='image_normalization')(x) ...
The code defines a neural network model with two input branches (image and speed), processes them through separate sub-networks, merges the outputs, and generates two outputs for steering and throttle control. It uses customizable activation functions, dropout, and batch normalization, returning a Keras Model for multi...
def complex_model(input_dim, conv_activation='relu', fcn_activation='relu', dropout_prob=0.5, use_bn=False): image_input, image_branch = create_image_branch(input_dim, conv_activation, fcn_activation, dropout_prob, use_bn) speed_input, speed_branch = create_speed_branch(fcn_activation, dropout_prob, use_bn) ...
def load_samples(data_dirs, skip_steerings=None, use_side_cameras=False, steering_correction=0.2): driving_log_file = 'driving_log.csv' samples = [] for data_dir in data_dirs: print('Loading samples from dir {0}'.format(data_dir)) driving_data = pd.DataFrame.from_csv(os.path.join(data_dir, ...
The main task of the code is to train a machine learning model using data generators, splitting the dataset into training and validation sets, applying callbacks for model checkpointing and early stopping, and returning the trained model along with training history. It uses `fit_generator` to train the model on generat...
def train(model, model_save_path, x_generator, y_generator, data_dirs, skip_steerings=None, use_side_cameras=False, steering_correction=0.2, generator_batch_size=128, nb_epoch=10): print('========================================================') origin_samples = load_samples(data_dirs, ski...
def check_top(number): if(number['line']>0): return check_line(schematic[number['line']-1],number['line']-1,number) return False def check_bottom(number): if(number['line']<len(schematic)-1): return check_line(schematic[number['line']+1],number['line']+1,number) return False def check_le...
The code checks if a given number meets any of four directional conditions (top, bottom, left, right) using logical OR, returning True if any condition is satisfied.
def check_number(number): return ( check_top(number) or check_bottom(number) or check_left(number) or check_right(number))
def check_top(number): if(number['line']>0): return check_line(schematic[number['line']-1]) return False def check_bottom(number): if(number['line']<len(schematic)-1): return check_line(schematic[number['line']+1]) return False def check_left(number): if(number['start']>0): ...
The code checks if a given number meets any of four directional conditions (top, bottom, left, right) by evaluating the results of four helper functions using logical ORs, returning True if any condition is satisfied.
def check_number(number): return ( check_top(number) or check_bottom(number) or check_left(number) or check_right(number))
def _get(self, d, k, mark, key=None): return self._log_if_none(key or k, d[k] if k in d else None, mark) def _parse_category(self, item, item_id): assert item is not None assert item_id is not None categories = self._get(item, 'Category', item_id) if categories is not None: ...
The code processes a list of items by extracting each item's ID and parsing its category, bid, and item details using helper methods, ensuring valid input and non-null item IDs through assertions.
def parse(self, items): assert items is not None for item in items: item_id = self._get(item, 'ItemID', 'at start') assert item_id is not None self._parse_category(item, item_id) self._parse_bid(item, item_id) self._parse_item(item, item_id)
def retrieve(n): d=" " print("retrieval of data") name_e1.delete(0,END) pswd_e1.delete(0,END) add_e1.delete(0,END) mail_e1.delete(0,END) contact_e1.delete(0,END) details=retrieval_data(n) print(details) name_e1.insert(0,details[0][1]) pswd_e1.insert(0,details[0][-1]) ...
The main task of the code is to create an admin profile management interface in a GUI application. It hides previous frames, displays a new frame with input fields for admin details (ID, name, password, etc.), and includes buttons to retrieve data, update profiles, delete entries, and return to the home screen. The int...
def adminProfile(): try: frame2.place_forget() frame3.place_forget() except: pass global frame7 frame7 = LabelFrame(root,bg="#142850") frame7.place(x=500,y=147,height=550,width=700) space=Label(frame7,text=" ",bg="#142850",fg="#ffffff",font=("Ubuntu",23,"bold"),ancho...
def retrieve_data(idd,upas): mydb=mysql.connector.connect( host="localhost", user="root", password="lenovog500s", database="DISPUR") cursor=mydb.cursor() data=(idd,upas) a="select * from customer where Reg_Id=%s and password=%s " cursor.execute(a,data) result=cursor.fetchall() ...
The code defines a login function that retrieves username and password from entry fields, verifies them against database records, and navigates to either an admin profile or user profile based on credentials. If invalid, it displays an error message.
def login(): idd=reg_en.get() reg_en.delete(0,END) u_pas=pas_en.get() pas_en.delete(0,END) res=retrieve_data(idd,u_pas) print("start",res,"Return valus") if(len(res) !=0): print("1st if",res[0][0]) if(str(idd)==str(res[0][0]) and u_pas==res[0][5]): print("2nd if...
def parse_arguments(args=None): parser = argparse.ArgumentParser(description = "This program removes reads from a BAM file according to the " + "filtering criteria. \n" + "1. Removes unmapped reads \n" + "2. Removes reads with invalid edit distance \n" + ...
The main task of the code is to filter BAM files based on specified parameters such as edit distance, insert size, mapping quality, and paired/single-read status. It processes input BAM files, applies quality control thresholds, and outputs filtered results to a designated directory. The script handles both paired and ...
def main(): args = parse_arguments() # test args # args = parse_arguments('--edit_max 100 --edit_min 0 --hybrid_reference ' \ # '-i /mnt/data/nextseq190419/yi293_GAACCG_1min_UV_with_USER_HAP1/split/subset/yi293_GAACCG.CTTTCTCTCGACTTG.human.bam ' \ # ...
def move_center(self, delta: tuple[int, int]): self.center = (self.center[0] + delta[0], self.center[1] + delta[1]) self._fix_center() self._show() def scale_up(self, at: tuple[int, int]): if self.scale < PlotWindow.MAX_SCALE: self.scale += PlotWindow.SCALE_STEP self....
This code handles mouse interactions for dragging and zooming in an image or object. It updates the dragging position when the left mouse button is pressed, releases dragging when the button is released, and scales the view up/down based on mouse wheel input. The title is updated after scaling operations to reflect cha...
def _on_mouse(self, event: int, x: int, y: int, flag: int, userdata): if flag & cv2.EVENT_FLAG_LBUTTON: if self._dragging is not None: self.move_center((self._dragging[0] - x, self._dragging[1] - y)) self._dragging = (x, y) elif self._dragging is not None and (not...
def reassign_communities(self): changes = False for u in self.edge_dct: c = self.node_community[u] self.reassign_community(u, c) if self.node_community[u] != c: changes = True return changes def deprecate_communities(self): new_G = {x...
The code implements the Louvain community detection algorithm, iteratively optimizing community assignments by reassigning nodes to maximize modularity. It removes empty communities, tracks community structures in `packed_communities`, updates the graph with deprecated communities, and terminates after one iteration. T...
def louvain(self): while True: idx = 0 changes = True while changes == True: idx += 1 changes = self.reassign_communities() empty_communities = [] for c in self.communities: if self.communities[c] == se...
def getDHDict(dh_line_list, joint_positions): dh_dict = dict({'alpha_i': [], 'a_i': [], 'd_i': [], 'theta_i': [] }) keys = ['alpha_i', 'd_i', 'a_i', 'theta_i'] for i, line in enumerate(dh_line_list): for j, key in enumer...
This function calculates the error and joint adjustments (delta_theta) for a robotic arm's end-effector to reach a desired position/rotation. It processes Denavit-Hartenberg (DH) parameters to compute transformation matrices, derives the Jacobian matrix, compares current and desired end-effector states, and computes th...
def getUpdateStep(point, R, joint_positions, dh_params): lines = dh_params.split("\n") dh_dict = getDHDict(lines, joint_positions) T = getTransformationMatrices(dh_dict) J = getJacobianMatrix(T) desired_params = [point, R] global current_params current_params = [getCoordinates(T[-1]), getRo...
def Gamma1mese(M, Ue, Umu, Utau): z = GammaRhoe(M, Ue, Umu, Utau) + GammaPie(M, Ue, Umu, Utau) + GammaKe(M, Ue, Umu, Utau) + GammaKse(M, Ue, Umu, Utau) + GammaDe(M, Ue, Umu, Utau) + GammaDse(M, Ue, Umu, Utau) return z def Gamma1mesmu(M, Ue, Umu, Utau): z = GammaRhomu(M, Ue, Umu, Utau) + GammaPimu(M, Ue, Umu...
The function `Gamma1mes` calculates the total value of Gamma1mes by summing four components: `Gamma1mese`, `Gamma1mesmu`, `Gamma1mesv`, and `GammaPitau`, each contributing to the overall result based on inputs M, Ue, Umu, and Utau.
def Gamma1mes(M, Ue, Umu, Utau): z = Gamma1mese(M, Ue, Umu, Utau) + Gamma1mesmu(M, Ue, Umu, Utau) + Gamma1mesv(M, Ue, Umu, Utau) + GammaPitau(M, Ue, Umu, Utau) return z
def Gammavvv(M, Ue, Umu, Utau): GF = 1.16e-5 A = (GF**2)/(192*(pi**3)) z = (Ue**2 + Umu**2 + Utau**2)*A*(M**5) return z def Gammavee(M, Ue, Umu, Utau): me = 5.11e-4 if M >= 2*me: z= (Ue**2 + Umu**2 + Utau**2)*Gammavll1(me,M) + (Ue**2)*Gammavll2(me, M) else: z=0 return z d...
The function `Gammalep` computes the total value `z` by summing seven distinct Gamma-related components (`Gammavvv`, `Gammavee`, etc.), each likely representing specific physical processes or terms in a theoretical model. It returns this aggregated result, combining contributions from various interactions involving par...
def Gammalep(M, Ue, Umu, Utau): z = Gammavvv(M, Ue, Umu, Utau) + Gammavee(M, Ue, Umu, Utau) + Gammavmumu(M, Ue, Umu, Utau) + Gammavemmup(M, Ue, Umu, Utau) + Gammavmumep(M, Ue, Umu, Utau) + Gammavemtaup(M, Ue, Umu, Utau) + Gammavtaumep(M, Ue, Umu, Utau) return z
def GammaPie(M, Ue, Umu, Utau): mPi = 0.13957 fPi = 0.13 Vud = 9.737e-1 me = 5.11e-4 if M >= (mPi + me): z = (Ue**2)*GammaPl(fPi, mPi, Vud, M, me) else: z = 0 return z def Gammavee(M, Ue, Umu, Utau): me = 5.11e-4 if M >= 2*me: z= (Ue**2 + Umu**2 + Utau**2)*Gam...
The code calculates a value `z` based on the ratio of summed decay rates (Gamma functions) when the input mass `M` exceeds twice the electron mass (`2*me`). If `M` meets this condition, `z` is the square root of the ratio of specific decay rate combinations; otherwise, `z` is zero. The Gamma functions likely represent ...
def ReT2KCC(M): me = 5.11e-4 if M >= 2*me: z = sqrt((GammaPie(M,1,0,0)+Gammavee(M,1,0,0)+Gammavemmup(M,1,0,0)+Gammavmumu(M,1,0,0))/ (GammaveeCC(M,1,0,0)+GammaPie(M,1,0,0)+Gammavemmup(M,1,0,0))) else: z = 0 return z
def Gammavee(M, Ue, Umu, Utau): me = 5.11e-4 if M >= 2*me: z= (Ue**2 + Umu**2 + Utau**2)*Gammavll1(me,M) + (Ue**2)*Gammavll2(me, M) else: z=0 return z def Gammavemmup(M, Ue, Umu, Utau): me = 5.11e-4 mmu = 1.05e-1 if M >= (me + mmu): z= (Ue**2)*Gammavllp(M, mmu) e...
The code calculates a ratio of decay rates (z) for a particle process involving charm quarks (ReCHARMCC) when the input mass M exceeds twice the electron mass (2*me). It sums three decay rate functions (Gammavee, Gammavemmup, Gammavmumu) in the numerator and two (GammaveeCC, Gammavemmup) in the denominator. If M is bel...
def ReCHARMCC(M): me = 5.11e-4 if M >= 2*me: z = sqrt((Gammavee(M, 1, 0, 0) + Gammavemmup(M, 1, 0, 0) + Gammavmumu(M, 1, 0, 0))/ (GammaveeCC(M, 1, 0, 0) + Gammavemmup(M, 1, 0, 0))) else: z = 0 return z
def GammaPie(M, Ue, Umu, Utau): mPi = 0.13957 fPi = 0.13 Vud = 9.737e-1 me = 5.11e-4 if M >= (mPi + me): z = (Ue**2)*GammaPl(fPi, mPi, Vud, M, me) else: z = 0 return z def Gammavee(M, Ue, Umu, Utau): me = 5.11e-4 if M >= 2*me: z= (Ue**2 + Umu**2 + Utau**2)*Gam...
The code calculates a value `z` as the square root of the ratio of summed decay width functions (GammaPie, Gammavee, Gammavmumu, Gammavemmup) to another set (GammaveeCC, Gammavemmup) for a given mass `M`, but only if `M` lies within a specific range defined by constants `mDs`, `mPi`, and `me`. The result `z` likely rep...
def ReBEBCCC(M): mDs = 1.97 mPi = 0.13957 me = 5.11e-4 if M > (mPi+me): if M < (mDs-me): z = sqrt((GammaPie(M,1,0,0)+Gammavee(M,1,0,0)+Gammavmumu(M,1,0,0)+Gammavemmup(M,1,0,0))/ (GammaPie(M,1,0,0)+GammaveeCC(M,1,0,0)+Gammavemmup(M,1,0,0))) return z
def Gammavee(M, Ue, Umu, Utau): me = 5.11e-4 if M >= 2*me: z= (Ue**2 + Umu**2 + Utau**2)*Gammavll1(me,M) + (Ue**2)*Gammavll2(me, M) else: z=0 return z def Gammavemmup(M, Ue, Umu, Utau): me = 5.11e-4 mmu = 1.05e-1 if M >= (me + mmu): z= (Ue**2)*Gammavllp(M, mmu) e...
The function computes a value `z` based on the input mass `M`, using a ratio of summed gamma functions (Gammavee, Gammavemmup, Gammavmumu, GammaveeCC) under a conditional threshold (twice the electron mass). If `M` meets the threshold, `z` is the square root of the ratio of these sums; otherwise, `z` is zero. This like...
def ReLHCCC(M): me = 5.11e-4 if M >= 2*me: z = sqrt((Gammavee(M, 1, 0, 0) + Gammavemmup(M, 1, 0, 0) + Gammavmumu(M, 1, 0, 0))/ (GammaveeCC(M, 1, 0, 0) + Gammavemmup(M, 1, 0, 0))) else: z = 0 return z
def Gammavmumep(M, Ue, Umu, Utau): me = 5.11e-4 mmu = 1.05e-1 if M >= (me + mmu): z= (Umu**2)*Gammavllp(M, mmu) else: z=0 return z def Gammavmumu(M, Ue, Umu, Utau): mmu = 1.05e-1 if M >= 2*mmu: z= (Ue**2 + Umu**2 + Utau**2)*Gammavll1(mmu,M) + (Umu**2)*Gammavll2(mmu, ...
The function RmuNUTEVCC calculates the square root of a ratio of summed decay width terms (Gammavmumep, Gammavmumu, GammaPimu, GammaRhomu) to their corresponding charged-current (CC) counterparts, but only if the input mass M exceeds the sum of me (5.11e-4) and mmu (1.05e-1). Otherwise, it returns zero. This computes a...
def RmuNUTEVCC(M): me = 5.11e-4 mmu = 1.05e-1 if M >= me + mmu: z = sqrt((Gammavmumep(M,0,1,0) + Gammavmumu(M,0,1,0) + GammaPimu(M,0,1,0) + GammaRhomu(M,0,1,0))/ (GammavmumuCC(M,0,1,0)+Gammavmumep(M,0,1,0)+GammaPimu(M,0,1,0)+GammaRhomu(M,0,1,0))) else: z = 0 return z
def GammaPimu(M, Ue, Umu, Utau): mPi = 0.13957 fPi = 0.13 Vud = 9.737e-1 mmu = 1.05e-1 if M >= (mPi + mmu): z = (Umu**2)*GammaPl(fPi, mPi, Vud, M, mmu) else: z = 0 return z def Gammavmumu(M, Ue, Umu, Utau): mmu = 1.05e-1 if M >= 2*mmu: z= (Ue**2 + Umu**2 + Uta...
This code calculates a dimensionless parameter 'z' by evaluating the square root of a ratio of summed decay rates (Gamma functions) for particle interactions, conditioned on the input mass 'M' exceeding a threshold (me + mmu). If the condition is met, it computes the ratio of specific decay processes; otherwise, 'z' is...
def RmuT2KCC(M): me = 5.11e-4 mmu = 1.05e-1 if M >= me + mmu: z = sqrt((GammaPimu(M,0,1,0) + Gammavmumu(M,0,1,0) + Gammavmumep(M,0,1,0) + Gammavee(M,0,1,0))/ (GammavmumuCC(M,0,1,0) + GammaPimu(M,0,1,0) + Gammavmumep(M,0,1,0))) else: z = 0 return z
def Gammavmumu(M, Ue, Umu, Utau): mmu = 1.05e-1 if M >= 2*mmu: z= (Ue**2 + Umu**2 + Utau**2)*Gammavll1(mmu,M) + (Umu**2)*Gammavll2(mmu, M) else: z=0 return z def Gammavmumep(M, Ue, Umu, Utau): me = 5.11e-4 mmu = 1.05e-1 if M >= (me + mmu): z= (Umu**2)*Gammavllp(M, mmu...
The code calculates a ratio involving decay rates (Gammavmumu, Gammavmumep, Gammavee, GammavmumuCC) for a given mass M. If M exceeds the sum of me (electron mass) and mmu (muon mass), it returns the square root of the ratio of summed decay rates; otherwise, it returns zero. This likely computes a branching fraction or ...
def RmuLHCCC(M): me = 5.11e-4 mmu = 1.05e-1 if M >= me + mmu: z = sqrt((Gammavmumu(M, 0, 1, 0) + Gammavmumep(M, 0, 1, 0) + Gammavee(M, 0, 1, 0))/ (GammavmumuCC(M, 0, 1, 0) + Gammavmumep(M, 0, 1, 0))) else: z = 0 return z
def gradient(func, h, params): """ calculates a gradient of a given function by numerical methods """ gradient_vector = np.array([(func(*(params[:i]+[params[i]+h]+params[i+1:]))- func(*(params[:i]+[params[i]-h]+params[i+1:])))/(2*h) for i in range(len(params))]) return grad...
This code implements gradient descent to minimize a given function using either Fibonacci or Golden Ratio methods for step size determination. It iteratively updates parameters by computing gradients, selects optimal steps via specified methods, tracks iterations, and returns the sequence of points approached during op...
def gradient_descent_swift(func, params, eps, method, start=0, end=1): """ swift gradient descent method to minimize a given function with given method (fibonacci or golden ratio) """ qty_steps=1 dot0 = np.array(params) steps = [dot0] while(np.linalg.norm(gradient(func, eps, dot0.t...
def _generate_fields(gen_name, annotations): for field_name, type_ in annotations.items(): if type(type_) == UnionType: yield from _generate_nullable(gen_name, field_name, type_) elif type(type_) == GenericAlias and get_origin(type_) == list: yield from _generate_multiple(gen...
This code generates code files from class and enum definitions using Jinja2 templates, filtering classes/enums by generation name and dependencies, then writing structured output to files while avoiding name conflicts.
def generate(gen_name, path, enums, classes, deps, settings): env = jinja2.Environment(loader=jinja2.FileSystemLoader(pathlib.Path(path, 'templates'))) rendered_classes = [] for _, klass in classes: field_tags = [] for tag in klass._tags: if tag.gen == gen_name: b...
def get_random_user_id() -> str: random_index = random.randint(0, len(get_user_id_list()) - 1) return get_user_id_list()[random_index] def generate_user_agent() -> str: return fake.user_agent() def generate_ip_address() -> str: return fake.ipv4()
The main task of the code is to generate a synthetic click event dictionary containing unique identifiers, user details, source platform, user agent, IP address, and timestamp. It creates randomized or default values for fields like user_id, source, and user_agent, then compiles them into a structured event object for ...
def generate_click_event(user_id: Optional[str] = None) -> dict: click_id = str(uuid4()) user_id = user_id if user_id else get_random_user_id() source = random.choice(["Unknown", "Facebook", "Unknown", "Twitter", "Tiktok", "Gmail", "Unknown", "Google", "Unknown", "Youtube", "Unknown"...
def generate_click_event(user_id: Optional[str] = None) -> dict: click_id = str(uuid4()) user_id = user_id if user_id else get_random_user_id() source = random.choice(["Unknown", "Facebook", "Unknown", "Twitter", "Tiktok", "Gmail", "Unknown", "Google", "Unknown", "Youtube", "Unknown"...
The code generates synthetic user click and checkout events, pushing them to Kafka topics for simulation. It first creates a click event, then randomly (50% chance) generates a checkout event linked to the same user, mimicking user behavior data streams for testing or analytics.
def generate_click_datastream() -> None: click_event = generate_click_event(None) push_to_kafka(click_event, 'clicks') # 50% of the time is checkouts while random.randint(1, 100) <= 50: checkout_event = generate_checkout_event(click_event['user_id'], get_random_product_id()) push_to_kafka(checkout_ev...
def __open_socket(self): address = (self.__ip, 80) self.__connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.__connection.bind(address) self.__connection.listen(5) def __wdt_init(self): wdt = WDT(timeout=5000) wdt.feed() wdt_timer = Tim...
The code listens for incoming client connections via a socket, initializes a watchdog timer, and routes each accepted connection to a handler. It continuously accepts clients in a loop, processes them using a router, and closes the connection after handling.
def listen(self): print('Listening for requests...') self.__open_socket() self.__wdt_init() while True: client = self.__connection.accept()[0] self.__router(client) client.close()
def calc_fkine_space(S, M, q): T = np.eye(4) for i in range(S.shape[1]): s = S[:, i] t = q[i] twist = twist2ht(s, t) T = T @ twist T = T @ M return T def MatrixLog6(T): R = T[:3, :3] p = T[:3, 3:] omg_mat = MatrixLog3(R) if np.equal(omg_mat, np.zeros((...
This code implements an inverse kinematics (IK) solver using the Jacobian pseudo-inverse method. It iteratively adjusts a robot's joint angles (q) to reach a target end-effector pose by comparing the current pose (from forward kinematics) to the desired pose, computing the Jacobian matrix, and solving for joint adjustm...
def IK(robot, q): currentPose = robot.getPose() currentQ = robot.getQ() T = calc_fkine_space(S, M, q) targetPose = MatrixLog6(T) targetPose = np.array([[targetPose[2, 1], targetPose[0, 2], targetPose[1, 0], *targetPose[:3, 3]]]).T while np.linalg.norm(targetPose - currentPose) > 1e-3: ...