dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _compute_loss_weights(label_dataset_size, partial_dataset_size, unlabeled_dataset_size, method=0): if method == 0: return 1.0, 1.0, 1.0 elif method == 1: # sqrt ratio weight partial_weight = float(label_dataset_size) / float(partial_dataset_size) unlabeled_weight...
This code trains a machine learning model using labeled, partially labeled, and unlabeled data. It computes loss weights based on dataset sizes, iterates through epochs, processes batches from each dataset type with distinct training operations, applies learning rate decay, evaluates performance on validation/test sets...
def train(self, label_dataset, partial_dataset, unlabeled_dataset): best_f1, no_imprv_epoch, lr, cur_step = -np.inf, 0, self.cfg.lr, 0 loss_weight = self._compute_loss_weights(label_dataset.get_dataset_size(), partial_dataset.get_dataset_size(), unlabeled...
def load_dataset(filename, iobes, lowercase=True, char_lowercase=False): dataset = [] for words, chars, labels in raw_dataset_iter(filename, lowercase, char_lowercase): if iobes: labels = iob_to_iobes(labels) dataset.append({"words": words, "chars": chars, "labels": labels}) retu...
The code processes datasets for a model by loading training, development, and test data, building token vocabularies (words, characters, labels), and saving structured datasets in JSON format. For the "dCRF" model, it splits training data into 10 folds, generates labeled, partially labeled, and unlabeled variants, and ...
def process_data(config): # load raw datasets train_data = load_dataset(config.train_file, config.iobes, config.word_lowercase, config.char_lowercase) dev_data = load_dataset(config.dev_file, config.iobes, config.word_lowercase, config.char_lowercase) test_data = load_dataset(config.test_file, config.io...
def set_palette_entry(img: Image.Image, index, color): palette = img.getpalette() palette[index * 3: index * 3 + 3] = color img.putpalette(palette) def mask_room_id_img(img: Image.Image, ids_to_mask: list, should_mask_passages=False, room_masked_value=13) -> np.array: img_masked_array = np.array...
This function applies random room masking to an input image based on configurable parameters. It selects a mask type (none/all/uniform/one), determines which rooms to mask, and returns the modified image with specified regions masked using a designated color. The masking strategy includes optional passage masking and u...
def __call__(self, img: Image.Image) -> Image.Image: should_mask_passages = np.random.random() < self.mask_passages_pct mask_type = np.random.choice(self.mask_types, p=self.mask_pcts) if self.masked_color is not None: assert self.masked_value == 99, "Expected masked_value to be 99...
def get_lines(self): """Collects lines from file Returns ------- list a list with reversed file lines False when file doesn't exists """ try: with open(self.document, 'r') as f: return reversed(f.readlines()) ...
The code processes a file by reading its lines, summing data by month, and checking if the month in the first line differs from a stored month. If so, it saves the current salary data, resets the salary object, and appends a new record. It then calculates and returns the total salary before tax, formatted with its curr...
def process_file(self): """Operates on file Gets file lines or False when it doesn't exists. Then iterates through them backward summing time as long as separator is met. When record from last file line is different than this stored in month attribute it saves summarization and replaces...
def send_request(self, command, *args): try: request = json.dumps((command, *args)) self.first_socket.sendall(request.encode()) except Exception as e: print(f"Error sending request: {e}") def receive_response(self): try: response = self.first_socke...
The code toggles the sorting order of a specified column (ascending/descending/no sort) or sets it as the new sorted column. It sends a "SORT_BY_COLUMN" request with updated parameters, updates the table if the response is successful, or prints an error otherwise.
def sort_by_column(self, column_name): if column_name == self.sorted_column: if self.sort_ascending == "No": self.sort_ascending = "Asc" elif self.sort_ascending == "Asc": self.sort_ascending = "Desc" elif self.sort_ascending == "Desc": ...
def send_request(self, command, *args): try: request = json.dumps((command, *args)) self.first_socket.sendall(request.encode()) except Exception as e: print(f"Error sending request: {e}") def receive_response(self): try: response = self.first_socke...
The code initializes a GUI application for displaying and interacting with a tabular dataset. It connects to a server via two sockets to request data, sets up a Tkinter interface with a sortable table, and continuously updates the view using a background thread. The main task is to fetch, display, and dynamically updat...
def __init__(self, host, port, num_rows): self.host = host self.port = port self.id = str(uuid.uuid4()) self.start_index = 0 self.num_rows = num_rows self.table_len = num_rows self.first_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: ...
def make_fittable_data(): # first, interpolat the data that we have, this is all with a huge margin of error anyway x1 = [n[0]+18 for n in neubig_gas_only] y1 = [n[1] for n in neubig_gas_only] f1 = interp1d(x1, y1, kind='cubic') x2 = [n[0]+18 for n in neubig_gao_and_gas] y2 = [n[1] for n in neubig_gao_and_gas] ...
The code performs a grid search optimization to find the best-fit parameters for a cAMP signaling model. It evaluates parameter combinations (Ga_f, eff_f, activation_factor, etc.) against experimental data, computes squared differences, and identifies the minimum error configuration. The optimal parameters are then use...
def main(): # for instructions on using lmfit see https://lmfit.github.io/lmfit-py/model.html check_deps([bngl, gnuplot]) agonist_conc, camp = make_fittable_data() params = ['Ga_f', 'eff_f', 'activation_factor', 'gpcr_concentration','gs_factor' ] param_values = {} param_values['Ga_f'] = Parameter(value=0.01, m...
def buildMirrorRegion_elliptical(a,hx,hy,MN,w0,h0=h0,n_f=n_f,engine=engine): """the function used to build mirriro region with elliptical holes Args: a (float): the lattice constant used to build the mirror region hx (float): hole diameter in the x direction hy (float): hole diameter i...
This function simulates an elliptical cavity's resonance properties by varying the tapering prefactor. It constructs mirror, tapered, and waveguide regions, computes resonance frequency, Q-factors, mode volume, and detuning. Fitness is calculated based on these parameters for optimization, with results saved to a CSV f...
def sweep_tapering_elliptical_cavity(param): """This function sweep through the tapering prefactor and simulate the corresponding resonsance Args: param (0): t the tapering prefactor associated with the defect region """ print("Start sim ==============================") start_time = datet...
def buildMirrorRegion_elliptical(a,hx,hy,MN,w0,h0=h0,n_f=n_f,engine=engine): """the function used to build mirriro region with elliptical holes Args: a (float): the lattice constant used to build the mirror region hx (float): hole diameter in the x direction hy (float): hole diameter i...
This function simulates the resonance of an elliptical cavity by varying the beam width prefactor. It constructs mirror and tapered regions, runs electromagnetic simulations, extracts resonance parameters (frequency, Q-factors, mode volume), calculates detuning from a target wavelength, and computes a fitness metric fo...
def sweep_beam_width_elliptical_cavity(param): """This function sweep through the beam width prefactor and simulate the corresponding resonsance Args: param (0): w the beam width prefactor associated with the defect region """ print("Start sim ==============================") start_time =...
def buildMirrorRegion_elliptical(a,hx,hy,MN,w0,h0=h0,n_f=n_f,engine=engine): """the function used to build mirriro region with elliptical holes Args: a (float): the lattice constant used to build the mirror region hx (float): hole diameter in the x direction hy (float): hole diameter i...
The code simulates an elliptical cavity's resonance properties, calculates quality factors (Qwvg, Qsc), mode volume (Vmode), and resonance frequency (F). It computes a fitness metric based on Q, performance (P), and wavelength detuning, then records data to a CSV file. The function returns the negative fitness value fo...
def sweep_beamWidth_ellipticalCavity_v2(param): print("Start sim ==============================") start_time = datetime.now() w0 = param[0] #build the left mirror cell region mirror_cells_left = buildMirrorRegion_elliptical(a,hx,hy,MN_L,w0,h0,n_f,engine) #build the right mirror cell region ...
def buildMirrorRegion_elliptical(a,hx,hy,MN,w0,h0=h0,n_f=n_f,engine=engine): """the function used to build mirriro region with elliptical holes Args: a (float): the lattice constant used to build the mirror region hx (float): hole diameter in the x direction hy (float): hole diameter i...
The function `sweep_cellNum_ellipticalCavity` simulates an elliptical cavity's resonance by constructing mirror and tapered regions, calculating quality factors (Q), and evaluating performance. It runs a resonance simulation, computes Q-values (Qwvg, Qsc), derives fitness based on Q, mode volume, and detuning, then log...
def sweep_cellNum_ellipticalCavity(param): """this function sweeps through the cell numbers associated with the cavity and calculate the associated Q Args: param[0] (float): the left mirror cell numbers param[1] (float): the tapering cell numbers Returns: _type_: _description_ ...
def buildMirrorRegion_elliptical(a,hx,hy,MN,w0,h0=h0,n_f=n_f,engine=engine): """the function used to build mirriro region with elliptical holes Args: a (float): the lattice constant used to build the mirror region hx (float): hole diameter in the x direction hy (float): hole diameter i...
This function simulates an elliptical photonic cavity by constructing mirror, taper, and waveguide regions. It calculates resonance frequency, Q-factors (Qwvg/Qsc), and mode volume (Vmode) using Lumerical's engine. The cavity's optical properties are analyzed, with results including Q-values, detuning, and resonance pa...
def sim_ellipticalCavity(a,hx,hx_min,hy,hy_min,t,t_wvg,WN,w0=w0,h0=h0,n_f=n_f,engine=engine): """this function sweeps through the hy associated with the cavity and calculate the associated Q Args: a (float): the lattice constant for the mirror cells hx (float): the hole radius in the x directi...
def corner_count_feature_extractor(self, image): # count strong corner as a feature corners = get_corner_points(image, 100) # cv2.imshow('image', image) # cv2.waitKey(0) features = array([len(corners)]) feature_names = array(['number_corners']) # corners = np.int0(corners) # for i in co...
The function extracts features from an image using three distinct methods: corner count, length-width ratio, and HSV color. It combines these features into a single array along with their corresponding names, then returns the concatenated feature names and values for further processing or analysis.
def feature_extractor_with_corner_count(self, image, c_image, g_imgs): #get feature info from selected extractor (feature_names1, features1) = self.corner_count_feature_extractor(image) (feature_names2, features2) = self.length_width_ratio_feature_extractor(image) (feature_names6, features6) = self.hsv_...
def corner_count_feature_extractor(self, image): # count strong corner as a feature corners = get_corner_points(image, 100) # cv2.imshow('image', image) # cv2.waitKey(0) features = array([len(corners)]) feature_names = array(['number_corners']) # corners = np.int0(corners) # for i in co...
This method extracts multiple visual features from an image and a color image, including corner count, length-width ratio, HOG texture, and HSV color features, then concatenates them into a combined feature vector with corresponding names for downstream tasks like object recognition or classification.
def all_feature_extractor(self, image, c_image, g_imgs): #get feature info from selected extractor (feature_names1, features1) = self.corner_count_feature_extractor(image) (feature_names2, features2) = self.length_width_ratio_feature_extractor(image) (feature_names3, features3) = self.hog_texture_extrac...
def txt_list(): archivo=open("lista2.txt","r") lista=[] for linea in archivo: num=conv(linea) lista.append(num) archivo.close() return lista def ame_increases(fnum,snum): if fnum>snum: return "d" #measurements are larger than the previous measurement elif fnum<snum: ...
The code processes a list (`lista`) to determine if each element is increasing, decreasing, or unchanged compared to the previous element, printing these results. It then sums the next three elements starting from each position (if available) and stores these sums in `lista2`. Finally, it passes `lista2` to a function ...
def Arraymap(): lista=txt_list() i=0 lista2=[] print(lista[i],"none") while i<len(lista): meas=ame_increases(lista[i-1],lista[i]) if meas=="d": print(lista[i],"(decreased)") if meas=="i": print(lista[i],"(increased)") if meas=="n": ...
def numerosBingo(): archivo=open(archivoB,"r") lista=[] for linea in archivo: if linea=="\n": break lista.append(linea) archivo.close() #paso los num de bingo a numeros lista=lista[0] listaNum=listnum(lista) return listaNum def listBoard(): archivo=open(a...
The code simulates a bingo game by repeatedly checking for winning rows or columns in two boards using numbers from a list. It removes the winning board and tracks the last called number. After determining the final winning board, it calculates the sum of unmarked numbers, multiplies it by the last called number, and p...
def listabingo(): listaBing=numerosBingo() listaBoard=listBoard() listaBoard2=listBoard() while len(listaBoard)>1: win=False winpos=0 listaNum=[] #agregoNumerosqueSalen en bingo cant=4 listaNum.append(listaBing[0]) listaNum.append(listaBing[1]) ...
def parse_request(self): global max_log_info, conf_dict ''' split the request at newline. Eg of request: GET /hello.html HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Accept-Encodi...
The main task of the code is to handle incoming HTTP requests by receiving and parsing client data, managing binary content, logging request details based on configuration, ensuring complete data reception, and routing the request to appropriate response methods (GET, POST, etc.) while handling errors and closing conne...
def handle_request(self): global active_threads, max_log_info, conf_dict # active_threads.append(self.client_connection) # receive data from client and parse the request # while self.client+c # self.request_data = self.client_connection.recv(limit_request_length) # print(...
def button_press(data,buttonsx): #Called when tile is pressed # Checks if flag mode is active if (flag == False): #Disables tile then checks what number is associated with it (buttonsx[ data[0]])[data[1]].config(state=DISABLED) print((buttonsx[ data[0]])[data[1]].cget('text')) ...
The function `build_button` generates a grid of buttons within a frame, linking each to a `button_press` handler. It initializes game UI elements like score, time, and control buttons (Reset, Back, Flag), sets global variables for game state tracking, and returns the structured button grid for further interaction.
def build_button(min,max,rows,root): #Main function to build tiles buttonsx = [] buttonsy = [] frame = Frame(root) #For loops creates all the tiles as buttons with command linking to button_press for x in range(min,max): for y in range(min,max): temp = ("Button" + str(x) + s...
def find_friends_node(self, node, new_friends=2): if self.count_friends(node) >= self.friend_limit: return # Try to give each node a new friend for i in range(new_friends): # Find a random node random_node = random.choice(list(self.G.nodes)) # If t...
The code's main task is to update the count of infected individuals in each region by iterating through all nodes in a graph. It initializes a list to track infected counts per region, processes each node's interactions (finding friends, partnerships, reproduction, relocation, aging), and then checks if nodes are infec...
def step(self): self.region_infected_population = [0, 0, 0, 0, 0, 0] for node in list(self.G.nodes): self.find_friends_node(node) self.partner_node(node) self.reproduce_node(node) self.relocate_node(node) self.age_node(node) # chec...
def calculation(self, data): """ Feature engineering function: calculate theta and phi for ball's rotation speed. :param data: data frame, ball's initial factors :return: data frame Note ---- add column w_theta: float angle between ball's rotatio...
The main task of the code is to calculate and adjust the trajectory of a ball using machine learning predictions for carry, distance, peak height, and offline ratio. It scales initial trajectory coordinates based on these predictions, simulates bounces by extending the track with scaled segments, applies exponential de...
def traj(self, data, reg_carry, reg_tot_dist, reg_peak_height, reg_offline_ratio): """ Calculate the trajectory of the ball, adjusted using ML :param data: shot factors :param reg_carry: linear regression model that predicts carry using above data :param reg...
def calculation(data): ball = data[["ball_speed", "launch_angle", "azimuth", "side_spin", "back_spin"]] ball.columns = ["launch_speed", "theta", "phi", "side_spin", "back_spin"] ball["theta"] = ball.theta.map(lambda x: math.radians(x)) ball["phi"] = ball.phi.map(lambda x: math.radians(x)) ball["laun...
The code loads session data, processes it to calculate ball trajectories, predicts the movement of a single observation using a TRACK function with specific parameters, extracts trajectory coordinates, and generates an animated plot visualizing the predicted 3D path of the ball.
def main(): # load data data = pd.read_csv("all_sessions_refined.csv") ball = calculation(data) # prediction for 1 observation row1 = ball.iloc[1] result = TRACK(0.04593, 0.04267, 1.2, 0.16, 0.1, row1[0], row1[1], row1[2], row1[5], row1[6], 0) x_track = result[0] ...
def __up(self): self.__change_position(Position(self.__body[-1].line-1, self.__body[-1].column)) def __down(self): self.__change_position(Position(self.__body[-1].line+1, self.__body[-1].column)) def __left(self): self.__change_position(Position(self.__body[-1].line, self.__body[-1].column-1)...
This function handles user input to change the snake's movement direction in a game. It checks if the pressed key (e.g., 'w', 's', 'a', 'd') is valid relative to the current direction, avoiding reversal (e.g., not moving down if currently moving up). If valid, it updates the snake's direction and triggers the correspon...
def move(self, key): """[move snake] Args: key ([byte]): [user key] """ if not key: key = self.__direction if key == b'w' and self.__direction != b's': self.__up() self.__direction = key elif key == b's' and self.__direction != b'w': ...
def getWeight(): return float(sys.argv[1]) def doRolls(array, weight): #initialize variables setRoll = 0 cntr = 0 iterations = 1000000 #store iterations for probability math array[2] = iterations #loop iteration count while (cntr < iterations): #use die roller module with...
The main task of the code is to simulate and compare dice roll probabilities for standard and loaded dice. It initializes arrays to store results, retrieves a weight parameter from command-line input, performs simulations using `doRolls`, and prints probability distributions with `printProb`, contrasting outcomes betwe...
def main(): #initialize variable and arrays weight = 0 #create array stdWins = arr.create1D(4,0) loadedWins = arr.create1D(4,0) #get commandline arg weight = getWeight() #program functions doRolls(stdWins, 0) printProb(stdWins, 0, 0) doRolls(loadedWins, getWeight()) p...
def data_over_time(coco_dset, fnum=1): """ import shitspotter coco_dset = shitspotter.open_shit_coco() """ rows = [] for gid, img in coco_dset.index.imgs.items(): row = img.copy() rows.append(row) img_df = pd.DataFrame(rows) img_df = img_df.sort_values('datetime') im...
The code updates dataset analytics by generating and saving multiple visualizations: a time-based data plot, a spacetime scatterplot, a dog image, and three sample images. It loads a COCO dataset, adjusts figure sizes, applies layouts, and exports PNGs/JPGs to a specified directory for analysis.
def update_analysis_plots(): """ Update all of the dataset analytics """ import shitspotter import kwplot kwplot.autoplt() coco_dset = shitspotter.open_shit_coco() print('coco_dset.fpath = {!r}'.format(coco_dset.fpath)) dump_dpath = (ub.Path(coco_dset.bundle_dpath) / 'analysis').en...
def reprog_to_seq(prog_in, is_gold): ''' predicted recursive program to list program ["divide(", "72", "multiply(", "6", "210", ")", ")"] ["multiply(", "6", "210", ")", "divide(", "72", "#0", ")"] ''' st = [] res = [] try: num = 0 for tok in prog_in: if tok ...
The function evaluates the correctness of predicted programs against reference programs and their execution results. It reads input and original JSON data, compares predicted vs. reference programs, and checks if execution results match gold standards. It calculates execution accuracy (exe_acc) and program accuracy (pr...
def evaluate_result(json_in, json_ori, all_res_file, error_file, program_mode): ''' execution acc program acc ''' correct = 0 with open(json_in) as f_in: data = json.load(f_in) with open(json_ori) as f_in: data_ori = json.load(f_in) data_dict = {} for each_data in ...
def gray_mapper_qam(P, M = 16, verbose=False): if(M==2): return {'0': [-P, 0], '1': [P, 0]} k = np.log2(M).astype(int) a = {} for j in range(M): bits = bin(j)[2:] bits = '0'*(k - len(bits)) + bits t = modulator(np.array([int(i) for i in bits]), M) a[bits] =[t.re...
The function calculates the Bit Error Rate (BER) of a communication system by simulating multiple transmission samples. It generates random bits, modulates them using QAM, transmits through a channel, equalizes the signal, demodulates, detects symbols, and compares the recovered bits to the original. The average BER ac...
def Ber(params, nber_sample=10, ns=10000, p=0.5, M=2): res = 0 ns=10#0#0#0 nb = np.log2(M).astype(int)*ns cnt = gray_mapper_qam(params.P, M) for i in range(nber_sample): b= source(nb, p) s = bit_to_symb(b, cnt) q0t = mod(params, s) qzt,_ = channel(params, q0t) ...
def pathGen_triangleExpanding(listIn, t): fProgr, fProgrTick = tmToBeat(t, u_bpm, 4) fProgrQ, fProgrTickQ = tmToBeat(t, u_bpm, 2) pos1 = seededRndFloat(fProgrTick) pos2 = seededRndFloat(fProgrTick + 1) pos = pos1 + (pos2 - pos1) * fProgr rangeStep = 4 cx = seededRndFloat(7 * math.floor(fPro...
The main task of the code is to generate multiple path sequences by combining outputs from three distinct path generation functions (`pathGen_triangleExpanding`, `pathGen_testProcFFT`, and `pathGen_trippyKaleidoscope5`), all processing input FFT frequency bands (`fftBandsIn`) and a time parameter (`t`). The function ag...
def pathGen_kaleidoSpectrum(fftBandsIn, t): paths = [] paths.extend(pathGen_triangleExpanding(fftBandsIn, t)) paths.extend(pathGen_testProcFFT(fftBandsIn, t)) paths.extend(pathGen_trippyKaleidoscope5(fftBandsIn, t)) # for i in range(min(len(fftBandsIn), len(list))): # list[i].y*=scaledLvlCl...
def rfind_on_level(string, target, end): def is_escaped(index): nindex = index while string[nindex-1] == "\\": nindex -= 1 return (index-nindex) % 2 == 1 stack = [None] escape = False for index, c in reversed(list(enumerate(string[:end...
This code parses function/method declarations, extracting argument types, return types, names, and test-specific data. It identifies test types (e.g., TEST, FUNCTIONTEST), splits test suite/method names, handles default arguments, and sets code block boundaries for analysis.
def __init__(self, scope_start, end): arg_start = rfind_on_level(content, "(", content.rfind(")", 0, scope_start)) args, arg_start, arg_end = get_args(content, arg_start) self.arg_types = [] for arg in args: type_end = rfind_on_level(arg[0], " ", len(arg[...
def add_ignore(dir, prev): ignore = [] ignorepath = os.path.join(dir, ".filterignore") try: if os.path.isfile(ignorepath): with open(ignorepath) as f: ignore.extend(f.read().split("\n")) ignore = [ig.strip() for ig in ignore if ig.strip() != ""] ig...
This function recursively processes files in a directory, applying ignore patterns to determine which files to exclude. It logs each file, moves non-excluded files to a specified output directory, and recursively processes subdirectories if enabled. The ignore list is updated with the current directory, and files are f...
def rem_in_dir(dir, ignore): ignore = add_ignore(dir, ignore) files = os.listdir(dir) files = [os.path.join(dir, file) for file in files] for file in files: if os.path.isfile(file): Logger.nextfile(file) do_include = ([True] + [include for regex, include in ignore if re...
def update(self, byte_in): """ Update a single byte, and add it to the hash digest :param byte_in: a single byte (8-bit char?) :return: """ self.x_buf[self.x_buff_off] = byte_in self.x_buff_off += 1 if self.x_buff_off == len(self.x_buf): sel...
The main task of the code is to finalize data processing in a cryptographic operation. It calculates the bit length of processed data, applies padding (-128 and 0x00), processes the bit length, and executes the final block processing to complete the operation, likely for hashing or encryption.
def finish(self): bit_length = self.byte_count << 3 self.update(-128) while self.x_buff_off != 0: self.update(0x00) self.process_length(bit_length) self.process_block()
def finish(self): bit_length = self.byte_count << 3 self.update(-128) while self.x_buff_off != 0: self.update(0x00) self.process_length(bit_length) self.process_block() def int_to_big_endian(self, n, bs, off): """ Convert int to big endian :p...
The main task of the code is to finalize processing by writing eight 32-bit integers (H1–H8) into the output buffer in big-endian format, starting at the specified offset. After writing these values sequentially, it resets the internal state and returns the modified output buffer.
def do_final(self, out, out_off): """ :param out: byte[] :param out_off: int :return: """ self.finish() out = self.int_to_big_endian(self.H1, out, out_off) out = self.int_to_big_endian(self.H2, out, out_off + 4) out = self.int_to_big_endian(self.H...
def generate(dims: tuple, mode: str = "glider"): modes = ["glider", "random", "sparse"] if not mode: choose_random_mode = randint(0, len(modes) - 1) mode = modes[choose_random_mode] if mode == "glider": out = np.repeat([0], dims[0] * dims[1]).reshape(dims) glider = np.array...
The code simulates Conway's Game of Life for a specified number of generations (`gens`), starting with a grid generated based on given dimensions (`dims`) and mode (`mode`). It visualizes each generation's state by counting living neighbors, applying update rules, and rendering the resulting grid. The process iterates ...
def run(gens: int = 500, dims: tuple = (30, 30), mode: str = None): """ Runs the game of life for `gen` number of generations. """ start = generate(dims=dims, mode=mode) render(start) for g in range(gens): summed = count_all_living_neighbours(start) out = apply_rules(start, summe...
def init(): offset = 0 for subdir, dirs, files in os.walk(path): for file in files: filepath = subdir + os.sep + file if filepath.endswith(".txt"): f = open(filepath, "r") lines = f.readlines() for line in lines: ...
The main task of the code is to create an interactive system that continuously accepts user input, generates and displays the top 5 completions using `get_best_k_completions`, and allows users to either append input or terminate the session with `#`. It initializes the system, processes input iteratively, and prints co...
def main(): print("Loading the files and preparing the system...") init() print("the system is ready. Enter your text:") while True: flag = True the_input = input() while flag: top_5 = get_best_k_completions(the_input) print_top_5(top_5) print(...
def levelup_text(stage): message_display(stage ,170, 220, 2) def crash(): message_display("Game over",190, 150, 0) message_display("Enter to play again",140, 185, 0) message_display("Space to quit",170, 220, 5) def main(): width = 510 height = 480 blue_color = (255, 255, 25...
The code initializes a game level with two controllable heroes (using different key mappings), multiple monsters and goblins, and manages their movement, collision detection, score tracking, and level progression. It handles player input, updates game entities, checks for collisions (scoring points or triggering game o...
def level_1(): # Hero hero = Hero(hero_image, [250, 400]) hero.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN] hero.vx = 5 hero.vy = 5 heros_group = pygame.sprite.Group() heros_group.add(hero) s_hero = Hero(s_hero_image, [350, 400])...
def levelup_text(stage): message_display(stage ,170, 220, 2) def crash(): message_display("Game over",190, 150, 0) message_display("Enter to play again",140, 185, 0) message_display("Space to quit",170, 220, 5) def main(): width = 510 height = 480 blue_color = (255, 255, 25...
The code initializes a game level with two heroes, multiple monsters, and goblins, handling their movement, collision detection, and scoring. Heroes move via keyboard inputs, while enemies update their positions. Collisions with enemies increase the score; hitting a hero triggers a crash and restart options. The level ...
def level_2(): # Hero hero = Hero(hero_image, [250, 400]) hero.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN] hero.vx = 5 hero.vy = 5 heros_group = pygame.sprite.Group() heros_group.add(hero) s_hero = Hero(s_hero_image, [350,...
def levelup_text(stage): message_display(stage ,170, 220, 2) def crash(): message_display("Game over",190, 150, 0) message_display("Enter to play again",140, 185, 0) message_display("Space to quit",170, 220, 5) def main(): width = 510 height = 480 blue_color = (255, 255, 25...
The code initializes and manages a game level with two controllable heroes, multiple monsters, and goblins. It handles player movement, collision detection for scoring, and transitions to the next level when a score threshold is met. The loop updates game elements, checks for collisions, renders visuals, and manages ga...
def level_3(): # Hero hero = Hero(hero_image, [250, 400]) hero.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN] hero.vx = 5 hero.vy = 5 heros_group = pygame.sprite.Group() heros_group.add(hero) s_hero = Hero(s_hero_image, [350,...
def levelup_text(stage): message_display(stage ,170, 220, 2) def crash(): message_display("Game over",190, 150, 0) message_display("Enter to play again",140, 185, 0) message_display("Space to quit",170, 220, 5) def main(): width = 510 height = 480 blue_color = (255, 255, 25...
The code defines the fourth level of a game, initializing two player characters (hero and s_hero) with movement controls, multiple monsters, and goblins. It handles collision detection for scoring, level progression (to Level 2 when score reaches 4), and game-over logic (restarting or quitting). The loop updates game e...
def level_4(): # Hero hero = Hero(hero_image, [250, 400]) hero.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN] hero.vx = 5 hero.vy = 5 heros_group = pygame.sprite.Group() heros_group.add(hero) s_hero = Hero(s_hero_image, [350, 400]) ...
def levelup_text(stage): message_display(stage ,170, 220, 2) def crash(): message_display("Game over",190, 150, 0) message_display("Enter to play again",140, 185, 0) message_display("Space to quit",170, 220, 5) def main(): width = 510 height = 480 blue_color = (255, 255, 25...
The code defines the fifth level of a game, initializing two heroes, multiple monsters, and goblins with specific positions and movement controls. It handles player input, collision detection, boundary checks, scoring, and level progression. When a hero collides with a monster or goblin, the score increases, and if the...
def level_5(): # Hero hero = Hero(hero_image, [250, 400]) hero.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN] hero.vx = 5 hero.vy = 5 heros_group = pygame.sprite.Group() heros_group.add(hero) s_hero = Hero(s_hero_image, [350, 400]) ...
def GetExpData(fname): """Function: GetExpData(input) Reads in the experimental data from the input file Input: fname = name of file that contains G(t) in 2 columns [t Gt] Output: A n*1 vector "t", and a n*1 vector Gt""" try: to, Gto = np.loadtxt(fname, unpack=True) # 2 columns, t - Gt except O...
The main task of the code is to compute the continuous spectrum $ H(s) $ from experimental data $ G_{\text{exp}}(t) $ using a regularization parameter $ \lambda_C $, determined via an L-curve analysis. The code initializes kernel matrices, solves for $ H $ with optimal $ \lambda_C $, and optionally generates plots and ...
def getContSpec(par): """ This is the main driver routine for computing the continuous spectrum (*) input : "par" dictionary from "inp.dat" which specifies GexpFile (often 'Gt.dat') (*) return : H and lambdaC; the latter can be used to microscpecify lambdaC as desired without having to do th...
def _remove_background(self, image): # Inspired by -> https://github.com/TheMemoryDealer/Robot-Programming-CMP9767M/blob/main/weeder/src/vision.py HSVimage = bgr_to_hsv(image) self.saveImage(HSVimage) # between values for thresholding min = np.array([35, 000, 000]) max =...
The code preprocesses an image by first removing its background, then eliminating vines from the background-free image. It tracks the number of processed images using a counter and saves the final vine-free image. The main tasks are background and vine removal, image counting, and storage.
def _preprocess_image(self, cv2_img): img_no_bg = self._remove_background(cv2_img) # remove background on start img_removeVines = self._remove_vines(img_no_bg) print("Count of images taken: ", self.image_count) self.saveImage(img_removeVines)
def _compute_action_and_certifications(self, actions): self._logger.info(f'[compute_action_and_certifications] actions = {actions}') actions_cnt = np.zeros(self.num_actions, dtype=np.int) for i in range(self.num_actions): actions_cnt[i] = np.count_nonzero(actions == i) a_star = np.argmax(actions_c...
The main task of the code is to evaluate actions for a given state, check if the state has been visited, and decide whether to add actions to a valid list or queue based on safety thresholds (rho). It processes each agent's action, computes certifications, filters actions using a reward shaping mechanism, and manages s...
def take_action(self, state, rho_lim, re_cur, no): # check whether state has been visited and determine whether needed to put in queue state_bytes = state.tobytes() if state_bytes in self.state_set[no]: self._logger.info(f'########################################### examining duplicated state...
def update_dict_2_level(self, state_bytes, new_dict, notice=False): if state_bytes not in self.state_dict: self.state_dict[state_bytes] = new_dict else: for k, v in new_dict.items(): if notice: assert k not in self.state_dict[state_bytes], f'k = {k} in self.state_dict[state_bytes],...
The code recursively expands a state in a reinforcement learning environment, exploring all possible actions from the current state to compute accumulated rewards. It maintains a state dictionary mapping states to reward values, updating entries based on maximum steps allowed, reward thresholds, and pruning conditions....
def expand(self, state, rho_lim=0, re_cur=0, no=0): state_bytes = state.tobytes() if re_cur >= self.re_min: self.update_dict_2_level(state_bytes, {self._max_steps_per_episode-no: 0}) self._logger.info(f'************************************************ pruning at no={no}') return self.state_di...
def _update_observation(self, state, observation): """Records an observation and update state. Extracts a frame from the observation vector and overwrites the oldest frame in the state buffer. Args: observation: numpy array, an observation from the environment. """ # Set current observat...
This code runs a multi-agent experiment by loading pre-trained models, initializing an environment, and iteratively processing state queues to build a certification map through exploration and reward-based state updates. It restores agent checkpoints, manages state transitions, and saves results, exiting after completi...
def run_experiment(self): self._logger.info('exp begin!') """Runs a full experiment, spread over multiple iterations.""" id_list = list(range(1, self._total_num+1)) # id_list = list(range(1, 31)) sess = tf.compat.v1.Session('', config=self.config) sess.run(tf.compat.v1.global_variables_initial...
def connect_slack_websocket(self, ws_url): """Uses http proxy if available""" if self.proxies and 'http' in self.proxies: parts = parse_url(self.proxies['http']) proxy_host, proxy_port = parts.host, parts.port auth = parts.auth proxy_auth = auth and auth.s...
This method connects to Slack's RTM API using either `rtm.start` or `rtm.connect`, handling reconnections with backoff logic if `auto_reconnect` is enabled. It manages rate-limiting (HTTP 429) by retrying after delays, resets retry counters on success, and initializes WebSocket connections upon successful authenticatio...
def rtm_connect(self, reconnect=False, timeout=None, use_rtm_start=True, **kwargs): """ Connects to the RTM API - https://api.slack.com/rtm If `auto_reconnect` is set to `True` then the SlackClient is initialized, this method will be used to reconnect on websocket read failures, which i...
def handle_multioption_headers(header, value): if header == constants.ADOPTION_DEADLINE_XPRESS_LEADS_HEADER: return map_from_to(value, constants.DEADLINE_VALUES, DROPDOWN_FIELDTYPE) #if header == constants.LEAD_RATING_XPRESS_LEADS_HEADER: #return map_from_to(value, constants.LEADS_VALUES, DROPD...
This function reads a CSV file containing lead data, maps its headers to Pardot field IDs with custom formatting, processes special fields (e.g., multi-option values, notes), and submits the transformed data to Pardot's API via POST requests to create or update leads.
def push_data_to_pardot(fn): with open(fn, "r") as csvfile: reader = csv.DictReader(csvfile) headers = reader.fieldnames tag_names = { constants.FIRST_NAME_XPRESS_LEADS_HEADER: constants.FIRST_NAME_FIELD_ID, constants.LAST_NAME_XPRESS_LEADS_HEADER: constants.LAST_NAME...
def cron_log(text): with open(cronlog_fn, "a+") as c_log: if text: c_log.write(str(text)) else: c_log.write( "Cron ran at: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n" ) def get_conf_data(): s...
The main task of the code is to execute a process that checks for a lock file to prevent concurrent runs. If the lock file does not exist, it creates one, retrieves configuration data, identifies new data, pushes it to Pardot and LS systems, and performs cleanup. If the lock exists, it exits. Errors trigger logging and...
def main(): cron_log(None) try: if os.path.isfile(lock_fn) != True: print("Lock file doesn't exist, process isn't currently running") open(lock_fn, "w+") # Getting fresh data get_conf_data() # Parsing through new data to check for duplicates ...
def cross_entropy(self, y, probs): """ Cross-entropy between two probability distributions of y and p_pred """ return -1 * np.mean(y * np.log(probs)) def predict_(self, X): pre_vals = np.dot(X, self.weights.T).reshape(-1, len(self.classes)) return self.softmax(pre_vals) def evaluate_(s...
This function trains a model by minimizing cross-entropy loss using stochastic gradient descent. It updates weights and bias parameters iteratively with random batches, computes gradients from prediction errors, adjusts parameters via gradient descent (w := w - lr*dw, b := b - lr*db), monitors convergence via gradient ...
def fit_(self, X, y, batch_size, lr, verbose): """ We optimize the cost function (cross-entropy) and update the parameters to minimize the cost. Using the gradients descent algorithm, the gradients of the 'w' and 'b' parameters are computed and the parameters are updated, as follows: w := w - lr * dw; b :...
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_(self, X, y, batch_size, lr, verbose): """ We optimize the cost function (cross-entropy) and update the parameters t...
This code trains a classifier by initializing parameters, preparing data with bias and one-hot encoding, and calling a training loop to update weights via optimization, tracking loss during the process.
def fit(self, X, y, batch_size=128, lr=0.001, rand_seed=4, verbose=False): """We just randomly initialize parameters 'w' and 'b' with 0 to start with (w vector has the shape (945, 1)), whereas the values will be updated using the optimization function.""" np.random.seed(rand_seed) self.classe...
def checkWin(grid): turns = turnCount(grid) for i in range(3): if(grid[i][0] == grid[i][1] == grid[i][2] != ' '): return 10-turns if grid[i][0]=='X' else -10+turns if(grid[0][i] == grid[1][i] == grid[2][i] != ' '): return 10-turns if grid[0][i]=='X' else -10+turns if((grid[0][0] == grid[1][1...
The code simulates a game by randomly selecting moves until a win or draw is determined, returning the outcome. It copies the board, alternates players, and applies random valid moves until `checkWin` identifies a result, then returns that result.
def rollout(self): board = copy.deepcopy(self.grid) player = self.turn while(checkWin(board)==None): moves = getPossibleMoves(board) randMove = randint(0, len(moves)-1) board = playTurn(board, moves[randMove], symbol[player]) player = 1-player ...
def getPossibleMoves(grid): moves = [] if checkWin(grid): return moves for i in range(3): for o in range(3): if grid[i][o]==' ': moves.append([i, o]) return moves def addState(self, newState): self.children[str(newState)] = Node(newState, parent=self, turn=1-s...
The main task of the code is to generate all possible next game states by applying shuffled valid moves to the current grid. It iterates through each move, executes it using `playTurn`, and adds the resulting state to the current state's children, enabling exploration of potential game paths in a tree structure.
def expansion(self): moves = getPossibleMoves(self.grid) shuffle(moves) for move in moves: self.addState(playTurn(self.grid, move, symbol[self.turn]))
def checkWin(grid): turns = turnCount(grid) for i in range(3): if(grid[i][0] == grid[i][1] == grid[i][2] != ' '): return 10-turns if grid[i][0]=='X' else -10+turns if(grid[0][i] == grid[1][i] == grid[2][i] != ' '): return 10-turns if grid[0][i]=='X' else -10+turns if((grid[0][0] == grid[1][1...
The code implements the minimax algorithm for a turn-based game, recursively evaluating all possible moves on a grid. It determines the optimal outcome by maximizing the player's score (turn 0) or minimizing the opponent's (turn 1), returning the best possible result based on the current game state and player's turn.
def minimax(grid, turn): if checkWin(grid)!=None: return checkWin(grid) maxOutcome = -2 minOutcome = 2 moves = getPossibleMoves(grid) for move in moves: i = move[0] o = move[1] if(grid[i][o]==' '): if(turn==0): maxOutcome = max(maxOutcome, ...
def checkWin(grid): turns = turnCount(grid) for i in range(3): if(grid[i][0] == grid[i][1] == grid[i][2] != ' '): return 10-turns if grid[i][0]=='X' else -10+turns if(grid[0][i] == grid[1][i] == grid[2][i] != ' '): return 10-turns if grid[0][i]=='X' else -10+turns if((grid[0][0] == grid[1][1...
This code implements a minimax algorithm with memoization to determine the optimal move in a game (e.g., tic-tac-toe). It recursively evaluates all possible moves, stores results in a memo dictionary to avoid redundant calculations, and alternates between maximizing and minimizing players' outcomes based on the turn. T...
def minimax_memo(grid, turn): if str(grid) in memo: return memo[str(grid)] if checkWin(grid)!=None: memo[str(grid)] = checkWin(grid) return memo[str(grid)] maxOutcome = -2 minOutcome = 2 moves = getPossibleMoves(grid) for move in moves: i = move[0] o = mov...
def checkWin(grid): turns = turnCount(grid) for i in range(3): if(grid[i][0] == grid[i][1] == grid[i][2] != ' '): return 10-turns if grid[i][0]=='X' else -10+turns if(grid[0][i] == grid[1][i] == grid[2][i] != ' '): return 10-turns if grid[0][i]=='X' else -10+turns if((grid[0][0] == grid[1][1...
This function implements alpha-beta pruning with memoization for game state evaluation. It recursively explores possible moves, storing results in 'memo' to avoid redundant calculations. For each turn, it maximizes/minimizes outcomes based on player roles, pruning branches where beta ≤ alpha to optimize search efficien...
def alpha_beta_memo(grid, turn, alpha, beta): if str(grid) in memo: return memo[str(grid)] if checkWin(grid)!=None: memo[str(grid)] = checkWin(grid) return memo[str(grid)] maxOutcome = -2 minOutcome = 2 moves = getPossibleMoves(grid) for move in moves: i = move[0]...
def checkWin(grid): turns = turnCount(grid) for i in range(3): if(grid[i][0] == grid[i][1] == grid[i][2] != ' '): return 10-turns if grid[i][0]=='X' else -10+turns if(grid[0][i] == grid[1][i] == grid[2][i] != ' '): return 10-turns if grid[0][i]=='X' else -10+turns if((grid[0][0] == grid[1][1...
This code implements the Alpha-Beta pruning algorithm for a two-player game, recursively evaluating possible moves on a grid. It alternates between maximizing (turn=0) and minimizing (turn=1) outcomes, using alpha and beta values to prune suboptimal branches. The function returns the optimal score for the current playe...
def alpha_beta(grid, turn, alpha, beta): if checkWin(grid)!=None: return checkWin(grid) maxOutcome = -2 minOutcome = 2 moves = getPossibleMoves(grid) for move in moves: i = move[0] o = move[1] if(grid[i][o]==' '): if(turn==0): maxOutcome = ...
def test_random_performance_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) strat = RandomStrategy(official_list.copy(), set(), 5, 6) return test_performance(strat, official_list, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, up...
This function tests a random strategy's performance against the official Wordle list, updates analytics data if specified, and displays the results. It takes print_mode for output control, data for storage, and update to determine if analytics should be updated. The function calculates a new performance metric, stores ...
def handle_random_official(print_mode, data, update): new_value = test_random_performance_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.RANDOM_OFFICIAL.value, new_value) display_performance("Simple Filter", "Official Wordle List", new_value)
def test_simple_filter_performance_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) strat = SimpleFilterStrategy(official_list.copy(), set(), 5, 6) return test_performance(strat, official_list, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn,...
This function tests the performance of a "Simple Filter" strategy on the official Wordle list, calculates a new performance metric, updates analytics data if specified, and displays the result with labels "Simple Filter" and "Official Wordle List".
def handle_simple_filter_official(print_mode, data, update): new_value = test_simple_filter_performance_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.SIMPLE_FILTER_OFFICIAL.value, new_value) display_performance("Simple Filter", "Official Wordle List", new...
def test_simple_filter_performance_with_all_5_letter_words(print_mode): lst = get_all_5_letter_words(current_path) strat = SimpleFilterStrategy(lst.copy(), set(), 5, 6) return test_performance(strat, lst, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updated_value): ...
This function tests the performance of a simple filter handling all 5-letter words, updates analytics if specified, and displays results with a descriptive label.
def handle_simple_filter_all_5(print_mode, data, update): new_value = test_simple_filter_performance_with_all_5_letter_words(print_mode) if update: update_performance_analytics(data, Strats.SIMPLE_FILTER_ALL_5.value, new_value) display_performance("Simple Filter", "all 5 letter word list", new_value...
def test_smart_guess_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) strat = SmartGuessStrategy(official_list.copy(), set(), 5, 6) return test_performance(strat, official_list, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updat...
The code tests a "Smart Guess" strategy against the official Wordle list, calculates performance metrics, updates analytics if specified, and displays results. It evaluates how effectively the strategy solves Wordle puzzles using the official word list, tracking accuracy or efficiency.
def handle_smart_guess_official(print_mode, data, update): new_value = test_smart_guess_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.SMART_GUESS_OFFICIAL.value, new_value) display_performance("Smart Guess", "Official Wordle List", new_value)
def test_smart_guess_with_all_5_letter_words(print_mode): lst = get_all_5_letter_words(current_path) strat = SmartGuessStrategy(lst.copy(), set(), 5, 6) return test_performance(strat, lst, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updated_value): if strategy ...
The function tests a smart guessing strategy using all 5-letter words, evaluates its performance, updates analytics data if specified, and displays results with the strategy name and description.
def handle_smart_guess_all_5(print_mode, data, update): new_value = test_smart_guess_with_all_5_letter_words(print_mode) if update: update_performance_analytics(data, Strats.SMART_GUESS_ALL_5.value, new_value) display_performance("Smart Guess", "all 5 letter word list", new_value)
def test_index_decision_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) strat = IndexDecisionStrategy(official_list.copy(), set(), 5, 6) return test_performance(strat, official_list, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy,...
The code tests an index decision strategy against the official Wordle list, calculates a new performance value, updates analytics if specified, and displays the result for "Index Decision" with the "Official Wordle List" label.
def handle_index_decision_official(print_mode, data, update): new_value = test_index_decision_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.INDEX_DECISION_OFFICIAL.value, new_value) display_performance("Index Decision", "Official Wordle List", new_value)
def test_index_decision_with_all_5_letter_words(print_mode): lst = get_all_5_letter_words(current_path) strat = IndexDecisionStrategy(lst.copy(), set(), 5, 6) return test_performance(strat, lst, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updated_value): if str...
This function tests an index decision strategy using all 5-letter words, calculates its performance, and either updates analytics data or displays results based on the 'update' flag.
def handle_index_decision_all_5(print_mode, data, update): new_value = test_index_decision_with_all_5_letter_words(print_mode) if update: update_performance_analytics(data, Strats.INDEX_DECISION_ALL_5.value, new_value) display_performance("Index Decision", "all 5 letter word list", new_value)
def test_index_decision_with_simplified_5_list(print_mode): lst = get_simplified_5_list(current_path) strat = IndexDecisionStrategy(lst.copy(), set(), 5, 6) return test_performance(strat, lst, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updated_value): if strat...
The function `handle_index_decision_large` tests an index decision strategy using a simplified 5-letter list, retrieves a new performance value, updates the provided data with this value if the `update` flag is True, and displays the performance metrics for "Index Decision" under the "Large 5-Letter List" category. The...
def handle_index_decision_large(print_mode, data, update): new_value = test_index_decision_with_simplified_5_list(print_mode) if update: update_performance_analytics(data, Strats.INDEX_DECISION_LARGE.value, new_value) display_performance("Index Decision", "Large 5-Letter List", new_value)
def test_out_the_box_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) secret_list = get_official_guess_list(current_path) strat = ThinkOutsideTheBoxStrategy(official_list.copy(), secret_list.copy(), 5, 6) return test_performance(strat, official_list, secret_list, PE...
The main task of the code is to test the "Think Outside The Box" strategy against the official Wordle list using the provided print mode. If the 'update' flag is True, it updates performance analytics with the new result. It then displays the performance metrics with specific labels: "Think Outside The Box" and "Offici...
def handle_outside_the_box_official(print_mode, data, update): new_value = test_out_the_box_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.OUTSIDE_THE_BOX_OFFICIAL.value, new_value) display_performance( "Think Outside The Box", "Official Wordle Lis...
def test_out_the_box_with_simplified_5_list(print_mode): simplified_5 = get_simplified_5_list(current_path) secret_list = get_all_5_letter_words(current_path) strat = ThinkOutsideTheBoxStrategy(simplified_5.copy(), secret_list.copy(), 5, 6) return test_performance(strat, simplified_5, secret_list, PERFO...
The function evaluates a "Think Outside The Box" strategy for a large 5-letter list, generating a performance metric. If the 'update' flag is True, it updates analytics with the new value; otherwise, it displays the result.
def handle_outside_the_box_large(print_mode, data, update): new_value = test_out_the_box_with_simplified_5_list(print_mode) if update: update_performance_analytics(data, Strats.OUTSIDE_THE_BOX_LARGE.value, new_value) display_performance( "Think Outside The Box", "Large 5-Letter List with all...
def test_markov_with_official_wordle_list(print_mode): official_list = get_official_list(current_path) strat = MarkovStrategy(official_list.copy(), set(), 5, 6) return test_performance(strat, official_list, set(), PERFORMANCE_MARKER, print_mode) def update_performance_analytics(jsn, strategy, updated_value)...
This function evaluates a Markov strategy's performance on the official Wordle list by calculating a new value. If 'update' is True, it updates the provided data with this value under the 'MARKOV_OFFICIAL' strategy. It then displays the performance metrics for the Markov approach against the official Wordle list, showi...
def handle_markov_official(print_mode, data, update): new_value = test_markov_with_official_wordle_list(print_mode) if update: update_performance_analytics(data, Strats.MARKOV_OFFICIAL.value, new_value) display_performance("Markov", "Official Wordle List", new_value)
def load_dataset(data_dir, model_params, inference_mode=False): """Loads the .npz file, and splits the set into train/valid/test.""" # normalizes the x and y columns using the training set. # applies same scaling factor to valid and test set. if isinstance(model_params.data_set, list): datasets = model_pa...
The code trains a Sketch-RNN model by configuring GPU settings, loading datasets, initializing model architectures, setting up a TensorFlow session, resuming training from checkpoints if specified, saving hyperparameters, and executing the training loop with training/validation/test data.
def trainer(model_params): """Train a sketch-rnn model.""" np.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True) #Set cuda device os.environ["CUDA_VISIBLE_DEVICES"]=model_params.gpu_id tf.logging.info("Using gpu:" + os.environ["CUDA_VISIBLE_DEVICES"]) tf.logging.info('sketch-rnn') t...
def generateCurrentVersion(): generateVersionTo(currentVersion()) def applyGenToAcual(): global items global locations items = genItems locations = genLocations def save(): print("Saving") itemfile = open("items.csv", "w") for item in items: itemfile.write(item.name + ",") ...
The code defines a function that continuously listens for incoming socket connections, receives data from clients, processes it to update version information, and sends back aggregated content (item, location files, and current version) to the client. It handles data parsing, version management, and bidirectional commu...
def recieveInformation(): while True: soc.listen() conn, addr = soc.accept() print("Connection recieved from " + str(addr)) data = conn.recv(1024) if not data: break recievedData = repr(data) recievedData = recievedData[2:-1] print("Recieved " + reci...
def load(): global currentVersion try: open("items.csv", "r").close() except FileNotFoundError: open("items.csv", "w").close() try: open("locations.csv", "r").close() except FileNotFoundError: open("items.csv","w").close() itemfile = open("items.csv", "r") ro...
This code synchronizes data between a client and server. It connects to a server, sends updated version data if changes exist, receives new data, splits it into items/locations, writes them to CSV files, updates local data structures, and reloads the application state.
def sync(event): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((HOST, PORT)) if not currentVersion.itemDiff == "" and not currentVersion.locationDiff == "": currentVersion.finalise() print("Sending " + currentVersion.finalversion) soc.sendall(currentVersion.fin...
def triangle_check(a, b, c, A, B, C): """ Uses geometric properties of triangles to determine if a triangle using the given values is possible. Parameters: a, b, c (float) - Side lengths for the given triangle A, B, C (float) - Angle values for the given triangle. Must be in radians. Retur...
The function `solve` determines a triangle's remaining values (sides/angles) using given parameters, employing triangle postulates (SSS, SAS, ASA, etc.). It first validates inputs with `triangle_check`, then selects appropriate helper functions based on the provided values' combination. It adjusts result ordering to ma...
def solve(a, b, c, A, B, C): """ Solves for the remaining values of a triangle given at least 3 values. Takes the given values and first checks which combination was given. It is imperative that any undefined values are entered as None. Calls triangle_check() first to determine if the values create...
def get_rays(h, w, K, c2w): i, j = torch.meshgrid(torch.linspace(0, w - 1, w), torch.linspace(0, h - 1, h)) # pytorch's meshgrid has indexing='ij' i = i.t() j = j.t() # directions dirs = torch.stack([(i - K[0][2]) / K[0][0], -(j - K[1][2]) / K[...
This code renders images by processing rays through a neural network. It generates or uses input rays, applies transformations (like NDC), batches them, and returns rendered outputs such as RGB, depth, and accumulation maps. The method handles camera parameters, view directions, and chunked processing for efficient ren...
def render(self, H, W, K, chunk=1024 * 32, rays=None, c2w=None, ndc=False, c2w_staticcam=None): if c2w is not None: # special case to render full image rays_o, rays_d = get_rays(H, W, K, c2w) else: # use provided ray batch rays_o, rays_d = r...
def get_default_prompts_and_hints(default_prompt_json_path, task_name): with open(default_prompt_json_path, 'r', encoding='utf8') as f: default_prompts_and_hints = json.load(f) return default_prompts_and_hints[task_name]['input_templates'], default_prompts_and_hints[task_name]['hints'] def get_example...
The code generates instruction templates for benchmark tasks by leveraging multiple prompt generation strategies (rephrasing, chain-of-thought, task description generation, and gradual generation) using meta-prompts and examples. It processes task-specific data, applies templates from a meta-prompts module, and saves t...
def generate_prompts(prompts_outpath, task_info_folder_path, default_prompts_and_hints_json_path, meta_prompts_module_path, task_names, num_calls_rephrase, num_calls_chain_of_thought, num_calls_task_description_generation, num_calls_gradual_generation, deri...
def _read_batcheff(self): if len(self.batch_files) == 1: batch_data, batch_names = self._read_factorize_data(self.batch_files[0]) else: list_batch = list() for one_file in self.batch_files: one_file_batch_data, one_file_batch_names = self._read_factori...
This code initializes a data handler by reading input files, processing batch effects, converting data to tensors, and setting up a TensorDataset for machine learning. It reads data and labels, checks dimensions, and prepares dataset splits. Key steps include loading data, handling batch-specific information, tensor co...
def __init__(self, batch_size: int, data_folder: str, data_file: str, label_file: str, batch_files: Optional[list] = None, doubles=False) -> None: # input file paths self.data_file = data_file self.batch_files = batch_files self.label_file = lab...
def clean_status(self): self._seen_edges = set() self._seen_input_names = set() self._predictions = OrderedDict() def get_node_names(node): return node.type().str().split(".") def make_graph( self, module, dot=None, parent_dot=None, prefix="", ...
The main task of the code is to generate a visual graph representation of a machine learning model's structure using the Digraph class. It cleans the module's state, identifies the model type from input nodes, creates a graph with specified formatting and labels, and constructs the graph by traversing designated classe...
def render( self, classes_to_visit={"YOLO", "YOLOHead"}, format="svg", labelloc="t", attr_size="8,7", ): self.clean_status() model_input = next(self.module.graph.inputs()) model_type = self.get_node_names(model_input)[-1] dot = Digraph( ...
def load_library(self, limit): """From the parent_dir, loads pgns and their summaries into a dataframe. TODO - Speed up, using multiprocessing.""" library = [] library_files = list(Path(self.parent_dir).rglob("*.[tT][xX][tT]")) print(f"Loading library ({len(library_files)} file...
The code initializes a class by setting the parent directory, extracting a username from the directory path, loading a dataset with a specified limit into a DataFrame, processing chess openings, and loading game data. The main task is to set up initial data and configurations for further processing or analysis.
def __init__(self, parent_dir, limit = 2000): self.parent_dir = parent_dir self.username = parent_dir.split('/')[-1] self.df = self.load_library(limit) self.get_chcom_openings() self.load_games()
def make_directions(self): self.possible_directions = ['right', 'left', 'up', 'down'] for block in env.group_blocks: if (block.check_point((self.rect.topright[0] + 7, self.rect.topright[1])) or block.check_point( (self.rect.bottomright[0] + 7, self.rect.bottomright[1]))) ...
This code updates an object's position by determining movement direction, wrapping around screen edges if out of bounds, and applying movement based on current direction if the game isn't over. It also adjusts speed and updates coordinates using difference_x and difference_y.
def update(self, *args): self.make_directions() self.change_direction(*args) if self.rect.left > settings.WIDTH: self.rect.right = 0 elif self.rect.right < 0: self.rect.left = settings.WIDTH elif self.rect.bottom < 0: self.rect.top = settings.H...
def _parse_manifest_for_dynamic_models(self): """Return only parts of the manifest that contain a dynamic models key""" return { k: v for k, v in self.manifest.to_dict()['files'].items() if v['parse_file_type'] == 'schema' and 'dynamic_models' in v['dfy'].keys() ...
The code processes dynamic models by parsing configurations, iterating through parameters, formatting SQL queries, and writing or testing them. It raises an error if no models are found, then compiles SQL for testing or writes outputs based on formatted model names, locations, and queries.
def execute(self): """Entrypoint to this class""" schema_dict = self._parse_manifest_for_dynamic_models() if not schema_dict: raise RuntimeError('No dynamic models found in your project') for _, dct in schema_dict.items(): dynamic_models = dct['dfy']['dynamic_mod...
def authenticate_user(self, reader, writer): writer.send( M_WELCOME( time=time.time(), msg=f'Players currently connected: {", ".join(self.player_map)}' ) ) writer.send( M_SERVER_CHAT( time=time.time(), ...
The main task of the code is to handle a user connection by authenticating the user, setting up input/output streams, and preparing the user for a game. If authentication fails, it cleans up resources and exits. Otherwise, it queues the user and waits for the game to start via a mainloop.
def handle_connection(self, conn): reader = get_struct_reader(conn) writer = get_struct_writer(conn) username = self.authenticate_user(reader, writer) # Clean up if authentication fails. if username is None: reader.close() writer.close() retu...
def setJsonConfigPath(): global _FILE_NAME print(sys.argv) if len(sys.argv) > 2: print("* Loading configuration file: ", sys.argv[1]) _FILE_NAME = sys.argv[1] def displayBanner(): print('***** Utility for compiling the respective source *****') print('Copyright 2020 AionDigital') def...
The main task of the code is to automate container builds and S3 uploads for multiple services using a JSON config. It sets up credentials, clones a Git repo, prunes existing images, recycles temp directories, and iterates through service configurations to build Docker containers, handling Git errors. The process ensur...
def main(): # Step 1: Set JSON configuration path setJsonConfigPath() #Step 2: Display banner displayBanner() #Step 3: Input User Source Control Credentials getUserInput() # Step 4: Read JSON config file data = loadConfig() #Step 4: Prune all existing images ...
def single_field(self, item, key, label): if (item[key] != None and item[key] != ""): self.item.append({"field": key, "value": item[key], "label": label}) return def get_provincie(self, id): retList = [] list = self.get_data("SELECT provincie FROM vereniging_provincie WHERE v...
This code retrieves a specific record from the 'vereniging_vereniging' database table using an ID, processes its fields (e.g., names, dates, relations), and returns structured data. It fetches related information like province, scope, and relations, formats fields, and compiles results into a return value for output or...
def detail(self, id): cur = self.conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("SELECT * FROM vereniging_vereniging WHERE id = " + id) record = cur.fetchone() self.single_field(record, "naam", "Naam") self.single_field(record, "opm_naam", "Opmerkingen naa...
def show_message(self, message): print(f"\n{message}\n") def verify_account(self, acc_num): for bank_acc in self.bank_accounts: if int(acc_num) == bank_acc["account_number"]: return bank_acc return None def get_username(self, acc_details): if acc_details: ...
The main task of the code is to handle user transactions for a banking system. It verifies the user's account, prompts for account type and transaction options (withdraw, deposit, check balance), collects input (amount, PIN), processes the transaction, and displays the available balance after the operation.
def main(self): self.show_message("Welcome to DnD Bank Ltd") user_input = input("Enter Account Number: ") self.verified_acc = self.verify_account(user_input) if not self.verified_acc: self.show_message("Account number not found.") return self.sho...
def create_instance_triple(data: dict, base_url=None): entity=None o_class=None parent=None if all(prop in data.keys() for prop in ['@type']): instance_id = str(data['@id']) o_class = get_obis_entity(data['@type']) if o_class: entity=URIRef(instance_id, TEMP) ...
The code converts JSON data into an RDF graph by recursively processing nested structures, creating entities and properties, and establishing relationships. It handles identifiers, custom properties, date formatting, and specific entity links (e.g., projects, spaces) while ensuring proper ontology alignment. The functi...
def iterate_json(data, graph, last_entity=None, base_url=None): if isinstance(data, dict): # lookup if the id and type in dict result in a ontology entity entity, e_class, parent = create_instance_triple(data, base_url=base_url) if entity and e_class: # if the entity is a Identif...
def initialize_board(rows, cols): board = [] for r in range(rows): board.append([0 for c in range(cols)]) return board def print_puzzle(board): for row in range(len(board)): print(board[row][:]) def solve(board, col): if col == len(board[0]): return True options = getOptions(boar...
The main task of the code is to solve a puzzle board of user-specified dimensions. It prompts for rows and columns, initializes the board, displays it, attempts to solve it using a `solve` function starting from position 0, and outputs "solved Hurray!" with the solution if successful, or "can not be solved" otherwise.
def main(): print("enter board size: ") n_rows = int(input()) n_cols = int(input()) print("solving") board = initialize_board(n_rows, n_cols) print_puzzle(board) print("solving...") if solve(board, 0): print("solved Hurray!") print_puzzle(board) else: pri...
def get_ordered_reads(read1, read2): """ Reorient reads The sequencing is usually not oriented. Reorient the reads so that r1 is always before r2. Sequencing is always performed from 5' to 3' end So in unstranded case, we can have 1 2 ---> ---> ========== or...
This function calculates the DNA fragment library size based on paired-end reads and their restriction fragment overlaps. It uses the interaction type (DE, RE, SC, VI) to determine the calculation method: subtracting read positions for DE/RE, summing distances from fragment ends for SC, and combining strand-specific di...
def get_PE_fragment_size(read1, read2, resFrag1, resFrag2, interactionType): """ Calculte the size of the DNA fragment library read1 : [AlignedRead] read2 : [AlignedRead] resfrag1 = restriction fragment overlapping the R1 read [interval] resfrag1 = restriction fragment overlapping the R1 read [...
def is_self_circle(read1, read2): """ Both reads are expected to be on the same restriction fragments Check the orientation of reads <--> read1 : [AlignedRead] read2 : [AlignedRead] """ ret = False # Get oriented reads r1, r2 = get_ordered_reads(read1, read2) # 1<- ->2 or 2<- ->...
This function classifies 3C interaction types between read pairs based on restriction fragment overlaps. It returns "SC" (self-circle), "DE" (dangling end), "RE" (religation), "VI" (valid interaction), or "SI" (single insert) by checking: 1) same fragment (SC/DE), 2) different fragments (RE/VI), or 3) unmapped reads (S...
def get_interaction_type(read1, read1_chrom, resfrag1, read2, read2_chrom, resfrag2, verbose): """ Returns the interaction type For a given reads pair and their related restriction fragment, classify the 3C products as : - Interaction - Self circle - Dangling end ...
def get_platform(): if sys.platform == "darwin": if "arm64" in out("uname -m"): return "mac-arm64" return "mac-x64" elif sys.platform.startswith("win"): return "win32" elif "linux" in sys.platform: return "linux64" def get_version(): platform = get_platform() if "mac" in ...
This code downloads the appropriate ChromeDriver version for the detected platform, extracts it from a ZIP archive, sets execute permissions on macOS, and outputs the installation path. It dynamically constructs download URLs, parses XML to identify correct files, and handles platform-specific configurations.
def download_and_unzip(): platform = get_platform() version = get_version() url = get_download_page() if isinstance(version, int): url = url.replace("index.html?path", "?delimiter=/&prefix") soup = BeautifulSoup(requests.get(url).text, features="xml").find_all("Key") keys = [f"https://chro...
def find_vial_devices(): for desc in hid.enumerate(): if VIAL_SERIAL_NUMBER_MAGIC in desc["serial_number"] and is_rawhid(desc) and is_vialrgb(desc): return desc def vialrgb_get_modes(dev): """ Retrieve list of supported modes from the keyboard """ data = hid_send(dev, struct.pack("BB", ...
The main task of the code is to create a GUI application for direct LED control of a VialRGB keyboard. It detects the device, checks compatibility, initializes a Pygame window, and allows users to navigate and modify LED colors in real-time via keyboard input, rendering the LED matrix and updating the device's lighting...
def main(): desc = find_vial_devices() if desc is None: print("failed to find any VialRGB devices!") return 1 print("Trying {} {}".format(desc["manufacturer_string"], desc["product_string"])) dev = hid.device() dev.open_path(desc["path"]) # Check this keyboard supports direct c...
def fit(self,X,y,alpha=0.1,lr=0.00001,epochs=1000): #X batch,features #y batch,1 optimizer = torch.optim.SGD(self.parameters(), lr=lr) for epoch in range(epochs): optimizer.zero_grad() outputs = self.forward(X) loss = torch.sum((outputs-y)**2)+alpha*t...
This code performs nested cross-validation to tune a model's hyperparameter 'alpha'. It uses an outer loop for evaluation and an inner loop to select the optimal 'alpha' by training/validation. The best 'alpha' for each outer fold is applied to the training set, then tested on the holdout set. Results include best alph...
def tune(self,X,y,kfold=5,alpha_range=[-5,5],lr=0.00001,epochs=1000): inner_fold = KFold(n_splits=kfold, shuffle=False) outer_fold = KFold(n_splits=kfold, shuffle=False) alpha_range = np.logspace(alpha_range[0],alpha_range[1],kfold) result_dict = {'best_alphas':[],'best_scores':[],'y_pre...
def _make_rhomat(rho_Tg=0.0, rho_Tv=0.0, rho_TM=0.0, rho_gv=0.0, rho_gM=0.0, rho_vM=0.0): rhomat = np.array([[1.0, rho_Tg, rho_Tv, rho_TM], [rho_Tg, 1.0, rho_gv, rho_gM], [rho_Tv, rho_gv, 1.0, rho_vM], [rho_TM, rho_gM, rho_vM, 1.0]]) return rh...
This function computes abundance tables and errors from line data after calculating uncertainties, using a correlation matrix (rhomat) to account for correlated stellar parameter errors (T, g, v, M). It processes line measurements, summarizes abundances, applies upper limits, and returns the final tables.
def process_session_uncertainties(session, rho_Tg=0.0, rho_Tv=0.0, rho_TM=0.0, rho_gv=0.0, rho_gM=0.0, rho_vM=0.0): """ After you have run session.compute_all_abundance_uncertainties(), this pulls out a big array of line data and computes the final abundance table and e...
def get_nearest_available_column(self, index: int) -> int: if index >= self.cols_count: index = self.cols_count - 1 if self.is_col_full(index): if index == 0: index += 1 elif index == self.cols_count - 1: index -= 1 ...
This code handles a player's turn in a game, determining the current player (AI or human), processing their move (random, follow, opposite strategies for AI or user input), updating the game board with the token, and incrementing the turn counter.
def play(self) -> None: current_player = self.first_player if self.first_player.playing else self.second_player print(f'Number of turn played: {self.turn}') print(f"{current_player.name} {current_player.color} turn...") index = -1 if current_player.ai_move: ai_move =...
def __initialize_weights(self): for weight_layer in range(0, len(self.weights)): self.weights[weight_layer] = np.random.uniform(-1, 1, (len(self.weights[weight_layer]), len(self.weights[weight_layer][0]))) def __feed_in_input(self, X): for i in range(0, len(X)): self.deep_layers[...
This code trains a neural network using backpropagation by iterating over epochs and examples, updating weights based on error gradients. It tracks training and test accuracy for each epoch, prints progress, and returns accuracy lists.
def fit(self, X, Y, X_Test = [], Y_Test = []): self.__initialize_weights() #Collecting stats train_acc = [] test_acc = [] for epoch in range(0, self.epochs): for example in range(0, len(X)): self.__feed_in_input(X[example]) self.__fee...
def __plurality_value(self, examples): unique, indices = np.unique(examples[1], return_inverse=True) return unique[np.argmax(np.bincount(indices))] def __importance(self, examples, attributes): #Keeping track of the attribute that maximizes the information that's gained argmax_attribute...
This function recursively constructs a decision tree by selecting the most important attribute, splitting the dataset based on its values, and creating subtrees for each subset. It handles base cases like empty examples, uniform classifications, or no remaining attributes by returning leaf nodes. The tree nodes are bui...
def __learn_tree(self, examples, attributes, parent_examples): #If the examples(X vector/Y vector) are empty if (len(examples[0]) == 0 or len(examples[1]) == 0): return DT_leaf_node(self.__plurality_value(parent_examples)) #If the Y vector passed in all have the same classifiction ...
def add_custom_collaborative_filtering_config(dku_config, config, file_manager): add_scoring_config(dku_config, config, file_manager) dku_config.add_param( name="similarity_scores_type", value=config.get("similarity_scores_type"), required=True, cast_to=SIMILARITY_TYPE, ) ...
The function `create_dku_config` generates a `DkuConfig` object tailored to a specified recipe type (`recipe_id`). Depending on the recipe (e.g., affinity score, sampling, collaborative filtering), it applies corresponding configuration settings using helper functions. The configured object is logged and returned for u...
def create_dku_config(recipe_id, config, file_manager=None): dku_config = DkuConfig() if recipe_id == RECIPE.AFFINITY_SCORE: add_custom_collaborative_filtering_config(dku_config, config, file_manager) elif recipe_id == RECIPE.SAMPLING: add_sampling_config(dku_config, config, file_manager) ...
def get_checkbox_true(ipy_sheet): """Get DataFrame with the rows where checkbox was set to True from the ipysheet sheet. Args: ipy_sheet (ipysheet sheet): Ipysheet sheet with the column called "Checkbox" with the checkbox. Returns: DataFrame: Pandas DataFrame with the rows where the checkb...
The main task of the code is to generate an editable final sheet (ipysheet) containing selected personnel data from a checked checkbox sheet, merged with company data. It creates a formatted sheet for corrections, returning an empty DataFrame with predefined columns if errors occur or data is missing.
def get_final_sheet(sheet_people_checked, df_company, height="300px", width="960px"): """Generates a final sheet for implementation of final corrections from the sheet with checked checkboxes. Args: sheet_people_checked (ipysheet sheet): Full ipysheet with filled checkboxes for item we choose. ...
def wrap(s, w): return [s[i:i + w] for i in range(0, len(s), w)] def createBorder(): global img global row global col borderType = cv.BORDER_CONSTANT TDLU = [0, 1, 0, 1] img = cv.copyMakeBorder(img, TDLU[0], TDLU[1], TDLU[2], TDLU[3], borderType, None, 255) row, col = img.shape def gene...
The code reads a grayscale image, initializes parameters, generates binary data, splits it into chunks, processes image dimensions for padding, creates rotations, preprocesses data, and invokes an ECO function for further processing, likely related to image transformation or encryption.
def main(): global img global row global col global windowSize global plane global hPath global dataRotations global hBlock path = "lena.jpg" img = cv.imread(path, 0) row, col = img.shape windowSize = 3 plane = 1 hPath = [1, 2, 3, 6, 9, 8, 7, 4, 5] data = ['1'...
def get_column_formats(self): """ Gets the formats to use for each column. """ format_actions = {} for column in self.col_idx.keys(): actions = self.format_picker(column) if column not in format_actions.keys(): format_actions[column] = acti...
This function formats a spreadsheet cell based on predefined column-specific rules, applying number formats (percent, currency, decimal, etc.), alignment, borders, and fill colors. It checks formatting instructions for the given column and updates the cell's style accordingly, while tracking if changes need to be saved...
def format_cell(self, column: str, row_i: int, col_i: int): """ Formats a cell based on the `column` name using `row_i` and `col_i`. """ # TODO add test for this cell = self.cur_sheet.cell(row=row_i, column=col_i) # gets format_actions if it has not be set yet if ...
def get_article_ref(self): href_article_references = [] try: href_article_references = WebDriverWait(self.browser, self.time_wait).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, '#referenceSrhResults'))).get_attribute('href') except (No...
The main task of the code is to fetch secondary information about a paper, including its references, related documents, and citing documents. It uses browser automation to navigate to specific URLs, scrapes Scopus data, and returns the results in a dictionary with default 'NA' values if data is missing.
def get_secondary_info(self): href_article_references = self.get_article_ref() if self.paper_reference is True else [] href_related_papers = self.get_article_related_doc() if self.related_document is True else [] href_cited_by_doc = self.get_cited_by_doc() if self.cited_document is True else []...
def get_title_theme(self, text_to_find_c): text_to_find = text_to_find_c.lower() res = len(text_to_find.split()) for k, v in self.menu.items(): title_theme = v['title'].lower() if title_theme in text_to_find: if res == 1: xpath_title =...
This function automates searching on Scopus by inputting a search term, selecting a search type via XPath locators, and scraping results. It validates input, configures search parameters, navigates to the base URL, executes the search, and returns flattened scraped data from Scopus' document search interface.
def scrape_via_search_term(self, keyword=None, search_term=None): if search_term is None: raise Exception("No search term provided") else: self.search_term = search_term text_to_find_c = keyword if keyword is not None else 'Article title, Abstract, Keywords' se...
def _make_frozen_graph( behavior_name: str, graph: tf.Graph, sess: tf.Session ) -> tf.GraphDef: with graph.as_default(): target_nodes = ",".join(_process_graph(behavior_name, graph)) graph_def = graph.as_graph_def() output_graph_def = graph_util.convert_variables_to_constants( ...
The function exports a TensorFlow policy model to .nn and/or .onnx formats for Unity embedding. It freezes the input graph, saves it as a .pb file, converts it to .nn using tf2bc (if enabled), and attempts ONNX conversion (if supported). Error handling ensures compatibility, with fallbacks for missing dependencies. The...
def export_policy_model( model_path: str, output_filepath: str, behavior_name: str, graph: tf.Graph, sess: tf.Session, ) -> None: """ Exports a TF graph for a Policy to .nn and/or .onnx format for Unity embedding. :param output_filepath: file path to output the model (without file suffi...
def rpc_reconnect(handler): logging.info('reconnecting;' + handler.request.remote_ip + ';' + handler.id) rpc = tornado.httpclient.AsyncHTTPClient() try: account = rdata.hget(handler.id, "account").decode('utf-8') except: logging.error( 'reconnect error, account not seen on th...
This code processes incoming messages by validating client rate limits, logging requests, and handling various RPC actions (e.g., subscriptions, price data, account checks). It parses JSON messages, executes corresponding functions for allowed actions, enforces rate control, and logs errors or exceptions, ensuring prop...
def on_message(self, message): address = str(self.request.remote_ip) now = int(round(time.time() * 1000)) if address in mesg_last: if (now - mesg_last[address]) < 25: logging.error('client messaging too quickly: ' + str( now - mesg_last[address]) +...
def make_test_map(index: int) -> Map: return Map( name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}" ) def make_test_map_xml(name: int, index: int) -> ElementTree.Element: return make_element_with_children( "Button", { "id": f"Test Map {name}"...
This test verifies that the `get_map_elements` function correctly generates a specific XML structure for a map with one item. It compares the actual output against an expected `ToggleGroup` element containing a child map element, ensuring proper formatting and attributes like `id` and `active` are correctly applied.
def test_map_generation_1(): actual = get_map_elements([make_test_map(1)]) expected = [ make_element_with_children( "ToggleGroup", {"id": "fanMapButtons1", "active": "False"}, [ make_test_map_xml(name=1, index=0), ], ) ] a...