dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def getRecipe(url): r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') return soup def getTitle(soup): title = str(soup.title.text) return title def getIngredients(soup): ingredients = soup.find_all("li", class_="ingredients-item") if not ingredients: #do this later ...
The code transforms a recipe based on user-specified categories (e.g., vegetarian, healthy, Chinese), fetching recipe details, modifying ingredients/steps using predefined mappings, and allowing iterative changes. It prints original and transformed data, then lets users select new transformations or recipes recursively...
def main(url, transform, passed_steps, passed_ingredients): stillRunning = True if url == '0': stillRunning = False while stillRunning: if transform == "vegetarian": transform_dict = vegetarian elif transform == "non-vegetarian": transform_dict = not_vegetar...
def adjustWeights(self,node: Node): curr = node while(curr): curr.height = self.adjustCurrentNodeWeights(curr) curr = curr.parent def balance(self, node: Node): curr = node while(curr): BF = self.getBalanceFactor(curr) leftBF = self.getBala...
This function deletes a specified value from a binary tree iteratively. It handles cases where the node is a leaf, has one child, or two children, adjusting the tree structure by updating parent pointers, rebalancing, and managing weights. If duplicates exist, it identifies and removes them, ensuring proper tree integr...
def deleteIter(self,value): count = 0 root = self.root duplicateExist = False while(root != None): count += 1 if(value < root.value): root = root.left elif(value > root.value): root = root.right else: ...
def prGreen(msg): return f"\033[1;32m{msg.upper()}\033[0m" def dupeChecker(letter, rowIP): # Edin doesn't have a repeat function so obviously my wordle is better global avaliableKeyboard dupeCount = theWord.count(letter) if dupeCount == 1: yellowLetter = prYellow(letter) totalRow = rowIP + f...
The function checks each letter of the input word against a target word, applying color coding (green for correct position, black for incorrect) and updating an available keyboard display. It constructs a feedback string, checks for a win, and updates the game board.
def wordChecker(wordInput): global avaliableKeyboard totalRow = '' for x in range(0, 5): if wordInput[x] == theWord[x]: greenLetter = prGreen(wordInput[x]) totalRow = totalRow + f'[{greenLetter}]' avaliableKeyboard = avaliableKeyboard.replace(wordInput[x], greenLe...
def vowelNumCheck(wordInput): vowels = "AEIOU" vowelState = False for y in vowels: if y in wordInput: vowelState = True if len(wordInput) != 5: vowelState = False return vowelState def alphaCheck(inWord): alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" verifier = 0 for al...
The code validates a user's input word by ensuring it contains the correct number of vowels and only alphabetic characters. It repeatedly prompts the user to re-enter the word if invalid. Once valid, it checks the word, displays the game board, and shows available letters for the word-guessing game.
def guess(guessWord): guessWord = guessWord.upper() while vowelNumCheck(guessWord) == False: guessWord = input('Your word isn\'t a real world, Enter again: ') guessWord = guessWord.upper() vowelNumCheck(guessWord) while alphaCheck(guessWord) == False: guessWord = input('Your ...
def responsive_spaces(frame, rows, columns): for i in range(rows): frame.grid_rowconfigure(i, weight=1) for i in range(columns): frame.grid_columnconfigure(i, weight=1) def get_time(self): string = strftime('%H:%M:%S %p') self.time_label.config(text=string, font=('Arial', 30, 'bo...
This code initializes a Hotel POS GUI with a database, setting up a Tkinter window for managing customer orders. It includes sections for customer details, time display, item registration, menu items, checkout totals, and table management. The interface allows loading room data, modifying order quantities, deleting ite...
def __init__(self, database: Database): self.data = database self.root = Tk() self.root.title("HotelPos") self.root.config(padx=20, pady=20) responsive_spaces(self.root, 10, 6) # ------------------------------------ VARIABLES ---------------------------------------------...
def _on_mouse_down(self): """Called when a mouse button is clicked""" pos = pg.mouse.get_pos() # If left button, add agent at cursor position if self._mouse_button_down == 1: self._add_agent((math.floor(pos[0] / self._cell_size), math.floor(pos[1] / self._cell_size)), 'p') de...
This code initializes a Pygame simulation window, processes user inputs (mouse/keyboard events), controls auto-run settings, executes simulation steps, and renders the grid. It handles quitting, mouse interactions, key commands (space, R, S, L), and auto-run delays. The loop updates the simulation state, draws the grid...
def start(self): """Main loop for the simulation""" # Start pygame and create a window pg.init() self._window = pg.display.set_mode(((self._grid_size[0]) * self._cell_size, (self._grid_size[1]) * self._cell_size)) done = False # Loops until closed while not done: ...
def _load(self): rospy.loginfo("[Blimp Environment Node] Load and Initialize Parameters...") self.cnt = 0 self.RATE = rospy.Rate(100) self.GRAVITY = 9.81 # actuator self.stick_angle = 0 self.elv1_angle = 0 self.elv2_angle = 0 self.rud1_angle = ...
The code initializes a ROS node for a blimp environment, loads configurations, sets up publishers/subscribers, and starts a control loop to manage the blimp's operations in a simulated or real-world setting.
def __init__(self): rospy.init_node('blimp_node', anonymous=False) rospy.loginfo("[Blimp Environment Node] Initializing...") self._load() self._create_pubs_subs() # self.gaz = GazeboConnection(True, "WORLD") # self.gaz.unpauseSim() rospy.loginfo("[Blimp Environme...
def st_stdout(dst, msg): """https://discuss.streamlit.io/t/cannot-print-the-terminal-output-in-streamlit/6602""" with st_redirect(sys.stdout, dst, msg): yield def get_sample_images(dataset, n): n_data = len(dataset) ans = [] if n < n_data: indexes = np.random.choice(n_data, n, replac...
The main task of the code is to create a Streamlit web application for anomaly detection in images. It allows users to select datasets (custom or MVTec), configure detection methods (SPADE, PaDiM, PatchCore), and visualize anomaly scores. The app loads training/test data, trains models, and displays pixel-level anomaly...
def main(): with open("./docs/streamlit_instructions.md","r") as file: md_file = file.read() st.markdown(md_file) st.sidebar.title("Config") app_custom_dataset = st.sidebar.checkbox("Custom dataset", False) if app_custom_dataset: app_custom_train_images = st.sidebar.file_uploader( ...
def remove_letter_to_match(data_collection, file_dict, prefix, i): SCORING = [10, 8, 6, 4, 2] tmp = get_best_k_completions(data_collection, file_dict, prefix) tmp = remove_duplicate_objects_from_list(tmp) for object_ in tmp: object_.set_score(SCORING[i] if i < len(SCORING) else SCORING[-1]) ...
The function `complete_word` generates text completions by modifying a given `prefix` through three operations: removing, changing, or adding a character. It checks if these modified prefixes exist in `data_collection`, then collects matching results using helper functions. The `search_result` list is pruned to size `K...
def complete_word(data_collection, file_dict, prefix, search_result): CHAR_LIST = list(ascii_lowercase) + list(digits) for i in range(len(prefix)): # remove one letter to match a completion if prefix[:i] + prefix[i + 1:] in list(data_collection.keys()): search_result += remove_lett...
def get_best_k_completions(data_collection, file_dict, prefix): list_of_auto_completes = load_data_from_files(data_collection[prefix], file_dict, prefix) return list(list_of_auto_completes.values()) def clean_string(string_): string_ = string_.translate(string_.maketrans("", "", string.punctuation)) re...
The function retrieves the best k completions for a given string from a dataset, returning them if sufficient; otherwise, it searches for similar completions to fulfill the request.
def online(data_collection, file_dict, string_to_complete): # get best k completions search_result = get_best_k_completions(data_collection, file_dict, clean_string(string_to_complete)) # found - return to user... if len(search_result) == K: return search_result # try to find similar compl...
def get_completed_companies() -> list[str]: try: with open('Voltooid.txt', 'r+') as file: data = file.read().splitlines() return data except FileNotFoundError: print('func: get_completed_companies: Voltooid.txt bestaat nog niet') def strip_name(string: str) -> str: fo...
The main task of the code is to add tags to companies in a DataFrame by checking each row against a list of completed companies. For unprocessed entries, it cleans the company name, invokes `find_company` with relevant parameters, and logs errors for timeout exceptions. The function processes debtor numbers, raw compan...
def add_tags(self, df: pd.DataFrame): completed_list = get_completed_companies() label = df.columns.to_list()[1] for index, row in df.iterrows(): if row[1] not in completed_list: try: company = strip_name(row[1]) if company is N...
def getScope(): scope = loadScope() scope = mergeScope( scope, parseFilter(os.getenv(cmd.upper(),"")) ) for key in scope: scope[key] = os.getenv(cmd.upper() + "_" + key.upper(), scope[key]) pass if scope["context"] == "" and scope["project"] != "": scope["context"] = getDefaultCo...
The main task of the code is to filter and list tasks from markdown files in a specified location, applying scope-based criteria if enabled. It loads YAML content from each file, checks scope key matches, sorts tasks by ID, assigns sequential numbers, and returns the structured list of valid tasks with metadata like fi...
def listTasks(location, useScope=True): scope = getScope(); files = findTaskFiles( location, "*.md" ) tasks = [] for filename in files: task = loadYaml(filename) task["fullfilename"] = filename addItem = True for key in scope: addItem = addItem and ( scope[key...
def getLastId(): files = findTaskFiles("*", "*.md") maxId = -1 for filename in files : # Open the file and load the file id = loadYaml( filename )["id"] if id > maxId: maxId = id pass pass return maxId pass def tskpath(): default=cmd ho...
The main task of the code is to create a new task file with metadata, generating a sanitized filename using the task name, timestamp, and ID, then saving it in a directory and committing the change via Git. It processes the input name by stripping whitespace, replacing quotes, splitting/joining spaces with underscores,...
def createTask( name ): name = name.strip() if name == "": return name = name.replace("\"","'") tasknameArr = name.split(" ") taskname = '_'.join( tasknameArr ) taskname = unidecode( taskname ) taskname = sanitize( taskname ).replace("'","").replace("\"","").replace("`","").replace("...
def listTasks(location, useScope=True): scope = getScope(); files = findTaskFiles( location, "*.md" ) tasks = [] for filename in files: task = loadYaml(filename) task["fullfilename"] = filename addItem = True for key in scope: addItem = addItem and ( scope[key...
The code archives completed or failed tasks by moving their files into a date-specific directory structure and commits the changes using Git. It retrieves current tasks, filters those marked as 'done' or 'fail', creates target paths, renames files accordingly, and executes a Git commit to record the archival action.
def archive( date ): tasks = listTasks("cur", useScope=False) if len(tasks) == 0: raise ETasksNotFound() pass for task in tasks: if task["status"] not in ["done","fail"]: continue pass targetPath = tskpath() + "/"+date+"/"+task["status"] os.ma...
def read_data(filename): with open(filename, 'r') as f: str = f.read() return ujson.loads(str) def file_exists(filename): try: os.stat(filename) return True except OSError: return False def encrypt_text2file(passw, text, file): barray = encrypt_text(passw, text) ...
The code initializes encryption keys and default configuration files for a system. It reads encryption parameters from a JSON file, sets global variables for keys and IV, and creates default master credentials, Wi-Fi settings, and an empty credentials file if they don't exist, ensuring essential system configurations a...
def init(): global enckey global enciv global enckey_set json = read_data(ENCRYPT_FILE) enckey = ubinascii.a2b_base64(json['encryption']['enckey']) enciv = ubinascii.a2b_base64(json['encryption']['iv']) enckey_set = json['encryption']['set'] if not file_exists(MASTER_FILE): mast...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The code handles a password change request by verifying the user's login status, checking for concurrent logins, decrypting the request payload, validating the current password against a master password, updating the SSID file's hint field with the new password hint, and returning a success or error response.
def change_pass(req): global loggedin if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg # decrypt payload bodytext = decode_and_decrypt(enckey, req.body) jsdata = ujson.loads(bodytext) if jsdata['password...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The main task of the code is to allow a logged-in user to change the access point's password and optionally its SSID name. It verifies the user's current password against a master password, updates the configuration in a JSON file, adjusts the global AP_PASSWORD variable, and returns success or error responses based on...
def change_ssid_pass(req): global AP_PASSWORD if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg # decrypt payload bodytext = decode_and_decrypt(enckey, req.body) jsdata = ujson.loads(bodytext) if jsdata['...
def get_login(): json = read_data(SSID_FILE) resp = send_file('static/views/login.html') resp.set_cookie('hintText', json['accesspoint']['hint']) return resp def decode_and_decrypt(enckey, text): decoded = ubinascii.a2b_base64(text) barray = bytearray(decoded) return decrypt_bytes(enckey, ba...
This code handles user login authentication by verifying provided credentials against a decrypted master file. It checks if a user is already logged in, processes GET/POST requests, decrypts login data, validates credentials, and updates global state variables (loggedin, MASTER_USER, MASTER_PASSWORD, IP_ADDRESS) upon s...
def login(req): global loggedin global MASTER_USER global MASTER_PASSWORD global IP_ADDRESS if loggedin: return send_file('static/views/index.html') if req.method == "GET": return get_login() bodytext = decode_and_decrypt(enckey, req.body) json_body = ujson.loa...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The function `get_keys` authenticates a logged-in user, checks for concurrent logins, decrypts a credentials file, processes its contents to generate sorted, encrypted keys, and returns them in a JSON structure with user status. It handles errors for logout, concurrent sessions, and decryption failures, ensuring secure...
def get_keys(req): if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg text = decrypt_file2text(MASTER_PASSWORD, CREDS_FILE) if text == 'ERROR': return prep_error('error') json = ujson.loads(text) rech...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The code deletes a specific record from an encrypted credentials file by decrypting the file, searching for a matching key, removing the corresponding entry, re-encrypting the updated data, and returning a success status. It also validates user authentication and checks for concurrent logins before performing the opera...
def del_key(req): if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg key = decode_and_decrypt(enckey, req.body) # create the array of hashes text = decrypt_file2text(MASTER_PASSWORD, CREDS_FILE) if text == 'ER...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The main task of the code is to retrieve and encrypt user credential key-value pairs from a decrypted file. It checks login status, decrypts stored credentials, processes records into sorted key-value pairs, encrypts them, and returns a JSON response with user status and encrypted data.
def get_key_values(req): if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg text = decrypt_file2text(MASTER_PASSWORD, CREDS_FILE) if text == 'ERROR': return prep_error('error') json = ujson.loads(text) arr = ...
def prep_error(status): user = {'status' : status} return ujson.dumps({'user' : user}) def logged_in_elsewhere(req): host_addr, port = req.client_addr if host_addr != IP_ADDRESS: return True, 'Not allowed to login from multiple devices at the same time.' else: return False, '' def de...
The function saves new key-value pairs to an encrypted credentials file after verifying user authentication and ensuring no duplicates. It decrypts existing credentials, merges new entries, and re-encrypts the updated data.
def save_key_values(req): if not loggedin: return prep_error('loggedout') error, msg = logged_in_elsewhere(req) if error: return msg curtext = decrypt_file2text(MASTER_PASSWORD, CREDS_FILE) json = ujson.loads(curtext) curarr = json['records'] # create a hash to...
def add_address_wrapper(address, user1): try: add_address(address, user1) except: print("AddressBook couldn't be added to") print("Address: ", address) print("user: ", user1) def show_table(tableName, mycursor=None): if mycursor is None: mycursor, connection = get_my...
The code fetches Bitcoin address data from an API, stores balances and transactions in a database, and displays address book contents. It processes two addresses for user "Bobert," retrieves balance details, logs transactions, and prints stored data. The script also includes commented-out functionality for user deletio...
def main(): print('Hello world') # store the URL in url as # parameter for urlopen url_base = 'https://api.blockchair.com/bitcoin/dashboards/address/' address = '3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd' address1 = 'bc1q0sg9rdst255gtldsmcf8rk0764avqy2h2ksqs5' user1 = "Bobert" add_address_wrap...
def deform_with_MLS(cage, new_cage, source_shape, cage_weights=None, pp_distances=None, alpha=0.5, deform_type='affine', epsilon=1e-8): ''' compute Moving Least Squares - Affine transformation. - ref: https://people.engr.tamu.edu/schaefer/research/mls.pdf Args: @Param 'cage': control points - (B, P...
This function logs and saves deformed 3D mesh outputs from a neural network at each training step. It applies multiple deformation methods (NeuralMLS, MLS, KPD, ARAP) to control points, generates colored 3D models, and stores them as .obj files in a specified directory. The function handles conditional saving based on ...
def log_outputs(opt, step, network, all_inputs, save_dir=None, save_all=False, KPDoutputs=None): if save_dir is None: save_dir = opt.log_dir faces_exists = 'source_face' in all_inputs and all_inputs['source_face'] is not None cp = all_inputs["source_cp"] device = cp.device source_shape = a...
def _create_cells(self): self._cells=[] for i in range(self._num_cols): col_cells=[] for j in range(self._num_rows): curr_x1 = self._x1 + i*self._cell_size_x curr_x2 = curr_x1 + self._cell_size_x curr_y1 = self._y1 + j*self...
This code initializes a maze structure with specified dimensions and cell sizes, sets up a graphical window if provided, and prepares the maze for generation by creating cells, breaking walls recursively, and setting entrance/exit points. It handles seed initialization for randomization and resets visited cell tracking...
def __init__( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None, ): self._x1=x1 self._y1=y1 self._num_rows=num_rows self._num_cols=num_cols ...
def build_data(): global data_processor data_processor = None data_processor = DataProcessor(tiker, is_local, period, interval, features, technical_indicators, target, batch_size, seq_len, train_ratio...
The code trains a model using built data, generates predictions, backtests them on simulated data, evaluates performance metrics (accuracy, AUC, Sharpe Ratio, etc.), and logs results with WandB if enabled. It saves visualization outputs with timestamped filenames for analysis.
def run(): global data_processor build_data() build_model() print_info() y_pred, acc, auc = train() sim_data = data_processor.get_simulate_data() sim_data['y_pred'] = y_pred bt = sim.backtest(sim_data) sim_result = bt.run() bt.plot(filename=f'./simulation/{model_name}_{time....
def __media(self, dataset): mu = np.array([]) for d in np.transpose(dataset): mu = np.append(mu,np.mean(d)) return mu def __varianza(self, dataset): var = np.array([]) for d in np.transpose(dataset): var = np.append(var, np.var(d)) return var def _...
This code implements gradient descent optimization for model training. It normalizes the dataset, iteratively updates parameters by subtracting a gradient scaled by λ, and stops when parameter changes fall below a threshold (min_step). The loop adjusts weights using gradient calculations, tracking parameter differences...
def train(self, result, dataset): self.media = self.__media(dataset) self.var = self.__varianza(dataset) norm_data = self.__normailize_dataset(dataset) avance = 1 params2 = self.params while avance>self.min_step: avance = 0 for i, w in enumerate(self...
def __media(self, dataset): mu = [0.0] * self.num_params for d in dataset: for i, e in enumerate(d): mu[i] += e for i in range(len(dataset[0])): mu[i] /= len(dataset) return mu def __varianza(self, dataset): var = [0.0] * self.num_params ...
The code performs gradient descent optimization by iteratively updating model parameters. It calculates the mean and variance of the dataset, then adjusts parameters using the gradient of the loss function. The loop continues until parameter updates fall below a threshold (min_step), ensuring convergence.
def train(self, result, dataset): self.media = self.__media(dataset) self.var = self.__varianza(dataset) avance = 1 params2 = self.params while avance>self.min_step: avance = 0 for i, w in enumerate(self.params): wprev = w param...
def init_game(self): self.restart_game() arcade.schedule(self.add_rocks, 1) arcade.schedule(self.add_invaders,2.5) def show_controls(self): self.app_started = False self.app_lose = False self.app_tutorial = True def show_introduction(self): self.app_started = False self.app_lose = False ...
This code handles keyboard input events in a game. It controls player movement (WASD/arrow keys), shooting bullets (W/Q), activating a shield (E), pausing (P), and managing game states (initiation, tutorial, exit). Different key actions trigger specific behaviors based on game conditions like pause status, shield activ...
def on_key_press(self, symbol: int, modifiers: int): if self.app_started: if not self.pause_game: if symbol == arcade.key.UP: self.player.speed_y = SPEED if symbol == arcade.key.DOWN: self.player.speed_y = -SPEED if symbol == arcade.key.LEFT: self.player.s...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image_gray = np.float32(image_gray) return image_gray def load_original_image()->np.ndarray: global g_...
The code processes an image to detect and visualize key points using Difference of Gaussian (DoG) and non-maxima suppression. It generates smoothed images at multiple scales, computes DoG images, identifies key points via suppression, and marks them on the original image. The key points are saved for subsequent tasks. ...
def task_2()->list: image = load_image_and_convert_to_grayscale() save_image = load_original_image() images, sigma_arr = get_twelve_smoothed_images(image) # This variable controls whether the original image is considered in the # scale space or not. # For now we set it to false include_base...
def get_twelve_smoothed_images(image)->tuple: sigma_arr = [] images = [] for k in range(12): sigma = (2 ** (k/2)) sigma_arr.append(sigma) g = get_gaussian_smoothing_kernel(sigma) im = cv2.filter2D(image.copy(), -1, g) images.append(im) return images, sigma_arr def...
The main task of the code is to generate and visualize Gaussian smoothing kernels for twelve different sigma values applied to a grayscale image. It loads an image, computes twelve smoothed versions with varying sigma values, prints the sigma array, displays the smoothed images, creates Gaussian kernels for each sigma,...
def task_1b(): images, sigma_arr = get_twelve_smoothed_images(load_image_and_convert_to_grayscale()) print(sigma_arr) display_images_meshgrid(images) gaussian_kernels = [] for s in sigma_arr: gaussian_kernels.append(get_gaussian_smoothing_kernel(s)) display_images_meshgrid(gaussian_kerne...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() #image = cv2.imread('sobx.png') image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #image_gray = image_gray.astype(float) image_gray = np.float32(image_g...
The main task of the code is to detect and visualize key points in an image using the Difference of Gaussians (DoG) method with non-maxima suppression. It loads and processes images, computes smoothed Gaussian versions, generates DoG images, identifies significant points via non-maxima suppression, and overlays these p...
def task_2()->list: image = load_image_and_convert_to_grayscale() save_image = load_original_image() images, sigma_arr = get_twelve_smoothed_images(image) include_base_image = False if include_base_image: new_images = [image.copy()] [new_images.append(x) for x in images] new...
def get_twelve_smoothed_images(image)->tuple: sigma_arr = [] for k in range(12): #sigma_arr.append(math.pow(2, k/2)) sigma_arr.append(2 ** (k/2)) images = get_smoothed_images(image, sigma_arr) return images, sigma_arr def load_image_and_convert_to_grayscale()->np.ndarray: """ Ope...
The main task of the code is to load and grayscale an image, generate twelve smoothed versions of it, display them, compute Gaussian kernels for varying sigma values from sigma_arr, and visualize these kernels in color. The code prints sigma values, displays smoothed images, and shows the corresponding Gaussian kernels...
def task_1b(): images, sigma_arr = get_twelve_smoothed_images(load_image_and_convert_to_grayscale()) print(sigma_arr) display_images_meshgrid(images) gaussian_kernels = [] for s in sigma_arr: gaussian_kernels.append(get_gaussian_smoothing_kernel(s)) display_images_meshgrid(gaussian_kerne...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() #image = cv2.imread('sobx.png') image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #image_gray = image_gray.astype(float) image_gray = np.float32(image_g...
The main task of the code is to detect key points in an image using the Difference of Gaussians (DoG) method. It generates smoothed images with varying sigma values, computes DoG images, applies non-maxima suppression to identify key points, visualizes the DoG results, and marks the detected points on the original imag...
def task_2()->list: image = load_image_and_convert_to_grayscale() save_image = load_original_image() images, sigma_arr = get_twelve_smoothed_images(image) include_base_image = False if include_base_image: new_images = [image.copy()] [new_images.append(x) for x in images] new...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image_gray = np.float32(image_gray) return image_gray def load_original_image()->np.ndarray: global g_...
The main task of the code is to process key points by calculating their direction using the derivative of Gaussian images, then visualizing these directions on the original image with circles and lines. It builds a cross-reference dictionary for future tasks, computes magnitudes and angles for each pixel, and returns a...
def task_3()->tuple: # Get the grayscale image image = load_image_and_convert_to_grayscale() # Also load the original color image, which we will use # to draw everything at the end save_image = load_original_image() # Get the twelve smoothed images images, sigma_arr = get_twelve_smoothed_im...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() #image = cv2.imread('sobx.png') image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #image_gray = image_gray.astype(float) image_gray = np.float32(image_g...
The main task of the code is to detect and visualize key points in an image using Gaussian derivatives. It computes smoothed images, calculates gradient magnitudes and angles, and augments key points with directional information. The function then draws circles and lines on the original image to represent these points,...
def task_3(): image = load_image_and_convert_to_grayscale() save_image = load_original_image() images, sigma_arr = get_twelve_smoothed_images(image) key_points = task_2() dog_images = get_derivative_of_gaussian(images, sigma_arr) magnitudes = [] theta_array = [] sigma_cross_ref = {} ...
def load_image_and_convert_to_grayscale()->np.ndarray: """ Open the image and convert to grayscale """ image = load_original_image() #image = cv2.imread('sobx.png') image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #image_gray = image_gray.astype(float) image_gray = np.float32(image_g...
The code processes an image to detect and visualize key points with their dominant orientations. It generates smoothed images, computes gradients, and determines magnitudes and angles. For each key point, it calculates the dominant direction using interpolation and weighted histograms, then draws circles and directiona...
def task_3(): image = load_image_and_convert_to_grayscale() save_image = load_original_image() images, sigma_arr = get_twelve_smoothed_images(image) key_points = task_2() dog_images = get_derivative_of_gaussian(images, sigma_arr) magnitudes = [] theta_array = [] sigma_cross_ref = {} ...
def unique_combinations(iterable, r): values, counts = zip(*Counter(iterable).items()) return unique_combinations_from_value_counts(values, counts, r) def tryAndFit(container, boxes): lenBoxes = len(boxes) width = container[0] height = container[1] contArea = width * height if lenBoxes > contArea: retu...
The function `rec` generates all valid combinations of nested boxes based on their sizes and quantities, avoiding redundant computations. It uses recursion to explore configurations where boxes fit inside each other, tracking used combinations globally. Key steps include sorting box data, selecting the box with the few...
def rec(allBoxes: dict, emptyBoxes:dict, fitInside: dict): global usedThiscombo tupleCreationAllBoxes = [] for i in allBoxes: tupleCreationAllBoxes.append((i[0], i[1], allBoxes[i])) tupleCreationAllBoxes.sort() tupleCreationEmptyBoxes = [] for i in emptyBoxes: tupleCreationEmptyBoxes.append((i[0], i[1], emp...
def update_scores(self, new_score: float): # adding to the last scores self.last_5 = self.last_5[:4] self.last_5 = [round(new_score, 2)] + self.last_5 # adding to the best scores self.best_5.append(round(new_score, 2)) self.best_5.sort(reverse=False) self.best_5 =...
The main task of the code is to continuously update scores with random values, detect false start conditions, and maintain the GUI interface by resetting when a false start occurs, while looping indefinitely with periodic updates.
def mainloop(self): i = 1 x = True while True: self.update_scores(randint(580, 9999) / 100) if x: if self.false_start(): x = False self.reset() self.tk.update() i += 1
def init_weights(self): np.random.seed(777) for index, layer in enumerate(self.layers[:-1]): self.weights[index] = np.random.randn(self.layers[index], self.layers[index + 1]) def init_biases(self): np.random.seed(42) for index, layer in enumerate(self.layers[:-1]): ...
This code trains a neural network model by iterating through the training data, performing forward propagation to compute predictions and loss, then using backpropagation to update model weights and biases. The loss values are recorded during each iteration to monitor training progress.
def fit(self, train_set, train_labels): self.train_set = train_set self.train_labels = train_labels self.init_weights() self.init_biases() for iteration in range(self.iterations): prediction, loss = self.forward_propagation() self.backward_propagation(pre...
def len_bets(auction_id): tot = client.llen(f'Auction_{auction_id}') return tot def last_bet(auction_id): last_price = client.lindex(f'Auction_{auction_id}', -1,) return last_price def last_user(auction_id): list_user = client.lindex(f'User_in_{auction_id}', -1) return list_user def send_on_chai...
The function determines the winner of an auction by updating the auction's total bets, closing price, and winner. It adjusts the winner's profile (incrementing wins and deducting the closing price from their wallet), processes a blockchain transaction, deactivates the user if their wallet balance goes negative, and sen...
def check_winner(request, id_auction): auction = Auction.objects.get(id=id_auction) auction.total_bet = len_bets(id_auction) auction.close_price = last_bet(id_auction) auction.winner = last_user(id_auction) auction.save() prof_user = Profile.objects.get(username=auction.winner) prof_user.win...
def _process_user_event(self, event_data): return self._retry_with_exponential_backoff(self.gitlab_client.users.get, event_data["user_id"]) def _process_project_event(self, event_data): return self._retry_with_exponential_backoff(self.gitlab_client.projects.get, event_data["project_id"]) def _process_is...
This code processes incoming GitLab events by determining their type, converting event data into corresponding GitLab objects via specialized methods, incrementing a counter for tracked events, and pushing processed objects to a "retrieval" queue for further handling. It handles multiple event types (users, projects, i...
def process_event(self, event_type, event_data): with self.event_processing_time.time(): try: # Determine how to retrieve data based on event type if event_type in [e.value for e in UserEvent]: gitlab_object = self._process_user_event(event_data) ...
def read_text(self): """ Reads the text from a text file. """ with open(self.filename, "rb") as f: self.text = f.read() return self.text def split_into_sentences(self): """ Split sentences on .?! "" and not on abbreviations of titles. """ ...
This code processes text from a file by reading, splitting into sentences, applying word replacements, augmenting the text, and writing the modified content. The main task is text augmentation through replacement and transformation, likely for data preprocessing or NLP tasks.
def __init__(self, filename): self.filename = filename self.text = "" self.split_text = [] self.swapped_text = [] self.augmented_text = [] self.replacers = {} self.read_text() self.split_into_sentences() self.create_replacers() self.replace...
def read_text(self): """ Reads the text from a text file. """ with open(self.filename, "rb") as f: self.text = f.read() return self.text def split_into_sentences(self): """ Split sentences on .?! "" and not on abbreviations of titles. """ ...
The code initializes a class to process a text file by reading its content, splitting it into sentences, identifying names and pronouns, replacing them with alternative forms (opposite, they, she, he), and writing the modified versions. It handles name and pronoun substitutions to generate text variations, likely for a...
def __init__(self, filename): self.filename = filename self.is_mixed = False self.text = "" self.split_text = [] self.opposite_names = {} self.they_names = {} self.she_names = {} self.he_names = {} self.opposite_name_swapped_text = [] self....
def archetypes(): """Return the 'archetypes' part of the Cyclus input file as a dict.""" archetypes_by_library = { "agents": ["NullRegion"], "cycamore": [ "DeployInst", "Reactor", "Separations", "Sink", "Source", "Storage", ...
The main task of the code is to generate a Cyclus input file by configuring reactor parameters, validating settings, and assembling simulation components like archetypes, facilities, and regions into a structured dictionary. It updates reactor-specific attributes, enforces constraints (e.g., global capacity factor), an...
def simulation(name="Pakistan", parameters=None): """Generate and save a Cyclus input file.""" if parameters is not None: PARAMS.update(parameters) PARAMS.update(name=name) if PARAMS["global_capacity_factor"] is not None: for i in range(1, 5): key = f"khushab{i}_capacity_fact...
def forward_prop(self, X): """Calculate forward propagation of the neural network""" self.__cache['A0'] = X A = X for l in range(1, self.__L + 1): Z = np.dot(self.__weights['W' + str(l)], A) + self.__weights[ 'b' + str(l)] A = self.sigmoid(Z) ...
The code trains a neural network by performing gradient descent over a specified number of iterations, validating input parameters, and iteratively updating the model's weights using forward propagation and gradient descent. It returns the model's evaluation on the training data after training.
def train(self, X, Y, iterations=5000, alpha=0.05): """Trains the neural network""" if not isinstance(iterations, int): raise TypeError("iterations must be an integer") if iterations < 1: raise ValueError("iterations must be a positive integer") if not isinstance(...
def forward_prop(self, X): """Calculate the forward propagation of the neural network""" Z1 = np.dot(self.W1, X) + self.b1 self.__A1 = self.sigmoid(Z1) Z2 = np.dot(self.W2, self.__A1) + self.b2 self.__A2 = self.sigmoid(Z2) return self.__A1, self.__A2 def gradient_descent(...
The code trains a neural network using gradient descent by iterating over data, validating inputs, performing forward propagation, updating weights, tracking costs, and optionally printing progress or plotting cost curves. It returns the model's evaluation on the training data.
def train(self, X, Y, iterations=5000, alpha=0.05, verbose=True, graph=True, step=100): """Train the neural network with options for verbose output and graphing""" if not isinstance(iterations, int): raise TypeError("iterations must be an integer") if iterations < 1: rais...
def DarknetConv2D_BN_Leaky(*args, **kwargs): """Darknet Convolution2D followed by BatchNormalization and LeakyReLU.""" no_bias_kwargs = {'use_bias': False} no_bias_kwargs.update(kwargs) return compose( DarknetConv2D(*args, **no_bias_kwargs), BatchNormalization(), LeakyReLU(alpha=...
The code constructs the initial 18 convolutional layers of the Darknet-19 neural network, used in YOLO object detection models. It sequentially applies DarknetConv2D_BN_Leaky layers, max-pooling, and bottleneck blocks with increasing filter sizes to extract hierarchical features from input images.
def darknet_body(): """Generate first 18 conv layers of Darknet-19.""" return compose( DarknetConv2D_BN_Leaky(32, (3, 3)), MaxPooling2D(), DarknetConv2D_BN_Leaky(64, (3, 3)), MaxPooling2D(), bottleneck_block(128, 64), MaxPooling2D(), bottleneck_block(256, ...
def create_buttons(self): self.create_canvas() self.main_title = tk.Message(text="The monitor 9000", bg="#3E3432", fg="blue") self.watchlist_btn = tk.Button(self.gridroot, text='Program watchlist', bg='#3E3432', fg='#FB6F14', command=lambda: [self.monitor_apps...
This code initializes a GUI application for monitoring and tracking user activity, including application and website usage times. It sets up the window, UI elements, data structures for storing process and site information, and initializes variables to accumulate and track total usage times for applications and website...
def __init__(self, width, height): self.gridroot = tk.Tk() self.height = height self.width = width self.lb_font = tkFont.Font(family="Helvetica", size=10, weight="bold") self.process_list = [] self.a_process_list = {} self.a_page_list = {} self.tab_list = ...
def backward_prop(inp, y, w1, w2, b1, b2, lr): dic = forward_prop(inp, w1, w2, b1, b2) dz2 = y - dic['a2'] dw2 = np.dot(dic['a1'],dz2.T) db2 = dz2 dz1 = np.dot(w2,dz2)*(dic['a1']>0) dw1 = np.dot(inp,dz1.T) db1 = dz1 w1 -= lr*dw1 w2 -= lr*dw2 b1 -= lr*db1 b2 -= lr*db2 retu...
The code trains a neural network using backpropagation over multiple epochs. It initializes weights and biases, iterates through data, computes errors, updates parameters via backward propagation, and returns the final trained weights and biases.
def training(x, y, num_epochs, lr): w1 = np.random.randn(3,5) w2 = np.random.randn(5,2) b1 = np.random.randn(5,1) b2 = np.random.randn(2,1) for _ in range(num_epochs): err = 0 for i in range(len(x)): (w1, w2, w3, b1, b2, b3) = backward_prop(np.reshape(x[i].T,(3,1)), y[i],...
def backward_prop(inp, y, w1, w2, b1, b2, w1_prev, w2_prev, b1_prev, b2_prev, n_p, lr, alpha): dic = forward_prop(inp, w1, w2, b1, b2) a1 = dic['a1'] a2 = dic['a2'] dz2 = 2*a2*(1-a2)*(a2-y)/n_p dw2 = np.dot(a1,dz2.T) db2 = dz2 dz1 = w2*dz2*a1*(1-a1) dw1 = np.dot(inp,dz1.T) db1 = dz1 ...
The code trains a neural network with one hidden layer using backpropagation and gradient descent. It initializes weights and biases, iterates over epochs, processes input data in a sliding window, updates parameters via backward propagation, computes mean squared error (MSE), and returns the trained weights and biases...
def training(x, num_epochs, n_p, n1, lr, alpha): w1 = np.random.randn(n_p, n1) w2 = np.random.randn(n1,1) b1 = np.random.randn(n1,1) b2 = np.random.randn(1,1) w1_prev = w1 w2_prev = w2 b1_prev = b1 b2_prev = b2 for _ in range(num_epochs): mse = 0 for i in range(n_p, l...
def forward_prop(inp, w1, w2, w3, b1, b2, b3): a1 = sigmoid(np.dot(w1, inp) + b1) a2 = sigmoid(np.dot(w2, a1) + b2) a3 = sigmoid(np.dot(w3, a2) + b3) return {'a1': a1, 'a2': a2, 'a3': a3} def cost(y, a): return (- np.dot(y.T, np.log(a)) - np.dot((1-y).T, np.log(1-a))) def backward_prop(inp, w1, w2, ...
The code implements gradient descent optimization for a neural network with three layers. It iterates over a specified number of epochs, performing forward propagation to compute predictions, calculating the cost, and using backward propagation to obtain gradients. The weights and biases are updated by subtracting the ...
def gradient_descent(inp, w1, w2, w3, b1, b2, b3, y, lr, num_ep): for _ in range(num_ep): a = forward_prop(inp, w1, w2, w3, b1, b2, b3)['a3'] c = cost(y, a) dic = backward_prop(inp, w1, w2, w3, b1, b2, b3, y) w1 -= lr*dic['dw1'] w2 -= lr*dic['dw2'] w3 -= lr*dic['dw3']...
def expv(v,n): d = v.shape[0] dim = (d**(n+1)-1)//(d-1) e = np.zeros(dim) for k in range(0,n+1): e = powerv(v,e,k,d) return e def prodsig(ev0,ev1,d,n): dim = (d**(n+1)-1)//(d-1) e = np.zeros(dim) for k in range(n+1): e = chen(e,ev0,ev1,k,d) return e def adj_expv(v_ad,...
This function computes the adjoint of a sequence of exponential and product signature operations. It first processes input vectors to generate intermediate values (Ss, evs), then computes the adjoint in reverse order using stored intermediates, updating the adjoint vector (v_ad) through adj_expv and adj_prodsig operati...
def adj_tosig(S_ad,v,n): d = v.shape[1] m = v.shape[0] Ss = np.zeros((m,S_ad.shape[0])) evs = np.zeros_like(Ss) v_ad = np.zeros_like(v) #restore intermediate values for j in range(m): if j==0: S = expv(v[j,:],n) else: ev = expv(v[j,:],n) e...
def logsig(x,d,n): #Logarithm of graded Tensor xm1 = x.copy(); xm1[0] = 0.0 logx = np.zeros_like(x) logxt = np.zeros_like(x); logxt[0] = -1.0 for i in range(1,n+1): logxt = prodsig(logxt,-xm1,d,n) logx += logxt/i return logx def expsig(x,d,n): #Exponential of graded Tensor expxt = np.zeros_li...
This function computes an iterative group mean of paths using logarithmic and exponential signatures. It initializes a first guess from path signatures, then refines it through multiple iterations by inverting the current mean, combining it with each path's signature, and updating the mean using the exponential of the ...
def group_mean(g,d,n,npath,ntr): sigdim = (d**(n+1)-1)//(d-1) #firstguess logp = np.zeros((sigdim,npath)) for jp in range(npath): logp[:,jp] = logsig(g[:,jp],d,n) gm = expsig(np.mean(logp,axis=1),d,n) #iterations for itr in range(ntr): gm_i = invsig(gm,d,n) for jp in range(npath): logp[:...
def tosig(v,n): d = v.shape[1] m = v.shape[0] for j in range(m): if j==0: S = expv(v[j,:],n) else: ev = expv(v[j,:],n) S = prodsig(S,ev,d,n) #signature return S def adj_homogenous_norm(norm_ad,S_ad,S,d,n): Sk_ad = 0.0 fn = 1 eps = sys.float_inf...
The function computes the adjoint of a cost function with respect to input variables using signature and norm operations, updating gradients through forward and backward passes involving reshaping, linear transformations, and specialized norm functions. It returns the flattened adjoint gradient vector for optimization.
def adj_cost(u,sigma,vi,Ss,n,m,d): sigdim = Ss.shape[0] u = np.reshape(u,(m,d)) u_ad = np.zeros_like(u) v = np.zeros_like(vi) S_ad = np.zeros(sigdim) for j in range(m): v[j,:] = u[j,:]*sigma[:]+vi[j,:] Jo_ad = 0.0 J_ad = 1.0 S = tosig(v,n) u_ad += J_ad*u Jo_ad += ...
def _find_necessary_columns(self): # TODO: Can try to remove columns that are only used in the # intermediate large_entity_frames from self.necessary_columns # TODO: Can try to only keep Id/Index/DatetimeTimeIndex if actually # used for features self.necessary_columns = defaultdi...
This code initializes a feature dependency graph by mapping features to their dependencies and dependents, organizing features into a structured format for processing. It processes input features, tracks dependencies, and prepares entities and feature groups for ordered computation, ensuring necessary data columns are ...
def __init__(self, entityset, features, ignored=None): self.entityset = entityset self.target_eid = features[0].entity.id if ignored is None: self.ignored = set([]) else: self.ignored = ignored self.feature_hashes = set([f.hash() for f in features]) ...
def _get_base_entity_id(f): # return f.entity_id if isinstance(f, IdentityFeature): return f.entity_id else: # Assume all of f's base_features belong to the same entity return f.base_features[0].entity_id def _get_ftype_string(f): if isinstance(f, TransformPrimitive): ret...
The code defines a function `key_func` that generates a composite key from multiple attributes of an input object `f`, including hash depth, entity IDs, type information, and processing flags. This key likely serves to uniquely identify or categorize `f` for grouping, sorting, or hashing operations in data processing t...
def key_func(f): return (feature_depth[f.hash()], f.entity.id, _get_base_entity_id(f), _get_ftype_string(f), _get_use_previous(f), _get_where(f), self.input_fra...
def _check_ndk_root_env(): ''' Checking the environment ANDROID_NDK, which will be used for building ''' try: ANDROID_NDK = None sdkRoot = os.environ.get('ANDROID_HOME', None) for _, ndkVers, _ in os.walk("{0}{1}ndk".format(sdkRoot, os.path.sep)): for ndkVer in ndkVers...
The main task of the code is to configure NDK and toolchain paths, generate a configuration file (userconf.ini) with project settings, set platform-specific environment variables, and execute Lua binding generation using tolua for multiple modules. It validates the NDK root, detects the OS, locates the LLVM toolchain, ...
def main(): global g_ndk_root cur_platform= '??' llvm_path = '??' if (g_ndk_root == None or not os.path.isdir(g_ndk_root)): g_ndk_root = _check_ndk_root_env() if not os.path.isdir(g_ndk_root): print("The ndk-r23c root not specified, please specifiy via --ndk_root '/path/to/ndk'") ...
def rel_to_abs(start_point,point_list): """ Converts a list of points points from relative to absolute coordinates Args: start_point: list of two floats representing the x and y coordinates of the next command will start at point_list: a list of floats in the form [x1,y1,x2,y2,...
This function converts SVG path commands (like M, C, L, H, V, Z) into G-code for 3D printing. It processes each command to generate coordinates, handles relative/absolute positioning, and writes toolpath data to a file using helper functions. The 'Z' command closes paths by linking back to the initial curve start point...
def svg_commands_to_gcode(filename,start_point,path_commands,scalers,draw_height=0): """ This function takes a list of svg commands with different key letters and converts those equations into points which it writes to Gcode. filename: a string representing the name of the file to write to ...
def test(model, testLoader, topk=(1,)): model.eval() losses = utils.AverageMeter() accuracy = utils.AverageMeter() top5_accuracy = utils.AverageMeter() start_time = time.time() #testLoader = get_data_set('test') #i = 0 with torch.no_grad(): for batch_idx, batch_data in enumerat...
The code's main task is to train and optimize deep learning models (VGG/ResNet) using either standard training or a bee-inspired pruning algorithm (BeePruning) to enhance accuracy. It handles model initialization, checkpoint resuming, distributed training, and optimization with SGD. The BeePruning component uses swarm ...
def main(): start_epoch = 0 best_acc = 0.0 best_acc_top1 = 0.0 code = [] if args.from_scratch: print('==> Building Model..') if args.arch == 'vgg': model = import_module(f'model.{args.arch}').VGG(num_classes=1000).to(device) elif args.arch == 'resnet': ...
def test(model, testLoader): global best_acc model.eval() losses = utils.AverageMeter() accurary = utils.AverageMeter() start_time = time.time() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(testLoader): inputs, targets = inputs.to(device), targets.to...
The code implements a BeePruning algorithm for neural network pruning using a bee colony optimization approach. It initializes model training, performs iterative pruning cycles (employing employed bees, onlooker bees, and scout bees), builds a model based on the best pruned configuration, trains it with SGD optimizer, ...
def main(): start_epoch = 0 best_acc = 0.0 code = [] if args.resume == None: test(origin_model, loader.testLoader) if args.best_honey == None: start_time = time.time() bee_start_time = time.time() print('==> Start BeeP...
def count_filled(board): count = 0 for i in range(size_of_board): if board[i]!=0: count+=1 return count def RandomizingGlobally(board1): index = random.randint(0, 80) return index def JumpingOneCell(index): if index<0: return 0 if (index//total_numbers)%2==0: ...
This code generates a partially filled Sudoku board based on specified difficulty levels by iteratively removing numbers while maintaining solvability and constraint requirements, using different algorithms for number removal depending on the difficulty, and ensuring the board meets minimum and maximum filled cell thre...
def digging(board, difficulty): start = time.time() level = levels[difficulty] # print(level) min_filled, maxfilled = level[0], level[1] min_RC = level[2] count = 0 filled = random.randint(min_filled,maxfilled) possible_dig = [True for _ in range(size_of_board)] count_available = siz...
def drawTitle(app, canvas): ##Draws the Game title canvas.create_text(app.width/2, app.height*0.07, text = "One-Dimensional Connect Four!", font = 'Arial 30 bold') def drawInstructions(app, canvas): yIncrement = 0.036*app.height count = 0 messages = ['See...
The main task of the code is to redraw all game elements on the canvas, including the title, instructions, current player, messages, game board, rules, selection (if applicable), and game-over status, to reflect the current state of the application in a graphical interface.
def redrawAll(app, canvas): drawTitle(app, canvas) drawInstructions(app, canvas) drawCurrentPlayer(app, canvas) drawCurrentMessage(app, canvas) drawBoard(app, canvas) drawRules(app, canvas) if app.selection != []: ##prevent out of index error drawSelection(app, canvas) drawGameOv...
def appStarted(app): (app.rows, app.cols, app.cellWidth, app.margin) = gameDimensions() app.emptyColor = 'blue' app.board = createBoard(app, app.rows, app.cols, app.emptyColor) app.tetrisPieces = tetrisPieces(app) app.tetrisPieceColors = (["red","yellow","magenta","pink", ...
This code handles keyboard input for a game, restarting on 'r', rotating the falling piece on 'Up', hard dropping it with 'Space', moving it down with 'Down', and left/right with 'Left'/'Right', while preventing actions if the game is over.
def keyPressed(app, event): if event.key == 'r': appStarted(app) if app.gameOver: return if event.key == 'Up': rotateFallingPiece(app) if event.key == 'Space': ## hard drop the piece num = howFarDrop(app) if app.frow < num: moveFallingPiece(app, num-app.fro...
def assign_id(assigned_ids, id_count, orig_doc_id, sentence): key = orig_doc_id + '_' + sentence.strip() if key not in assigned_ids: if orig_doc_id not in id_count: id_count[orig_doc_id] = 0 assigned_ids[key] = orig_doc_id + '_' + str(id_count[orig_doc_id]) id_count[orig_do...
The code processes medical text lines to extract entities (adverse events, drugs) and their relations. It assigns unique document IDs, parses sentences with spaCy, and structures tokens, entities, and relations into ordered dictionaries. Final output is a list of processed documents with tokens, entities, relations, an...
def read_docs(lines, nlp): documents = OrderedDict() entities, relations = dict(), dict() assigned_ids, id_count = dict(), dict() for line in tqdm(lines): parts = line.split('|') sentence = parts[1] doc_id = assign_id(assigned_ids, id_count, parts[0], sentence) ae_text...
def _get_all_latest_healthy_submissions() -> List[Tuple[Submission, float]]: """Gets a list of submissions along with their healths from 1 to 0. Submissions with health 0 are omitted as they should not be run""" with cuwais.database.create_session() as database_session: healthy_subq = database_sessi...
The function `_run_typical_match` selects a specified number of submissions based on their "health" scores, normalizes these scores to determine probabilistic selection, runs a match using the selected submissions, and saves the results while updating scores if any submission was healthy. It returns `True` on success o...
def _run_typical_match(gamemode: Gamemode, options) -> bool: logger.debug("Starting typical match") # Get n sumbissions submissions = [] if gamemode.player_count > 0: newest = _get_all_latest_healthy_submissions() if len(newest) < gamemode.player_count: return False ...
def _get_all_untested_submissions() -> List[Submission]: logger.debug(f"Getting untested submissions") with cuwais.database.create_session() as database_session: logger.debug(f"Got session") # All submissions with no results res = database_session.query(Submission)\ .outerjoi...
The function `_run_test_match` executes a test match using a specified game mode and options. It retrieves untested submissions, runs the match with randomized submissions for each player, logs results, and records outcomes. If no submissions exist, it returns `False`; otherwise, it returns `True` after processing.
def _run_test_match(gamemode: Gamemode, options) -> bool: logger.debug("Starting test match") # Get n sumbissions submissions = [] if gamemode.player_count > 0: newest = _get_all_untested_submissions() if len(newest) == 0: return False submissions = [random.choice(ne...
def get_song_features(playlist_id): playlist = sp.user_playlist_tracks("spotify", playlist_id) playlist_tracks = [item['track'] for item in playlist['items']] audio_features_all_songs = [(track['name'], sp.audio_features(track['uri'])[0]) for track in playlist_tracks] filtered_audio_features = [] for song in audi...
This function identifies the song in a specified playlist most similar to a given average song vector by comparing audio feature vectors. It iterates through each track, calculates the difference between its vector and the average vector, and tracks the smallest difference. The result is the track with the closest matc...
def most_similar_song_in_playlist(playlist_id, avg_song_vector): tracks_in_playlist = get_song_features(playlist_id) min_difference, min_track = None, None for track in tracks_in_playlist: track_audio_vector = audio_features_to_vector(track[1]) err = compare_vectors(track_audio_vector, avg_song_vector) if ...
def check_all_plane_threats(grid,opponent_symbol): """ input grid data, opponent symbol return [boo,cordinate] true if threat, coordinate block move """ outside_diag1 = [[[0,1,0],[0,2,0],[3,1,3],[3,2,3]],[[1,0,1],[1,3,1],[2,1,2],[2,2,2]]] center_diag1 = [[1,1,1],[1,2,1],[2,1,2],[2,2,2]] ...
The function determines the bot's optimal move in a 3D tic-tac-toe game by prioritizing: 1) Blocking opponent's immediate threats (3-in-line, 2-in-line, or plane threats), 2) Creating its own winning opportunities (3-in-line, 2-in-line setups, or dual-threat positions), and 3) Playing a random move if no threats exist....
def bot_decide_move(grid,bot_symbol,opponent_symbol): """ return best bot_move""" cube_data = cube.get_cube_data(grid,bot_symbol) #collect data for lines threat3 = check_all_plane_threats(grid,opponent_symbol) #center of plane if threat3[0]:#also potentional threat print(bot_symbol, " move...
def make_connected(data): connected = [] for mol in data.Drug.tolist(): if '.' in mol: new_mol = mol.split('.') lens = [len(i) for i in new_mol] actual = max(lens) corrected_mol = new_mol[lens.index(actual)] connected.append(corrected_mol) ...
The function converts SMILES-based molecular data into PyTorch Geometric (PyG) datasets for graph-based machine learning. It fills missing values with -1, ensures data connectivity, limits examples in dev mode, transforms SMILES strings to PyG graphs, assigns labels, and saves train/valid/test sets. The core task is pr...
def gen_pyg_dataset(args, train_data, valid_data, test_data) -> tuple: train_data = train_data.fillna(-1) valid_data = valid_data.fillna(-1) test_data = test_data.fillna(-1) train_data = make_connected(train_data) valid_data = make_connected(valid_data) test_data = make_connected(test_data) ...
def format(args, group, label, train_data, valid_data, test_data) -> tuple: # Some groups have multiple labels if label: if args.prop_source == 'Tox': data = Tox(name = group, label_name = label) elif args.prop_source == 'ADME': data = ADME(name = group, label_name = lab...
The function `load_data` primarily loads and preprocesses datasets for machine learning tasks, returning PyTorch Geometric datasets. It handles different data sources: (1) For graph datasets like PROTEINS, it splits a TUDataset into train/valid/test. (2) For other cases, it either loads preprocessed data from files or ...
def load_data(args, train=None, valid=None, test=None) -> torch.utils.data.Dataset: if args.group_name in ['PROTEINS', 'ENZYMES', 'MUTAG']: path = './data/{}'.format(args.group_name) dataset = TUDataset(path, name=args.group_name).shuffle() n = (len(dataset) + 9) // 10 test_data = d...
def _get_string_until_char_and_stack(self, end_char, stack): substring = self._get_compressed_substring(end_char) if substring: logging.debug(f"The substring is {substring}") stack.put(substring) return True return False def _add_node_to_graph(self, is_substri...
This code parses a complex string by processing substrings, using stacks for numbers/characters, and recursively building a graph structure. It identifies sections bounded by '[' or '!', extracts them, adds nodes to a graph, and continues parsing the remaining string, adjusting behavior based on substring status and st...
def parse_comp_string(self, is_substring=False): if self.string_index == len(self.comp_string): return else: search_res = re.search(r'\[', self.comp_string[self.string_index:]) end_char = '[' if search_res else '!' stack = self.number_stack if search_res e...
def load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 real_image = image[:, :w, :] input_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) r...
The main task of the code is to preprocess training images by applying random jittering and normalization to both input and real images, preparing them for machine learning model training.
def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image
def arrow_to_sqlserver(reader: pa.RecordBatchReader, target_table_name: str, uri: str) -> None: arrow_schema_to_mssql_table(reader.schema, target_table_name, uri) arrow_data_to_mssql_table(reader, uri, target_table_name) def arrow_to_postgres(reader: pa.RecordBatchReader, target_table_name: str, uri: str) -> No...
This function ingests data from a pyarrow RecordBatchReader into a database, routing the data to the appropriate database handler based on the connection type (SQL Server, PostgreSQL, Snowflake). It uses the specified table name and connection URI to write the Arrow data to the target database, defaulting to SQL Server...
def ingest_arrow_reader(self, reader: pa.RecordBatchReader) -> None: if self.connection_type == "sqlserver": arrow_to_sqlserver(reader, self.table.full_name, self.connection_uri) elif self.connection_type == "postgresql": arrow_to_postgres(reader, self.table.full_name, self.conne...
def NPCDistance(self): if self.game._player.mapPos == self.mapPos: return True wallDistanceVertical, wallDistanceHorizontal = 0,0 playerDistanceVertical, playerDistanceHorizontal = 0,0 oX,oY = self.game._player.pos xMap, yMap = self.game._player.mapPos rayAng...
This code manages an NPC's behavior based on its state. If alive, it checks for obstructions, handles pain animations, moves when unobstructed, attacks within range, or idles. If dead, it plays a death animation by rotating sprites. Key tasks include animation triggers, movement logic, attack detection, and state trans...
def NPCBehavior(self): if self._alive == True: self._ObstructCheck = self.NPCDistance() self.NPCHitDectection() if self._pain == True: #animate #self.NPCDamageReceiveAnimation() self.animate(self._painSprite) if self.animationTr...
def get_latest_github_release(owner: str, repository: str) -> GithubRelease: uri = f"https://api.github.com/repos/{owner}/{repository}/releases/latest" response = requests.get(uri) response.raise_for_status() return GithubRelease.parse_raw(response.text) def compute_ccn_scores( ccn_metrics: Collect...
The function computes and returns CCN and CRN scores for a node by retrieving the latest GitHub releases of "pyaleph" and "aleph-vm", then calculating scores using node metrics and release data. It combines these into a NodeScores object for output.
def compute_scores(node_metrics: NodeMetrics) -> NodeScores: latest_ccn_release = get_latest_github_release("aleph-im", "pyaleph") latest_crn_release = get_latest_github_release("aleph-im", "aleph-vm") ccn_scores = compute_ccn_scores(node_metrics.ccn, latest_ccn_release) crn_scores = compute_crn_scores...
def gpt_call(self) -> dict: """ Will call gpt-3.5-turbo for querying informations about a company. Args: name(str): Name of the company country(str): Country of the company website(str): Website of the company Results: output(dict) = Pars...
The main task of the code is to perform a GPT search, extract product/service information, generate a Google query from the results, execute a Google image search, and combine the outputs into a structured response containing both parsed GPT data and retrieved images.
def main(self): """ Will do the innoscripta querying """ logger.info("Doing GPT search...") parsed_gpt_ouput = self.gpt_call() logger.info("Doing Google search...") google_query = self.google_query_formation( parsed_gpt_ouput["products_services"] ...
def CBC_controller(X): global A global b global St global count global SEL if (count == 0): u = -(St[0] / St[1]) * X # Robust controller SEL = np.append(SEL, [[St[0]], [St[1]]], axis=1) # Store the new alpha_t,beta_t # Remember we have alpha*=1.5*Ts+1, beta*=Ts ...
The function `play_dynamics` computes the system's state derivative using a control input `u` generated by the `CBC_controller`. It stores the control input, current state `X`, and computed derivative in global arrays (`U`, `S`, `Dot_X`) for simulation or analysis, up to a predefined limit `N`. The returned value repre...
def play_dynamics(X): global count global last_u #u=u_nominal(X) u=CBC_controller(X) if (count < N): U[count]=u S[count]=X Dot_X[count]=f(X)+theta_star*F(X)+np.dot(g(X),u) count=count+1 return (f(X)+theta_star*F(X)+np.dot(g(X),u))
def aggregate_raw_data(user_raw_data_consumption_map, agg_mode, billing_cycle_list, is_billing_end_date_inclusive): aggregated_data = [] if agg_mode == "DAY": aggregated_data = aggregate_raw_data_on_day(user_raw_data_consumption_map) elif agg_mode == "MONTH": aggregated_data = aggregate_raw...
The function generates user billing records by aggregating raw consumption data into billing cycles, calculating costs using a given rate, and writing the structured billing data to a file. It processes input configurations, computes duration and cost per cycle, populates dummy records with dynamic values, and appends ...
def create_billing_data_for_a_user(billing_data_configs, user_raw_data_consumption_map, billing_cycle_list, rate, id): file_write_mode = "a" billing_data_file_path = billing_data_configs["billing_data_file_path"] dummy_billing_data_record = billing_data_configs["dummy_billing_data_record"] variable_fie...
def is_solar_user(uuid): # getting user details api response using USER_DETAILS_API in json format api_data = api_call(api=USER_DETAILS_API.format(uuid=uuid), method='GET', params=PARAMS, data="")["payload"][ "homeAccounts"] is_solar = api_data["hasSolar"] # populating solar data into JSON_REPOR...
The function processes a subset of UUIDs by fetching and storing user data (solar status, rate info, billing cycles, seasons, days in cycles, billing/disagg/survey data) into a JSON report. Each UUID undergoes multiple data retrieval steps with error handling, logging exceptions and progress. Results are stored in JSON...
def thread_target_function(uuid_list, start, end): for uuid in uuid_list[start:end + 1]: try: # initializing JSON_REPORT for current uuid JSON_REPORT[uuid] = {} print("checking user:", uuid, " is solar or not") is_solar_user(uuid) print("solar ch...
def decision_tree(training_data, attributes, target_variable): ''' function that recursively builds the decision tree for the given training data :param training_data: the data on which the decision tree is built :param attributes: the attributes in the training data :param target_variable: list of ...
The main task of the code is to train a decision tree classifier on training data from a CSV file, construct the tree structure, and generate a Python script that applies the trained decision tree to test data. The script writes classifications to a CSV file using preorder traversal to encode the tree's if-else logic.
def main(): # getting the training data from the CSV file data = np.genfromtxt("HW_05C_DecTree_TRAINING__v540.csv", delimiter=",", dtype="unicode") # separating the attributes from the rest of the data attributes = data[0] attributes = attributes[:len(attributes) - 1] # separating the trainin...
def send_information(self, info_bytes): # send flag self.send_single_byte(self.START_FLAG) # send info bytes for info_byte in info_bytes: self.send_single_byte_with_stuffing(info_byte) # Get the crc as the fcs field crc1, crc0 = self.crc16_ccitt(info_bytes)...
This function sends a packet to a lamp, handles CRC mismatches, and retries up to a maximum number of attempts. It checks received packets for validity, including CRC integrity and control byte status, and returns data bytes on success or None on errors. If CRC mismatches occur, it retransmits the packet. It also handl...
def send_packet_with_response(self, send_bytes, attempt=1, crc_mismatch=False): if attempt == self.max_attempts: print("Max attempts reached. Lamp command dropped") return None if not crc_mismatch: self.send_information([self.HDLC_L_CLEAR] + send_bytes) else...
def import_data(pth): ''' returns dataframe for the csv found at pth input: pth: a path to the csv output: data_df: pandas dataframe ''' return pd.read_csv(pth) def add_churn_col(data_df): """ Compute and add Churn data to the given dataframe. input: data_d...
The main task of the code is to predict customer churn by loading bank data, adding a churn column, performing exploratory data analysis (EDA), splitting data into training/test sets via feature engineering, and training predictive models to identify customers likely to leave the bank.
def main(): """Run churn prediction""" data_df = import_data('data/bank_data.csv') data_df = add_churn_col(data_df) perform_eda(data_df) x_train, x_test, y_train, y_test = perform_feature_engineering(data_df) train_models(x_train, x_test, y_train, y_test)
def display_board(board): """ Display 3x3 board where index of each cell corresponds with a number on a keypad as follows:\n |7|8|9|\n |4|5|6|\n |1|2|3| :param board: list of 10 elements where the element at position 0 is not used :return: """ clear() print('-' * 13) print(f'...
This function handles a single turn in a tic-tac-toe game by displaying the board, allowing a player to choose a position, placing their marker, checking for a win or tie, and switching players if the game continues. It returns the next player's number and the updated game status (continued or ended).
def play_turn(board, player_marker, player_num, game_on): # Show the board display_board(board) # Chose a position position = player_choice(board, player_num, player_marker) # Place the marker on the board place_marker(board, player_marker, position) # Check if they won if win_check(boa...
def display_board(board): """ Display 3x3 board where index of each cell corresponds with a number on a keypad as follows:\n |7|8|9|\n |4|5|6|\n |1|2|3| :param board: list of 10 elements where the element at position 0 is not used :return: """ clear() print('-' * 13) print(f'...
The code implements a two-player Tic Tac Toe game. It initializes the game board, lets players choose markers (X/O), determines the first player, and alternates turns. The game loop handles player moves, checks game status, and ends when a player wins or the board is full. After each game, it asks if players want to re...
def main(): print('Welcome to Tic Tac Toe!') while True: # Play the game board = [' '] * 10 display_board(board) player1_marker, player2_marker = player_input() print(f'PLAYER-1 marker: {player1_marker}, PLAYER-2 marker: {player2_marker}') player_num = choose_fi...
def getQueueFiles(taskQueueName): qFiles = [] fs = os.listdir(taskQueueName) for f in fs: isQueuefile = re.search(r"\w+.queue$", f) if isQueuefile: isQueuefile = isQueuefile.group() # timestamp_pid.queue qFiles.append( f ) return qFiles def getPythonPids(show=Fa...
The function `clearDeadProcQFile` identifies and deletes queue files associated with non-running processes. It retrieves files for a given task queue, checks active Python process IDs, and removes any queue file whose process ID is no longer active, ensuring cleanup of orphaned or terminated process-related files.
def clearDeadProcQFile(taskQueueName): # get taskQueueName forder files qFiles = getQueueFiles(taskQueueName) # get tasklist pids taskPids = getPythonPids(show=False) logger.debug(f"taskPids: {taskPids}") # clear qfile if it not exist in tasklist for qfile in qFiles: logger.debug(q...
def getQueueFiles(taskQueueName): qFiles = [] fs = os.listdir(taskQueueName) for f in fs: isQueuefile = re.search(r"\w+.queue$", f) if isQueuefile: isQueuefile = isQueuefile.group() # timestamp_pid.queue qFiles.append( f ) return qFiles def getPythonPids(show=Fa...
The main task of the code is to identify active task queue files by checking if their associated processes are running. It retrieves queue files, compares their PIDs with running Python processes, retains valid ones, deletes dead files, and returns a sorted list of active queue files.
def readTaskQueue(queueName): logger.info(f"read real task queue from {queueName}") # get real queue file by comparing with tasklist realQueue = [] qFiles = getQueueFiles(queueName) # get python proc tasklist pids taskPids = getPythonPids(show=False) # compare qfile pid with taskl...
def getQueueFiles(self, queueForder): qFiles = os.listdir(queueForder) qFiles = [f"{queueForder}{os.sep}{q}" for q in qFiles] return qFiles def getPythonPids(self, show=False): # --- get encoding coding = locale.getdefaultlocale()[1].strip() cmd = 'tasklist /SVC /FI "IM...
The main task of the code is to identify active task files in a queue by checking if their associated process IDs (PIDs) are running. It retrieves queue files, compares their PIDs with running Python processes, retains files with active PIDs, deletes others, and returns a sorted list of active task files.
def readTaskQueue(self, queueName): self.logger.info(f"read real task queue from {queueName}") # get real queue file by comparing with tasklist realQueue = [] qFiles = self.getQueueFiles(queueName) # get python proc tasklist pids taskPids = self.getPytho...
def getQueueFiles(self, queueForder): qFiles = os.listdir(queueForder) qFiles = [f"{queueForder}{os.sep}{q}" for q in qFiles] return qFiles def getPythonPids(self, show=False): # --- get encoding coding = locale.getdefaultlocale()[1].strip() cmd = 'tasklist /SVC /FI "IM...
The code identifies and deletes queue files associated with processes no longer running. It retrieves queue files linked to a task queue, checks active Python process IDs, and removes queue files if their associated process ID is not found in the active list, ensuring cleanup of stale entries.
def clearDeadProcQFile(self): # get taskQueueName forder files qFiles = self.getQueueFiles(self.taskQueueName) # get tasklist pids taskPids = self.getPythonPids(show=False) # clear qfile if it not exist in tasklist for qfile in qFiles: qPid = self.getQueuePi...
def clearDeadProcQFile(taskQueueName): # get taskQueueName forder files qFiles = getQueueFiles(taskQueueName) # get tasklist pids taskPids = getPythonPids(show=False) logger.debug(f"taskPids: {taskPids}") # clear qfile if it not exist in tasklist for qfile in qFiles: logger.debug(q...
The main task of the code is to implement a distributed locking mechanism using a queue system. It ensures exclusive access to a resource by creating a unique queue file for the current process, then waiting in order based on the lexicographical position of its queue file in the task queue directory. The process sleeps...
def getPermission(taskQueueName): myPid = os.getpid() logger.info(f'{myPid} try getting {taskQueueName} queue permission..') # create taskQueueName forder if it not exist if not os.path.isdir(taskQueueName): os.mkdir(taskQueueName) logger.debug(f"create {taskQueueName} forder")...
def clearDeadProcQFile(self): # get taskQueueName forder files qFiles = self.getQueueFiles(self.taskQueueName) # get tasklist pids taskPids = self.getPythonPids(show=False) # clear qfile if it not exist in tasklist for qfile in qFiles: qPid = self.getQueuePi...
The main task of the code is to acquire permission to process tasks by ensuring the current process's queue file is first in the task queue order. It creates necessary directories, clears dead processes' files, generates a unique queue file for the current process, and waits in a loop until its queue file reaches the t...
def get(self): self.logger.info(f'{self.pid} try getting {self.taskQueueName} queue permission..') # create taskQueueName forder if it not exist if not os.path.isdir(self.taskQueueName): os.mkdir(self.taskQueueName) self.logger.debug(f"create {self.taskQueueName}...
def insert_movies(session): logging.info("inserting movies ...") data_stream = prepare_data(MOVIE_DATA, Movie.file_mapping) for count, data in enumerate(data_stream, 1): title_data, genres = data title = Movie(**title_data) for g in genres: g_obj = session.query(Genre)....
The main task of the code is to insert movie, character, conversation, and line data into a database using SQLAlchemy, with error handling that rolls back transactions on failure and ensures session closure. It orchestrates data insertion in a structured order, maps conversations to lines, and performs cleanup of recor...
def main(): engine = create_engine(DATABASE_URI) Session = sessionmaker(bind=engine) session = Session() try: insert_movies(session) insert_characters(session) line_to_conv_mapping = insert_conversations(session) insert_lines(session, line_to_conv_mapping) clean_...
def _build_image(requirements_path): if image_cache.has(requirements_path): image = image_cache.get(requirements_path) logger.debug(f"Image was found in cache: {image}") return image nfs_path = upload_local_to_nfs(requirements_path) while True: job_info = client.build_image(n...
The main task of the code is to execute a specified script on a remote system (Christofari) by handling GPU configurations, dependencies, file uploads, and job submission. It validates inputs, builds Docker images if needed, uploads the script and agent code, processes arguments (including S3 paths), and launches the j...
def run(script, args, gpu, image, requirements, root, name, logs): """Run script on Christofari.""" executable = os.path.abspath(script) if not os.path.exists(executable): click.secho(f"File {executable} doesn't exist", bold=True, fg="red") sys.exit(1) # parse gpu n_workers = 1 ...
def print_board_state(bstate): # Function for printing Board print(f" { bstate[0] if bstate[0]!=0 else ' '} | { bstate[1] if bstate[1]!=0 else ' '} | {bstate[2] if bstate[2]!=0 else ' '} ") print(f"---|---|---") print(f" {bstate[3] if bstate[3]!=0 else ' '} | {bstate[4] if bstate[4]!=0 else ' '} | {bstate[...
This code implements a single-player Tic-Tac-Toe game where the user competes against an AI using the Minimax algorithm. The AI selects optimal moves to win or force a tie. The game alternates turns, validates user input, and checks for wins/ties after each move.
def one_player_hard(): # 0 1 2 3 4 5 6 7 8 bstate = [0,0,0,0,0,0,0,0,0] usr_symb = input("Enter your symbor (X or O): ").upper() # To get symbol for user comp_symb = ('X' if usr_symb=='O' else 'O') # assinging Symbol to computer turn= random.choice(['O','X']) print("First turn goes to ->"...
def not_terminal(c): #c=[stack,buffer,arcs] #print('terminal: ', c[1]) if c[1]==[]: #buffer is empty return False else: return True def get_oracle_transitions(state,correct_arcs): if should_leftarc(state, correct_arcs): t = 'LA' elif should_rightarc(state, correct_arcs): ...
The code generates a sequence of parsing transitions (`seq`) and tracks intermediate states (`c_set`) by applying oracle-guided transitions to a start state. It iteratively computes the correct transition (`t`) for the current state `c` using `get_oracle_transitions`, applies it to update `c`, and records both the tran...
def oracle_parse(start_state, correct_arcs): #c=[stack,buffer,arcs] correct_arcs: list of heads sequence seq=[] c=start_state #start_state=[ [0],[1,2,...],[-1]*len ] c_set=[] c_set.append(copy.deepcopy(start_state) ) while not_terminal(c): #c=[stack,buffer,arc] t=get_oracle_transitions(c,co...
def get_current(): nu = 0 with sv.open('Externals') as ext: nu = ext["current"] return nu def create_layout(self, size, frame): self.lay_grid = [] for row in range(size[0]): self.update() frame.rowconfigure(row, weight=1) grid_row = [] ...
The code initializes a grid-based environment by updating the layout, mapping obstacles, and defining agent and destination positions. It populates dictionaries (`all_states` and `available_states`) with adjacent cell coordinates for navigation, checking background colors to determine valid moves. The agent starts at [...
def refresh_(self): self.layout = get_current() self.create_layout(self.layout, self.layout_frame) self.obstacles(self.layout) self.agent_pos = [0, 0] self.all_states = {} self.available_states = {} for i in range(self.layout[0]): self.update(...
def get_table_names(sqlite_db): """ Queries 'table' table to get all CAS related table names :param sqlite_db: db file path :return: list of CAS related table names """ cas_tables = list() with closing(sqlite3.connect(sqlite_db)) as connection: with closing(connection.cursor()) as cu...
The function exports data from an SQLite database into a CAS JSON file by parsing relevant tables (metadata, annotation, labelset, etc.), incorporating anndata matrix data if available, and writing structured cell type annotations. It skips reviews, handles missing matrix_file_id configurations, and ensures output file...
def export_cas_data(sqlite_db: str, output_file: str, dataset_cache_folder: str = None): """ Reads all data from TDT tables and generates CAS json. :param sqlite_db: db file path :param output_file: output json path :param dataset_cache_folder: anndata cache folder path """ cta = CellTypeAnn...
def gh_login(purl_folder): github_token = os.environ.get(GITHUB_TOKEN_ENV) token_file = os.path.join(purl_folder, TOKEN_FILE) with open(token_file, 'w') as f: f.write(github_token) runcmd("git config --global credential.helper store") runcmd("gh auth login --with-token < {}".format(token_fi...
The function creates a GitHub pull request to publish a PURL configuration by cloning the repository, creating a branch, pushing the config file, and submitting a PR, while checking for existing forks or PRs to avoid conflicts.
def create_purl_request(purl_folder: str, file_path: str, taxonomy_name: str, user_name: str): """ Creates a purl publishing request at the purl repository. :param purl_folder: path of the purl folder :param file_path: purl config file path :param taxonomy_name: name of the taxonomy :param user_...
def report_problem(msg: str, purl_folder: str): """ Logs the problem and raises an exception. :param msg: error message :param purl_folder: folder where temp files are created inside """ print(msg) cleanup(purl_folder) raise Exception(msg) def create_purl_request(purl_folder: str, file_p...
The function publishes a taxonomy to the PURL system by checking if a configuration already exists. If not, it creates a GitHub pull request to add the configuration using Git and environment variables for authentication. It validates required credentials, sets Git user details, locates the PURL config file, and either...
def publish_to_purl(file_path: str, taxonomy_name: str, user_name: str) -> str: """ Publishes the given taxonomy to the purl system. First checks if PURL system already has a config for the given taxonomy. If not, makes a pull request to create a config. :param file_path: path to the project root folder...
def format_user_traits(self, user_traits: 'UserTraits', simple_or_expanded: str = 'simple') -> str: """ Formats a user's traits into a detailed description, suitable for inclusion in prompts to the language model. Args: user_traits (UserTraits): An object containing the user's trait...
The code generates a prompt for ChatGPT to predict whether a user will play or skip a recommended song, incorporating user traits, listening history, and song details formatted according to specified options.
def generate_prediction_prompt(self, user_traits: 'UserTraits', song_history: list[Song], recommended_song: Song, lyric_option: str, user_profile_option: s...