dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_source_dir(): """Directory of the python executable""" global source_dir return source_dir def install_2000(source): """Install Dominions ][. Our current directory should be an empty game directory""" if os.path.exists('DOMIN2.EXE'): raise Exception("Refusing to install over an e...
The main task of the code is to manage a Dominions game server, handling installation, user management, and game operations. It uses command-line arguments to install games (with version control), add/remove users, run the game, or execute nightly turns. The code ensures directory setup, loads a game database, enforces...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--gamedir', default='.', help='Game directory. Defaults to current directory.') subparsers = parser.add_subparsers(help='sub-command', dest='cmd') install_parser = subparsers.add_parser('install', help='Install a new Domi...
def getData(): # return symboldf, column names, row list url = "https://www.prnewswire.com/news-releases/news-releases-list/" symbol_df = tickerFromCision(url) if symbol_df.empty == False: tickerList = symbol_df.iloc[:,0].tolist() # all symbols for symbol in tickerList: if symbo...
The code processes data by retrieving it with `getData()`, checks for errors (returning -1 if failed), then saves symbol data to 'symbol.csv' and transforms column formats using `changeColmnformat()` before saving the transformed data to 'yahoo.csv'
def process(): res = getData() if res == -1: return -1 else: symboldf = res[0] colname = res[1] rowlist=res[2] print(symboldf) savecsv('./symbol.csv',symboldf) final_df = changeColmnformat(colname,rowlist) print(final_df) savecsv('./yah...
def do_installs(): nltk.download('punkt') def create_or_open_index(index_dir): if not os.path.exists(index_dir): os.makedirs(index_dir) print(f"Created new index directory: {index_dir}") # Ensure indexed_files.txt is empty with open(CONFIG["INDEXED_FILES_LIST"], 'w',encoding="utf...
The main task of the code is to index all 'transcription.txt' files in a specified directory into a search index, skipping already indexed files. It creates/openes an index, walks through the directory, processes each file with an asynchronous writer, and commits the indexed data for search.
def index_content(): do_installs() print(f"Indexing content from directory: {CONFIG['txt_directory']}") ix = create_or_open_index(CONFIG["index_dir"]) writer = AsyncWriter(ix) indexed_files = get_indexed_files() with ix.searcher() as searcher: for root, _, files in os.walk(CONFIG["txt_...
def read_fitnesses(self): """ Goes through all of the {indv_id}.fit in trial/gen/ and reads them into a dict of {indv_id:fit} """ #fitness_files = glob.glob("trial%d/gen%d/*.fit" % (self.trial_num, self.cur_gen)) # we're going to have all of them in one JSON file for now fitness_dict = {} for i in r...
This code manages an evolutionary algorithm process by either resuming from a previous trial's highest generation or starting anew. It loads existing populations, computes fitness, selects top individuals, and evolves them through generations. Error handling includes logging and dumping state for recovery. The core tas...
def start(self, trial_num, n_generations): """ Runs through the whole process """ # Build in ability to recover self.trial_num = trial_num if os.path.isdir("trial%d" % trial_num): highest_gen = max(map(lambda x: int(x.split('/')[-1][3:]), glob.glob("trial%d/gen*" % (trial_num)))) else: h...
def get_tool_conf(): tool_conf = ToolConfJsonFile(get_lti_config_path()) return tool_conf def get_launch_data_storage(): return DjangoCacheDataStorage() def index(request): # get data for launch tool_conf = get_tool_conf() # render index.html return render( request, "index.h...
The main task of the code is to process an LTI (Learning Tools Interoperability) launch request by retrieving configuration and launch data, extracting user and course information from the LTI message payload, storing key details in global variables, and rendering the index page. It initializes an LTI message handler, ...
def launch(request): # get data for launch tool_conf = get_tool_conf() launch_data_storage = get_launch_data_storage() message_launch = ExtendedDjangoMessageLaunch( request, tool_conf, launch_data_storage=launch_data_storage ) message_launch_data = message_launch.get_launch_data() pp...
def generate_userdata(): firstname, lastname = barnum.create_name() lastname += str(random.randint(1, 1000)) password = barnum.create_pw(length=10) email = barnum.create_email(name=(firstname, lastname)).lower() return firstname, lastname, email, password def register_user(self, ...
The main task of the code is to inject test data ("noise") into a service for later retrieval, with methods varying based on `self.variant_id`. It generates user data, creates posts, uploads images, and stores recovery details in `chain_db`. The noise is non-secret and can be recovered, with different scenarios handlin...
def putnoise(self): # type: () -> None """ This method stores noise in the service. The noise should later be recoverable. The difference between noise and flag is, that noise does not have to remain secret for other teams. This method can be called many times per round. Check how often...
def check_pages(self, flag): page = 0 while 1: t = self.check_page(page) if "Activities by" not in t: return "" if flag in t: return t page += 1 def login_user(self, email: str, password: str): resp = self.http_post(...
The `getnoise` method retrieves and verifies noise data (text or images) from a service based on `variant_id`, ensuring correct functionality through assertions and error checks. It handles public/private posts, image uploads, and validation, raising exceptions on failures like missing data or mismatched responses.
def getnoise(self): # type: () -> None """ This method retrieves noise in the service. The noise to be retrieved is inside self.flag The difference between noise and flag is, that noise does not have to remain secret for other teams. This method can be called many times per roun...
def pulley(self, state: str): if state == "up": self.motor(75, "pulley") # elif state == "down": self.motor(-50, "pulley") elif state == "stop": self.motor(0, "pulley") def pusher_activate(self): """back and forth movement""" self.pusher("push...
The code's main task is to execute a timed sequence of mechanical operations to offload an item: lowering a pulley, stopping it, activating a pusher, raising the pulley again, and reactivating the pulley with precise delays to ensure synchronized movement during the offloading process.
def offload(self): """method for complete offload operation""" self.pulley("down") time.sleep(0.97) self.pulley("stop") self.pusher_activate() self.pulley("up") time.sleep(1.1) self.pulley_activate()
def CheckDependencies(self, verbose_output=True): """Checks the availability of the dependencies. Args: verbose_output (Optional[bool]): True if output should be verbose. Returns: bool: True if the dependencies are available, False otherwise. """ check_result = True if self._depend...
(The main task of the code is to check the availability and versions of test dependencies required for running tests. It first verifies base dependencies via `CheckDependencies`, then iterates through sorted test dependencies to validate each module's presence and version using `_CheckPythonModule`. Results are logged,...
def CheckTestDependencies(self, verbose_output=True): """Checks the availability of the dependencies when running tests. Args: verbose_output (Optional[bool]): True if output should be verbose. Returns: bool: True if the dependencies are available, False otherwise. """ if not self.Chec...
def process_report(self, report_path): logger().info(f"processing report: {report_path}") try: with open(report_path, "r") as report: return self.process_lines(report) except EnvironmentError: return result.unknown def valid_result(self): if self....
The code initializes a class with a report and configuration, processes the report to determine a verification result, validates the result, logs details, and optionally parses a model if symbolic analysis is enabled.
def __init__(self, report, cfg): self.cfg = cfg self.model = Model() self.verification_result = self.process_report(report) if report else result.unknown if not self.valid_result(): logger().info(f"invalid result: {self.verification_result}") self.verification_r...
def swap(self, i, j): self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def dec_count(self): self.count -= 1 def max_heapify(self, k): self.sink(k)
The code implements a heap sort algorithm by repeatedly extracting the maximum element from the heap, swapping it to the end of the array, reducing the heap size, and re-heapifying to maintain the max-heap structure, thus sorting the array in ascending order.
def sort(self): for _ in range(1, len(self.arr)): self.swap(1, self.count) self.dec_count() self.max_heapify(1)
def get_page_type(page_strings): page_header = page_strings[0] if page_header == OFFICER_PAGE_HEADER: return PageType.officer elif page_header == SUMMARY_PAGE_HEADER: return PageType.summary return PageType.unknown def parse_officer_page(page_markdown, page_strings, df=None): all_nam...
This code processes a PDF file by parsing its content page-by-page, extracting structured data (names, violations, demographics) from specific page types (officer and summary pages), and compiling the extracted information into a CSV file for further analysis or reporting.
def main(): fname = sys.argv[1] f = open(fname, "rb") viewer = SimplePDFViewer(f) viewer.render() page_strings = viewer.canvas.strings page_markdown = viewer.canvas.text_content page_type = get_page_type(page_strings) df = pandas.DataFrame(columns = ['Name', 'Violation'] + ['/'.joi...
def switch_jean_pos(): # switching the jean postion x=jean_pos[0] y=jean_pos[1] if x==3 and y==4: jean_pos[0]=jean_pos[1]=0 else: jean_pos[0]=3 jean_pos[1]=4 def move_wolverine(U): # move wolverine x=wolverine[0] y=wolverine[1] up_x=x-1 up_y=y up_value=0...
The main task of the code is to perform policy iteration in a reinforcement learning framework. It iteratively evaluates and improves a policy by updating the utility matrix (U) and checking for optimal actions. The loop continues until the policy stabilizes or Wolverine reaches Jean, incorporating random movements for...
def policyIteration(policy, U): while True: if random.randint(1, 100) <80: switch_jean_pos() move_wolverine(U) move_magneto_in_random_direction() U = policyEvaluation(policy, U) unchanged = True for r in range(NUM_ROW...
def update_cols( flt, pars, OMSLOP ): """ update the twotheta, eta, g-vector columns to be sure they are right fill in some weighting estimates for fitting """ tth, eta = transform.compute_tth_eta( [flt.sc, flt.fc], **pars.parameters ) gve = transform.compute_g_vectors( tth, eta, flt.omega,...
The code processes diffraction data by filtering column files, assigning peaks to grains, and reconstructing grain orientations. It reads input files, sets parameters for peak detection and image reconstruction, updates column data, and iterates over grains to fit each, generate sinograms, and extract active regions. R...
def main(): flt = columnfile.columnfile( sys.argv[1] ) grains = grain.read_grain_file( sys.argv[2] ) pars = parameters.read_par_file( sys.argv[3] ) newgrainfile = sys.argv[4] hkltol = 0.05 # for first peak assignments nmedian = 5 # for removing peak fit outliers omegastep = ...
def eat(screen): message_display("It has no taste", screen) def hear( screen): message_display("This is the AXC " , screen) def see(screen): message_display("hi Iam " + c.UserDict[c.usuario][0], screen) def text_objects(text, font): textSurface = font.render(text, True, c.BLACK) return textSu...
This function creates a Pygame button that changes color when hovered and triggers actions like "eat", "hear1", or "see1" when clicked. It draws the button on the screen, checks mouse interactions, and executes predefined functions based on the 'action' parameter.
def button(msg,x,y,w,h,ic,ac, screen, event, action=None): mouse = pg.mouse.get_pos() if x+w > mouse[0] > x and y+h > mouse[1] > y: pg.draw.rect(screen, ac,(x,y,w,h)) if event.type == pg.MOUSEBUTTONDOWN and action != None: if action == "eat": eat(screen) e...
def hear( screen): message_display(p.create_database() , screen) def see(screen): message_display("hi Iam Pomologist" , screen) def text_objects(text, font): textSurface = font.render(text, True, c.BLACK) return textSurface, textSurface.get_rect()
This function creates a Pygame button with hover and click functionality. It draws a rectangular button at specified coordinates, changes color when hovered, and executes predefined actions ("hear" or "see") on mouse click. The button displays text centered within its bounds, using Pygame's font rendering. It handles m...
def button(msg,x,y,w,h,ic,ac, screen, event, action=None): mouse = pg.mouse.get_pos() if x+w > mouse[0] > x and y+h > mouse[1] > y: pg.draw.rect(screen, ac,(x,y,w,h)) if event.type == pg.MOUSEBUTTONDOWN and action != None: if action == "hear": hear(screen) el...
def sweep(*funcs, **kwargs : Optional[Dict[str,Union[float,tuple]]] ) -> Union[Dict[str,Array],Array]: ''' Performs a dc analysis sweep of the input voltage `Vin`, and optionally over any tuples in `kwargs`. If any `kwargs` are not tuples, they are treated as circuit parameters for ...
The function `bifurcate` performs bifurcation analysis of a dynamical system by iterating initial conditions `v0` over parameter sweeps or grids. It discards transient dynamics (`T` steps) and computes Lyapunov exponents for stable states. Results are stored in an `xarray.Dataset`, with separate variables for each para...
def bifurcate(res=None, v0=0, T=500, N=1000, as_grid=False, **kwargs): ''' Creates a bifurcation of the system about the given parameters. If `as_grid`, the result is assumed to be evaluated over a grid; else, a `sweep` is assumed. ...
def wait(self, delaytime): startTime = time.time() while time.time() < startTime + delaytime: pass def hubRLR(self, angle): self.hub0R(angle) self.hub1L(angle) self.hub2R(angle) def hubLRL(self, angle): self.hub0L(angle) self.hub1R(angle) self....
The code executes a sequence of timed movements and rotations, likely controlling a mechanical system or robot. It alternates between setting hub positions (hubRLR, hubLRL) and rotational adjustments (rotRLR, rotLRL) with pauses (wait) to synchronize actions, suggesting a walking or stepping motion pattern.
def plugWalk(self): self.wait(self.speed) self.hubRLR(30) self.hubLRL(0) self.wait(self.speed) self.rotRLR(-30) self.rotLRL(30) self.wait(self.speed) self.hubRLR(0) self.hubLRL(30) self.wait(self.speed) self.rotRLR(30) ...
def make_cmd_array(command, data_list, data_byte_count=FP_DATA_BYTES): byte_list = flatten([to_bytes(i, data_byte_count) for i in data_list]) return "({}, {})".format(std_logic_vector(command, 8), ", ".join([std_logic_vector(i, 8) for i in byte_list])), len(byte_list)+1 def flatten(list_of_lists): if len(li...
The code generates VHDL constant arrays from various data parameters (e.g., frequencies, polynomial features, weights) by converting them to hexadecimal, creating command arrays, and printing them with size calculations. It tracks total byte count for all parameters and outputs VHDL code for hardware description. The m...
def print_tb_arrays(): byte_count = 0 print("type variable_array is array (natural range <>) of std_logic_vector(7 downto 0);") # Send param_frequencies cmds, length = make_cmd_array(cmd["param_frequencies"], flatten(frequencies), data_byte_count=4) byte_count += length print("-- frequencies ="...
def init_system(control_pub, ref_drone, velocity_z): # Function to Initialize the system vx_c = np.array([[0.0], [0.0], [0.0]]) vy_c = np.array([[0.0], [0.0], [0.0]]) vz_c = np.array([[0.0], [0.0], [0.0]]) for k in range(0, 350): tic = time.time() condicion = axes[5] if condi...
The main task of the code is to simulate a drone's control system using PD controllers to track desired velocities (linear and angular) in a body frame, collect real-time system states and control signals during a 60-second simulation, and save the results as MATLAB (.mat) files for analysis. The code initializes param...
def main(control_pub): global massm, gravity, ts, flag_system # Definition Twist message in order to control the system ref_drone = TwistStamped() flag_system = 1 # Simulation time parameters tf = 60 t = np.arange(0, tf+ts, ts, dtype=np.double) # COntrol gains k1 = 1 k2 = 1 ...
def _render(self, epoch, cluster_map, centroids): if self._renderer: self._renderer.render(self._dataset, epoch, cluster_map, centroids) def _update_clusters(self, cluster_map, n_cluster): clusters = [(cluster_map == cluster_id).nonzero()[0] for cluster_id in range(n_cluster)] self._...
This code performs an iterative clustering algorithm by initializing random cluster assignments, updating centroids, and reassigning points to nearest centroids. It visualizes each step, stops early if no reassignments occur, and returns final cluster IDs and centroids.
def run(self, n_cluster, max_epochs=10): cluster_map = np.random.randint(n_cluster, size=self.dataset_size) self._render(RendererBase.INITIAL, cluster_map, centroids=np.empty(shape=(0, 2))) for epoch in range(max_epochs): centroids = self._update_clusters(cluster_map, n_cluster) ...
def solve(self, points) -> Hull: # base case: len(points) = 2 or 3 if len(points) == 2: node1 = Node(points[0]) node2 = Node(points[1]) self.connectNodes(node1, node2) self.connectNodes(node2, node1) return Hull(node1, node2) if len(points) == 3: node1 = Node(points[0]) node2 = Node(points[1...
The code computes the convex hull of a set of 2D points using a sorted list, constructs a polygon from the hull's nodes, and displays the result with a time measurement. It sorts points by x-coordinate, generates QLineF objects for the hull edges, and visualizes the convex hull in red while reporting the computation ti...
def compute_hull( self, points, pause, view): self.pause = pause self.view = view assert( type(points) == list and type(points[0]) == QPointF ) t1 = time.time() sorted_points = sorted(points, key=lambda x: x.x(), reverse=False) t2 = time.time() t3 = time.time() hull = self.solve(sorted_points) ...
def debug_print(message): if DEBUG: print(message) def updateTXT(input): # filepath_txt = sys.argv[2] + '\\misc\\' + filename_txt directory = os.path.dirname(filepath_txt) if not os.path.exists(directory): os.makedirs(directory) with open(filepath_txt, 'a') as file: file.writ...
The code validates Arduino sketch models by checking model parameters, ensuring correct model types and sequences, verifying presence of required .nb files for customized models, and updating logs with model details and header files. It processes JSON/cache files to locate sketches, validates model configurations, and ...
def validationCheck(input): # check current running ino for file_json in os.listdir(input): if file_json.endswith(".json") and "build" in file_json: with open(os.path.join(input, file_json), "r+") as file: data = json.load(file) example_path = data["sketchLoca...
def debug_print(message): if DEBUG: print(message) def input2model(input): # convert user parameter into model name model_mapping = { "CYV3": "yolov3_tiny", "CYV4": "yolov4_tiny", "CYV7": "yolov7_tiny", # "CM8": "mobilefacenet_i8", "CM16": "mobilefacenet_i16",...
The code backs up user models by copying files to a destination directory, handling OS-specific path separators (Linux/macOS vs. Windows), and renaming files during the process. It checks for existing backups, duplicates the Cmodel twice with OS-specific paths, and logs progress.
def backupModel(user_model): # backup Dmodel for dest_file in os.listdir(dest_path): if "Dbackup" in dest_file: debug_print(f"[INFO] Backup-ed {input2model(user_model)}.nb found !!!") break renameFile(input2filename(user_input_sub1), 1) # backup Cmodel if pl...
def debug_print(message): if DEBUG: print(message) def resetTXT(): # filepath_txt = sys.argv[2] + '\\misc\\' + filename_txt directory = os.path.dirname(filepath_txt) if not os.path.exists(directory): os.makedirs(directory) with open(filepath_txt, 'w') as file: pass debug_...
The main task of the code is to process user input (from command-line arguments or manual input), perform validation checks, and reset text and JSON files. It debug-prints parameters, handles input acquisition, and triggers reset and validation functions.
def main(param1, param2): debug_print(f'Parameter 1: {param1}') debug_print(f'Parameter 2: {param2}') user_input_flag = False while user_input_flag == False: if len(sys.argv) > 1: user_input_sub1 = sys.argv[1] else: user_input_sub1 = input("Please provide a valid ...
def get_square_image(width): img = Image.new('RGBA', (width, width), color=(0, 0, 0, 0)) return img def draw_hexagon(img, radius=None, color=(255, 255, 255, 255)): if not radius: radius = min(img.size) / 2 vertexes = [] width, height = img.size x_c = width / 2 y_c = height /...
The function generates an image encoding data using concentric hexagons and markers. It creates a white hexagon, overlays a smaller black one, adds data markers, and writes encoded data. If orientation is 'CRYSTAL', it resizes, rotates (-30°), and thumbnails the image to maintain size. The result is a visual data repre...
def build_code(data, size=1000, color_map=None, orientation=None): code_image = get_square_image(size) code_image = draw_hexagon(code_image, radius=min(code_image.size) / 2, color=(255, 255, 255, 255)) code_image = draw_hexagon(code_image, radius=min(code_image.size) / 2 * 0.99, color=(0, 0, 0, 255)) co...
def count_cell_width(image): transformed_image = transform_for_small_contour_detection(image) triangles = find_shapes(transformed_image, 3) cell_width_values = [] for triangle in triangles: side_length = get_side_length(triangle) cell_width_values.append(side_length) average_value = ...
The code rotates an image by determining an angle based on the colors of six points around its center. It calculates a cell width, identifies six reference points, detects the odd color among them, computes a rotation angle from the odd point's position, and rotates the image accordingly. The rotated image and cell wid...
def rotate(image): cell_width = count_cell_width(image) pick_radius = image.shape[0] / 2 - cell_width / 2 pick_points = count_6_points(image.shape[0] / 2, image.shape[1] / 2, pick_radius) pick_point_colors = [] for point in pick_points: pick_point_colors.append(color_from_area(image, point[1...
def show_image(img, size=700): if len(img.shape) == 3: height, width, _ = img.shape else: height, width = img.shape k = size / max(width, height) img_s = cv.resize(img, (int(width * k), int(height * k))) cv.imshow('Output', img_s) cv.waitKey(0) def transform_for_contour_detection...
The code processes an image by reading, transforming, detecting a hexagonal shape, warping, rotating, extracting data cells, and returning structured data. It automates image analysis for structured grid-based data extraction, likely from scanned documents or patterns.
def scan(path): image = cv.imread(path) show_image(image) transformed_image = transform_for_contour_detection(image) main_hex = find_main_shape(transformed_image, 6) warped_image = warp(image, main_hex) show_image(warped_image) rotated_image, cell_width = rotate(warped_image) show_image(...
def draaiwiel(richting, hoeveelheid): global delay global stepcountVoorAchter aantal = hoeveelheid * 256 for step in range (0,aantal) : time.sleep(delay) if (richting == "links") : links(step % stepcountVoorAchter) if (richting == "rechts") : ...
The code controls a robot's movement using sensor inputs to navigate intersections. It detects crossings via GPIO sensors, adjusts direction based on predefined 'richting' (direction) settings, and sends HTTP status updates. The robot turns left, right, or continues forward, resetting steps periodically. Upon detecting...
def rijden(): step = 0 kruispuntGehad = False while True: #Kruispunt gedetecteerd if (not GPIO.input(sensorl) and not GPIO.input(sensorm) and not GPIO.input(sensorr)) : #Controleren op tweede keer kruispunt if (kruispuntGehad) : #Tweede keer kruispunt ...
def generate_chromosome(constraint = False, constraint_levers = [], constraint_values = [], threshold = False, threshold_names = [], thresholds = []): """ Initialises a chromosome and returns its corresponding lever values, and temperature and cost. **Args**: - constraint (*b...
The code performs genetic algorithm (GA) iterations on the Global Calculator to optimize lever values under constraints, thresholds, and output bounds. It initializes a population, evaluates fitness based on temperature/cost outputs, selects top parents, applies crossover/mutation, and enforces constraints. The process...
def GA_iterate(iterations = 5, population_size = 30, constraint = False, constraint_levers = [], constraint_values = [], output_constraint = False, output_constraint_names = [], output_constraints = [], threshold = False, threshold_names = [], thresholds = [], std_...
def shrink_cols(self, new_cols): self.hidden_cols += self.cols - new_cols self.apply_to_range(Space.grid_remove, col_min=new_cols) self.cols = new_cols def expand_cols(self, new_cols): all_cols = self.cols + self.hidden_cols self.apply_to_range(Space.grid, col_max=min(new_cols, a...
The code adjusts the game grid's size by shrinking or expanding columns and rows based on new dimensions, updates the number of mines, and resets the game state.
def change_size(self, new_rows, new_cols, new_mines): if new_cols < self.cols: self.shrink_cols(new_cols) else: self.expand_cols(new_cols) if new_rows < self.rows: self.shrink_rows(new_rows) else: self.expand_rows(new_rows) self.min...
def right(): global motion aim[0] = 20 aim[1] = 0 motion = "Right" update_motion() def left(): global motion aim[0] = -20 aim[1] = 0 motion = "Left" update_motion() def up(): global motion aim[0] = 0 aim[1] = 20 motion = "Up" update_motion() def down(): gl...
This function manages a snake's motion state in a game. If not paused, it stops the snake and sets status to "Paused". If already paused, it resumes movement in the direction the snake was moving before pausing by analyzing the last two positions of the snake's body, then updates the motion state accordingly.
def paused(): global motion # If the status isn't Paused, make the snake stop and change status into Paused. if motion != "Paused": aim[0] = 0 aim[1] = 0 motion = "Paused" # If the status is Paused, make the snake move along the direction before Paused # and change status int...
def _scan(self, filename: Path, getsig=False) -> ScanResult: procArguments = f"C:\Program Files\Windows Defender\MpCmdRun.exe -Scan -ScanType 3 -File {filename.absolute()} -DisableRemediation -Trace -Level 0x10" process = subprocess.run(procArguments.split(), timeout=30, capture_output=True) if ...
The code recursively scans a file by splitting it into halves, isolating malicious segments. It reads the file, splits it, scans each half using _scan, and if a threat is found, further splits the suspicious portion. The process continues until the threat is pinpointed or no threat is detected, marking the scan as comp...
def scan(self): originalPath = Path(self.filename) originalFileStatus = self._scan(originalPath, True) # No threat found. Exit. if originalFileStatus == ScanResult.NoThreatFound: self.complete = True # Start half-splitting originalFileBytes = originalPath.re...
def detect(self,image): tic = time.time() detections = self.detector.detect(image) if len(detections) == 0: return detections valid_detections_ids = [] # Ignore invalid detections for i,detection in enumerate(detections): if self.valid_detection(de...
The code processes an image for object detection or tracking based on the segmentor's mode. In detection mode, it uses ground-truth boxes or runs detection, adds bounding box buffers, reinitializes trackers, and switches to tracking. In tracking mode, it performs periodic checks and returns tracked objects. It handles ...
def process_image(self,image,time,gt_boxes=None): ''' Process an image by running detection and/or tracking and returning the bouding box, according to the state of the image segmentor. The gt_boxes is an optional argument which is used when using ground-truth for the detected boxes gt_b...
def latency(sender_node,receiver_node,message_bits): """ Function calculates the time delay of sending a packet from one node to the other node Parameters ---------- sender_node:Node object from which packet is sent receiver_node:Node object receiving the packet message_bits: Packet size ...
This function processes events in a blockchain simulation, managing transaction/block propagation, UTXO pool updates, and mining. It handles "generate_txn" (transaction creation), "generate_block" (mining), "receive_txn" (forwarding transactions), "receive_block" (block propagation/fork handling), and "retry_mining" (U...
def event_handler(event_list, event, ttx): """ A function that traverses a min heap: event_list (Top element is a the event with min timestamp) and handles events case-wise. Parameters ---------- event_list: A min heap containing a list of tuple: 1st element is timestamp and 2nd element is the e...
def photometric_distort(image): """ Distort brightness, contrast, saturation, and hue, each with a 50% chance, in random order. :param image: image, a PIL Image :return: distorted image """ new_image = image distortions = [FT.adjust_brightness, FT.adjust_contrast, ...
The code applies data augmentation and preprocessing to images and their annotations for training or testing. For training, it performs photometric distortions, random expansion, cropping, flipping, and normalization. For both splits, it resizes images to 300x300 and normalizes using ImageNet stats. It returns transfor...
def transform(image, boxes, labels, difficulties, split): """ Apply the transformations above. :param image: image, a PIL Image :param boxes: bounding boxes in boundary coordinates, a tensor of dimensions (n_objects, 4) :param labels: labels of objects, a tensor of dimensions (n_objects) :param...
def graphCreator(edges): for val in edges: addEdge(graph,val[0],val[1]) def createInitPopulation(graph): for i in range(0,size_of_population): chromosome = list() for i in range(0,no_of_nodes): n = random.randint(0,2) chromosome.append(n) # print(chromoso...
The code implements a genetic algorithm to solve a graph coloring problem. It creates a random graph, initializes a population with random node colors, iteratively evolves the population over generations to maximize fitness (likely minimizing conflicts), and terminates when optimal fitness (50) is achieved or a timeout...
def main(): gc = Graph_Creator() # ********* You can use the following two functions in your program edges = gc.CreateGraphWithRandomEdges(no_of_edges) # Creates a random graph with 50 vertices and 200 edges #Graph created from the edges graphCreator(edges) #Initial population initialized wit...
def graphCreator(edges): for val in edges: addEdge(graph,val[0],val[1]) def createInitPopulation(graph): for i in range(0,size_of_population): chromosome = list() for i in range(0,no_of_nodes): n = random.randint(0,2) chromosome.append(n) population.appen...
The code implements a genetic algorithm to solve a graph coloring problem, aiming to maximize fitness by assigning colors to nodes. It runs the algorithm on multiple graphs (either from a CSV or randomly generated), tracks fitness over generations, enforces a timeout, and averages results across 10 iterations. The best...
def main(): sum =0 for somerandom in range (10): #This was used in case to run for 10 graphs and find average gc = Graph_Creator() # ********* You can use the following two functions in your program edges = gc.ReadGraphfromCSVfile("Testcases/200") # Reads the edges of the graph from a g...
def onChoose(self): self.c_couplet = str(self.comboBox_couplet.currentText()) self.c_species = str(self.comboBox_species.currentText()) # try: zero_text, one_text = self.db.show_couplet(self.c_couplet) state = self.db.show_state(self.c_species, self.c_couplet) ...
This code initializes UI components by populating combo boxes with database entries and connecting UI events to handler methods. It links combo box selections to the `onChoose` method, navigation buttons to `onCouplet`/`onSpecies` for traversal, the "change" button to `onChange`, and menu actions to password change and...
def UiComponents(self): # ui setup self.comboBox_couplet.addItems(self.db.db_couplets) self.comboBox_species.addItems(self.db.db_species) self.comboBox_status.addItems(['0', '1', '01', 'NA']) self.onChoose() # choose self.comboBox_couplet.currentIndexChanged.co...
def findInColumns(self, columns, groupByFields = [], fieldsToAggregate = []): for column in columns: if column not in self.columns: raise Exception ('There is no such column as',column) def parsColumns(self, columnsID): return lambda row: [row[id] for id in columnsI...
This code performs a database query by selecting rows based on conditions, filtering using variables, and optionally grouping data with aggregation functions. It maps column IDs to selected rows, returns filtered results, or processes grouped/aggregated data if specified. The output includes transformed row data and co...
def Select(self, columns, var1, condition ,var2 , groupByFields, aggFunctions, fieldsToAggregate): self.findInColumns(columns) if condition.text in columns: columnsID = [self.columns[column][ID] for column in columns ] return[map(self.parsColumns(columnsID),self.table), columns] ...
def send_to_server(self, seqid: str = '0', message: str | None = None) -> Tuple[str, int]: '''Send a packet to connected server. :param seqid - str, sequence number :param message - str or None, if None a random message is generated :return server_address - Tuple[str, int], server_addres...
The code runs a client pipeline to send packets to a server, wait for responses, handle timeouts, validate messages, record round-trip times (RTTs), and log results via events and CSV files. It iterates over a specified number of packets, emits status events, checks for errors, and ensures data integrity before summari...
def run(self) -> None: '''Run client pipeline. Make server send a message to the connected server and wait for a valid response. :param None :return None ''' for i in range(self._number_of_packets): server_ip, server_port = self.send_to_server(str(i)) ...
def training_session(self,epochs,sess=None,dir="probeview",continued=False): session = sess if sess else TFT.gen_initialized_session(dir=dir) self.current_session = session self.roundup_probes() # this call must come AFTER the session is created, else graph is not in tensorboard. self.do...
The code's main task is to train a model for a specified number of epochs, test it on training data, execute a final testing session, and close the session. It uses interactive plotting, resumes training if continued, and applies bestk for evaluation. The method manages the training lifecycle, including session handlin...
def run(self,epochs=100,sess=None,continued=False,bestk=None): PLT.ion() self.training_session(epochs,sess=sess,continued=continued) self.test_on_trains(sess=self.current_session,bestk=bestk) self.testing_session(sess=self.current_session,bestk=bestk) self.close_current_session(v...
def is_empty_directory(path): """ Check if directory is empty """ items = os.listdir(path) if len(items) == 0: return True else: return False def is_dot(path): """ Checks if file path(both directory and file) if it is a dot file """ if get_file_pre(path) == '.': ret...
This function recursively scans a directory and its subdirectories, categorizing entries into files, directories, symbolic links, and identifying empty directories. It appends each entry to respective lists in a global 'vars' object, processes files, and checks for dot directories (e.g., . or ..).
def scan_file_directory(path): """ Scan files and directories and increment counter for each """ items = os.scandir(path) for entry in items: if entry.is_dir(): if is_empty_directory(entry.path) == True: vars.empty_dirs.append(entry) vars.di...
def locate_pt(self, x): for face_idx in self.tri_list: e0_id_rot = self.tri_list[face_idx].edge_id_rot[0] e1_id_rot = self.tri_list[face_idx].edge_id_rot[1] e2_id_rot = self.tri_list[face_idx].edge_id_rot[2] orig_id0, dest_id0 = self.edge_list[e0_id_rot[0]].get_e...
This code adds a new point to a Delaunay triangulation by creating a vertex, inserting it into the structure, splitting the containing triangle, and iteratively checking/adjusting to maintain Delaunay properties.
def add_pt(self, x_coord): self.max_vert_id += 1 x = Vertex(x_coord, edge_ids=[], id=self.max_vert_id) self.vert_list[self.max_vert_id] = x cur_tri = self.locate_pt(x) self.split_to_3_tri(cur_tri, x) # d.draw() # draw_vert(x, c='b') while True: ...
def request_user_selection(): """ Asks the user what they would like to drink. """ return input("What would you like to drink? (espresso/latte/cappuccino): ") def generate_report(): """ Generate a report of the shows current resource values. """ available_resources = open_json('data.json...
The code runs a coffee machine by continuously processing user requests until 'off' is entered. It checks available drinks, verifies resource availability, handles payments, updates inventory, and generates reports. The loop ensures repeated user interaction for orders or status checks, terminating only when the user s...
def run_coffee_machine(): """ Main code block to run coffee machine. """ # Variable declarations user_request = request_user_selection().lower() while user_request != 'off': if user_request == 'report': generate_report() if user_request in AVAILABLE_DRINKS: ...
def gamma_correction(rgb, gamma=2.4): """ Apply sRGB gamma correction :param rgb: array of shape (M, N, 3) with sRGB values in the range [0, 255] :param gamma: :return: linear_rgb, array of shape (M, N, 3) with linear sRGB values between in the range [0, 1] """ linear_rgb = np.zeros_like(rgb...
The code processes an input image to either simulate color blindness effects or adjust the image for color-blind viewers. It accepts arguments for input/output paths, simulation mode, color blindness type (d, p, t), and gamma correction. The image undergoes gamma correction, then applies the specified transformation (s...
def main(): import argparse # pylint: disable=invalid-name parser = argparse.ArgumentParser() parser.add_argument("input_image", type=str) parser.add_argument("output_image", type=str) group = parser.add_mutually_exclusive_group() group.add_argument("-s", "--simulate", help="create simulated...
def _prepare_for_transform(fig): """ Gather color keys/info for mpl figure and arange them such that the image simulate() or daltonize() routines can be called on them. """ mpl_colors = get_mpl_colors(fig) rgb, alpha = arrays_from_dict(mpl_colors) return rgb, alpha, mpl_colors def inverse_ga...
This function simulates color blindness on a matplotlib figure by adjusting colors based on the specified type of color deficit (deuteronopia, protonopia, or tritanopia). It applies inverse gamma correction, simulates the color deficiency, reapplies gamma correction, and updates the figure's colors. The simulation can ...
def simulate_mpl(fig, color_deficit='d', copy=False): """ Simulate color blindness on a matplotlib figure. Arguments: ---------- fig : matplotlib.figure.Figure color_deficit : {"d", "p", "t"}, optional type of colorblindness, d for deuteronopia (default), p for protonapia, ...
def _prepare_for_transform(fig): """ Gather color keys/info for mpl figure and arange them such that the image simulate() or daltonize() routines can be called on them. """ mpl_colors = get_mpl_colors(fig) rgb, alpha = arrays_from_dict(mpl_colors) return rgb, alpha, mpl_colors def inverse_ga...
This function Daltonizes a matplotlib figure to make it more accessible for individuals with specific color vision deficiencies (deuteranopia, protanopia, or tritanopia). It adjusts the figure's colors by applying inverse gamma correction, simulating the specified colorblindness, reapplying gamma correction, and updati...
def daltonize_mpl(fig, color_deficit='d', copy=False): """ Daltonize a matplotlib figure. Arguments: ---------- fig : matplotlib.figure.Figure color_deficit : {"d", "p", "t"}, optional type of colorblindness, d for deuteronopia (default), p for protonapia, t for tritanop...
def generate_points(): ret_points = [] step = 1 for k in np.arange(-1, 7 + 2 * step, step): ret_points.append((k, f(k))) return ret_points def spline_third(): n = len(points) first_row = [1] + [0 for i in range(n - 1)] last_row = first_row[::-1] right = 0 left = n - 3 mat...
The main task of the code is to generate a set of 2D points, extract their x and y coordinates, compute a third-order spline interpolation (Y), calculate interpolated points using this spline, and plot both the original points (as red circles) and the interpolated spline points (as blue circles) for visualization. The ...
def main(): global points points = generate_points() xpoints = [x[0] for x in points] ypoints = [y[1] for y in points] # spline_points = spline_first() # xspline = [x for x, _ in spline_points] # yspline = [y for _, y in spline_points] # # plt.plot(xspline, yspline, 'bo') # plt....
def start_ws(self): self.last_ping = dt.datetime.now() self.ohlcv = None self.initiate_ws() self.recv() def getOhlcv(self): params = { "exchange": self.exchange, "segment": self.segment, "symbol": self.symbol, "interval": self.inter...
The main task of the code is to retrieve and process financial market data (OHLCV and footprint) via a WebSocket, filter it based on specified time intervals, compute derived metrics like volume, open interest, delta values, and buyer/seller ratios, and return structured results in a list format for analysis.
def getData( self, symbol: str = "BANKNIFTY-I", exchange: str = "NSE", interval: str = "1m", rows: int = 200, segment: str = "FUTURE", date: dt.datetime.date = dt.datetime.now().date().strftime("%Y-%m-%d"), required_minutes: list = [], ) -> None: ...
def pack_search_attr_request(services: List[int], attributes: List[Union[Tuple[int, int], int]], max_response_size=0xffff, cstate=b'') -> bytes: # Need a UUID that we're going to find payload = pack_services(services) # Max response size payload += struct.pack('>H', max_response_size) payload += pac...
This function repeatedly sends search attribute requests over a socket, processes responses, and yields request-response pairs until the search completes. It packs requests with specified services/attributes, sends them, unpacks responses, extracts the 'cstate' for continuation, and breaks when 'cstate' is empty, enabl...
def do_search_attr_request_full(socket: socket.socket, services: List[int], attributes: List[Union[Tuple[int, int], int]], max_response_size=0xffff): cstate = b'' while True: #print("Packing") request = pack_search_attr_request(services=services, attrib...
def proj_line_seg(X, x0): # This function computes the projection of the point x0 onto the line segment between the points x1 and x2. x1 = X[:,0] x2 = X[:,1] alpha = float(np.dot(np.transpose(x1-x2), x0-x2))/(np.dot(np.transpose(x1-x2), x1-x2)) alpha = max(0,min(1,alpha)) y = alpha*x1 + (1-alpha)*...
The function computes the projection of a point $ x_0 $ onto a 5-cell (4-simplex) defined by the rows of $ X $. It first calculates an initial projection using linear algebra, then checks if the result lies within the 5-cell. If not, it evaluates distances from $ x_0 $ to all 5 vertices, 10 edges, 10 triangular faces, ...
def proj_5cell(X, x0): # This function computes the projection of the point x0 onto the 5-cell with corners specified with the rows of X. d = len(x0) XX = np.zeros((d,4)) XX[:,0] = X[:,0] - X[:,4] XX[:,1] = X[:,1] - X[:,4] XX[:,2] = X[:,2] - X[:,4] XX[:,3] = X[:,3] - X[:,4] P = np.dot(np.l...
def mnmf(K, X, H_init, W_init, t_initial, t_final, X_original_block_1,X_original_block_2,periodicity,tau_2,n,d,d0,w,tau_1a,periods_to_forecast, max_iter, X_test,lmin=0.001, lmax=10, lambda_no=20, c_lambda=1.2): # lambdas = np.geomspace(lmin, lmax, lambda_no) lambdas = np.linspace(lmin, lmax, lambda_no) l_no...
The function `experiments_amf` performs time series forecasting using a semi-NMF (Non-negative Matrix Factorization) approach with varying window sizes (`list_w`) and ranks (`list_rank`). It processes input data (`X_original`) by splitting it into training and test sets, applies periodicity-based data blocking, and ite...
def experiments_amf(X_original,periods_to_forecast,list_w,list_rank,periodicity,log_file): n = np.shape(X_original)[0] d = np.shape(X_original)[1] d0 = d-periods_to_forecast X_train = X_original[:, :d0] X_test = X_original[:, d0:d0+periods_to_forecast] X_original = X_original[~np.all(X_t...
def proj_line_seg(X, x0): # This function computes the projection of the point x0 onto the line segment between the points x1 and x2. x1 = X[:,0] x2 = X[:,1] alpha = float(np.dot(np.transpose(x1-x2), x0-x2))/(np.dot(np.transpose(x1-x2), x1-x2)) alpha = max(0,min(1,alpha)) y = alpha*x1 + (1-alpha)*...
This function projects the origin onto the convex hull of matrix X's rows using the GJK algorithm. It iteratively computes the projection via geometric methods (line, triangle, tetrahedron) for small active sets or optimization techniques (FISTA/Nesterov) for larger sets, adjusting the active set dynamically. The proje...
def gjk_proj(X,m,epsilon=1e-3,threshold=1e-8,niter=10000,verbose=False,method = 'fista', fixed_max_size=float("inf")): # Projects origin onto the convex hull of the rows of 'X' using GJK method with initial simplex size equal to 'm'. The algorithm is by Gilbert, Johnson and Keerthi in their paper 'A fast procedur...
def project_principal(X,r): # This function computes the rank 'r' pca estimate of columns of 'X'. U, s, V = np.linalg.svd(X) V = V[0:r,:] U = U[:,0:r] s = s[0:r] proj_X = np.dot(U, np.dot(np.diag(s), V)) return proj_X def wolfe_proj(X,epsilon=1e-6,threshold=1e-8,niter=10000,verbose=False): # ...
The function `palm_nmf_update` performs one iteration of the PALM algorithm for non-negative matrix factorization (NMF). It updates the matrices $ H $ (archetypes) and $ W $ (weights) by minimizing a cost function involving the data $ X $, using projection methods (e.g., Wolfe, GJK) to enforce constraints. Key steps in...
def palm_nmf_update(H, W, X, l, proj_method='wolfe', m=5, c1=1.2, c2=1.2, proj_low_dim = False, eps_step=1e-4, epsilon='None', threshold=1e-8, niter=10000, method = 'fista', weights_exact = False, fixed_max_size=float("inf")): # Performs an iteration of PALM algorithm. The inputs are as below. # 'H': Current matrix of...
def wolfe_proj(X,epsilon=1e-6,threshold=1e-8,niter=10000,verbose=False): # Projects origin onto the convex hull of the rows of 'X' using Wolfe method. The algorithm is by Wolfe in his paper 'Finding the nearest point in A polytope'. The input parameters are as below: # 'epsilon', 'threshold': Algorithm parameters dete...
The code computes the cost function for PALM iterations in non-negative matrix factorization (NMF). It calculates the Frobenius norm of the data matrix $ X $ minus the product $ WH $, then adds a regularization term $ \lambda \times \|\text{proj}(X - H_i)\|^2 $ for each archetype $ H_i $, where projections depend on th...
def costfun(W, H, X, l, proj_method='wolfe', m=3, epsilon='None',threshold=1e-8,niter=1000, method = 'fista', fixed_max_size=float("inf")): # Computes the value of the cost function minimized by PALM iterations. The inputs are as below: # 'W': Matrix of weights. # 'H': Matrix of Archetypes. # 'X': Data matrix. # 'l': ...
def project_principal(X,r): # This function computes the rank 'r' pca estimate of columns of 'X'. U, s, V = np.linalg.svd(X) V = V[0:r,:] U = U[:,0:r] s = s[0:r] proj_X = np.dot(U, np.dot(np.diag(s), V)) return proj_X def plot_data( X, col ): # This function plots the 'data points', (rows of ...
The function `palm_nmf` performs Non-negative Matrix Factorization (NMF) via PALM iterations to estimate archetypes (H) and weights (W) from data matrix X, minimizing a cost function with regularization parameter λ. It supports data-driven λ selection, projection methods, and convergence checks. If ground truth (H0) is...
def palm_nmf(X,r,l = None,lmax = 10, lmin = 0.001, lambda_no=20, c_lambda=1.2, proj_method='wolfe', m=5,H_init= None, W_init = None, maxiter=200, delta=1e-6, c1=1.1, c2=1.1 ,proj_low_dim = False, eps_step=1e-4, epsilon='None', threshold=1e-8, niter=10000, verbose=False, plotit=False, plotloss= True, ploterror= True, or...
def project_principal(X,r): # This function computes the rank 'r' pca estimate of columns of 'X'. U, s, V = np.linalg.svd(X) V = V[0:r,:] U = U[:,0:r] s = s[0:r] proj_X = np.dot(U, np.dot(np.diag(s), V)) return proj_X def wolfe_proj(X,epsilon=1e-6,threshold=1e-8,niter=10000,verbose=False): # ...
This function performs one iteration of the Accelerated PALM algorithm for Non-Negative Matrix Factorization (NMF). It updates factors H and W using gradient descent with projections (e.g., Wolfe, GJK, FISTA), computes intermediate variables (I, J, Y, Z), and applies acceleration via parameter t. The algorithm minimize...
def acc_palm_nmf_update(H, H_old, I, W, W_old, Y, t, t_old, X, l, proj_method='wolfe', m=5, c1=1.2, c2=1.2, proj_low_dim = False, eps_step=1e-4, epsilon='None', threshold=1e-8, niter=10000, method = 'fista', weights_exact = False, fixed_max_size=float("inf")): # Performs one iteration of the Accelerated PALM iteration...
def header(self, extends_from: str = "") -> str: if extends_from != "": extends_from = f"({extends_from})" return f"class {self.class_name}{extends_from}:\n" def generate_init(self) -> str: return self.init() def generate_setters_and_getters(self, tabs: int = 0) -> str: msg ...
The code generates a string representing a class entity by concatenating a header, initialization method, and setter/getter methods. It combines these components into a single string for output, likely used in code generation or template creation.
def generate_entity(self) -> str: msg = self.header() msg += self.generate_init() msg += self.generate_setters_and_getters(tabs=1) return msg
def handle_CreateAccount(tx, action_detail): # Sample # { # "actions": ["CreateAccount", { # "Transfer": { # "deposit": "200000001000000000000000000" # } # }, { # "AddKey": { # "access_key": { # ...
The function `handle_action` processes transaction actions by routing them to specific handler functions based on their type. It checks if the action is 'CreateAccount' and uses `handle_CreateAccount`, otherwise extracts the action type from a dictionary and calls corresponding handlers like `handle_FunctionCall`, `han...
def handle_action(tx, action): if type(action) == 'str' and action == 'CreateAccount': message_addon = handle_CreateAccount(tx, action) return message_addon action_type = list(action.keys())[0] action_detail = action[action_type] message_addon = '' if action_type == 'FunctionCall': ...
def create_linkhash(hash): short_hash = '\.\.\.' + hash[-6:] link = 'https://testnet.nearblocks.io/txns/{}'.format(hash) message = '[{}]({})'.format(short_hash, link) return message def extract_action(tx): return tx['actions'] def handle_action(tx, action): if type(action) == 'str' and action ==...
The code generates a formatted message for a transaction by creating a clickable hash link, extracting actions from the transaction, and appending processed details of each action with separators. It returns a structured string combining the hash and action-specific information.
def handle_transaction(tx): message = 'Hash: {}\n'.format(create_linkhash(tx['hash'])) actions = extract_action(tx) for action in actions: message = message + '`---------------`\n' message = message + handle_action(tx, action) return message
def croppedImg(): img = cv.imread("/home/atharvakango/Desktop/ProPy/Finger-Knuckle-based-Biometric-Identification-master/test_data_model/downloaded.jpg") x1=1600 y1=800 x2=2400 y2=1550 crop_img = img[y1:y2, x1:x2] cover = cv.resize(crop_img,(int(160),int(180))) cv.imwrite('/home/atharvak...
This code handles a user login request by retrieving a username and image URL from POST data, downloading the image, processing it with biometric analysis functions (cropping, PCA), and using a kNN classifier to verify the user. It returns verification success or error messages based on the classifier's output.
def loginPage(request): if request.method == 'POST': th=request.POST.get('username') print (th) flink=request.POST.get('filename') print(flink) urllib.request.urlretrieve(flink,"/home/atharvakango/Desktop/ProPy/Finger-Knuckle-based-Biometric-Identification-master/test_data_model/downloaded.jpg") croppedImg...
def croppedImg2(): img = cv.imread("/home/atharvakango/Desktop/ProPy/Finger-Knuckle-based-Biometric-Identification-master/Replica_Register/downloaded.jpg") x1=1600 y1=800 x2=2400 y2=1550 crop_img = img[y1:y2, x1:x2] cover = cv.resize(crop_img,(int(160),int(180))) cv.imwrite('/home/atharv...
The main task of the code is to generate five replicated versions of a processed image, saving them with filenames incorporating the provided username and an index (0–4). It reads an image, applies preprocessing steps (via called functions), and outputs identical copies to a specified directory.
def replicateImage(username): i=0 croppedImg2() negative2() pca2() img=cv.imread("/home/atharvakango/Desktop/ProPy/Finger-Knuckle-based-Biometric-Identification-master/Replica_Register/downloaded.jpg") for i in range(5): cv.imwrite('/home/atharvakango/Desktop/ProPy/Finger-Knuckle-based-B...
def get_auth0_bearer(): resp = requests.post( f"https://{auth0_domain}/oauth/token", json={ "client_id": client_id, "client_secret": client_secret, "audience": f"https://{auth0_domain}/api/v2/", "grant_type": "client_credentials", }, ) ...
The code clones a project, its campaign, and associated tasks from a source project using authentication tokens and user details. It retrieves the source project and campaign, clones the campaign with the user's ID, replicates the project with the new campaign ID, and duplicates tasks, all using command-line arguments ...
def main(): parser = argparse.ArgumentParser() parser.add_argument("source_project") parser.add_argument("email") args = parser.parse_args() auth0_bearer = get_auth0_bearer() rf_bearer = get_rf_bearer() auth0_user = get_user_by_email(args.email, auth0_bearer) source_project = get_project...
def getDatasetName(nbPerGenre, sliceSize): name = "{}".format(nbPerGenre) name += "_{}".format(sliceSize) return name def createDatasetFromSlices(nbPerGenre, genres, sliceSize, validationRatio, testRatio): data = [] for genre in genres: print("-> Adding {}...".format(genre)) # Get sl...
The function `getDataset` generates or retrieves a dataset based on specified parameters (e.g., number of slices per genre, slice size, validation/test ratios). It checks if precomputed files exist; if not, it creates the dataset using `createDatasetFromSlices`. Finally, it loads and returns the dataset in the specifie...
def getDataset(nbPerGenre, genres, sliceSize, validationRatio, testRatio, mode): print("[+] Dataset name: {}".format(getDatasetName(nbPerGenre, sliceSize))) if not os.path.isfile(datasetPath + "train_X_" + getDatasetName(nbPerGenre, sliceSize) + ".p"): print("[+] Creating dataset with {} slices of size ...
def enumerate_legal_moves(self): # catalogue legal moves legal_moves_arr = [] for x_dir in range(-1, 2): for y_dir in range(-1, 2): # assume the move is legal and traverse in every direction to find out legal = True # standing still ...
This function runs a game loop for testing purposes, displaying the board and legal moves, allowing user input to execute moves until no legal moves remain. It repeatedly enumerates available moves, prints them, updates the display, and processes user input to advance the game state.
def ugly_run_game(self): # run game with bad display (for testing graphics) while self.legal_moves_arr != []: self.enumerate_legal_moves() print(self.legal_moves_arr) self.display_board() key = input() move = self.move(key) ...
def enumerate_legal_moves(self): # catalogue legal moves legal_moves_arr = [] for x_dir in range(-1, 2): for y_dir in range(-1, 2): # assume the move is legal and traverse in every direction to find out legal = True # standing still ...
This code runs a game loop in a fullscreen terminal, displaying a numbered game board and player position. It handles input (manual or automated), updates the board based on moves, and continues until no legal moves remain. The game ends with a "Game Over" message showing the final score.
def run_game(self): with self.term.fullscreen(): # draw the numbers for row_number in range(len(self.game_board)): for col_number in range(len(self.game_board[row_number])): # read the number number = self.game_board[row_number][co...
def _mapping_to_substitution_list( mapping: Mapping, _prefix: Optional[Sequence[Substitution]] = None ) -> List[Substitution]: out: List[SomeSubstitutionsType] = [] for name, value in mapping.items(): name = normalize_to_list_of_substitutions(name) if _prefix: combined = lis...
(This code initializes a ROS2 node by configuring parameters, remappings, and generating a command to execute the node on a remote system. It normalizes input values, constructs the 'ros2 run' command with substitutions, and passes it to a superclass for remote execution, handling various parameter formats and ensuring...
def __init__( self, *, user: SomeSubstitutionsType, machine: SomeSubstitutionsType, executable: SomeSubstitutionsType, package: Optional[SomeSubstitutionsType] = None, name: Optional[SomeSubstitutionsType] = None, namespace: Optional[SomeSubstitutionsType] = None,...
def updateJobStatus(): for job, status in jobList.items(): if (status == JobStatus.RUNNING.value) or (status==JobStatus.PAUSED.value): container = client.containers.get(job) container.reload() if(container.attrs['State']['Status'] == "exited"): print("in ...
The code monitors and manages job execution by continuously checking job statuses, memcached state, and system resources. It categorizes jobs into running, paused, and succeeded states, adjusts job execution via main_logic based on memcached conditions, and ensures all seven jobs complete successfully before terminatin...
def launchJobs(): countNum = 0 while(True): print("==================================================== ",countNum+1) updateJobStatus() print("current job status: ",jobList) previous_cores = memcached_core memcachedState = monitorMemcached() running_jobs =...
def retrieve_big_scape_output(bigscape_out_dir: Path, cutoff_f='0.30', cutoff_c='0.70'): bgc_data = dict() for bgc_class in tqdm(BGC_classes): class_dir = bigscape_out_dir / Path(bgc_class) if not class_dir.exists(): continue bgc_data[bgc_class] ...
The main task of the code is to process BigScape output data by retrieving and formatting results with specified cutoffs, merging representative information from MIBiG and ABCHuMi databases, and exporting the structured data as a TSV file containing GCF/GCC IDs, associated BGCs, and database entries.
def main(): path_bigscape = os.path.join(sys.argv[1], 'network_files') cutoff_gcc_gcf = sys.argv[2] cutoff_gcc = sys.argv[3] output_tsv = sys.argv[4] dirs = sorted(x for x in os.listdir(path_bigscape) if os.path.isdir(os.path.join(path_bigscape, x))) dir_latest = dirs[-1] path_latest = os.p...
def make_frequency_dict(text): """ Calculate the frequency of each letter in the file. Args: text: str The input text string to deal with. """ frequency = {} for character in text: if character not in frequency: frequenc...
The main task of the code is to compress input data using Huffman encoding by generating frequency dictionaries, building a Huffman tree, encoding text, padding the encoded data, converting it to bytes, and storing both the compressed bytes and the reverse mapping for decompression.
def compress_data(self): """ Makes the necessary data package for file compression. """ text = FileOperator.prepare_file_compress(self, "rb") frequency = self.make_frequency_dict(text) self.make_heap(frequency) self.merge_nodes() self.make_codes() encoded_text ...
def generate_initial_population(dna, k, population_size): population = [] positions = [] # Track start positions for _ in range(population_size): start_positions = [randint(0, len(seq) - k) for seq in dna] motifs = [seq[pos:pos+k] for seq, pos in zip(dna, start_positions)] populatio...
This function implements a genetic algorithm to find optimal DNA motifs. It initializes a population, iterates through generations, selects individuals, applies crossover and mutation, and tracks the best motifs based on fitness scores. The goal is to evolve motifs that best match the input DNA sequence, minimizing a s...
def genetic_algorithm(dna, k, population_size, generations, score_threshold): population, positions = generate_initial_population(dna, k, population_size) best_score = 1e9 best_motifs, best_positions = None, None for _ in range(generations): selected, selected_positions = selection_with_posit...
def get_user_choice(menu): while True: print(tabulate(menu, headers="keys", tablefmt="rounded_outline")) choice = input("Choose one action to proceed: ").strip().upper() if choice in [item["Key"] for item in menu]: return choice print("Invalid action, try again.") def che...
The code defines a menu-driven interface for a Family Expenses Manager. It loops to display options (Check Status, Expenses, Family, Quit), processes user input via get_user_choice(), and delegates tasks to respective functions (check_status(), expenses(), family()). The main task is to manage family expense tracking a...
def main(): print("\n**Family Expenses Manager**") running = True while running: instructions = [ {"Key": "C", "Action": "Check Status"}, {"Key": "E", "Action": "Expenses"}, {"Key": "F", "Action": "Family"}, {"Key": "Q", "Action": "Quit"} ] action = get_u...
def prep_plot(self): ''' Take the input values and create a dataframe for plotting ''' # Create a table for plotting step_deltas = list(pd.Series(self.step_values).diff().fillna(pd.Series(self.step_values)).values) df_plot = pd.DataFrame( [self.step_values+[se...
This method generates a customizable waterfall chart using matplotlib, plotting bars and connecting lines to visualize cumulative changes. It accepts parameters for axes, figure size, labels, colors, and styling, prepares data via `prep_plot()`, and returns the configured Axes object with formatted limits, labels, and ...
def plot_waterfall(self, ax=None, figsize=(10, 5), title='', bar_labels=True, color_kwargs={}, bar_kwargs={}, line_kwargs={}): ''' Generate the waterfall chart and return the Axes object. Parameters: ax [Axes]: (optional) existing axes. Default is None. If Non...
def __remove_white_characters(self, string): # replace \n to , string = string.replace("\n", ",") # remove spaces, tabulations and 'returns' string = string.replace(" ", "") string = string.replace("\t", "") string = string.replace("\r", "") return string def __ca...
The code processes a list of host entries by splitting them into individual packets, validating IP addresses and subnet masks, generating IP ranges for subnets, and handling errors. It removes whitespace, checks mask validity, verifies IP formats, and either adds IPs or skips invalid entries based on user input. The re...
def resolve_hosts(self, hosts): hosts = self.__remove_white_characters(hosts) # divide HOST string to individual packets and process them for host_packet in hosts.split(","): try: # subnet mask if host_packet.__contains__("/"): ip =...
def _get_main_parameters(self) -> None: views_df = self.sql_executor.execute(PG_VIEWS_INFO_TEMPLATE.format(name=self.name, schema=self.schema)) matviews_df = self.sql_executor.execute(PG_MATVIEWS_INFO_TEMPLATE.format(name=self.name, schema=self.schema)) if not views_df.empty: main_pa...
The main task of the code is to create a `View` object by either retrieving a cached version (if available) or fetching necessary parameters, privileges, and metadata, then caching it before invalidating the cache to prevent reuse. It ensures efficient retrieval while avoiding stale data in subsequent calls.
def create(self) -> View: """Creates View object with all necessary information. :return: View object """ # None when called from user code, Dict when called within this class if self._cached_views is None: self._cached_views = {} if (self.schema, self.name)...
def get_exists(self): return (not self.exited) and (self.count > 0) def do_look(self): self.add_reply(self.look()) def status(self): s = ["we are %d people." % self.count] if len(self.commands.list) > 0: if isinstance(self.commands.list[0], CommandLook): s.append('we are looking around.') elif isins...
This code processes and executes commands from a list in sequence. It checks if the current command's trigger time has been reached, executes the corresponding action (e.g., moving, stopping, patrolling), and manages auto-repeating commands. If a command completes successfully and has auto-repeat enabled, it is re-adde...
def tick(self): # we don't handle fight here, fights are handled by somethg else. # but still, there is a command added to the list, that will prevent other commands to be added if not self.get_exists(): self.commands.reset() return if len(self.commands.list) > 0: command = self.commands.list[0] if c...
def translateBackTicker(transed_yfinance_ticker): translation = transed_yfinance_ticker translation = translation.replace("I_","^") translation = translation.replace("EQ_","=") translation = translation.replace("D_","-") translation = translation.replace("P_",".") return translation def dropTabl...
The function updates financial data tables in a SQLite database by dropping existing tables (excluding specified ones) and downloading new data between given start and end dates. It queries all tables, filters out predefined tables, translates table names, drops the translated names, then downloads ticker information f...
def datesUpdated(s_date, e_date): global cur, con res = cur.execute("""SELECT name FROM sqlite_master WHERE type='table';""") ticker_names = [] ticker_names_translated = [] for x in res.fetchall(): x = list(x) if x[0] != 'CUSTOMER' and x[0] != 'ORDER_HISTORY' and x[0] != 'STRATEGIES...
def resetCustomerCash(): global cur, con cur.execute("UPDATE CUSTOMER SET current_cash = starting_cash;") con.commit() def clearOrderTable(): global cur, con cur.execute("DELETE FROM ORDER_HISTORY;") con.commit() def retrieveStrategies(): global cur, con res = cur.execute("SELECT * FROM ...
The code simulates stock trading strategies for customers by retrieving their strategies, determining purchase dates based on predefined rules (e.g., daily, red/green days, 1% drops), compiling these dates, sorting them, and executing trades accordingly. It resets customer cash, clears orders, and processes each custom...
def executeSimulation(): resetCustomerCash() clearOrderTable() strats = retrieveStrategies() customers = list(getCustomers()) for customer in customers: full_date_table = [] for strat in strats: if strat[0] == customer[0]: if strat[1] == '1': #Buy Ever...
def markdown_ast_to_solr_fields(fields, ast, prefix=''): r = fields.copy() if ast['type'] == 'Heading': level = min(ast['level'], 6) _add_field(r, f'{prefix}heading', '#' * level + ' ' + _get_markdown_text(ast)) _add_field(r, f'{prefix}heading_{level}', _get_markdown_text(ast)) elif ...
This function converts markdown content into a dictionary of Solr fields by parsing the markdown into an AST, mapping nodes to Solr fields with a customizable prefix. It specifically extracts operation notes, adds the full markdown as 'about' if the heading contains 'about', and includes the markdown as 'todo' if empha...
def markdown_to_solr_fields(markdown, prefix=''): ast = json.loads(mistletoe.markdown(markdown, ASTRenderer)) r = {} r = markdown_ast_to_solr_fields(r, ast, prefix=prefix) operation_note = _retrieve_markdown_content( ast, re.compile(r'Operation\s*Note', re.IGNORECASE) ) if opera...
def _meme_to_solr_document(meme): doc = {} if 'current' in meme: doc['lc_cell_meme__current'] = meme['current'] if 'next' in meme: doc['lc_cell_meme__next'] = meme['next'] if 'previous' in meme: doc['lc_cell_meme__previous'] = meme['previous'] if 'execution_end_time' in meme:...
The function converts a Jupyter notebook cell into a Solr document by extracting metadata, content, and outputs. It constructs a dictionary with fields like cell type, execution count, source code/markdown, and contextual meme relationships (previous/next in notebook/section). Outputs are aggregated, and text fields ar...
def cell_to_solr_document(notebook_id, path, cell, cell_index, cells=None, notebook_attr=None): doc = { 'id': notebook_id + f'_{cell_index}', 'index': cell_index, 'notebook_id': notebook_id, 'notebook_filename': path, } if notebook_attr is not None: doc.update([(f'not...
def notebook_to_notebook_id(path, notebook_data): _, filename = os.path.split(path) if 'metadata' not in notebook_data: return f'unknown_undefined_{filename}' metadata = notebook_data['metadata'] meme = 'undefined' if 'lc_notebook_meme' not in metadata or 'current' not in metadata['lc_notebook_m...
The function converts a Jupyter notebook into a structured Solr document by extracting metadata, processing cells for content/output, aggregating execution timestamps, and formatting text fields. It generates a document with unique ID, filename, cell-derived content, meme metadata, and computed fields like execution en...
def notebook_to_solr_document(path, notebook_data, attr=None, user_pattern=None): notebook_id = notebook_to_notebook_id(path, notebook_data) _, filename = os.path.split(path) doc = { 'id': notebook_id, 'filename': filename, } if attr is not None: doc.update(attr) memes = ...
def _get_notebook_attr(notebook_data, base_attr=None): attr = {} if base_attr is not None: attr.update([(k, v) for k, v in base_attr.items() if v is not None and len(v) > 0]) if 'metadata' in notebook_data and 'lc_notebook_meme' in notebook_data['metadata']: lc_notebook_meme = notebook_data[...
This function converts a Jupyter notebook (from given data) into structured Solr-compatible documents. It generates metadata for both the entire notebook and individual cells, returning a dictionary with 'jupyter-notebook' (notebook-level metadata) and 'jupyter-cell' (per-cell metadata) entries. The process involves ex...
def ipynb_to_documents(path, notebook_data, attr=None, user_pattern=None): notebook_attr = _get_notebook_attr(notebook_data, base_attr=attr) notebook_docs = notebook_to_solr_document(path, notebook_data, attr=notebook_attr, user_pattern=user_pattern) notebook_id = notebook_to_notebook_id(path, notebook_data...
def create_cluster_list(geodata: pd.DataFrame) -> (np.ndarray, pd.DataFrame, pd.DataFrame): # Read in the full output file from polygon clustering pand_data = geodata # Split df into bulding that based on polygon are within or without a cluster no_cluster = pand_data[pand_data["cluster"] == -1] no...
This function applies DBSCAN clustering to geospatial data, assigns cluster labels, calculates average neighbor scores for clustered points, and merges results with non-clustered data. It processes input DataFrames, merges cluster information, executes clustering logic, separates clustered and non-clustered entries, co...
def db_scan_clusters(output: pd.DataFrame, geodata: pd.DataFrame, eps: int, minpts: int) -> pd.DataFrame: """ This function performs the DBSCAN Algorithm, for each cluster individually. It then also counts the neighbours and calculates the average neighbour score """ output = output[[0, 'cluster']] ...
def read_geodata() -> pd.DataFrame: # Read in geodata PROJECT_PATH = pathlib.Path(os.path.abspath(__file__)).parent.parent geodata_path = os.path.join(PROJECT_PATH, "outputs", "geodata_all_scenarios.csv") geodata = pd.read_csv(geodata_path) return geodata def add_x_y_dbscan(geodata: pd.DataFrame) ...
The main task of the code is to process geospatial data by clustering points using DBSCAN, compute risk-related metrics, and generate GeoJSON files for visualization. It reads geodata, extracts coordinates, assigns risk scores, clusters points, calculates neighbor relationships, and exports polygon/point data in Tablea...
def run_script(eps: int, minpts: int): # First read in the geodata, stored in a CSV file in the 'outputs' directory geodata = read_geodata() # Extract an X and Y coordinate from the 'Point' column, in the Geodata DataFrame and add these as two seperate cols geodata = add_x_y_dbscan(geodata) # Gen...
def read_raw_json(): data = [] for drive in detect_drives(): file = read_drive(drive) data.append(read_file(os.path.join(drive, file), KEY)) return data def detect_drives(): os.chdir('/Volumes') List = os.listdir() i = 0 while i < len(List): if (List[i] == 'Macintosh ...
The main task of the code is to modify specific card attributes for two players in a JSON structure, print the updated player data, and write the modified player data to separate storage drives. It retrieves player data, updates image/type fields conditionally, handles drive detection, and returns a JSON success/failur...
def transfer_player(): try: player1 = read_raw_json()[0] player2 = read_raw_json()[1] # commander1 = player1["cards"][0]; # commander2 = player2["cards"][0]; # card_to_roster2 = player2["cards"].pop() # player2["cards"].append(commander1) # print(play...
def __inputBenchFile(self): inputFile = "" while True: inputFile = input("Enter bench file> ") if not os.path.isfile(f"bench/{inputFile}.bench"): print(f'File {inputFile} not found') continue break inputFile = open(f"bench/{i...
The method loads a bench file based on user input (either standard or C432 format), sorts the file data, processes the sorted entries, creates a deep copy of nodes for wire processing, and initiates wire-related processing. It handles input selection, data organization, and preparation for subsequent operations like wi...
def __loadBenchFile(self): if self.userOption != "3": self.__inputBenchFile() else: self.__inputC432BenchFile() benchFile = self.__sortBenchFile() self.__processBenchFile(benchFile) self.noWireNodeList = deepcopy(self.nodes) self.__processWire()
def __exhaustInputs(self): TV = [] startingTV = "" for i in range(self.numInputs): startingTV += "0" binStr = startingTV TV.append(startingTV) for i in range(2**self.numInputs-1): binInt = self.__bin_to_dec(binStr) + 1 binStr = self._...
The code simulates fault detection in a circuit using Monte Carlo methods. It iterates through test vectors (TV) derived from input constraints, applies each fault in the fault list, updates circuit node values, simulates the circuit, checks for faults, and resets nodes. The goal is to verify if faults are detectable u...
def __simulateMonteCarlo(self, originalKnownList, originalUnknownList): print("Simulating all faults in fault list...\n") TV = [] # determine TV to be used if self.numInputs <= 10: TV = self.__exhaustInputs() else: TV = self.__random1000TV() # optional: r...
def __exhaustInputs(self): TV = [] startingTV = "" for i in range(self.numInputs): startingTV += "0" binStr = startingTV TV.append(startingTV) for i in range(2**self.numInputs-1): binInt = self.__bin_to_dec(binStr) + 1 binStr = self._...
This code simulates fault effects in a digital circuit using Monte Carlo methods. It generates test vectors (TV) based on input count, applies each TV to the circuit, activates individual faults, runs simulations, and checks fault impacts. The process iterates through all faults and TV combinations to analyze circuit b...
def __simulateMonteCarlo_PRPG(self, originalKnownList, originalUnknownList): print("Simulating all faults in fault list...\n") TV = [] # determine TV to be used if self.numInputs <= 10: TV = self.__exhaustInputs() else: TV = self.__LFSR_userAmount() # opt...
def NOT(self, node, inputs, NodeList, option="-"): if option == "c": # control ipc0 = NodeList[inputs[0].split("-")[1]].c0 # c0(node) ipc1 = NodeList[inputs[0].split("-")[1]].c1 # c1(node) # flip c0 and c1 values for output node and +1 NodeList[node].c0 = s...
This method dispatches logical operations by calling specific handler functions (e.g., NOT, AND, XOR) based on the 'op' parameter. It processes nodes and inputs for circuit operations, with a special case for "WIRE" conversion when option ≠ "c". Unrecognized operations trigger an error message.
def _operation(self, node, inputs, NodeList, op="-", option="-"): if op == "NOT": self.NOT(node, inputs, NodeList, option) elif op == "BUFF": self.BUFF(node, inputs, NodeList, option) elif op == "AND": self.AND(node, inputs, NodeList, option) elif op =...
def __loadBenchFile(self): if self.userOption != "3": self.__inputBenchFile() else: self.__inputC432BenchFile() benchFile = self.__sortBenchFile() self.__processBenchFile(benchFile) self.noWireNodeList = deepcopy(self.nodes) self.__processWire() d...
This function handles user interaction for fault simulation in a digital circuit. It loads a bench file, displays the netlist, prompts for a test vector, and lets the user choose simulation modes: normal simulation, single fault analysis, full fault list simulation, or generating test vectors to cover faults.
def __userOption1_FaultSim(self): # A1: ask user for bench file print("Available bench files:") print(" " + str(self.benchFiles)[1:][:-1]) print() # load bench file and update known/unknown lists self.__loadBenchFile() self.__appendKnownUnknow...
def __loadBenchFile(self): if self.userOption != "3": self.__inputBenchFile() else: self.__inputC432BenchFile() benchFile = self.__sortBenchFile() self.__processBenchFile(benchFile) self.noWireNodeList = deepcopy(self.nodes) self.__processWire() d...
This method processes a bench file by loading circuit data, updating node states, generating fault lists, simulating control signals, performing Monte Carlo analysis, and displaying results including controllability and MC statistics for circuit evaluation.
def __userOption2_ControlandMC(self): print("Available bench files:") print(" " + str(self.benchFiles)[1:][:-1]) print() # load bench self.__loadBenchFile() self.__appendKnownUnknownList(self.nodes, self.knownList, self.unknownList, self.inputTV) ...
def __loadBenchFile(self): if self.userOption != "3": self.__inputBenchFile() else: self.__inputC432BenchFile() benchFile = self.__sortBenchFile() self.__processBenchFile(benchFile) self.noWireNodeList = deepcopy(self.nodes) self.__processWire() d...
This function performs PRPG-based fault simulation by loading a benchmark file, processing node lists, updating input values, generating fault lists, and simulating control with user-selected LFSR tap configurations. It runs Monte Carlo simulations, tracks fault detection metrics (detected count, level, c0/c1, n0/n1 ra...
def __userOption3_PRPG(self): # option 4: PRPG # load and process bench file self.__loadBenchFile() # 9V algebra starts here, comment out to remove user input # noWireKnownList, noWireUnknownList, noWireInputTV = [], [], deepcopy(self.inputTV) # for control self.__appen...
def __userOptionMain(self): self.userOption = input("\nSelect an option:\n 1: Fault Simulation\n 2: Controllability & Monte Carlo\n 3: PRPG on bench c432.bench\n > ") while self.userOption not in self.options: print("\nInvalid option selected") self.userOption = input("\nSelect ...
The code's main task is to execute user-selected simulation tasks: fault analysis (single/full faults, top 5 test vectors), controllability/Monte Carlo analysis, or PRPG operations. It processes user input via `__userOptionMain()`, performs corresponding simulations, and logs results to `.pkl` and CSV files via `__logR...
def simulate(self): # while userChoice != "q" self.__userOptionMain() # Fault Simulation (single fault, full fault list, best 5 TV) if self.userOption == "1": self.__userOption1_FaultSim() # Controllability & Monte Carlo elif self.userOption == "2": ...
def initialize(self): t = [0,0] self.old[t[0]:t[0]+self.rowPatch,t[1]:t[1]+self.colPatch] = self.pattern[0:self.rowPatch,0:self.colPatch] self.new= deepcopy(self.old) self.change_masking(t) self.change_seams_value(t,t,np.ones((self.rowPatch,self.colPatch))) def minCut_calculate(s...
The function applies random patching to a grid by iterating over randomly spaced coordinates, calculating min-cut values at each patch location, and placing additional patches through a loop. It returns a processed grid section after evaluating these patches.
def patching_func(self): self.initialize() x = random.randint( int(1*self.rowPatch/3), int(2*self.rowPatch/3)) y = 0 while(y < self.realCols): while(x < self.realRows): self.minCut_calculate([x,y]) x += random.randint( int(1*self.rowPatch/3), i...
def _write_words(self, port_name, num_words, value): fn = getattr(self.lib, 'set_' + port_name) fn.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint32] for i in range(num_words): word = ctypes.c_uint32(value >> (i * 32)) fn( self.model, i, word ) self._p...
This function writes a value to a specified hardware port by determining the port's width and delegating the write operation to appropriate helper methods (_write_words, _write_64, or _write_32) based on the width. It first validates the port's existence, then handles widths >64, 32-64, and ≤32 differently to ensure co...
def _write(self, port_name, value): port_width = None for name, width in self.inputs: if port_name == name: port_width = width if port_width is None: raise ValueError('cannot write port "%s" because it does not exist (or it is an output)' % port_name) ...
def detect_joint_pos(self,image): # a = self.pixel2meter(image) a = 0.04 # Obtain the centre of each coloured blob center = a * self.detect_yellow(image) circle1Pos1 = a * self.detect_blue(image) circle2Pos1 = a * self.detect_green(image) circle3Pos1 = a * self.detect_red(image) target...
The code processes incoming image data by converting it to an OpenCV image, detects joint positions, calculates target coordinates relative to a yellow object using pixel-to-meter conversion, and publishes the image along with joint and target position data as ROS messages.
def callback1(self,data): # Recieve the image try: self.cv_image1 = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) # Uncomment if you want to save the image #cv2.imwrite('image_copy.png', cv_image) cv2.imshow('window', self.cv_image1) cv2.wa...
def detect_joint_pos2(self,image): # a = self.pixel2meter(image) a = 0.04 # Obtain the centre of each coloured blob center = a * self.detect_yellow(image) circle1Pos1 = a * self.detect_blue(image) circle2Pos1 = a * self.detect_green(image) circle3Pos1 = a * self.detect_red(image) targe...
The main task of this code is to process a received image by converting it from a ROS message to an OpenCV image, detect joint and target positions, calculate their relative positions in meters, and publish the processed image, joint coordinates, and target position data via ROS topics.
def callback2(self,data): # Recieve the image try: self.cv_image2 = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) # Uncomment if you want to save the image #cv2.imwrite('image_copy.png', cv_image) #im2=cv2.imshow('window2', self.cv_image2) cv2.waitKe...
def inrange(vk,vt): vkpos=vk.get_curr_pos() vtpos=vt.get_curr_pos() dist=mobility_model(vkpos[0],vtpos[0],vkpos[1],vtpos[1],vkpos[2],vtpos[2]) if dist<vt.radius: return 1 return 0 def isrelay(v_n,v_m,candidate_rn): print("CCCCCCC : ",candidate_rn) print("CCCCCCC : ",v_n.id) for e...
This function calculates the direct computation time between two vehicles (v_n and v_m) by considering their communication range (alpha_n_m), relay dependency (beta_n_m), data size (d_off_n_m), transmission rate (r_n_m), computational cost (c_off_m), and processing speed (f_off_m). It returns the total time required fo...
def t_direct(v_n,v_m,t_n,candidate_relay,vehicles): alpha_n_m=inrange(v_n,v_m) beta_n_m=isrelay(v_n,v_m,candidate_relay) d_off_n_m=t_n[0] r_n_m=get_transmission_rate(v_n,v_m,vehicles) c_off_m=t_n[1] f_off_m=v_m.computation_cycles_per_sec t_direct_n_m=alpha_n_m*(1-beta_n_m)*((d_off_n_m/r_n_m...
def inrange(vk,vt): vkpos=vk.get_curr_pos() vtpos=vt.get_curr_pos() dist=mobility_model(vkpos[0],vtpos[0],vkpos[1],vtpos[1],vkpos[2],vtpos[2]) if dist<vt.radius: return 1 return 0 def isrelay(v_n,v_m,candidate_rn): print("CCCCCCC : ",candidate_rn) print("CCCCCCC : ",v_n.id) for e...
This function calculates the minimum latency for data transmission from vehicle v_n to v_m via relay candidates in v_prime_list. It evaluates each relay candidate's performance by considering transmission rates, distances, computing capacities, and relay eligibility, then returns the lowest latency path.
def t_relay(v_n,v_m,v_prime_list,t_n,candidate_relay,vehicles): alpha_n_m=inrange(v_n,v_m) beta_n_m=isrelay(v_n,v_m,candidate_relay) d_off_n_m=t_n[0] r_n_m=get_transmission_rate(v_n,v_m,vehicles) latency_list=[] for v_p in v_prime_list: alpha_m_p=inrange(v_m,v_p) beta_m_p=isrela...