dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def isLegalMove(self, column, state): """ Boolean function to check if a move (column) is a legal move """ for i in range(6): if state[i][column] == ' ': # once we find the first empty, we know it's a legal move return True # ...
This function performs a minimax search with alpha-beta pruning to evaluate the best move for the current player by recursively exploring game states up to a specified depth. It generates legal moves, checks for terminal conditions, and calculates heuristic values. The alpha value represents the optimal score for the c...
def search(self, depth, state, curr_player): """ Searches the tree at depth 'depth' By default, the state is the board, and curr_player is whomever called this search Returns the alpha value """ # enumerate all legal moves from this stat...
def isLegalMove(self, column, state): """ Boolean function to check if a move (column) is a legal move """ for i in range(6): if state[i][column] == ' ': # once we find the first empty, we know it's a legal move return True # ...
The function `bestMove` determines the optimal next move in a game by evaluating all legal moves using a minimax algorithm with alpha-beta pruning. It recursively evaluates each move's outcome via the `search` method, negating results to account for the opponent's turn, then selects the move with the highest alpha valu...
def bestMove(self, depth, state, curr_player): """ Returns the best move (as a column number) and the associated alpha Calls search() """ # determine opponent's color if curr_player == self.colors[0]: opp_player = self.colors[1] else: ...
def getData(url): req = Request(url, headers={"User-Agent":"Mozilla/5.0"}) data = urlopen(req).read().decode("utf-8") data = data.split("\n") weekNumber = date.today().isocalendar()[1] yearNumber = date.today().year data = makeData(data, weekNumber, yearNumber) return data def makeMsg(data):...
The main task of the code is to retrieve data from a specified URL, generate a message from the retrieved data, and send the message to recipients defined in a configuration file. The program checks if data is successfully retrieved before proceeding to create and send the message.
def main(): """Main program flow. Runs functions to gather data, make message and print it, as well as send it.""" data = getData(bot.url) """Test if there is data coming back from your request""" if len(data) > 0: message = makeMsg(data) bot.send_message(message, get_recip_from_config(c...
def convert(s, k): ara = [] for i in range(0, len(s), k): row = [] for j in range(i, min(i + k, len(s))): if s[j].isupper(): # Check if the character is uppercase row.append(ord(s[j]) - 65) # Convert uppercase character to 0-25 range elif s[j].islower():...
This function decrypts a Hill cipher ciphertext using a given key matrix. It calculates the modular inverse of the key matrix determinant, computes the adjugate matrix, and applies it to the ciphertext. The result is processed to remove padding characters 'x' before returning the decrypted plaintext.
def decrypt(cipher, k,key_string): k = int(k) matrix = convert(key_string,k) ans = "" det = int(np.linalg.det(matrix)) det = ((det%26) + 26) % 26 det = inverse(det, 26) adj = np.linalg.inv(matrix) * np.linalg.det(matrix) adj = np.round(adj, decimals=3) adj = process(adj, k) for i...
def inverse(a, m): gcd, x, y = extended_gcd(a, m) if gcd != 1: raise ValueError("Modular inverse does not exist") return (x % m + m) % m def process(matrix, k) : for i in range(k): for j in range(k): matrix[i][j] = (((matrix[i][j] % 26) + 26) % 26) return matrix def encrypt(plain, k, m...
This function decrypts a cipher text using a matrix and key k by computing the modular inverse of the matrix determinant, adjusting the adjugate matrix, and applying it to the cipher. It processes the matrix elements modulo 26, transforms the cipher with the adjusted matrix, and trims trailing 'x' characters for the fi...
def decrypt(cipher, k, matrix): ans = "" det = int(np.linalg.det(matrix)) det = ((det%26) + 26) % 26 det = inverse(det, 26) adj = np.linalg.inv(matrix) * np.linalg.det(matrix) adj = np.round(adj, decimals=3) adj = process(adj, k) for i in range(k): for j in range(k): ...
def extractPatch_2D_patchs_no_gt(self): if self.appply_on_batch_files is False: # single image # get image name and extension img_name = self.image_name img_name = os.path.split(img_name) img_name = img_name[-1] img_name_split = img_name.split(".") ...
This function determines the appropriate 2D/2.5D/3D patch extraction method based on input parameters. It checks patch type, validates dimensional consistency, and routes to specific extraction methods like extractPatch_2D_patchs_mask_gt() or extractPatch_3D_patchs_no_gt() depending on patch type and ground truth type ...
def patch_generator_main(self): """ This is the function called from GUI and depending on the dimension and type of patch requested it will execuete corresponding class method. """ # check the type of patch if self. patch_type=='2D': # for 2D patch ext...
def _load(self, path): """Loads the data from txt file and splits it into training and testing components""" data = np.loadtxt(path, delimiter=',') return train_test_split(data[:, :-1], np.reshape(data[:, -1], newshape=(-1)), ...
(The main task of the code is to train and evaluate a logistic regression model via multiple initializations, standardizing features, tracking the best model based on loss, plotting training curves (loss/accuracy vs. epochs), and outputting validation accuracy/F1-score. It loads data, performs cross-validation, saves o...
def fit(self, path, print_after=1, plot=False): """Wrapper method for training and saving the model""" X_train, X_test, Y_train, Y_test = self._load(path) Y_train = Y_train.reshape((1,-1)) Y_test = Y_test.reshape((1,-1)) X_train = standardize(X_train) X_test = standardi...
def assign_scores(self, city: City): scores: t.List[float] = self.get_prediction(city) person: Person for idx, person in enumerate(city.pop): person.vaccine_score = scores[idx] def get_inputs(self, city: City) -> torch.Tensor: x: torch.Tensor = torch.zeros(size=(len(city.pop)...
The code trains a neural network (NN) to predict outcomes in a simulated city environment using a custom loss function (COVIDloss). It runs the NN for a specified number of cycles, each involving generating a random city, simulating its dynamics over days, extracting inputs and actual outcomes, computing loss, and upda...
def train(self, max_cycles: int = 100): print(f"Training {self.name} for {max_cycles} cycles") self.nn.train() optimizer = torch.optim.Adam(self.nn.parameters(), lr=0.01) loss_fn = COVIDloss() train_start_time = time.perf_counter() for cycle in range(max_cycles): ...
def custom_collate(batch, dataset_name): # Check each data entry in the batch for data in batch: images, targets, calib_data, _ = data # If any of images, targets, or calib_data is None, return None for the entire batch if images is None or targets is None or calib_data is None: ...
The main task of the code is to perform 3D object detection using a pre-trained FCOS model on the KITTI or Waymo datasets, with options for training, inference, and checkpoint resuming. It initializes the model, loads data, handles device placement, and during inference evaluates detection accuracy by computing mAP met...
def main(mode='inference', dataset_name='waymo', image_path=None, load=None): # Main function to handle training and inference device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") if mode == 'inference': device = "cpu" print(devi...
def initialise_poly(self, path:str)->None: # object of import data class with required data self.poly_ = io.import_object(path) #base class constructor initialisation by default(no usage in this case) super().__init__() # object of tkinter library self.root_ = Tk...
The code initializes a GUI application to draw a polygon from a given path, retrieves the polygon's edges, binds mouse interactions to these edges, and starts the main event loop for the graphical interface.
def __init__(self, path:str)->None: #calling the required functions to draw polygon self.initialise_poly(path) self.get_polygon(self.poly_.edges_) self.mouse_binder(self.poly_.edges_) self.root_.mainloop()
def print_instructions(self): header = self.ascii_art.header instructions = "\nTo uncover a cell, enter a row number and a column number separated by a space." \ + "\n--For example, to select row 3 and column 4, Enter: 3 4" \ + "\n--Row numbers are displaye...
The main task of the code is to run a game loop that repeatedly plays rounds, prompts the user to continue, and resets the game state if requested. It starts by displaying instructions, executes a round, asks if the user wants to play again, and breaks the loop if the answer is not "y". The game resets for subsequent r...
def play_game(self): self.print_instructions() while True: self.play_round() play_again = input("\n==>Would you like to play again? y/n: ").strip() if play_again != "y": break self.reset_for_next_round() print("Thanks for playing! S...
def create_random_mine_locations(self): possible_mine_locations = itertools.product( range(self.side_length_of_square_grid), range(self.side_length_of_square_grid)) return set(random.sample(list(possible_mine_locations), self.num_mines)) def empty_board(self): num_rows = ...
This code initializes a Minesweeper game board with a specified square grid size and number of mines. It calculates safe cells, sets up neighbor transformation offsets, generates random mine positions, creates an empty board, and populates it with cells. The main task is to configure the game environment for play, trac...
def __init__(self, side_length_of_square_grid, num_mines): self.side_length_of_square_grid = side_length_of_square_grid self.num_mines = num_mines self.num_safe_cells = self.side_length_of_square_grid**2 - self.num_mines self.num_safe_cells_uncovered = 0 self.mine_uncovered = Fal...
def __serialise_ethernet(self, ts, eth): ''' ethernet has the following in it: time_stamp int Number of seconds since Unix epoch destination bytes string I can't decode it. Might be a MAC address ...
This code serializes network packets from a pcap file into a structured text format, writing each packet's Ethernet, IP, ICMP, TCP, and UDP fields along with metadata (filename, index) to a CSV-like output file. It handles protocol-specific data extraction, logs errors for malformed packets, and appends results to the ...
def serialise(self): logger = logging.getLogger() index = 0 columns = ('time_stamp,eth.source,eth.destination,' 'eth.type,ip._v_hl,ip.version,ip.ihl,ip.tos,' 'ip.dscp,ip.ecn,ip.length,ip.identification,' 'ip.offset,ip.ttl,ip.protocol,ip.checksum,' ...
def extract (msgfile, key): m = message_from_file(msgfile) From, To, Subject, Date = caption(m) Text, Html, Files, Parts = pullout(m, key) Text = Text.strip(); Html = Html.strip() msg = {"subject": Subject, "from": From, "to": To, "date": Date, "text": Text, "html": Html, "parts": Parts} ...
The code parses an EML file, extracts embedded files, and generates metadata including file paths, MD5/SHA1/SHA256 hashes, and file types using the `magic` library. It returns both the original extraction output and a dictionary containing processed file details with computed hashes and types.
def eml_file_parse(path=None): file = path f = open(file, "r") output = (extract(f, f.name)) f.close() files = output['files'] file = {} for name, value in files.items(): file[f'{name}'] = [] file[f'{name}'].append(value[0]) md5_digest = md5_of_file(file[f'{n...
def get_total_page_nums(self): self.get_total_players() total_pages = (self.total_players // self.records_per_page) + 1 return total_pages def get_page_records(self,page_num): page_num = page_num records = self.records_per_page base_url = Urls.player_query_url par...
The main task of the code is to gather player data from multiple pages by iterating through each page, retrieving records, parsing player information, and updating a database. It prints progress updates and summarizes the total players gathered.
def insert_records(self): page_nums = self.get_total_page_nums() for page_num in range(1, page_nums+1): print(f"Gathering data from page:{page_num}".ljust(35," "),end="\r") player_data = self.get_page_records(page_num=page_num) records = player_data.get('results') ...
def shortestPath(graph, start, end, printing=False): return DFS(graph, start, end, [], None, printing) def printPath(path): result = '' for i in range(len(path)): result = result + str(path[i]) if i != len(path) - 1: result = result + '->' return result def BFS(graph, start, ...
The main task of the code is to construct a directed graph with 7 nodes and multiple edges, then compare the shortest paths from node 0 to node 6 using DFS and BFS algorithms, printing both results for analysis.
def testDFS_BFS(): nodes = [] for name in range(7): nodes.append(Node(str(name))) g = Digraph() for n in nodes: g.addNode(n) g.addEdge(Edge(nodes[0], nodes[1])) g.addEdge(Edge(nodes[1], nodes[2])) g.addEdge(Edge(nodes[2], nodes[3])) g.addEdge(Edge(nodes[2], nodes[4])) ...
def IDT(document): for aM in range(corpusLength): line = document[aM] appendMaster(line, 1) #print(MasterLibrary) TF = [] for tf in range(corpusLength): tempTF = termFrequency(document[tf], 1) TF.append(np.array(tempTF)) idfARRAY = np.zeros(len(M...
The code computes TF-IDF vectors for each document in a corpus by calculating term frequency (TF) divided by document length, multiplying it with inverse document frequency (IDF) values from a master term library, and storing the results in a list. The function processes each document, splits it into terms, normalizes ...
def tf_idf(document): row = 0 tfIDF = [] idf, TF = IDT(document) for row in range(corpusLength): line = document[row] temp = gramSplit(cleanData(line), 1) docLength = len(temp) termfreq = TF[row]/docLength for feature in Master...
def svenn(x0, grad, lmb, delta): # # One-dimensional Svenn search # # print ("Svenn stage...") f0 = function(calcX(x0, grad, lmb)) if f0 < function(calcX(x0, grad, lmb+delta)): delta = -delta x1 = lmb + delta f1 = function(calcX(x0, grad, x1)) while f1 < f0: delta ...
The code performs a one-dimensional golden section search to find the minimum of a unimodal function. It initializes an interval [a, b] using the `svenn` function, then iteratively narrows the interval by comparing function values at points divided by the golden ratio (0.382 and 0.618). The loop continues until the int...
def gold(x0, grad, eps, lmb, delta): # One-dimensional gold search [a,b] = svenn(x0, grad, lmb, delta) l = b - a x1 = a + 0.382*l x2 = a + 0.618*l while l > eps: if function(calcX(x0, grad, x1)) < function(calcX(x0, grad, x2)): b = x2 x2 = x1 ...
def svenn(x0, grad, lmb, delta): # # One-dimensional Svenn search # # print ("Svenn stage...") f0 = function(calcX(x0, grad, lmb)) if f0 < function(calcX(x0, grad, lmb+delta)): delta = -delta x1 = lmb + delta f1 = function(calcX(x0, grad, x1)) while f1 < f0: delta ...
The code performs a numerical approximation method, likely for root-finding or optimization. It calculates three points (x1, x2, x3) using the `svenn` function, evaluates their corresponding function values (f1, f2, f3), and computes an improved approximation (xApprox) via a weighted formula involving these values. The...
def dsc(x0, grad, lmb, delta): svenn_res = svenn(x0, grad, lmb, delta) x1 = svenn_res[0] x3 = svenn_res[1] x2 = (x1 + x3)/2 f1 = function(calcX(x0, grad, x1)) f2 = function(calcX(x0, grad, x2)) f3 = function(calcX(x0, grad, x3)) xApprox = x2 + ((x3 - x2) * (f1 - f3)) / (2 * (f1 - 2 * f2 ...
def svenn(x0, grad, lmb, delta): # # One-dimensional Svenn search # # print ("Svenn stage...") f0 = function(calcX(x0, grad, lmb)) if f0 < function(calcX(x0, grad, lmb+delta)): delta = -delta x1 = lmb + delta f1 = function(calcX(x0, grad, x1)) while f1 < f0: delta ...
This code implements a **one-dimensional golden-section search** to find the minimum of a unimodal function. It starts by determining an initial interval [a, b] using the `svenn` function. The interval is iteratively narrowed by evaluating the function at two points (x1, x2) derived from the golden ratio (0.382 and 0.6...
def gold(x0, grad, eps, lmb, delta): # One-dimensional gold search [a,b] = svenn(x0, grad, lmb, delta) l = b - a x1 = a + 0.382*l x2 = a + 0.618*l while l > eps: if function(calcX(x0, grad, x1)) < function(calcX(x0, grad, x2)): b = x2 x2 = x1 ...
def svenn(x0, grad, lmb, delta): # # One-dimensional Svenn search # # print ("Svenn stage...") f0 = function(calcX(x0, grad, lmb)) if f0 < function(calcX(x0, grad, lmb+delta)): delta = -delta x1 = lmb + delta f1 = function(calcX(x0, grad, x1)) while f1 < f0: delta ...
This code performs a numerical optimization step by calculating approximate solutions using quadratic interpolation. It computes three points (x1, x2, x3) via the svenn function, evaluates their corresponding function values (f1, f2, f3), and derives an improved approximation (xApprox) using a quadratic formula. The re...
def dsc(x0, grad, lmb, delta): svenn_res = svenn(x0, grad, lmb, delta) x1 = svenn_res[0] x3 = svenn_res[1] x2 = (x1 + x3)/2 f1 = function(calcX(x0, grad, x1)) f2 = function(calcX(x0, grad, x2)) f3 = function(calcX(x0, grad, x3)) xApprox = x2 + ((x3 - x2) * (f1 - f3)) / (2 * (f1 - 2 * f2 ...
def dsc(x0, grad, lmb, delta): svenn_res = svenn(x0, grad, lmb, delta) x1 = svenn_res[0] x3 = svenn_res[1] x2 = (x1 + x3)/2 f1 = function(calcX(x0, grad, x1)) f2 = function(calcX(x0, grad, x2)) f3 = function(calcX(x0, grad, x3)) xApprox = x2 + ((x3 - x2) * (f1 - f3)) / (2 * (f1 - 2 * f2 ...
The code implements a modified Powell's method for finding the minimum of a function. It iteratively narrows an interval [a, b] by evaluating function values at points a, xmin, and b, computing quadratic approximations (a1, a2), and updating xApprox using these slopes. The loop continues until the difference between xm...
def dscPowell(x0, grad, eps, lmb, delta): dsc_res = dsc(x0, grad, lmb, delta) a = dsc_res[0] xmin = dsc_res[1] b = dsc_res[2] xApprox = dsc_res[3] while abs(xmin-xApprox) >= eps or abs(function(calcX(x0, grad, xmin)) - function(calcX(x0, grad, xApprox))) >= eps: if xApprox < xmin: ...
def dsc(x0, grad, lmb, delta): svenn_res = svenn(x0, grad, lmb, delta) x1 = svenn_res[0] x3 = svenn_res[1] x2 = (x1 + x3)/2 f1 = function(calcX(x0, grad, x1)) f2 = function(calcX(x0, grad, x2)) f3 = function(calcX(x0, grad, x3)) xApprox = x2 + ((x3 - x2) * (f1 - f3)) / (2 * (f1 - 2 * f2 ...
This code implements a modified Powell's method for finding the minimum of a function. It iteratively refines an approximation (xApprox) by evaluating the function at points a, xmin, and b, computing quadratic coefficients (a1, a2), and updating xApprox using a quadratic interpolation formula. The loop continues until ...
def dscPowell(x0, grad, eps, lmb, delta): dsc_res = dsc(x0, grad, lmb, delta) a = dsc_res[0] xmin = dsc_res[1] b = dsc_res[2] xApprox = dsc_res[3] while abs(xmin-xApprox) >= eps or abs(function(calcX(x0, grad, xmin)) - function(calcX(x0, grad, xApprox))) >= eps: if xApprox < xmin: ...
def mults(x, n): res = [] for i in range(len(x)): res.append(x[i]*n) return res def SysKO(x0, grad,lmb,eps): if(norm(difference(calcX(x0, grad, lmb),x0))/norm(x0) <= eps and abs(function(calcX(x0, grad, lmb)) - function(x0))<= eps): return False return True def gradient(x): grad ...
The function performs gradient descent with a line search to minimize a function, using a specified initial point x0 and stopping criteria based on epsilon values. It iteratively calculates the gradient, determines an optimal step size (lambda) via one-dimensional search, updates the position, and terminates when the g...
def fastestDescent(x0, eps1, eps2): # # Gradient descent with lambda. calculated with one-dimensional search # print("fastest descent goes!") xs = [] xs.append(x0) x0 = mults(x0, -1) x1 = [-x0[0], -x0[1]] lmb = 0.1 # while norm(difference(x1, x0))/norm(x0) >= eps1: while(S...
def gradient(x): grad = [] for i in range(len(x)): # grad.append(LeftDerivative(x, i, H_Derivative)) grad.append(CentralDerivative(x, i, H_Derivative)) # grad.append(RightDerivative(x, i, H_Derivative)) return grad def SysKO(x0, grad,lmb,eps): if(norm(difference(calcX(x0, grad, l...
The code implements an iterative optimization algorithm that adjusts parameters (x0) using gradient calculations and lambda values (lmb) to converge towards a solution. It repeatedly computes new points (x1, x2, x3), updates the gradient, and increments a dot count until convergence criteria (SysKO) are met. The proces...
def partan(x0, eps1,lmb, color): grad = gradient(x0) count_dots = 0 # while NormKO(grad, eps1): while(SysKO(x0, grad, lmb, eps1)): xs = [] xs.append(x0) print ("x0 = " + str(x0)) lmb = calcLambda(x0, grad, eps1, lmb, DELTA_MOP) x1 = calcX(x0, grad, lmb) pr...
def CountToZero(): global count_func count_func = 0 def fastestDescent(x0, eps1, eps2): # # Gradient descent with lambda. calculated with one-dimensional search # print("fastest descent goes!") xs = [] xs.append(x0) x0 = mults(x0, -1) x1 = [-x0[0], -x0[1]] lmb = 0.1 # ...
The code executes the fastest descent optimization algorithm starting from the point [-1.2, 0.0] with parameters EPSILON and LYAMBDA to find a function's minimum. It resets a counter, runs the algorithm, displays a plot, and prints the total function evaluations and the minimum function value at the computed solution x...
def fastestDescent_run(): CountToZero() x0 = fastestDescent([-1.2,0.0],EPSILON, LYAMBDA) pl.show() print("FUNCTIONS COUNT = " + str(count_func)) print("MIN FUNCTION = " + str(function(x0)))
def CountToZero(): global count_func count_func = 0 def partan(x0, eps1,lmb, color): grad = gradient(x0) count_dots = 0 # while NormKO(grad, eps1): while(SysKO(x0, grad, lmb, eps1)): xs = [] xs.append(x0) print ("x0 = " + str(x0)) lmb = calcLambda(x0, grad, eps1, ...
The code executes the 'partan' optimization algorithm starting from the point [-1.2, 0.0], using parameters EPSILON (tolerance) and LYAMBDA (damping factor). It visualizes the optimization path, counts function evaluations and steps, then prints these metrics along with the minimum function value found at the optimal p...
def partan_run(): CountToZero() count_dots, x0 = partan([-1.2,0.0],eps1=EPSILON, lmb =LYAMBDA, color = ['orange', 'red', 'yellow', 'white']) pl.show() print("FUNCTIONS COUNT = " + str(count_func)) print("STEPS COUNT = " + str(count_dots)) print("MIN FUNCTION = " + str(function(x0)))
def gradient(x): grad = [] for i in range(len(x)): # grad.append(CentralDerivative(x, i, H_Derivative)) grad.append(RightDerivative(x, i, H_Derivative)) return grad def calcLambda(x0, grad, eps, lmb, delta): # return gold(x0, grad, eps, lmb, delta) return dscPowell(x0, grad...
This code implements an optimization algorithm that iteratively computes points (x0, x1, x2, x3) using gradient and lambda calculations, updating parameters until the gradient's norm falls below a threshold (eps1). It tracks iterations (count_dots), adjusts a global parameter (R_func), and visualizes the path with colo...
def Rpartan(x0, eps1,lmb, color): STOP = False STOP_R = False grad = gradient(x0) count_dots = 0 while not STOP_R: STOP = False while not STOP: xs = [] xs.append(x0) print ("x0 = " + str(x0)) lmb = calcLambda(x0, grad, eps1, lmb, DELT...
def tune_run(num_samples: int = 1, max_num_epochs: int = 10, gpus_per_trial: int = 1, checkpoint: str | Path | None = None): DATA_DIR = "./data/fma_small_spect_dpi100" data_dir = os.path.abspath(DATA_DIR) local_dir = os.path.join(RESULT_DIR, f"tuning_multiclass_{len(genres)}_genres", os.path.basename(da...
The code's main task is to train and evaluate a music genre classification model with configurable modes. It supports three scenarios: (1) Hyperparameter tuning with 8 genres, (2) Binary classification experiments between genre pairs (e.g., Pop vs. Rock), and (3) A simple 3-class classification (Pop, Rock, Instrumental...
def main(): TUNE = False EXPERIMENT = False global CLASSES global genres MODEL_DIR = "C:/Users/thoma/ray_results/train_fma_2023-01-16_19-17-07" MODEL_DIR = None genres = ['Hip-Hop', 'Pop', 'Folk', 'Experimental', 'Rock', 'International', 'Electronic', 'Instrumental'] genres = ['Hip-Ho...
def createJob(concurrencyLimit): job = lc.Job( tasks=createTasks(), concurrencyLimit=concurrencyLimit, sqsQueueUrl=sqsQueueUrl, s3Bucket=s3ResultsBucket ) return job def recordPerformanceMetrics(internalTimes, externalTimes, concurrencyLimit, metricsPath, totalTime): inte...
The main task of the code is to run three trials of a job with a fixed concurrency limit of 1000, execute all tasks, record performance metrics (total, internal, and external times), save results to specified directories, and optionally verify outcomes against baseline data from SSW alignments stored in an S3 bucket. C...
def main(): for i in range(0, 3): trialNumber = 1 + i print("Starting trial", trialNumber) concurrencyLimit = 1000 job = createJob(concurrencyLimit) job.executeAllTasks() totalTime, internalTimes, externalTimes = job.getTasksTimes() path = r"./perfor...
def create_model(self): """ Creates an instantiation of the model using the given hyperparameters and the primed hyperparameters Returns: hyperparameters(dict{hyp:val}): dictionary of hyperparameters for the optimizer and model ""...
This method trains a neural network model for a specified number of epochs, tracking training metrics, updating learning rates, and optionally saving checkpoints or logging results to TensorBoard. It handles hyperparameter optimization, model initialization, and directory management for checkpoints/runs. Training inclu...
def train(self, epochs=1, update_every=0, save_every=0, opt=None): """ Train the stored model and optionally save checkpoints and output model statistics every few epochs By default, no checkpoints or statistics are saved Args: epochs(int): The number of epochs to tr...
def create_model(self): """ Creates an instantiation of the model using the given hyperparameters and the primed hyperparameters Returns: hyperparameters(dict{hyp:val}): dictionary of hyperparameters for the optimizer and model ""...
The code performs hyperparameter optimization by iteratively sampling hyperparameter combinations, training models for a specified number of epochs, and logging training/validation metrics (loss, accuracy) to TensorBoard. It clears prior results, runs multiple trials (`iters`), and stores each trial's performance along...
def hyp_opt(self, epochs=1, iters=10): """ Repeatedly call train for a short number of epochs to measure the effectiveness of each hyperparameter combination Args: epochs(int): The number of epochs to train for per combination iters(int): Number of times to sample hyperp...
def _create_vars(self, vertices): for vertex in vertices: for i in range(self.colors_num): key = str(vertex.id*self.colors_num + i + 1) self.vars[key] = Bool(key) def _add_clauses(self, clauses): for clause in self._parse_clauses(clauses): self.sol...
The code solves a Boolean satisfiability (SAT) problem by creating variables from vertices, adding clauses, and checking solver results. If the solver finds a solution (`sat`), it returns `['SAT', model]`; otherwise, `['UNSAT', None]`. The method encapsulates SAT solving logic, leveraging a solver to determine formula ...
def solve(self, vertices, clauses): self._create_vars(vertices) self._add_clauses(clauses) if self.solver.check() == sat: return ['SAT', self._get_model()] else: return ['UNSAT', None]
def get_av_splits(): """Gets the output of ffmpeg list_devices splits it into video and audio sections""" output = subprocess.run(['ffmpeg', '-list_devices', 'true', '-f', 'dshow', '-i', 'dummy'],capture_output=True).stderr.decode('utf-8') return output.split('(video)') def get_video_devices(self) -> list[...
The code initializes device configurations based on the operating system. For Windows, it retrieves video and audio devices using system-specific methods. For POSIX systems, it manually sets default device entries (e.g., /dev/video0 for video, 'default' for audio) with placeholders for future expansion. It raises an er...
def __init__(self): if os.name == 'nt': self.av_splits = get_av_splits() self.video_devices = self.get_video_devices() self.audio_devices = self.get_audio_devices() elif os.name == 'posix': # Must be entered manually self.av_splits = [] ...
def play_1_is_valid(play, player_id, turn_history): # check if the current player has previously made any play within this turn if play[1]: if turn_history[-1][0] != player_id: return True return False def play_2_is_valid(play, player_id, turn_history, discard): # check if the c...
This function checks if a player's move in a card game is valid based on the game state, turn history, and phase status. It routes validation to specific helper functions for each play type (1-5), ensuring compliance with rules like turn order, discard constraints, and phase requirements.
def phasedout_is_valid_play(play, player_id, table, turn_history, phase_status, hand, discard): # the last play of the game so far last_play = turn_history[-1][-1][-1][0] # the player that made `last_play` last_player = turn_history[-1][0] if last_player == player_i...
def set_window(x1, y1, x2, y2): global x_min, y_min, x_max, y_max x_min, y_min = x1, y1 x_max, y_max = x2, y2 def draw_Window(): turtle.penup() turtle.goto(x_min, y_min) turtle.pendown() turtle.goto(x_max, y_min) turtle.goto(x_max, y_max) turtle.goto(x_min, y_max) turtle.goto(x_m...
The code uses the Sutherland-Hodgman algorithm to clip a defined polygon against a rectangular window, then visualizes and prints the resulting clipped polygon's vertices. It sets up a Turtle graphics environment, draws the original polygon, applies clipping, and displays the clipped shape in red while outputting its c...
def main(): # Set up the Turtle screen turtle.speed(1) turtle.setup(width=900, height=700) # Defining clipper window vertices in clockwise order clipper_window = [[-100, -100], [-100, 100], [100, 100], [100, -100]] set_window(-100, -100, 100, 100) draw_Window() # Defining polyg...
def handle_snakes_and_ladders(self, position): # Define your game's snakes and ladders logic here snakes_and_ladders = {3: 22, 17: 4, 19: 7} # Example positions return snakes_and_ladders.get(position, position) def update_ui(self): self.canvas.delete("all") self.draw_board() ...
The code simulates a dice roll for a player, updates their position, adjusts for snakes/ladders, refreshes the UI, checks for a win, and displays the winner if applicable.
def roll_dice(self, player_index): dice_roll = random.randint(1, 6) player = self.players[player_index] player["position"] += dice_roll player["position"] = self.handle_snakes_and_ladders(player["position"]) self.update_ui() if self.check_win(player["position"]): ...
def findPieceSquare(position): #find a square that has a piece on it foundRow = False rows = position.split("/") while not foundRow: #find a row with pieces in it row_num = random.randrange(0, 8) # pick the row which we change, 0-7 if rows[row_num] != "8": #if not 8 spaces then has pieces on it break row ...
This function moves a randomly selected piece from its current position to an empty square. It identifies the piece's type, determines valid rows based on the piece's key, locates an empty spot, removes the piece from its original position, and places it in the new location, returning the updated board state.
def move_piece(position): #move a random piece somewhere old_r, old_col, piece = findPieceSquare(position) p = -1 for key, value in piece_dict.items(): if piece == value: p = key break if p <= 1: new_r, new_col = findEmptySquare(position, row_lower=1, row_upper=7) else: new_r, new_col = findEmpty...
def change_piece(position): #change a piece to another piece changed = False rows = position.split("/") while not changed: row_num = random.randrange(0, 8) # pick the row which we change if not rowIsEmpty(rows[row_num]): # rows[row_num] != "8": # found a row thats not empty i.e. has pieces i...
The code generates valid chess positions by mutating a seed position through random changes (e.g., altering pieces, colors, or moves). It tests each mutated position against chess engines (Stockfish, Rubichess) and collects divergences in their analysis results (AB, BC, AC). The goal is to identify inconsistencies or b...
def fuzzer(seed_position, number_required_divergences=100): divergences = 0 AB_divergences = [] BC_divergences = [] AC_divergences = [] position = seed_position valid_positions = 0 while ( valid_positions < 100 # divergences < number_required_divergences # and len(crash) + len(hang) < number_required_mutat...
def info(*args, **kwargs): print_base(green, *args, **kwargs) def np_l2_sum(x): return np.sqrt(np.square(x.copy()).sum()) def np_l2_mean(x): return np.sqrt(np.square(x.copy()).mean())
The code's main task is to print statistical information about a tensor/array `x`, including its shape, minimum/maximum values, and L2 norm sum/mean, using helper functions `np_l2_sum` and `np_l2_mean`.
def print_l2(x): info(x.shape,min=x.min(),max=x.max(),sum_l2 =np_l2_sum(x),mean_l2=np_l2_mean(x))
def checkYesOrNo(string): while True: option = input(string).lower() if option != "y" and option != "n": print("\nInvalid input. Please try again.") else: break if option == "y": return True else: return False def getWeather(self, weekInYear): print() dayList = [] ...
The function determines the current week and year, prompts the user to check this week's weather, and displays holidays for the week. If the user confirms, it retrieves and shows weather data; otherwise, it directly shows holidays.
def viewCurrentWeek(self): # Use the Datetime Module to look up current week and year current = datetime.datetime.now() currentYear = current.isocalendar()[0] currentWeekNumber = current.isocalendar()[1] weekInYear = [currentYear, currentWeekNumber] # Ask user if they wan...
def Statement(): return Lazy(IfElseStmt) | Lazy(IfStmt) | Lazy(FuncStmt) | Lazy(ConstStmt) def Operator(): return Op("+") | Op("-") | Op("*") | Op("/") | Op("%") | Op("=") | Op(".") | Op("@") | Op("!") | Op("~") | Op("void") def Literal(): return NumberLiteral() def Reference(): return Name() >> Entoken...
The main task of the code is to generate a sequence of elements, where each element is either a statement, operator, literal, or reference, repeated as needed. The function `Segment()` returns a structure that allows for the repeated combination of these components, likely for parsing or constructing expressions in a p...
def Segment(): return Repeat(Statement() | Operator() | Literal() | Reference())
def filter_empty(strings): return list(filter(lambda s: not re.match(r"^[ \t\r\n]*$", s), strings)) def strip_comments(lines): return list(map(lambda l: l.split("--")[0].strip(), lines)) def parse_macros(lines): lines = lines[:] i = 0 in_macro = False start = 0 name = None regions = [] ...
The code assembles assembly language into machine instructions by processing input code: removing empty lines and comments, parsing and expanding macros, resolving symbol addresses, and converting operations into a flat list of instructions for execution. Your return
def assemble(code): lines = filter_empty(code.split("\n")) lines = strip_comments(lines) lines = filter_empty(lines) macros, lines = parse_macros(lines) macros = expand_macros(macros) lines = insert_macros(lines, macros) # print("\n".join(map(lambda l: f"{l[0]}\t{l[1]}", enumerate(lines)))) ...
def get_random_formula( clause_no: int, clause_size: int, max_var: int ) -> List[List[int]]: # clause_no = a * n # clause_size = 3 # max_var = n formula = [get_random_clause(clause_size, max_var) for _ in range(clause_no)] return formula def is_satisfiable(formula: List[List[int]]) -> bool: ...
The function `calc_sat_probs_and_plot` calculates the probability of random 3-CNF formulas being satisfiable as the number of variables (n) increases. It iterates over clause-to-variable ratios (a), generates random formulas for each ratio, checks their satisfiability across multiple trials, and averages results. The p...
def calc_sat_probs_and_plot() -> None: """ Calculate probability of random formula being satisfiable based on it's size n (number of variables). The result is plotted and shown. Conclusion: probability sharply decreases with number of variables, which makes sense, since this problem is hard. ""...
def _stop_handler(self, cmd): """Handle the stop of a specific program of process.""" if len(cmd) == 1: return self._stop_all() elif len(cmd) == 2: splitted_cmd = cmd[1].split(':') if len(splitted_cmd) == 1: return self._stop_program(cmd[1]) ...
The main task of the code is to process a queue of commands in a thread-safe manner. It acquires a lock, iterates through commands, executes corresponding handlers (e.g., start/stop/restart/status), updates process states, and synchronizes data using locks to prevent race conditions. The commands are handled in reverse...
def __call__(self): """main part of our class""" self.lock_commands.acquire() if self.commands: print("commands:") print(self.commands) while self.commands: cmd = self.commands.pop() self.procs_state.clear() if c...
def _get_key(self): """ Read part of our code with setting and resetting """ ch = sys.stdin.read(1) return ch def _history(self, key): """Function to handle the history""" if self.hist_mode == True and self.hist: if self.command and key == 'B' and self.histoffset < -1...
This function parses terminal input to handle command navigation, history, and editing. It reads key presses, processes arrow keys for history traversal, backspace for deletion, and printable characters for command input. Terminal settings are adjusted temporarily, and the function restores them before exiting. It retu...
def _parse_key(self): """Function that parse readed key and execute """ # get winsize of our term self.rows, self.columns = os.popen('stty size', 'r').read().split() self.rows = int(self.rows) self.columns = int(self.columns) try: termios.tcsetattr(self.fd, ...
def _set_processes_arch(self): """Build the data structure and architecture for the processes.""" prog_names = self._fetch_progam_names() for prog_name, settings in self.progs_conf.items(): if prog_name not in prog_names: program = Program(prog_name, settings) ...
The main task of the code is to launch and manage processes defined in the 'programs' dictionary by initializing process configurations, starting them via '_launcher()', and continuously monitoring their state. It also initiates a separate thread for communication handling while maintaining thread safety using a lock d...
def run(self): """launch every processes inside the dictionary 'programs'.""" self.umask = self.taskmaster.config.umask self._set_processes_arch() # print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%") # print(self.progs_conf) # print("%%%%%%%%%%%%%%%%%%%%%%%%%...
def pretrain_wv( train_path_ls, wv_dir = "data/wordvec/fasttext/Custom_Lang", vec_size = 100): print("Pretrain word vector...") Path( wv_dir).mkdir(parents=True, exist_ok=True) train_path_ls = [train_path_ls] if isinstance(train_path_ls, str) else train_path_ls train_file = get_sentences(train_path_ls)...
This function trains and uses a Stanza model for linguistic parsing. It pretrains FastText embeddings on CONLLU data, trains a parser with custom parameters, and applies it to predict annotations in input files. The model handles different tagging modes (with gold UPOS tags, tokenized input, or raw text) and saves pred...
def train_pred_stanza(project_path, parser_id, epochs = 5, need_train = True, keep_upos = True, tokenized = True, epochs_tok = 100): print("stanza train pred") res_folder = os.path.join( abs_root, project_path, f"{parser_id}_res") conll_path = os.path.join( res_folder, 'extern_data/conllus/xxx_stanza') ...
def sha512_foldername(conll_names, conll_set_list, parser_id, dev_set, epochs, keep_upos): input_string_ls = [str(parser_id), str(dev_set), str(epochs), str(keep_upos)]+conll_names for conll in conll_set_list: input_string_ls.append(re.sub(comment_pattern_tosub ,'', conll).strip() ) input_string = ...
The function `prepare_folder` creates a temporary project directory for training and parsing tasks, generating unique folder names using SHA-512 hashing. It checks if pre-trained models or parsed data already exist, avoiding redundant processing. If not, it sets up directories, stores input files, and prepares datasets...
def prepare_folder(project_name, train_names, train_set_list, parse_names, to_parse_list, parser_id = 'kirParser', dev_set = 0.1, epochs = 100, keep_upos= False): """ make temporal project folder by default we parse also the training set parser_id = 'auto' or parser_id in ['hopsParser', 'kirParser', ...
def get_relevant_predicates(self, predicates, starting_phrases, seen): starting_words = set(starting_phrases) if not bool(starting_words): return set() link_words = [] for predicate in predicates: all_args = predicate.all_args if set(all_args).intersec...
The code generates a logical program by combining test facts and rules derived from paths between predicates. It constructs coreference rules for a pronoun symbol and aggregates relevant predicates into a Prolog-like format, returning the unified program for downstream tasks like reasoning or debugging.
def build(self, unused_background_knowledge, test, test_predicates): candidates = test.get_correct_candidate().split() + test.get_incorrect_candidate().split() + ['_'.join(test.get_correct_candidate().split())] + ['_'.join(test.get_incorrect_candidate().split())] starting = self.get_relevant_predicates(...
def match_pos(self, tokens, pos): return self.match(lambda token: token.pos, pos, tokens) def next_id(self, word): self.counter.update([word]) return f'{word}_{self.counter[word]}' def _normalise(self, token): lemmatised_token = token.lemma_ if lemmatised_token == '-PRON-': ...
The main task of the code is to extract structured events (subjects, objects, and related verbs) from a list of tokens by analyzing grammatical dependencies and normalization. It identifies verbs, assigns unique IDs, and constructs events based on syntactic roles like nsubj (subject), dobj (direct object), and dependen...
def extract_events(self, tokens): events = [] verbs = self.match_pos(tokens, [symbols.VERB]) for verb in verbs: new_events = [] id = self.next_id(verb.lemma_) self.span_to_id[verb] = id id = self._normalise(verb) if verb.dep in [symbols...
def match_branch(self, tokens, left_branch, right_branch, connecting_node=None): props = [] right_arcs = self.match( lambda token: token.dep, [right_branch], tokens, lambda token: (token.head, token) ) for head, property_name in right_a...
The main task of the code is to extract properties from a tokenized text by analyzing syntactic dependencies, focusing on subject-predicate-object relationships, modifiers, and prepositional objects. It identifies attributes, complements, and dependencies through multiple branching patterns, normalizes tokens, and aggr...
def extract_properties(self, tokens): properties = [] properties += self.match_branch(tokens, symbols.nsubj, symbols.acomp) properties += self.match_branch(tokens, symbols.nsubj, symbols.attr) properties += self.match_branch(tokens, symbols.nsubj, symbols.advmod, connecting_node=symbols....
def solve_with_no_background(self, test_example, test_predicates): return self.build_and_run([], test_example, test_predicates) def batch_solve(self, test_example, test_predicates): answer_found = False answer = [] program = '' similar_sentences = self.get_background(test_exa...
The code solves a Winograd Schema Challenge (WSC) problem by extracting semantic predicates from the input sentence. Depending on the model type and mode (batch or iterative), it applies different solving strategies to determine the correct answer. If an answer is found, it retrieves similar background sentences and re...
def solve(self, test_example): test_example = WSCProblem( test_example[SENTENCE], test_example[CANDIDATE_1], test_example[CANDIDATE_2], test_example[ANSWER]) test_predicates = self.semantic_extractor.extract_all(test_example.get_sentence()) if self...
def extract_events(self, tokens): events = [] verbs = self.match_pos(tokens, [symbols.VERB]) for verb in verbs: new_events = [] id = self.next_id(verb.lemma_) self.span_to_id[verb] = id id = self._normalise(verb) if verb.dep in [symbols...
The code processes an input sentence using a model to extract events, modifiers, and properties, then returns their combined results. It resets a tracking dictionary before extraction to ensure each processed sentence starts with a clean state.
def extract_all(self, sentence): doc = self.model(sentence) # Reset id tracker. self.span_to_id = {} return self.extract_events(doc) + self.extract_modifiers(doc) + self.extract_properties(doc)
def update_from_api(location_db, location, start_id, update_quantity): """ Main bridge between pulling the sales data and storing it in the database. Parameters: location_db : SqlManager Database object for performing SQL queries location : str World/DC Location to p...
This function updates market data by fetching sales information from an API, updating ingredient costs, and recalculating crafting costs in a database. It uses parameters like location, start item ID, and update quantity to manage the process, logging each step's completion.
def update(location_db, location, start_id, update_quantity): """ Main function to perform all the market cost updating. Parameters: location_db : SqlManager Database object for performing SQL queries location : str World/DC Location to pull start_id : str ...
def update(location_db, location, start_id, update_quantity): """ Main function to perform all the market cost updating. Parameters: location_db : SqlManager Database object for performing SQL queries location : str World/DC Location to pull start_id : str ...
The main task of the code is to configure and execute a market data update process by parsing settings, creating/updating a database, tracking progress via a state table, processing profit data, and optionally sending Discord notifications. It handles location-based marketboard types, manages update ranges, and maintai...
def main(): """Main function""" main_config = config.parse_main_config() endless_loop = main_config["endless_loop"] marketboard_type = main_config["marketboard_type"] update_quantity = int(main_config["update_quantity"]) extra_tables = main_config["extra_tables"] location_switch = { ...
def stamp_nofile(img): """ Function: stamp_nofile(img) Parameters: img: (str) an file name/path Returns: nofile_id: (int) stamp id Stamps a warning message if a file is missing/can't be opened """ # stamps error msg on main playing area S.addshape(img) T.shape(img) ...
The function `set_tracking` updates and displays game tracking data, including leaderboards, matches, and guesses. It writes leaderboard titles, checks for file errors (`nofile_l`), and displays an error image if true; otherwise, it updates scores. The function also positions text and handles visual elements like title...
def set_tracking(data): """ Function: set_tracking() Parameters: data: (dict) a dictionary of data from the game Returns: None Keeps track of leaderboard, matches and guesses for each game and updates with they're updated """ for a in Board.instances: if a.name ...
def won_game(): """ Function: won_game() Parameters: None Returns: None Let's user know they've won if board is cleared """ for a in Board.instances: if a.name == "main": m_x = a.x m_y = a.y for o in GameData.obj: name = o.name ...
The main task of the code is to handle user click interactions in a game by checking conditions such as win states, quit actions, and card matches. It processes clicks on the quit button, determines if the game is won, and manages card clicks to either allow new selections or compare previously clicked cards, updating ...
def if_click_conditions(q, clicked_cards, x, y): """ Function: if_click_conditions(q, clicked_cards, x, y) Parameters: q: (object) quit section object from Board class clicked_cards: (list) clicked_cards list from GameData class x: (int) x coordinate of the turtle y: (int) y ...
def try_file(file_name, mode): """ Function: try_file(file_name, mode) Parameters: file_name: (dict) a file name mode: (str) what to do with the file (w, r, or a) Returns: None Returns True if file can be opened and accessed, False and throws exception if it can not ...
The function `load_images` loads card image paths from a configuration file based on the game mode, handles file errors by displaying a no-file message, and returns a dictionary of game card information including images and an error identifier if the file is inaccessible.
def load_images(cards, data, f="images.cfg"): """ Function: load_images(cards, data, f="file../images.cfg") Parameters: cards: (int) user card number input data: (dict) a dictionary of data from the game f: (file) file with card image names Returns: game_cards: (dict) a d...
def get_help_message(subcommand: str = "") -> str: """Obtain the help message for subcommand from docker-compose.""" args = [arg for arg in ["docker-compose", subcommand, "--help"] if arg] process = subprocess.run(args, capture_output=True, text=True) if process.returncode: logger.error( ...
The function `generate_class` automates generating a Python class (`DockerBaseRunner`) from Docker CLI help text. It parses command sections, extracts arguments/options, and constructs a formatted class with attributes, methods, and imports. The output includes docstrings, type hints, and proper code formatting (via `i...
def generate_class(class_name: str, cmd: str, level=0) -> str: docker_lines = get_help_message(cmd) nl = level + 4 sections, arguments = parse_help(docker_lines) cmd_fns = "" add_imports: Set[str] = set() if "commands" in sections: logger.info("Found commands in section {}", cmd) ...
def write_class(cmd: str) -> None: """ Generate a class for `cmd` and write it to `file_name` :param cmd: docker-compose command to create or an empty string for root. :param file_name: Name of output file (empty/None for auto-generation) :return: """ base_path = Path(__file__).parents[1] /...
The main task of the code is to process Docker command-line help messages by retrieving them, parsing their structure, and generating corresponding classes for each identified command. It iterates through parsed command entries, extracts the command name, and invokes a `write_class` function to create or update class r...
def main() -> None: write_class("") docker_lines = get_help_message("") sections, _ = parse_help(docker_lines) for cmd_line in sections["commands"]: if not cmd_line: continue cmd = cmd_line.split()[0] write_class(cmd)
def get_points_in_fov(self, idx): """ Args: idx: int, sample index Returns: points: ndarray of float32, [N, 4], points of (x, y, z, intensity) in fov """ points = self.get_points(idx) calib = self.get_calib(idx) fov_flag = self.get_fov_flag...
The main task of the code is to retrieve and construct a data dictionary for a specific sample index, containing LiDAR points, colored points, RGB images, calibration info, and optionally ground truth bounding boxes. It filters annotations by predefined class names if labels exist, ensuring data consistency for trainin...
def __getitem__(self, idx): """ Args: idx: int, sample index Returns: data_dict: frame_id: str points: ndarray of float32, [N, 4], points of (x, y, z, intensity) in fov colored_points: ndarray of float32, [N, 7], colored poi...
def get_repos(org_search=True, user_search=False, pub_search=args.public): if pub_search: for orgs in get_org(pub=args.org): repo = [r.refresh() for r in orgs.iter_repos() if r.name == args.repo] return repo elif org_search: for orgs in get_org(): repos = [repos for repos in orgs.iter_repos() if repos.nam...
The code generates reports based on the input integer `rtype`, processing data (repositories, pull requests) to analyze metrics like user languages, PR ratios, contributions, sentiment, and more, then exporting results to CSV files. Each `rtype` triggers a specific analysis, using helper functions to retrieve data, gen...
def report(rtype): if not isinstance(rtype, int): return "Expected an integer value. Exiting" elif rtype == 1: repo = get_repos() report = Report(repo=repo).user_languages() return out2csv(report, '../reports/issue_contrib.csv') elif rtype == 2: pulls = get_prs() report = Report(pulls=pulls).pr_ratios() ...
def misp_event(self, enclave): event_id, event_uuid = self.get_event_id(enclave_name=enclave["name"].strip()) event = MISPEvent() event.info = enclave["name"].strip() event.add_tag({"name": "trustar", "colour": "#3568D5"}) event.add_tag(f"{enclave['name']}") event.distrib...
This function processes enclaves by querying TruSTAR for indicators (use_case 1) or reports (use_cases 2/3) within a time range, generating MISP events, handling empty results, and checkpointing progress. It differentiates processing based on enclave configuration, logs status, and raises exceptions with recovery instr...
def ts_reports_to_misp(self): try: for enclave in self.enclaves: if enclave["use_case"] != 3: event = self.misp_event(enclave) self.globals_list["event_count"] += 1 else: event = MISPEvent() ...
def get_public_key(private_key=None): if private_key is None: private_key = get_private_key() privkey = PrivateKey(private_key, raw=True) return privkey.pubkey.serialize() def address_from_hash(addr): return b58_encode(addr+bytes((getxor(addr), ))) def public_key_to_hash(pub_key, chain_id=8964,...
The main task of the code is to generate a blockchain address from a public key (or derive it from a private key if provided) using a specified chain ID. It hashes the public key with the chain ID and converts the hash into a standardized address format, commonly used in blockchain systems for identifying accounts.
def get_address(public_key=None, private_key=None, chain_id=261): if public_key is None: public_key = get_public_key(private_key=private_key) return address_from_hash(public_key_to_hash(public_key, chain_id=chain_id))
def _encode_text_sdxl_with_negative(model: StableDiffusionXLPipeline, prompt: str) -> tuple[dict[str, T], T]: added_cond_kwargs, prompt_embeds = _encode_text_sdxl(model, prompt) added_cond_kwargs_uncond, prompt_embeds_uncond = _encode_text_sdxl(model, "") prompt_embeds = torch.cat((prompt_embeds_uncond, pro...
This function performs DDIM sampling to generate image latents from an initial latent state z0. It iteratively predicts noise using a text-guided diffusion model, updates the latent state, and collects all intermediate latents. The process uses text embeddings and guidance scale to refine the output, finally returning ...
def _ddim_loop(model: StableDiffusionXLPipeline, z0, prompt, guidance_scale) -> T: all_latent = [z0] added_cond_kwargs, text_embedding = _encode_text_sdxl_with_negative(model, prompt) latent = z0.clone().detach().half() for i in tqdm(range(model.scheduler.num_inference_steps)): t = model.schedul...
def coord_to_key(coord): return "{}{}".format(coord[0],coord[1]) def not_visited(key, visited): return key not in visited or not visited[key] def bfs(matrix, coord, queue, visited, answer, level): key = coord_to_key(coord) queue.append((coord, level)) visited[key] = True while queue: cur...
The main task of the code is to count and print the number of connected components of '0's in a matrix using BFS. Each '0' group represents an "icecream," and the code iterates through the matrix to identify and count these groups, printing each result and the total count.
def bfs_method(matrix, N, M): visited = {} queue = [] start_node_cnt = 0 for i in range(N): for j in range(M): if matrix[i][j] == '0': key = coord_to_key((i, j)) if not_visited(key, visited): # start node start_node_cnt += 1 ...
def coord_to_key(coord): return "{}{}".format(coord[0],coord[1]) def not_visited(key, visited): return key not in visited or not visited[key] def dfs(matrix, coord, visited, answer, level): key = coord_to_key(coord) if not_visited(key, visited): visited[key] = True adjacents = [] ...
The code performs a depth-first search (DFS) to count and print the number of connected components (regions of '0's) in a matrix. It iterates through each cell, initiating DFS from unvisited '0's to explore and record each distinct region. Each region's result is printed, and the total count of such regions is displaye...
def dfs_method(matrix, N, M): visited = {} start_node_cnt = 0 for i in range(N): for j in range(M): if matrix[i][j] == '0': start_key = coord_to_key((i, j)) if not_visited(start_key, visited): # start node answer = [] ...
def init_gnucash_file(path): session = Session("xml://%s" % path, is_new=True, force_new=True) book = session.book comm_table = book.get_table() #Set new root account root_acct = Account(book) root_acct.SetName("Root") root_acct.SetType(13) #ACCT_TYPE_ROOT = 13 book.set_root_acc...
This test inserts price data from a JSON file (stdin) into a GNU Cash file, verifying the output matches expected patterns. It creates a JSON file with commodity prices, runs the `insert_prices` function, and checks if the correct price entries are added, including handling duplicates and namespace checks.
def test_insert_prices_json_from_stdin(self): gnucash_file = FILE_PREFIX + "4.gnucash" json_file = FILE_PREFIX + "4.json" ses = init_gnucash_file(gnucash_file) ses.save() ses.end() f = open(json_file, 'w+') f.write('[\n') f.write('{"isin": "' + get_commo...
def selection(population): population = sortFitness(population) return population[:int(breeders_count)] def crossover(old_population): old_population = sortFitness(old_population) parents = old_population[:breeders_count] population = [] [population.append(old_population[i]) for i in range(elite...
The main task of the code is to generate a new population for the next generation in an evolutionary algorithm by sequentially applying selection, crossover, and mutation operations to the current population.
def newGeneration(population): population = selection(population) population = crossover(population) population = mutation(population) return population
def toGray(img): (img_width, img_height, img_channel) = img.shape for x in range(img_width): for y in range(img_height): b = int(img.item(x, y, 0)) g = int(img.item(x, y, 1)) r = int(img.item(x, y, 2)) avg = (b + g + r) // 3 for i in range(3):...
The code implements the Canny edge detection algorithm on an input image. It converts the image to grayscale, applies Gaussian blur, computes Sobel gradients, performs non-maximum suppression, and applies thresholding to detect edges. The function returns the processed edge-detected image.
def Canny(img): res_img = copy(img) print('canny: toGray start') res_img = toGray(res_img) print('canny: toGray end') print('canny: gauss start') res_img = gauss(res_img) print('canny: gauss end') print('canny: sobel start') res_img, gradientMatrix = sobel(res_img) print('canny: ...
def check_tokens(plots): enc = tiktoken.encoding_for_model(default_model) return sum([cal_tokens(enc, plot) for plot in plots]) def cal_cost(num_of_tokens: int) -> float: return .0004 / 1000 * num_of_tokens def embedding_from_string(string, model, embedding_cache): """Return embedding of given string, u...
The main task of the code is to process movie plot data, generate embeddings using a language model, and produce recommendations. It loads movie metadata, filters American films, calculates token costs, caches embeddings for efficiency, and uses these embeddings to find similar movies via the get_recommendations functi...
def main(): data_sample_path = "movie_plots.csv" df = pd.read_csv(data_sample_path) cache_exists = False # Load cache if exists, and save a copy to disk try: embedding_cache = pd.read_pickle(embedding_cache_path) cache_exists = True except FileNotFoundError: print(f"{colo...
def get_reddit(): return praw.Reddit( client_id=config["REDDIT_CLIENT_ID"], client_secret=config["REDDIT_CLIENT_SECRET"], user_agent=f"script:test:0.0.1 (by u/RowEnvironmental7282)" ) def collect_comments(filename: str, target_comments_per_subreddit: int, max_comments_per_submission: int...
The main task of the code is to perform sentiment analysis on Reddit comments by collecting them, processing into a structured dataset, estimating costs, scoring sentiments using a model, and visualizing results. It ensures data integrity by validating column structure and executes analysis workflows for semantic insig...
def main(): print("Start semantic analyzing") reddit = get_reddit() collect_comments( filename=default_filename, target_comments_per_subreddit=50, max_comments_per_submission=10, max_comment_length=1000, reddit=reddit ) df = pd.read_csv(default_filename, index...
def getTemplateIDs(): """ Returns a list of template ID's from central account """ templateWorkloads = wa_client.list_workloads( WorkloadNamePrefix=os.environ.get("TEMPLATE_PREFIX", "CentralTemplate") ) templateIDs = [] for workload in templateWorkloads['WorkloadSummaries']: tem...
The main task of the code is to process AWS Lambda events by updating workloads based on template IDs and their associated lenses. It retrieves template IDs and a mode ("overwrite" or "append"), then iterates through each template and lens. Depending on the mode, it either overwrites or appends workload data using corr...
def lambda_handler(event, context): logger.debug(event) templateIDs = getTemplateIDs() mode = getMode() logger.info("Updating templates in {} mode".format(mode)) for templateID in templateIDs: lenses = getTemplateLenses(templateID) logger.debug(lenses) for lens in lenses: ...
def addFile(path): #add new file to backup #copy target of path to Primary folder as same type, #and to Secondary folder with .bu suffex, add entry on Global.cl #read given path to fp (file path) as a Path type fp=Path(path) #write original file path to FL.sy with open ("Hawkins_P0/Sy...
This function handles user actions for file management: adding files to backup (act=1), updating existing files (act=2), viewing global changelogs (act=3), listing system files (act=4), or exiting (act=5). It validates file paths, processes commands from a system file (FL.sy), and interacts with external functions like...
def actionFuncCall(act): if act == 1: #add file to backup #accept and verify user input file path. Loop until valid file path given. path=Path('') print(term.bright_blue_on_black) while not path.is_file(): try: path=Path(input('Please enter a ...
def _parse_salutation(self): if self._salutation is None: temp_content = self._whole_email_body reply_text = self._get_trailing_emails_content(temp_content) if reply_text: temp_content = self._whole_email_body[:self._whole_email_body.find(reply_text)] ...
The code's main task is to parse structured text into components: salutation, body, signature, and trailing emails. It sequentially calls helper methods to extract these parts, then aggregates them into an `Inner` object, returning it. The `parse_body` method is invoked twice—once with `check_signature=False` to avoid ...
def parse_text(self): self._parse_salutation() self._parse_body(check_signature=False) self._parse_body() self._parse_signature_and_trailing_emails() return self.Inner(self._salutation, self._body, self._signature, self._trailing_emails_entire_text)
def get_product_vendor_list(self, uri_binding_list): product_vendor_list = [(self.wfn_converter.convert_cpe_uri_to_wfn(x).get('product'), self.wfn_converter.convert_cpe_uri_to_wfn(x).get('vendor')) for x in uri_binding_list] return product_vendor_list def is_product_in_c...
The main task of the code is to filter CVEs (Common Vulnerabilities and Exposures) from a DataFrame based on product, vendor, and version matches. It checks if the asset's product/vendor combination exists in the CVE's CPE list or summary, and if the asset's version aligns with the CVE's version logic. The function ret...
def search_cves_by_product_vendor_version(self, wfn): asset_product = wfn.get('product') asset_vendor = wfn.get('vendor') asset_version = wfn.get('version') df_temp_cves = self.df_cves.copy() df_temp_cves['result'] = self.df_cves.apply( lambda row: True if ((((asset...
def get_possible_key_lengths(self, sub_word_distance): # count the factors factors_count = {} for key in sub_word_distance: for i in sub_word_distance[key]: for j in self.get_factors(i): if j not in factors_count: factors_co...
The code decrypts a cipher by testing possible key lengths derived from repeated patterns, removing spaces for decryption, and reconstructing the original spacing in the decrypted text if a valid plaintext is found.
def crack(self, cipher): cipher = cipher.lower() self.cipher_with_spaces = cipher # save spacing of message for later cipher = cipher.replace(' ', '') # remove spaces for decryption possible_key_lengths = self.get_possible_key_lengths(self.find_repeated(cipher)) for key_length ...
def parse_badchars(badchars_str): try: bad_chars_tmp = ast.literal_eval("b'{0}'".format(badchars_str)) return bytes(set(bad_chars_tmp)) except Exception as e: print(e) pass raise Exception('Unable to parse bad chars: {0}'.format(badchars_str)) def bytes_to_hex_escaped(data_b...
The main task of the code is to encode shellcode while avoiding specified bad characters. It parses command-line arguments, validates user-provided bad characters, reads and normalizes input shellcode, encodes it using a multi-encoder to bypass restrictions, and outputs the resulting encoded shellcode in hexadecimal fo...
def main(): global ALLOWED_CHARS global BAD_CHARS parser = argparse.ArgumentParser(description='SmartEncoder arguments') parser.add_argument('--bad-chars', help="Bytes to avoid in gadget addresses. Example: --bad-chars='\\x00\\x0d\\x0a'", type=str) args = parser.parse_args() bad_chars = b'' ...
def change_hover_bg(self, button): button.config(bg = "#1f1f1f") def change_exit_bg(self, button): button.config(bg = "black") def pressed(self, number): if self.entry.get() == "Invalid": self.clear_() self.invalid_() if number == "11" and self.entry.get() != "0": self.pm_() elif number == "11" and...
This code creates a calculator's graphical user interface (GUI) with a display entry and buttons for digits, operations (add, subtract, multiply, divide), and functions (clear, sign change, equals). It sets up button layouts, hover effects, and grid positioning to simulate a calculator keypad, enabling user input and b...
def screen(self): # Buttons self.entry = Entry(self.master, bg = "black", fg = "white", bd = 0, font = ("Sans-Bold", 35), justify = "right", width = 10) self.entry.insert(END, "0") self.entry.bind("<Key>", lambda e: "break") self.borderclear= LabelFrame(self.master, bd = 1, bg = "white", relief = FLAT) se...
def is_float(x) -> bool: return to_float(x) != None def to_excel_date(input: float | str): if input == None: return None elif isinstance(input, str): excel_date_number = to_float(input) if excel_date_number == None: return None else: excel_date_number = input ...
The function `to_date` converts input `x` to a date object by first checking if it's a float (converted to Excel date), then attempting to parse it as a string using ISO format, followed by alternative date formats like "01-Feb-2011" and "YYYY-MM-DD HH:MM:SS". If all fail, it returns `None`.
def to_date(x): if is_float(x): return to_excel_date(x) if not is_str(x): return None try: return date.fromisoformat(x) except: pass try: # 01-Feb-2011 return datetime.strptime(x, "%d-%b-%Y").date() except: pass try: # 2022-0...
def DrawBoard(board): line="" print("\n\n\n") print("------------------------------------") for i in range(7,-1,-1): line="" for j in range(8): line += ' | ' + board[i][j] line+= ' |' print(i+1,line) print("------------------------------------") print(" a b c d e f g h") global score...
The main task of the code is to execute a single turn in a game. It draws the current board state, retrieves a move, updates the board with that move, and increments the global turn counter to track progression.
def DoRound(board): DrawBoard(board) move = GetMove() Update(board, move) global turn turn +=1
def getSpect(infile,spectfile,nosub=False,MAF=False): Spect={}; numSites=0 if nosub: print('Generating spectrum for all polymorphic sites. Substitutions (x=n or x=0) won\'t be considered.') with open(infile,'r') as sites: l=next(sites) for l in sites: (x,n...
The code parses command-line arguments to process genetic data, generating allele frequency spectra or configuration files, or analyzing selection footprints via likelihood ratio computation. It initializes parameter grids, reads input data, and scans for selection signals using specified models (balancing/positive sel...
def main(): #parsing arguments parser = argparse.ArgumentParser()#usage='python {} -i <input file> -o <output file> --spect <spect/config file> [--help] [--nofreq] [--nosub] [--MAF] [--getSpect] [--getConfig] [--fixSize] [--physPos] [--rec <recomb rate>] [-w <window size>] [--noCenter] [-s <step size>] [--fixX...
def parse_axt_and_vcf_w_recmap(ch, axtfile, vcffile, rec_map, rec_rate, outfile, pop_list, ploidy): # load axt file print(f'Loading the alignment for chr{ch}...') axt_lib, aligned_pos = _load_alignment(axtfile, ch) # sanity check assert len(axt_lib) > 0 and len(aligned_pos) > 0, aligned_pos # r...
The main task of the code is to parse VCF and alignment files to generate input for BalLeRMix, using either a recombination map or a uniform rate. It processes chromosome data, handles haploid/diploid organisms, filters samples, and outputs processed data with genetic position calculations. The script uses command-line...
def main(): import argparse parser = argparse.ArgumentParser() # file paths parser.add_argument('--vcf', dest='vcffile', help='Path and name of the vcf file. Format can be either .vcf or .vcf.gz.\n', required=True) parser.add_argument('-c', '--chr', dest='ch', help='ID of th...
def get_raw_probs(self, k, n, x, a, Stat): if (n, x, a) not in self.rawProbs: #for B1, polymorphism is 1, substitution is 0 if Stat == "B1": #sanity check assert set(k) == set([0,1]) b = self._get_b(x, a) probs = np.where( k == 0 , betabinom(n,a,b).pmf(n) , (1. - betabinom(n,a,b).pmf(n) - betabi...
The code computes and stores normalized probability distributions for different configurations of parameters (x, a) across various sample sizes. It uses conditional logic based on flags (nofreq, MAF, nosub) to calculate raw probabilities, normalize them with specific methods, and store the results in a lookup table to ...
def __init__(self, InputData, Grids, nofreq, MAF, nosub): #create a look-up library such that each configuration only get computed once self.betabinomprobs = {} self.rawProbs = {} self.normBase = {} self.normProbs = {} for x in Grids.x : for a in Grids.abeta : #container for probs full_probs_lis...
def _init_global_step(self): self.global_step = training_util.get_or_create_global_step() self._training_ops.update({ 'increment_global_step': training_util._increment_global_step(1) }) def _init_placeholders(self): """Create input placeholders for the SAC algorithm. ...
The code initializes components for a reinforcement learning agent, setting up placeholders, global step, and operations for actor and critic network updates. It prepares training mechanisms for policy (actor) and value estimation (critic), including a simulated critic update, to enable model training through gradient-...
def _build(self): self._training_ops = {} self._real_training_Q_ops = {} self._init_global_step() self._init_placeholders() self._init_actor_update() self._init_critic_update() self._init_critic_simulated_update()
def tokenize(self, sentence): words = nltk.word_tokenize(sentence); return(words) def checkprofanity(self, sentence): profanities = [] profanitydict = [] datahelper.query("generalkeyword", "phrase", "category='profanity'", profanitydict) for profanityword in profanitydict...
The code analyzes a sentence by tokenizing, checking profanity, performing POS tagging, extracting skills/themes, calculating sentiment, and using a model to predict constructiveness. It returns a JSON with features like profanity words, sentiment scores, detected skills, themes, and a constructiveness probability (0-1...
def textanalyzer(self, sentence): words = self.tokenize(sentence) #nltk tokenizer (Winny has undone the nopunct because we need the punct to do POS properly) #spellchecked = self.spellcheck(nswords) #check for spelling pfwords = self.checkprofanity(sentence) postag = pos_tag(words) ...
def get_local_ip_address(): try: # Create a temporary socket and connect to a dummy IP address with socket(AF_INET, SOCK_DGRAM) as temp_socket: temp_socket.connect(("10.255.255.255", 1)) local_ip_address = temp_socket.getsockname()[0] except Exception: # Fallb...
The main task of the code is to create a client application that connects to a server, registers itself, and sends/receives messages. It uses a separate thread to handle incoming messages from the server while allowing the user to input messages to send. The client establishes a connection to the server, authenticates ...
def main(): global current_prompt_to_console, balance # Configure the server PORT and IP variables serverIP = '127.0.0.1' # since running on same computer serverPort = 12000 # Get the username and port # for this client, from the user (for now) userName = input('What is your userName: ') ...
def dumb(env, maxDocs, params): ret = [] todo = [] todo.append(env.rootNode) visited = set() langsVisited = {} while len(todo) > 0 and len(visited) < maxDocs: node = todo.pop(0) #print("node", node.Debug()) if node.urlId not in visited: visited.add(...
The code generates and saves a plot comparing the performance of four crawling strategies (dumb, random, balanced, and RL) by plotting the number of found items against crawled items. It calculates average metrics after a warm-up period, labels each strategy with its average value, and saves the visualization as a PNG ...
def SavePlot(sess, qns, params, env, saveDirPlots, epoch, sset): print("Walking", env.rootURL) arrDumb = dumb(env, len(env.nodes), params) arrRandom = randomCrawl(env, len(env.nodes), params) arrBalanced = balanced(env, len(env.nodes), params) arrRL, totReward, totDiscountedReward = Walk(env, params...
def Train(F, R, Q, gamma, lrn_rate, goal, ns, max_epochs): scores = [] for i in range(0, max_epochs): curr_s = np.random.randint(0, ns) # random start state score = Trajectory(curr_s, F, R, Q, gamma, lrn_rate, goal, ns) scores.append(score) return scores def my_print(Q): rows ...
This code sets up a 15x15 maze grid, initializes a Q-learning algorithm for pathfinding, trains the model using reinforcement learning to navigate from start (0) to goal (14), and outputs the learned Q-values and optimal path. It defines feasible paths, assigns move rewards, and iteratively updates the Q-matrix to dete...
def Main(): print("Starting") np.random.seed() print("Setting up maze in memory") F = np.zeros(shape=[15, 15], dtype=np.int) # Feasible F[0, 1] = 1; F[0, 5] = 1; F[1, 0] = 1; F[2, 3] = 1; F[3, 2] = 1 F[3, 4] = 1; F[3, 8] = 1; F[4, 3] = 1; F[4, 9] = 1; F[5, 0] = ...
def Trajectory(env, epoch, params, sess, qns): ret = [] visited = set() langsVisited = np.zeros([1, params.maxLangId + 1]) # langId -> count candidates = Candidates(params, env) node = env.nodes[sys.maxsize] #stopNode = env.nodes[0] #link = Link("", 0, stopNode, stopNode) #candidates.Ad...
This function trains a model using multiple environments by collecting trajectories, performing training iterations, and periodically saving training/test plots. It loops through epochs, gathers data via Trajectory(), trains neural networks (qns) on collected data, and saves visualizations at specified intervals. Timer...
def Train(params, sess, saver, qns, envs, envsTest): print("Start training") for epoch in range(params.max_epochs): #print("epoch", epoch) for env in envs: TIMER.Start("Trajectory") _ = Trajectory(env, epoch, params, sess, qns) TIMER.Pause("Trajectory") ...
def readFolderContent(path): # read the files file_list = os.listdir(path) res = [] for filename in sorted(file_list): p = path + '/' + filename current_file = pd.read_csv(p) smth = current_file.iloc[0:toys, :] res.append(smth) #res.append(current_file) ...
The code processes text data from a folder, applies natural language processing (NLP) techniques, performs topic modeling using a specified algorithm, and generates visualizations to analyze topic distributions and key words. It filters data for specific years (2016-2017), adds collocations, saves the model, and constr...
def main(path): data = readFolderContent(path) # reaad folder data["content"] = data["content"].apply(text_process) # apply processing func on the content only_for_spec = data # copy inds = filtered_df(data) # get inds for the rows in 2016-2017 data = add_colos(data) # add colocarti...
def winner(self) -> Optional[Player]: if not self._is_more_than_one_player_alive(): winner = [x for x in self.players if x.alive][0] logger.debug(f'We have a winner: {winner}') return winner elif self._has_anyone_won(): winner = [x for x in self.players if...
This code handles a player's action in a game by validating the action, recording the game state and move, processing the action, transitioning to the next player or starting a new round, and updating legal moves. It ensures the game progresses correctly by checking for game over conditions, legal moves, and managing t...
def push(self, action: Union[Action, str]): if self.winner() is not None: raise GameIsOver() if isinstance(action, str): action = Action.from_notation(action) if action not in self.legal_moves: raise MoveIsNotLegal() self.state_record.append(deepcopy(s...
def player_link(player): """ Given the name of an NBA player, the function returns the html of their gamelogs on basketball reference for the current year. If player is not in the NBA, function returns None. """ if not player: return None names = player.lower().split() # List of low...
The code predicts an NBA player's next-game stats by fetching their historical stats, opposing team data, and using regression models. It handles errors for invalid players, retired players, missing stats, or scraping issues, returning appropriate messages. If valid, it estimates playing time, predicts stats, and forma...
def make_message(player): """ Given the name of an NBA player, return a string predicting the player's stats for their next game. Return some error message if something goes wrong. """ playerLink = player_link(player) # Get link to player page on basketball reference # If player named is not...
def is_whitespace(char: str): return char == " " or char == "\n" or char == "\t" def skip_whitespace(self): while self.pos < self.length and self.is_whitespace(self.char): self.advance() def peek(self): if self.pos + 1 < self.length: return self.content[self.pos + 1] ...
This method parses the input stream into tokens by checking the current character and returning the appropriate Token object for whitespace, comments, numbers, null, strings, and symbols like brackets, braces, colon, and comma. It advances the position in the input and handles edge cases like EOF or invalid characters ...
def next_token(self) -> Token: if self.pos >= self.length: return Token(value="", type=TokenType.EOF) if self.is_whitespace(self.char): self.skip_whitespace() return self.next_token() if self.char == "/" and self.peek() == "/": self.skip_comment(...
def get_responses(*args): """ Fetches responses from an API for a list of parameters. Args: *args: Variable number of parameters. Returns: dict: A dictionary containing the API responses for each parameter. Raises: None """ list_of_responses = {} for parm ...
The main task of the code is to generate an interactive folium map with multiple thematic layers, using GeoJSON data and parameters from `response_dict`. It automates layer creation by applying color thresholds, adding popup values, and integrating colormap scales for each layer. The map includes a basemap, layer contr...
def create_map(params,long,lat): #should automize getting the long and the lat """ Creates a folium map with multiple layers based on the given parameters. Args: params (tuple): Tuple of parameters. long (float): Longitude coordinate. lat (float): Latitude coordinate. Returns: ...
def _set_cur_loc(self): for i, row in enumerate(self.board_state): for j, val in enumerate(row): if val == 1: self.cur_loc = (i, j) return def _get_hider_loc(self) -> Tuple: # Returns None if hider is not in sight, otherwise returns hid...
This function determines the next move for an agent in a game by updating its state, locating the hider, and selecting an action. If the hider is unseen, it searches toward an LRS square; if visible, it chases the hider directly. The function updates internal state variables, tracks turns, and returns the chosen move c...
def get_action_from_state(self, board_state: List[List[int]], visible_squares: List[Tuple[int, int]], valid_moves: List[Tuple[int, int]]) -> Tuple[int, int]: self.prev_state = self.state self.board_state = board_state self.visible_squ...
def add_column_ma(self, src_data: pd.Series=None, mode: str='ma', period: int=9)->pd.Series: """ add a column of moving average (MA) to stock_data return: ma Parameter ----- - src_data: pd.Series of source stock price to cal ma - period: time period (day) ...
The function identifies buy points in stock data by applying filters (e.g., converging bottom, rising peak, moving average crossover, RSI thresholds) and trend analysis. It updates the 'buy pt' column in self.stock_data with True at detected points, ensuring required columns exist and validating conditions for potentia...
def __set_breakpoint(self, trend_col_name: str=None, bpfilters: set=set(), ma_short: list=None, ma_long: list=None, rsi_thres: float=0, zz_thres: float=0)->None : """ - set function of 'buy pt' column of self.st...
def parse_data_handshake(data): length = struct.unpack('!B', data[:1])[0] if length > 0: protocol_name = data[1:length + 1] if protocol_name == b'BitTorrent protocol': data = data[length+1:] if data: zeros = struct.unpack('!Q', data[:8])[0] data = data[8:] if len(data) > 20: return data[:20...
The main task of the code is to handle a peer connection in a BitTorrent-like protocol. It performs an initial handshake verification, sends a bitfield indicating downloaded pieces, and processes incoming requests. Global variables are set for torrent metadata (size, file path, multi-file status, piece length) to enabl...
def serve_peer(peer_socket, peer_address, infos): dict_hash, my_peer_id, downloaded_pieces, path, length, multi, piece = infos global SIZE SIZE = length global MULTI MULTI = multi if MULTI: global FILES FILES = path else: global PATH PATH = path global PIECE_LENGTH PIECE_LENGTH = piece data = peer...
def rows(self): return len(self.board) def cols(self): firstIndex = 0 return len(self.board[firstIndex]) def canPlay(self, rowNum, colNum): # return True if the space in the indicated column and row is EMPTY if self.board[rowNum][colNum] == EMPTY: return True ...
This code identifies a winning move for the given piece by simulating placements on the grid. It iterates through each cell, temporarily places the piece, checks if it results in a win, and returns the coordinates if successful. If no winning move is found, it returns (-1, -1).
def hint(self, piece): # for-loop iterating through all the rows in the grid for row in range(self.rows()): # nested for-loop iterating through all the spaces in each row for col in range(self.cols()): # if-statement checking if the pl...