dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def incrementAmount(self): if not self.hidden: self.amount.set(self.amount.get() + 1 * self.incrementMultiplier) def decrementAmount(self): if not self.hidden: if self.amount.get() > 0: self.amount.set(self.amount.get() - 1 * self.incrementMultiplier) def bind(sel...
This code initializes a UI component with an image, amount label, and optional controls. It sets up attributes for positioning, scaling, and interactivity, creates visual elements on a canvas, and binds mouse events for editing and scrolling. The main task is to create a customizable, interactive image element with dyn...
def __init__(self, parent, scale, material, x, y, labelHeight, var, editable = True, scrollable = False, incrementMultiplier = 1, additionalLabels = []): self.parent = parent self.material = material self.scale = scale self.x = x self.y = y self.labelHei...
def validate_connect_input(self): view = self.view # validate tcp host if view.is_tcp and not view.is_valid_tcp_host: view.focus_tcp_host() view.show_error('*Enter valid tcp host') return False # validate visa resource if view.is_visa and not...
The code's main task is to establish a connection by first clearing errors, validating input, and then delegating to either TCP or VISA connection methods based on the view's protocol setting. It returns the result of the chosen connection method or False if validation fails.
def connect(self): # clear error messages self.view.clear_error() # validate input if not self.validate_connect_input(): return False # connect if self.view.is_tcp: return self.connect_tcp() else: return self.connect_visa()
def update_view(self): model = self.model view = self.view # update settings view.is_tcp = model.connection_method == 'tcp' view.tcp_host = model.tcp_host view.visa_resource = model.visa_resource view.delay_s = model.delay_s view.displa...
This code initializes a GUI application by setting up the model and view, configuring the window title with a version number, loading saved settings, attempting a connection, connecting signals/slots for interactivity, and displaying the view.
def __init__(self, model, view): # save model, view self.model = model self.view = view # set window title view.title = f'R&S Trace History GUI v{VERSION}' # load saved settings model.load_settings() self.update_view() # connect? self....
def populate_title_by_genre_urls_to_crawl(self) -> bool: self.log.info("Parsing title-by-genre listing page URLs.") for slug in self.db.get_platforms_without_genre_crawl_urls(): platform_home_url = f"https://www.metacritic.com/game/{slug}" html = self.web.fetch(platform_home_url)...
The main task of the code is to systematically crawl and process game data by first collecting URLs for title-by-genre listings, recording final page numbers, extracting game titles, and then gathering game details and reviews (user and critic) from incomplete database entries, iterating until all data is fully crawled...
def main(self): self.populate_title_by_genre_urls_to_crawl() self.log.debug("All title-by-genre listing page URLs present in database.") run = True while run: final_page_crawl = self.db.get_one_incomplete_last_page_crawl() if not final_page_crawl: ...
def load_tree(self) -> None: """Load tree from list representation, including parent node pointers.""" self.root = self.load_node(self.root, self.number) self.parent_fix(self.root) def explode(self): """Apply explosion to found exploder node.""" # get node to 'explode' ex...
The code defines the `__add__` method to handle custom addition between two instances. It merges their `number` attributes, rebuilds the tree structure, and repeatedly applies `explode` and `split` operations until the tree is normalized. Finally, it updates the number from the processed tree and returns the modified i...
def __add__(self, other): self.number = [self.number, other.number] self.load_tree() while self.explode() or self.split(): self.update_number_from_tree() continue return self
def update_base_count(base, count, base_counts): """Increase the 'base_count' for the given 'base' by 'count'.""" if base not in base_counts: base_counts[base] = count else: base_counts[base] += count return base_counts def get_pairs(polymer): """For a list of characters (a polymer),...
The code simulates polymerization over a specified number of steps using given rules, tracking character and pair counts. It initializes counts from a template, iteratively updates them via the 'step' function, and returns the difference between the most and least common base counts.
def run_simulation(num_steps, rules, template): # Initialise rules lookup rules = {rule[0]: rule[1] for rule in rules} # Initialise base counts (the count of each character in the full polymer) base_counts = {} for base in template: base_counts = update_base_count(base, 1, base_counts) ...
def is_feasible_component(self, component): for node in component: if self.node_splex[node - 1] != 1: return False return True def get_possible_non_splex_node_connections_in_component(self, i): "get list of edges in component of i of which at least one is not splex" ...
The main task of the code is to add edges to a graph component to ensure feasibility by prioritizing cheaper non-splex edge pairs over splex ones. If infeasible, it iteratively adds edges from a pool of missing connections, randomizing processing order when 'construct' is True. The loop continues until nodes meet degre...
def add_edges(self, component_set, construct=False): ''' Process a component that needs to have edges added. construct flag enables randomization of processing order to generate different solutions. Check pool of edge pairs that are both not in splex status first, if those are cheaper than splex...
def get_component_required_degree(self, component): check = len(component) - self.instance.s if check < 1: check = 1 return check def add_edges(self, component_set, construct=False): ''' Process a component that needs to have edges added. construct flag enables random...
The function `repair_component` adjusts a graph's component by either adding or removing edges based on a threshold comparison between the component's average degree and required degree, or a 50% random chance. If the average degree exceeds the threshold-multiplied required degree, or a random condition is met, edges a...
def repair_component(self, component, construct=False): required_degree = self.get_component_required_degree(component) avg_degree = self.graph.get_component_avg_degree_from_component(component) if avg_degree > self.instance.parameters["threshold"] * required_degree or randint(0, 1) == 1: ...
def compute_fitness(self): "higher number is better" return 1000/(self.cost + self.node_splex.count(0) * self.instance.parameters["penalty"]) def is_feasible_solution(self): for node in range(1, self.instance.n + 1): if self.node_splex[node - 1] != 1: return False ...
The main task of the code is to construct a feasible solution by iteratively checking components of a graph, repairing any infeasible components through shuffling and targeted repairs, until the entire solution meets feasibility criteria. The process computes initial fitness, identifies infeasible components, and appli...
def construct(self): self.fitness = self.compute_fitness() while not self.is_feasible_solution(): components = list(self.graph.get_components()) shuffle(components) # print(components) for component in components: # print(f"Checking {compon...
def build_send_payload(self, message): msg_dict = self._build_standard_message_dict(message) self._add_mailjet_options(message, msg_dict) if getattr(message, 'alternatives', None): self._add_alternatives(message, msg_dict) self._add_attachments(message, msg_dict) r...
This function sends an email via Mailjet by constructing a payload, posting it to Mailjet's API, and parsing the response. It checks for recipients, handles errors silently or raises them, and updates the message object with the Mailjet response. It returns True on success or False if no recipients or errors occur.
def _send(self, message): message.mailjet_response = None if not message.recipients(): return False try: payload = self.build_send_payload(message) response = self.post_to_mailjet(payload, message) message.mailjet_response = self.parse_response(...
def search(self, root, val): if root.item == val: return self.splay(root, root.parent) elif root.item < val and root.right != None: return self.search(root.right, val) elif root.item > val and root.left != None: return self.search(root.left, val) else:...
This code deletes a node with the specified value from a tree. It handles cases where the node has no children, one child, or two children. For two children, it finds the maximum node in the left subtree, splays it, and reconnects the right subtree. The function returns the updated root of the tree after deletion.
def delete(self, root, value): temp = self.search(root, value) if temp == False: return root root = temp t1 = root.left t2 = root.right root = None if t1 is None and t2 != None: t2.parent = None return t2 elif t2 is None...
def cache_scibert(model_type, cache_folder='~/.cache/torch/transformers'): if not model_type.startswith('scibert'): return model_type underscore_model_type = model_type.replace('-', '_') cache_folder = os.path.abspath(cache_folder) filename = os.path.join(cache_folder, underscore_model_type) ...
The main task of the code is to compute and visualize the BERTScore similarity matrix between a candidate sentence and a reference sentence. It tokenizes inputs, generates contextualized BERT embeddings, normalizes them, calculates pairwise token similarities, and plots the results as a heatmap. Optional rescaling with...
def plot_example(self, candidate, reference, model_type=None, num_layers=None, lang=None, rescale_with_baseline=False, fname=''): """ BERTScore metric. Args: - :param: `candidate` (str): a candidate sentence - :param: `reference` (str): a reference s...
def steepest_descent(x, func, grad, mu, penalty, epsilon=1e-3): record = [x] epoch = 0 max_iter = 100 while epoch < max_iter: k = -grad(x, mu, penalty) alpha = goldstein(func, grad, mu, penalty, x, k) x = x + alpha * k record.append(x) if np.linalg.norm(k) < eps...
This function performs iterative optimization using a penalty method. It applies steepest descent to minimize a function with constraints, adjusting the penalty parameter (mu) multiplicatively by rho each iteration. The process repeats up to 6 times, returning the estimate when the gradient's norm falls below a thresho...
def penalty_function(x, rho, penalty, tau=1e-5): mu = 1 epoch = 0 max_iter = 6 while epoch < max_iter: x_estimate = steepest_descent(x, func, grad, mu, penalty, epsilon=1e-3)[-1] grad_estimate = grad(x_estimate, mu, penalty) print("---Iteration: {}---".format(epoch + 1)) ...
def count_cards(running_count, state): player_hand = state.player_hand dealer_hand = state.dealer_hand if state.hand_over: if len(player_hand) > 2: running_count += calc_running_total(player_hand[2:]) running_count += calc_running_total(dealer_hand[1:]) ...
This function updates Q-values using temporal difference learning in a reinforcement learning context. It adjusts Q-values based on reward and next state's Q-value, applying a discount factor. If the next state is terminal, it directly updates the Q-value with the reward. Otherwise, it calculates the TD target and erro...
def q_update(superState, action, reward, nextState, running_count): action = actions.index(action) running_count, true_count, decks_remaining = count_cards(running_count, nextState) statekey = find_key(superState, action) if nextState.hand_over: q_vals[statekey] += (alpha_val...
def compute_isolated_eye(self): region = np.array([(self.landmarks.part(self.points[0]).x, self.landmarks.part(self.points[0]).y), (self.landmarks.part(self.points[1]).x, self.landmarks.part(self.points[1]).y), (self.landmarks.part(self.points[2]).x, self.la...
The code evaluates eye thresholds by selecting left or right eye landmarks based on the 'side' attribute, computes isolated eye data, checks if sufficient threshold data exists across frames, evaluates thresholds if necessary, and retrieves the final threshold value for analysis.
def eval_eye(self): if not self.side: self.points = self.LANDMARKS_LEFT_POINTS elif self.side: self.points = self.LANDMARKS_RIGHT_POINTS self.compute_isolated_eye() if not ( len(self.tresholds_left) >= self.nb_frames and len(self.treshold...
def _newer_requires_files(egg_info_dir): """Check to see if any of the requires files are newer than egg-info.""" for target, sources in (('requires.txt', get_requirements_files()), ('test-requires.txt', TEST_REQUIREMENTS_FILES)): target_path = os.path.join(egg_info_dir, targ...
The main task of the code is to prepare and update the package's egg-info directory by checking its existence and required files' freshness. If outdated or missing, it generates the egg-info, installs test requirements, and copies them to the directory, ensuring proper setup for package distribution and testing.
def pre_run(self): self.egg_name = pkg_resources.safe_name(self.distribution.get_name()) self.egg_info = "%s.egg-info" % pkg_resources.to_filename( self.egg_name) if (not os.path.exists(self.egg_info) or _newer_requires_files(self.egg_info)): ei_cmd = self...
def move(self, creature, xDist, yDist, time): self.matrix[creature.x, creature.y, time + 1] = Water() if xDist != 0: creature.moveX(xDist) if yDist != 0: creature.moveY(yDist) self.matrix[creature.x, creature.y, time + 1] = creature def eat(self, lists, pos): ...
This function checks if a creature can move in a specified direction, handling boundary collisions and interactions with other creatures or food. If movement is valid, it updates the creature's position; if encountering food (type 3), it processes eating, nutrient calculation, and logs the event. Movement is blocked fo...
def move_Check(self, creature, xDist, yDist, time, genome): if xDist == 0 and yDist == 0: self.move(creature, 0, 0, time) return #check position for type targetX = creature.x + xDist targetY = creature.y + yDist if targetX >= self.maxX or targetX < 0 or t...
def relu_back(Z): return (Z > 0) * 1 def swish_back(Z): return swish(Z) + sigmoid(Z) * (1 - swish(Z)) def sigmoid_back(Z): return sigmoid(Z) * (1 - sigmoid(Z)) def tanh_back(Z): return 1 - np.power(np.tanh(Z),2)
The function performs backpropagation to compute gradients of weights and biases in a neural network. It iterates through layers in reverse order, calculating derivative of loss (dZ) using activation functions (ReLU, Swish, sigmoid, tanh, softmax), then computes dW, db, and dA for each layer. Gradients are stored in a ...
def back_prop(params, cache, activations, Y): W = params["weights"] L = len(W) m = Y.shape[1] grads = {} for i in reversed(range(L)): # ==========dZ=========== if activations[i] == "relu": dZ = dA * relu_back(cache["Z" + str(i + 1)]) elif activations[i] == "swis...
def relu_back(Z): return (Z > 0) * 1 def swish_back(Z): return swish(Z) + sigmoid(Z) * (1 - swish(Z)) def sigmoid_back(Z): return sigmoid(Z) * (1 - sigmoid(Z)) def tanh_back(Z): return 1 - np.power(np.tanh(Z),2)
This function performs backpropagation with L2 regularization in a neural network. It computes gradients for weights (dW) and biases (db) for each layer by iterating backward through the network, applying activation derivatives to calculate dZ, adding L2 regularization terms, and propagating gradients to previous layer...
def back_prop_L2(params, cache, activations, Y,lambd): W = params["weights"] L = len(W) m = Y.shape[1] grads = {} for i in reversed(range(L)): # ==========dZ=========== if activations[i] == "relu": dZ = dA * relu_back(cache["Z" + str(i + 1)]) elif activations[i]...
def params_init(X, layer_dims): # L = number of layers (not counting input) L = len(layer_dims) # insert the input layer size to make things easier layer_dims.insert(0, X.shape[0]) weights = {} biases = {} np.random.seed(1) # - randomize weights and multiply them by np.sqrt(1./layer_di...
This function trains a neural network with specified layer dimensions and activation functions using mini-batch gradient descent or Adam optimizer. It initializes parameters, performs forward/backward propagation with optional L2 regularization, updates weights via chosen optimizer (with learning rate decay), and saves...
def train(X, Y, layer_dims, activations,learning_rate=0.0075,lambd=0.0, epochs=1, mini_batch_size=32, beta1=0.9, beta2=0.999,epsilon=1e-8, optimizer="gd", lr_decay=0.0005, report=False,save=False): # list of costs (for debugging) # costs = [] # seed for epoch randomization seed = 1 ...
def retrieve_input(self): input_val = self.textBox.get("1.0",END) try: input_val = int(input_val) except: self.write('please input an intiger') self.window.mainloop() input_val = 0 if input_val < 0 or input_val > int(self.max_index): self.write('please enter a value between 0 and {}'.format(self....
This code initializes a GUI for video labeling, supporting 'single' and 'duo' modes. It sets up a canvas to display video frames, buttons for navigation/playback, dropdowns for label selection, frame sliders, and a console. It binds keypresses, loads video data, and prepares label dictionaries for annotation. The inter...
def __init__(self, root, video_path, csv_path, labels_csv, mode): self.video_path = video_path self.fps = cv2.VideoCapture(video_path).get(cv2.CAP_PROP_FPS) self.csv_path = csv_path self.mode = mode if self.mode == 'single': self.labels = get_labels_single(labels_csv) self.CLASSES = self.labels.label...
def nxt(self): #move to previous image if self.current_index == self.max_index: self.update_all() else: self.current_index +=1 self.update_all() def prev(self): #move to next image if self.current_index == 0: self.update_all() else: self.current_index -=1 self.update_all() def write(self, ...
This code handles keyboard events to navigate frames, select start/end frames for labeling, and submit/cancel selections. It uses states (0, 1, 2) to track selection progress: space selects start (state 0→1), then end (state 1→2); Enter submits the label (state 2) by calling make_label(); Escape cancels selections, res...
def key_pressed(self,event): if event.keysym == 'Right': self.nxt() if event.keysym == 'Left': self.prev() if event.keysym == 'space': if self.current_state == 0: self.start_frame = self.current_index self.write('selected a start frame, press space to select end frame or esc to cancel selection')...
def royal(self,hand_value,hand_suit): if self.straight_flush(hand_value,hand_suit) and hand_value[0]==10: return True def straight_flush(self,hand_value,hand_suit): if self.straight(hand_value) and self.flush(hand_value,hand_suit): return self.selfstraight(hand_value) els...
This code evaluates a 5-card poker hand by determining its rank (e.g., straight flush, four of a kind) and returning a tuple with the rank priority and relevant value. It processes card values, checks for specific hand types in descending priority, and returns results like (10,10) for royal flush or (1, [high cards]) f...
def eval(self): values = {'A': 14, 'K': 13, 'Q': 12, 'J': 11, 'T': 10} hand_value=[] hand_suit = [] for i in range(5): if self.cards[i][0] in values: val = values[self.cards[i][0]] else: val = int(self.cards[i][0]) han...
def resetGame(self, master, commentry, player_cash_label, ai_cash_label,AI_card_space): deck = Deck() hand_AI = Hand(deck) hand_human = Hand(deck) reset_text = "Select retainable cards" commentry.config(text=reset_text) human_card_space = [tkinter.Label(master) for i in...
This code initializes a graphical user interface (GUI) for a simple five-card draw poker game using tkinter. It sets up the game window, displays player and AI cash, renders card slots, allows users to select discardable cards via checkboxes, and includes buttons to draw cards or reset the game. The main task is to cre...
def mainGame(self): master = tkinter.Tk() master.title('Simple Five-Card Draw') deck = Deck() hand_AI = Hand(deck) hand_human = Hand(deck) commentry = tkinter.Label(master, text="Select Retainable Cards") commentry.grid(row=1, column=0, columnspan=5) pla...
def is_valid_ip_format(ip): # Utilizza una regex per controllare il formato: valore.valore.valore.valore maschera ip_pattern = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \d{1,2}$" return re.match(ip_pattern, ip) is not None def is_valid_ip(ip): # Divide l'indirizzo IP e la maschera e verifica i valori va...
The main task of the code is to validate a user-input IP address for a network interface. It repeatedly prompts the user to enter an IP address in the format "valore.valore.valore.valore maschera," checking its format and validity using helper functions. If valid, it configures the router interface and exits the loop; ...
def convalidaIP(numerodiporte): router1 = Router(None, None) interfaccia1 = Interfaccia(None) while True: ip_interfaccia = input(f"Inserisci l'indirizzo IP dell'interfaccia (valore.valore.valore.valore maschera) per l'interfaccia GigabitEthernet: ") if is_valid_ip_format(ip_interfaccia) and...
def forward(self, X): self.reset() self.AL.append(X) for i in range(self.n-1): wm = self.WML[i+1] b = self.BL[i+1] z = np.matmul(self.AL[i], wm) + b a = squish(z) fp = squishprime(z) self.AL.append(a) se...
The code performs a single batch training step by computing forward pass outputs, calculating gradients via backward propagation using target labels Y, and updating model weights with learning rate alpha.
def batchTrain(self, X, Y, alpha): self.forward(X) self.backward(Y) self.updateWeights(alpha)
def get_target(self, pacman_pos, pacman_direction, blinky_pos): pass def kill(): pass def move(self, selected_algorithm): # Increment the move counter and check if it'st time to move self.move_counter += 1 if self.move_counter < 3: # Adjust this number for different speeds ...
This code updates a ghost's movement logic in a Pac-Man game. If the ghost is frightened, it randomly selects a target node; otherwise, it determines a target based on Pac-Man's position and direction. It checks if the ghost collides with Pac-Man by comparing tile positions. If so, the ghost is removed (killed). Finall...
def update(self, pacman_pos, pacman_direction): if self.frightened: self.target = random.choice(self.nodes) else: self.target = self.get_target(pacman_pos, pacman_direction) x, y = self.rect.topleft[0] // TILE_SIZE, self.rect.topleft[1] // TILE_SIZE current_tile2 ...
def solve1(): tiles = parse() borders = {} for n, t in tiles.items(): # all possible borders for each tile borders[n] = set.union(*[set(get_borders(fl)) for fl in get_flips(t)]) graph = networkx.Graph() for i, j in itertools.combinations(borders, 2): # 2 adjacent tiles sha...
The code solves a tiling puzzle by determining the correct orientation of corner tiles, constructing a 12x12 grid of adjacent tiles, and then identifying the number of monster patterns in the assembled image to compute the final result by subtracting the monster count from the total hash sum.
def solve2(): corners, tiles, graph = solve1() for fl in get_flips(tiles[corners[0]]): grid = {(0, 0): (corners[0], fl)} place_adjacent_tiles_on_grid(grid, (0, 0), graph, tiles) # correct position of top left corner is found because we placed its adjacent tiles if len(grid) == 3:...
def updateUserBox(self, user): userId = user['platformUserIdentifier'] if user['platformSlug'] == "steam" else user['platformUserHandle'] searchUrl = "https://api.tracker.gg/api/v2/rocket-league/standard/profile/" + \ user['platformSlug']+"/"+userId+"?" userStatsResp = req.get(sear...
This code searches for and displays replays associated with a given user by clearing existing session data, updating the user interface with the current user, fetching replay data from Ballchasing, processing and displaying the results, refreshing a graph visualization, and adjusting the window size to fit the content.
def searchReplays(self, user): self.sessionListBox.delete(0, tk.END) self.updateUserBox(user) ballchasingResult = self.getReplaysFromBallchasing(user) self.processReplays(ballchasingResult['list'], user) self.refreshGraph() self.master.minsize(self.master.winfo_width...
def createCollapsible(self, collapsibleInfo, master): self.__setattr__(collapsibleInfo['name'], CollapsiblePane( master, collapsibleInfo['title'] + " <<", collapsibleInfo['title'] + " >>")) self.__getattribute__(collapsibleInfo['name']).grid( row=collapsibleInfo['gridpos'][0], co...
The main task of the code is to create and configure GUI widgets for a game application, including setting the window title, icon, and game stats label, dynamically generating collapsible sections or widgets based on a schema, and handling the window close event to trigger the onExit method.
def createWidgets(self): self.master.title(self.game.Date.strftime( "%d/%m: %H:%M: ") + self.game.mode) defaultIco = FileSystem.resource_path('icon.ico') self.master.iconbitmap(default=defaultIco) self.GameStatsBoxLabel = tk.Label( self, text="Game Stats") ...
def createSearchBox(self, master): self.UserSearchLabel = tk.Label( master, text="User to Search For:") self.UserSearchLabel.grid( row=0, column=0, sticky="nw", padx=2, pady=2) self.UserSearch = ttk.Combobox(master) self.UserSearch.bind('<KeyRelease>', self.check...
This code creates a GUI for a Rocket League stats application by setting up a window with a title/icon, a File menu, and multiple organized frames for search, user input, graph options, session data, and visualizations. It configures layout, initializes widgets, adjusts window sizing, and prepares components for dynami...
def create_widgets(self): self.master.title("Rocket League Stats") defaultIco = FileSystem.resource_path('icon.ico') self.master.iconbitmap(default=defaultIco) self.menu = tk.Menu(self) self.m_file = tk.Menu(self, tearoff=0) self.m_file.add_command(label="Exit", command=...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0, num_layers - 1): W = self.xavier_init(size=[layers[l], layers[l + 1]]) b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up two neural networks (layers1/layers2) to approximate a vector field (a) and conductivity (σ), using collocation points in subdomains and the full domain. Placeholders for input data, boundary con...
def __init__(self, X_quad, X_full, X_bdr, layers1, layers2, theta, normalx, normaly, normalz, f, g, dudxq, dudyq, dudzq): self.theta = theta self.xq = X_quad[:, 0:1] self.yq = X_quad[:, 1:2] self.zq = X_quad[:, 2:3] self.xf = X_full[:, 0:1] ...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0, num_layers - 1): W = self.xavier_init(size=[layers[l], layers[l + 1]]) b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a physics-informed neural network (PINN) to solve a partial differential equation (PDE) by combining neural networks for vector fields and conductivity. It sets up placeholders, initializes weights/biases, defines loss terms for PDE residuals, boundary conditions, and conductivity smoothness, then...
def __init__(self, X_quad, X_bdr, layers1, layers2, theta, n1, n2, n3, n4, n5, f, g, dudx1q, dudx2q, dudx3q, dudx4q, dudx5q): self.theta = theta self.x1q = X_quad[:, 0:1] self.x2q = X_quad[:, 1:2] self.x3q = X_quad[:, 2:3] self.x4q = X_quad[:, 3...
def check_suit(self): if len(self.hand_colors()) != 1: return False return True def check_for_sequence(self): for i in range(4): if self.hand_values()[i + 1] != self.hand_values()[i] - 1: return False return True def hand_values(self): va...
The code evaluates a poker hand to determine its type, checking for flushes, straights, and repeated card values. It prioritizes higher-ranking hands like Royal Flush, Straight Flush, and Four of a Kind, then lower ones like Pair or NONE, using conditional checks on suit consistency, sequential values, and repetition p...
def check_hand(self): if self.check_suit(): if self.check_for_sequence(): if self.hand_values()[0] == 14: return "ROYAL_FLUSH" return "STRAIGHT_FLUSH" return "FLUSH" else: if self.check_for_sequence(): ...
def get_neighbour(tiles, tile, matches, my_edge, edge_to_match): f = lambda data : data if get_edges(tiles[tile])[my_edge] == get_edges(data)[edge_to_match] else None for match in matches[tile]: new_data = apply_function_to_rotated_data(tiles[match], f) if new_data is not None: tiles...
This function orients a corner tile by rotating it up to four times and flipping it if necessary, ensuring its neighboring tiles (specifically in directions 3,2 and 1,0) are valid matches. It exits early if both neighbors exist, otherwise adjusts the tile's orientation through rotation and flipping to align with the gi...
def orient_corner(tiles, corner, matches): for __ in range(2): for _ in range(4): if get_neighbour(tiles, corner, matches, 3, 2) is not None and get_neighbour(tiles, corner, matches, 1, 0) is not None: return tiles[corner] = rotate(tiles[corner]) tiles[corner]...
def orient_corner(tiles, corner, matches): for __ in range(2): for _ in range(4): if get_neighbour(tiles, corner, matches, 3, 2) is not None and get_neighbour(tiles, corner, matches, 1, 0) is not None: return tiles[corner] = rotate(tiles[corner]) tiles[corner]...
The main task of the code is to construct an image by assembling tiles starting from a specified corner tile. It orients the corner, iteratively collects tile IDs in each row by moving rightward, clears edge data, stitches the tiles row by row, and returns the final assembled image as a list of stitched images.
def make_image(tiles, corner, matches): orient_corner(tiles, corner, matches) left = corner image = [] ids = [] while left is not None: ids.append(get_ids_in_row(tiles, left, matches)) left = get_neighbour(tiles, left, matches, 1, 0) clear_edges(tiles) print(ids) for row ...
def __solve_points(self, n_pairs): """Generates random points on the hypersurface with Monte Carlo #TODO explain the MC method or refer to the paper Args: -------- n_pairs: The number of random pair used in Monte carlo. Returns: -------- A list of ran...
The code initializes a hypersurface by generating points via Monte Carlo methods using `__solve_points()` and automatically defining patches with `__autopatch()`. It sets up coordinates, function, patches, and gradients, handling input points or generating them if unspecified. The class stores properties like dimension...
def __init__(self, coordinates, function, n_pairs=0, points=None, norm_coordinate=None, max_grad_coordinate=None): """Initialize the hypersurface Given the sympy coordinates Z, function f an...
def kahler_potential(self, h_matrix=None, k=1): sections, n_sec = self.get_sections(k) if h_matrix is None: h_matrix = np.identity(n_sec) # Check if h_matrix is a string elif isinstance(h_matrix, str): if h_matrix == "identity": h_matrix = np.ident...
The code computes the Kähler metric tensor by differentiating the Kähler potential. If no point is specified, it calculates the metric using holomorphic and anti-holomorphic derivatives of the potential with respect to affine coordinates, constructing a SymPy matrix from these derivatives. The result is a matrix repres...
def kahler_metric(self, h_matrix=None, k=1, point=None): if point is None: pot = self.kahler_potential(h_matrix, k) metric = [] #i holomorphc, j anti-hol for coord_i in self.affine_coordinates: a_holo_der = [] for coord_j in self.af...
def lookup(self,key): if(isinstance(key,int)): hashvalues=self.integerHashFunction(key) else: key = key.lower() hashvalues=self.stringHashFunction(key) if self.hashtable[0][hashvalues[0]] is not None and self.hashtable[0][hashvalues[0]][0]==key: return True if self.hashtable[1][hashvalues[1]] is not...
The code deletes a key from a hash table structure by checking its existence, computing hash values based on key type (integer/string), and removing the key from the appropriate hash table index or stash if found.
def delete(self,key): if self.lookup(key): if isinstance(key,int): hashvalues = self.integerHashFunction(key) else: key = key.lower() hashvalues = self.stringHashFunction(key) if self.hashtable[0][hashvalues[0]] is not None and self.hashtable[0][hashvalues[0]][0]==key: self.hashtabl...
def _crawl(self, start_dir: Path) -> list[Path]: """Generate recursive list of paths by crawling down every branch from the starting_dir.""" paths = [] print_in_place(f"Crawling {start_dir}...") for item in start_dir.iterdir(): if item.is_file(): paths...
The main task of the code is to generate a directory tree structure from a starting directory. It crawls the directory to collect file paths, clears redundant data, removes parent directory references, constructs the tree hierarchy, and converts it into a string representation for display or further processing.
def generate(self): self.paths.extend(self._crawl(self.starting_dir)) clear() self._drop_parents() self._generate_tree() self._generate_tree_string()
def remove_duplicate_tags(self): page_content = self.soup.find_all(self.filter) for dup in page_content: match dup.name: case self.htmlTag_ul: a_list_ul = dup.find_all(self.tag_a) for a_ul in a_list_ul: if a_ul ...
The main task of the code is to parse HTML content by extracting structured data from specific tags (like links, paragraphs, lists, etc.) and aggregating them into a dictionary. It processes elements from `page_content`, identifies their tag types, applies corresponding parsing methods, and updates the `all_content` di...
def parse_html_content(self): page_content = self.remove_duplicate_tags() all_content = {"Title": self.get_text(self.soup.title)} for s in page_content: match s.name: case self.tag_a: all_content.update(self.parse_a(s)) case self...
def parse_html_content(self): page_content = self.remove_duplicate_tags() all_content = {"Title": self.get_text(self.soup.title)} for s in page_content: match s.name: case self.tag_a: all_content.update(self.parse_a(s)) case self...
This code scrapes webpage data, saves it to a JSON file, tracks visited URLs, and recursively processes sublinks if enabled. It handles exceptions, quits the browser, and spawns new spiders for each sublink in the queue, ensuring efficient crawling and data storage.
def scrape_data(self): try: all_content = self.parse_html_content() self.write_data_to_json_file(all_content, self.output_file_name) all_visited_links.update({self.url: True}) if self.url in links_queue: links_queue.remove(self.url) ...
def _connect_stores(self) -> None: for store_class in self.stores: self._store_instances[store_class] = store_class(monitor=self) def _connect_sources(self) -> None: for source_class in self.sources: self._source_instances[source_class] = source_class(monitor=self) def _evaluate_...
The main task of the code is to initiate a monitoring process by connecting to data stores and sources, then evaluating predefined rules to detect or analyze events, likely for real-time decision-making or alerting.
def execute(self) -> None: """Start monitoring.""" self._connect_stores() self._connect_sources() self._evaluate_rules()
def read_data(self): self.final_list = {} for i in range(0, self.number_channels): self.final_list[i] = [] stops = set(stopwords.words('english')) # Load data set data_df = pd.read_csv(self.data_file, sep='\t') data_df = self.change_words_to_numbers(data_df, s...
The main task of the code is to prepare structured data for machine learning by splitting raw data into training, validation, and test sets, computing class-weighting schemes for imbalanced datasets, converting labels to NumPy arrays, loading feature data, verifying data consistency, and converting final data into PyTo...
def create_data(self): # Loading data and building vocabulary. data_df = self.read_data() X = data_df[self.final_name] Y = data_df[self.score_col] self.question_index = [] self.x_train, self.x_val_temp, self.y_train, self.y_val_temp = split_data(X, Y, train_size=self.tra...
def question_method1(self): """ First method: if a sentence end in ? it is a question """ number_sentences = 0 for comment in self.text: sentences = self.tokenize(comment) number_sentences = number_sentences + len(sentences) for se...
The code defines a pipeline method that selects and executes one of eight question-processing methods based on the input parameter `question_method`, then calls a printing function to output results. It acts as a dispatcher routing execution to specific question-extraction strategies, with each method likely handling d...
def pipeline(self, question_method): print("using question extraction method: " + str(question_method)) if question_method == 1: self.question_method1() elif question_method == 2: self.question_method2() elif question_method == 3: self.question_method3...
def create_voc_variable(self): self.number_to_word = {} self.word2index = {} for i in range(0, self.number_channels): self.word2index[i] = {} self.word2index[i]['PAD'] = 0 return def create_data(self): # Loading data and building vocabulary. data_d...
This code initializes a data processing class for text classification tasks, configuring parameters like data splitting ratios, feature inclusion (POS tags, medical terms, clusters), and vocabulary settings. It constructs input/output features based on flags, prepares training/validation data structures, and initialize...
def __init__(self, column_names, data_name, data_file, train_ratio=0.8, test_val_ratio=0.5, med_flag=2, weight_flag=0, seed=5, upos=False, umed=False, uad=False, qk=False, cluster_size=0, wordnet=False, class_number=3, vocab_limit=None): self....
def get_arguments(): parser = argparse.ArgumentParser(description="Playfair Cipher") parser.add_argument("m", type=str, help="Message") parser.add_argument("k", type=str, help="Key") args = parser.parse_args() return args def decode(ciphertext, key): key_table = get_key_table(key) bigrams = ...
The main task of the code is to encode a message `m` using a key `k` and then decode the result with the same key `k`, effectively demonstrating the encoding-decoding process. This likely verifies the correctness of the `encode` and `decode` functions by ensuring the decoded output matches the original message.
def main(): args = get_arguments() decode(encode(args.m, args.k),args.k)
def get_arguments(): parser = argparse.ArgumentParser(description="The Alphabet-Cipher, Lewis Carroll, 1868") parser.add_argument("m", type=str, help="Message") parser.add_argument("k", type=str, help="Key") args = parser.parse_args() return args def decode(key, ciphertext): repeated_key = get_r...
The main task of the code is to demonstrate encoding and decoding processes using a key. It first encodes input data `m` with key `k` via `encode()`, then decodes the result using the same key `k` via `decode()`, effectively showing how decoding reverses encoding operations. This likely illustrates encryption/decryptio...
def main(): args = get_arguments() decode(args.k, encode(args.k, args.m))
def get_arguments(): parser = argparse.ArgumentParser(description="Chaocipher - John F.Byrne - 1918") parser.add_argument("m", type=str, help="Message") args = parser.parse_args() return args def decode(ciphertext): plaintext = chaocipher_process(ciphertext, STARTING_LEFT, STARTING_RIGHT, False) ...
The main task of the code is to retrieve input arguments, encode a specific parameter (`args.m`), and then decode the encoded result, likely for data transformation or validation. The function processes input data through an encoding-decoding workflow to achieve a defined computational goal.
def main(): args = get_arguments() decode(encode(args.m))
def generate_dataset(Icase=1): xmin = 20. xmax = 230. func = TF1('func', ftrue, xmin, xmax, 3) func.SetParameters(0.01,1,0.2) Cs = TCanvas('Cs', '', 10, 10, 800, 600) func.Draw() func.GetXaxis().SetTitle('mass [GeV]') func.GetYaxis().SetTitle('Arbitrary Scale') Cs.SaveAs('Cs_func.png...
The main task of the code is to process datasets based on case and method parameters, prepare histograms for unfolding analysis, and execute the unfolding process. It dynamically sets grid dimensions (nx, ny) depending on Icase and Imethod, loads or generates ROOT files, constructs matrices (hA, hx, hb), and invokes th...
def main(Icase = 1, Imethod=1): filename = 'data_'+str(Icase)+'.root' if not os.path.isfile(filename): print('generate dataset ......................................................') generate_dataset(Icase) f = TFile(filename, 'read') tree = f.Get('nominal') nx = 30 ny = 30 ...
def unfold_core(self, sigtree, datatree, nsplit=-1, dotoymc=0): if self.debug: print('signal tree', sigtree, sigtree.GetEntries()) print('data tree', datatree, datatree.GetEntries()) if nsplit>=0: self.nsplit = nsplit binning = self.initbinning hb, b =...
The code generates toy Monte Carlo (toymc) samples by creating multiple TTree instances filled with random values from a histogram (hrec). It performs unfolding on each toy dataset, collects results, and computes a new Vx parameter using these results. The function handles edge cases like negative toy counts, writes ou...
def do_toymc(self, sigtree, hrec, hout0): print('We are doing toy mc...') if self.ntoys < 0: print('WARNING: ntoys < 0, set it to 1') self.ntoys = 1 nevents = int(hrec.Integral()) list_hout = [] toymcfile = TFile('toymcfile.root', 'recreate') for i...
def unfold_core(self, sigtree, datatree, nsplit=-1, dotoymc=0): if self.debug: print('signal tree', sigtree, sigtree.GetEntries()) print('data tree', datatree, datatree.GetEntries()) if nsplit>=0: self.nsplit = nsplit binning = self.initbinning hb, b =...
This function performs unfolding on signal and data trees by loading ROOT files, extracting histograms, and computing unfolded distributions. It generates reconstructed, true, and output histograms, optionally runs a toy Monte Carlo simulation, converts histograms to lists, and calculates covariance/correlation matrice...
def do_unfold(self, nsplit = -1): sigfile = TFile(self.sig_filepath, 'read') sigtree = sigfile.Get(self.sig_treename) datafile = TFile(self.data_filepath, 'read') datatree = datafile.Get(self.data_treename) if self.debug: print('tree, nentries =', tree.GetName(), tree...
def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def getExtension(inputFile): return '.' and inputFile.rsplit(".",1)[1].lower() def openPic(filenameAndExtenstion,userEmail,firstName,lastName,outgoingZip,encryptOrPlaintext): """ Thi...
The main task of this code is to handle file uploads, extract user form data, process the uploaded image into text/audio, encrypt it, send an encryption key via SMS, and clean up temporary files. It validates uploads, saves files, executes conversion/encryption functions, and ensures secure file handling and deletion a...
def upload_file(): uploaded_file = '' title = "Upload Image to Convert" if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['fil...
def print_field(self): for row in self.field: for cell in row: if cell is None: print(".", end="") else: print(cell.name[0], end="") print() def get_current_player(self): if self.turn == 1: return...
The code runs a game loop that continuously displays the game field, prompts the current player for commands, and processes actions like adding/moving units or ending the turn until the player quits.
def run(self): while True: self.print_field() player = self.get_current_player() print(f"{player.name}'s turn") command = input("Enter command: ") if command == "quit": break elif command == "add unit": self....
def print_field(self): for row in self.field: for cell in row: if cell is None: print(".", end="") else: print(cell.name[0], end="") print() def computer_turn(self, player): print(f"{player.name}'s turn") ...
The play method manages a game loop by printing the game field, handling turns for human and computer players, checking game-over status, and declaring the winner. It alternates turns until the game ends, then displays the winner's name and terminates the loop.
def play(self): while True: self.print_field() player = self.players[self.turn - 1] if player.is_computer: self.computer_turn(player) else: self.human_turn(player) if not self.is_game_over(): self.end_tur...
def stft_extraction(filepath, n_chunks): x, sr = librosa.load(filepath) s = np.abs(librosa.stft(x, n_fft=1024, hop_length=512, win_length=1024, window='hann', center=True, dtype=np.complex64, pad_mode='reflect')) #m, t, s = signal.stft(x, window='hann', nperseg=1025, noverlap=None, nff...
The function `feature_extraction` selects and applies a specified audio feature extraction method based on the `mode` parameter. It processes an audio file from `filepath`, divides it into `n_chunks`, and returns extracted features using techniques like STFT, CQT, or MFCCs, depending on the chosen mode. The main task i...
def feature_extraction(filepath, n_chunks, mode): if mode == 0: s = stft_extraction(filepath, n_chunks) elif mode == 1: s = complex_stft(filepath, n_chunks) elif mode == 2: s = cqt_extraction(filepath, n_chunks) elif mode == 3: s = mfccs_extraction(filepath) elif mode == 4: s...
def _get_random_pose(self,mark=False,idx=1): k = self.cfg["MAP_REDUCTION_FACTOR"] free_idx = np.argwhere(self.mini_map == 0) mini_r, mini_c = self.rng.choice(free_idx) r = k * mini_r + (k // 2) c = k * mini_c + (k // 2) if mark: self._set_mini_map(r,c,idx) ...
This function resets a multi-robot environment by randomizing robot and target positions/orientations, assigning random sensor competencies (Vel, FOV, Range), initializing a reduced-resolution map for path planning, advancing simulation steps, and resetting tracking variables. It returns the initial observation and set...
def reset(self, seed=None, options=None): for i in range(len(self.robots)): pose,ori = self._get_random_pose() self.client.resetBasePositionAndOrientation(self.robots[i], [*pose, 0.25], p.getQuaternionFromEuler([0, 0, ori])) vel = self.rng.random() fov = self.rng....
def _rc2minirc(self, r, c): k = self.cfg["MAP_REDUCTION_FACTOR"] return r // k, c // k def _xy2rc(self, x, y): r0 = self.cfg["HEIGHT"] / 2 c0 = self.cfg["WIDTH"] / 2 rc = np.array([x, -y]) / self.cfg["RESOLUTION"] + np.array([c0, r0]) return int(rc[1]), int(rc[0]) def _wr...
This code executes a reinforcement learning step for multi-robot navigation, using A* path planning to generate waypoints based on actions. It applies velocity and torque control to robots, detects collisions, simulates physics, and returns observations, rewards, and environment state updates.
def step(self, action): self.t += self.repeat self.path_lens = [] vels = [] for i in range(len(self.robots)): context_length = self.obs["context"].shape[0] // self.cfg["N_ROBOTS"] pose = np.array([self.obs["context"][context_length*i + 0], self.obs["context"][cont...
def get_status(self): self.stack = self.heatclient.stacks.get(self.stack.id) # check if any of deployments' child resource has last # event indicating that it has reached a breakpoint (this # seems to be the only way how to check pre-create breakpoints ATM) resources = self._reso...
The function `do_interactive_update` monitors an ongoing update process, waiting for it to complete or fail. When the status is 'WAITING', it lists affected resources and prompts the user to proceed, cancel, or specify references to clear. User input determines actions like continuing, rolling back, or exiting interact...
def do_interactive_update(self): status = None while status not in ['COMPLETE', 'FAILED']: status, resources = self.get_status() print(status) if status == 'WAITING': for state in resources: if resources[state]: ...
def getToken(refresh_token): token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token" token_data = { "grant_type": "refresh_token", "client_id": os.getenv("OUTLOOK_CLIENT_ID"), "client_secret": os.getenv("OUTLOOK_SECRET"), "refresh_token": refresh_token, } ...
The code retrieves upcoming calendar events from Microsoft 365 using the Graph API, paginating through results while filtering out recurring event masters. It processes each event, simplifying data for the specified user, and returns a list of formatted event objects.
def getEvents(profile): token, token_type = getToken(profile.calendar_token) headers={'Content-Type': 'application/x-www-form-url-encoded', 'Authorization': token_type + " " + token} all_events = [] max_loops = 100 while True: max_loops -= 1 if max_loops < 0: break ...
def _add_to_stack(self, element: "BaseElement") -> None: if self._stack: self._stack[-1].append(element) def _add_child( self, child: _T_child, *, idx: Optional[int] = None, idx_replace: bool = False, exit_context_manager: bool = False, ) -> "BaseE...
This code initializes an element with children, attributes, and DOCTYPE handling. It processes children, strips/renames attribute keys, validates empty elements, and sets internal state for rendering.
def __init__( self, *args: _T_child, _prepend_doctype: Optional[bool] = None, **kwargs: Optional[_T_attribute], ) -> None: """ Args: *args: The element's children. A `TextNode` is automatically created when passing anything other than a sub...
def _set_attribute(self, key: str, val: _T_attribute) -> None: key = self._clean_attribute_key(key) if ( not self.any_attribute and not key.startswith(("data-", "aria-")) and key not in self.all_attributes ): warnings.warn(exc.InvalidAttributeWarni...
This method handles item assignment for different key types: sets attributes for string keys, replaces children at specific indices for integer keys, and updates child slices by converting iterables to children, then removes them from the internal stack.
def __setitem__( self, key: Union[str, int, slice], val: Union[_T_attribute, _T_child, Iterable[_T_child]], ) -> None: if isinstance(key, str): val = cast(_T_attribute, val) self._set_attribute(key, val) elif isinstance(key, int): val = cas...
def get_high_card(self, id=0): return [sorted(self.cards)[-1 - id]] def is_royal(self): return self.is_flush() and self.is_straight(royal=True) def is_flush(self): cards = {} for card in self.cards: cards[card.suit] = cards.get(card.suit, 0) + 1 return max(cards.values()) == 5 def is_straight(...
This function determines the rank of a poker hand by sequentially checking for specific hand types from highest to lowest precedence (e.g., royal flush to high card). It updates `self.best` with relevant card combinations and returns an integer rank (1-10) based on the hand's value.
def get_rank(self): self.best = self.get_high_card() # royal flush 10 if self.is_royal(): return 10 # staight flush 9 flush = self.is_flush() straight = self.is_straight() if flush and straight: return 9 # four of a kind 8 if self.get_quadruple(): self.be...
def log(self, msg: str): """Log a message to unified log.""" NSLog(f"{APP_NAME} {__version__} {msg}") # if debug set in config, also log to file # file will be created in Application Support folder if self._debug: with self.open(LOG_FILE, "a") as f: f...
The code initializes a macOS application (Textinator) with menu bar functionality for text detection in images. It sets up configuration options, language support, clipboard monitoring, and toggles for features like QR code detection, notifications, and dark/light mode. The app loads settings from a plist file, registe...
def __init__(self, *args, **kwargs): super(Textinator, self).__init__(*args, **kwargs) # set "debug" to true in the config file to enable debug logging self._debug = False # pause / resume text detection self._paused = False # set the icon to a PNG file in the current ...
def log(self, msg: str): """Log a message to unified log.""" NSLog(f"{APP_NAME} {__version__} {msg}") # if debug set in config, also log to file # file will be created in Application Support folder if self._debug: with self.open(LOG_FILE, "a") as f: f...
This method processes notifications from a Spotlight query, handling events like query start, finish, progress, and updates. It logs status changes and triggers actions such as initializing screenshots upon completion or processing new results when updates occur, adhering to PyObjC's naming conventions with the trailin...
def query_updated_(self, notif): """Receives and processes notifications from the Spotlight query. The trailing _ in the name is required by PyObjC to conform to Objective-C calling conventions. Reference: https://pyobjc.readthedocs.io/en/latest/core/intro.html#underscores-and-lots-of-them ...
def get_bridge_name(cli: ApiextensionsV1Api, custom_obj: CustomObjectsApi) -> str: """ Function that gets OVS bridge present in node. Args: cli (ApiextensionsV1Api) - Object to interact with Kubernetes Python client's Apiextensions API custom_obj (CustomObje...
Your returnThe function `pod_ingress_shaping` configures Kubernetes pod ingress traffic shaping by applying network parameters (latency, loss, bandwidth) to specified pods. It loads templates, retrieves pod/node data, applies policies, and manages job execution (serial/parallel) while handling errors. It returns succes...
def pod_ingress_shaping( params: IngressParams, ) -> typing.Tuple[ str, typing.Union[PodIngressNetShapingSuccessOutput, PodIngressNetShapingErrorOutput] ]: """ Function that performs ingress pod traffic shaping based on the provided configuration Args: params (Ingr...
def discover(): raw_schemas = load_schemas() streams = [] for stream_id, schema in raw_schemas.items(): stream = create_stream(stream_id) streams.append( CatalogEntry( tap_stream_id=stream_id, stream=stream_id, schema=schema, ...
The main task of the code is to either discover a data catalog structure or synchronize data using it, based on command-line arguments. If the `--discover` flag is used, it runs discovery mode and outputs the catalog. Otherwise, it loads a specified or discovered catalog, expands environment variables in the config, an...
def main(): # Parse command line arguments args = utils.parse_args(REQUIRED_CONFIG_KEYS) # If discover flag was passed, run discovery mode and dump output to stdout if args.discover: catalog = discover() catalog.dump() # Otherwise run in sync mode else: if args.catalog: ...
def random_permutation(cities): perm = list(range(len(cities))) for i in range(len(perm)): r = random.randint(0, len(perm)-(i+1)) + i perm[r], perm[i] = perm[i], perm[r] return perm def cost(permutation, cities): distance = 0 for i in range(len(permutation)): c2 = permutation...
This code implements an Ant Colony Optimization (ACO) algorithm to solve the Traveling Salesman Problem (TSP). It initializes pheromones, iteratively generates ant solutions using heuristic and pheromone guidance, updates pheromones locally after each ant's move, and globally decays pheromones after each iteration. The...
def search(cities, max_it, num_ants, decay, c_heur, c_local_phero, c_greed): best = {'vector':random_permutation(cities)} best['cost'] = cost(best['vector'], cities) init_pheromone = 1.0 / (float(len(cities)) * best['cost']) pheromone = initialise_pheromone_matrix(len(cities), init_pheromone) for it...
def create_bplustree(order=8): return { "root": create_node(order) } def insert(bplustree, key, value): """Inserts a key-value pair after traversing to a leaf node. If the leaf node is full, split the leaf node into two. """ parent = None child = bplustree["root"] # Traverse tre...
The main task of the code is to demonstrate the operations of a B+ tree implementation, including initialization, insertion of key-value pairs, visualization of the tree structure after each insertion, and retrieval of values. The demo inserts six entries, shows the tree state at each step, and tests retrieval of speci...
def demo_bplustree(): print('Initializing B+ tree...') bplustree = create_bplustree(order=4) print('\nB+ tree with 1 item...') insert(bplustree, 'a', 'alpha') show_bplustree(bplustree) insert(bplustree, 'a', 'akjjkh') show_bplustree(bplustree) print('\nB+ tree with 2 items...') in...
def _data_from_host_to_device(self, images): print("data interaction from host to device") # copy images to device self._data_interaction(images, ACL_MEMCPY_HOST_TO_DEVICE) # load input data into model self._gen_dataset("in") # load output data into model self._ge...
The code's main task is to process input images by transferring them to a device (e.g., GPU), performing a forward pass of a neural network, and returning the computed results back to the host (CPU). It handles data movement and computation in a typical deep learning workflow.
def run(self, images): self._data_from_host_to_device(images) self.forward() return self._data_from_device_to_host()
def clustering(data, sort = True): """ Return a new dataframe containing the junctions, the coordinates of theirs centers of masses, theirs members and weight. Parameters: ----------- data: pandas dataframe data must contain at least three columns named x, y and z and one column ...
The main task of the code is to perform clustering analysis on multiple `.pkl` files from an input directory, applying functions like `linksLinear`, `neighboursList`, `connexComponents`, `smallJunctions`, `bridges`, and `degree` to process each file. Results are saved in a structured output directory. The script reads ...
def mainClustering(dir_in, dir_out, name, box_size = 48, boundary = 'pbc'): """ Do the clustering, linksLinear, neighbours_list, connex_components, small_junctions, bridges and degree functions for a bunch of file and save the result in a (new) directory. Parameters: ----------- dir_in: st...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_student...
This function retrieves student and parent data from multiple schools via the Transparent Classroom API, aggregates the results, and returns them in the specified format (dataframe or list). It handles default parameters, processes each school's data individually, and converts the final output to dataframes if requeste...
def fetch_student_data( self, school_ids=None, pull_datetime=None, only_current=False, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.t...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_session...
The function fetches session data from multiple schools, handling datetime normalization and format conversion. It retrieves school IDs if not provided, aggregates session data from each school, and returns the result as a DataFrame or list based on the specified format.
def fetch_session_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) if scho...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_user_da...
The main task of the code is to fetch user data from multiple schools via the `fetch_user_data_school` method, aggregate the results into a list or DataFrame based on the specified `format` parameter, and return the consolidated user data. It handles default values for `school_ids` and `pull_datetime`, logs progress, a...
def fetch_user_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) if school_...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_classro...
The main task of the code is to fetch classroom data from multiple schools, either as a list or DataFrame, using specified school IDs and a timestamp. It defaults to current UTC time if no timestamp is provided, retrieves school IDs if none are given, aggregates data across schools, and converts the result to the reque...
def fetch_classroom_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) if sc...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_form_te...
The function fetches form template data from Transparent Classroom for specified schools, aggregates results, and returns them in the requested format (dataframe or list). It handles default school IDs and pull datetime, converts data to a dataframe if required, and logs the process.
def fetch_form_template_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) i...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_form_da...
The main task of the code is to fetch form data from multiple schools, aggregate it into a structured format (list or DataFrame), and return it. It handles default parameters like school IDs and timestamps, iterates over each school to collect data, and converts the result to a DataFrame if specified. The function ensu...
def fetch_form_data( self, school_ids=None, pull_datetime=None, form_template_id=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.t...
def convert_session_data_to_df(session_data): if len(session_data) == 0: return pd.DataFrame() session_data_df = pd.DataFrame( session_data, dtype='object' ) session_data_df['pull_datetime'] = pd.to_datetime(session_data_df['pull_datetime']) session_data_df = session_data_df....
The main task of the code is to fetch student-classroom association data from Transparent Classroom systems. It accepts either session data or school IDs as input, processes them by school, and aggregates results. The function handles data formatting, validates inputs, and returns the data as a DataFrame or list, ensur...
def fetch_student_classroom_data( self, school_ids=None, session_data=None, pull_datetime=None, only_current=False, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime ...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_user_da...
The function fetches teacher data from Transparent Classroom by retrieving user data for specified schools, filtering users with 'teacher' roles, and returning the result as a DataFrame or list based on the format parameter.
def fetch_teacher_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) if scho...
def fetch_school_ids(self): logger.info('Fetching school IDs for all schools') school_data = self.fetch_school_data( pull_datetime=None, format='list' ) school_ids = [school.get('school_id_tc') for school in school_data] return school_ids def fetch_user_da...
The function fetches parent data from Transparent Classroom by retrieving user data for specified schools, filtering users with 'parent' roles, and returning results in the requested format (dataframe or list). It handles default school IDs and datetime values, logs progress, and converts data accordingly.
def fetch_parent_data( self, school_ids=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=datetime.timezone.utc) if schoo...
def fetch_teacher_user_ids_school( self, school_id ): teachers_school = self.fetch_teacher_data_school( school_id=school_id, pull_datetime=None, format='list' ) teacher_user_ids_school = [teacher.get('user_id_tc') for teacher in teachers_sc...
The function fetches teacher-classroom association data for a given school, either as DataFrames or lists. It retrieves user IDs if not provided, iterates through each teacher to collect default and accessible classroom data, converts results to DataFrames if requested, and returns both datasets in the specified format...
def fetch_teacher_classroom_data_school( self, school_id, user_ids=None, pull_datetime=None, format='dataframe' ): school_id = int(school_id) pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datet...
def convert_user_data_to_df(user_data): if len(user_data) == 0: return pd.DataFrame() user_data_df = pd.DataFrame( user_data, dtype='object' ) user_data_df['pull_datetime'] = pd.to_datetime(user_data_df['pull_datetime']) user_data_df = user_data_df.astype({ 'school_id...
The function fetches teacher-classroom association data from a system called "Transparent Classroom," either by processing provided user data (filtering teachers) or by iterating over specified school IDs. It aggregates default and accessible classroom data for each teacher, converting results to DataFrames if requeste...
def fetch_teacher_classroom_data( self, school_ids=None, user_data=None, pull_datetime=None, format='dataframe' ): pull_datetime = wf_core_data.utils.to_datetime(pull_datetime) if pull_datetime is None: pull_datetime = datetime.datetime.now(tz=date...
def cli_grab(): """take stuff from cli, output it in a dict""" parser = argparse.ArgumentParser(description="Find Contrail charm versions that were commited at the same time") parser.add_argument("charm_version", help="Charm version e.g. contrail-agent-21") args = vars(parser.parse_args()) return ar...
The main task of the code is to identify compatible charms based on version and hash. It parses command-line arguments, extracts charm components and versions, removes the queried component from a list, retrieves its hash, and searches for matching charms using the hash and version. It aggregates results, including the...
def main(): args = cli_grab() queried_charm = args['charm_version'] component = '-'.join(queried_charm.split('-')[0:2]) queried_version = int(queried_charm.split('-')[2]) CHARM_LIST.remove(component) queried_hash = get_hash(queried_charm) compatible_charms = [queried_charm] for component...
def cli_grab(): """take stuff from cli, output it in a dict""" parser = argparse.ArgumentParser(description="compare charm commit hashes. " "Arguments = all the versions to check") parser.add_argument("agent", help="contrail-agent charm version") parser.a...
The main task of the code is to compare commit dates of different charm versions by retrieving their commit hashes, then outputting the difference between the earliest and latest commits if the 'diff' flag is enabled, including their timestamps and changes.
def main(): args = cli_grab() try: diff = args.pop('diff') except KeyError: diff = False charm_vers = args.values() commit_hashes = get_hashes(charm_vers) commit_dates = compare_hashes(commit_hashes) component = "" if diff: print('#' * 90) print("Outputing...
def continue_line(self): return "&" + self.newline() + "& " def emit_arg(self, option): text = '' if option in self.args: value = self.args[option] if option in MAPL_DataSpec.optional_options: if self.args[option] == '': return '' ...
The main task of the code is to generate a formatted string representing a function call to `MAPL_Add<SpecType>Spec`, dynamically incorporating parameters from `MAPL_DataSpec.all_options`. It adjusts indentation, constructs the call with capitalized category names, iterates through options to append arguments using `em...
def emit_args(self): self.indent = self.indent + 5 text = "call MAPL_Add" + self.category.capitalize() + "Spec(gc," + self.continue_line() for option in MAPL_DataSpec.all_options: text = text + self.emit_arg(option) text = text + MAPL_DataSpec.TERMINATOR + self.newline() ...
def emit_header(self): text = self.newline() if 'condition' in self.args and self.args['condition']: self.indent = self.indent + 3 text = text + "if (" + self.args['condition'] + ") then" + self.newline() return text def emit_args(self): self.indent = self.inden...
The code's main task is to generate a specification string by concatenating three components: the header, arguments, and trailer. It calls `emit_header()` for the header, `emit_args()` for arguments, and `emit_trailer(nullify=False)` for the trailer, combining them into a single output string. This likely constructs a ...
def emit_specs(self): return self.emit_header() + self.emit_args() + self.emit_trailer(nullify=False)
def check_game_end(color, board, board_positions, board_positions_set): if len(board_positions) >= 400: return True return False def genmove(color, board, board_positions, board_positions_set): valid_positions = [] for i in range(len(board)): for j in range(len(board[0])): i...
The function `play_to_end` simulates a game of Go until termination, alternating turns between players. It deep-copies the board and positions, iteratively generates moves, updates the board state, and switches the active player. The loop halts when `check_game_end` confirms the game's conclusion. Finally, it returns t...
def play_to_end(color, board, board_positions, board_positions_set, komi): board = copy.deepcopy(board) # May not need deep copy for the following board_positions = copy.copy(board_positions) board_positions_set = copy.copy(board_positions_set) while not check_game_end(color, board, board_position...
def store(self): """ Embed the currently active piece into the gameboard and then generate a new active piece. """ for y in range(self.piece.shape[0]): for x in range(self.piece.shape[1]): if self.piece.piece[y][x] != 0: self.board[...
This method accelerates a Tetris piece downward by one grid square. It increases the piece's y-coordinate, checks if it exceeds the grid's lower bound, and either stores the piece or checks for collisions. If a collision occurs, it merges the piece with the grid. The method then checks for and returns the number of com...
def accelerate(self): """ Accelerates tetris piece down by one grid square. :return num_rows_deleted: number of rows that were deleted after this acceleration call. """ num_rows_deleted = 0 self.piece.y += 1 if self.piece.y > sel...
def check_collision(self, piece, pos): """ Check if a collision occurred between the currently active piece and either the walls of the board or any placed piece. :param piece: a Piece array :param pos: current position of the piece in the board :type piece: List[List[int]] ...
This function generates all possible next states for a game piece by rotating it (1-4 times based on type) and testing each rotation's valid horizontal positions. For each rotation and x-position, it simulates dropping the piece until collision, truncates it, updates the board, and stores the resulting state properties...
def get_next_states(self): """ Get all possible next states for this piece. :return states: dictionary of actions and corresponding state properties """ states = {} piece_id = self.ind curr_piece = [row[:] for row in self.piece] curr_pos = {'x': self.curre...
def matchTranslation(self): translate_X = self.readTransform_Children("translate", "X") translate_Y = self.readTransform_Children("translate", "Y") translate_Z = self.readTransform_Children("translate", "Z") return translate_X, translate_Y, translate_Z def matchRotation(self): r...
The function `matchAllTransformation` retrieves three transformation parameters—translation, rotation, and scale—by calling respective methods (`matchTranslation`, `matchRotation`, `matchScale`), then returns them as a tuple to provide a comprehensive transformation analysis.
def matchAllTransformation(self): translate = self.matchTranslation() rotate = self.matchRotation() scale = self.matchScale() return translate, rotate, scale
def overlap_add(x, win_len, hop_size, target_shape): # target.shape = (B, C, seq_len) # x.shape = (B*n_chunks, C, win_len) , n_chunks = (seq_len - hop_size)/(win_len - hop_size) bs, channels, seq_len = target_shape hann_windows = torch.ones(x.shape, device=x.device) * torch.hann_window(win_len, device=x...
The function evaluates a model's performance on a test dataset by comparing predicted outputs with high-resolution ground truth. It processes each batch, computes metrics (LSD, SISDR), saves sample reconstructions, and returns aggregated mean and standard deviation of metrics. If `eval_input` is True, it evaluates the ...
def evaluate_dataset(model, test_loader, sample_path, eval_input=False): window_size, stride, sr = test_loader.dataset.window, test_loader.dataset.stride, test_loader.dataset.sr results = [] # lsd, lsd_high, sisdr for i, (x_lr, x_hr, inp) in enumerate(tqdm(test_loader)): x_hr = x_hr.numpy()[0, :] ...
def translate_coords(self, x, y): sx, sy = utils.tx_world_to_screen(x, y, self.world, self.screen_size) return sx, sy def draw_sensors(self, player): has_search_results = hasattr(player, "searchResults") if has_search_results: px, py = self.translate_coords(player.x, player....
This code draws a player on the screen by rotating their image according to their heading, positioning it centered at their coordinates, and optionally rendering sensors. It translates coordinates, adjusts placement, and uses blit to render the rotated image.
def draw_player(self, player): image = player.image px, py = self.translate_coords(player.x, player.y) blitx = px - image.get_width() / 2 blity = py - image.get_height() / 2 if self.should_draw_sensors: self.draw_sensors(player) rotatedImage = self.rotate_ima...
def updatePosition(self, dt): dx = math.cos(math.radians(self.heading)) dy = math.sin(math.radians(self.heading)) n = utils.normalize_2d_vector([dx, dy]) self.x += n[0] * self.speed * dt self.y += n[1] * self.speed * dt if self.commandedHeading is not None: ...
This code updates an object's position, sensors, and timers over time 'dt', executes a search, and performs mode-specific actions (pursuit or firing) based on its current operational mode.
def update(self, dt): self.updatePosition(dt) self.updateSensors(dt) self.updateTimers(dt) self.doSearch(dt) if self.mode == "PURSUIT": self.doPursuit(dt) if self.mode == "FIRE": self.doFire(dt)
def draw_background(self): self.screen.blit(self.art.assets["background"], [0, 0]) def draw_fighters(self): for playerId in self.world.players: player = self.world.players[playerId] if player.state != "DEAD": self.draw_player(player) def draw_missiles(self): ...
The main task of the code is to render all game elements by sequentially drawing the background, fighters, missiles, explosions, selection, score, and platform info panel, then updating the display with pygame.display.flip() to visualize the game state.
def draw_everything(self) -> None: self.draw_background() self.draw_fighters() self.draw_missiles() self.draw_all_explosions() self.draw_selection() self.draw_score() self.draw_platform_info_panel() pygame.display.flip()
def compute_scores(self): score = {RED: 0, BLUE: 0} for playerId in self.world.players: p = self.world.players[playerId] if not p.state == "DEAD": score[p.force] += 1 return score def handle_events(self): for event in pygame.event.get(): ...
The main task of the code is to run a game loop that handles events, updates the game world, renders graphics, and maintains a 50 FPS frame rate using Pygame. The loop continues until the game state is marked as done, at which point it quits Pygame.
def mainloop(self): ticks = 0 self.clock = pygame.time.Clock() self.initialScore = self.compute_scores() while not self.done: self.handle_events() self.draw_everything() if not self.paused: self.world.update(ticks / 1000.0) ...
def resetCube(self): #M = np.arange(9).reshape(3,3) #self.state[self.T],self.state[self.L],self.state[self.C]=10+M,20+M,30+M #self.state[self.R],self.state[self.B],self.state[self.F]=40+M,50+M,60+M self.state[self.T],self.state[self.L],self.state[self.C]=1,2,3 self.state...
The main task of the code is to reset the cube's state by applying a series of random actions (excluding specified ones) for `rand_steps` steps, optionally performing a random face roll, and initializing memory for tracking states. It returns the last applied action if `rand_steps > 0`, otherwise -1, to prepare the env...
def reset(self,rand_steps,exclude=[],do_rand_roll=0): self.resetCube() self.state_mem = np.ones((self.mem_size,3*4,3*3))*-1 for i in range(rand_steps): while 1: rand_action = np.random.randint(12) if rand_action not in exclude: ...
def printMetadata(): print( '-----GLOBAL PARAMETERS-----') print('MEM_SIZE ={}'.format(MEM_SIZE )) print('BATCH_SIZE ={}'.format(BATCH_SIZE )) print('GAMMA ={}'.format(GAMMA )) print('EPS_START ={}'.format(EPS_START )) print('EPS_E...
The main task of the code is to execute and compare three reinforcement learning algorithms (Regular, Reverse with uniform/TD exploration) under curriculum learning. It tracks success rates across episodes, saves neural network parameters and results, and generates plots visualizing performance against a threshold, ann...
def main(): printMetadata() sim_timestamp = datetime.now().strftime("@_%d_%m_%y_Time_%H_%M") saveMetadata(SAVE_DIR + 'simulation_' + sim_timestamp) success_rate_graph = np.empty((3, int(args.num_episodes/TEST_RATE))) #success_rate_graph_first = np.empty_like(success_rate_graph) print('---...
def resetCube(self): #M = np.arange(9).reshape(3,3) #self.state[self.T],self.state[self.L],self.state[self.C]=10+M,20+M,30+M #self.state[self.R],self.state[self.B],self.state[self.F]=40+M,50+M,60+M self.state[self.T],self.state[self.L],self.state[self.C]=1,2,3 self.state...
This function resets the cube's state by applying a series of random actions (excluding specified ones) for a given number of steps, optionally applying a random roll. It initializes memory storage, updates the state, and returns the last action taken if random steps were executed.
def reset(self,rand_steps,exclude=[],do_rand_roll=0): self.resetCube() self.state_mem = np.ones((self.mem_size,3*4,3*3))*-1 for i in range(rand_steps): while 1: rand_action = np.random.randint(12) if rand_action not in exclude: ...
def _on_enter_pressed(self, event): global bot msg = self.msg_entry.get() self._insert_message(msg, "You", bot) def _change_language(self, Event): # _change_language and _change_personality have to be declared before declaring the buttons global tran...
The code sets up a chat application's main window with a title, fixed size, and background. It creates UI elements like a welcome label, message display area with scrollbar, input field, send button, and additional controls for translation and bot personality changes. The layout uses relative positioning, and the text ...
def _setup_main_window(self): self.window.title("Chat") self.window.resizable(width=False, height=False) self.window.configure(width=950, height=550, bg=BG_COLOR) # head label head_label = Label(self.window, bg=BG_COLOR, fg=TEXT_COLOR, text="We...
def encode_bit(data, pos, value): if np.uint16(value) != np.uint16(0): data[int(pos/8)] = data[int(pos/8)] | (1 << (pos & np.uint16(7))) return pos + 1 def encode_bits(data, pos, value, nbits): for i in range(0, nbits): pos = encode_bit(data, pos, np.uint16(value & np.uint16(1 << i))) ...
The function encodes a chess board state into a 32-byte binary representation, storing piece positions, king locations, castling rights, en-passant square, move counter, and 50-move clock. It uses bit manipulation to compactly represent the board's state for storage or transmission, omitting redundant king data and han...
def encode_position(board): data = np.zeros(32, dtype='uint8') pos = np.uint16(0) # Encode side to move pos = encode_bit(data, pos, np.uint16(not board.turn)) # Encode king positions pos = encode_bits(data, pos, np.uint16(board.king(chess.WHITE)), 6) pos = encode_bits(data, pos, np.uint16(...