dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_variable_value(variable): global variables_list print(variables_list) print(variable) if variable in ["WIN", "FAIL"]: return variable print(f"Variable: {variable}") if variable.isdigit(): if variable.find(".") != -1: return float(variable) else: ...
This function converts a variable's value to a specified target data type (e.g., integer, float, string, boolean) by applying type-specific transformation rules. It handles numeric-to-string, numeric-to-boolean, and uninitialized variable conversions, with special formatting for stringed numbers and boolean casting. If...
def is_now_a(variable, target_type): # get the value variable_value = get_variable_value(variable) print(f"\nvariable_value:\t{variable_value}.") # this is the current datatype of the variable current_type = get_datatype(variable_value) # print notifications for now print(f"current_type:\...
def get_variable_value(variable): global variables_list print(variables_list) print(variable) if variable in ["WIN", "FAIL"]: return variable print(f"Variable: {variable}") if variable.isdigit(): if variable.find(".") != -1: return float(variable) else: ...
The function `maek` converts a variable's value from its current data type to a specified target type (e.g., integer, float, string, boolean). It checks the variable's current type, applies conversion rules (e.g., integer to float, stringed number to numeric), handles edge cases like uninitialized values, and returns t...
def maek(variable, target_type): # get the value variable_value = get_variable_value(variable) print(f"\nvariable_value:\t{variable_value}.") # this is the current datatype of the variable current_type = get_datatype(variable_value) # print notifications for now print(f"current_type:\t{cu...
def set_variable_value(variable, value): global variables_list for value_pair in variables_list: if (value_pair[0] == variable): value_pair[1] = value variableValues[variable] = value return value_pair[1] return ERROR def get_numerical_value_from_string(number): ...
The function `symbolTableAnalyzer` performs syntax analysis on a list of lexemes to construct a symbol table, tracking identifiers and their values. It processes language constructs like loops, conditionals, arithmetic operations, and variable assignments, updating variable values dynamically. The function handles cont...
def symbolTableAnalyzer(_lexemesList): '''Function that executes syntax analysis given the list of lexemes. This function returns a list of identifiers and their values.''' # access the global variable global variables_list, lexemesList, current_lexeme_index # place lexemesList to global variable ...
def get_input(): wrong_input=True while wrong_input: user_input=is_input_string() if user_input!=False: return user_input else: print("invalid input") def convert_input_to_list(user_input): array=[letter for letter in user_input] return array def convert_i...
The code checks if a user-input string is a palindrome by comparing the original character list with its reversed version.
def start(): user_input=get_input() array=convert_input_to_list(user_input) array_backword=convert_input_to_list_backword(user_input) print(is_string_palindrome(array,array_backword))
def get_number_of_output(): global mat wrong_input=True while wrong_input: user_input=is_input_number() if user_input==False or user_input>len(mat): print("invalid input") else: return user_input def get_number_of_soldiers(): global mat rows_soldiers=[...
The main task of the code is to process soldier data by extracting specific elements, sorting them, and generating formatted output based on the number of required outputs. It retrieves input values, manipulates the data, and prints the result using a dedicated output function.
def start(): number_of_output=get_number_of_output() rows_soldiers=get_number_of_soldiers() array=[element[1] for element in rows_soldiers] array.sort() print(print_output(number_of_output,rows_soldiers,array))
def get_input(): wrong_input=True while wrong_input: user_input=is_input_string() if user_input!=False: return user_input else: print("invalid input") def convert_string_to_list(second_string): array=[letter for letter in second_string] return array def ch...
The code's main task is to check if the characters of the first input string can be formed using the characters of the second input string, ignoring case differences. It converts both inputs to lowercase, transforms the second string into a list of characters, and uses a `check` function to determine if the first strin...
def start(): first_string=get_input().lower() second_string=get_input().lower() second_string_array=convert_string_to_list(second_string) result=check(first_string,second_string_array) print(result)
def crawl(directory): """ Parse (analyse) a directory of HTML pages and check for links to other pages. Return a dictionary where each key is a page, and values are a list of all other pages in the corpus that are linked to by the page. """ pages = dict() # Extract all links from HTML files...
The main task of the code is to compute and display PageRank values for a given corpus using two methods: sampling and iteration. It validates input, crawls the corpus, calculates ranks via sampling with specified iterations, prints results, then computes ranks iteratively and prints them again, formatting outputs with...
def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRank Results from Sampling (n = {SAMPLES})") for page in sorted(ranks): print(f" {page}: {ranks[page]:.4f}") ...
def update_sentence(self, knowledge): print("Inside update") for sentence in knowledge: if sentence.known_mines(): print("Inside update: add mines") copy_set = deepcopy(sentence.known_mines()) for mine in copy_set: self.mark...
The function updates the Minesweeper AI's knowledge base by adding a new sentence derived from a safe cell's mine count, then infers additional safe/mines cells, updates existing sentences, and generates new knowledge. It marks the cell as safe/made, processes neighbor cells based on position, removes obsolete sentence...
def add_knowledge(self, cell, count): """ Called when the Minesweeper board tells us, for a given safe cell, how many neighboring cells have mines in them. This function should: 1) mark the cell as a move that has been made 2) mark the cell as safe 3)...
def __find_files(self): """ AFter downloading the data into row/CMAPSSDATA this function read each txt file and assign the file into train, test, rul :return: """ print("Reading the txt files ...\n") train = [] test = [] rul = [] path1 = os...
The function loads and processes data from text files by reading, splitting into train/val/test sets, and normalizing/combining data if specified. It saves processed data to 'data/processed' when enabled.
def load_dataframes(self, comb_and_norm=False, save_processed=True): """ Load row data and normalize it. It also combine sub-train datasets into one big train data :param comb_and_norm: to combine and normalize :param save_processed: to save the processed data into the data/processed ...
def _get_audio_sample_path(self, index): return self.audio_files[index] def _get_audio_sample_label_name(self, filename): return self.annotations.loc[self.annotations['link'] == self.cut_ext(filename)]['category'].values[0] def __getitem__(self, index): audio_filename = self._get_audio_sample_pa...
The code saves audio tensors from a dataset to a specified folder, skipping existing files. It tracks the count of each label and stores each audio signal as a PyTorch tensor (.pt) file, ensuring no duplicates are processed.
def save_all_tensors(self, out_folder): counter = [0 for _ in range(len(self.total_label_names))] os.makedirs(out_folder, exist_ok=True) for ind in tqdm(range(len(self.audio_files))): audio_filename = self._get_audio_sample_path(ind) label = self._get_audio_sample_label_n...
def fillFieldList(self, row = None): oldRow = self.form.fieldList.currentRow() if oldRow == -1: oldRow = 0 self.form.fieldList.clear() n = 1 for field in self.model.fieldModels: label = field.name item = QListWidgetItem(label) self....
The main task of the code is to initialize and configure field-related UI elements, connect event handlers for user interactions (e.g., adding/deleting fields, updating properties), and establish signal-slot connections to manage field data dynamically. It sets up the interface for field management, including validatio...
def setupFields(self): self.fieldOrdinalUpdatedIds = [] self.updatingFields = False self.needFieldRebuild = False self.fillFieldList() self.fieldChanged(0) self.readField() self.connect(self.form.fieldList, SIGNAL("currentRowChanged(int)"), se...
def setupCards(self): self.needFormatRebuild = False self.updatingCards = False self.playedAudio = {} # replace with more appropriate size hints for e in ("cardQuestion", "cardAnswer"): w = getattr(self.form, e) idx = self.form.templateLayout.indexOf(w) ...
This code initializes a dialog for editing or previewing card layouts in Anki. It sets up UI components, handles different scenarios (existing cards, new facts, template types), and prepares data for display. It also restores UI settings, connects signals, and ensures proper focus on active templates.
def __init__(self, parent, factedit, factOrModel, card=None): self.parent = parent QDialog.__init__(self, parent, Qt.Window) self.mw = ankiqt.mw self.deck = self.mw.deck self.factedit = factedit self.card = card if factedit is not None: self.fact = fac...
def getNthPlaylistNumTotal(self, n): total = self.getPlaylist()[n]["tracks"]["total"] return total def getPlaylistItems(self, limit, offset): url = f"https://api.spotify.com/v1/playlists/5Dww7ikBY4JDVUe5Csdpm8/tracks?limit={limit}&offset={offset}" headers = self.get_auth_header()...
This function retrieves music data from a playlist, aggregates track and artist information including audio features, and compiles it into a pandas DataFrame for analysis. It processes songs in batches of 100, extracts metadata like track names, album details, artist genres, and audio features, handles missing genre da...
def getDefaultDataframe(self): total_num_of_songs = self.getNthPlaylistNumTotal(2) data_dict = {"track_id" : [], "track_name" : [], "album_name" : [], "album_popularity" : [], "release_date": [], "artist_name" : [], "artist_genres" : [], "acousticness" : [], "danceability" : [], "energy": [], "instrume...
def balance_amount(self): return self.balances[self.quote_symbol] def round_to_precision(price,precision,round_floor=True): """ Parameters ---------- price : float price. precision : float smallest step round_type: bool defines whether to round to upper or l...
The main task of the code is to place a limit buy order for a specified cryptocurrency asset, ensuring it does not exceed open position limits, avoids duplicate orders, and uses either a user-specified quantity or an automatically calculated proportion of available balance. It handles order execution, updates position ...
def limit_buy(self,base_symbol,buy_price,qty=-1.0): """ base_symbol: str buy_price: float qty: float, value of base to buy, default to -1 (in which case automatic decision is made in funcrion of available balance) ...
def round_to_precision(price,precision,round_floor=True): """ Parameters ---------- price : float price. precision : float smallest step round_type: bool defines whether to round to upper or lower bound Returns ------- float price with a correct ...
This function executes a limit sell order for a specified cryptocurrency asset, checking if the asset is held, adjusting quantity and price to market precision, placing the order via an API, and notifying via Telegram upon success or failure. It returns True if the order is filled, False otherwise, while handling excep...
def limit_sell(self,base_symbol,sell_price,qty=-1.0): # if NOT already holding this asset, dont sell try: if not self.balances[base_symbol]>0: return False except KeyError: traceback.print_exc() pass t...
def empty_cells(state): cells = [] for x, row in enumerate(state): for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) return cells def game_over(state): return checkWin(state, HUMAN) or checkWin(state, COMP) def clean(): os_name = platform.system(...
The code executes the computer's turn in a game by selecting a move based on a magic square strategy. It checks game state, renders the board, generates a magic square number, locates its position in the grid, places the computer's mark at that cell, and introduces a delay before proceeding.
def ai_turn(c_choice, h_choice): depth = len(empty_cells(board)) if depth == 0 or game_over(board): return clean() print(f'Computer turn [{c_choice}]') render(board, c_choice, h_choice) r=MagicSquare() print(f"chosen number in magic square is {r}") for x, row in enumerate(squ...
def empty_cells(state): cells = [] for x, row in enumerate(state): for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) return cells def game_over(state): return checkWin(state, HUMAN) or checkWin(state, COMP) def clean(): os_name = platform.system(...
The function `human_turn` handles a human player's move in a Tic-Tac-Toe game. It validates user input (1-9) corresponding to board positions, checks if the move is allowed, updates the board, and ensures the game state is correctly rendered. It manages errors like invalid inputs, keyboard interrupts, and ensures the m...
def human_turn(c_choice, h_choice): depth = len(empty_cells(board)) if depth == 0 or game_over(board): return # Dictionary of valid moves move = -1 moves = { 1: [0, 0], 2: [0, 1], 3: [0, 2], 4: [1, 0], 5: [1, 1], 6: [1, 2], 7: [2, 0], 8: [2, 1], 9: [2, 2], } ...
def clean(): os_name = platform.system().lower() if 'windows' in os_name: system('cls') else: system('clear') def empty_cells(state): cells = [] for x, row in enumerate(state): for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) ...
The code implements a Tic-Tac-Toe game where a human player competes against an AI. It allows the human to choose 'X' or 'O', determines the AI's symbol, and lets the player decide who starts. The game alternates turns between human and AI until a win or draw is detected, then displays the result.
def play(): clean() h_choice = '' # X or O c_choice = '' # X or O first = '' # if human is the first # Human chooses X or O to play while h_choice != 'O' and h_choice != 'X': try: print('') h_choice = input('Choose X or O\nChosen: ').upper() except (E...
def xconv2D (nOf_filters,d_rate=1,name=None,inp_layer=None): nOf_filters = int(nOf_filters/2) d_rate = (d_rate,d_rate) t_layer1 = Conv2D(nOf_filters,3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inp_layer) t_layer1 = Conv2D(nOf_filters,3, activation = 'relu', padding = 's...
This function constructs an encoder component of a neural network, typically used in a U-Net architecture. It processes input layers through multiple convolutional blocks with increasing filter sizes, applying max-pooling, dropout, and custom operations like channel attention and correction. The encoder extracts hierar...
def u_encoder(nOf_filters = [32,64,128,256,512],inp_layer=None): F1 = nOf_filters[0] F2 = nOf_filters[1] F3 = nOf_filters[2] F4 = nOf_filters[3] F5 = nOf_filters[4] wire = Conv2D(F1,3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inp_layer) wire = xconv2D(F1...
def get_moveable_days(my_date: date) -> dict[str, date]: easter_day = easter(my_date.year) principal_days = { "easter_day": easter_day, "ash_wednesday": easter_day - timedelta(days=46), "pentecost": easter_day + timedelta(days=49), "advent_sunday": date(my_date.year, 12, 25) ...
The function `get_lectionary_data` calculates and returns liturgical data for a given date, including the liturgical year (e.g., Year A/B/C), the current liturgical season (e.g., Advent, Lent), and a filtered list of relevant liturgical days. It uses helper functions to determine moveable days, the liturgical year, sea...
def get_lectionary_data(my_date: date) -> tuple[str, str, list[str]]: moveable_days = get_moveable_days(my_date) liturgical_year = get_liturgical_year(my_date, moveable_days) liturgical_season = get_liturgical_season(my_date, moveable_days) liturgical_days = get_liturgical_days(my_date, moveable_days, l...
def generate_populasi_awal(pop_size): populasi_awal = [] for _ in range(pop_size): menu = random.choices(menu_makanan, k=17) # Mengambil 7 makanan untuk 1 minggu populasi_awal.append(menu) return populasi_awal def seleksi_orangtua(populasi, target_kalori, target_protein): k = 3 # Jumla...
The code implements a genetic algorithm to optimize a solution (e.g., diet plan) meeting specific caloric and protein targets. It evolves a population over generations through selection, crossover, mutation, and fitness evaluation, retaining top-performing solutions to iteratively improve toward the desired nutritional...
def algoritma_genetika(target_kalori, target_protein, pop_size, mutation_rate, generations): populasi = generate_populasi_awal(pop_size) for _ in range(generations): orangtua1, orangtua2 = seleksi_orangtua(populasi, target_kalori, target_protein) anak1, anak2 = crossover(orangtua1, orangtua2) ...
def extract_name(node: ast.expr) -> Optional[str]: if isinstance(node, ast.Name): return node.id if isinstance(node, ast.Call): return extract_name(node.func) if isinstance(node, ast.Attribute): return f"{extract_name(node.value)}.{node.attr}" def extract_constant(node: ast.expr) -> ...
This function processes a Python class node to extract QML metadata, checking for QmlElement/QmlUncreatable decorators, collecting superclass info, and parsing class body elements into structured data including properties, signals, and slots, returning a dictionary with QML-related metadata and class structure informat...
def maybe_process_class_def(class_node: ast.ClassDef) -> Optional[Dict[str, Any]]: if not any(extract_name(n) == "QmlElement" for n in class_node.decorator_list): return class_infos_data = [ {"name": "QML.Element", "value": "auto"}, ] for node in class_node.decorator_list: if ex...
def collect_files(paths, include_pat): for top in paths: if not os.path.isdir(top): if not include_pat.match(top): continue yield top continue for root, _dirs, files in os.walk(top): for f in files: if not include_pat.m...
This script processes files matching specified patterns, converts them to JSON format, and outputs results to a directory or stdout. It uses argparse for parameters, collects files from given paths, applies include filters, and serializes data with dump_json.
def main(): ap = argparse.ArgumentParser() ap.add_argument("-I", "--include", action="append") ap.add_argument("-O", "--output-directory") ap.add_argument("paths", nargs="+") args = ap.parse_args() if args.include: include_pat = re.compile( "|".join("(?:%s)" % fnmatch.transla...
def getEndpointsList(sqlScript): conn = tcp.getconn() cursor = conn.cursor() cursor.execute(sqlScript) tcp.putconn(conn) return cursor.fetchall() def getIpToEndpointMap(sqlScript): conn = tcp.getconn() cursor = conn.cursor() cursor.execute(sqlScript) ip_list = cursor.fetchall() t...
The main task of the code is to continuously monitor and collect data from endpoints every hour, process the results asynchronously, and update a database with metrics like latency, block height, and connection status. It uses an infinite loop to refresh endpoint lists, runs async tasks, handles exceptions, and logs pe...
def updateApp(): endpointsList=getEndpointsList(GET_ENDPOINTS_SQL) ipToEndpointMap=getIpToEndpointMap(GET_ENDPOINTS_IP_SQL) while True: t0 = time.time() d = datetime.datetime.utcnow() if d.hour==10: endpointsList=getEndpointsList(GET_ENDPOINTS_SQL) ipToEndpoin...
def nine_lines(): # define a function named nine_lines # to get total of nine lines by using three_lines() function 3 times three_lines() three_lines() three_lines() def three_lines(): # define a function by using the new_line function # three_lines function will print out 3 lines this new_li...
The main task of the code is to generate exactly 25 lines of output by sequentially calling the nine_lines(), three_lines(), and new_line() functions, with specific print statements to confirm the total line count.
def clear_screen(): # add a function named clear_screen without parameter # function body combines nine_lines,three_lines,new_line to get total 25 lines nine_lines() # call the nine_lines()function to print out 9 lines code print('This is 9th lines') nine_lines() three_lines() three_lines() ...
def load_data(): '''Loads all subject faces from data/faces and loads the feature classifiers''' global face_cascade, eye_cascade print("Beginning Haar Classifier loading") images = [] face_cascade = cv.CascadeClassifier() eye_cascade = cv.CascadeClassifier() # Load the classifiers if n...
The main task of the code is to process image datasets by converting them to grayscale, detecting and bounding faces, rotating images, re-detecting faces post-rotation, and cropping/scaling detected faces. The processed images are saved in designated directories for further analysis or model training, focusing on facia...
def main(): print("* * * * * CSC 515 - Critical Thinkning 3 * * * * *") # Load Data images = load_data() # Convert to Grayscale grayscale_conversion(images) write_images(images, 'data/grayscale/', 'face') # Initial Face Detection images_and_boxes = detect_facial_features(images) ...
def __initialize_origin(self, origin_id): """ Initialise the origin node, identified by the given ID. :param origin: the origin id """ self.__origin = self.__space.nodes[origin_id] self.__origin.route_distance = 0 def __initialize_goal(self, goal_id): """ ...
The main task of the code is to compute the shortest path between two nodes in a graph, returning a list of node IDs from the origin to the goal. It checks for valid nodes, handles trivial cases where origin equals goal, resets internal structures, initializes search parameters, and triggers the route-finding algorithm...
def find_route(self, origin_id, goal_id): """ Find the shortest route between the specified nodes. :param origin_id: the ID of the "origin" node :param goal_id: the ID of the "goal" node :returns: a list of IDs representing the steps from the origin to the goal, or None ...
def volume_up(): key(VK_VOLUME_UP) def volume_down(): key(VK_VOLUME_DOWN) def next_track(): key(VK_MEDIA_NEXT_TRACK) def prev_track(): key(VK_MEDIA_PREV_TRACK) def play_pause(): key(VK_MEDIA_PLAY_PAUSE)
The code defines a main function that runs a loop to handle user input for controlling a media player. It processes commands like volume adjustment, track navigation, play/pause, and quitting. The loop continues until the user inputs 'q', at which point it exits and displays a quit message.
def main(): done = False while (not done): inp = input("volume up: w volume down: s next: d prev: a play/pause: p quit: q\n") if inp == 'w': volume_up() print("volume up") if inp == 's': volume_down() print("volume down") ...
def init_population(nim_size): #initiates population population = [] max_leave = (nim_size-1)*2 # last row of the table will have nim_size*2-1 objects cond = POPULATION_SIZE while cond: #creates individuals individual = {'Rule1': random.randint(0,max_leave), 'Rule2': [random.randint(0...
The code evolves a population of players for the Nim game through generations. It initializes a population, creates offspring with mutation, evaluates their fitness, selects the next generation, and iterates until convergence. The goal is to find the optimal strategy by iteratively improving the population, ultimately ...
def evolution_agent(nim_size): population = init_population(nim_size) #creates population for _ in range(GENERATIONS): offspring = create_offspring(population, 0.2) #creates a new offspring calculate_fitness(offspring, nim_size) #calculates fitness of offspring popula...
def is_proper_zephyr_project(): return os.path.isfile(os.path.join(PROJECT_DIR, "zephyr", "CMakeLists.txt")) def create_default_project_files(): cmake_tpl = """cmake_minimum_required(VERSION 3.13.1) include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) project(%s) FILE(GLOB app_sources ../src/...
The main task of the code is to generate a CMake code model for a Zephyr project. It ensures the project is properly configured, triggers CMake reconfiguration if needed, cleans the build directory, creates necessary query files, runs CMake with the provided manifest, validates the output directory, parses the resultin...
def get_cmake_code_model(manifest): if not is_proper_zephyr_project(): create_default_project_files() if is_cmake_reconfigure_required(): # Explicitly clean build folder to avoid cached values if os.path.isdir(CMAKE_API_DIR): fs.rmtree(BUILD_DIR) query_file = os.path...
def load_west_manifest(manifest_path): if not os.path.isfile(manifest_path): sys.stderr.write(f"Error: Couldn't find `{manifest_path}`\n") sys.exit(1) with open(manifest_path, encoding="utf8") as fp: try: return yaml.safe_load(fp).get("manifest", {}) except yaml.YAML...
The main task of the code is to install or verify package installations for a specified platform using a west manifest. It checks for an existing state file to skip redundant installations, ensures Git is available, processes bundled projects, and either saves the installation state or cleans up and exits on failure. T...
def main(platform_name, secondary_installation): framework_dir = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..") ) packages_folder = os.path.join(framework_dir, "_pio") state_file = os.path.join(packages_folder, "state.json") if os.path.isfile(state_fi...
def multiple_factor(self): if "contree" in self.announcement: return 2 elif "sur-contree" in self.announcement: return 4 else: return 1 def announce_done(self, announ, atout): if announ[0] == "capot": if len(self.team_taker.round_win) == 32...
This function calculates and updates team scores based on specific announcements (like "capot," "contree") and the atout (trump suit). It uses predefined score values, multipliers, and checks if the announcement was successfully completed. Scores are added to either the team_taker or other_team depending on conditions,...
def calcul_team__score(self, specific_announcement_score_value, announ, atout): if announ[0] == "capot": score = pecific_announcement_score_value[2] * self.multiple_factor() if self.announce_done(announ, atout): self.team_taker.score += score else...
def create_player(self, window, name_1, name_2, name_3, name_4): player_1 = contree_player(window=window, name=name_1) player_1.player_frame = player_frame(window=window, name=player_1.name, xlabel=550, ylabel=50, xdeck=500, ydeck=100) player_1.xplayed_card, player_1.yplayed_card= 115, 0 ...
The main task of the code is to initialize and start a game by creating players, configuring the game environment, determining the first dealer, and defining teams. It organizes game setup through four key steps: player creation, game packing with color and name, dealer selection, and team assignment, ensuring all nece...
def start_game(self, cname, color, window, name_1, name_2, name_3, name_4): self.create_player(window, name_1, name_2, name_3, name_4) self.pack_game(window, cname, color) self.first_dealer() self.def_team()
def getImagesFromFiles(startDir, filenames, input_resolution=224): return [getImageFromFile(startDir, filename, input_resolution) for filename in filenames] def extractNames(filenames): ''' Finds last part of list of filenames ''' return [os.path.basename(os.path.normpath(filename)) for filename in filename...
The main task of the code is to generate a visual graph by processing input files into images, extracting associated text from filenames, and combining them with optional descriptions. It uses `getImagesFromFiles` to convert files into images, defaults to filename-based text extraction if none is provided, and passes t...
def graphFiles(startDir, filenames, input_resolution=224, texts=None, descriptions=None): images = getImagesFromFiles(startDir, filenames, input_resolution) if texts is None: texts = extractNames(filenames) return graphImages(images, texts, descriptions)
def find_opposite_player_2(player): if player == 'X': return 'Y' return 'X' def selection(root_node): #starts as root node child_node = root_node while len(child_node.child_array) > 0: #takes on value of best child node of node that was passed into function child_node = find_...
The code implements a Monte Carlo Tree Search (MCTS) algorithm to determine the optimal move for a player in a board game. It constructs a game tree, simulates random games within a 1.5-second time limit, and selects the move with the highest visit count from the root node's children, returning the corresponding board ...
def montecarlo(game_board, player): opponent = find_opposite_player_2(player) tree = Tree() root_node = tree.root temporary_board = copy.deepcopy(game_board) temporary_state = state(temporary_board) root_node = node(temporary_state) root_node.a_state.player = player #'X' for the first time ...
def check_win(self, player): # TODO: Check if self.check_col_win(player) == True: return True if self.check_diag_win(player) == True: return True if self.check_row_win(player) == True: return True return False def check_tie(self): # ...
This code implements the minimax algorithm for a tic-tac-toe-like game. It recursively evaluates all possible moves for the given player ('O' or 'X'), simulating moves, checking game states (win, tie), and selecting the optimal move based on maximizing/minimizing scores. It returns the best score and corresponding row/...
def minimax(self, player, depth): opt_row = -1 opt_col = -1 if self.check_win('O'): return (10, None, None) if self.check_win('X'): return (-10, None, None) if self.check_tie(): return (0, None, None) if (depth == 0): retur...
def check_win(self, player): # TODO: Check if self.check_col_win(player) == True: return True if self.check_diag_win(player) == True: return True if self.check_row_win(player) == True: return True return False def check_tie(self): # ...
This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player in a game (e.g., Tic-Tac-Toe). It evaluates game states recursively, maximizing scores for 'O' and minimizing for 'X', while pruning irrelevant branches to improve efficiency. It returns the best score and ...
def minimax_alpha_beta(self, player, alpha, beta, depth): opt_row = -1 opt_col = -1 if self.check_win('O'): return (10, None, None) if self.check_win('X'): return (-10, None, None) if self.check_tie(): return (0, None, None) if (depth ...
def print_instructions(): # TODO: Print the instructions to the game print("The bot is X and you are Y") print("The first player to get three in a row of their tile wins. The number 0 signifies a blank tile") return def print_board(bored): # TODO: Print the board print("\t0\t1\t2...
The main task of the code is to play a tic-tac-toe game where one player uses a Monte Carlo algorithm to choose moves, while the other player takes manual input. The game alternates turns, checks for wins/ties after each move, and ends when a player wins or the game ties.
def play_game(): #TODO: Play game current_player = 'X' game_board = board() print_instructions() while True: print_board(game_board) if current_player == 'X': #the move is a tuple that contains two elements: a 2 element long tuple of coordinates, and the player ...
def print_instructions(self): # TODO: Print the instructions to the game print("Player 1 is X and Player 2 is O") print("The first player to get three in a row of their tile wins") return def print_board(self): # TODO: Print the board print("\t0\t1\t2") count = 0 ...
The main task of the code is to implement a Tic-Tac-Toe game loop. It alternates turns between players 'X' and 'O', prints the game board, checks for a win or tie after each move, and displays the result when a player wins or the game ends in a tie. The loop continues until a terminal game state is reached.
def play_game(self): #TODO: Play game player = 'X' self.print_instructions() while True: self.print_board() self.take_turn(player) if self.check_win(player) == True: print(player + " Wins!") break if self...
def xformNoteData(synth): global noteCount0, noteCount1, noteCount2, noteCount3 global songList global note0, note1, note2, note3 global dur0, dur1, dur2, dur3 global oct0, oct1, oct2 global vol0, vol1, vol2 # synth 0 (Thick): # Read the strings for note, octave, volume, and duration fr...
The `metronome` function controls multiple synthesizers (synth0-synth3) to play a song's notes and lyrics in sync. It manages note timing, volume, rests, and transitions between notes using tick counters. For eSpeak (synth3), it triggers text-to-speech lyrics. The function checks if each synth is active, updates playba...
def metronome(channel): global count # DEBUG global metronomeON global noteCount0, noteCount1, noteCount2, noteCount3 global songList global songChoice global endOfSongSynth0, endOfSongSynth1, endOfSongSynth2, endOfSongSynth3 global synth0TickCount, synth1TickCount, synth2TickCount, synth...
def load_and_add_cards(self, cards_type, path): with open(path) as file: cards = json.load(file) self.add_cards_by(cards_type, cards) def add_colony(self, colony): strength_to_type = { 3: VERY_EASY, 9: EASY, 15: MEDIUM, 21: HARD, ...
The main task of the code is to initialize game components by structuring cards, setup cards, colonies, and statues from JSON files. It organizes cards into epochs and categories, loads setup cards with initiative values, reads colonies by strength, and initializes statues with requirements and points, all stored in di...
def __init__(self): # setup cards layout self.cards = { EPOCH1: [], EPOCH2: [], EPOCH3: [] } for epoch in self.cards: self.cards[epoch] = { INCOME: [], MILITARY: [], CULTURE: [], ...
def assignToAuthor(messageTOTAL, message): fileName = "people/" + str(messageTOTAL.author) saveToFile(message, fileName) def assignToChannel(messageTOTAL, message): fileName = "channels/" + str(messageTOTAL.channel) saveToFile(message, fileName) def assignToServer(messageTOTAL, message): fileName = ...
The main task of the code is to assign the author, channel, and server information from the input message to the messageTOTAL object, likely for data aggregation or storage purposes.
def fullSave(messageTOTAL, message): assignToAuthor(messageTOTAL, message) assignToChannel(messageTOTAL, message) assignToServer(messageTOTAL, message)
def processMessage(message): global totalWordTracker, prevThreePrev, threePrev, prevTwoPrev, twoPrev, prevThreMultiWord, threeMultiWord, multiWord, mostRecent, singleWord, lastWord global lastTrackedWord global multiWordStarts message = ' '.join(message.split()) #if the message is longer than one wo...
The main task of the code is to generate a response string by selecting random words from a corpus based on input messages. It uses `processMessage` to start with a word, iteratively appends subsequent words via `crawlCorpusForNext`, and handles exceptions by attempting fallback methods like multi-word starters. If all...
def getResponse(messageTOTAL, message): out = "" try: starter = processMessage(message) #calls processMessage to input to corpus. Recieves a list of every word and picks a random one to start responding with nextWord = crawlCorpusForNext(totalWordTracker[1][starter]) for i in range(1, ra...
def collect_investment_data(): investments = [] investment_data = {} investment_data['start'] = get_input("Starting Amount ($): ", int) while True: investment_data['after'] = get_input("After (years): ", int) investment_data['return_rate'] = get_input("Return rate (%): ", float) ...
The main task of the code is to generate a formatted table summarizing investment data (start date, return rate, contributions, etc.), calculate total contributions, starting money investments, and DCA investments, then display the table and final financial metrics like end balance. It uses collected investment data, p...
def main(): Input = collect_investment_data() # Prepare data for tabulation headers = ["Start", "After (Years)", "Return Rate (%)", "Compound", "Addition", "Contribute"] rows = [[inv.get('start', 'N/A'), inv.get('after'), inv.get('return_rate'), inv.get('compound'), inv.get('addition'), inv.get('contrib...
def parse_first_line(self, first_line): # split line on spaces to get words line_parts = first_line.split() # should be three parts if len(line_parts) == 3: self.method = line_parts[0] self.full_url = line_parts[1] # try to split the full_url ...
The main task of the code is to parse an HTTP request by splitting it into lines, extracting the first line's method, URL, and protocol, parsing headers into a dictionary, and handling the request content based on its Content-Type, such as multipart/form-data, URL-encoded, or JSON formats.
def parse_request(self, raw_request): if len(raw_request) > 0: # some data supplied # check end of line chars eol_char = '\r\n' # default as per HTTP protocol if raw_request.find('\r\n') == -1: # some systems may use single char newline ...
def _move(self, action: list): # [rotations, x] x = action[0] rotate_num = action[1] # rotate if rotate_num % 4 != 0: for i in range(rotate_num): self.current_block.rotate() # move to x diff = x - (self.current_block.shape[4].x / BLO...
This function processes a single game step in a Tetris-like game by handling user input, moving and placing the current block, checking for game over, clearing completed lines, updating the score, summoning a new block if applicable, updating the UI, and returning the score and game over status.
def play_step(self, action): # 1. get user input for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # 2. move current block (until placed) self._move(action) # move block L/R or rotate, and then place all th...
def _fragment_connect_request(crypto, client_uuid, pubkey_type, pubkey, userhash, auth_token, request_num=0): """ Internal method to fragment ConnectRequest. Args: crypto (Crypto): Instance of :class:`Crypto` client_uuid (UUID): Client UUID pubkey_type ...
The main task of the code is to establish a connection to a console using Xbox Live authentication credentials (userhash and XSTS token), with optional retries and fragmentation handling for large payloads. It initializes cryptographic parameters, sends connection requests, awaits acknowledgment, and configures session...
def connect(self, userhash, xsts_token, client_uuid=uuid.uuid4(), request_num=0, retries=3): """ Connect to console Args: userhash (str): Userhash from Xbox Live Authentication xsts_token (str): XSTS Token from Xbox Live Authentication client_...
def _set_result(self, identifier, result): """ Called when an acknowledgement comes in, unblocks `_await_ack` Args: identifier (str): Identifier of ack result (int): Ack status Returns: None """ self._pending[identifier].set(result) del s...
This function handles incoming smartglass packets by unpacking data, processing packet types (DiscoveryResponse, ConnectResponse, Message), logging events, managing sequence numbers, reassembling fragments, and triggering callbacks. It uses crypto if enabled, tracks discovered devices, handles pending connections, and ...
def handle(self, data, addr): """ Handle incoming smartglass packets Args: data (bytes): Raw packet addr (str): IP address of sender Returns: None """ try: host, _ = addr if self.crypto: msg = packer.unpac...
def gen_random_parameters(self, branch_prefix="release/", version_prefix=""): version = self.random_version() branch_name = '{}{}.{}'.format(branch_prefix, version[0], version[1]) latest_tag = '{}{}.{}.{}'.format(version_prefix, version[0], version[1], version[2]) expected_tag = '{}{}.{}...
This test verifies the default behavior of the git-bump-version tool by simulating a Git repository setup, checking if it correctly identifies the latest tag, generates the expected incremented version tag, and returns a success code (0) when no arguments are provided.
def test_bump_version_defaults(self): branch_name, latest_tag, expected_tag, _ = self.gen_random_parameters() self.configure_git_repo_mock(branch_name=branch_name, tag_found=True, latest_tag=latest_tag) result = git_bump_version.main([]) self.verify_expected_tag(expected_tag) ass...
def gen_random_parameters(self, branch_prefix="release/", version_prefix=""): version = self.random_version() branch_name = '{}{}.{}'.format(branch_prefix, version[0], version[1]) latest_tag = '{}{}.{}.{}'.format(version_prefix, version[0], version[1], version[2]) expected_tag = '{}{}.{}...
This test verifies that the git-bump-version tool correctly creates the expected initial tag when no existing tags are present in the repository. It configures a mock git environment with a random branch name, runs the tool without arguments, checks if the generated tag matches the expected value, and confirms the proc...
def test_bump_version_first_tag(self): branch_name, _, _, expected_tag = self.gen_random_parameters() self.configure_git_repo_mock(branch_name=branch_name, tag_found=False) result = git_bump_version.main([]) self.verify_expected_tag(expected_tag) assert result is 0, 'return code ...
def gen_random_parameters(self, branch_prefix="release/", version_prefix=""): version = self.random_version() branch_name = '{}{}.{}'.format(branch_prefix, version[0], version[1]) latest_tag = '{}{}.{}.{}'.format(version_prefix, version[0], version[1], version[2]) expected_tag = '{}{}.{}...
This test verifies that the 'git-bump-version' tool correctly increments the version without creating a new tag when the '--dont_tag' flag is used. It sets up a mock git repository, executes the command, checks if the expected version is achieved without tagging, and confirms the process returns a success code (0).
def test_bump_version_dont_tag(self): branch_name, latest_tag, expected_tag, _ = self.gen_random_parameters() self.configure_git_repo_mock(branch_name=branch_name, tag_found=True, latest_tag=latest_tag) result = git_bump_version.main(['--dont_tag']) self.verify_expected_tag(expected_tag,...
def gen_word(self): return ''.join(random.choice(string.ascii_lowercase) for i in range(self.gen_small_random_number())) def gen_random_parameters(self, branch_prefix="release/", version_prefix=""): version = self.random_version() branch_name = '{}{}.{}'.format(branch_prefix, version[0], version...
This test verifies that the git-bump-version tool correctly handles a custom version prefix by generating random parameters, configuring a mock git repository, executing the tool with the specified prefix, and asserting that the resulting version tag matches expectations and the return code is 0.
def test_bump_version_custom_version_prefix(self): version_prefix = self.gen_word() branch_name, latest_tag, expected_tag, _ = self.gen_random_parameters(version_prefix=version_prefix) self.configure_git_repo_mock(branch_name=branch_name, tag_found=True, latest_tag=latest_tag) result = g...
def gen_word(self): return ''.join(random.choice(string.ascii_lowercase) for i in range(self.gen_small_random_number())) def gen_random_parameters(self, branch_prefix="release/", version_prefix=""): version = self.random_version() branch_name = '{}{}.{}'.format(branch_prefix, version[0], version...
This test verifies that the `git_bump_version` tool correctly generates a version tag using a custom prefix when no existing tags are present. It configures a mock Git repository, executes the tool with the specified prefix, and asserts that the resulting tag matches expectations and the process completes successfully ...
def test_bump_version_custom_version_prefix_first_tag(self): version_prefix = self.gen_word() branch_name, _, _, expected_tag = self.gen_random_parameters(version_prefix=version_prefix) self.configure_git_repo_mock(branch_name=branch_name, tag_found=False) result = git_bump_version.main(...
def generate_routefile(): random.seed(42) # make tests reproducible N = 3600000 # number of time steps # demand per second from different directions with open("data/cross.rou.xml", "w") as routes: print("""<routes> <vType id="typeWE" accel="0.8" decel="4.5" sigma="0.5" length="5" minGa...
The main task of the code is to implement a reinforcement learning-based traffic light control system using Deep Q-Networks (DQN) in a TraCI simulation. It trains multiple DQNs to optimize traffic flow by minimizing waiting time and CO2 emissions through adaptive signal phase adjustments. The code runs simulations, col...
def run(): """execute the TraCI control loop""" # first, generate the route file for this simulation generate_routefile() traci.init(PORT) loops = traci.inductionloop.getIDList() lights = traci.trafficlights.getIDList() history_len = 5 input_size = len(lights) + history_len * len(lights)...
def load_session(self): if self.has_session and os.path.isfile(self.path_to_session): with open(self.path_to_session, 'r') as f: return f.read() else: return "" def is_valid_entry(self): maybe_valid = '\n'.join([self.curr_session, self.body]) if is_valid_python(maybe_valid): re...
This code initializes an object by parsing a raw string to extract session information, processes lines starting with '#', constructs a session file path, loads the session data, validates the entry, and updates the session. It handles potential errors in session ID extraction and prepares the session for further use.
def __init__(self, raw_string): lines = raw_string.splitlines() os.makedirs(self.session_dir, exist_ok=True) self.raw_string = raw_string try: self.timestamp, self.session_id = lines[0].split(" SESS_ID:") self.session_id = int(self.session_id.strip()) self.has_session = True except...
def get_ip(): return request.headers.get('X-Forwarded-For', request.remote_addr) def addlog(ip, ig=0): log = ldlog() if ip not in log or ig: entry = genkey(ip) log[ip] = entry fi = "\n".join([" ".join(log[x]) for x in log]) with open("data/ips.txt", "w") as iplog: ...
The function `show_captcha` generates a CAPTCHA form or approval message based on user IP status. It checks approval status; if unapproved, it displays a CAPTCHA form with logging details and redirect. If approved, it shows an approval message. The output is returned directly if `hide` is True, otherwise wrapped in a p...
def show_captcha(hide=0, redir='.'): from view import ld_page, mk_page ip = get_ip() mylog = addlog(ip) out = "" if not approve(): out += ld_page("captcha_form").format(mylog[ip][1], redir) else: out += "Your IP is approved for posting" if hide: return out return ...
def show_tags(): """Format a tag list for users""" tags = tag_list() page = ["<ul>"] for t in tags: if t[1] == 0: continue line = f"<li><a href='/tags/{t[0]}/'>#{t[0]}</a> - {t[1]} " if t[1] > 1: line += "threads" else: line += "thread"...
This function generates an HTML page listing threads tagged with specified keywords, excluding those with "badtags". It processes input tags, filters relevant threads from a database, sorts results by comment count, and formats output with links and metadata. If no matches are found, it displays a "Zero entries" messag...
def tag_index(tags, badtags=None): """Show a list of threads with specific tag/tags""" atoms = " <link rel='alternate' type='application/atom+xml'" atoms += f" href='/atom/tag/{tags[0]}'>" title = "" if badtags: if "+" in badtags: badtags = badtags.split("+") elif " " in ...
def push(self, start: Optional[torch.IntTensor], limit: torch.IntTensor = None): # check inputs if limit is None: start, limit = torch.zeros_like(start), start # calculate coordinate to evaluate edges = self.gen_edges_range_(start, limit) # calculate the new distanc...
This code iteratively expands a search area within a tensor-based cell structure, updating boundaries until all regions are evaluated. It uses PyTorch operations to track valid search ranges, compute closest boundaries, and update limits for subsequent iterations. If symmetry is enabled, it generates symmetric edges an...
def build(self): start = torch.full_like( self.cell[:, :, 0], fill_value=0, dtype=torch.int32) limit = torch.full_like( self.cell[:, :, 0], fill_value=1, dtype=torch.int32) search = True batch = self.batch[self.unique_src] while search: k_d...
def getTokenCount(s): """ Input a string and return an integer representing the number of tokens in the string according to Tiktoken's 'cl100k_base' encoding. :param s: string to be tokenized :return: integer representing the number of tokens in s. """ return len(tokenize(s)) def embed(*args,**k...
The main task of the code is to determine which parts of the conversation history and current prompt can be sent to the OpenAI Chat API without exceeding token limits. If the total tokens are within the limit, it returns the full conversation history. If not, it uses embeddings to filter the most semantically relevant ...
def getMessagesToSend(self,prompt): """ This function determines which parts of the conversation history and the current prompt can be sent to the OpenAI Chat API given the API's token limits. :param prompt: string representing the prompt for the API. :return: integer representing the pr...
def getMessagesToSend(self,prompt): """ This function determines which parts of the conversation history and the current prompt can be sent to the OpenAI Chat API given the API's token limits. :param prompt: string representing the prompt for the API. :return: integer representing the pr...
The code sends a prompt to the OpenAI API using a specified model, appends the prompt and response to a conversation history (self.messages), and manages token limits by embedding and filtering historical messages if needed. It returns the API response while logging interactions with token counts and embeddings for con...
def queryApi(self,prompt): """ Sends prompt to the OpenAI API and then receives response from API using openai.ChatCompletion.create Stores the prompts and responses in self.messages. The model used by the Chat API is determined by self.model. If the conversation exceeds ...
def is_return_journey(self) : return self.returnJourney def deduct_for_one_way_journey(self, actualTravelFare, collectionSummary) : self.check_balance_and_deduct(actualTravelFare, collectionSummary) def update_return_journey_status(self, updatedReturnJourney) : self.returnJourney = updatedReturn...
The code deducts travel charges based on journey type: one-way or return. If one-way, it deducts directly and marks the journey as return. If return, it reduces the fare, deducts the adjusted amount, and marks the journey as non-return. The method updates the journey status accordingly after processing.
def deduct_travel_charges(self, travelFare, collectionSummary) : #if passenger doing OneWay Journey if not self.is_return_journey() : self.deduct_for_one_way_journey(travelFare, collectionSummary) self.update_return_journey_status(True) #if passenger doing Return Journ...
def read_genome(genome): file_name = GENOME_FILE_PREFIX + genome + ".txt" with open(file_name, "r") as file: dna = file.read() file.close() return genome_preprocessing(dna) def get_protein(dna): rna = translation(dna) protein = transcription(rna) return protein def create_note_sequen...
This code converts a genome sequence into a MIDI music file by reading the genome, translating it into protein sequences, generating a musical note sequence based on the given key and scale, and finally creating a MIDI file with these parameters.
def start(genome, key, scale): dna = read_genome(genome) protein = get_protein(dna) note_sequence = create_note_sequence(protein, key, scale) return create_midi(genome, note_sequence, key, scale)
def options(flg): choice2=vl.options_prompt()#Login, Register, Back #print('choice2-->',choice2) if choice2=='1': present,user_id=login_user(flg) #print("@@@@@",present) if present: #print(f"Flag {flg}++++++UserID{user_id}") enter_app(flg,user_id) els...
The code manages a login interface by repeatedly prompting the user to choose between 'Librarian', 'User', or 'Quit'. Depending on the choice, it triggers corresponding functions (options with flags 1/2) or exits. Invalid inputs trigger warnings and re-prompting via recursive calls.
def app_login(): choice=None while choice !='3': choice=vl.prompt_user()#Librarian, User, Quit #print('*******',choice) if choice=='1': #print(f"choice 1 -> {choice}") flg=1 options(flg) elif choice=='2': #print(f"choice 2 -> {...
def write_to_file(path_to_filename, content, overwrite=True): """ Overwrites or appends a pre-determined string to a file :param path_to_filename: str :param content: str :param overwrite: bool :return: """ if overwrite: with open(path_to_filename, 'w', encoding='utf-8') as f: ...
The main task of the code is to write answers to three questions (a, b, c) into a file. It first writes the answer to question a, then appends the answers to questions b and c, each prefixed with a newline. The method uses `write_to_file` to handle file operations, with the first call potentially overwriting the file a...
def write_answers_to_file(self): """ Writes the answers to questions a, b, c to a file """ write_to_file(self.FILEPATH, ('Answer to a: ' + self.question_a()), True) write_to_file(self.FILEPATH, ('\nAnswers to b: ' + self.question_b()), False) write_t...
def price(self, ticker, database): try: # price = float(Stock(ticker).get_price()) price = Stock(ticker).get_price() # self.myDatabase.at["price", ticker] = price self.price_fetch_price(ticker, price, database) except: try: pri...
The main task of the code is to update stock prices and trigger email notifications for users when predefined thresholds are met. It iterates through a stock list from the database, updates each stock's price, checks for notification triggers, retrieves relevant news, and sends emails via the provided email object. It ...
def update_prices(self, email, stock_news, database): # print("updating...") # calls email object and sends out email if notifications hit threshold list = database.stock_list() for stock in list: self.price(stock, database) stock_info = self.notify_user(stock, da...
def unbounded_seg_seg_intersection(seg1, seg2): if len(seg1) == 2 and len(seg2) == 2: aligned_seg1 = _alignment_transformation(seg1).transformPoints(seg2) if not math.isclose(aligned_seg1[0][1], aligned_seg1[1][1]): t = aligned_seg1[0][1] / (aligned_seg1[0][1] - aligned_seg1[1][1]) ...
The function determines the intersection point between the original outstroke and either the last segment (if flipped) or the closest point on the outstroke to the last corner node's position, depending on the flipped state.
def recompute_outstroke_intersection_point(self, original_outstroke): if self.flipped: # Project it return unbounded_seg_seg_intersection( as_tuples(self.last_seg), original_outstroke ) # Bend it return closest_point_on_segment( or...
def process_text(content,ctype): global use_lematizer content = content.lower() ## casefolding if ctype=='title': tokens = tokenize(content,True) words = process_words(tokens,use_lematizer) return words if ctype=='body': text, categories, links, info = get_sections(conte...
This code parses XML data to extract and count words from Wikipedia page elements (title, text, categories, links, info). It maintains global dictionaries to track word occurrences per document, appending counts with section-specific prefixes (t, b, c, l, i). After processing each page, it periodically writes intermedi...
def parseXML(context): global page_dict, try_till, write_after, words_dict, file_count, curpage_counts, docid for event, elem in context: if elem.tag == prefix+"title": ## Uncomment this if you need to continue prcessing after a break # if docid <= 3780932: # cont...
def upd_slacks(self): self.s = self.b - self.A @ self.x def upd_SinvA(self): self.SinvA = (self.s**(-1))[:, None] * self.A def upd_Hinv(self): self.Hinv = inv(self.SinvA.T @ self.SinvA) def upd_P(self): self.P = self.SinvA @ self.Hinv @ self.SinvA.T def upd_sigmas(self): self.sig...
The main task of the code is to sequentially update multiple components of a system or model, including slack variables, inverse matrices (SinvA, Hinv), parameters (P), and sigma values. These updates are likely part of an iterative optimization or simulation process, ensuring the model's internal state remains consist...
def do_update(self): self.upd_slacks() self.upd_SinvA() self.upd_Hinv() self.upd_P() self.upd_sigmas()
def add_row(self, a_new, b_new): self.A = np.vstack((self.A, a_new.T)) self.b = np.append(self.b, b_new) self.t_of_i = np.append(self.t_of_i, self.iteration) def do_update(self): self.upd_slacks() self.upd_SinvA() self.upd_Hinv() self.upd_P() self.upd_sigm...
This code performs an iterative optimization step by updating the model's parameters (self.x) using gradients and a Hessian approximation matrix (Q). It computes new gradient (a_new) and scalar (b_new), updates the trajectory and gradients lists, modifies the Q matrix, and adjusts self.x. A while loop ensures convergen...
def step(self): self.iteration += 1 a_new, _ = self.oracle(self.x) # e_t = F'(x_t) self.trajectory.append(self.x.copy()) self.grads.append(a_new.copy()) b_new = np.dot(a_new, self.x) + np.sqrt((a_new.T @ self.Hinv @ a_new) / self.tau) self.add_row(a_new, b_new) # Q_t ...
def js_response(content): ''' Kept for backward compatibility. Users might as well use JSResponse directly. ''' return JSResponse(content) def d(text): return json.dumps(text) def _optional_unblock(unblock): return unblock_form() if unblock else js_response('');
The function `alert` generates a JavaScript alert with the provided message and optionally unblocks further submissions based on the `allow_further_submissions` parameter, primarily used for non-form error messages or button-triggered actions without dedicated error containers.
def alert(message, allow_further_submissions=False): ''' Useful for error messages that aren't really typical form error messages, or for actions that are triggered by a simple button push (where there is no corresponding container for error messages). Note - allow_further_submissions is so-called ...
def js_response(content): ''' Kept for backward compatibility. Users might as well use JSResponse directly. ''' return JSResponse(content) def _get_script_content(script_name): with open(os.path.join(os.path.dirname(__file__), 'js_helpers', script_name)) as f : return f.read() de...
The main task of the code is to reset and unblock a Django form by generating JavaScript code that executes a predefined script (`clear_form_errors.js`) to clear form errors and optionally unblock the form based on the `unblock` parameter. The function returns a JavaScript response to handle frontend form state updates...
def clear_form_errors(unblock=True): ''' Requires django Resets and unblocks form. ''' return js_response(f''' {_get_script_content("clear_form_errors.js")}; clear_form_errors(form); ''')+_optional_unblock(unblock)
def js_response(content): ''' Kept for backward compatibility. Users might as well use JSResponse directly. ''' return JSResponse(content) def _get_script_content(script_name): with open(os.path.join(os.path.dirname(__file__), 'js_helpers', script_name)) as f : return f.read() de...
The function generates a JavaScript response to set form errors on the client-side, using `form_errors` and `error_map` to display validation errors. It optionally unblocks UI elements, focuses on errors, and sets an HTTP status code, returning a structured response object with these configurations.
def set_raw_form_errors(form_errors, error_map, status_code=400, unblock=True, focus_errors=True): r = js_response(f''' {_get_script_content("set_form_errors.js")}; set_form_errors(form, {d(form_errors)}, {d(error_map)}); ''')+_optional_unblock(unblock)+_optional(focus_errors and focus_form_erro...
def js_response(content): ''' Kept for backward compatibility. Users might as well use JSResponse directly. ''' return JSResponse(content) def _get_script_content(script_name): with open(os.path.join(os.path.dirname(__file__), 'js_helpers', script_name)) as f : return f.read() de...
The main task of the code is to reset a form by clearing its validation errors and resetting field values using JavaScript, while optionally unblocking a UI element. It combines a script to clear errors, resets the form, and manages UI blocking states for a seamless user experience.
def reset_form(unblock=True): return js_response(f''' {_get_script_content("clear_form_errors.js")}; clear_form_errors(form); form.reset(); ''')+_optional_unblock(unblock)
def IJsq(RI,RJ): return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) ) def N(a,l,m,n): N = (2*a/math.pi)**(3/4) * (((8*a)**(l+m+n) * special.factorial(l,exact=True) * special.factorial(m,exact=True) * special.factorial(n,exact=True))/(special.factorial(2*l,exact=True) * special.factorial(2*m,exact=True) * special.factori...
The code computes the overlap matrix S by iterating over all pairs of atomic orbitals in the basis. For each pair, it calculates the overlap integral using exponential terms, normalization constants, and contraction coefficients. The result is accumulated into the matrix S, which represents the overlap between basis fu...
def buildS(basis, S): for A, bA in enumerate(basis): # retrieve atomic orbital A from the basis for B, bB in enumerate(basis): # retrieve atomic orbital B from the basis for a, dA in zip(bA['a'],bA['d']): # retrieve A.O. A alpha and contraction coefficients for b, dB in zip(bB['a'],bB['d']):...
def gaussianProduct(a,RA,b,RB,g): P = [] for i in range(3): P.append( (a*RA[i]+b*RB[i])/g ) return P def IJsq(RI,RJ): return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) ) def gi(l,lp,r,rp,i, lA,lB,Ai,Bi,Pi,gP, lC,lD,Ci,Di,Qi,gQ): delta = 1/(4*gP) + 1/(4*gQ) gi = (-1)**l gi *= theta(l,lA,lB,Pi-Ai,Pi-Bi,...
This function computes a three-dimensional integral involving Gaussian basis functions, combining angular momentum components via nested loops and radial parts using the Boys function. It calculates electron repulsion integrals in quantum chemistry by evaluating products of Gaussian functions, applying normalization fa...
def Gxyz(lA,mA,nA,lB,mB,nB,lC,mC,nC,lD,mD,nD,a,b,c,d,RA,RB,RC,RD): gP = a + b gQ = c + d delta = 1/(4*gP) + 1/(4*gQ) RP = gaussianProduct(a,RA,b,RB,gP) RQ = gaussianProduct(c,RC,d,RD,gQ) ABsq = IJsq(RA,RB) CDsq = IJsq(RC,RD) PQsq = IJsq(RP,RQ) Gxyz = 0 for l in range(0,lA+lB+1): for r in ran...
def IJsq(RI,RJ): return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) ) def N(a,l,m,n): N = (2*a/math.pi)**(3/4) * (((8*a)**(l+m+n) * special.factorial(l,exact=True) * special.factorial(m,exact=True) * special.factorial(n,exact=True))/(special.factorial(2*l,exact=True) * special.factorial(2*m,exact=True) * special.factori...
This code constructs a matrix T by summing contributions from all pairs of basis functions. It iterates over basis elements, computes terms involving exponential decay, normalization factors, and a kernel function Kxyz, then accumulates results into T[A,B]. The nested loops and element-wise operations suggest it calcul...
def buildT(basis, T): for A, bA in enumerate(basis): for B, bB in enumerate(basis): for a, dA in zip(bA['a'],bA['d']): for b, dB in zip(bB['a'],bB['d']): RA, RB = bA['R'], bB['R'] lA, mA, nA = bA['l'], bA['m'], bA['n'] lB, mB, nB = bB['l'], bB['m'], bB['n'] ...
def add_bias(self,X): return np.insert(X, 0, 1, axis=1) def one_hot(self, y): return np.eye(len(self.classes))[np.vectorize(lambda c: self.class_labels[c])(y).reshape(-1)] def fit_data(self, X, y, batch_size, lr, verbose): i = 0 while (not self.n_iter or i < self.n_iter): sel...
This code trains a classifier by initializing weights, preprocessing input data (adding bias, one-hot encoding labels), and performing batch gradient descent via the fit_data method to minimize loss during training.
def fit(self, X, y, batch_size=64, lr=0.001, rand_seed=4, verbose=False): np.random.seed(rand_seed) self.classes = np.unique(y) self.class_labels = {c:i for i,c in enumerate(self.classes)} X = self.add_bias(X) y = self.one_hot(y) self.loss = [] self.weights = np...
def add_bias(self,X): return np.insert(X, 0, 1, axis=1) def one_hot(self, y): return np.eye(len(self.classes))[np.vectorize(lambda c: self.class_labels[c])(y).reshape(-1)] def fit_data(self, X, y, batch_size, lr, verbose): i = 0 while (not self.n_iter or i < self.n_iter): sel...
This function trains a classification model using gradient descent with autograd. It preprocesses input data by adding bias terms and one-hot encoding labels, initializes weights, and calls a training method to optimize parameters. The goal is to learn weight matrices that minimize classification loss over batches of d...
def fit_w_Autograd(self, X, y, batch_size=64, lr=0.001, rand_seed=4, verbose=False): np.random.seed(rand_seed) self.classes = np.unique(y) self.class_labels = {c:i for i,c in enumerate(self.classes)} X = self.add_bias(X) y = self.one_hot(y) self.loss = [] self.w...
def get_user_input(): user = request.form.get('user') period = request.form.get('period') return user, period def get_data(fetcher): data_artists = fetcher.get_json_data("user.gettopartists") data_tracks = fetcher.get_json_data("user.gettoptracks") data_albums = fetcher.get_json_data("user.getto...
The main task of the code is to retrieve and process user-specific music data (artists, tracks, albums) based on input parameters, generate visualizations (pie charts), and render a dynamic HTML dashboard displaying top tracks, albums, artist similarities, recent activity, and graphical data representations for user an...
def index(): if request.method == 'POST': user, period = get_user_input() fetcher = DataFetcher(user, period) data_artists, data_user, data_tracks, data_albums, data_recent_tracks = get_data(fetcher) top_artists_and_similars = process_data(fetcher, data_artists) top_track...
def isEmpty(self): if len(self.values)==0: return True return False def pop(self): if not self.isEmpty(): x = self.values[-1] del self.values[-1] return x return -1 def insertAtBottom(self, item): if self.isEmpty(): self.push(item) else: temp = self.pop() self.in...
The code recursively reverses a stack by popping the top element, reversing the remaining stack, and inserting the popped element at the bottom, effectively reversing the entire stack's order.
def reverse(self): if not self.isEmpty(): x = self.pop() self.reverse() self.insertAtBottom(x)
def get_H(train_data, w_matrix): H = [] for x_vector in train_data: H.append(get_h_j(x_vector, w_matrix)) return np.transpose(H) def B_vector(H, T_vector, N_h, C): return np.dot(np.linalg.pinv(np.dot(H, np.transpose(H)) + np.identity(N_h)/C), np.dot(H, np.transpose(T_vector))) def y_out(B, H): ...
The main task of the code is to compute the mean squared error (MSE) between true labels and model predictions generated by a weight matrix and parameters. It transforms input data with the weight matrix, calculates intermediate values (H, B), generates predicted outputs (y_vector), and evaluates prediction accuracy vi...
def test_mse(weight_matrix, train_data, y_true_train, C): H = get_H(train_data, weight_matrix) H = np.array(H) B = B_vector(H, y_true_train, len(weight_matrix[0, :]), C) y_vector = y_out(B, H) return mse(y_true_train, y_vector)
def get_H(train_data, w_matrix): H = [] for x_vector in train_data: H.append(get_h_j(x_vector, w_matrix)) return np.transpose(H) def B_vector(H, T_vector, N_h, C): return np.dot(np.linalg.pinv(np.dot(H, np.transpose(H)) + np.identity(N_h)/C), np.dot(H, np.transpose(T_vector))) def y_out(B, H): ...
The code evaluates a model's performance on test data using a weight matrix. It computes the hypothesis matrix (H), derives a bias vector (B), generates predicted labels (y_vector), thresholds them to binary classes, and calculates metrics like precision, recall, F-score, accuracy, MSE, and confusion matrix. It prints ...
def test(weight_matrix, test_data, y_true_test, C): H = get_H(test_data, weight_matrix) H = np.array(H) B = B_vector(H, y_true_test, len(weight_matrix[0, :]), C) y_vector = y_out(B, H) for i in range(len(y_vector)): if y_vector[i] >= 0: y_vector[i] = 1 else: ...
def customLook1(array): """ You can perform any grading operation here. This is open-domain data encoded in the workspace colorspace. """ return array def applyAgxLog(array): # type: (numpy.ndarray) -> numpy.ndarray """ Convert open-domain to log domain. Returns: AgX Log (Kr...
The function `applyAgX` processes a linear sRGB image array by applying a custom grading, AgX Log encoding, AgX Base LUT, and Punchy view-transform to convert it into a display-ready sRGB SDR format for standard monitors. It takes a float32 RGB array as input and returns the transformed array optimized for visual outpu...
def applyAgX(array): # type: (numpy.ndarray) -> numpy.ndarray """ -> take linear - sRGB image data as input - apply custom grading if any - apply the AgX Punchy view-transform - return a display-ready array encoded for sRGB SDR monitors Args: array: float32 array, R-G-B format, sRGB...
def generatePossible(puz: puzzle) -> list: """ This function takes in a puzzle and returns a 2D list of all the valid moves for a space. :param puz: puzzle :return: list """ poss = [] for row in range(9): poss.append([]) for col in range(9): poss[row].append([]) ...
The code solves a puzzle by first applying logical deduction techniques (solving singles and hidden singles) iteratively until no more progress is possible. If the puzzle remains unsolved, it initiates a brute-force solution in a separate thread with a 5-minute timeout. It validates the puzzle's solvability, prints pro...
def solve(puz: puzzle) -> None: """ Main code for solving a single puzzle. :param puz: :return: """ poss1 = [] poss2 = generatePossible(puz) # Makes sure all single and hidden solved while not puz.solved() and poss2 != poss1: poss1 = poss2 solveSingles(puz) so...
def readInput(): with open('./input.txt', 'r') as f: boarding_passes = [i.strip() for i in f.readlines()] return boarding_passes def part1(boarding_passes): max_id = 0 for boarding_pass in boarding_passes: row_code = boarding_pass[:-3] seat_code = boarding_pass[7:] ro...
The main task of the code is to process boarding passes by reading input data, then executing two separate functions (`part1` and `part2`) to compute results, likely for solving a puzzle or problem involving seat assignments or similar logic. The code structure separates input handling and problem-solving steps.
def main(): boarding_passes = readInput() part1(boarding_passes) part2(boarding_passes)
def train_mini_batch(model, feats, labels, batch_size, criterion, optimizer, lamb=1): """ Train MLP for large datasets. Process the data in mini-batches. The graph is ignored, node features only. lamb: weight parameter lambda """ model.train() num_batches = max(1, feats.shape[0] // batch_size) ...
This function trains an inductive MLP model using observed and target data splits, performs early stopping based on validation performance, evaluates on validation and test sets, and returns model outputs along with validation and test scores. It uses mini-batch training, tracks best epochs, and logs results.
def run_inductive_mlp( conf, model, obs_g, g, obs_feats, obs_labels, feats, labels, indices, criterion, evaluator, optimizer, logger, loss_and_score ): obs_idx_train, obs_idx_val, obs_idx_test, idx_obs, idx_test_ind = indices batch_size = conf["batch_...
def is_collision(self, block=None): ''' Check for collision against a wall or the snake's body. ''' if block is None: block = self.head # Hits boundary if block.x > self.width - TILE_SIZE or block.x < 0 or block.y > self.height - TILE_SIZE or block.y < 0: return T...
The code simulates one game frame by updating the snake's state, checking collisions, determining the agent's action based on environmental cues (direction, food position), executing movement, handling food consumption, and resetting the game if conditions trigger a loss. It maintains game logic, UI updates, and perfor...
def play_step(self): ''' Run a frame of the game. ''' self.frame_iteration += 1 # Set-up for getting the state head = self.snake[0] point_l = Point(head.x - TILE_SIZE, head.y) point_r = Point(head.x + TILE_SIZE, head.y) point_u = Point(head.x, head.y - TILE_SIZE)...
def update_archive(self, Y): self.gen+=1 if self.gen < self.delta: self.archive.append(Y) self.CR_archive.append(self.calc_CR()) self.Ui_archive.append(self.calc_Ui()) else: self.archive.append(Y) self.archive.pop(0) ...
The code implements a stopping criterion in an online learning process. It checks if the current Ui_star value is less than Ut. If true, it resets internal archives and counters, signaling termination. Otherwise, it continues. The condition likely determines when to halt based on performance metrics, with archive reset...
def OnlineStoppingCriteria(self, Y): self.update_archive(Y) # flag = self.CR_archive[-1]>0.9 #0.8 flag = self.Ui_star() < self.Ut() if flag: self.archive = [] self.CR_archive = [] self.Ui_archive = [] self.Uinit = -1 self.gen = ...
def plist_reader(plist_file_path): """A helper function to get the contents of a Property List file. Args: plist_file_path (str): A .plist file path to read in. Returns: stdout: Returns the contents of the plist file. """ if os.path.exists(plist_file_path): log.debug(f"Reading {plist_file_path}...") w...
The main task of the code is to clean up a configured delay for an application by removing its entry from a patch_plist file, stopping the associated LaunchDaemon service, and deleting the LaunchDaemon file. It handles parameters like application name, launch daemon details, and OS version, ensuring safe removal by che...
def clean_up(**parameters): """Cleans up a configured delay for the application and stops and deletes the delay LaunchDaemon. Args: parameters (kwargs): Key word arguments """ log.info("Performing cleanup...") application_name = parameters.get("application_name") launch_daemon_label = parameters.get('launc...
def is_daemon_running(os_version, launch_daemon_label): """Checks if the daemon is running. Args: os_version (int): Used to determines the proper launchctl syntax based on OS Version of the device launch_daemon_label (str): The LaunchDaemon's Label Returns: bool: True or False whether or not the LaunchDae...
This function starts or restarts a macOS LaunchDaemon based on the OS version. If the daemon is already running, it restarts it after detecting plist changes. For OS 10.11+, it uses `bootstrap` and `enable` with formatted paths; for 10.10-, it uses `load`. It logs actions and ensures proper daemon initialization throug...
def start_daemon(os_version, launch_daemon_label, launch_daemon_location): """Starts a daemon, if it is running, it will be restarted in case a change was made to the plist file. Args: os_version (int): Used to determines the proper launchctl syntax based on OS Version of the device launch_daemon_label (str)...
def plist_reader(plist_file_path): """A helper function to get the contents of a Property List file. Args: plist_file_path (str): A .plist file path to read in. Returns: stdout: Returns the contents of the plist file. """ if os.path.exists(plist_file_path): log.debug(f"Reading {plist_file_path}...") w...
The code creates a macOS LaunchDaemon to trigger a "Delayed Patch" policy in Jamf Pro after a specified delay. It updates a patch plist to mark the application as "Delayed," generates a LaunchDaemon plist with the policy ID and delay interval, writes both plists, and starts the daemon if successful.
def create_delay_daemon(**parameters): """Creates a LaunchDaemon based on the user selected delay time which will the call a "Delayed Patch" Policy in Jamf Pro. Args: parameters (kwargs): Key word arguments """ application_name = parameters.get("application_name") launch_daemon_label = parameters.get('launch...
def get_angular_edge_ordering(metro_map, node): edge_list = [] for e in metro_map.edges(node): edge_dir = (e[1].coord_x - e[0].coord_x, e[1].coord_y - e[0].coord_y) angle = get_map_edge_angle(edge_dir) edge_list.append((e, angle)) edge_list.sort(key=lambda x: x[1]) return [x[0]...
The function adjusts sink edge costs in a graph (A_) by initializing them to zero, then adding bend costs based on adjacent edges in another graph (G). It uses angular ordering from a metro map to determine valid edge ranges, setting invalid edges' costs to infinity. This ensures correct edge ordering and penalizes ben...
def open_sink_edges(A_, G, metro_map, octi_node, input_node, input_edge, a_change_dict): # easy but incomplete: just set the sink weights to their default value # for sink_edge in A_.edges(octi_node): # A_[sink_edge[0]][sink_edge[1]]['cost'] = get_sink_edge_cost(sink_edge) # more advanced but still i...
def auxiliary_graph(G: nx.Graph): A = nx.Graph() # add for node in G.nodes: intermediate_nodes = [] for edge in list(G.edges(node)): other_node = edge[0] if node == edge[1] else edge[1] intermediate_nodes.append((node, other_node)) A.add_node((node, othe...
The function `fix_weights` modifies the edge costs in an auxiliary graph `A` derived from `G`. It adjusts edge costs based on adjacency to sets `S` or `T`: edges connected to `S` are scaled by the distance from their node to input node `iS`, and similarly for `T` and `iT`, using `CELL_SIZE` for normalization. Non-adjac...
def fix_weights(G, iS, S, iT, T): A = auxiliary_graph(G) for edge in A.edges: n1 = edge[0] n2 = edge[1] if n1 in S or n2 in S: # edge adjacent to set S, set off cost by distance to input node iS n = n1 if n1 in S else n2 A[n1][n2]["cost"] = get_auxil...
def is_aux_edge(e): n1 = e[0] n2 = e[1] if is_aux_sink_node(n1) and is_aux_sink_node(n2): return False return True def is_aux_sink_edge(e): assert is_aux_edge(e) n1 = e[0] n2 = e[1] for n in [n1, n2]: if is_aux_sink_node(n): return True return False def ...
The function determines if an edge is an auxiliary bend edge by verifying it is an auxiliary edge (via assert), and ensuring it is neither an auxiliary sink edge nor an auxiliary external edge. It returns True only if both conditions are met.
def is_aux_bend_edge(e): assert is_aux_edge(e) return (not is_aux_sink_edge(e)) and (not is_aux_external_edge(e))
def show_octilinear_graph(Graph, labels): G = Graph color_map_nodes = [] for node in G.nodes: if G.nodes[node]['isStation']: color_map_nodes.append('red') else: color_map_nodes.append('blue') color_map_edges = [] for edge in G.edges: if 'line' in G.ed...
The main task of the code is to route edges in a graph by mapping input nodes to an octilinear grid, using auxiliary graphs and Dijkstra's algorithm to find optimal paths between candidate nodes. It adjusts graph structures, enforces station connections, and ensures connectivity while handling edge cases like missing p...
def route_edges(edges, G, metro_map): show_octilinear_graph(G, False) grid_node_dict = {} # drawn_edges_dict = {} A = auxiliary_graph(G) num_edges = len(edges) # iterate through edges of input graph for i, edge in enumerate(edges): try: node_0 = edge[0] node...
def edge_adj_to_edge(e1,e2): return e1[0] == e2[0] or e1[0] == e2[1] or e1[1] == e2[0] or e1[1] == e2[1] def is_aux_bend_edge(e): assert is_aux_edge(e) return (not is_aux_sink_edge(e)) and (not is_aux_external_edge(e)) def get_bend_edge_cost(edge): return cost_dictionary[get_auxiliary_bend_angle(edge)]...
This function identifies and processes edges crossed by a new path in a metro map graph, adjusting auxiliary edge costs for bends and diagonals, updating a change dictionary, and ensuring valid crossings while raising errors if no viable path exists.
def open_crossed_edges(A, edge, metro_map, G, drawn_edges_dict, a_change_dict): crossed_edge_dict = {} this_bb = BBox(edge) min_path_length = 1 for mm_edge in metro_map.edges: if edge_adj_to_edge(edge, mm_edge): continue if not edge_intersect(edge, mm_edge, this_bb): ...
def MF_KBRendering(self,B,success,error): if self.Book_KB >= self.MF_Steps*1024 and self.MF_Steps < self.MF_Num: self.OF_CreateSizeFile(self.MF_Steps) self.NameList.append(str(self.MF_Steps)) self.MF_Steps += 1 if self.Book_KB < self.MF_Steps*1024: if no...
This code creates a GUI application for sorting e-book words using various algorithms. It initializes a Pygame window with menus to select single/multi-file modes, adjust file sizes, choose books, select sorting methods (Merge, Shell, Heap, Quick), and display results. The interface handles user interactions, state tra...
def MainRun(self): pg.init()#initialize pygame BG=BackGround()#call Background screen object screen=pg.display.set_mode((BG.width,BG.height))#Set width and height of screen pg.display.set_caption('E-Book Words Sorting')#Set caption of screen #Create Text and Buttons for menu i...
def collect_extern_file_imports(fname): imports = find_toplevel_imports(fname) return [i for i in imports if not is_in_cwd(i) and not is_std_lib(i)] def collect_dir_imports(dir): imports = {} for root, dirs, files in os.walk(dir, topdown=False): for f in [f for f in files if os.path.splitext(f)[...
The main task of the code is to validate whether all external imports in a specified Python file or directory are listed in a given requirements file. It accepts either a single file or directory path, parses the requirements from a file, and checks if all detected imports are present. If valid, it prints a success mes...
def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("--file", default=None, help="single file") group.add_argument("--dir", default=None, help="directory") parser.add_argument("--req", default=None, help="compare to requirements") args ...
def find_matrix_list_from_gen(GF, gen_matrix): """ DESC: base function for finding all permutations of a generalized matrix PARAMS: gen_matrix(matrix of int): general matrix for all possible matrices in final list ...
The function `generate_list_of_type_matrices` generates and prints matrices of type "sqrt" or "chol" based on input parameters `GF` (field size), `n` (matrix dimension), and `type`. It first creates an upper triangular matrix, derives candidate matrices, then filters them into either square root (sqrt) or Cholesky (cho...
def generate_list_of_type_matrices(type, GF, n): """ DESC: generate a list of matrices which conform to runtype set, GF, and n PARAMS GF(int)...
def BuySellHold(): if portfolioStocks: for stock in portfolioStocks.copy(): if get_market_price(stock) > get_lr_prediction(1, load_data(stock)) or calcChange(stock, portfolioStocks) < 0.1: ...
The code's main task is to display a user's portfolio information in a Streamlit app, showing the total portfolio value and individual stock metrics (name, value, and percentage change) organized in a 3-column layout. It uses a spinner for loading feedback, checks for stock data, and dynamically renders stock details u...
def display(self): self.st.title("Portfolio") with self.st.spinner('Loading...'): if stockList: BuySellHold() self.st.write('Your Portfolio Value: ', round(get_portfolioValue(), 2), '$') i = 0 cols = self.st.columns(3) for stock...