dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def mult(self, P, n): Q = P R = identity while n > 0: if n % 2 == 1: R = self.add(R, Q) if R is None: return None Q = self.add(Q, Q) if Q is None: return None n = n // 2 re...
This code attempts to solve the discrete logarithm problem by randomly sampling elements to find a value n_candidate such that P * n_candidate ≡ Q (mod p), using a meet-in-the-middle approach. It generates candidate values, checks for collisions in a precomputed dictionary, and recursively retries if no solution is fou...
def log(self, P, Q): r = int(np.sqrt(self.p)) jlist = {} jj = np.random.choice(self.p, r, replace=False) for j in jj: jlist[self.mult(P, j)] = j kk = np.random.choice(self.p, r, replace=False) for k in kk: candidate = self.add(Q, self.mult(P, k)) ...
def get_geoshape_info_from_api_request_for_areacode(self, area_code): """ Function to make the API GET request, handle API response, process JSON, and parse out and return the polygon coordinates. The API provides access to a geographical repository maintained by Opendatasoft ab...
The function creates a GeoDataFrame for a specified region using geospatial data retrieved from an API. It converts API-provided polygon coordinates into a structured GeoDataFrame. If the API request succeeds, it returns the GeoDataFrame and a `False` error flag; if the request fails, it returns an empty GeoDataFrame a...
def create_region_geodf(self, area_code): """ Function to create geopandas dataframe for an individual region. Parameters ---------- area_code: string The 'Area Code' for the region whose data has been collected. Returns ------- True/False: ...
def get_all_regions(self): """ Function to create a pandas dataframe containing only the nine regions in the dataset for a given year. Parameters ---------- None Returns ------- filtered_regions_df: Pandas dataframe A dataframe contai...
The main task of the code is to generate a choropleth map by preparing region data, creating a combined shapefile, and displaying the map. It orchestrates steps like filtering dataframes, extracting region codes, and handling errors, returning a boolean to indicate success or failure in map creation.
def create_map_of_all_regions(self): """ Function to handle the creation of the choropleth map. For increased readbility, re-usability, and expandability, the main steps of this process are broken into separate functions, which are called and evaluated here. Parameters ...
def model_train(loader, natural): model.train() train_loss = mse_loss = KLD_loss = num_unlabeled = 0 ccs = [] labls = [] for batch_idx, (data, labels) in enumerate(loader): data = data.cuda() labels = labels.float().cuda() optimizer.zero_grad() model.mode = 'natural' if natural else 'synth' recon_batch,...
The code trains a model on synthetic and natural datasets over multiple epochs, logging training metrics (e.g., loss, accuracy, MAE) and periodically evaluating performance, saving checkpoints, and generating visualizations. It alternates between training, testing, and logging intervals, with options to delete old chec...
def learn(start_epoch, max_epochs, plot_interval, test_interval, eval_interval, checkpoint_interval, delete_checkpoints): global epoch for epoch in range(start_epoch, int(max_epochs) + 1): sys.stdout.flush() # while os.path.exists("stop.txt"): # Allows pausing during training # time.sleep(5) start_time = time...
def model_train(loader, natural): model.train() train_loss = mse_loss = KLD_loss = num_unlabeled = 0 ccs = [] labls = [] for batch_idx, (data, labels) in enumerate(loader): data = data.cuda() labels = labels.float().cuda() optimizer.zero_grad() model.mode = 'natural' if natural else 'synth' recon_batch,...
This code performs transfer learning by gradually unfreezing model layers during training, alternating between synthetic and natural datasets, logging metrics, saving checkpoints, and evaluating performance at specified intervals. It uses staged parameter thawing, cross-domain training, and periodic visualization of re...
def transferlearn(max_epochs, plot_interval, test_interval, eval_interval, checkpoint_interval, delete_checkpoints): global epoch for epoch in range(1, int(max_epochs) + 1): sys.stdout.flush() # while os.path.exists("stop.txt"): # Allows pausing during training # time.sleep(5) if thaw: if (epoch == 0): ...
def assign_roles(self): usernames = list(self.players.keys()) werewolf_count = max(1, len(usernames) // 4) werewolves = random.sample(usernames, werewolf_count) for username in usernames: role = "werewolf" if username in werewolves else "villager" self.players[use...
The code initializes a game by setting its active status, waiting for 60 seconds (likely for player connections), assigning roles, and then entering a loop that alternates between night and day phases until the game ends. It manages game progression, ensuring phases execute while the game is active, and concludes with ...
def start_game(self): self.game_active = True logging.info("Game starting in 60 seconds...") time.sleep(60) # Wait for 60 seconds after minimum players are connected self.assign_roles() while self.check_game_status(): self.night_phase() self.day_phase() ...
def cleanup(root_path): all = os.listdir(root_path) for i in all: path = root_path + i try: if os.path.isfile(path): if i != 'manifest.json': os.unlink(path) else: shutil.rmtree(path) except: continue...
The main task of this code is to analyze Chrome extension versions by parsing their manifest files, extracting background/content scripts, web-accessible resources, and popup pages. It crawls these files to detect API usage, handles various parsing errors, and stores the analysis results in a PostgreSQL database. The p...
def analyze_process(stringified_dict): f = json.loads(stringified_dict) id, versions = f.popitem() errors = '' d = {} d['versions'] = {} con = psycopg2.connect( host = 'localhost', database = 'extension_updates', user = 'anton', password = 'vgJttLSune5ijQfg3ch6ujh4AgLw{nLs7lfJ') ...
def setup(self): curses.curs_set(0) curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) self._window.bkgd(" ", curses.color_pair(1) | curses.A_BOLD | curses.A_REVERSE) def draw_score(self): self._draw(0, 0, f"Score: {self.score}") self._draw_line(2) def draw_map(self) -> ...
The code initializes a game environment by setting up the window, score, game map, and character. It assigns the provided `window` and `piece` parameters, initializes the score to 0, draws the score, creates a map structure, determines the character's starting position via `draw_map()`, instantiates a `Character` objec...
def __init__(self, window, piece): self._window = window self.setup() self.score = 0 self.draw_score() self.map = {} character_start_y, character_start_x = self.draw_map() self._character = Character(character_start_y, character_start_x, piece, self.map) ...
def draw_character(self): self._draw(*self._character) def draw_score(self): self._draw(0, 0, f"Score: {self.score}") self._draw_line(2) def clear_old_character_spot(self, original_y, original_x): start_x, length = get_clear_space( original_y, self._character.y, original_x, s...
The main task of the code is to handle user input for a game loop, process character movement actions, update the score based on collected items, and manage game rendering. It continuously reads input, checks for quit commands, updates the character's position, redraws the screen, and adjusts the score. The function re...
def run(self) -> int: try: while True: key = self._window.getch() action = Action.from_user_input(key) if action == Action.QUIT: break original_y = self._character.y original_x = self._character.x ...
def __analyze_contours(self): """ Transforms the image colors to black and white in a way so that only the edges become clearly visible. """ cv2_image = cv2.imread(self.image) cv2_image = imutils.resize(cv2_image, height=500) # Gray the image and detect edges grayscaled = cv2.cv...
The code scans an image to detect a rectangular object, processes it to generate a scan result, and saves the output as a PDF file in the specified directory. Key steps include analyzing image contours, transforming the detected object, and exporting the scanned image as a PDF.
def scan_and_save(self): """ Searches for an rectangular object in the given image and saves the scan result of that object in the destination directory as pdf file """ screenContours = self.__analyze_contours() scan_img = self.__transform_and_scan(screenContours) # Save the ima...
def fix_urls(tpcs_file, conferences_file, logger, debug): if os.name == 'nt': logger.info("Opening csv files in Windows mode") tpcs_f = open(tpcs_file,'r', newline='', ) conferences_f = open(conferences_file,'r', newline='') else: logger.info(f"Opening csv files in {os.name} mode...
The main task of the code is to process input TPCs and conference CSV files, generating LaTeX, HTML, and XML outputs for student records. It supports URL fixing, customizable output directories, and debug logging. The script uses command-line arguments to specify inputs, outputs, and processing options, handling file p...
def main(): parser = argparse.ArgumentParser(description='Generate Student tex/html file for TPCs') parser.add_argument('file', type=str, help='Input TPCs csv file') parser.add_argument('conferences', type=str, help='Conference names csv file') parser.add_argument('-d', dest='debug', type=str, defau...
def parse_bib(logger, bib_file, years, collaborators): bib = parse_file(bib_file) for item in bib.entries: entry = bib.entries[item] # check if within the year threshold month = entry.fields['month'] if 'month' in entry.fields.keys() else 'December' if month_differenc...
The main task of the code is to process input files (BibTeX, CSVs) and generate collaborator lists (LaTeX) and conflict reports (TXT) for CV purposes. It parses academic data, extracts collaboration/conflict information, and outputs structured files based on user-defined parameters like years, output directories, and d...
def main(): parser = argparse.ArgumentParser(description='Generate bibtex/CSV file for CV') parser.add_argument('bib_file', type=str, help='Input bibtex file') parser.add_argument('student_csv', type=str, help='Input student csv file') parser.add_argument('funding_csv', type=str, help='Input funding csv...
def gen_latex(csvfile, logger, phd_tex, phd_foot, ms_tex, ms_foot, pdf_tex, ug_tex, meng_tex, stats_tex): if os.name == 'nt': logger.info("Opening " + csvfile + " in Windows mode") csv_in_f = open(csvfile,'r', newline='') else: csv_in_f = open(csvfile,'r') stats_current_phd = 0 ...
The main task of the code is to parse a CSV input file containing student data, process it using command-line arguments, and generate structured output files (TeX, HTML, XML) for CV purposes. It supports customizing output filenames, logging levels, and directories, while producing LaTeX documents, HTML listings, and C...
def main(): parser = argparse.ArgumentParser(description='Generate Student tex/html file for CV') parser.add_argument('file', type=str, help='Input csv file') parser.add_argument('-d', dest='debug', type=str, default='critical', choices = ['debug', 'info', 'error', 'critical'], help='Produce debug output') ...
def importVerses(self, versesFileName = "Verses.xlsx"): """ Function to import verses from excel file. Parameters: versesFileName (str): The input filename for verse list (Defaults to "Verses.xlsx"). Returns: (0): No errors, (Anything else): Errors. De...
Your returnThe code initializes a class to bold specific columns in an Excel file based on unique words from verses. It imports verses, identifies unique words, loads questions from a file, and exports the questions with designated columns bolded. Key tasks include data import, unique word extraction, and Excel formatt...
def __init__(self, colLetters, questionsFileName = "Questions.xlsx", outputFilename = "Questions.xlsx"): """ The constructor for class UniqueWordBolder. Parameters: colLetters (array of str): The columns letters to be bolded. questionsFileName (str): The output filename,...
def graphLosers(): losers = getLosers() location = ["Loser1", "Loser2", "Loser3"] i = 0 for loser in losers: df = data.DataReader(loser[0], start= oneYears, end= currentDate, data_source='yahoo') makeGraph(df, location[i], loser[1]) i = i +1 def graphGainers(): gainers = getG...
The main task of the code is to execute three functions—graphLosers(), graphGainers(), and graphIndexes()—which likely generate visualizations for financial data, such as stock market losers, gainers, and index performance. The run() function orchestrates these operations to produce or display the graphs sequentially.
def run(): graphLosers() graphGainers() graphIndexes()
def request_package_sync( self, content_set_name: str, preset_content_set_name: str, internal_change_number: int = 0, output_format: str = "json", split_files: bool = False, ): """Request that datafeed begin packaging a contentset for download (sync version)""...
The fetch_sync function retrieves a content set by name, generates files on disk, and handles download processes. It requests a package token, creates a destination folder, retrieves file lists, downloads files, and optionally extracts resources. It manages errors and returns the destination folder path, serving as the...
def fetch_sync( self, content_set_name: str, preset_content_set_name: str, internal_change_number: int = 0, output_format: str = "json", split_files: bool = False, extract_resources: bool = False, ): """ Fetch a content set by name, producing f...
def get_avdl_doclen(docPath): totalcount = 0 f = open(docPath, 'r+', encoding='utf-8') content = f.read() contents = content.split("\n") global N N=len(contents) for c in contents: d = c.split("-->") doc_length[d[0]] = int(d[1]) totalcount += float(d[1]) global av...
The code executes a pseudo-relevance feedback process in an information retrieval system. It loads document lengths, queries, an index, and stopwords, then performs two searches: first without pseudo-relevance (Pseudo_Relevance_Done=False), then with it enabled (True), saving results to "PRF.txt". The purpose is to enh...
def _main(): queryPath = "queries.txt" indexPath = "Som_Index.txt" docPath = "Som_tokens.txt" common_words_path = "stopwords.txt" results="PRF.txt" Pseudo_Relevance_Done = False get_avdl_doclen(docPath) get_queries(queryPath) get_index(indexPath) get_stop_words(common_words_path)...
def get_nondominated_per_hp(self): temp_dict = {} return_dict = {} pts = self.get_nondominated() hps = lookup_hp[self.model_name] for hp in hps: pts[hp] = pts['model'].map(lambda x: x[x.find(hp) + len(str(hp) + '='):].split('_')[0]) temp_dict[hp] = list(pt...
The function computes statistical metrics (mean and standard deviation of distances) for each hyperparameter (hp) and its values, comparing non-dominated and dominated points. It normalizes data if specified, aggregates unique values per hp, and calculates distances between points, handling missing data gracefully. The...
def get_statistics_per_hp(self, normalization=True): non_dom, dom = self.points[0][:, 1:].astype('float'), self.points[1][:, 1:].astype('float') non_dom_hp, dom_hp = self.get_nondominated_per_hp(), self.get_dominated_per_hp() hps = lookup_hp[self.model_name] stats_hp = {} for hp ...
def __GetFileContent(self): fileContent = '' for eachMessage in self.__messageHandler.m_MessageList: logLevelText = self.__logConfiguration.logLevelsList[eachMessage.logLevel] logTypeText = self.__logConfiguration.logTypesList[eachMessage.logType] fileContent += '[' +...
The main task of the code is to save file content either as a new file or to the existing file based on the `saveAsANewFile` flag. It retrieves file content via `__GetFileContent`, then uses `__SaveAsANewFile` if the flag is True, otherwise `__SaveFile` to handle the save operation.
def SaveAll(self): fileContent = self.__GetFileContent() if self.__saveAsANewFile.get() == True: self.__SaveAsANewFile(fileContent) else: self.__SaveFile(fileContent)
def __GetFilteredFileContent(self): fileContent = self.__textBoxHandler.m_TextBox.get("1.0", tk.END) return fileContent def __SaveAsANewFile(self, fileContent): self.__bIsFileCreated = False self.__SaveFile(fileContent) def __SaveFile(self, fileContent): if self.__bIsFileCreated ...
The main task of the code is to save filtered file content either as a new file or overwrite the existing file based on the `saveAsANewFile` flag. It retrieves filtered content using `__GetFilteredFileContent()`, then conditionally calls `__SaveAsANewFile()` or `__SaveFile()` depending on the flag's state.
def SaveFiltered(self): fileContent = self.__GetFilteredFileContent() if self.__saveAsANewFile.get() == True: self.__SaveAsANewFile(fileContent) else: self.__SaveFile(fileContent)
def selection(self): """The leaf node with the maximum UCB is selected Returns: node: leaf node selected """ is_terminal_state = False leaf_node_id = (0,) while not is_terminal_state: node_id = leaf_node_id number_of_child = len(self...
The code implements the MCTS algorithm to determine the best action by simulating a specified number of games. It iteratively selects, expands, simulates, and backpropagates results through a game tree. After completing the simulations, it identifies the child node with the highest visit count from the initial state, r...
def start_the_game(self): """Complete MCTS iteration with all the process running for a certain number of games Returns: tuple: the best action """ is_expanded = False nbr_game = 0 while nbr_game < self.game_training: node_id = self.sel...
def drawgrid(): pygame.draw.line(gameDisplay,RED,(400,150),(400,450),2) pygame.draw.line(gameDisplay,RED,(500,150),(500,450),2) pygame.draw.line(gameDisplay,RED,(300,250),(600,250),2) pygame.draw.line(gameDisplay,RED,(300,350),(600,350),2) pygame.display.update() def message_display(text,x,y,size,c...
This code implements a two-player tic-tac-toe game where players take turns clicking on a grid to place their marks (X/O). It tracks moves, checks for winning conditions, displays results (win/tie), and resets the game. The code handles input events, updates the game state, and renders the game interface with visual fe...
def vsPlayer(): Player1=Player(0,0) #thiis should be displayed as USERNAME Player2=Player(0,0) drawgrid() message_display("Player 1:X Player 2:O",100,20,20,WHITE) count=0 totalmoves=[] player1moves=[] player2moves=[] won=False done=False while not done: clock.tick(6...
def drawgrid(): pygame.draw.line(gameDisplay,RED,(400,150),(400,450),2) pygame.draw.line(gameDisplay,RED,(500,150),(500,450),2) pygame.draw.line(gameDisplay,RED,(300,250),(600,250),2) pygame.draw.line(gameDisplay,RED,(300,350),(600,350),2) pygame.display.update() def message_display(text,x,y,size,c...
The main task of the code is to implement a Tic-Tac-Toe game where Player 1 (X) competes against a computer (O). It handles user input for moves, alternates turns, checks for win/tie conditions, updates the game board, and restarts the game after a win or tie. The computer uses a predefined strategy to select moves, wh...
def vsComp(): comp=Player(0,0) Player1=Player(0,0) drawgrid() message_display("Player 1:X Computer:O",100,20,20,WHITE) count=0 totalmoves=[] player1moves=[] compmoves=[] won=False done=False while (not done) and (not won): clock.tick(60) for event in pygame.ev...
def is_valid_materialized_set(direct_dependency_id, material_set_id, graph): derived_nodes = all_derived_nodes(material_set_id, graph) not_derived_dd = [ dd for dd in direct_dependency_id if not dd in derived_nodes] if len(not_derived_dd) == 0: return True else: dprint("invalid materia...
This function identifies all minimal valid subsets of a given materialized set that satisfy dependency constraints in a graph. It recursively removes elements from the set, checks validity and minimality, and collects all minimal subsets that cannot be further reduced while maintaining validity.
def set_of_minimal_relations(material_set_id, direct_dependency_id, graph): if not isinstance(material_set_id,list): material_set_id = sorted(list(material_set_id)) # invalid if not is_valid_materialized_set(direct_dependency_id,material_set_id, graph): return set() # none set else: ...
def is_terminate_materialize_set(ms, G): for n in ms: if not G.has_node(n): # controllable: public interface "decimals" is not in any edge, thus not in relation dependencies, and thus not in graph G continue if len(list(G.predecessors(n))) != 0: return False else: ...
The function generates all minimal materialized sets (mms) by recursively expanding dependencies. It processes each input set, checks termination conditions, replaces nodes with direct dependencies, and accumulates results through union operations to avoid duplicates, returning the aggregated set of minimal mms derived...
def get_minimal_all(mms_collec,direct_dependency_id, G): assert isinstance(mms_collec, set) mms_all = set() repeated_count = 0 # mms_downstream = mms_downstream.union(mms_collec) for mms in mms_collec: mms_all.add(tuple(sorted(mms))) if is_terminate_materialize_set(mms,G): ...
def ReadRules(): with open(RulesPath, 'r') as f: rules = f.read() output = Texttable(0) output.add_row(["Name", "Direction", "Drc Ip", "Dst Ip", "Protocol", "Src Port", "Dst Port", "Ack", "Action"]) for rule in rules.splitlines(): output.add_row(RuleRawToPrint(rule)) print(output.draw()) def LoadRules(rulesFil...
The main task of the code is to execute different functions based on the input command. If the command is "show_rules" or "show_log" or "show_conns", it reads respective data; if "load_rules", it loads rules from the provided file; if "clear_log", it resets the log. The function acts as a dispatcher, routing commands t...
def main(command, rulesfile): if command == "show_rules": ReadRules() elif command == "load_rules": LoadRules(rulesfile) elif command == "show_log": ReadLog() elif command == "clear_log": ResetLog() elif command == "show_conns": ReadConns()
def arrangement(self, allocation, location, remain): self.run(np.array([10, 10])) def expected_minimum_rejection(self): total_cars = config.num_cars charge_time = config.charging_time_base total_time = config.observation_time loop_times = total_time // charge_time charger...
The code's main task is to calculate and display the minimum possible rejection when arranging 'm' chargers into 'slots' using an arrangement algorithm. It initializes a zero-filled array for slots, computes the expected minimum rejection, and visualizes results via display functions. The output includes the rejection ...
def main(self, m, slots): self.arrangement(np.zeros(slots), 0, m) # m is total chargers, n is slots print( "minimum possible rejection is: {}".format( self.expected_minimum_rejection() ) ) self.result_display() self.figure_display(x_stick_...
def test_update_assignment(): ####################################################### # You do not need to change anything in this function # ####################################################### # set up (list_of_points, labels, centroids_dict1, centroids_dict2) = setup_for_tests() # ...
The main task of the code is to execute three test functions—test_update_assignment(), test_majority_count(), and test_accuracy()—to verify the correctness of implementations. If all tests pass, it prints "all tests passed." This function serves as a testing framework to validate the functionality of other components w...
def main_test(): ####################################################### # You do not need to change anything in this function # ####################################################### test_update_assignment() test_majority_count() test_accuracy() print("all tests passed.")
def setup_data_centroids(): """Creates are returns data for testing k-means methods. Returns: list_of_points, a list of data points centroids_dict1, two 4D centroids centroids_dict2, two 4D centroids """ ####################################################### # You do not...
The main task of the code is to test the correctness of the `update_centroids` function by comparing its computed results with expected values for given datasets. It verifies that centroid updates match expectations and ensures that the original input parameters remain unmodified, confirming the function's proper imple...
def test_update_centroids(): """Function for verifying if update_centroids is correctly implemented. Will throw an error if it isn't. """ ####################################################### # You do not need to change anything in this function # #############################################...
def get_practice_graph(): """Builds and returns the practice graph """ practice_graph = nx.Graph() practice_graph.add_edge("A", "B") practice_graph.add_edge("A", "C") practice_graph.add_edge("B", "C") practice_graph.add_edge("B", "D") practice_graph.add_edge("D", "C") practice_graph...
The main task of the code is to compare two recommendation algorithms (common friends vs. influence-based) on social network graphs. It first visualizes practice and Romeo-and-Juliet graphs, then analyzes node recommendations in the Romeo-and-Juliet graph to identify where the methods differ. For the Facebook graph, it...
def main(): practice_graph = get_practice_graph() # Comment out this line after you have visually verified your practice # graph. # Otherwise, the picture will pop up every time that you run your program. draw_practice_graph(practice_graph) rj = get_romeo_and_juliet_graph() # Comment out ...
def test_euclidean_distance(): """Function for verifying if euclidean_distance is correctly implemented. Will throw an error if it isn't. """ ####################################################### # You do not need to change anything in this function # #########################################...
The main task of the code is to execute a series of test functions for clustering algorithms, including Euclidean distance calculation, centroid assignment, and centroid updates. It verifies the correctness of these operations and prints "all tests passed" if they succeed.
def main_test(): ####################################################### # You do not need to change anything in this function # ####################################################### test_euclidean_distance() test_get_closest_centroid() test_update_assignment() test_mean_of_points() t...
def computeAccuracy(inputs, weights_in_hid, weights_hid_out, targets, confmat): # activation at the hidden layer activations_hid = np.dot(inputs, weights_in_hid) activations_hid = vectorized_sigmoid(activations_hid) # add the bias neuron to the hidden layer hid_inputs = np.concatenate((activati...
The code trains a neural network with specified hidden units and learning rate, tracks training and test accuracies over epochs, and outputs the results. It initializes accuracy lists, computes initial values, trains the network, then writes the recorded accuracies.
def network(h_units,alpha): train_accuracy = [] test_accuracy = [] # training and testing accuracies at epoch 0 initial_accuracy = computeAccuracy(train_inputs, weights_in_hid, weights_hid_out, train_target, False) train_accuracy.append(initial_accuracy) initial_accuracy = computeAccuracy(t...
def send_request_vote(self): print("🗳 Requesting votes...") request_vote_request = raft_pb2.RequestVoteRequest() self.voted_for = self.node_id self.metadata.update_metadata("NodeID", self.voted_for) self.votes_recieved.add(self.node_id) self.current_term = self.current_...
This code manages a distributed consensus algorithm by running an infinite loop that handles role-specific tasks: as a Candidate, it requests votes when the election timer expires; as a Follower, it initiates elections if both election and lease timers expire; as a Leader, it sends periodic heartbeats. The core purpose...
def start_client(self): while True: if self.current_role == "Candidate": if self.election_timer and self.election_timer_alive == False: self.send_request_vote() elif self.current_role == "Follower": if ( self.electio...
def unload(self, board): if not self.canMove() or self.loaded_count<=0: return self.command.append(6) self.count+=1 self.loaded_count-=1 board[self.y][self.x]+=1 def findmax(self, board, visit): coord = [0,0] diff = len(board) * len(board) for i in range(s...
The code's main task is to determine whether to load or unload based on the comparison between the current cell's value and an average, using `findmax` and `findmin` to adjust operations. It unloads if the cell is below average, loads if above, and returns a command after processing.
def choice(self, board, visit): #if self.loaded_count>self.average: if board[self.y][self.x]==0 and self.loaded_count>0: while self.count<self.MAX_COUNT and board[self.y][self.x]<=self.average: self.unload(board) self.count+=1 self.findmax(board, visit...
def find_min(self, board, visit): _min = 9999999 diff = 9999999 result = [0,0] for i in range(self.n): for j in range(self.n): if visit[i][j]: continue if board[i][j]<_min: _min = board[i][j] result[0] = ...
The code manages a truck's loading/unloading operations on a grid. It prioritizes unloading at locations with minimal demand or hot lend areas, then loads at high-demand/max locations if under capacity. The truck moves to optimal positions, adjusts cargo based on board values and visit status, and returns command data.
def solution(self, board, visit): if self.loaded_count>0: ey, ex = self.find_min(board, visit) check = self.move(ey,ex) if check: if self.hot_lend_places[ey][ex]: for _ in range(self.loaded_count): self.unload(board)...
def find_min(self, board, visit): n = self.N result = [0,0] _min = 9999999 diff = 1000000 for i in range(n): for j in range(n): if visit[i][j]: continue if _min<board[i][j]: continue if _min==board[i][j]: ...
The code navigates a board by moving to the minimum and maximum positions identified by `find_min` and `find_max`. It loads/unloads cargo based on `loaded_count` thresholds and hotplace status. If `loaded_count` is low, it moves to the max position, loads cargo (1/4 or 1/2 of the cell's value), then moves to the min po...
def solution(self, board, visit): min_y, min_x, _min = self.find_min(board, visit) max_y, max_x, _max = self.find_max(board, visit) if self.loaded_count<=_max or self.loaded_count<=self.MIN_LOADED_COUNT: for _ in range(10): self.move(max_y, max_x) if self....
def find_min(self, board, visit): _min = 999999 diff = 999999 coord = [0,0] for i in range(self.n): for j in range(self.n): if visit[i][j]: continue if board[i][j]<_min: _min = board[i][j] coord[0]=i ...
The code balances board values by unloading items at low-value cells (min) and loading from high-value cells (max), adjusting based on loaded_count, mean, and cell type-specific rules. It moves to min/max positions, updates the board/visit matrix, and returns the result of `get()` after redistributing items.
def solution(self, board, visit): min_y,min_x,_min = self.find_min(board, visit) if self.loaded_count>_min: if self.move(min_y,min_x): if (min_y, min_x) in self.lend_places: cnt = ((self.loaded_count+1)*3)//4 else: cnt =...
def get_finest_locks(filename): with open(filename, 'r') as f: tokens = json.load(f) locks = {} for t in tokens: for c in t['conflicts']: lockname = '_'.join(sorted([t['name'], c['conflict']])) if not lockname in locks: lock = Lock(lockname) ...
The code generates a lattice structure by recursively creating coarser levels from the finest locks in a file. It starts with the finest level, iteratively builds next levels using `get_level`, reduces the total levels count, and stops when only one level remains. Duplicates are removed, and the cleaned lattice levels ...
def generate_lattice(filename): levels = [] finest = get_finest_locks(filename) levels += [[finest]] total_levels = len(finest) # print('finest', len(finest)) base = [finest] while total_levels > 1: next_level = get_level(base) # print('level', next_level) levels += ...
def quicksort(sort_list: list, dict_value: str) -> list: """A simple quicksort function used to order a series of numbers based on there size Splits the list in too smaller and smaller lists of the values lower and higher than the first value of the currently list, allowing them to be sorted When the le...
The code constructs a binary tree by repeatedly merging the two smallest elements in a priority queue. It combines their "character" strings and sums their "value" fields, updating the tree structure with new nodes. The merged value is reinserted into the sorted queue, ensuring the next smallest elements are processed ...
def binary_tree(queue: list) -> list: """The system used to generate a binary tree once all values have been collected This works through a queue system taking the two smallest values, assigning a binary value to it and then combining them into one item in the queue""" #first sends the queue to be sorte...
def get_train_state(rng: PRNGKey, ctable: CTable) -> train_state.TrainState: """Returns a train state.""" model = get_model(ctable) params = get_initial_params(model, rng, ctable) tx = optax.adam(FLAGS.learning_rate) state = train_state.TrainState.create(apply_fn=model.apply, params=params, tx=tx) ...
The main task of the code is to train a model for a fixed number of steps while periodically evaluating it by decoding outputs and saving checkpoints. It initializes training state, iterates over batches, updates the model, logs metrics, and at specified intervals, decodes samples, writes metrics, and stores checkpoint...
def train_and_evaluate(workdir: str) -> train_state.TrainState: """Trains for a fixed number of steps and decode during training.""" ctable = tasks[FLAGS.task](FLAGS.max_len_query_digit) rng = jax.random.PRNGKey(0) state = get_train_state(rng, ctable) writer = metric_writers.create_default_writer(...
def getSeeds(line): numbers = getNumbers(line) return {num: num for num in numbers} def iterateDicts(seeds,lines): map = [] auxSeeds = seeds for line in lines: if isMap(line): map.clear() elif line == '\n': auxSeeds = advanceSeedData(auxSeeds,map) els...
The code reads input data from a local file, extracts seed values from the first line, processes subsequent mapping rules to transform seed values, and identifies the lowest resulting seed position. It skips initial lines, iterates through mappings, and outputs the minimum seed value after transformations. Your return
def main(): url = "https://adventofcode.com/2023/day/5/input" session_cookie = "qxlqgk30wfecah70syeql7zrnvacazsl" #file = getInput(url,session_cookie) file = "/home/hutarsan/projects/leisure/advent_code_2023/day5_py/input.txt" #file = "/home/hutarsan/projects/leisure/advent_code_2023/day5_py/aux.t...
def create_matrix(file_path): matrix = [] with open(file_path, 'r') as file: for line in file: char_list = list(line.strip()) matrix.append(char_list) return matrix def create_nums_and_pos_matrix(file_path): nums_and_pos = [] with open(file_path, 'r') as file: ...
The code's main task is to solve Advent of Code 2023 Day 3's puzzle by reading a grid input, identifying numbers and their positions, and calculating the sum of products for gears (asterisks) that have exactly two adjacent numbers. It processes the input matrix to detect valid gear parts and computes their total sum.
def main(): url = "https://adventofcode.com/2023/day/3/input" session_cookie = "v2aoeint49rehy7tqcn2fwxaook1yhd3" #file = getInput(url,session_cookie) #file = "input.txt" file = "/home/hutarsan/projects/leisure/advent_code_2023/day3_py/input.txt" #file = "aux.txt" matrix = create_matrix(fi...
def loadUniverse(file): universe = [] try: with open(file, 'r') as file: for line in file: line = line.rstrip('\n') universe.append(line) except FileNotFoundError: print(f"The file '{file}' was not found.") return universe def getExpandedRows(u...
The code calculates the total sum of shortest path distances between all galaxy pairs in an expanded universe, accounting for row and column expansions. It reads galaxy positions from input, identifies expansion regions, and computes pairwise distances with adjustments for cosmic expansion.
def main(): universe = loadUniverse("input.txt") exp_rows = getExpandedRows(universe) exp_cols = getExpandedCols(universe) galaxies = getGalaxiesPos(universe) distance = calculateDistancesInAllPairs(galaxies,exp_rows,exp_cols) print("\nTotal galaxies shortest paths: "+str(distance))
def populateData(LFUDict, LRUQ, C, D, CacheTS, CachePID): global X,Y C = list(C) Y_current = getY(C, D) X_current = getX(LRUQ, LFUDict, C, CacheTS, CachePID) Y = np.append(Y, Y_current) X = np.concatenate((X,X_current)) assert(Y_current.count(1) == eviction) return Y_current def lruPred...
The code implements a modified Belady's optimal page replacement algorithm to calculate the hit rate for a given memory frame size. It uses a combination of optimal (future access prediction), LRU (least recently used), and LFU (least frequently used) strategies. The algorithm tracks block positions, timestamps, and ac...
def belady_opt(blocktrace, frame): global maxpos OPT = defaultdict(deque) D = defaultdict(int) LFUDict = defaultdict(int) LRUQ = [] CacheTS = defaultdict(int) CachePID = defaultdict(int) for i, block in enumerate(tqdm(blocktrace, desc="OPT: building index")): OPT[block].append(i...
def load_test_data(): sentences, labels = load_data_and_labels() sentences_padded = average_length(sentences) with open(save_dest + 'vocabulary.pkl', 'rb') as f: vocabulary = pickle.load(f) f.close() with open(save_dest + 'vocabulary_inv.pkl', 'rb') as f: vocabulary_inv = pickl...
The function `load_data` loads and preprocesses text data, returning input vectors, labels, vocabulary, and inverse vocabulary. It conditionally loads test data, previously saved data, or processes new data by padding sentences (either to average length or maximum length) and building a vocabulary. If not using saved d...
def load_data(avg_len=False, load_saved_data=False, load_testdata=False): """ Loads and preprocessed data for the dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. """ if load_testdata: x, y, vocabulary, vocabulary_inv = load_test_data() elif load_saved_data: ...
def auth_to_open(username, password): auth_boolean = auth(username, password) # opens library if auth_boolean returns true if auth_boolean: print("Auth returned True") login_page_object.close() open_library() else: # TODO: finish warning box work messagebox.showwa...
This code initializes a GUI login interface with username/password fields, login button, and options to create/delete accounts. It sets window properties, arranges labels/entries using grid layout, and links buttons to functions for authentication and form switching.
def __init__(self, master): self.master = master self.master.title("Welcome") # names the form self.master.geometry('275x400') # width then height self.master.resizable(0, 0) # cannot resize form # intro label self.Top_Lbl = Label(self.master, text="Sign in") \ ...
def interpolate(matrix, mask): n = len(matrix) m = len(matrix[0]) for j in range(0, m): mb_start = -1 prev_value = np.nan step = 0 #init for i in range(0, n): if mask[i][j]: # current value is missing - we either start a new block, or...
The function `centroid_recovery` imputes missing values in a matrix using iterative low-rank reconstruction via centroid decomposition. It initializes missing values, performs truncated matrix decomposition, and iteratively updates the matrix by replacing missing entries with reconstructed values until convergence (bas...
def centroid_recovery(matrix, truncation = 0, maxIterations = 100, threshold = 1E-6): # input processing matrix = np.asarray(matrix, dtype=np.float64).copy() n = len(matrix) m = len(matrix[0]) if truncation > m: #strictly bigger print("[Centroid Recovery] Error: provided truncation para...
def get_munros_to_include(munros, regions_to_include): munros_copy = munros.copy() for munro in munros_copy.keys(): if munros_copy[munro]["region"] not in regions_to_include: del munros[munro] return munros def get_users_outstanding_munros(user, munros_to_include): print (f"Fetching ou...
The main task of the code is to generate a list of recommended walks for users based on their outstanding munros in specified regions. It calculates walk scores using munro ratings and new munro counts per user, then outputs formatted results including user progress, shared outstanding munros, and sorted walks by score...
def generate_walk_list(user_names, regions_to_include): with open("munro_data.json", "r", encoding="utf-8") as json_in: current_munro_data = json.load(json_in) munros_data = current_munro_data["munros"] walks_data = current_munro_data["walks"] munros_to_include = get_munros_to_include(munros_data, region...
def set_optimizer(self): # Set learning rate decay self.LR = tf.train.exponential_decay( learning_rate=self.learning_rate, global_step=self.global_step, decay_steps=self.decay_step, decay_rate=self.decay_rate, staircase=True ) o...
This code initializes a model by configuring directories, setting up TensorFlow variables and optimizers, creating summaries for training monitoring, and loading pre-trained weights if specified. It prepares the model architecture, training parameters (learning rate, decay), and logging infrastructure for training or e...
def init(self): cfg = self.cfg self.img_size = cfg.IMG_SIZE pwd = os.path.dirname(os.path.abspath(__file__)) self.summary_dir = os.path.join(pwd, cfg.SUMMARY_DIR) if not os.path.exists(self.summary_dir): os.makedirs(self.summary_dir) self.model_dir = cfg.MODE...
def GetHV(d): ''' input ----- d: vec3 numpy array this is the direction vector(the way the camera is pointing) must be normed output ------ H,V: tuple of vec3 numpy array H=Horiztial screen direction V=Vertical screen direction calculates screen d...
The main task of the code is to compute the brightness of a given pixel by tracing a ray from the camera through the pixel's position, determining the intersection point using ray marching, and calculating the light contribution at that point from the provided light sources.
def mainImage(pixel, Camera, Lights): ''' input ----- pixel: vec2 numpy array the position of the pixel on the screen [0,0] is bottom left output ------ pixel brightness ''' uv = (pixel - 0.5*Camera.Res)/Camera.Res[1] #As y res is smaller make system correctly ...
def getChannels(self): """ Returns the channels in use """ return self.getParam('channelUsed') def getDepth(self, channel=None): """ Returns the gate depths for given channels in mm Arguments: ========== channel: int or list A channel number (1 to 10)...
The code prints the operating and resulting parameters of a specified channel, formatting values using the given alignment. It checks if the channel exists, retrieves parameters like frequency, burst length, TGC mode, and depth, then displays them with consistent formatting. TGC values are adjusted based on mode (unifo...
def printSettings(self, channel, align='>16'): """ Prints out the operating parameters of a channel Arguments: ========== channel: int Channel number. align: str Alignment format string for the printed values. """ print('Operating paramete...
def getChannels(self): """ Returns the channels in use """ return self.getParam('channelUsed') def getTime(self, channel=None): """ Returns the timestamps for given channels in seconds Arguments: ========== channel: int or list A channel number (1 to ...
This method generates a contour plot visualizing UDV data over time and depth for specified profiles and channels. It slices input data using timerange, depthrange, and limits timesteps with maxtimes to prevent RAM overload. The plot uses matplotlib's contourf, with options to adjust contour levels and other visual par...
def contour(self, profile, channel=None, timerange=slice(None), depthrange=slice(None), maxtimes=1000, **kw): """ Show the contour plot of a profile over time and depth Attention: Use this method only as a quick way to visualise the UDV-data. To save RAM, a maxim...
def set_loop(self, loop): "Pass a string of the desired loop to play into this method" self.loop = loop def set_running(self, running): "Pass a 'False' boolean into this method to end the game loop" self.running = running def set_fullscreen(self, fullscreen): "Toggles fullscreen ...
This method handles Pygame events for a Window class, processing 'QUIT' (exit) and 'KEYDOWN' events. It toggles pause state on ESC (key 27), switches fullscreen mode on F11 (key 1073741892), and prints unknown key codes. The 'QUIT' event stops the application loop.
def events(self, event): "The events method contains event listeners for the Window class" match event.type: # - Event '256' is 'pygame.QUIT' case 256: self.set_loop('NA') self.set_running(False) # - Event '768' is 'pygame.KEYDOWN' ...
def get_volqty(stock_packet): volqty_pos = get_volqty_pos(stock_packet) volqty = int(stock_packet[volqty_pos:volqty_pos+2], 16) return volqty def get_vol_size(stock_packet): # get volume-price type, from position 3 to 4 # 00: price 4 chars, volume 4 chars # 02: price 8 chars, volume 4 chars, for...
The code calculates the total volume from a stock packet by iterating over volume quantities, extracting hexadecimal values at calculated positions, converting them to integers, and summing them. It uses helper functions to determine quantity, size, and starting position, then processes each volume chunk to accumulate ...
def get_total_vol(stock_packet): volqty = get_volqty(stock_packet) vol_size = get_vol_size(stock_packet) vol_start_pos = get_volqty_pos(stock_packet) + 2 # at each volqty, get volume from stcok packet total_vol = 0 for i in range(volqty): vol_pos = vol_start_pos + ( i * vol_size ) ...
def squareUnderAttack( self, r, c ): # determine if the enemy can attack the square (r,c) self.WhitetoMove = not self.WhitetoMove # switch to opponent's turn oppMoves = self.getAllPossibleMoves() self.WhitetoMove = not self.WhitetoMove for move in oppMoves: if ...
This function generates valid castling moves for a king. It first checks if the current square is under attack, returning early if so. Depending on the player's turn and available castling rights, it calls methods to add king-side or queen-side castling moves to the list, ensuring legality based on game state and rules...
def getCastleMoves(self, r, c, moves, allyColor): if self.squareUnderAttack(r, c): return # can't castle while we are in check if (self.WhitetoMove and self.currentCastlingRight.wks) or ( not self.WhitetoMove and self.currentCastlingRight.bks ): self.getKing...
def checkForPinsAndChecks(self): pins = [] # squares where the allied pinned piece is and direction pinned from checks = [] # squares where enemy is applying a check inCheck = False if self.WhitetoMove: enemycolor = "b" allycolor = "w" startRow = se...
This function generates valid chess moves for the current player, considering checks, blocking pieces, king movement, and castling. It first checks if the king is in check, then filters moves to block checks or move the king if there's one check, or forces the king to move in case of double check. It also adds castling...
def getValidMoves(self): moves = [] self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks() if self.WhitetoMove: kingRow = self.whiteKingLocation[0] kingCol = self.whiteKingLocation[1] else: kingRow = self.blackKingLocation[0] k...
def sample_joint_R2_q(Rs, qs, z, beta, sigma2): """ Sample R2 and q jointly using the posterior on a grid of R2 and q values """ posterior = compute_posterior_grid(Rs, qs, z, beta, sigma2) # Normalize posterior posterior = posterior / np.sum(posterior) # Sample R2 and q random_idx = np.r...
This function performs one iteration of the Gibbs sampler by sequentially updating parameters R2, q, z, sigma2, and beta using their conditional distributions given the current values of the other parameters. It returns the updated parameter values after one complete cycle of sampling.
def one_gibbs_iteration(X, Y, R2, q, z, sigma2, beta, Rs, qs, k, T): """Run one iteration of the Gibbs sampler""" R2, q = sample_joint_R2_q(Rs, qs, z, beta, sigma2) z = sample_z(X, Y, z, R2, q, T) sigma2 = sample_sigma2(X, Y, R2, q, z, T) beta = sample_beta(X, Y, R2, q, sigma2, z, k) return R2, ...
def is_tie(self): return self.player1_score == self.player2_score def get_tie_score(self): if self.is_past_forty(): return 'Deuce' else: return f"{self.get_player1_score()}-All" def is_past_forty(self): return self.player1_score>= 4 or self.player2_score >= 4 def ...
The code determines the current score by checking game conditions: if tied, it retrieves the tie score; if past forty, it checks if the game is over; otherwise, it gets the standard game score. The function returns the appropriate score string based on these conditions.
def get_score(self): score = "" if self.is_tie(): score = self.get_tie_score() elif self.is_past_forty(): score = self.is_over() else: score = self.get_game_score() return score
def refresh_available_runs(self): available_runs = [] for x in glob(self.result_dir+"20*"): if '_orig' not in x and not x.startswith('_'): available_runs.append(os.path.basename(x)) available_runs.sort() if self.selectedRunIdx >=...
This code initializes a class to handle solar data processing, model evaluation, and visualization. It sets up directories, SSIM metrics configurations, selects specific runs/epochs/images, and prepares plotting tools for analyzing generated images and metrics.
def __init__(self, Epoch=None, runTimestamp=None, useTorchMetrics=True): ###################################################################### ### Which relevant timestamps file to use: self.relevant_timestamp_path = 'relevant_timestamps_171_193_304_2010-2017_c4h_10m_15sp.txt' ...
def updateSliderSatLow(val): global logscale,square_root, saturation_lower_limit, saturation_upper_limit val = calc_pre_processing(val, maxValSliderLow) saturation_lower_limit = val if saturation_lower_limit == saturation_upper_limit: saturation_lower_limit -= 1 sliderSatLow.valtex...
The function `updatePreprocessing` toggles preprocessing settings (logscale, square root, saturation clipping) based on the input label. It updates sliders, recalculates and sets text box values using `calc_pre_processing`, and refreshes the plot to reflect changes in real-time. Global variables track state, ensuring U...
def updatePreprocessing(label): global logscale, square_root, saturation_clip if label == "logscale": logscale = not logscale if label == "square root": square_root = not square_root if label == "saturation clipping": saturation_clip = not saturation_clip updateSliderSat...
def clear_buffers(self, red=True, black=True): """Clear buffer. Args: red (bool): True (default) = clear red buffer black (bool): True (default) = clear black buffer """ if red: self.ryFB.fill(0xFF) if black: self.blackFB.fill(0xF...
This code initializes a display device by configuring SPI interface and GPIO pins, setting up frame buffers for black and red/yellow images, and sending initialization commands to prepare the display for rendering. It allocates memory buffers, configures pin states, and executes setup sequences to ready the display har...
def __init__(self, spi, cs, dc, rst, busy, width=128, height=296): """Constructor for Display. Args: spi (Class Spi): SPI interface for display cs (Class Pin): Chip select pin dc (Class Pin): Data/Command pin rst (Class Pin): Reset pin bus...
def write_cmd(self, command, *args): """Write command to display. Args: command (byte): Display command code. *args (optional bytes): Data to transmit. """ self.dc(0) self.cs(0) self.spi.write(bytearray([command])) self.cs(1) # Han...
This code presents an image on an e-paper display by sending black and/or red buffer data based on the 'black' and 'red' parameters. It transmits the respective image data via commands, triggers a display refresh, waits 200ms, and checks for display readiness. The function defaults to presenting both black and red buff...
def present(self, red=True, black=True): """Present image to display. Args: red (bool): True (default) = present red buffer black (bool): True (default) = present black buffer """ if (black and self.blackimage is not None): self.write_cmd(self.DATA_ST...
def ReadBusy(self): """Check if display busy.""" self.write_cmd(self.GET_STATUS) while self.busy.value() == 0: # 0: busy, 1: idle self.write_cmd(self.GET_STATUS) sleep_ms(200) def clear_buffers(self, red=True, black=True): """Clear buffer. Args: ...
The code clears the display by resetting red and black buffers, controlled by boolean parameters. It waits for display readiness, clears buffers, updates the display, and waits again to ensure completion.
def clear(self, red=True, black=True): """Clear display. Args: red (bool): True (default) = clear red black (bool): True (default) = clear black """ self.ReadBusy() self.clear_buffers(red, black) self.present(red, black) self.ReadBusy()
def parseXml(fp): return xml_to_list(fp) def ngrams(inp, n): output = [] for i in range(len(inp)-n+1): output.append(tuple(inp[i:(i+n)])) return output def getNext(bigram,possibilities,start_notes,NMarkov): import numpy as np possibs = [ p for p in possibilities if start_notes[-(NMarkov-...
The code generates a new MIDI file using a Markov chain model based on an input MIDI file. It parses the input, constructs a Markov model of n-grams, generates new notes by predicting sequences, and writes the resulting melody to a MIDI file with specified tempo and duration, using music21 for music processing.
def generate_from_file(NMarkov=2, tempo=70,nrMinutes=12,inputfn="./midi/una_mattina.mid",outputfn="./midi/markov.mid"): import music21 as m21 scores = parseXml(inputfn) from itertools import product score = m21.stream.Score() tm = m21.tempo.MetronomeMark(number=tempo) score.append(tm) ...
def HandleSceneConfigCreation(self): if self.CheckSceneConfigStatus() == True: with open(self.GetSceneConfigPath()) as f: try: data = json.load(f) self.outjs = data except Exception as e: print(e) def AddItem...
The code's main task is to process a C4D scene by checking for a scene configuration file, collecting selected objects, generating/outputting JSON data to a scene file, optionally exporting FBX files, and notifying the user of completion. It handles scene config creation, object selection, JSON writing, FBX export, and...
def ExecuteProcess(self): # Check if Scene Config Exists in the same directory path as the C4D Scene file. Sets self.outjs to the JSON inside of the .scene file. self.HandleSceneConfigCreation() # Get Selected Items In Scene self.AddItemsToObjectsList() # Create/update the Scen...
def CreateDependenciesRow(self): self.GroupBegin(0, c4d.BFV_FIT|c4d.BFH_SCALEFIT, 2, 0, "Dependencies", 0) self.GroupBorderSpace(5, 5, 5, 5) self.GroupBorder(c4d.BORDER_GROUP_IN) self.AddCheckbox(IDC_CHECKBOX_SCENEFILEEXISTS, c4d.BFH_SCALE|c4d.BFV_TOP, 150, 20, "Config Exists") ...
The main task of the code is to initialize and configure the primary user interface (UI) layout of an application. It creates UI elements such as dependency settings, group configuration rows, path settings, and subsequent group rows, ensuring the interface is structured and functional for user interaction.
def SetupMainLayout(self): self.CreateDependenciesRow() self.CreateGroupSettingsRow() self.SetPaths() self.CreateGroupNextRow()
def SetPaths(self): filee = os.path.dirname(__file__) path = Path(filee).parent.absolute() self.dirpath = path self.doc = c4d.documents.GetActiveDocument() self.SceneFilePath = self.GetCurrentScenePath() +"/"+self.GetCurrentSceneName()+".scene" self.PartsPath = self.GetCu...
The code's main task is to generate a configuration file path for the current scene by concatenating the scene's directory path, name, and the ".scene" extension. It first sets necessary paths via `SetPaths()` and then constructs the full path using `GetCurrentScenePath()` and `GetCurrentSceneName()` to return the comp...
def GetSceneConfigPath(self): self.SetPaths() return self.GetCurrentScenePath() +"/"+self.GetCurrentSceneName()+".scene"
def GetCurrentScenePath(self): return self.doc.GetDocumentPath() def GetCurrentSceneName(self): return os.path.splitext(self.doc.GetDocumentName())[0] def SetPaths(self): filee = os.path.dirname(__file__) path = Path(filee).parent.absolute() self.dirpath = path self.doc =...
The main task of the code is to import a scene file by prompting the user to select a VLT .scene file, copying it to the current scene's directory with the same name, and updating paths. It uses Cinema 4D's storage dialog for file selection, Python's shutil for copying, and a method to set paths, ensuring the imported ...
def ImportSceneFile(self): fn = c4d.storage.LoadDialog(0, 'Select a VLT .scene File') shutil.copy(fn, self.GetCurrentScenePath() +"/"+self.GetCurrentSceneName()+".scene") self.SetPaths()
def ImportSceneFile(self): fn = c4d.storage.LoadDialog(0, 'Select a VLT .scene File') shutil.copy(fn, self.GetCurrentScenePath() +"/"+self.GetCurrentSceneName()+".scene") self.SetPaths() def GetCurrentScenePath(self): return self.doc.GetDocumentPath() def GetCurrentSceneName(self): ...
This code handles GUI button events in a C4D plugin, executing actions like importing/exporting scene files, deleting files, refreshing data, and opening dialogs. It checks the widget ID (wid) to determine which button was clicked, triggering corresponding methods such as file operations, dialog spawning, and export pr...
def Command(self, wid, msg): if wid == IDC_BUTTON_IMPORTVLTSCENEFILE: print('IDC_BUTTON_IMPORTVLTSCENEFILE Clicked') self.ImportSceneFile() # f = open(fn.decode("utf-8")) if wid == IDC_BUTTON_CLEARVLTSCENEFILE: print('IDC_BUTTON_CLEARVLTSCENEFILE...
def _test_case_1(): log('Test case 1') sys.argv = sys.argv[:1] try: main() except SystemExit: pass def _test_case_2(): log('Test case 2') sys.argv = sys.argv[:1] + [""] try: main() except SystemExit: pass def _test_case_3(): log('Test case 3') sys....
The code defines a function `test()` that sequentially executes five private test case functions: `_test_case_1()` through `_test_case_5()`. Its primary task is to run these test cases, likely validating different aspects of a program or system, possibly as part of a testing framework or verification process.
def test(): _test_case_1() _test_case_2() _test_case_3() _test_case_4() _test_case_5()
def load_palette(self, path="auto"): """ Loads a DAT file representing a graphical palette """ if path is None: self.palette = None self.palette_name = "None" return True if path == "auto": path = os.path.join( os.path.dirname(os.p...
This code initializes a class to load and parse ZZT/SAV game files, setting up game elements like palette, character set, world data, and boards. It handles file input, metadata, and game state loading for a ZZT-like game engine.
def __init__(self, file=None): self.fh = None self.meta = Meta() self.world = World() self.boards = [] # Palette settings self.load_palette() # Charset settings self.load_charset() if file: self.load_file(file) if file[-4:].lower() ...
def generate_fake_users(self):#1000 users for _ in range(100): fake_user = self.fake_user() self.users_list.append(fake_user) self.users_id.append(fake_user['user_id']) def fake_user_package(self):#1000 package for user in self.users_id: data=self.fake_sin...
The main task of the code is to generate fake user, site, and metrics data, export them into JSON files (or other formats), and insert them into a database. It creates user packages, associates users with packages, and saves site-package relationships. The process includes generating data, writing files, and calling in...
def init_fake_data(self,format='JSON'): self.generate_fake_users() users_file = f'fake_users.{format}' with open(users_file, "w") as file: json.dump(self.users_list, file) insert_users_data(self.users_list) print(f"Fake users has been exported to {users_file}") ...
def upload(filename): def read_file(filename, chunk_size=5242880): with open(filename, 'rb') as _file: while True: data = _file.read(chunk_size) if not data: break yield data response = requests.post(upload_endpoint, ...
The code downloads audio from a YouTube video, uploads it, transcribes the audio, and returns a score based on the transcribed text.
def Download(video_url): data = YouTube(video_url) videos = data.streams.filter(only_audio=True) videos[0].download(filename="sample.mp3") audio_url = upload('sample.mp3') text = get_transcript(audio_url) return score_text(text)
def upload(filename): def read_file(filename, chunk_size=5242880): with open(filename, 'rb') as _file: while True: data = _file.read(chunk_size) if not data: break yield data response = requests.post(upload_endpoint, ...
The code processes an audio input by saving it as a WAV file, uploading it to generate a URL, transcribing the audio into text, and returning a score based on the transcribed text.
def audio_input(audio): sr, data = audio sf.write("temp.wav", data, 44100) audio_url = upload("temp.wav") text = get_transcript(audio_url) return score_text(text)
def upload(filename): def read_file(filename, chunk_size=5242880): with open(filename, 'rb') as _file: while True: data = _file.read(chunk_size) if not data: break yield data response = requests.post(upload_endpoint, ...
The code processes an audio input by saving it as a WAV file, uploading it to generate a URL, transcribing the audio into text, and then scoring the transcribed text. The main task is to convert audio to text and evaluate its quality or relevance through scoring.
def audio(audio): sr, data = audio sf.write("temp.wav", data, 44100) audio_url = upload("temp.wav") text = get_transcript(audio_url) return score_text(text)
def symbolsEst(Y, H, A, Qx, Qn, nSlots, L): ''' Function that implements the symbols estimation for spread-based MIMO system X: diagonal matrix contains the symbol for each user, H: channel matrix, N: noise Input: Y: received vector, H: channel matrix, A: spreading sequence ...
The code decodes received signals using a polar decoder with interleaving. It estimates symbols, decodes each user's data, and separates successfully decoded users from undecoded ones. The function returns lists of decoded/undecoded users, estimated symbols, and decoded messages, using QPSK mapping and channel estimati...
def decoder(self, H, idxSSHat): K = idxSSHat.size symbolsHatHard = np.zeros((K, self.nDataSlots), dtype=complex) # ==================================== Symbol Estimation Decoder ============================================== # symbolsHat = symbolsEst(self.Y[self.nPilots::, :], H, self.A[:, idxSSHat], n...
def checkPerformance(self): numDE, numFA = 0, 0 for i in range(self.count): flag = 0 for k in range(self.K): binSum = sum((self.msgs[k, :] + self.msgsHat[i, :]) % 2) if binSum == 0: flag = 1 break if flag == 1: numDE +=...
The code implements a receiver to detect and decode user messages from noisy signals using energy detection, channel estimation, polar coding, and successive interference cancellation (SIC). It iteratively identifies users, estimates their symbols, cancels interference, and computes detection (DE) and false alarm (FA) ...
def receiver(self, Y): ''' Function to recover the messages of the users from noisy observations Input: The received signal, dimensions of Y, n x M Output: Probability of Detection and False Alarm ''' self.msgsHat = np.zeros((self.K, self.Bf + self.Bs)) # Store the rec...
def reset_bord(): global BORD BORD=[ [3,2,7], [8,6,0], [1,5,4] ] def solve_largeur(): root=Node(BORD,0) nodes=[] nodes.append(root) visited=set() n=0 while nodes : if nodes[0].bord==TARGET: getSolPath(nodes[0],SOLUTIONPATH_LARGEUR) ...
The code handles button clicks to trigger different pathfinding algorithms (BFS, DFS, IDDFS, A*), resets the board, and displays the number of nodes visited for each algorithm on the screen using Pygame.
def display_algo(): if b1.draw_button(): reset_bord() solve_largeur() if b2.draw_button(): reset_bord() solve_profondeur() if b3.draw_button(): reset_bord() solve_profondeur_limite(20) if b4.draw_button(): reset_bord() solve_Astar() if ...
def eval_class(gt_annos, dt_annos, metric, iou_th): metric_names = ['BEV', '3d'] case_name = '{}_{}'.format(metric_names[metric], iou_th) overlaps, total_gt_num, total_dt_num = calculate_iou_partly(gt_annos, dt_annos, metric, num_parts=100) confidence = [] tp = [] fp = [] difi...
The function `get_tree_eval_result` evaluates object detection performance by comparing ground truth (`gt_annos`) and detected (`dt_annos`) annotations across specified classes (`current_classes`). It filters annotations for each class, computes 2D (BEV) and 3D evaluation metrics using predefined IoU thresholds (0.3, 0...
def get_tree_eval_result(gt_annos, dt_annos, current_classes, PR_detail_dict=None): min_overlaps = [0.3, 0.5, 0.7] ret2d_dict = {} ret3d_dict = {} ret_dict = {} result = '\n' for cur_cls in current_classes : gt_annos_cls = [] total_gt_num = 0 for gt_anno in gt_annos ...
def download_file(url, folder): if not os.path.isdir(folder): os.makedirs(folder) try: urllib.request.urlretrieve(url, folder + '/icon') except: try: urllib.request.urlretrieve( "http://127.0.0.1:6391/images/default-browser-icon.png...
The main task of the code is to fetch search results from a local API, process each result by downloading associated icons, and format them into structured data items with URLs, titles, and modifier actions (e.g., markdown, anybox, or direct links). The function returns a list of these items for display or further proc...
def get_links(): headers = {'x-api-key': api_key} payload = { 'q': q, 'limit': 30, } data = urllib.parse.urlencode(payload) req = urllib.request.Request('http://127.0.0.1:6391/search?' + data, headers=headers) try: with urllib.request.urlopen(req) as response: list = json.loads(respons...
def visibility(polygons, poit1, poit2): for polyg in polygons: for i in range(len(polyg)): if poit1 != polyg[i-1] and poit1 != polyg[i] and poit2 != polyg[i-1] and poit2 != polyg[i]: if check_intersect(poit1,poit2,polyg[i-1],polyg[i]): return 0 # f...
This code constructs a roadmap graph for polygonal environments by connecting reflex vertices that are mutually visible and satisfy geometric constraints. It maps vertices to indices, builds adjacency lists with weighted edges based on visibility and bitangent/cons_reflex checks, and returns the graph structure for pat...
def computeSPRoadmap(polygons, reflexVertices): vertexMap = dict() adjacencyListMap = dict() for i in range(len(reflexVertices)): vertexMap[i+1] = reflexVertices[i] adjacencyListMap[i+1] = [] for i in range(len(reflexVertices)-1): for j in range(i+1, len(reflexVertices)): ...
def __deleteInstances(self): item = self.__class__.toolName + 'WorkspaceControl' if cmds.workspaceControl(item, ex=True, q=True): cmds.deleteUI(item) def __initTable(table, cols): table.setMinimumWidth(50) table.setSelectionMode(QTableWidget.ExtendedSelection) table.s...
This code initializes a Maya plugin GUI window for managing light presets, creating a UI with a menu bar, splitter layout for light/attribute tables, search bars, and connections to update filters. It sets up window properties, UI components, layouts, and initializes data handling via a logic object, defaulting to LL.L...
def __init__(self, parent=None, logic=None): self.__deleteInstances() if parent is None: parent = shiboken2.wrapInstance(long(MayaUI.MQtUtil.mainWindow()), QtWidgets.QMainWindow) super(self.__class__, self).__init__(parent=parent) self.logic = logic if self.logic is ...
def __checkDir(self): if not os.path.exists(self.__startDir): os.makedirs(self.__startDir) return False return True def renderAll(self): self.renderCheckmark() self.renderCross() self.renderExclamation() self.renderPlus() def __fileExists(self, pat...
The method ensures required SVG files are present by checking their existence and generating them if missing. It first sets a flag, verifies a directory condition, and triggers a full render if the directory check fails. Subsequent checks for specific SVG files (checkmark, cross, exclamation, plus) trigger individual r...
def renderRequired(self): self.requiredChecked = True if not self.__checkDir(): self.renderAll() return if not self.__fileExists("checkmark.svg"): self.renderCheckmark() if not self.__fileExists("cross.svg"): self.renderCross() if n...
def find_make_symbolic(file_path): #Gets the names of the variables as seen in the program and in KLEE symbolic_var=[] program_file=open(file_path,"r+") lines=program_file.readlines() for i in range(len(lines)): #Finding the lines which make the variables symbolic if ("klee_make_symb...
The main task of the code is to generate symbolic input data based on variable structures from a program and assembly files. It processes symbolic variables, determines their types (arrays/structures), calculates element sizes, generates formatted numeric values, and constructs a string containing symbolic names, gener...
def gen_input(program_path,assembly_path): #Symbolic var structure : #SIZES IN BITS not un bytes #[var_name in the program, symbolic_name, type, size] everything as strings #In the case where there is an array the structure looks like : #[var_name in the program, symbolic_name, 'array', global size,...
def deriveNonlinearity(flatFiles=None, samples_per_ramp=None, ramps_per_file=None, times=None, time_axis=0, doplot=True): # The "flatFiles", "samples_per_ramp", "ramps_per_file", and "times" arguments # here all need to be lists, and they all need to be the same length. nFiles = len(flatFiles) nl_coeff...
This function processes science, dark, and flat image files to generate corrected science frames by creating master dark and flat references. It applies nonlinearity correction, bad pixel masking, and combines calibration data. Outputs include corrected science frames, optional master dark/flat files, and per-ramp FITS...
def makeCorrectedFrame(files_science=None, files_dark=None, files_flat=None, do_science=True, do_flat=True, do_dark=True, master_dark=None, master_flat=None, nl_correction=None, nl_correction_outFile=None, bad_pixels=None, bad_p...
def setup(config=None): ''' This loads and parses the config file. It makes a dictionary which contains the keyword arguments needed to run makeCorrectedFrames output: a dictionary which can be used as input to makeCorrectedFrame(), resulting in corrected frames reduced in the m...
The code processes astronomical data using a configuration file to generate calibrated images. It creates corrected frames, runs SExtractor for object catalogs if enabled, and generates plots. Key steps include parsing arguments, reading config settings, processing frames with `makeCorrectedFrame`, and optionally creat...
def main(argv): import argparse import configparser import socket parser = argparse.ArgumentParser( description='generate calibrated images of some data.') parser.add_argument('--config', default='default.config', help="config file to use for processing.") args = ...
def is_capture(self) -> 'Bool': if self.cap is not None: return True for y in range(8): for x in range(8): if ((self.board[y, x] * self.current_player > 0) and self.can_capture(x, y)): return True return False def do_move_man(self, from...
This function validates and executes a move in a checkers game. It checks if the move is legal by verifying the source piece belongs to the current player, the target square is empty and of the correct color, and no same-colored piece is captured. If valid, it delegates to either `do_move_man` or `do_move_king` based o...
def do_move(self, from_x, from_y, to_x, to_y, need_to_cap: bool = None) -> Optional['BoardState']: if (self.cap is not None and (from_x, from_y) != self.cap): sys.stdout.flush() return None if (self.board[from_y, from_x] * self.current_player <= 0): return None ...
def is_capture(self) -> 'Bool': if self.cap is not None: return True for y in range(8): for x in range(8): if ((self.board[y, x] * self.current_player > 0) and self.can_capture(x, y)): return True return False def on_board(self, x, y) -...
This function generates all possible next board states by iterating through the board, checking valid moves for the current player, and applying movement rules in various directions and step sizes. It handles capture scenarios, skips invalid pieces, and collects valid new board states via `do_move` into a list.
def get_possible_moves(self) -> List['BoardState']: res = [] A = self.is_capture() for y in range(8) if self.current_player == 1 else reversed(range(8)): for x in range(8): if (self.board[y, x] * self.current_player <= 0): continue ...
def create_abstract_item(self) -> Optional[AbstractProductItem]: metric: Optional[str] = None name: Optional[str] = None while name is None: try: self.log(f"Input name") name = input("Name: ").strip() except Exception: pass...
The main task of this code is to create a concrete product item by gathering user input for details like an abstract item selection, store specificity, measurement, name, and brand. It interacts with the user to search for or select an abstract item, determine store-specific settings, input measurement and name, and ch...
def create_concrete_item(self, purchase_store, item_search_phrase) -> ConcreteProductItem: abstract_item: Optional[AbstractProductItem] = None store_specific: Optional[bool] = None store: Optional[Store] = None measurement: Optional[int] = None name: Optional[str] = None ...
def input_select_store(self) -> Store: """routine for selecting and returning store from other routines""" selected_store = None try: self.log("Select store:") self.log("-------------") for store in self.stores: # self.log(f'{temp_item_id_help...
The main task of the code is to input and record purchase details by selecting a store, entering a date, searching for items (abstract/concrete), specifying quantity, measurement, and cost, then saving the purchase data. It allows dynamic updates to date/store, item creation, and batch processing of purchases with vali...
def enter_purchase(self): selected_store: Optional[Store] = None date: Optional[datetime.date] = None while True: while selected_store is None: selected_store = self.input_select_store() while date is None: try: self.lo...
def __produce_ovpn_config(config_object): cfg_str = '\n'.join(config_object) return cfg_str def __prepare_ovpn_config_object(self, certs): config_lines = list() config_lines.append('# OpenVPN client config') config_lines.append('# generated automatically by OVCCG software') ...
The code generates an OpenVPN configuration file by collecting runtime parameters, preparing certificates, and creating a config string. It saves the config to a specified path (based on runtime arguments or defaults) and prints a confirmation message indicating the file's location.
def cfg_get(self): """ Main method of OVCCG class used for run config generation algorithm :return: None """ if self.__runtime_args.user and self.__runtime_args.email: config = self.__produce_ovpn_config( self.__prepare_ovpn_config_object( ...
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ for i, j in self.globalIdx: if any(self...
The main task of the code is to simulate a game between a predefined offensive agent and defensive agent using either minimax or alpha-beta pruning. It tracks the best moves, corresponding values, expanded nodes, game boards at each step, and determines the winner. The function alternates turns between maxPlayer and mi...
def playGamePredifinedAgent(self, maxFirst, isMinimaxOffensive, isMinimaxDefensive): """ This function implements the processes of the game of predifined offensive agent vs defensive agent. input args: maxFirst(bool): boolean variable indicates whether maxPlayer or minPlayer plays first....
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ for i, j in self.globalIdx: if any(self...
The code simulates a game between the agent and a predefined offensive agent using minimax or alpha-beta pruning. It alternates turns, evaluates possible moves, tracks best moves, game boards, expanded nodes, and determines the winner. The agent selects optimal moves based on specified algorithms, returning game states...
def playGameYourAgent(self,maxFirst,isMinimaxOffensive,isMinimaxDefensive): """ This function implements the processes of the game of your own agent vs predifined offensive agent. input args: output: bestMove(list of tuple): list of bestMove coordinates at each step gameB...
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ for i, j in self.globalIdx: if any(self...
The function `my_minimax` implements the minimax algorithm for ultimate tic-tac-toe, recursively evaluating game states to determine the optimal move. It checks terminal conditions (max depth, no moves left, or a winner) and returns an evaluation score. For non-terminal states, it generates valid moves, simulates them,...
def my_minimax(self, depth, currBoardIdx, isMax): """ This function implements minimax algorithm for ultimate tic-tac-toe game. input args: depth(int): current depth level currBoardIdx(int): current local board index alpha(float): alpha value beta(float): beta val...
def checkMovesLeft(self): """ This function checks whether any legal move remains on the board. output: movesLeft(bool): boolean variable indicates whether any legal move remains on the board. """ for i, j in self.globalIdx: if any(self...
This function enables an AI agent (maxPlayer) to play against a human (minPlayer) in a game, using minimax for AI moves and human input for player moves. It tracks game states, best moves, expanded nodes, and determines the winner. The loop continues until no moves remain or a winner is found, returning game boards, mo...
def playGameHuman(self): """ This function implements the processes of the game of your own agent vs a human. output: bestMove(list of tuple): list of bestMove coordinates at each step gameBoards(list of 2d lists): list of game board positions at each move winner(int): 1 ...
def input_spellchecker(self, entered_string): #INITAL STAGE OF CALLING THE SPELL CHECK #CHECKING OF THE CORRECTNESS OF THE INPUT tup = ('aa','ab','bb','ba') new_string = [] #lets make a copy of entered_string copy_entered_string = entered_string[:] #making a copy of the input for i in copy_entered_stri...
The main task of the code is to process an input string through spell-checking, preprocessing, and stage2 initialization, handling errors at each step. It writes valid results to "input.txt" and returns the final string set, or error details if any stage fails.
def input(self,entered_string): #AKA MAIN FUNCTION #FUNCTION 1 #THIS IS THE FIRST FUNCTION THAT IS CALLED #THIS WILL ACT AS THE MAIN FUNCTION global error_catch global error_update global error_log #ERROR HANDLING if(len(entered_string)==0): error_catch.append([1,error_log[1]]) error_updat...
def runGeneration(self): if self.mutationPhysicalConstraints: interactionPairs = getNeighborPairs(self.populationGraph, self.nodes, self.nodePos) print('Running {} interactions...'.format(len(interactionPairs))) else: interactionPairs = pickInteractionPairs(self.nodes...
This function simulates evolutionary processes over multiple generations. It iterates through 'numGenerations', executing reproduction (via 'normal', 'moran', or 'social' methods), logging generation data at intervals defined by 'logFreq'. Logs are aggregated into 'perGenLogs' and passed to 'finalLogs' for post-process...
def runSimulation(self): print('===== Initiating simulation ======') perGenLogs = [] for i in range(self.numGenerations): print('-- Generation {} --'.format(i)) lg = self.runGeneration() lg['generation'] = i l = None if i%self.lo...
def __draw_flag(self, canvas : pygame.Surface, target : cell) : if not target.has_flag() : return self.__draw_image_at_index(canvas, self.flagImageIdx, self.__minefield.get_rect(target)) def __draw_mine_count(self, canvas : pygame.Surface, curCell : cell) : if curCell.is_armed() : return min...
This code renders a minefield game board on a canvas, updating cell visuals based on their state (visited, armed, detonated). It draws cells with appropriate colors, flags, mine counts, highlights active cells, and reveals all mines if the game is completed.
def draw(self, canvas : pygame.Surface) : canvas.fill(self.fillColour) minefield = self.__minefield if minefield is None : return for cell in self.__cells : if not cell.is_visited() : minefield.draw_cell(canvas, cell, self.boardColour, self.lineColour) self.__draw_flag(canva...
def __new_game(self) : canvasSz = self.__board.make_rect(32, 18, 100) self.__canvas = self.__set_canvas_size(canvasSz) def __load_res(self) : self.__sprites = strip(64, 64, 'assets/field_sprites.png') self.__endSprites = strip(256, 256, 'assets/win_fail.png') def __poll_events(self) : board = self._...
The code initializes a game by creating a new game instance, loading resources, attaching sprites to the game board, and entering a loop to process events and render the game until events stop.
def run(self) : self.__new_game() self.__load_res() self.__board.attach_sprites(self.__sprites) while self.__poll_events() : self.__present()
def _install_dir(release): release_dir = _release_dir(release) return release_dir + 'app/' def _database_name(release): release_name = release.replace('.','') db_name = "prestashop" + release_name return db_name def remove_database(db_user, db_password, db_name): logi("Removing db '{}' ...".for...
The main task of the code is to set up an application instance by installing it in a specified directory, configuring a database, copying source files, and dumping the database, but only if the target directory does not already exist. If the directory exists, it logs that the instance already exists and copies template...
def setup(release): install_dir = _install_dir(release) database_name = _database_name(release) if not os.path.isdir( install_dir ): remove_database(MYSQL_USER, MYSQL_PASSWORD, database_name) copy_src(installDir = install_dir, release = release) install(installDir = install_dir, ...