dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_question_grades(recalculate, recalculate_numbers): """ Example for single question: let there be a question with 4 sub-questions that have graded by 5, 5, 5, and 10 but actually total grade for the question should be 20 and last question should be scaled to make max point 5. For this exa...
The main task of the code is to automate updating quiz/exam scores in a spreadsheet and sending personalized email notifications to students. It parses grading parameters, retrieves scores from sheets, updates administrative records, and sends emails via Gmail with attached files if configured. The process includes han...
def main(args): # parse recalculate arguments question_grades = get_question_grades(args.recalculate, args.recalculate_numbers) # get scores from the sheets question_headers, scores = get_scores(args.sheet_title, args.score_title, get_exceptions(args.exceptions...
def create_build_gradle(root: str, env: Environment, args: dict): build_gradle = root + '/' + 'build.gradle' template = env.get_template('app/build.gradle.jinja') package_name = get_package_name(args) with open(build_gradle, 'w') as f: f.write(template.render(package_name=package_name)) pri...
The main task of the code is to create an Android app module by generating necessary files and directory structure. It initializes a new app directory under the given root path, then creates Gradle build scripts, ProGuard rules, dependency configurations, and source files to set up a functional Android project module.
def create(root: str, env: Environment, args: dict): print('🛠 App module...') location = root + '/app' os.mkdir(location) create_build_gradle(location, env, args) create_proguard_rules(location, env) create_dependencies_gradle(location, env, args) create_sources(location, env, args)
def flush(self): """Save any remaining in-memory data to disk""" if self.compress: with BZ2File(self.get_next_file(), "wb") as f: self._flush(f) else: with open(self.get_next_file(), "wb") as f: self._flush(f) def clear(self): self....
The main task of the code is to replace the current contents of an object with the elements from the provided iterable. It first flushes and clears existing data, then appends each item from the iterable to rebuild the content.
def save(self, iterable: t.Iterable): """Replace everything with the current contents""" self.flush() self.clear() for i in iterable: self.append(i)
def token_requests_to_valid(self): token_number = int(input('How many tokens to check?: ')) self.all_pools = self.getPairs(token_number) self.build_routes(self.all_pools, self.arb_toks) self.pcsPairAbi = None print(f'Gathered {len(self.all_pools)} pools.') _valid_pools =...
This function loads valid pools from a JSON file, generates route data if missing, assigns tri-routes to pools using pickle-stored data, and prepares pools for reserve checks. It handles file absence by prompting user input or regenerating data, then processes pools to identify arbitrage opportunities and their routes,...
def get_duo_pools_from_valid(self): try: with open("valid_pools.json", 'r') as f: valid_pools = json.load(f) print(f'Checking {len(valid_pools)} pools...') except FileNotFoundError: input('Valid pools were never found. Do you want to check now?') ...
def token_requests_to_valid(self): token_number = int(input('How many tokens to check?: ')) self.all_pools = self.getPairs(token_number) self.build_routes(self.all_pools, self.arb_toks) self.pcsPairAbi = None print(f'Gathered {len(self.all_pools)} pools.') _valid_pools =...
The code initializes a blockchain connection using Web3 and an async client, loads token and pool data, and sets up a filter for monitoring transactions. It checks user input to refresh token lists, builds a pair dictionary, and raises an error if insufficient pools are found, aiming to prepare for blockchain data inte...
def __init__(self): start_t = time.time() self.provider = HTTPProvider("https://bsc-dataseed.binance.org/") self.w3 = Web3(self.provider) self.async_client = AsyncClient(self.w3) self.pcsPairAbi = None self.all_tokens = None self.token_pairs = None self.ex...
def stop(self): self.media.stop() def main(self, para, expression): my_songs = SongManager() songs_to_play = my_songs.get_song() self.chosen_song = songs_to_play[random.randint(0, len(songs_to_play)-1)][expression] print("* NOW PLAYING :- *") print(str(self.chosen_song)) ...
The code's main task is to handle the 'next' command by stopping the current process, retrieving the next song using the 'main' method, and then searching for that song with a parameter of 2, likely for playback or retrieval.
def next(self,expression): self.stop() song = self.main('next',expression) self.search(song, 2)
def search(self, name, n): query_string = urllib.parse.urlencode({"search_query": name}) formatUrl = urllib.request.urlopen("https://www.youtube.com/results?" + query_string) search_results = re.findall(r"watch\?v=(\S{11})", formatUrl.read().decode()) clip2 = "https://www.youtube.com/wat...
This code creates a Tkinter GUI window with buttons to control audio playback, including 'play', 'stop', 'pause/play', and 'next' functions. The 'play' button triggers a search method with the provided song and an argument of 2, while other buttons invoke stop, pause, and next methods. The interface allows user interac...
def gui(self, song): m = tk.Tk() m.title("play n pause interface") self.start_button = tk.Button(m, text="play", width=10, height=2, command=lambda: [self.search(song, 2)]) stop_button = tk.Button(m, text="stop", width=10, height=2, command=lambda: [self.stop()]) pause_button = t...
def getAverageTimesequential_search(list): total_time = 0 for i in range(100): myList = get_me_random_list(list) start = time.time() sequential_search(myList, 9999) time_spent = time.time() - start total_time += time_spent return total_time / 100 def getAverageTimeor...
The main task of the code is to benchmark and compare the average execution times of different search algorithms—sequential, ordered sequential, binary iterative, and binary recursive—on lists of varying sizes (500, 1000, and 5000 elements). It calculates and prints the average time taken for each algorithm to run, for...
def main(): avg_time = getAverageTimesequential_search(n500) print(f"sequential search took {avg_time:10.7f} seconds to run, on average for a list of {n500} elements") avg_time = getAverageTimesequential_search(n1000) print(f"sequential search took {avg_time:10.7f} seconds to run, on average for a list...
def getAverageTimePythonSort(list): total_time = 0 for i in range(100): myList = get_me_random_list(list) start = time.time() python_sort(myList) time_spent = time.time() - start total_time += time_spent return total_time / 100 def getAverageTimeInsertion_Sort(list):...
The main task of the code is to benchmark and compare the average execution times of three sorting algorithms—Python's built-in sort, insertion sort, and shell sort—on lists of 500, 1000, and 5000 elements, printing the results for performance analysis.
def main(): avg_time = getAverageTimePythonSort(n500) print(f"Python sort took {avg_time:10.7f} seconds to run, on average for a list of {n500} elements") avg_time = getAverageTimePythonSort(n1000) print(f"Python sort took {avg_time:10.7f} seconds to run, on average for a list of {n1000} elements") ...
def _read_batch_features(self, filenames, num_epochs, batch_size, reader_num_threads=1, parser_num_threads=1, shuffle=False, shuffl...
This test function verifies the correct reading of batched data from multiple files using different batch sizes and epoch counts. It checks data integrity through _verify_records and ensures OutOfRangeError is raised when exhausting data, testing both single-file and multi-file scenarios with varying parameters.
def testRead(self): for batch_size in [1, 2]: for num_epochs in [1, 10]: with ops.Graph().as_default() as g: with self.test_session(graph=g) as sess: # Basic test: read from file 0. self.outputs = self._read_batch_features( filenames=self.test_filename...
def _read_batch_features(self, filenames, num_epochs, batch_size, reader_num_threads=1, parser_num_threads=1, shuffle=False, shuffl...
The code tests the parallelism of data readers and parsers in TensorFlow. It iterates over varying batch sizes, reader threads, and parser threads to validate correct data reading and parsing. It verifies data integrity across multiple epochs and thread configurations, ensuring the system raises an `OutOfRangeError` wh...
def testParallelReadersAndParsers(self): num_epochs = 5 for batch_size in [1, 2]: for reader_num_threads in [2, 4]: for parser_num_threads in [2, 4]: with ops.Graph().as_default() as g: with self.test_session(graph=g) as sess: self.outputs = self._read_batch_fea...
def _create_file(self, fileno, header=True, comment=True): fn = os.path.join(self.get_temp_dir(), "csv_file%d.csv" % fileno) f = open(fn, "w") if header: f.write(",".join(self.COLUMNS) + "\n") for recno in range(self._num_records): f.write(self._csv_record(fileno, recno) + "\n") if com...
This test verifies creating a CSV dataset without header lines or comments. It uses a file generated without headers, configures a dataset with batch size 2 and 10 epochs, then checks if the dataset correctly produces expected records through session execution.
def test_make_csv_dataset_with_no_comments(self): """Tests that datasets can be created from CSV files with no header line. """ defaults = self.DEFAULTS file_without_header = self._create_file( len(self._test_filenames), comment=False) with ops.Graph().as_default() as g: with self.test...
def _create_file(self, fileno, header=True, comment=True): fn = os.path.join(self.get_temp_dir(), "csv_file%d.csv" % fileno) f = open(fn, "w") if header: f.write(",".join(self.COLUMNS) + "\n") for recno in range(self._num_records): f.write(self._csv_record(fileno, recno) + "\n") if com...
This test verifies that CSV datasets can be created without a header line by generating a header-less file, constructing a dataset with specified parameters (batch size, epochs), and confirming the output matches expected results through validation.
def test_make_csv_dataset_with_no_header(self): """Tests that datasets can be created from CSV files with no header line. """ defaults = self.DEFAULTS file_without_header = self._create_file( len(self._test_filenames), header=False) with ops.Graph().as_default() as g: with self.test_se...
def get_points_center_rtheta(self, dist, theta_offset, index=None): """ Return 6 points that are dist-and angle theta away from the hex center Parameters ---------- dist : float distance from the hexagon center, in hexagon-size units. Note: This is not absolute distance. T...
This method generates and returns specific points on or within a hexagon based on parameters like point type (`center`, `vertex`, `edge`, etc.), distance from the center, angle, and index. It handles cases for center points, vertices, edges, spokes/apothems, and returns 1–6 coordinates in [(x,y)] format, optionally ran...
def point( self, pt_name, action=None, index=None, dist=None, theta=None, ax=None, **kwargs ): """ Return one or six points in the hexagon based on specifications. Parameters ---------- pt-name: string Name of the point type desired: Allowable v...
def render_spokes(self, index=None, ax=None, **kwargs): """ Draws spokes from center to specific vertices Parameters ---------- index: None or integer index specifies which vertex to use when drawing the spoke If index is None, then all 6 spokes...
The code's main task is to draw one or multiple lines within a hexagon based on specified start and end points (e.g., center, vertices, edges). It handles various configurations like spokes from the center to vertices, edge connections, and customizable positions/distances. The function uses internal methods (`render_s...
def line( self, start_point, end_point, start_pos=None, end_pos=None, index=None, line_len=None, theta=None, ax=None, **kwargs, ): """ Draw one or multiple lines in the hexagon based on specifications. P...
def get_lattice_points(self, density=2): """ This method serves two purposes. It will store the interior 'lattice' points of a hexagon in a dictionary called `lattice` which can then be used. It also returns the dictionary, for plotting purposes. Parameters ...
The function `draw_symmetrical_shapes` draws symmetrical lines or polygons by connecting lattice points across a specified axis of reflection (x, y, z, or 6-fold). It generates mirrored pairs of shapes using input lattice coordinates, applies color schemes for original and reflected elements, and supports closure of sh...
def draw_symmetrical_shapes( self, lattice_tup, axis, shape=["line"], ax=None, color_scheme={}, close=False, connect_original_points=True, draw_axis=False, **kwargs, ): """ Draw pairs of lines connecting the given points...
def get_lattice_points(self, density=2): """ This method serves two purposes. It will store the interior 'lattice' points of a hexagon in a dictionary called `lattice` which can then be used. It also returns the dictionary, for plotting purposes. Parameters ...
The function `_draw_symmetrical_lines` draws symmetrical line pairs across a specified axis (x, y, z, or 6-fold) for given lattice points. It generates mirrored points using reflection symmetry, applies color schemes for original/reflected lines, and connects them. For 6-fold symmetry, it handles hexagonal segments wit...
def _draw_symmetrical_lines( self, lattice_tup, axis, color_scheme={}, close=False, connect_original_points=True, draw_axis=False, **kwargs, ): """ Draw pairs of lines connecting the given points across the specified axis. ...
def check_no_matches(*args) -> bool: """Check that all of the arguments are unique (or are None). Examples -------- 1. {1, 2, None, None} -> True 2. {0, 0} -> False """ num_none = sum(arg is None for arg in args) num_unique = len({arg for arg in args if arg is not None}) return len(...
The main task of the code is to parse command-line arguments for input files and plot options, validate for duplicate output paths, and generate specified plots (runtime, accuracy, throughput) using default or custom output names. It processes input files with given extensions and produces visualizations for different ...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--inputs", "-i", nargs="+", type=Path, help="file/directory of input(s)" ) parser.add_argument( "--extensions", nargs="+", type=str, default=[".log"], help="extensions to process (format:...
def mattson(trace: List[int]) -> Tuple[Dict[int, int], int]: seen_elements: Set[int] = set() histogram: Dict[int, int] = {} infinite_stack_distances: int = 0 for i, e in enumerate(trace): if e not in seen_elements: seen_elements.add(e) infinite_stack_distances += 1 ...
The code processes two trace datasets (SIMPLE_TRACE and TRACE_100) by generating histograms using the `mattson` function, then sequentially converting them into list and dictionary formats via `listify_histogram` and `dictify_histogram`. It prints the intermediate results at each step to demonstrate the transformation ...
def main(): histogram = mattson(SIMPLE_TRACE) print(histogram) histogram = listify_histogram(histogram) print(histogram) histogram = dictify_histogram(histogram) print(histogram) print("---") histogram = mattson(TRACE_100) print(histogram) histogram = listify_histogram(histogra...
def divide_array(array: np.ndarray, subdivisions: int): """Divide an array into evenly sized chunks.""" return [ array[i * len(array) // subdivisions : (i + 1) * len(array) // subdivisions] for i in range(subdivisions) ] def choose_selective_intervals(array: list[np.ndarray], head: None | in...
The main task of the code is to process input files containing numerical data, split them into intervals, analyze statistical properties, and generate visualizations like cache size miss rate plots and histograms. It uses command-line arguments to control input files, interval selection, and plotting parameters, ultima...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--input-files", "-i", nargs="+", type=str, help="input file paths (root is used for output path)", ) parser.add_argument( "--head", type=int, default=None, help="u...
def getNumberOfWords(file): data=file.read() words=data.split() return str(len(words)) def execute_query(query,args=()): cur=get_db().execute(query,args) rows=cur.fetchall() cur.close() return rows def commit(): get_db().commit()
The code handles user registration by validating form inputs, processing uploaded files, checking for existing usernames in a database, and inserting new user data if valid. It returns error messages for missing fields or duplicate usernames, then redirects to a login page upon successful registration.
def registration(): message='' if request.method=='POST' and str(request.form['username'])!="" and str(request.form['password'])!="" and str(request.form['firstname'])!="" and str(request.form['lastname'])!="" and str(request.form['email'])!="": username=str(request.form['username']) ...
def create_bingo_boards_from_lines(inputLines): allBoards = [] bingoLines = create_all_bingo_lines(inputLines) linesForNewBoard = [] countId = 1 for x in range(len(bingoLines)): linesForNewBoard.append(bingoLines[x]) if len(linesForNewBoard) == 5: boardToAdd = BingoBoard...
The function determines the first winning Bingo board by iterating through drawn numbers, updating boards, and checking for horizontal/vertical wins. It returns the winning board and sets the global `winning_number` to the number that caused the win, or None if no win occurs.
def ChooseBoard(): global winning_number winning_number = 0 boards = create_bingo_boards_from_lines(read_input_file("bingoBoards1.txt")) bingoBalls = get_bingo_balls() for number in bingoBalls: boards = pull_number(number, boards) verticalBingoBoard = check_vertical_bingo(boards) ...
def create_bingo_boards_from_lines(inputLines): allBoards = [] bingoLines = create_all_bingo_lines(inputLines) linesForNewBoard = [] countId = 1 for x in range(len(bingoLines)): linesForNewBoard.append(bingoLines[x]) if len(linesForNewBoard) == 5: boardToAdd = BingoBoard...
The main task of the code is to simulate a bingo game by processing numbered balls sequentially, updating bingo boards, and checking for vertical or horizontal wins. It returns the first winning board and corresponding number when a win is detected (winningNumber == 200), otherwise returns None.
def go_through_boards(): boards = create_bingo_boards_from_lines(read_input_file("bingoBoards1.txt")) bingoBalls = get_bingo_balls() for number in bingoBalls: boards = pull_number(number, boards) verticalBingoBoard = check_vertical_bingo(boards) if verticalBingoBoard.winningNumber ...
def create_bingo_boards_from_lines(inputLines): allBoards = [] bingoLines = create_all_bingo_lines(inputLines) linesForNewBoard = [] countId = 1 for x in range(len(bingoLines)): linesForNewBoard.append(bingoLines[x]) if len(linesForNewBoard) == 5: boardToAdd = BingoBoard...
The main task of the code is to process bingo boards by removing those that have already achieved a bingo, determine the final winning board, and calculate its score using the winning number. It reads input boards, filters out completed boards, prints the winning number and remaining board, then computes and displays t...
def Challenge2(): boards = create_bingo_boards_from_lines(read_input_file("bingoBoards1.txt")) singleBoard = remove_boards_with_bingo(boards) print(winningNumber2) print(singleBoard) print("The final calculation is: " + str(calculate_score_winning_board(singleBoard, winningNumber2)))
def draw_horizontal_stripe(stripe): if stripe.begin.right < stripe.end.right: draw_hor_stripe_generic(stripe, "right") else: draw_hor_stripe_generic(stripe, "left") def draw_vertical_stripe(stripe): if stripe.begin.down < stripe.end.down: draw_ver_stripe_generic(stripe, "down") e...
This function determines the direction of a stripe and delegates drawing to the appropriate helper function: horizontal, vertical, or diagonal, based on the 'direction' parameter. It prints debug messages upon exiting each case.
def draw_stripe(stripe, direction): if direction == "hor": draw_horizontal_stripe(stripe) print("in hor exit") elif direction == "ver": draw_vertical_stripe(stripe) print("in ver exit") else: # if diag draw_diagonal_stripe(stripe)
def findDomain(data): domain = [] for datum in data.keys(): if data[datum] not in domain: domain.append(data[datum]) return domain def uniformdistro(domain): total = len(domain) uniformdistro = {} for i in domain: uniformdistro[i] = 1/total return uniformdistro def exponentialmechanism(Queries,data,distro...
(PMW is a privacy-preserving algorithm that iteratively optimizes a model (A) using noisy mechanisms (exponential and Laplace) while maintaining differential privacy constraints. It selects queries via the exponential mechanism, applies Laplace noise, updates the model, and refines it through shuffled historical update...
def PMW(Queries, data, epsilon): domain = findDomain(data) doman_size = len(domain) A = uniformdistro(domain) scale = 2.0 * T/(epsilon * len(data.keys())) Qt = [] At = [A] Mt = [] print("PMW Started") for i in range(T): print("Current iteration number:", i) #q = noisy_max(Queries,data,A,scale/0.5) q = ex...
def download_and_load_datasets(self, force_download=True): if force_download: dataset = tf.keras.utils.get_file( fname="aclImdb.tar.gz", origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz", extract=True) else: da...
The main task of the code is to process an input sentence by downloading datasets, converting them into BERT format, tokenizing the sentence using a BERT tokenizer, preparing training features, and training a model with an estimator. The function handles data loading, tokenization, feature conversion, and model trainin...
def executeProcessing(self, sentence): train, test = self.download_and_load_datasets() train_InputExamples, test_InputExamples = self.processDataInBertFormat(train, test) tokenizer = self.create_tokenizer_from_hub_module() self.tokenizeSentences(tokenizer, sentence) train_feat...
def magnitude(self) -> float: """ alias for Vector.length """ return self.length() def setmagnitude(self, magnitude: float) -> "Vector": """ sets the magnitude of a vector """ return self.__class__( *map(lambda i: i/self.magnitude() * magnitude...
The code limits the vector's magnitude to a specified value by reducing its length if it exceeds the limit, maintaining its direction, and returning a copy of the original vector if the magnitude is already within the limit.
def limit(self, limit: float): """ limits the length of the vector. if it's larger reduce magnitude """ if self.magnitude() > limit: return self.setmagnitude(limit) return self.copy()
def is_executable(exe): """Verify exe is executable and raise exception if it is not. Execute exe with an empty string input and verify that it returns zero. We can't just check the executable bit because scripts with incorrect shebangs result in difficult-to-understand error messages. """ tr...
The code implements a MapReduce framework by orchestrating the mapping, grouping, and reducing stages. It validates input/output directories, prepares temporary directories for processing, executes map and reduce tasks using specified scripts, groups intermediate results, and transfers final outputs to the user-specifi...
def mapreduce(input_dir, output_dir, map_exe, reduce_exe): """Madoop API.""" # Do not clobber existing output directory output_dir = pathlib.Path(output_dir) if output_dir.exists(): raise MadoopError(f"Output directory already exists: {output_dir}") output_dir.mkdir() # Executable scrip...
def pprime_0(alpha): # This comes from Equation 3 return p_1(alpha) * (1 - alpha) def p_k(alpha, k): # This comes from Equation 5 return p_1(alpha) * (alpha / (1 - alpha)) ** (k - 1) def p_gt2(alpha): # This comes from Equation 5 # and infinite sum of geometric series formula which is "a / (1 - ...
The function `r_selfish` computes a weighted sum of four terms involving probability functions `pprime_0`, `p_k`, and `p_gt2`, combined with coefficients derived from parameters `alpha` and `gamma`. It likely models a risk or utility calculation where `alpha` represents a probability threshold, and `gamma` adjusts cont...
def r_selfish(alpha, gamma): # This comes from Equation 7 return pprime_0(alpha) * alpha * 2 + \ pprime_0(alpha) * gamma * (1 - alpha) * 1 + \ p_k(alpha, 2) * (1 - alpha) * 2 + \ p_gt2(alpha) * (1 - alpha) * 1
def r_selfish(alpha, gamma): # This comes from Equation 7 return pprime_0(alpha) * alpha * 2 + \ pprime_0(alpha) * gamma * (1 - alpha) * 1 + \ p_k(alpha, 2) * (1 - alpha) * 2 + \ p_gt2(alpha) * (1 - alpha) * 1 def r_others(alpha, gamma): # This comes from Equation 6 retu...
This function computes a time array `t` and a corresponding array `Gt` based on parameters `alpha` and `gamma`. It calculates `Gt` using piecewise logic involving rate ratios (`r_pool`, `r_total`), thresholds (`T_1`), and scaling factors. The output arrays represent time intervals and derived growth rates, adjusted for...
def get_t_and_Gt(alpha, gamma=0, MAX_HEIGHT=4096): T = 2016 / 6 MAX_T = MAX_HEIGHT / 6 N = 1001 t = np.linspace(0, MAX_T, N) # Y = np.zeros((N)) r_pool = r_selfish(alpha, gamma) r_total = r_pool + r_others(alpha, gamma) r_total_ = 1 / r_total # print(r_total, r_total_) # prin...
def events(self): # Game Loop - events for event in pg.event.get(): # check for closing window if event.type == pg.QUIT: if self.playing: self.playing = False self.running = False if event.type == pg.KEYDOWN: ...
The code defines a game loop that runs while `self.playing` is True. It maintains the game's frame rate using `self.clock.tick(FPS)`, processes events, updates game state, and renders graphics in each iteration to sustain gameplay.
def run(self): # Game Loop self.playing = True while self.playing: self.clock.tick(FPS) self.events() self.update() self.draw()
def clear(): os.system("cls") print() def instruction(): # to ask the user if they have played TIC TAC TOE before: instruction = valid_input( color.BOLD + "Have you played my TIC TAC TOE before? <yes> or <no>:" + color.END, instructions_list, "I am sorry wrong input, please try again") # to convert user'...
The main task of the code is to run a Tic Tac Toe game with two modes (player vs player or computer vs player), handle user input validation, manage game flow including turns, win/tie checks, and display updates. It allows replaying the same mode, switching modes, or quitting, ensuring a clear interface with ASCII art,...
def main(): clear() # to clear the terminal print(''.join([line for line in f])) # This section is for welcoming the user, it is going to call the txt file that consists the ascii art instruction() # to ask the user if they have played the game before. if answer is yes, then it will, else it will show t...
def asking_name(n,names,elements): while n != 3: # asks the user for their name and put their name into a vairable called "name" name = input("Hi player {} what would be your name?: ".format(n)) # append or put the input to an empty array called names names.append(name) # ch...
The code implements a Tic Tac Toe game allowing players to choose between human vs human or human vs computer modes. It initializes game settings, manages turn-taking, handles player/computer moves, checks for wins/ties, and repeats the game based on user input.
def main(): print("Welcome to tic tac toe!") print("type the appropiate number to choose a game option: ") choice = input("1.player vs player\n2.player vs computer\n: ") if choice == '1': names = [] elements = [] asking_name(1, names, elements) player1_is_human = True ...
def initialize_stores(exit_on_failure=True): """ Initialize the database stores dictionary. Returns a dictionary. The optional boolean argument, set to True by default, determines if the process should exit if any of the connections fail to initialize. For each store defined in 'config/stores....
This function executes and caches INDI statements (e.g., DQL/DML) by checking a cache first. If cached, it returns results directly; if not, it executes the statement against specified stores, caches the result with affected primary keys, and invalidates relevant cached queries for CREATE/UPDATE/DELETE operations to ma...
def execute_then_cache_indi(statement, caches, stores, which_store='all'): """ Execute and cache an INDI statement. Returns a multi-dimensional list. The first argument is the INDI statement as a string, the second argument is the cache dictionary (as generated by initialize_cache()), the third arg...
def bilinear_resampling_glob(geoide,lat_min,lat_max,nrows,lon_min,lon_max,ncols): y = np.linspace(float(geoide.metadata['lat max']),float(geoide.metadata['lat min']),int(geoide.metadata['nrows'])) x = np.linspace(float(geoide.metadata['lon min']),float(geoide.metadata['lon max']),int(geoide.metadata['ncols'])-...
The main task of the code is to process and correct geoid data by eliminating global residuals, removing systematic errors using a master geoid reference, and generating a final corrected matrix. It involves bilinear resampling, matrix adjustments, and combining residual corrections across multiple geoids into a unifie...
def end(global_url,delta_lat,delta_lon,geoids_url,geoids_shapefile,alpha,master,master_number,global_geoid_name,nations_name,nrows,ncols,lat_max,lat_min,lon_max,lon_min,nome_file): k = 0 s = 0 master_coeff = None glob_geoid = Geoide(global_url,None) residui_globali = bilinear_resampling_glob(glob_...
def turn_deg(num): deg, minutes, seconds,no = re.split('[°\'"]',num) return str((float(deg) + float(minutes)/60 + float(seconds)/(60*60))) def bilinear_resampling_glob(geoide,lat_min,lat_max,nrows,lon_min,lon_max,ncols): y = np.linspace(float(geoide.metadata['lat max']),float(geoide.metadata['lat min']),in...
The function processes geoid data by adjusting residuals, removing systematic errors, and generating a final corrected matrix. It converts degree symbols to decimal values, resamples geoid data, eliminates global residuals, calculates systematic coefficients, and constructs a refined geoid model using bilinear interpol...
def end(global_url,delta_lat,delta_lon,geoids_url,geoids_shapefile,alpha,master,master_number,global_geoid_name,nations_name,nrows,ncols,lat_max,lat_min,lon_max,lon_min): k = 0 s = 0 if '°' in delta_lat: delta_lat = turn_deg(delta_lat) if '°' in delta_lon: delta_lon = turn_deg(delta_lon...
def search_commits(project_full_name: str, analysers: Iterable[Callable], branch: Optional[str]): """ Search every commit diff for features """ git_url = f"https://github.com/{project_full_name}" project_path = clone_git_repo(git_url) repo = git.Repo(project_path) results = [] # TODO: ...
The function `find_features` retrieves features from a GitHub project by aggregating results from commits, issues, and pull requests using specified analysers. It authenticates via an optional token, searches each source for features, and combines them into a unified list. The goal is to compile project features by ana...
def find_features(project_full_name: str, analysers: Iterable[Callable], branch:Optional[str] = None, auth_token: Optional[str] = None): """Find features in a GitHub project""" global GH_HANDLE GH_HANDLE = github.Github(auth_token) features = [] # TODO: These should be customisable features = ...
def _manifest_id(self, item_id: str): manifest_type_dict = {'Collection': 'manifest', 'Manifest': 'manifest', 'Canvas': 'canvas'} type_of_manifest_piece = manifest_type_dict.get(self.type) return os.path.join(self.iiif_base_url, type_of_manifest_piece, item_id.replace("/", "%2F")) def _lang_wrap...
The function constructs a IIIF manifest (or collection/canvas) by populating a dictionary with metadata, identifiers, labels, thumbnails, rendering info, item references, and type-specific properties like dimensions or duration. It uses input JSON data, handles fallback values, and applies rules for different manifest ...
def _build_mainfest(self): # noqa: C901 label_contents = self.standard_json.get('title') if not label_contents: # file records do not have a title field label_contents = self.standard_json.get('id') try: label_contents = os.path.basename(label_contents) # if th...
def _fetch_challenge(self, authz_url, cType): r = self._send_post(authz_url, False) debug_print("-fetch_challenge", authz_url, r.headers, r.json()) challenge = {} if r.status_code == 200: self._nonce = r.headers["Replay-Nonce"] # receive challenge object ...
This code handles HTTP-01 challenges for Let's Encrypt ACME protocol by configuring an HTTP server, generating key authorization tokens, responding to challenges, and verifying their validation status. It starts a server process, processes each authorization challenge, checks their status, and terminates the server upo...
def _http_challenge(self, host, http_port): # config http server http_server = HTTP_SERVER(host, http_port) challenges = [] for authz_url in self._order["authorizations"]: challenge = self._fetch_challenge(authz_url, "http-01") if challenge == {}: ...
def _fetch_challenge(self, authz_url, cType): r = self._send_post(authz_url, False) debug_print("-fetch_challenge", authz_url, r.headers, r.json()) challenge = {} if r.status_code == 200: self._nonce = r.headers["Replay-Nonce"] # receive challenge object ...
This function handles DNS-01 challenges for Let's Encrypt certificate validation by iterating through authorizations, generating TXT records with challenge tokens, updating DNS zones, responding to challenges, and polling for successful authorization status. It returns True if all challenges complete successfully, Fals...
def _dns_challenge(self): # caution: updating zone with records for all authzs at once does not work for {"*.a", "a"} for authz_url in self._order["authorizations"]: challenge = self._fetch_challenge(authz_url, "dns-01") if challenge == {}: return False ...
def create_account(self): payload = {"termsOfServiceAgreed": True} r = self._send_post(self._subdir_url["newAccount"], True, payload) debug_print("-create_acct", r.headers, r.json()) # account exists or account created if r.status_code == 200 or r.status_code == 201: ...
The code automates obtaining and managing SSL certificates by creating an account, submitting an order, solving challenges (e.g., HTTP validation), finalizing the order, downloading the certificate, and optionally revoking it immediately. It returns True if all steps succeed, otherwise False.
def run(self, host, http_port, cType, domains, revoke=False): self.create_account() self.submit_order(domains) # invalid: order rejected, remove order from storage, then exit ret = False if self.do_challenges(host, http_port, cType): if self.finalize_order(domains): ...
def make_user(self, data): """returns the data of the newly created user, including uuid""" d = self.create_user(data) d.addCallback(lambda resp: resp.headers.getRawHeaders('location')[0]) d.addCallback( lambda location: treq.get('http://localhost:%s%s' % ( se...
This test verifies that retrieving a user relationship (type: LIKE) returns a 200 OK status and the correct data structure containing the relationship type and associated metadata. It creates two users, establishes a relationship with custom data, then checks that the GET request for that relationship returns the expec...
def test_get_relationship_200(self): payload = { 'username': 'foo', 'email_address': 'hkkyh@example.com', 'msisdn': '+27000000000', } user1 = yield self.make_user(payload) user2 = yield self.make_user(payload) yield self.create_relationship(use...
def get_video_id(url): pattern = re.compile('\d+') video_id = pattern.search(url).group() return video_id def _get_video_audio_links(url, video_id): page_content = requests.get(url, headers=_get_facebook_request_headers()).text html_content = get_video_html(page_content, video_id) resolutions_li...
The code downloads a Facebook video by extracting its video and audio components from given URL, saves them as temporary files, merges them into a single MP4 file using FFmpeg, then deletes the temporary files, returning the merged video filename.
def _download_facebook_video(url): """ Some FB scraping/downloading ideas taken from https://github.com/renanrgs/fb-video-downloader. """ video_id = get_video_id(url) video_link, audio_link = _get_video_audio_links(url, video_id) video_filename = _save_linked_file(video_link) audio_filename ...
def remove_cached_template(instance, **kwargs): """ Called via Django's signals to remove cached templates, if the template in the database was changed or deleted. """ cache.delete(get_cache_key(instance.name)) def remove_notfound_key(instance): # Remove notfound key as soon as we save the templ...
This function caches Django templates in response to database changes. It removes existing cached entries and updates the cache with the template's new content using a generated key.
def add_template_to_cache(instance, **kwargs): """ Called via Django's signals to cache the templates, if the template in the database was added or changed. """ remove_cached_template(instance) remove_notfound_key(instance) cache.set(get_cache_key(instance.name), instance.content)
def update_weights(X, y, W, eta): W = W - eta * gradient(X, y, W) return W def update_learning_rate(X, y, W, update_type, eta, k, eta0, alpha, beta): if update_type == 1: return eta elif update_type == 2: return eta0 / math.sqrt(k) elif update_type == 3: return alpha_beta_bac...
The function performs gradient descent to train a model's weights using either batch or minibatch updates, iteratively adjusting weights and learning rates, and returns the final weights along with loss history.
def gradient_descent( X, y, eta, max_iters, mode="batch", update_type=None, eta0=None, alpha=None, beta=None, ): """ Perform gradient descent to learn the weights of the model. """ num_classes = y.shape[1] # Initialize the weights W = np.zeros((X.shape[1], num...
def extract_spreadsheet_id(url): """ Extracts the Google Spreadsheet ID from a given URL. Args: url (str): The URL of the Google Spreadsheet. Returns: str: The extracted Spreadsheet ID. """ # Regular expression pattern to match the Google Spreadsheet ID pattern = r"/spreadsheets/d/...
The main task of the code is to generate a CV by retrieving data from a Google Sheet. It first extracts the sheet ID from provided arguments or a URL, defaults to predefined sheets if none are given. Then, it fetches data and parameters from the sheet, finally using them to generate the CV.
def main(**kwargs): print("===== 1/3) GET GOOGLE SPREADSHEET ID ....") if 'sheet_id' in kwargs: sheet_id = kwargs['sheet_id'] elif 'sheetURL' in kwargs: # Extract the sheet ID from the URL # Assuming the URL format is standard Google Sheets format sheet_id = extract_sp...
def checkParams(params): ################################################################################################ ################################################################################################ ###### MAIN STYLING VARIABLES #######################################################...
The main task of the code is to generate a formatted PDF resume by assembling structured content sections (header, contact, columns, body) using custom styles and document frames, then compiling them into a multi-page PDF document with specified page templates and layout parameters.
def generatePDFresume(data, params): params = checkParams(params) styles = getCustomStyles(params) params['styles']=styles doc, params= createFrames(params) ################################################################################################ #### HEADER FRAME content =...
def addSection(elements,text,width,section_color,fontname_headers,spacer_offset): styles = getSampleStyleSheet() if isinstance(section_color,colors.Color) : #type(section_color) section_color = section_color.hexval() # Section Style styles.add(ParagraphStyle( name='sec...
This function generates content for a right column by processing 'awards' and 'conferences' sections from input data. It formats entries as tables or lists based on parameters, appending styled content to a list. It uses section headers, date ranges, and field values, leveraging parameters for styling, layout, and form...
def get_content_column2(data,params): # unpack data sections = data.keys() styles = params['styles'] line_width = params['line_width2'] RIGHT_COLUMN = [] ################################################################################################ #### AWARDS ...
def checkParams(params): ################################################################################################ ################################################################################################ ###### MAIN STYLING VARIABLES #######################################################...
The main task of the code is to generate a structured PDF resume by assembling content sections (header, contact, columns, body) using customizable parameters. It organizes content into frames, handles page breaks, and applies styles to create a multi-page document, ensuring proper formatting and layout for resume elem...
def generatePDFresume(data, params): params = checkParams(params) styles,params = getCustomStyles(params) doc, params= createFrames(params) content = [] ################################################################################################ #### HEADER FRAME content.append(...
def get_products_for_export(self, p_class): products = Product.objects.filter(product_class=p_class) return products def get_attributes_to_export(self, p_class): attributes = p_class.attributes.all() self.attributes_to_export = attributes return attributes def export(self, produc...
The main task of the code is to process and export product data based on the provided product class. It retrieves relevant products, gathers necessary attributes, executes the export process, and returns the resulting data. The function orchestrates data fetching, attribute mapping, and export operations to generate th...
def handle(self): product_class = self.form_data['product_class'] products = self.get_products_for_export(product_class) self.get_attributes_to_export(product_class) result = self.export(products) return result
def cot_langchain_llama27b(query_string: str) -> str: inference_server_url_local = "http://infs.cavatar.info:8083" llm_local = HuggingFaceTextGenInference( inference_server_url=inference_server_url_local, max_new_tokens=200, top_k=5, top_p=0.96, typical_p=0.95, t...
This function formats a user's input for processing by incorporating the conversation history, handling image inputs, and applying system conditioning. It constructs a structured list of strings, including user and assistant messages, image paths, and conditional reasoning (CoT) based on prompt keywords. The output con...
def format_user_prompt_with_im_history_and_system_conditioning( current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]] ) -> Tuple[List[str], List[str]]: """ Produces the resulting list that needs to go inside the processor. It handles the potential image box input, th...
def format_user_prompt_with_im_history_and_system_conditioning( current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]] ) -> Tuple[List[str], List[str]]: """ Produces the resulting list that needs to go inside the processor. It handles the potential image box input, th...
The function performs model-based text generation using specified decoding strategies (Greedy/Top P Sampling) for user prompts and chat history, with optional image input. It formats prompts, interacts with an API client, manages generation parameters, and dynamically updates chat history with streaming responses. Imag...
def model_inference( model_selector, user_prompt_str, chat_history, image, decoding_strategy, temperature, max_new_tokens, repetition_penalty, top_p, ): if user_prompt_str.strip() == "" and image is None: return "", None, ch...
def asr_inference(audio): audio = whisper.load_audio(audio) audio = whisper.pad_or_trim(audio) mel = whisper.log_mel_spectrogram(audio).to(asr_model.device) _, probs = asr_model.detect_language(mel) options = whisper.DecodingOptions(fp16 = False) result = w...
The main task of the code is to perform automatic speech recognition (ASR) on an audio input, integrate the transcribed text with chat history and image context, and generate a response using a language model. It handles decoding strategies (Greedy/Top P Sampling), keyword extraction for image generation, and dynamical...
def model_inference_asr( model_selector, audio, chat_history, image, decoding_strategy, temperature, max_new_tokens, repetition_penalty, top_p, ): user_prompt_str = asr_inference(audio) acc_text = "" if user_prompt_str.s...
def format_user_prompt_with_im_history_and_system_conditioning( current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]] ) -> Tuple[List[str], List[str]]: """ Produces the resulting list that needs to go inside the processor. It handles the potential image box input, th...
The main task of the code is to process a text-image input using a specific large language model (idefics-9b-instruct) in greedy mode, format prompts with chat history, handle image encoding, generate responses with predefined parameters, and return the updated chat history containing the model's output. The function p...
def process_example(message, image): """ Same as `model_inference` but in greedy mode and with the 80b-instruct. Specifically for pre-computing the default examples. """ model_selector="local/idefics-9b-instruct" user_prompt_str=message chat_history=[] max...
def readFile(path, nodelist): # Open input file infile = open(path, 'r') # Read instance header Name = infile.readline().strip().split()[1] # NAME Comment = infile.readline().strip().split()[1] # COMMENT dimension = int(infile.readline().strip().split()[1]) # DIMENSION EdgeWeightType = i...
The code reads city coordinates from a file, constructs a graph of distances between cities, generates a random initial route, applies a three-opt optimization algorithm to find a near-optimal path, and calculates the total distance of the optimized route for solving the Traveling Salesman Problem (TSP).
def main(path): # extract the data global start_time nodelist, dimension = [], 0 nodelist, dimension = readFile(path, nodelist) # build the dictionary of the coordinate coor_dict = {} for city in nodelist: city_id = city[0] x = city[1] y = city[2] coor_dict[c...
def make_entity_dict(entity_id, page, wikidata_title, wikidata_url): page_wikidata_id = wikidata_id_of_wikipage(page.fullurl.split("/")[-1]) entity_dict = {"wikidata_id": entity_id, "page_wikidata_id": page_wikidata_id, "wikidata_title": wikidata_title, "wikipedia_title": page.title, ...
The main task of the code is to fetch Wikipedia page information for entities listed in a JSONL file, extract metadata using their sitelinks, and save the results. It processes each entity, checks for valid Wikipedia links, retrieves page data if available, updates progress tracking, and handles errors like missing pag...
def write_wiki_info(): pbar = None no_urls_entities = [] with open('entity_meta_info.jsonl', 'r') as json_file: json_list = list(json_file) print("Fetching info from wikipedia...") if debug: pbar = tqdm(total=debug_count) else: json_list = tqdm(json_list) c = 0 ...
def Type_specifier(self, node): if self.lookahead == 'int': temp = Node("Type-specifier", parent=node) # change node self.match(temp, 'int') elif self.lookahead == 'void': temp = Node("Type-specifier", parent=node) # change node s...
The function `Declaration_initial_sub` parses a "Declaration-initial" construct by checking the lookahead token against grammar rules. It creates a node for "Declaration-initial", processes a type specifier, and matches an identifier (ID). If syntax errors occur—such as missing declarations, unexpected EOF, or invalid ...
def Declaration_initial_sub(self, node): if self.lookahead in first['Type-specifier']: temp1 = Node("Declaration-initial", parent=node) #temp1 = Node("Type-specifier", parent=node) self.Type_specifier(temp1) self.match(temp1, 'ID') elif self.lookahead in...
def Declaration_initial_sub(self, node): if self.lookahead in first['Type-specifier']: temp1 = Node("Declaration-initial", parent=node) #temp1 = Node("Type-specifier", parent=node) self.Type_specifier(temp1) self.match(temp1, 'ID') elif self.lookahead in...
This function parses a 'Param' non-terminal in a grammar by checking the lookahead token. If valid, it creates a 'Param' node, processes 'Declaration-initial' and 'Param-prime' subrules recursively, and builds an abstract syntax tree. It handles syntax errors for unexpected EOF or invalid tokens by logging errors and c...
def Param_sub(self, node): if self.lookahead in first['Param']: temp = Node("Param", node) #temp = Node("Declaration-initial", node) self.Declaration_initial_sub(temp) #temp = Node("Param-prime", node) self.Param_prime_sub(temp) elif self.loo...
def Param_sub(self, node): if self.lookahead in first['Param']: temp = Node("Param", node) #temp = Node("Declaration-initial", node) self.Declaration_initial_sub(temp) #temp = Node("Param-prime", node) self.Param_prime_sub(temp) elif self.loo...
This function parses parameter lists in a grammar. It handles comma-separated parameters recursively, constructs Param-list nodes, and processes epsilon productions when no parameters are present. It also detects syntax errors for unexpected EOF or invalid tokens, appending error messages with line numbers and context.
def Param_list(self, node): if self.lookahead == ',': temp = Node("Param-list", node) #temp = Node("Param", node) self.Param_sub(temp) #temp = Node("Param-list", node) self.Param_list(temp) elif self.lookahead in follow['Param-list']: ...
def match(self, node, exp_token): if self.lookahead == exp_token: temp = Node(self.cpl_token, node) if not self.lookahead=='$': self.next_token() def Param_prime_sub(self, node): if self.lookahead == '[': temp = Node("Param-prime", node) #...
This function parses a parameter list in a grammar, constructing an abstract syntax tree (AST) node for "Param-list-void-abtar". It matches expected tokens, handles epsilon productions, and reports syntax errors for unexpected inputs. The parser recursively processes parameters and their components, ensuring correct st...
def Param_list_void_abtar(self, node): if self.lookahead in first['Param-list-void-abtar']: temp = Node('Param-list-void-abtar', node) self.match(temp, "ID") #temp = Node("Param-prime", node) self.Param_prime_sub(temp) #temp = Node("Param-list", node)...
def init_centroid(rand, k, X): centroids=list() if rand==False: #using the given cenroids c = open('F:/Uni/991/Pattern/SPR_HW4/inputs/P5/initial_centroids.txt', 'r') for line in c: last = line centroids.append(line[:-2]) centroids=centroids[:-1] ce...
The code implements the K-means clustering algorithm. It initializes centroids randomly, iteratively assigns data points to the nearest centroid, recalculates centroids based on cluster memberships, and repeats until centroids stabilize. The loop terminates when no updates occur, returning final centroids and cluster a...
def kmeans(k,rand,X): #initialization centroids = init_centroid(rand, k, X) t = 0 print('Initial Centroids:\n', centroids) #the loop will stop whenever there is no update, this is done by compring the previous and the current centroids list while t==0: prev_centroids = centroids.copy() ...
def input_excel(): global ws, city, district, ownership, type, condo_location, occupy, adverse, facilities, townhouse_location, adverse_range, nuclear_station, street_type, storey, electric, parking_type, parking_no, lease, basement, freehold_location, ownership_restriction_checkbox global year_built, sqft ...
The main task of the code is to generate a comprehensive report by compiling data from an Excel sheet, creating detailed comments on basement, interior, sales history, and neighborhood information, concatenating them into a text file named "Output.txt", and automatically inputting the compiled data into a PDF document ...
def full_report(): result = '' print('Welcome') #assign_var() #import excel sheet input_excel() # generate long comments basement_comments = (basement_comment_gen()) interior_comments = (interior_info()) sales_history_comments = (sales_history()) site_neighbourhood_comments = (ne...
def change(key): if key is not None: go_back = input("Will you like to choose a different category? That's fine, type in 'o': ") if go_back == "o": key = beginning() else: print("Oops, that isn't 'o'...") change(key) else: key = beginning() ...
The code defines a function `final` that processes a category key to retrieve and display associated TV channels. If no channels exist, it notifies the user. It then prompts for navigating to another category, recursively invoking itself if confirmed, creating a loop for continuous category exploration and information ...
def final(key=None): key = change(key) decision = retrieval(key) if decision is not None: print("This channel is " + str(decision)) else: ("This category does not have any TV stations") again = input("Would you like to move to another category? Enter y\n: ") if again == "y": ...
def greet(): print("The TV is on!!!") print("These are the channel categories available:\n" + Channel_Type_String) def final(key=None): key = change(key) decision = retrieval(key) if decision is not None: print("This channel is " + str(decision)) else: ("This category does not ha...
The code defines a function `reccomendation()` that sequentially executes three sub-functions: `greet()` to initiate interaction, `final()` to deliver a recommendation or conclusion, and `goodbye()` to conclude the process. Its main task is to guide a user through a structured recommendation workflow, starting with a g...
def reccomendation(): greet() final() goodbye()
def is_leaf(self, current: TreeNode) -> bool: """ Simple check whether or not the node is a leaf. """ return current.left is None and current.right is None def get_successor(self, current: TreeNode) -> TreeNode: """ Get successor of the current node. It should be a node ...
This function deletes a node with the specified key from a binary search tree. It recursively locates the node, handles three cases (leaf, one child, two children), and maintains tree structure by either removing the node, replacing it with a child, or using a successor node. It updates the tree's length and returns th...
def delete_aux(self, current: TreeNode, key: K) -> TreeNode: """ Attempts to delete an item from the tree, it uses the Key to determine the node to delete. """ if current is None: # key not found raise ValueError('Deleting non-existent item') elif ke...
def split_d_parameter(string_to_parse: str): # replace all separators to space for char in ["\t", "\n", "\f", "\r", ","]: string_to_parse = string_to_parse.replace(char, " ") string_to_parse = string_to_parse.strip(" ") # divide into commands commands = split_by_commands(string_to_parse) ...
This function transforms input data by splitting it into commands, modifying them with 'vh_to_l', applying a matrix transformation, then rejoining the commands into a string.
def apply_matrix_transformation(matrix: types.Matrix, input_data: str): commands = split_d_parameter(input_data) modify_vh_to_l(commands) apply_matrix_to_commands(matrix, commands) result = join_d_parameter(commands) return result
def collect_defs(self, element: ET.Element): # read attrib for attrib_name, attrib_value in element.attrib.items(): attrib_name = tools.remove_link_from_string(attrib_name) if attrib_name in ("id"): # not used in convert pass else: ...
This function processes SVG elements by extracting and mapping attributes like viewBox, height, and width to structured SVG data. It recursively processes child elements, handling specific SVG tags (e.g., path, rect) by calling dedicated methods to collect group data, while logging unsupported attributes or elements. T...
def collect_svg(self, element: ET.Element): # read attrib for attrib_name, attrib_value in element.attrib.items(): attrib_name = tools.remove_link_from_string(attrib_name) if attrib_name == "viewBox": values = attrib_value.split(" ") self.data.svg_...
def get_user(request): return request.user def is_student(user): return user.groups.filter(name='student').exists() def student(request, is_redirect=False): user = get_user(request) if is_student(user): notifications = RequestNotification.objects.filter(student=request.user) requests = A...
The code handles a POST request to assign a user to a selected group, adds the group to the user's permissions, and redirects to either the student or tutor view based on the user's role. If the 'group' parameter is missing, it returns an error response.
def view_redirect(request): user = get_user(request) error = False try: selected_choice = request.POST['group'] except: error = True pass if not error: user.groups.add(selected_choice) user.save() if is_student(user): return student(request, is_red...
def get_user(request): return request.user def is_tutor(user): return user.groups.filter(name='tutor').exists() def is_student(user): return user.groups.filter(name='student').exists() def view_redirect(request): user = get_user(request) error = False try: selected_choice = request.POST[...
The code handles user authentication and role-based redirection. It checks if the user is anonymous, redirecting to Google login if so. Authenticated users who are tutors or students are redirected to a view, while others see a signup page with available groups.
def index(request): user = get_user(request) anon = user.is_anonymous if anon: return render(request, 'tutor_me/google_login.html') elif not anon and (is_tutor(user) or is_student(user)): return view_redirect(request) else: groups = Group.objects return render(request...
def print_ok_msg(msg): print(bcolors.OKBLUE + msg + bcolors.ENDC) def check_and_create_node_exporter_user(): print_ok_msg('Creating node_exporter user') try: user_info = getpwnam('node_exporter') print_ok_msg('node_exporter user already exists') # executing useradd command using subp...
The code's main task is to install and configure the Node Exporter by switching to the HOME directory, downloading and extracting the latest release, setting proper permissions, copying the binary to /usr/bin, creating a systemd service, enabling it, and cleaning up temporary files.
def main(): # We will work in HOME dir print_ok_msg('Switching to HOME dir') os.chdir(os.getenv("HOME")) check_and_create_node_exporter_user() set_latest_release_info() download_node_exporter_tarball() deflate_tarball() copy_node_exporter_to_usr_bin_dir() change_ownership_of_node_exp...
def createChair(n : int): chairInstance = Chair(sanitizeURI(uri = f'chair_{n}')) chairInstance.fullname = f"Chair {n}" return chairInstance def createEditor(n : int): editorInstance = Editor(sanitizeURI(uri = f'editor_{n}')) editorInstance.fullname = f"Editor {n}" return editorInstance def sanit...
This code generates an ABox (assertional knowledge base) by parsing CSV datasets to create entities like authors, papers, conferences, and journals, while establishing relationships such as authorship, publication venues, and topic associations. It uses dictionaries to map entities and their connections, randomly assig...
def abox(): """ Generate the ABox from the datasets. """ personDict : Dict[str, Person] = dict() topicDict : Dict[str, Topic] = dict() conferenceDict : Dict[str, Conference] = dict() journalDict : Dict[str, Journal] = dict() editionDict : Dict[str, Edition] = dict() volumeDict : Dict...
def authorsearch(word): sth = [value for key, value in author_dictionary.items() if word in key.lower()] if len(sth) > 0: sth = list(flatten(sth)) return sth else: return [] def singleword(word): stemmedword = snow_stemmer.stem(word) if stemmedword in lexicon: wordid...
The code implements a search function that processes user queries to retrieve relevant documents from a database. It handles two main tasks: 1) Author-specific searches by identifying documents associated with a given author, and 2) Multi-word and single-word searches by analyzing word occurrences in titles, proximity,...
def searching(searchquery): while searchquery != "-1": searchquery = input("Enter your query") wordsInSearch = searchquery.split() if ".author" in wordsInSearch: x = searchquery.split(".author ") string = "".join(x) x = string.split() string =...
def authorsearch(word): sth = [value for key, value in author_dictionary.items() if word in key.lower()] if len(sth) > 0: sth = list(flatten(sth)) return sth else: return [] def singleword(word): stemmedword = snow_stemmer.stem(word) if stemmedword in lex_dictionary: ...
The main task of the code is to implement a search function that processes single-word and multi-word queries, prioritizing title matches first, then content. It handles multi-word searches by checking exact phrase matches, proximity in content, and standalone word occurrences. The function also supports author searche...
def searching(search, lis): ''' The searching functions perform the searching. **** FOR SINGLE WORD SEARCH **** -> Title occurrences are shown first. -> Occurrence in content are then shown. *** FOR MULTIWORD SEARCH *** -> Title with all or more than 1 words in it are shown. -> Content ...
def clear(): scframe.destroy() create() def searching(search, lis): ''' The searching functions perform the searching. **** FOR SINGLE WORD SEARCH **** -> Title occurrences are shown first. -> Occurrence in content are then shown. *** FOR MULTIWORD SEARCH *** -> Title with all or mo...
The main task of the code is to retrieve a user query, clear previous results, search for items, and dynamically generate clickable buttons displaying search results. Each button, when clicked, triggers the `openlink` function with its corresponding index and item from the search results list, updating the GUI with int...
def getquery(): clear() lis.clear() e = user_query.get() searching(str(e), lis) for i, x in enumerate(lis): btn = tk.Button(scframe.interior, height=1, width=74, relief=tk.FLAT, bg="gray99", fg="blue", font="Dosis", text=f"{lis[i]}", command=lambda i=i, x=x: openlink(...
def skip(word_list, word_type): while peek(word_list) == word_type:#while the first of word of word_list is 'type' match(word_list, word_type) def peek(word_list):#word_list= ('noun','princess') if word_list: word = word_list[0]#word = ('noun', 'princess') return word[0]#word[0]='noun' else: return...
This function parses a sentence by identifying its subject. It skips 'stop' words, checks the next token: if it's a noun, it uses that as the subject; if a verb, it defaults to 'player' as the subject. It then calls `parse_subject` with the determined subject, or raises an error if the starting token isn't a noun or ve...
def parse_sentence(word_list): skip(word_list, 'stop') start = peek(word_list) if start == 'noun': subj = match(word_list, 'noun') return parse_subject(word_list, subj) elif start == 'verb': return parse_subject(word_list, ('noun', 'player')) else: raise ParserError("Must start with subje...
def clean_table(self, table): table.clear() while table.rowCount() > 0: table.removeRow(0) def _gather_info_for_linear_regression(self): target_name, _ = QInputDialog.getText(self, 'Target column is needed for linear regression', 'Enter t...
This code processes user-configured data analysis tasks by gathering parameters, setting up evaluation criteria, and executing analysis using Orange or RapidMiner. It handles functionality selection (regression, prediction, clustering), user inputs for parameters, normalization, outlier removal, and result comparison. ...
def process(self): configuration = {'path': self.edit_data_path.text(), 'functionality': 0, 'rapidminer': self.cBx_rp_service_run.isChecked(), 'orange': self.cBx_orange_service_run.isChecked(), 'comparison': [], ...
def error_exit(code: int) -> Any: """Exit with return code `code` and delete the temporary file `INTERMEDIATE_JSON`.""" os.remove(INTERMEDIATE_JSON) sys.exit(code) def parse_command_line() -> argparse.Namespace: """ Parse the command line. Return the parsed command line arguments. Retu...
(This script generates a Buck2 configuration file by validating required JSON and rule scripts, setting up an Opam switch environment, installing dependencies if specified, creating a symlink for the Opam path, and executing two scripts to process package metadata into JSON and final Buck2 output. It handles command-li...
def main() -> None: """Main entry point of this script.""" source_dir = Path(__file__).parent.resolve() json_script = source_dir.joinpath(JSON_SCRIPT_NAME) if not json_script.exists(): print(f"ERROR: script file {json_script} not found!", file=sys.stderr) return error_exit(1) rules_s...
def build_MSSQLHandler(self): connectionString = ConnectionStringBuilder() connectionString.set_base(self.config.try_get_value("baseConnectionString", "Driver={ODBC Driver 17 for SQL Server};")) connectionString.set_server(self.request_database_server()) # If trusted connection ...
The code's main task is to parse command-line parameters, establish an MSSQL connection, and execute SQL queries or run a UI based on flags (-f, -q, -lq). It handles parameter parsing, database setup, query execution, and error handling for invalid inputs, defaulting to UI mode if no specific execution flags are provid...
def run(self): try: self.paramReader.parse(sys.argv) self._sqlHandler = self.build_MSSQLHandler() if(self.paramReader.has_value("-f", "-q", "-lq")): self.try_executing_file() self.try_executing_listed_query() self.try_executing...
def activate(self): active_tokens.append(self) if self.color == red: active_red.append(self) for i in inactive_red: if i == self: inactive_red.remove(i) elif self.color == blue: active_blue.append(self) for i in ...
This code moves a token on a board based on dice input. It removes the token from its current position, updates its position pointer (either initializing it for new tokens or adding dice value for active ones), and places it in the new location. Color-specific starting positions are set for inactive tokens, and the tok...
def get_roll(self, dice): for i in theBoard[ self.position]: # we need to pop the token from the old position before appending it to the new location theBoard[pos] if i == self: theBoard[self.position].remove(i) if self not in active_tokens: if self....
def message_to_screen(msg,color,font_size,display_width,display_height): font = pygame.font.Font('freesansbold.ttf',font_size) text = font.render(msg,True,color) win.blit(text,[display_width,display_height]) def name(color, wdt, ht, n): name = "NONE" s = True text = "PLAYER_" + str(n) font = pygame.f...
The code displays a screen for entering player names, creates four colored name input fields, and waits for a "PLAY" button click. Upon clicking, it returns the list of player objects.
def page2(): flag = True page2 = True win.fill(purple) while page2: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() message_to_screen("Enter Player Names", white, 45, 180, 50) if(flag): player_list.append(name(red, 700, 140, 1)) player_list.append(name(green, 700, 210, 2)) pl...
def get_bbg_api_url(): """get the bloomberg api url from the open-faas secrets or from .env file""" url = os.environ.get("bloomberg-external-api-url", None) if url is None: with open("/var/openfaas/secrets/bloomberg-external-api-url") as f: url = f.read() return url def _get_blg_df_f...
The main task of the code is to fetch financial data using either an API or a local random generator based on the environment. It checks if a URL is available for API access; if not, it determines if the function is running locally. If local, it generates random data; otherwise, it raises an error for missing environme...
def bdp_wrapper(tickers=[], fields=[], YAS_YIELD_FLAG=None): """wrapper for the function to check if the function is running locally or not""" url = get_bbg_api_url() if url is not None: df = _get_blg_df_from_api( url=url, tickers=tickers, fields=fields, YAS_YIELD_FLAG=YAS_YIELD_FLAG ...
def get_reading_and_video_content_in_week(self): uls = self.driver.find_elements(By.TAG_NAME, "ul") uls = [ul for ul in uls if (PROCESS_VIDEO in ul.text or PROCESS_READ in ul.text)] # Skip the uls not related to class. index = 0 # uls_text = [ul.text for ul in uls] # whi...
This function processes list items within a specific unordered list (UL) by identifying their type (reading or video), logging relevant text to a file, handling honor modals, and executing corresponding processing methods. It iterates through each list item, checks content type, navigates to the item, manages pop-ups, ...
def process_ul(self, ul_index: int): uls = self.get_reading_and_video_content_in_week() ul = uls[ul_index] lis = ul.find_elements(By.TAG_NAME, "li") index = 0 for index in range(len(lis)): uls = self.get_reading_and_video_content_in_week() ul = uls...
def set_buttons_text(self): buttons = self.driver.find_elements(By.TAG_NAME, "button") self.buttons_text = [button.text.split('\n')[0] for button in buttons if len(button.text) > 0 and not ('Grade' in button.text)] def get_weeks_li(self): uls = self.driver.find_elements(By.TAG_NAME, "ul") ...
This function processes content from a specified week by retrieving and organizing reading/video materials, creating a structured file hierarchy, and writing headers to an index file while iterating through elements to handle each item systematically.
def process_week(self, week_index: int): self.set_buttons_text() weeks_li = self.get_weeks_li() week = weeks_li[week_index] week_text = week.text self.week_saving_path = os.path.join(self.course_saving_path, self.util.get_clean_name(week_text)) self.util.check_folder(sel...
def initial_index_file(self): course_name = self.get_course_name() course_name = self.util.get_clean_name(course_name) self.course_saving_path = os.path.join(self.default_saving_path, course_name) self.util.check_folder(self.course_saving_path) self.index_file_name = os.path.join...
The code processes each week in a list by first initializing an index file, retrieving the list of weeks, and sequentially processing each week using a loop.
def process(self): # Initial the index .md file self.initial_index_file() weeks_li = self.get_weeks_li() index_week = 0 while index_week < len(weeks_li): self.process_week(index_week) index_week = index_week + 1 return;
def infer1(inp_img, num_output_channel): f = 256 cnv1 = cnv(inp_img, [7, 7, 1, 64], 'cnv1', stride=[1,1,1,1]) cnv2 = cnv(cnv1, [3, 3, 64, 128], 'cnv2') #pool1 = pool(cnv2, 'pool1') cnv2b = cnv(cnv2, [3, 3, 128, 128], 'cnv2b') cnv3 = cnv(cnv2b, [3, 3, 128, 128], 'cnv3') cnv4 = cnv(cnv3, [3, 3...
The code processes a multi-band input image by splitting it into two bands, extracting features from each band and a full-band input, concatenating these features across different layers, and applying convolutional networks to generate predictions. It combines band-specific features, stacks them, and produces multiple ...
def multi_band_multi_stack(inp_img,num_output_channel): band0, band1 = tf.split(inp_img, num_or_size_splits=2, axis=1) full_band = inp_img two_band_concat = [] all_band_concat = [] final_preds = [] band0_feature_output, band0_preds = infer1(band0, num_output_channel) print("band0_featur...
def pageHeader(self, title): """Render the page header""" self.setSessionCookie() head_text = '''\ Content-type: text/html; charset=UTF-8 <html> <head><title>%s</title></head> <style type="text/css"> * { font-family: verdana,sans-serif; } body { width: 50em...
The code's main task is to render an HTTP response page by sending a status code, displaying a message in a specified CSS class, rendering SREG/PAPE data if provided, and including a footer with form contents. It dynamically constructs a webpage with headers, messages, and optional data blocks based on input parameters...
def render(self, message=None, css_class='alert', form_contents=None, status=200, title="Python OpenID Consumer Example", sreg_data=None, pape_data=None): """Render a page.""" self.send_response(status) self.pageHeader(title) if message: self.wfi...
def isAuthorized(self, identity_url, trust_root): if self.user is None: return False if identity_url != self.server.base_url + 'id/' + self.user: return False key = (identity_url, trust_root) return self.server.approved.get(key) is not None def approved(self, re...
This code handles ID verification requests by checking user authorization, generating responses based on approval status, and managing immediate or deferred decisions through appropriate display methods.
def handleCheckIDRequest(self, request): is_authorized = self.isAuthorized(request.identity, request.trust_root) if is_authorized: response = self.approved(request) self.displayResponse(response) elif request.immediate: response = request.answer(False) ...
def render(self, message=None, css_class='alert', form_contents=None, status=200, title="Python OpenID Consumer Example", sreg_data=None, pape_data=None): """Render a page.""" self.send_response(status) self.pageHeader(title) if message: self.wfi...
The main task of the code is to process OpenID verification by validating user input, initiating the verification process, handling discovery errors, and redirecting users or generating forms for authorization based on parameters like 'immediate', 'use_sreg', and 'use_pape'. It ensures secure communication with identit...
def doVerify(self): """Process the form submission, initating OpenID verification. """ # First, make sure that the user entered something openid_url = self.query.get('openid_identifier') if not openid_url: self.render('Enter an OpenID Identifier to verify.', ...
def getConsumer(self, stateless=False): if stateless: store = None else: store = self.server.store return consumer.Consumer(self.getSession(), store) def quoteattr(s): #qs = cgi.escape(s, 1) qs = html.escape(s, 1) return '"%s"' % (qs,) def render(self, message...
This code handles OpenID authentication verification after a redirect. It checks the response status from the OpenID server, processes success/failure/cancel scenarios, extracts user data, and renders appropriate messages or alerts for the user.
def doProcess(self): """Handle the redirect from the OpenID server. """ oidconsumer = self.getConsumer() # Ask the library to check the response that the server sent # us. Status is a code indicating the response type. info is # either None or a string containing more i...
def displayResponse(self, response): try: webresponse = self.server.openid.encodeResponse(response) except server.EncodingError as why: text = why.response.encodeToKVForm() #self.showErrorPage('<pre>%s</pre>' % cgi.escape(text)) self.showErrorPage('<pre>%s...
This code processes OpenID requests by decoding incoming queries, handling protocol errors, displaying an about page for undefined endpoints, and routing requests to appropriate handlers based on their mode (e.g., checkid_immediate/setup) or general request processing, finally displaying the response.
def serverEndPoint(self, query): try: request = self.server.openid.decodeRequest(query) except server.ProtocolError as why: self.displayResponse(why) return if request is None: # Display text indicating that this is an endpoint. self.s...
def render(self, message=None, css_class='alert', form_contents=None, status=200, title="Python OpenID Consumer Example", sreg_data=None, pape_data=None): """Render a page.""" self.send_response(status) self.pageHeader(title) if message: self.wfi...
This method handles HTTP GET requests by dispatching logic based on URL paths: '/' (display form), '/verify' (initiate OpenID verification), '/process' (handle OpenID redirect), and '/affiliate' (custom logic). It parses query parameters, routes requests to corresponding methods, returns 404 for unmatched paths, and se...
def do_GET(self): """Dispatching logic. There are three paths defined: / - Display an empty form asking for an identity URL to verify /verify - Handle form submission, initiating OpenID verification /process - Handle a redirect from an OpenID server Any othe...
def setUser(self): cookies = self.headers.get('Cookie') if cookies: morsel = Cookie.BaseCookie(cookies).get('user') if morsel: self.user = morsel.value def showMainPage(self): yadis_tag = '<meta http-equiv="x-xrds-location" content="%s">' %\ (s...
This code handles HTTP GET requests by parsing URLs, extracting query parameters, and routing based on the path to perform actions like displaying pages, processing logins, or handling OpenID/YADIS endpoints, with error responses for invalid paths or exceptions.
def do_GET(self): try: self.parsed_uri = urlparse(self.path) self.query = {} for k, v in parse_qsl(self.parsed_uri[4]): self.query[k] = v self.setUser() path = self.parsed_uri[2].lower() if path == '/': se...
def setUser(self): cookies = self.headers.get('Cookie') if cookies: morsel = Cookie.BaseCookie(cookies).get('user') if morsel: self.user = morsel.value def serverEndPoint(self, query): try: request = self.server.openid.decodeRequest(query) ...
This code handles POST requests by parsing URI paths, extracting query parameters from request data, and routing to specific methods like `serverEndPoint` or `handleAllow` based on the URL path. It also includes error handling to respond with 404 for unknown paths and 500 for exceptions, displaying debug information.
def do_POST(self): try: self.parsed_uri = urlparse(self.path) self.setUser() content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) self.query = {} for k, v in parse_qsl(post_data): ...
def check_tree_height_lr(tuple_list): for i, r in enumerate(tuple_list): # print(i, r) tallest_so_far = '-' if r == tuple_list[0] or r == tuple_list[-1]: change_row_vis(r) #Swaps entire row to true continue #First/last row is always visible for n, t in enumera...
The main task of the code is to validate tree heights in a 2D grid by checking visibility in all four cardinal directions (left-right, right-left, top-bottom, bottom-top). It processes the input list, reverses it, applies directional checks, reverses again, and returns the validated transformed list.
def check_vis(tuple_list): check_tree_height_lr(tuple_list) check_tree_height_rl(tuple_list) revlist = reverse_2d_list(tuple_list) revlist = check_tree_height_tb(revlist) revlist = check_tree_height_bt(revlist) revlist = reverse_2d_list(revlist) return revlist
def check_device_id(self): device_id = (self._read(0x0002) & 0xF) << 12 device_id |= self._read(0x0003) << 4 device_id |= self._read(0x0004) >> 4 return device_id == 0x0606 or device_id == 65535 def enable(self, active): if active: value = 0x00 else: ...
This code initializes an IDT driver instance by setting up an I2C connection to a device at a specified address. It verifies the device's presence via a check, disables the device, configures it using the IDT_Synth parameter, then re-enables it. The main task is to establish communication with the IDT8TN24x device, val...
def __init__(self, master, address): """Create a new instance of the IDT driver Parameters ---------- master : IIC master IIC master the device is connected to address : int IIC address of the device """ self._master = master self...
def R_assigner(node_x,node_y,R,LHS): size_LHS = np.shape(LHS) a = np.zeros((size_LHS[0],size_LHS[1])) if(node_x == 0): a[node_y-1][node_y-1] = R elif(node_y == 0): a[node_x-1][node_x-1] = R else: a[node_x-1][node_x-1] = R a[node_x-1][node_y-1] = -R ...
The function models a MOSFET in a circuit simulation by assigning voltages to its terminals, configuring resistors, capacitors, diodes, and calculating small-signal parameters (gm, gds) based on the transistor's operating region (linear/saturation/cutoff). It updates the circuit's LHS (conductance matrix) and RHS (curr...
def fet_assigner(number, node_vd, node_vg, node_vs, node_vb, solution, LHS, RHS, mode): # the position of the drain, gate, source, and base voltages are hard-coded for the transistor model # we are using a discrete MOSFET, so the vb is connected to the source terminal add = 0 for i in range(number-1): ...
def loss_function(self,y,pred_y): return float((np.linalg.norm(y-pred_y)**2)/len(y)) def forward_pass(self,data): self.layer1_data = self.network(self.w1,data) self.layer2_data = self.network(self.w2,self.layer1_data) self.output_value = self.network(self.w3,self.layer2_data) def back_p...
The code trains a neural network by iterating through epochs, calculating loss, performing forward and backward passes if the loss exceeds 0.01, and periodically evaluating performance. It returns the final predicted labels after training.
def process(self,origin_data,label): self.input_data = origin_data self.truth_data = label self.output_value = np.ones(len(origin_data)) self.output_label = np.ones(len(origin_data)) for i in range(self.epochs): loss_error = self.loss_function(label,self.output_value)...
def reprojection(self, theta): """ input: theta: angle of reprojection. output: proj: reprojection OCS image. """ print('The 3D reference model is reprojecting: %s ...' % (theta,)) reference_theta = np.zeros((self.proj_shape[0], self.proj_shape[1...
This function performs multi-process alignment by iterating through predefined steps (coarse and fine) to process angular data. It calculates offsets for misaligned angles, moves/saves corrected positions, and logs successful/failure cases. The task involves reprojection, offset computation, and parallel processing to ...
def alignment_multi_part(self, start_num, stop_num): """Child processes for multi-process alignment.""" times = 5 for i in range(times): step = self.step_size[i] if i < 3: print('Coarse alignment part [2]: %s, Step: %s ' % (i, step)) else: ...
def reprojection(self, theta): """ input: theta: angle of reprojection. output: proj: reprojection OCS image. """ print('The 3D reference model is reprojecting: %s ...' % (theta,)) reference_theta = np.zeros((self.proj_shape[0], self.proj_shape[1...
The code performs multi-process alignment in two stages: coarse alignment iterates through angles in steps, calculates offsets for misaligned projections, and logs successes/failures. Fine alignment then uses multiprocessing to handle segments of aligned angles, spawning processes for parallel processing of alignment t...
def alignment_multi(self): """Multi-process alignment.""" for i in range(2): step = self.step_size[i] print('Coarse alignment part [1]: %s, Step: %s ' % (i, step)) fail_theta = [] num = self.angles.index(self.start_angle) theta = self.start_an...