dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def three_from_four_rdm(four_rdm, nelec): # Last two indices refer to middle two second quantized operators in the 4RDM three_rdm = np.einsum('ikjlmnpp->ijklmn', four_rdm) three_rdm /= (np.sum(nelec)-3) return three_rdm def two_from_three_rdm(three_rdm, nelec): # Last two indices refer to middle two...
The function converts a spin-free reduced density matrix (rdm) of arbitrary rank into a spin-free, ordered format by recursively generating lower-rank RDMs (using helper functions like `three_from_four_rdm`) and applying reordering operations (`unreorder_rdm12`, etc.) based on the original rank. It returns a list of or...
def spinfree_nord_to_pose(rdm, nelec): rank = len(rdm.shape)/2 rdms = [rdm] if rank>3: rdms.insert(0, three_from_four_rdm(rdms[0], nelec)) if rank>2: rdms.insert(0, two_from_three_rdm(rdms[0], nelec)) if rank>1: rdms.insert(0, one_from_two_rdm(rdms[0], nelec)) if rank==2...
def load_spin_resolved_rdm(fname, rank): archive = h5py.File(fname, 'r')['archive'] nspinorb = int(archive['propagator']['nsite'][()])*2 nelec = int(archive['propagator']['nelec'][()]) nord_rdm = np.zeros((nspinorb,)*(rank*2)) data = archive['rdms'][str(rank)*2+'00'] assert rank*2 == data['indic...
This function loads a spin-resolved 1-RDM from an HDF5 file, restores its permutation symmetries, converts it to a spin-free representation, and returns the resulting spin-free 1-RDM.
def load_spinfree_1rdm_from_m7(h5_fname): rdm1 = load_spin_resolved_rdm(h5_fname, 1) rdm1_restored = restore_perm_syms(rdm1, True, False) rdm1_sf = spin_resolved_to_spinfree(rdm1_restored, True) return rdm1_sf
def load_spin_resolved_rdm(fname, rank): archive = h5py.File(fname, 'r')['archive'] nspinorb = int(archive['propagator']['nsite'][()])*2 nelec = int(archive['propagator']['nelec'][()]) nord_rdm = np.zeros((nspinorb,)*(rank*2)) data = archive['rdms'][str(rank)*2+'00'] assert rank*2 == data['indic...
This function loads spin-free 1- and 2-RDMs from an HDF5 file. It first retrieves the number of electrons (nelec) if not provided, then loads the spin-resolved 2-RDM. After restoring permutation symmetries and converting to spin-free form, it derives the 1-RDM from the 2-RDM. Finally, it reorders and returns the spin-f...
def load_spinfree_1_2rdm_from_m7(h5_fname, nelec=None): if nelec is None: archive = h5py.File(fname, 'r')['archive'] nelec = int(archive['propagator']['nelec'][()]) rdm2 = load_spin_resolved_rdm(h5_fname, 2) rdm2_restored = restore_perm_syms(rdm2, True, False) rdm2_sf = spin_resolved_to_...
def make_all_perms(rank): all_perms = [] for order in permutations(range(rank)): all_perms.append([order, parity(order)]) return all_perms def spins(spinorbs, nspat): return tuple(spin(i, nspat) for i in spinorbs) def get_expval(creinds, desinds): return pyscf_casci_spin_resolved_element(casci, ...
The function constructs a spin-resolved reduced density matrix (RDM) of specified rank, incorporating spin conservation and time-reversal symmetry. It iterates over creation/destruction index combinations, applies symmetry constraints, and populates the RDM tensor using permutations and symmetry operations (e.g., Krame...
def make_spin_resolved_rdm(norb, rank, get_expval, spin_major, time_reversal_sym, tol=1e-12): sm = norb if spin_major else None nspinorb = norb*2 rdm = np.zeros((nspinorb,)*(rank*2)) perms = make_all_perms(rank) for icre, creinds in enumerate(combinations(range(nspinorb), rank)): crespins = ...
def is_wumpus_at(self, coords: Coords) -> bool: return coords == self.wumpus_location def is_pit_at(self, coords: Coords) -> bool: return coords in self.pit_locations def is_stench(self) -> bool: return self.is_wumpus_adjacent(self.agent.location) def is_breeze(self) -> bool: return self...
The code simulates an agent's action in a Wumpus world, updating the environment and agent state based on the action (e.g., moving, turning, grabbing, climbing, shooting). It returns a new environment state and percept (sensory input + reward), handling death, gold collection, orientation changes, and wumpus interactio...
def apply_action(self, action: Action) -> Tuple[Self, Percept]: if self.terminated: return ( self, Percept(False, False, False, False, False, True, 0) ) if action == Action.Forward: new_agent = self.agent.forward(self.grid_widt...
def assignCentroids(self, class_names, centroids): if not centroids: return {} assignedCentroids = {} for i in range(0, len(centroids)): assignedCentroids[class_names[i]] = str(centroids[i]) return assignedCentroids def annotate(self, filename, annotation_f, centr...
This function processes an image using a CNN model (YOLACT) to detect objects, generating class labels, scores, bounding boxes, and masks. It assigns centroids to detected classes, labels the image, and either annotates it with provided annotations or updates internal tracking information based on the detection results...
def applyYolactImage(self, img, annotation, annotation_f=None, filename=None, annotations=None): preds, frame = self.cnn.process_batch(img) classes, class_names, scores, boxes, masks, centroids = self.cnn.raw_inference(img, preds=preds, frame=frame) c = self.assignCentroids(class_names, centroid...
def print_the_field(fields): output = find_the_output(fields) lines = [" ".join(output[6:]), " ".join(output[3:6]), " ".join(output [:3])] print ("\n".join(lines)) def modify_the_field(fields, player): move = choose_a_field(fields, player) fields[move[0]]["figure"]=move[1] fields[move[0]]["ac...
The main task of the code is to handle a player's turn in a game by printing the current round and active player, displaying the game field, modifying the field based on the player's move, updating the visual representation, and returning the modified field state for the next steps of the game.
def make_move (round, player_whose_turn, fields, second_player): print (f"Round {round+1}. {player_whose_turn}'s turn. ") print_the_field(fields) fields = modify_the_field(fields, player_whose_turn) plot_the_field(fields, player_whose_turn, second_player) return fields
def make_fields (): fields = { "1": {"coordinates": (1,1), "access": True, "figure": "1"}, "2": {"coordinates": (3,1), "access": True, "figure": "2"}, "3": {"coordinates": (5,1), "access": True, "figure": "3"}, "4": {"coordinates": (1,3), "access": True, "figure": "4"...
The code runs a tic-tac-toe game where players choose X/O, take turns making moves, check for wins/draws, and repeat rounds based on user input. It initializes game settings, alternates moves, validates wins, and manages replay options.
def game_main(): figure = Choice(["x", "o"], "Do you want to be X or O? (type x or o) ", ["X", "o"]) another_round = Choice (["y", "n"], "Do you want another round? (type y for yes, n for no) ", [True, False]) game=True while game: first_player = figure.players_choice() second_pl...
def get_entity(elt: Element, att_tag:str = 'type') -> Entity: text = get_w_content(elt) tag = elt.get(att_tag) if att_tag in elt.attrib else "" tokens = get_tokens_from_tei(elt) #TODO fix this, issue with pickle etree element parent = ''#elt.getparent() start = None end = None id = elt...
The main task of the code is to extract nested entities from TEI XML elements by iterating through specific `<rs>` tags with `@type='ene'` and `@subtype='ene'`, creating `Entity` objects with attributes like `toponyms_candidate`, `named_entities`, and `level`, while handling potential issues with XML element serializat...
def get_nested_entities_from_tei(elt: Element) -> List[Entity]: nestedEntities = [] for e in elt.findall(".//rs[@type='ene']/rs[@subtype='ene']"): entity = get_entity(e) entity.toponyms_candidate = get_toponyms_from_tei(e) #TODO fix this, issue with pickle etree element entity.ch...
def getPathScales(self, path, w, h, minOverlap): scales = torch.zeros_like(path[:, 0]) theta = math.atan2(h, w) C = 1 - minOverlap if h < w: scales[0] = asin(sin(theta) / (1 - C)) - theta else: scales[0] = theta - acos(theta / (1 - C)) scales[1] =...
The code initializes a class to process a path by computing scaling factors (`scales`) based on dimensions and overlap, adjusting these scales using normalized standard deviation of the path relative to a fitted quadratic path (`agPath`), and recalculating a parameter `T` dependent on the updated scales. The main task ...
def __init__(self, path, w, h, minOverlap): self.origPath = path self.path = path.clone() self.sigLen = path.shape[1] self.scales = self.getPathScales(self.path, w, h, minOverlap) self.T = self.getMaxT(w, h, self.scales, minOverlap) agPath = self.fitPathQP() std =...
def getFlowCoeffs(self, flow): return torch.tensordot(flow, self.dctBases, ([-2, -1], [0, 1])) def getReverseFlowCoeffs(self, coeffs): UX, UY = self.getUniformGrid() flow = self.cvtCoeffs2Flow(coeffs) X = UX + flow[0] Y = UY + flow[1] revCoeffs = torch.zeros_like(coeffs)...
The main task of the code is to generate the reverse of a given flow by first extracting its coefficients, computing their inverse counterparts, and then converting these inverse coefficients back into a flow structure. This process effectively transforms the original flow into its reversed version through coefficient ...
def getReverseFlow(self, flow): coeffs = self.getFlowCoeffs(flow) invCoeffs = self.getReverseFlowCoeffs(coeffs) revFlow = self.cvtCoeffs2Flow(invCoeffs) return revFlow
def douglas_peucker_distances(points, threshold=0.00001): distances = [None] * len(points) distances[0] = threshold * (zoom_factor ** num_levels) distances[-1] = distances[0] if(len(points) < 3): return distances stack = [(0, len(points) - 1)] while stack: a, b = stack.pop() ...
The function `encode_pairs` encodes a list of latitude/longitude points into a compressed string format, using the Douglas-Peucker algorithm to simplify the points based on a threshold. It generates two outputs: (1) an encoded string representing the simplified points and (2) an encoded string indicating the maximum zo...
def encode_pairs(points, threshold=0.00001): """Encode a set of lat/long points. ``points`` A list of lat/long points ((lat, long), ...) Note carefully that the order is latitude, longitude return - An encoded string representing points within our error ``threshold``, ...
def print_usage(): print("USAGE:") print("\thexdump [options] <filename>") print("OPTIONS:") for opt in options: if opt["short_flag"] != None and opt["only_flag"] == False: left_str = "[-{:s} | --{:s}=] ARG".format( opt["short_flag"], opt["long_flag"]) elif opt["short_flag"] != None and opt["only_flag"] ...
This code parses command-line arguments into key-value pairs, handling both short (-) and long (--) options. It processes arguments by extracting keys and values, updates configuration options, and prints verbose output if enabled. Non-option arguments are treated as "path" values. Finally, it initiates a hex dump proc...
def main(): if len(os.sys.argv) <= 1: print_usage() else: # TODO: Implement key-value pairs with spaces in between. for arg in os.sys.argv[1:]: if arg[0:2] == '--': key_end_idx = arg.find("=") if key_end_idx != -1: key = arg[2:key_end_idx] val = arg[key_end_idx + 1 :] else: key = a...
def get_hull_shape(shape): """ It returns the smallest envellope of points that englobe the shape. """ points = [ [point[0], 400-point[1]] for path in shape for point in path ] points = np.array(points) hull = ConvexHull(points) envelop_points = hull.points[hull.vertices] return envelop_...
The code calculates the roundness of a shape by comparing its area to the area of a circle with the same perimeter, returning the ratio as a measure of how closely the shape resembles a perfect circle.
def get_roundness(shape): """ It calculates the roundness of the shape. Roundness is a measure of how closely the shape of an object approaches that of a mathematically perfect circle. """ from math import pi hull_points = get_hull_shape(shape) length = get_length(hull_points) area = get...
def all_creation_wrapper(creator): # using dependence injection because I need to avoid circular imports # this requires a MarketingFirmCreator be passed in firm = creator.choose_manager_type() firm.create_sweepstakes() contestants = select_user_type() firm.manager.insert_sweepstakes(inject_user...
This function provides a command-line interface for testing marketing firm and sweepstake creation/management. It uses dependency injection to avoid circular imports, offering options to create new firms, add sweepstakes to existing firms, modify active sweepstakes, or exit. Input validation ensures numeric choices bet...
def bare_bones_front_end(creator, firm=None): # using dependence injection because I need to avoid circular imports # this requires a MarketingFirmCreator be passed in print("This Menu is primarily for testing purposes") print("While it is use able for all functionality") print("it is recommended yo...
def getCurrentIndex(self): return self.code.text.index("insert") def deleteLine(self, index): line, char = self.getIndexCoordinates(index) deletedText = self.getFullLineText(index) self.code.text.delete("%s.0" % line, "%s.end" % line) return deletedText def getLineIndents(self, l...
This function handles the Shift+Tab key event by deleting the current line, adjusting its indentation by removing leading spaces or two characters if present, then reinserting the modified line. It prevents further processing by returning 'break'.
def onShiftTabPressed(self, event): index = self.getCurrentIndex() deletedLine = self.deleteLine(index) spaces = self.getLineIndents(deletedLine) if spaces >= 2: deletedLine = deletedLine[2:] else: deletedLine = deletedLine.lstrip(" ") self.code.te...
def getIndexCoordinates(self, index): return index.split(".") def getCurrentIndex(self): return self.code.text.index("insert") def getPreviousLineIndieces(self): start, end = self.getCurrentLineIndieces() return self.jumpIndex(start, -1, 0) def getFullLineText(self, index): line,...
The function retrieves the text of the previous line in a document by first determining the current line and character position, obtaining the index of the preceding line, and then fetching the full text of that line.
def getPreviousLineText(self): currentLine, currentChar = self.getIndexCoordinates(self.getCurrentIndex()) prev = self.getPreviousLineIndieces() return self.getFullLineText(prev)
def getCurrentLineIndieces(self): lineStartIndex = self.code.text.index("insert linestart") lineEndIndex = self.code.text.index("insert lineend") return lineStartIndex, lineEndIndex def getLineTextBetween(self, start, end): return self.code.text.get(start, end) def processLine(self, line...
This method handles text changes in a code editor by checking key presses (like Backspace, Delete, Return, etc.), determining the current line's type and syntax, and adjusting indentation when a new line is created. It ensures proper syntax highlighting and maintains consistent indentation by copying the previous line'...
def onCodeChanged(self, args): #print(args) ## allow cahracters and some specific control keys to start the parsign of teh line (to color text and stuff) if args.keysym == "BackSpace" or args.keysym == "Delete" or args.keysym == "Return" or args.keysym == "Tab" or args.keysym == "Control_L" or a...
def docker_reset(self, container): container.run(["rm", "-rf"] + [ os.path.join(self.config.mountpoints.remote, path) for path in os.listdir(self.config.mountpoints.local) ]) container.restart() def copyfiles(self, mail, files): for old, new in files if type(files...
This function prepares a test environment by resetting a Docker container, copying specified files if required, and launching services with delays. It first resets the container, copies files based on the testgroup's configuration, then iterates through each service to execute its binary in the container, detaching the...
def _run_testgroup_setup(self, mail, container, testgroup): self.docker_reset(container) if testgroup.get("copy"): self.copyfiles(mail, testgroup.copy) for service in testgroup.get("services", []): self.docker_exec(container, service.binary, service, detach=True) ...
def _pretests(self, tests, binary, *args): if tests: self.vprint(f'Mouli "{self.config.name}": Running pretests for {binary}') for test in tests: out, err = subprocess.Popen([test, binary], stderr=subprocess.PIPE).communicate() if err: return err.decod...
This function runs unsecure test groups for a given mail, executing each test in both test and reference modes. It processes pretests, runs tests within Docker containers, captures errors and outputs, and updates results. If failures occur, it logs errors and populates results with None outputs. Validated test groups a...
def _run_tests_unsecure(self, mail, container, results, validated): for testgroup_name, testgroup in self.config.testgroups.iteritems(): if testgroup_name in validated: continue self.vprint( f'Mouli "{self.config.name}": Running "{testgroup_name}" grouptes...
def _run_setup(self): self.vprint(f'Mouli "{self.config.name}": Setup') mps = self.config.mountpoints if os.path.exists(mps.local): shutil.rmtree(mps.local) os.mkdir(mps.local) def get_closing_container(self): mps = self.config.mountpoints return closing(C...
The code executes tests for a given email address, initializes test environments, collects results in a nested dictionary structure, handles exceptions during test execution, and returns parsed test outcomes. It uses a container for resource management, tracks errors and outputs, and processes results through a parsing...
def run_tests(self, mail): self.vprint(f'Mouli "{self.config.name}": Running tests for {mail}') self._run_setup() results = defaultdict(lambda: defaultdict(lambda: JsonObject.Json({ "error": [None, None], "output": defaultdict(lambda: ["", ""]) }))) valida...
def iterclone(self, mails): return ((mail, self.clone(mail)) for mail in mails) def run_tests(self, mail): self.vprint(f'Mouli "{self.config.name}": Running tests for {mail}') self._run_setup() results = defaultdict(lambda: defaultdict(lambda: JsonObject.Json({ "error": [None...
The main task of the code is to clone repositories listed in 'mails', run tests on each cloned repository, record test results (score, summary, and details), and optionally send email notifications with the results. It returns a dictionary mapping each repository to its test outcomes, handling cloning errors by marking...
def clone_and_test(self, mails, send=False): self.vprint(f'Mouli "{self.config.name}": Starting phase of "clone and test"') results = {} for mail, error in self.iterclone(mails): if error is not None: score = None short = "Unable to clone" ...
def get_kingside_moves(self, row, col, king): if self.board[row][col+1] == ".." and self.board[row][col+2] == "..": one_right = Move((row, col), (row, col+1), self.board) two_right = Move((row, col), (row, col+2), self.board) if not (self.is_attacked(one_right) or self.is_att...
This code determines valid castling moves for a king in a chess game. It checks kingside and queenside castling conditions based on the current player's turn and castling rights. If valid, it retrieves potential moves via helper functions. It then verifies if the king is in check; if so, it returns an empty list, block...
def get_castle_moves(self, king): row = king.row col = king.col castle_moves = [] # checking for kingside castling moves if self.white_to_move and self.current_castle_state.white_kingside or \ not self.white_to_move and self.current_castle_state.black_kingside: ...
def get_castle_moves(self, king): row = king.row col = king.col castle_moves = [] # checking for kingside castling moves if self.white_to_move and self.current_castle_state.white_kingside or \ not self.white_to_move and self.current_castle_state.black_kingside: ...
This function generates valid moves for a king by checking all possible moves (including castling) and filtering out those that would leave the king in check. It simulates each move, verifies if it results in a check, and retains only non-check moves. If the input isn't a king, it prints an error.
def get_king_moves(self, king): moves = [] if king.name == "king": # filters moves that would lead to a king into a check possible_moves = king.possible_moves() # gets "regular" king moves castle_moves = self.get_castle_moves(king) # gets castling moves if castle_move...
def check_for_pins_and_checks(self): if self.white_to_move: start_row, start_col = self.find_king_pos("white") color = "white" for piece in self.white_playable_pieces: piece.is_pinned = False piece.pin_direction = () if piece.na...
The code generates valid moves for a chess engine by checking for pins, checks, and king safety. It identifies pinned pieces, calculates possible moves for all pieces, and filters out invalid moves when the king is in check. If no valid moves exist, it declares checkmate or stalemate.
def get_valid_moves(self): moves = [] in_check, pins, checks = self.check_for_pins_and_checks() dir_to_tuple = { "up": (-1,0), "down": (1, 0), "left": (0,-1), "right": (1, 1), "up-right": (-1, 1), "up-left": (-1, -1), ...
def initial_population(self): population = [] num_of_ones_limit = self.calculate_num_of_ones_limit() # probabilities are set according to in-degree of nodes probabilities = [len(self.incoming_neighbors[i]) + sum([len(self.incoming_neighbors[j]) for j in range(i)]) for i in range(self.n)] ...
The code implements a genetic algorithm to find an optimal solution by evolving a population of chromosomes. It initializes a population, iteratively selects parents via tournament selection (with diversity consideration for small problems), generates new offspring, and applies local search to refine solutions at key i...
def start(self): # trivial cases if self.n == 0 or self.n == 1: return Chromosome(0, self.n) population = self.initial_population() population.sort(key = lambda x: x.fitness) for i in range(self.iterations): if self.n < 1000: reproduction_set = self.tournament_s...
def inject_load(): table = fetchingMapDatafromSQL() tableLimits = fetchingAlertDatafromSQL() IRSensorsStrings = [] DSSensorsString = [] for i in range(8): IRSensorsStrings.append( 'Object: ' + str(table[0][i+1]) + ' Ambient: ' + str(table[0][i+9]) + ' Limit: ' + str(tableLimits[0...
The code periodically checks for new data entries, updates a map and chart, logs temperature and alarm messages, and dynamically renders these updates on a webpage using Turbo. It runs every 10 seconds via a timer, ensuring real-time UI updates for monitoring purposes.
def update_load(): inject_load() with app.app_context(): if checkForNewEntry(): updateMap() updateChart() messageAlarm = updateLogAlarm() messageTemp = updateLogTemp() turbo.push(turbo.prepend(render_template( 'read.html', messa...
def open_b2(access_key: str, shared_key: str, host: str) -> Bucket: """ Get the B2 bucket for a host :param access_key: The application key id :param shared_key: The application key :param host: The host name to generate the bucket name :return: The host B2 bucket """ b2_api.authorize_ac...
The main task of the code is to process files from a "send_queue" by uploading them to a B2 storage service with retry logic for errors. It attempts to upload each file, logging progress and errors, and moves successfully uploaded files to an "unlink_queue". If uploads fail after maximum retries, it logs an error. The ...
def sending_worker(queues: Dict[str, Queue], access_key: str, shared_key: str, host: str): """ Sends things from the queues :param queues: Dictionary of queues :param access_key: B2 access key :param shared_key: B2 shared key :param host: host """ start_time = time() counter = 0 ...
def get_current_video_title(self): return self.driver.execute_script("return document.title").replace(" - YouTube", "") def pause_video(self): self.driver.execute_script("document.getElementById('movie_player').pauseVideo()") def video_is_playing(self): # if we're still on the starting "10-hour ...
The code automates YouTube video playback by navigating to a video, accepting cookies, pausing the initial video, and managing a queue. It continuously checks if the current video has stopped and plays the next item from the queue, ensuring seamless playback. The function also handles cookie prompts to avoid interrupti...
def video_thread(self): # play silence to get past cookie prompt self.driver.get('https://www.youtube.com/watch?v=g4mHPeMGTJM') cookie_button_xpath = "//button[@aria-label='Accept the use of cookies and other data for the purposes described']" # cookie_button_xpath = "//button[@aria-labe...
def get_dashboard(self, limit=REBLOG_CHECK_LIMIT): return self.client.dashboard(limit=limit)["posts"] def get_reblog_post(self, posts): r_post = posts[randrange(0, len(posts))] while not self.is_valid_reblog_post(r_post): r_post = posts[randrange(0, len(posts))] # Add a rand...
The reblog method fetches a post from the dashboard, reblogs it with optional comments, likes it, follows the original author, and follows the source blog if present, logging success or errors. It handles exceptions and ensures interaction with the post's metadata.
def reblog(self): posts = self.get_dashboard() r_post = self.get_reblog_post(posts) try: rid = r_post["id"] rkey = r_post["reblog_key"] rtitle = r_post["blog"]["title"] rurl = r_post["short_url"] # reblog, like and follow original post...
def reblog(self): posts = self.get_dashboard() r_post = self.get_reblog_post(posts) try: rid = r_post["id"] rkey = r_post["reblog_key"] rtitle = r_post["blog"]["title"] rurl = r_post["short_url"] # reblog, like and follow original post...
The code's main task is to execute a series of social media automation actions: reblogging posts, following followers, logging the current follower count, and recording the timestamp of the last execution. These steps aim to maintain engagement and track account activity.
def execute(self): self.reblog() self.follow_followers() log_message = "Total Followers: {0}".format(self.get_num_followers()) self.logger.info(log_message) self.last_executed = datetime.now()
def inputComputerMove(board,user_char,ai_char): possible=find_possible_moves(board) max_stat=900000 index=0 for i in range(len(possible)): wins=0 draws=0 loss=0 for j in range(1000): tboard=[] for k in range(len(board)): ...
The function `gameplay` handles a single turn of a game where the computer and user alternately make moves on a board. It updates the board with the AI's move, checks for a win/draw, then prompts the user for a valid move. After updating the board with the user's move, it checks for a user win/draw. Returns `True` if t...
def gameplay(board,user_char, ai_char): c_pos=inputComputerMove(board,user_char,ai_char) board[c_pos]=ai_char print("Computer Move: ", c_pos) drawBoard(board) if (checkwin(board,ai_char)): print("Computer Won") return False if(checkdraw(board)): print("Drawn") ...
def extract_ip(part_str): parts = part_str.split(".") if len(parts) != 4: return None try: ip_parts = [int(part) for part in parts] return ip_parts except ValueError: return None pass def info_group(self): self.number_groups = int(input("Enter the number of gr...
The code's main task is to classify a user-input IP address into its network class (A, B, or C) using the IPAnalyzer, then execute corresponding methods like `found_prefix_A()`, `found_prefix_B()`, or `found_prefix_C()` based on the classification, alongside retrieving and displaying IP-related information via `info_gr...
def run(self): user_input = input(">> Enter your IP address of network (e.g., 192.168.1.0): ") ip_parts = extract_ip(user_input) self.ip_analyzer = IPAnalyzer(ip_parts) self.ip = self.ip_analyzer.classify_ip() Class = self.ip_analyzer.classify_ip() if Class == 'A': ...
def getNumLeafs(myTree): numLeafs=0 firstStr=list(myTree.keys())[0] secondDict=myTree[firstStr] for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': # Test if node is dictionary numLeafs+=getNumLeafs(secondDict[key]) else: numLeafs+=1 return numLeafs def getTreeDepth(myTree): maxDept...
This code generates a visual representation of a decision tree using matplotlib. It initializes a plot, calculates tree dimensions, sets node positions, and renders the tree structure with specified nodes and connections.
def createPlot(inTree): fig=plt.figure(1,facecolor='white') fig.clf() axprops=dict(xticks=[],yticks=[]) createPlot.ax1=plt.subplot(111,frameon=False,**axprops) plotTree.totalW=float(getNumLeafs(inTree)) plotTree.totalD=float(getTreeDepth(inTree)) plotTree.xOff=-0.5/plotTree.totalW plotTree.yOff=1.0 ''' plotNo...
def get_unit(state, player_id): for unit in state.units: if unit.unit_type == CMsgBotWorldState.UnitType.Value('HERO') \ and unit.player_id == player_id and not unit.is_illusion: return unit raise ValueError("unit {} not found in state:\n{}".format(player_id, state)) def select_a...
This function converts observations into actionable commands for a game agent. It identifies the hero unit, generates policy inputs and action masks, logs actions, converts them to protocol buffers, and appends training ability upgrades. The result is a list of action protocol buffers for execution, combining movement,...
def obs_to_actions(self, obs): actions = [] hero_unit = get_unit(state=obs, player_id=self.player_id) policy_input, action_dict, action_mask, unit_handles = self.select_action( world_state=obs, hero_unit=hero_unit, ) self.policy_inputs.append(policy_inpu...
def _set_lossW(self): if self.flags_.slow_var: self.varW = min(1, 1 * self.nIter_/self.flags_.epoch_vae * self.flags_.varW) else: self.varW = self.flags_.varW if self.flags_.slow_entr: self.entrW = min(1, 1 * self.nIter_/self.flags_.epoch_vae * self.flags_.e...
The main task of the code is to perform a training step for a neural network model with VAE and tree decoder components. It alternates between training the VAE (for initial epochs) and the tree decoder (later stages), applying constraints, computing reconstructions, and backpropagating losses. The function returns mult...
def train_step(self, input): self._set_lossW() input = input.to(self.device_) self.clonalP_.train() self.encoder_.train() self.nn_decoder_.train() self.tree_decoder_.train() if self.nIter_ < self.flags_.epoch_vae: self._freeze('tree') clo...
def chatBox(event, car, inputText, text_input, text_input_render, button_image, button_rect): if event.type == KEYDOWN: if event.key == pygame.K_TAB: car.ready = True elif event.key == K_BACKSPACE: text_input = text_input[:-1] elif event.key == K_RETURN: c...
The code implements a multiplayer racing game with real-time collision detection, scoring, and chat functionality. It manages car movement, obstacle generation, player interactions, and game states (start, play, game over). The main tasks include handling network communication, rendering game elements, detecting collis...
def main(inputText): global messages global startTime global text_input global text_input_render global game_over global finish run = True roadx = 0 roady = 0 car_vel = 15 road_vel = 12 obs_x = 0 obs_img = 0 obstacle_y = -100 started = False chatOnly =...
def makeNewNote(self, name): time = datetime.now() timestamp = time.strftime("%d/%m/%Y %H:%M:%S") with open(os.path.join(self.curNotesPath, name), 'w') as newNote: newNote.write('# ' + name + '\n') newNote.write(timestamp +'\n\n') def setupFileTree(self): if self....
The code generates a default-named Markdown note using the current timestamp, creates the note, closes the note-creation window, updates the file tree view, and loads the new note's content into the preview pane.
def makeNewNoteDefaultName(self): time = datetime.now() name = time.strftime("%d-%m-%Y@%H%M%S") + '.md' self.makeNewNote(name) self.newNoteWindowToplevel.destroy() self.setupFileTree() self.setPreviewText(''.join(open(os.path.join(self.curNotesPath, name), 'r', encoding =...
def makeNewNote(self, name): time = datetime.now() timestamp = time.strftime("%d/%m/%Y %H:%M:%S") with open(os.path.join(self.curNotesPath, name), 'w') as newNote: newNote.write('# ' + name + '\n') newNote.write(timestamp +'\n\n') def setupFileTree(self): if self....
This function creates a new note with a custom name by retrieving text from a widget, processing it into a valid file path, and saving it as a .md file. If successful, it destroys the creation window, refreshes the file tree, and displays the new note's content in the preview.
def makeNewNoteCustomName(self, event = None): name = self.newNoteName.get(1.0, 'end-1c') name = os.path.normpath(name.replace('\n', '')) + '.md' if name != "": self.makeNewNote(name) self.newNoteWindowToplevel.destroy() self.setupFileTree() if name != "": ...
def task2A(tracks, frame, img): ''' 1. Extracts the common features from the first and last frame 2. Visualises the correspondences ''' # The first and the last frames frame1 = 0 frame2 = frame-1 # Extract the common features & visualise correspondences = [] first_last_corresp = {} for track in t...
This function processes image correspondences between frames to track objects, detect outliers, and generate visualizations. It sequentially performs correspondence detection, transformation estimation, inlier selection, outlier filtering, and track updates, returning processed data for analysis and visualization.
def task2(tracks, frame, img): print('-------------------Task2 A-----------------------------') correspondences, ucorrespondences = task2A(tracks, frame, img) print('-------------------Task2 B-----------------------------') (x1n, x2n, T1, T2) = task2B(correspondences) print('-------------------Task2 C--------...
def task1(): print('-------------------Task1 A-----------------------------') object_points = [] image_points = [] images = glob.glob("Assignment_MV_02_calibration/*.png") for index, file_name in enumerate(images): # Reads the image image = cv2.imread(file_name) last = index == len(images) - 1 ...
The main task is to process image pairs for 3D reconstruction by detecting features, computing correspondences, and applying camera calibration parameters to calculate depth. It creates an output directory, runs feature tracking (task1), finds correspondences (task2), and computes depth maps (task3) using camera matric...
def main(): # Checks if the output directory already exists else creates it if not os.path.exists('output'): os.makedirs('output') (tracks, frame, img, img2, K, d, rvec, tvec) = task1() nimg = copy.deepcopy(img) nimg2 = copy.deepcopy(img2) (correspondences, ucorrespondences, selected, unselected, F, is_...
def parse_args(): # Training settings parser = argparse.ArgumentParser(description='') parser.add_argument('cmd', choices=['train', 'test']) parser.add_argument('-d', '--data-dir', default='../dataset/nyud2') parser.add_argument('-s', '--crop-size', default=0, type=int) parser.add_argument('-g',...
The main task of the code is to execute either training or testing for a segmentation model based on the command-line argument (`args.cmd`). If the command is 'train', it initiates the training process via `train_seg(args)`. If 'test', it runs evaluation using `test_seg(args)`. The function parses input arguments and r...
def main(): args = parse_args() #print(os.environ['MASTER_PORT']) if args.cmd == 'train': train_seg(args) elif args.cmd == 'test': test_seg(args)
def _replace_variables(self, content, variables): for variable in variables: variable_content = '{0}: {1};'.format( variable['name'], variable['value'] ) regex = r'{0}\:?\s(.*?);'.format(variable['name']) content = re.sub(regex, var...
This function replaces variables in content retrieved from a specified URL and XML ID, then updates the content with the modified version. It first fetches the original content using `get_content`, applies variable substitutions via `_replace_variables`, and stores the updated content using `replace_content`.)
def replace_values(self, url, xmlid, variables): content = self._replace_variables( self.get_content(url, xmlid), variables ) self.replace_content(url, xmlid, content)
def addDataLabel(self,el): assert el.data=="instruction"; labelName=el.children[0]; dimension=el.children[1]; valList=[]; if el.children[1]=="ds": sttrr=el.children[2].children[0].replace("\"",""); for c in sttrr: valList.append(ord(c))...
This function converts parsed assembly code into binary format by processing instructions, labels, and data directives. It validates the code structure, handles label definitions, implants jump addresses, generates the data segment, and ensures proper memory addressing. The output includes binary code in `outBinArr` an...
def spitBinary(self,outBinArr,outDataSegment): # tree root must be a start assert self.parsedTree.data=="start"; # list of labels labelList=[]; for el in self.parsedTree.children: #print(el); assert el.data=="instruction"; instr...
def start_threads(start = "all"): """ starts all or specific threads that are defined in run["threads"] :param start: "all" or the token of the thread name, string """ print("in start_threads()") if not (start == "all" or start in run["threads"]): raise ValueError("valid dict key expec...
The main task of the code is to set up signal handlers for termination signals (SIGUSR1, SIGINT, SIGTERM, etc.), initialize threads and system setup, and enter an infinite loop to periodically monitor thread status. The code handles graceful shutdowns via signals and maintains thread health monitoring.
def main(): # install signal handler signal.signal(signal.SIGUSR1, shutdown) for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT]: signal.signal(sig, signal_handler) #hello_and_goodbye("hello") start_threads() setup() while True: time.sleep(1) mo...
def toggle_pause(mpdclient): """ toggles play/pause but also starts playback if state is stop :param mpdclient: MPDClient() """ with connection(mpdclient): try: status = mpdclient.status() state = status["state"] if state == "play": m...
The main task of the code is to monitor an RFID reader, process card data, and execute predefined commands (e.g., toggle pause, schedule shutdown, adjust volume) by interacting with a music player and scheduling system. It handles RFID inputs, manages state transitions, and triggers actions like playlist control, sleep...
def check_rfid_reader(in_q): print("starting check_rfid_reader() thread") reader = SimpleMFRC522() while True: try: qdata = in_q.get(False) except queue.Empty: qdata = None if qdata is _shutdown: print("_shutdown in check_rfid_reader()") ...
def next_album(mpdclient): print("in next_album()") with connection(mpdclient): try: status = mpdclient.status() plist = mpdclient.playlistinfo(str(status["song"]) + ":" + str(status["playlistlength"])) this_album = plist[0][...
The code handles timed forward button presses, performing actions based on duration: single press (1s) advances the playlist by one song, double press (within 1s) skips 30s forward, holding >1s switches to the next artist, and a single press followed by a hold plays from a bookmarked timestamp. It uses a queue for comm...
def check_forward_button(in_q): """ handles timed presses for the forward button the time frame for connected presses is 1 s a single press moves the playlist one song forward a double press moves the song 30 s forward holding the button for longer than 1 s moves to the next artist a single ...
def previous_album(mpdclient): print("in previous_album()") with connection(mpdclient): try: status = mpdclient.status() if "nextsong" in status: plist = mpdclient.playlistinfo("0" + ":" + str(status["nextsong"])) else: plist = mpdclien...
This function handles backward button interactions with timed logic: single press (1s) moves playlist backward, double press (within 1s) rewinds 30s, hold >1s navigates to previous artist, and a single press followed by hold saves current track as a bookmark. It uses a queue for input, tracks button states, and trigger...
def check_backward_button(in_q): """ handles timed presses for the backward button the time frame for connected presses is 1 s a single press moves the playlist one song backward a double press moves the song 30 s backward holding the button for longer than 1 s moves to the previous artist a...
def predict_co2_emission_future(self): self.initialize_prediction_df() if self.predict_new and self.prediction_without_covid_case: for _, scenario in enumerate(self.prediction_cases): self.execute_prediction(scenario) else: self.execute_prediction('with co...
The code generates a CO2 emission prediction plot by checking conditions to either predict new data or restore existing predictions, then creates the visual graph and returns the file path stored in OUTPUT_GRAPH_PATH.
def create_visual_graph(self): """ creates a plot and outputs path of the plot that's returned to the user interface :rtype: string """ if self.predict_new and self.prediction_without_covid_case: self.predict_co2_emission_future() self.save_prediction_df()...
def deserialize(seq): """into ndarray of (25, 401), (10, 26)""" return seq[:25 * 401].reshape(25, 401), seq[25 * 401:].reshape(10, 26) def gradient(theta, X, y): # initialize t1, t2 = deserialize(theta) # t1: (25,401) t2: (10,26) m = X.shape[0] delta1 = np.zeros(t1.shape) # (25, 401) delt...
This function computes the regularized gradient for a neural network by applying L2 regularization to weight parameters (excluding bias terms) and adding the regularization term to the gradients. It deserializes the input theta into weight matrices, zeros out bias columns, calculates regularization terms using lambda/m...
def regularized_gradient(theta, X, y, l=1): """don't regularize theta of bias terms""" m = X.shape[0] delta1, delta2 = deserialize(gradient(theta, X, y)) t1, t2 = deserialize(theta) t1[:, 0] = 0 reg_term_d1 = (l / m) * t1 delta1 = delta1 + reg_term_d1 t2[:, 0] = 0 reg_term_d2 = (l ...
def initialize_weights(self): ''' Initialize weights, initialization method depends on the Activation Function and the Number of Units in the current layer and the next layer. The weights for each layer as of the size [next_layer, current_layer + 1] ''' self.weigh...
The code trains a neural network using gradient descent by iterating through backpropagation to compute gradients, updating weights via gradient descent, optionally adapting the learning rate, and periodically minimizing weight errors over a specified number of iterations.
def train(self, training_input, training_output, reset=True): if reset: self.initialize_weights() for i in range(1, self.max_iterations + 1): if self.verbose: print("Iteration: " + str(i)) self.gradients = self.backpropagation(training_input, training_...
def get_Next_Slot_Available(type: reservationapi): try: print("\nLoading.....") res = type.get_slots_available() next_slot = res[0]['id'] return next_slot except BadRequestError as e: print("Bad Request Error: Code 400") sys.exit() except InvalidTo...
This function reserves separate earliest available slots for two distinct reservation types (band and hotel) when no common slot exists. It releases existing bookings, reserves new slots individually, and triggers a recheck to confirm the reservations.
def book_When_noCommon(type1: reservationapi, type2: reservationapi): # Find the best slot for each invidually since there is no common slot. bbest = get_Next_Slot_Available(type1) print("\nWe will arrange a reservation for the band in slot " + str(bbest) + " Which is the earliest available slot.") tim...
def earliest_Common_Slot(type1: reservationapi, type2: reservationapi): print("\nChecking the availablity of common slots....") # Get the lists of available slots for both the hotel and band. res1 = type1.get_slots_available() res2 = type2.get_slots_available() # A list to contain common slots. ...
The code's main task is to find and book the earliest common reservation slot for a hotel and band using reservationapi instances. It checks for overlapping availability, releases existing bookings if needed, reserves the optimal slot, and rechecks for potential improvements, ensuring efficient resource allocation for ...
def start_App(type1: reservationapi, type2: reservationapi): print("Welcome to The Wedding Planner!\n") print("We will do our best to find you the best reservations for your hotel and band") time.sleep(1) print("First we will look for the common slots where the band and hotel are available.") time....
def apply_mouse_offset(self, mpos): return mpos[0] - self.offset[0], mpos[1] - self.offset[1] def hovered_tile(self, mpos): tx, ty = self.screen_to_tile(mpos) tx = int(tx) ty = int(ty) return tx, ty def calculate_grabbed_objects(self, direction, start_tile): tx, ty = star...
This function updates the dragging of a tile by adjusting its position based on mouse movement, checking for valid moves in horizontal/vertical directions, calculating obstructions, and updating the game state with tile movement, direction, and visual/audio feedback if movement is allowed.
def update_dragging(self): mpos = list(self.apply_mouse_offset(pygame.mouse.get_pos())) if self.grabbed_tile: test_positions = [(mpos[0], self.grab_position[1]), (self.grab_position[0], mpos[1])] if self.drag_direction is not None and self.drag_direction == c.HORIZONTAL: ...
def all_grid_objects(self): for grop in self.all_grid_objects_and_position(): yield grop[0] def apply_mouse_offset(self, mpos): return mpos[0] - self.offset[0], mpos[1] - self.offset[1] def update_hovered_statuses(self, mpos): hovered = self.hovered_object(mpos) for grid_obje...
This code updates game elements over time, handles mouse interactions for grabbing/releasing objects, triggers a win shake animation after victory, updates grid objects, checks for victory conditions, and tracks time-related states like 'last_scrape' and 'since_won'. It manages object interactions, dragging mechanics, ...
def update(self, dt, events): if self.won: self.since_won += dt if not self.win_shake_occurred and self.won and self.since_won>0.15: self.frame.shake(12) self.win_shake_occurred = True for grid_object in self.all_grid_objects(): grid_object.update(...
def load(self): try: with open(self.fileloc + "users_" + self.filename, 'rb') as handle: self.users = pickle.load(handle) handle.close() with open(self.fileloc + "markets_" + self.filename, 'rb') as handle: self.markets = pickle.load(handl...
This code initializes a Tkinter-based application for a prediction market system, loading user and market data from a file, validating user permissions, setting up GUI frames, and configuring initial displays. It handles user authentication, data persistence, and interface setup for market management and trading activi...
def __init__(self): Tk.__init__(self) """ ------------------------------------------------------------------------------------------------------------ CORE Code stuff ------------------------------------------------------------------------------------------------ ----------------------...
def parse_args(): parser = argparse.ArgumentParser(description='Install or verify GPU drivers.') parser.add_argument("action", choices=['install', 'verify'], default="install", nargs="?") parser.add_argument("--force", help="Forces driver installation, even if there is no GPU detected.", ...
The main task of the code is to execute an installation or verification process for drivers and CUDA Toolkit. It checks system prerequisites, ensures root privileges, detects the Linux distribution, installs dependencies, verifies GPU presence, and performs driver installation with post-install steps, exiting early if ...
def main(): """ Main function of the installation script. """ args = parse_args() if args.action == 'verify': verify_installation() elif args.action == 'install': # Prerequisites check_python_version() if os.geteuid() != 0: print("This script needs to...
def avg_ifr(region,which='mean'): """ Calculate average infection fatality ratio for a population, given age-group-specific fatality ratios and assuming a uniform attack rate across all age groups. """ if which == 'mean': ifr_values = data.ifr elif which == 'low': ifr_values ...
The function determines a time-dependent intervention factor based on recent data, fits it to the SIR model, and forecasts future disease outcomes (e.g., deaths, infections) under varying intervention scenarios. It uses historical case/death data, population estimates, and parameters like beta (transmission rate) and g...
def fit_q_and_forecast(region,beta=default_beta,gamma=default_gamma,forecast_length=200,set_q=None,int_len=None,which_ifr='mean'): """ Determine an intervention factor (possibly time-dependent) that explains the recent data, and then use that to forecast into the future. Inputs: - set_q: If 'e...
def avg_ifr(region,which='mean'): """ Calculate average infection fatality ratio for a population, given age-group-specific fatality ratios and assuming a uniform attack rate across all age groups. """ if which == 'mean': ifr_values = data.ifr elif which == 'low': ifr_values ...
The function infers past infections using historical data and models the epidemic's progression up to the present, accounting for intervention effectiveness. It adjusts reported deaths by an estimated mortality ratio (emr), employs stochastic or deterministic methods (via nTrials), and returns inferred infection dates ...
def get_past_infections(region,beta=default_beta,gamma=default_gamma,nTrials=1,which_ifr='mean',emr=1.0): """Infer past infections up to offset days in the past. Then model up to the present based on a fitted intervention effectiveness. Inputs: - emr: estimated mortality ratio; real deat...
def avg_ifr(region,which='mean'): """ Calculate average infection fatality ratio for a population, given age-group-specific fatality ratios and assuming a uniform attack rate across all age groups. """ if which == 'mean': ifr_values = data.ifr elif which == 'low': ifr_values ...
The function `compute_and_plot` models disease spread using epidemiological parameters (beta, gamma) and historical data for a specified region. It infers initial conditions, fits a model to past data, forecasts future cases/deaths (with uncertainty intervals), and visualizes both historical predictions and future proj...
def compute_and_plot(region,beta=default_beta,gamma=default_gamma,q=0., intervention_start=0,intervention_length=30,forecast_length=14,scale='linear', plot_type='cumulative',plot_value='deaths',plot_past_pred=True,plot_interval=True, death_model='gamma',estimate_q=False): "Sho...
def avg_ifr(region,which='mean'): """ Calculate average infection fatality ratio for a population, given age-group-specific fatality ratios and assuming a uniform attack rate across all age groups. """ if which == 'mean': ifr_values = data.ifr elif which == 'low': ifr_values ...
The main task of the code is to generate and save epidemiological forecasts for specified regions (excluding China) into a JSON file. It calculates intervention effectiveness, estimates immunity levels, projects daily/new infections, and compares scenarios with/without interventions. The output includes predicted death...
def write_JSON(regions, forecast_length=200, print_estimates=False): output = {} gamma = default_gamma beta = default_beta pdf = deconvolution.generate_pdf(8.,14./8.,3*forecast_length) for region in regions: # China's recent data is nonsense. if region == 'China': continue ...
def add_current(self, city): city = myapiref(city) if(city in self.Info): index = self.Info.index(city) self.Info.insert(0,self.Info.pop(index)) else: self.Info.insert(0, city) def get_data(self): self.splash.repaint() def change_window(self, index): ...
The code checks if the input text is "current". If true, it updates the location, caches data, rearranges display elements, and switches to a specific window. If false, it combines the input with a selected option from a dropdown, sets a new city, and triggers a city update process.
def Check_current(self): word = self.textbox.text().lower() if word == "current": self.add_current("Current Location") write_cache(self.Info) self.get_data() self.t.insert(0, self.t.pop(self.t.index(self.Info[0][0]))) self.change_window(0) ...
def _is_move_legal(self, x: int, y: int): if self.check_is_winner("o") or self.check_is_winner("x"): return False return self.board[x][y] == "" def check_is_winner(self, marker: str): win_condition = str(marker * 3) # Check rows if "".join(self._get_row(0)) == win_con...
This function updates the Tic-Tac-Toe board with a player's marker at position (x,y) if the move is legal. It checks for a win, a draw, or continues the game, returning corresponding status codes like ILLEGAL_MOVE, O_WINS, X_WINS, DRAW, or END_MOVE.
def update_board(self, x, y, marker: str): if self._is_move_legal(x, y): self.board[x][y] = marker else: return TicTacToe.ILLEGAL_MOVE if self.check_is_winner(marker): return TicTacToe.O_WINS if marker == 'o' else TicTacToe.X_WINS if self.check_board_f...
def create_files_sync_folder(self): if not os.path.isdir(self.sync_folder_path): os.makedirs(self.sync_folder_path) def create_files_db(self): database_obj = { 'files': self.get_folder_content() } if not os.path.isfile(self.files_chk_db): with open(sel...
The code initializes a class instance for file synchronization, setting up a sync folder, creating a database file, loading the database, and initializing a controller. It prepares the environment for tracking file changes and managing synchronization tasks.
def __init__(self, controller): self.sync_folder_path = 'files_sync' self.files_chk_db = 'files_chk_db.json' self.create_files_sync_folder() self.create_files_db() self.files_database = self.read_db_file() self.incoming_actions = [] self.controller = controller
def load_single_genes(self, workdir_singlerun, genename): """ Load PhylUp class objects and make a single dict per run. Removes abandoned nodes and gap only columns first. :param workdir_singlerun: directory of single gene run :param genename: string, name for locus provided by...
The main task of the code is to concatenate multiple gene alignment results into a unified table by loading individual gene data, adding alignment information, ensuring data uniqueness, and combining them into a single DataFrame. It checks for duplicate accessions and indices, then saves the combined table as a CSV if ...
def write_comb_table(self, genelistdict, suggest): """ This is the main method to concatenate different runs into a single alignment and tree. :param genelistdict: dictionary with gene names as key and the corresponding workdir :return: """ # self.concatfile = user_conc...
def clean_aln(aln_fn): """ Replace '?' with '-' in alignment :param aln_fn: :return: """ aln = DnaCharacterMatrix.get(path=aln_fn, schema='fasta') aln_string = aln.as_string('fasta') aln_string = aln_string.replace('?', '-') with open(aln_fn, "w") as aln_file: aln_file.write...
This function concatenates multiple gene alignments into a single combined alignment, processes each locus by cleaning, trimming, and removing gaps, and optionally combines trees. It builds a data table with alignment details, appending results to a combined table, then triggers a concatenation calculation for downstre...
def run_fresh(self, aln_dict, spn_dict, schema='fasta', tre_dict=None, tre_schema=None, self_select=False): """ This is the main method to concatenate different runs into a single alignment and tree. :param aln_dict: :param spn_dict: dict with gene names as key and the corresponding sp...
def load_single_genes(self, workdir_singlerun, genename): """ Load PhylUp class objects and make a single dict per run. Removes abandoned nodes and gap only columns first. :param workdir_singlerun: directory of single gene run :param genename: string, name for locus provided by...
This function concatenates multiple gene alignments into a single combined alignment and phylogenetic tree. It processes each gene from genelistdict, loads alignment data, merges sequences into a unified table, ensures unique indices, and triggers concatenation calculations. The method either uses user-supplied tables ...
def run_phylup(self, genelistdict, self_select=False): """ This is the main method to concatenate different runs into a single alignment and tree. :param self_select: T/F: True will read in user supplied concatenation table. :param genelistdict: dictionary with gene names as key and t...
def idle(self): image = pygame.image.load(self.up + "WarriorUpIdle.png") self.idle_up = self.animator(image, 'up', self.idle_steps) image = pygame.image.load(self.down + "WarriorDownIdle.png") self.idle_down = self.animator(image, 'down', self.idle_steps) image = pygame.image.load(self.left + "WarriorLeftIdle...
The code initializes step counts for different character animations (walking, fighting, flashing, idle) and sets graphic directories for each direction. It calls methods to prepare or trigger these animations, likely for a game or sprite rendering system.
def __init__(self): self.walk_steps = 8 self.fight_1_steps = 6 self.fight_2_steps = 6 self.flash_steps = 5 self.idle_steps = 5 self.up = "graphics/Warrior/Up/Png/" self.down = "graphics/Warrior/Down/Png/" self.left = "graphics/Warrior/Left/Png/" self.right = "graphics/Warrior/Right/Png/" self.i...
def input(self): if self.left_click: self.target = pygame.math.Vector2(pygame.mouse.get_pos()) + self.cam_group.offset self.face_update() self.left_click = False keys = pygame.key.get_pressed() if self.test_keyboard: ...
The code's main task is to update an object's state by sequentially processing user input, initiating an attack, checking for collisions, and updating movement. This method likely belongs to a game entity or simulation object, orchestrating its actions in a single update cycle to maintain interactive behavior and physi...
def update(self): self.input() self.attack() self.check_collision() self.movement()
def conv3x3(in_tensor, filters, strides=1, groups=1, trainable=True, name=""): return _conv2d( in_tensor, filters=filters, kernel_size=3, strides=strides, padding=[[0, 0], [0, 0], [strides, strides], [strides, strides]], groups=groups, use_bias=False, ...
This function implements a residual block with group convolutions. It processes inputs through two 3x3 convolutions, applies batch normalization and ReLU, and adds a residual connection (with optional downsampling via 1x1 convolution). The block supports group convolutions for efficiency and includes trainable paramete...
def basic_block( inputs, filters, strides=1, downsample=None, num_group=32, trainable=True, training=True, layer_block="", ): residual = inputs conv1 = conv3x3( inputs, filters * 2, strides, trainable=trainable, name=layer_block + "conv1" ) bn1 = _batch_norm( ...
def ReadConfigFile(): if(os.path.exists("config.dat")): f = open("config.dat","r+") d : dict = json.loads(f.read()) for item in d.items(): configSettings[item[0]] = item[1] f.close() else: WriteConfigFile() def ConsoleWrite(text,color='black',boldPrefixChars=0): consoleLogQueue.append([text,color,boldPr...
The main task of the code is to create a GUI configuration window using Tkinter. It dynamically generates input fields for each configuration setting, loads existing values, and provides a "Save & Close" button to update settings. The window size adjusts based on the number of settings, and a timestamped log message co...
def CreateConfig(): global configRoot, configSettingsInputs ReadConfigFile() configRoot = Tk() configRoot.title("Config") configRoot.geometry("600x"+str(100+20*len(configSettings.items()))) configRoot.resizable(False,False) i = 0 configSettingsInputs = [] for config in configSettings.items(): l = Label(confi...
def make_piece(self): middle = len(self.columns) // 2 shape = self.rand.choice(Piece.SHAPES) made_piece = Piece(middle - shape["x_adj"], 0, shape, shape["color"]) return made_piece def piece_can_move(self, x_move, y_move): """Returns True if a piece can move, False otherwise.""" ...
The function generates the initial game piece, positions it at the drop point, and checks if it can be placed. If not, it finalizes the piece, marks the game as over, and resets the piece. It ensures the first piece is created when the game starts and handles game-over logic if the initial placement is invalid.
def hold_generate_piece(self): if self.game_over: return if self.first_hold is False: self.piece = self.make_piece() self.first_hold = True self.piece.x = self.drop_x self.piece.y = self.drop_y self.piece if not self.piece_can_move(0...
def make_piece(self): middle = len(self.columns) // 2 shape = self.rand.choice(Piece.SHAPES) made_piece = Piece(middle - shape["x_adj"], 0, shape, shape["color"]) return made_piece def piece_can_move(self, x_move, y_move): """Returns True if a piece can move, False otherwise.""" ...
The main task of the code is to generate a new random game piece and place it at the board's top. If the piece cannot be placed (game over condition), it finalizes the piece, marks the game as over, and resets the piece to None. The function exits early if the game is already over.
def generate_piece(self): """Creates a new piece at random and places it at the top of the board.""" if self.game_over: return self.piece = self.make_piece() if not self.piece_can_move(0, 0): # Show piece on the board self.finalize_piece() ...
def piece_can_move(self, x_move, y_move): """Returns True if a piece can move, False otherwise.""" for base_x, base_y in self.piece: x = x_move + base_x y = y_move + base_y if not 0 <= x < len(self.columns) or y >= self.columns[x]: return False ...
The main task of the code is to either move a game piece down one level if possible or finalize it (lock it in place) and generate a new piece when it can no longer move downward. It checks if the piece can move, handles finalization with a delay, and triggers new piece generation if enabled, managing game state transi...
def drop_piece(self): """Either drops a piece down one level, or finalizes it and creates another piece.""" if self.piece is None: return if not self.piece_can_move(0, 1): # We want to give a short leeway for the player to move the piece, once it's hit bottom ...
def piece_can_move(self, x_move, y_move): """Returns True if a piece can move, False otherwise.""" for base_x, base_y in self.piece: x = x_move + base_x y = y_move + base_y if not 0 <= x < len(self.columns) or y >= self.columns[x]: return False ...
This function either moves the current game piece down as far as possible or finalizes it when it can't descend further, then generates a new piece. It checks if the piece can move down, repeatedly moves it if possible, and upon blockage, finalizes the piece and creates a new one for continued gameplay.
def full_drop_piece(self): """Either drops a piece down one level, or finalizes it and creates another piece.""" if self.piece is None: return while self.piece_can_move(0, 1): self.piece.move(0, 1) self.finalize_piece() self.generate_piece()
def traverseImageMultiScale(img, model, sizes=[(140, 140), (100, 100), (64, 64)], x=30,\ y=[(380, 665), (380, 665), (380, 665)], background=False, ther=0.9): img1 = np.zeros_like(img) rects = [] for i in range(len(sizes)): img1, rect = traverseImage(img, model, ((x, y[i][0]), sizes[i]), ...
The code detects cars in an image using a multi-scale approach with a preloaded model. It processes the image at specified scales, filters detected regions (rectangles) based on a threshold, and applies the final bounding boxes to the image, returning the annotated image with detected cars.
def detect_cars(img): global model img1, rects = traverseImageMultiScale(img, model, sizes=[[80, 80], [100, 100], [124, 124]], ther=0.3) rects,_ = filterSomeRects(img1, rects, thershold=3) img1 = applyRects(img1, rects) return img1
def get_features_for_Classification(data): data_nocode = data.No_code_tokens data_nocode = [literal_eval(x) for x in data_nocode] data_phraseList = data.ranked_phraseList data_phraseList_L = [literal_eval(x) for x in data_phraseList] feature_set = [a + b for a, b, in zip(data_nocode, data_phra...
The code performs supervised learning using a trained Word2Vec model for feature extraction on classification data, evaluates an SVM classifier, and then employs the same model to predict labels for additional data in a mining task, enabling manual labeling of new samples.
def main(): path_dir = os.path.dirname('filepath') read_miner = os.path.join(path_dir, 'More_SO_data.csv') read_classifier_data = os.path.join(path_dir, 'Classifier_data.csv') #Load the trained RL model with Collocations RL_model = Word2Vec.load('RL_Model.model') '''Supervised Learning''' ...
def getGenreTags(): query = """ { findTags( tag_filter: {name: {value: """ + '"' + config.genre_parentname + '"' + """ , modifier: EQUALS}} filter: {per_page: -1} ) { count tags { id name children { name id ...
The code generates an XML NFO file for media metadata, populating fields like title, unique IDs, ratings, and tags from a scene object. It processes performers, genres, thumbnails, and fanart, formatting them into a structured XML template for use in media libraries like Kodi. The function dynamically constructs elemen...
def generateNFO(scene): ret = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- Generated by StashNfoExporterKodi plugin on {now} --> <movie> <title>{title}</title> <uniqueid type="stash" default="true">{id}</uniqueid> {stash_ids} <mpaa>XXX</mpaa> <playcount>{o_counter}</playcount> ...
def getOutputNFOFile(scene): if config.filename == "filename": return os.path.join(config.save_path, "{}.nfo".format(os.path.splitext(basename(scene["path"]))[0])) elif config.save_path == "with files": return os.path.join(os.path.dirname(scene["path"]), "{}.nfo".format(os.path.splitext(basename...
The code processes input JSON data to generate NFO and STRM files for media scenes. It loads input from command-line arguments or stdin, connects to a server via StashInterface, retrieves scene details, checks conditions to skip generation if configured, creates NFO files with UTF encoding, and optionally generates STR...
def main(): global stash if len(sys.argv) > 1: # Loads from argv for testing... json_input = json.loads(sys.argv[1]) else: json_input = json.loads(sys.stdin.read()) stash = StashInterface(json_input["server_connection"]) sceneID = json_input['args']['hookContext']['id'] s...
def test(self): self.model.eval() if self.indiv_acc: test_loss = 0 correct = 0 indiv_acc_dict = {} for i in range(self.num_classes): indiv_acc_dict[self.get_class(i)] = [0,0,0] with torch.no_grad(): for data,target in self.test_data_loader: if args.use_cuda: data, target = data.cu...
The code performs iterative filter pruning on a neural network to reduce its size by 67%, while maintaining accuracy. It tests the model pre-pruning, ranks filters for removal, applies pruning, fine-tunes after each iteration, and saves the optimized pruned model. The process involves training parameters, calculating p...
def prune(self): #Get the accuracy before prunning self.test() self.model.train() #Make sure all the layers are trainable for param in self.model.features.parameters(): param.requires_grad = True starting_number_of_filters = self.total_num_filters() num_filters_to_prune_per_iteration = 512 iteratio...
def dfs(self): time = 0 for aVertex in self: aVertex.setColor('white') aVertex.setPred(None) for aVertex in self: if aVertex.getColor() == 'white': self.dfsvisit(aVertex, time) def get_transpose(self): # Get transpose graph g_...
This code implements Kosaraju's algorithm to find all strongly connected components (SCCs) in a directed graph. It first performs a DFS on the original graph to record finishing times, then constructs the transpose graph. A second DFS on the transpose graph, processed in decreasing order of finishing times, identifies ...
def print_scc(self): # Step 1: DFS on the graph G to compute finishing times for each vertex self.dfs() # Step 2: Get the transpose graph G^T g_t = self.get_transpose() # Step 3: DFS on the graph G^T (explore each vertex in order of decreasing finishing time) # Get des...
def gen_driver(self): try: chrome_options = uc.ChromeOptions() chrome_options.headless = True # chrome_options.add_argument('--proxy-server=http://'+PROXY) driver = uc.Chrome(options=chrome_options) return driver except Exception as e: ...
This code initializes a web scraping class for image collection, setting up a browser driver, creating an 'Images' directory, storing search keywords, and preparing variables to store image URLs and quantity. It also triggers a scraper manager to handle the scraping process.
def __init__(self, search_kw_list): # logger("on") # Turning on the logger ;) self.driver = self.gen_driver() self.dirManager('Images') self.search_kw_list = search_kw_list self.search_querry = None self.imgurls = None self.image_quantity = 4 self.scraper...
def decode_netout(netout, anchors, obj_thresh, net_h=416, net_w=416): grid_h, grid_w = netout.shape[:2] nb_box = 3 netout = netout.reshape((grid_h, grid_w, nb_box, -1)) nb_class = netout.shape[-1] - 5 boxes = [] netout[..., :2] = _sigmoid(netout[..., :2]) netout[..., 4:] = _sigmoid(netout[.....
The main task of the code is to process YOLO model outputs by decoding bounding boxes, adjusting their dimensions to match the input image, applying non-max suppression to eliminate overlapping boxes, and returning the final detected objects' coordinates, labels, and confidence scores.
def yolo_decode_boxes(yhat, class_threshold, image_h, image_w, input_h=416, input_w=416): boxes = list() for i in range(len(yhat)): # decode the output of the network boxes += decode_netout(yhat[i][0], anchors[i], class_threshold, input_h, input_w) # correct the sizes of the bounding boxes ...
def simple_lda_model_training(input_matrix: csr_matrix, logger_: logging.Logger) -> LatentDirichletAllocation: """ A very simple LDA model. """ logger = logger_.getChild("simple_lda_model") logger.debug("Initializing LDA Model...") lda_model = LatentDirichletAllocation(n_components=NUM_TOPICS, v...
The code performs topic modeling on a document corpus using Latent Dirichlet Allocation (LDA). It loads documents, converts them into TF-IDF vectors, and trains both batch and online LDA models to identify topics. Results are processed and logged, with topic distributions saved for analysis. The main task is to analyze...
def driver(logger_: logging.Logger) -> None: """ DRIVER. """ logger = logger_.getChild("driver") documents = [" ".join(doc) for doc in get_corpus(logger)] logger.debug("Loading document vectors...") start = timer() # vectorizer, input_matrix = vectorize_count(logger, documents, save_matr...
def __mutation(self, genome: list) -> list: """Function to perform bit-wise mutation""" # Loop over all bits of the two genomes and flip bit to its opposite based on uniform distribution for idx in range(self.dim): if uniform(0,1) < self.Pm: genome[idx] = np....
This function executes a genetic algorithm generation by handling stagnation via mutation adjustment, performing selection, applying crossover (either ncrossover or unicrossover based on N), applying mutation, and evaluating the new population's fitness, returning updated population and fitness values.
def __newgeneration(self, pop: list, fitness: list) -> list: """Function to perform all operators of the GA, this includes the stagnation emergency case""" # EMERGENCY CASE WHEN STAGNATION if (self.cached > self.pop_size*3) and (self.Pm == 0): self.cached = 0 ...
def set_hyper_parameters(problem_id: int): if problem_id == 18: # Set hyperparameters specific to problem F18 return { "mu": 5, "lambda_": 100, "stagnation_threshold": 10, "threshold_divisor": 3, "initial_mutation_rate": 1.0, "m...
The main task of the code is to implement an evolutionary strategy (ES) algorithm with dynamic mutation rate adjustment and restart mechanisms. It evolves a population through recombination, mutation, and selection, dynamically increasing or decreasing the mutation rate based on stagnation thresholds. If stagnation is ...
def s3490750_s3739759_ES(problem, run, fid): """The main function implementing the evolutionary strategy.""" # Set hyperparameters params = set_hyper_parameters(fid) mu_ = params["mu"] lambda_ = params["lambda_"] stagnation_threshold = params["stagnation_threshold"] threshold_divisor = param...
def __initialization(self) -> list: """Function to initialize the population of the GA""" pop = [self.__creategenome() for _ in range(self.pop_size)] return pop def __evaluategeneration(self, pop: list) -> list: """Function to evaluate a population of a generation""" ...
The main task of the code is to train a Genetic Algorithm by initializing a population, evaluating its fitness, and iteratively generating new generations until the evaluation budget is exhausted. It first verifies that tunable parameters are set, then proceeds with population initialization and fitness assessment. The...
def main(self): """Function to perform training of the Genetic Algorithm""" # Check if tuneable parameters are set if self.params == False: raise InterruptedError("Please first set the parameters for the model with class.setparameters()!") # initialize popul...
def greedy(self, time_allowance=60.0): # Get all the cities and the number of cities cities = self._scenario.getCities() ncities = len( cities ) approx = self.defaultRandomTour() cost = np.inf route = approx['soln'] # Decides whether we skip checking the solutio...
The code implements a branch-and-bound algorithm for solving the Traveling Salesman Problem (TSP). It initializes counters, generates an approximate solution via a greedy method, constructs a reduced cost matrix, and explores potential paths using a priority queue. Nodes are expanded iteratively, pruning suboptimal bra...
def branchAndBound( self, time_allowance=60.0 ): # Reset the global values self.max_queued = 0 self.total_nodes = 0 self.soln_cnt = 0 self.pruned = 0 # Get the cities and tyhe number of cities cities = self._scenario.getCities() ncities = len(cities) ...
def generate_power_plot(self, axes): self.q = self.c.get_value() * self.emf self.i = 0 return axes.plot(lambda t: self.get_power_and_energy()[0], [0, self.delta.get_value(), self.dt]).set_color(RED) def generate_energy_plot(self, axes): self.q = self.c.get_value() * self.emf self...
The main task of the code is to create an interactive visualization demonstrating the parametric effect on energy, using dynamically updated graphs, equations, and real-time values to illustrate relationships between inductance, current, and energy over time.
def construct(self): # --- Axes --- axes = Axes( x_range=[self.start.get_value(), self.time.get_value()+0.00001,self.time.get_value()], y_range=[-0.001, 0.001], x_length=10, axis_config={"color": WHITE}, x_axis_config={"numbers_to_include": np.arange...
def gen_naive_solution(points_list): num_drivers = len(points_list) solution = [] for i in range (1, num_drivers + 1): list = [int(i)] solution.append(list) return solution def calc_route_cost(points_list, route): total_distance = 0.0 home = Point(0.0,0.0) current_point = hom...
The code generates an initial solution for a routing problem by first creating a naive solution, sorting it by route cost, and then merging routes to reduce the number of required drivers while adhering to constraints. It iteratively combines routes if they meet the annealing constraint, eliminating redundant drivers t...
def gen_starting_solution(points_list): initial = gen_naive_solution(points_list) initial = sorted(initial, key = lambda x: calc_route_cost(points_list, x)) # try to combine the smallest bins to the smallest to eliminate drivers initial_bin = 0 for idx, route in enumerate(initial): if initi...
def calc_solution_cost(points_list, solution): total_cost = 0.0 for route in solution: total_cost += calc_route_cost(points_list, route) total_cost += 500*len(solution) return total_cost def switch_or_add_new(points_list, solution): solution_copy = copy.deepcopy(solution) p_switch = 0.7...
The code implements a Simulated Annealing algorithm to optimize a solution represented by `starting_sol`, aiming to minimize the cost calculated by `calc_solution_cost`. It iteratively generates new states via swapping, adding, or shuffling points, accepts worse solutions probabilistically based on temperature, and upd...
def simulated_annealing(points_list, num_iter, starting_sol): initial_temp = 200.0 cooling_rate = 0.01 current_state = starting_sol current_score = calc_solution_cost(points_list, current_state) p_shuffel_all = 0.3 best_state = current_state best_score = current_score new_state = [] ...
def check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mouse_x, mouse_y): """ Start a new game when the player clicks Play """ button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) if button_clicked and not stats.game_active: # Play button is that the button region on th...
This function handles user input events in a game, including quitting the game, detecting mouse clicks to start gameplay, and processing keyboard presses/releases to control the ship's movement. It checks for mouse position to trigger the play button and delegates key events to separate functions for movement logic.
def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets): """ Respod to keypresses and mouse events. """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # To use the mouse. mouse_x, mouse_y = pygame.mouse.get_pos()...
def check_fleet_edges(ai_settings, aliens): """ Respond appropriately if any aliens have reached an edge """ for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): """ Respond to ship being hit ...
This function updates alien positions by checking fleet edges and moving aliens. It detects collisions between the ship and aliens, triggering a ship-hit response, and checks if aliens reach the screen bottom, initiating game-over logic.
def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): """ Check if the fleet is at an edge, and then update the positions of all the aliens in the fleet. """ check_fleet_edges(ai_settings, aliens) # Check if any alien are at an edge. aliens.update() # Look for alien-ship collisions. """ akes t...
def uninstall(LOCAL_DIR: str = LOCAL_DIR): print(f"uninstall {NAME} {VERSION}") for path in [ LOCAL_LIB_DIR(LOCAL_DIR), USR_ICON, LOCAL_SHARE_SHORTCUT(LOCAL_DIR), USR_SHORTCUT, USR_APP, ]: _remove(path) def _live_view(process: subprocess.Popen): while pro...
This function installs a software package by downloading a source file, extracting it to a local directory, and creating necessary links. It checks the platform, handles uninstallation based on root privileges, validates download responses, and executes installation steps conditionally. The process includes error handl...
def install(LOCAL_DIR: str = LOCAL_DIR): print(f"platform: {platform.platform()}") local_lib_dir = LOCAL_LIB_DIR(LOCAL_DIR) print(f"Start install {NAME} {VERSION} on {local_lib_dir}") if IS_ROOT: uninstall(LOCAL_DIR) else: _live_view(_run_command(*BASE_COMMAND, "uninstall", LOCAL_D...
def parse_fontFamily(textStyle): fontFamily = None if 'weightedFontFamily' in textStyle and 'fontFamily' in textStyle['weightedFontFamily']: fontFamily = textStyle['weightedFontFamily']['fontFamily'] return fontFamily def add_end(text, add_text): idx = find_rindent(text) if idx: text...
This function recursively processes structural elements of a document to convert text, tables, footnotes, and images into markdown format, handling nested elements, formatting styles, code blocks, and inline objects while updating global variables for document structure and content.
def read_strucutural_elements(document, elements, current_text, current_footnotes_text, tblscsr): global md_doc_global, table_counter, para, namedStyleType, testStyle, Dcount, urls_map, fenced_flag, code_flag, bullet_flag, footnote_flag, nestinglevel,final_dir_bm, image_stats, scan """Recurses through a list o...
def define_vars(self) -> None: """ Defines the variables used in the update target requirements window. """ self.min_uppers_optionmenu_var = ctk.StringVar( value=self.password_target.min_uppers ) self.min_lowers_optionmenu_var = ctk.StringVar( val...
This method configures a top-level GUI window for updating requirements, setting its size, title, and initializing UI components like frames, buttons, option menus, and labels through helper methods. It organizes the interface to facilitate user interaction with requirement management features.
def set_up_toplevel_window(self) -> None: """ Sets up the toplevel window. """ self.window.geometry("400x650") self.window.title("Update requirements") self.window.frame_1 = ctk.CTkFrame(master=self.window) self.define_vars() self.set_up_buttons() ...
def generate_key(): p = random.choice(prime_list) q = random.choice(prime_list) while p == q: q = random.choice(prime_list) n = p*q # calculate euler function phi(n) phi = (p-1) * (q-1) # Choose an integer e that is relative prime with phi(n) e = random.randint(1, phi) while ...
The main task of the code is to demonstrate RSA encryption and decryption. It generates a public-private key pair, encrypts a message ("Hi") using the public key, and decrypts the result with the private key, showcasing secure message transmission through asymmetric cryptography.
def main(): public_key, private_key = generate_key() print(public_key, private_key) message = "Hi" print(message) encrypted_message = encryption(message, public_key) print('Here is the encrypted message: ', end = '') print(encrypted_message) received_message = decryption(encrypted_messag...
def _clear_ob(self, dark=False): ''' clears the order book note: only clears the outstanding orders coming from the file and any dummy orders, any outstanding orders placed by the actor will remain ... ''' if dark: clear_orders = self.dark_orders...
The main task of the code is to update the limit order book (LOB) by clearing outdated orders, incorporating historical trades to simulate market impact, and integrating bid/ask prices from a LOB snapshot. The sequence ensures accurate state management by first removing old data, applying impact adjustments, and finall...
def _set_ob(self): ''' sets the new lob by performing the following 1. clear the old instance of the limit order book ... only keeping outstanding orders from the actor 2. add the historical trades that were completed by the actor ... to approximate her market impact 3. add t...
def _set_ob(self): ''' sets the new lob by performing the following 1. clear the old instance of the limit order book ... only keeping outstanding orders from the actor 2. add the historical trades that were completed by the actor ... to approximate her market impact 3. add t...
The code resets the environment's state for a new episode by selecting a random ticker, initializing order book data, adjusting time and volume parameters, resetting counters, and reinitializing tracking structures like order/trade histories and visual components. It prepares the environment for simulation by returning...
def reset(self): ''' resets the state of the environment ''' # limit order book data for a randomly sampled ticker self.ticker = random.choice(self.tickers) ob = self.lobs[self.ticker] # reset the counter self.current_step = 0 # cutoff point, when the last trad...
def _cancel_orders(self, orders=None): ''' cancels the actor's outstanding orders ''' if orders is None: active_orders = self.order_history.loc[self.order_history['active'] == True] else: active_orders = orders # cancel the active orders specified ...
The code processes an agent's action in a trading environment by updating the limit order book, managing dark orders, executing trades, calculating immediate and delayed rewards, and determining episode termination conditions such as step limits or inventory liquidation. It maintains state transitions, tracks time step...
def step(self, action): # if the action involves a cancel, clear the outstanding orders BEFORE we update the book ... if action[0] in [2, 3]: self._cancel_orders() # update the lob and accumulate delayed rewards self._set_ob() # add dark orders to the book ... these...