dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def stress_test(num_tests=1, verbose=True): """ Generate random problem and solve Args: num_test (int): number of tests to perform Returns: int: number of failed tests """ failed_tests = [] for i in range(int(num_tests)): nv = random.randrange(50, 10000) ...
The `main` function parses command-line arguments to control test execution. It runs all tests if no arguments are provided, or specific tests if names are given. Flags like `-nv` (non-verbose), `-np` (set processes), and `-st` (stress test) modify behavior. Stress tests execute a specified number of test runs, reporti...
def main(argv): """ Parses command line options and runs tests Empty commandline runs all tests Otherwise individual tests can be specified by name Pass in '-nv' with args to remove additional information Args: argv (list): command line parameters Returns: int: number ...
def writeSummaryExcel(sheet, allVideos, daysOfTheWeek, dailyTeamPoints): # Stats Summary writeHeaderRowExcel(sheet, ['Total Players', 'Total Videos', 'Reviewed', 'Unreviewed']) row = 2 reviewedCount = len([vid for vid in allVideos if vid.get('reviewed')]) sheet.cell(row=row, column=2, value=len(allV...
This function generates a weekly Excel report summarizing video data, including team points, pending reviews, parsing errors, CHIMP awards, and upload day mismatches. It creates a timestamped output directory, constructs a multi-sheet workbook with specific data sheets, and saves the report as an Excel file.
def createReport(allVideos, chimpList, videosPendingReview, videosNeedFixing, weekNumber: int, dayOfWeekNames, dailyTeamPoints): now = datetime.datetime.now() timestamp = "{}.{}.{}.{}.{}.{}".format(now.year, now.month, now.day, now.hour, now.minute, now.second) outputPath = os.path.join('output', timestamp)...
def loadDriveApi(): SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) drive =...
The main task of the code is to retrieve and process Google Drive data for a VanCity Pro challenge, categorizing videos by team, identifying entries needing fixes or review, updating points for reviewed videos, and generating summaries/reports with weekly statistics, team points, and video status tracking.
def main(): global pageToken gdriveApi = loadDriveApi() print("--------------------------------------------------------------------") print("VanCity Pro Stay Home Stay Safe Challenge Drive Data for Week {}".format(getWeekNumber())) print("------------------------------------------------------------...
def loadDriveApi(): SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) DRIVE =...
The code's main task is to retrieve and process video data from Google Drive folders, skip specified folders, collect team video information, and generate summaries of reviewed/unreviewed videos, points, and failures, using the Drive API for data access and iteration.
def main(): global pageToken DRIVE = loadDriveApi() while True: print("--------------------------------------------------------") print("Getting Drive Data") print("--------------------------------------------------------") uploadVidsFolderId = getRootFolderId(DRIVE) ...
def load_downsampled_model(downsampling): assert downsampling in ALL_MODEL_DOWNSAMPLINGS filename = 'models/tsu_{:02d}.uai.gz'.format(downsampling) return load_uai(filename) def convert_to_lp(nodes, edges): lp = pulp.LpProblem('GM') # populate LP mu_N = [] # label pick vector Vertices mu_E ...
The code evaluates different downsampled models by solving linear and integer linear programming problems, recording metrics like variables, constraints, optima values, and inference time, then displaying results in a formatted table for comparison.
def exercise_2_5(): table = {"Model": [], "Image Dimensions": [], "#vars": [], "#contrs": [], "LP optima": [], "ILP optima": [], "Inference Time": []} dimensions = [(384, 288), (192, 144), (96, 72), (48, 36), (24, 18), (12, 9)] f...
def get_params(self, option='classifier'): """ Check if user provided parameters for the classifier. If not, get the default value from the PulsnarParams.py file """ # check if param file was provided by user? param_file = False config = None if self.pulsn...
The function processes data for a machine learning model, estimating parameters (alpha) through clustering, cross-validation, and calibration. It splits data into labeled/unlabeled subsets, trains classifiers per cluster, evaluates performance metrics (AUC, F1, accuracy), and aggregates results. Key steps include featu...
def snar_data_processing(self, X, Y, Y_true, mv_list): """ Process scar data and return results """ # local variables to store results est_alphas = [] res = {} clf_bs = [] clf_aps = [] clf_auc = [] clf_f1 = [] clf_mcc = [] c...
def add_unique_words_to_documents(documents, num_of_words_to_add, num_of_words_from_category): ultimate_list = create_list_of_unique_words(num_of_words_from_category) f = open("boosteddata.csv", 'w') f.write('boosted,mock \n') for sentence in documents: if isinstance(sentence, str): ...
The function processes text data by loading Polish stop words, augmenting them with custom terms from files, and applying TF-IDF vectorization on boosted document data. It then performs K-means clustering with PCA on processed features and input data, aiming to optimize text clustering through customized preprocessing ...
def ultimate_loop_of_optimalization_kmeans(df_processed, documents, num1, num2, num3): stop_words_pl = pd.read_csv('https://raw.githubusercontent.com/bieli/stopwords/master/polish.stopwords.txt', header=None) stop_words_pl = set(stop_words_pl[0].values) klient = open("klient....
def add_unique_words_to_documents(documents, num_of_words_to_add, num_of_words_from_category): ultimate_list = create_list_of_unique_words(num_of_words_from_category) f = open("boosteddata.csv", 'w') f.write('boosted,mock \n') for sentence in documents: if isinstance(sentence, str): ...
The main task of the code is to process text data by integrating custom stop words, adding specific terms to documents, generating TF-IDF features, and applying DBSCAN clustering with PCA for optimal text clustering. It combines preprocessing, feature extraction, and clustering to analyze document structures.
def ultimate_loop_of_optimalization_dbscan(df_processed, documents, num1, num2, num3): stop_words_pl = pd.read_csv('https://raw.githubusercontent.com/bieli/stopwords/master/polish.stopwords.txt', header=None) stop_words_pl = set(stop_words_pl[0].values) klient = open("klient....
def write_archive(self, timestamp): """ Write an archive record """ if timestamp == None: # Complete and close self.pmi.pmiEnd() self.pmi = None return if self.pmi == None: # Create a new archive self.pmi = pmi.pmiLogImport...
This function reports metric values by formatting a timestamp and writing the data to a specified output destination, such as an archive, CSV file, standard output, or Zabbix. It checks the `self.output` value to determine which writing method to use, ensuring the timestamp is properly formatted before passing it to th...
def report(self, tstamp): """ Report the metric values """ if tstamp != None: tstamp = tstamp.strftime(self.timefmt) if self.output == OUTPUT_ARCHIVE: self.write_archive(tstamp) if self.output == OUTPUT_CSV: self.write_csv(tstamp) if self.outp...
def parse_metric_info(self, metrics, key, value): """ Parse metric information """ # NB. Uses the config key, not the metric, as the dict key if ',' in value or ('.' in key and key.rsplit(".")[1] not in self.metricspec): # Compact / one-line definition spec, insts = self....
This function constructs and prepares a set of metrics by reading configuration files, parsing global and command-line specified metrics, validating their existence, and combining them into a unified metrics set for further processing. It handles error cases like missing metrics or configurations and organizes metric d...
def prepare_metrics(self): """ Construct and prepare the initial metrics set """ metrics = self.opts.pmGetOperands() if not metrics: sys.stderr.write("No metrics specified.\n") raise pmapi.pmUsageErr() # Read config config = ConfigParser.SafeConfigParser(...
def get_local_tz(self, set_dst=-1): """ Figure out the local timezone using the PCP convention """ dst = time.localtime().tm_isdst if set_dst >= 0: dst = 1 if set_dst else 0 offset = time.altzone if dst else time.timezone currtz = time.tzname[dst] if offset: ...
The code's main task is to fetch and report performance metrics using a PMAPI context (host or archive), configure output formatting (delimiter, timezone, headers), handle time-related settings, and iteratively retrieve and output metric data while adhering to specified intervals, sample counts, and output modes like C...
def execute(self): """ Using a PMAPI context (could be either host or archive), fetch and report the requested set of values on stdout. """ # Set output primitives if self.delimiter == None: if self.output == OUTPUT_CSV: self.delimiter = CSVSEP ...
def TaskExecution(self): wish() error = "There is an error, Please try again later" while 1: self.query = self.takecommand().lower() while self.query == "none": speak("Pleas say that again") self.query = self.takecommand().lower() ...
The code defines a `run` method that continuously listens for voice commands. It executes tasks via `TaskExecution()` when a "wake" command is detected, handles a "sleep" command by re-prompting for input, and terminates the program with a farewell message upon receiving "break," "stop," "exit," or "goodbye," ensuring ...
def run(self): self.TaskExecution() while True: self.query = self.takecommand().lower() if "wake" in self.query: self.TaskExecution() elif "sleep" in self.query: self.query = self.takecommand().lower()\ elif "break" in s...
def get_result_set(db, sql): """The executes a passed SQL command and returns a result set. If INSERT or UPDATE is detected, a write is assumed and a commit is also performed. Args: sql (string): SQL command Returns: list: a result set resulting from the execution of the SQ...
The main task of the code is to check if the "miscreated.db" database exists in a path without spaces, retrieve base and vehicle data, calculate vehicle ownership, and log details of owned vehicles with their positions. If no vehicles are owned, it informs the user.
def main(): """ Summary: Default method if this module is run as __main__. """ logging.basicConfig(level=logging.INFO) script_path = os.path.abspath(os.path.dirname(sys.argv[0])) # Check to see if the path includes a space and exit if it does if script_path.find(' ') >= 0: logging....
def parse_input(data): valves = dict() for line in data: parts = line.replace('Valve ', '').replace('has flow rate=', '').replace('tunnels lead to valves ', '').replace('tunnel leads to valve ', '').split('; ') name, flow_rate = parts[0].split(' ') flow_rate = int(flow_rate) tunnels = parts[1].spl...
The code simulates a valve-opening problem to maximize pressure release. It reads input data, parses valve connections, and calculates optimal paths starting from 'AA'. Part 2 (active) uses a 26-minute time limit with two parallel explorations, tracking pressure via the `next_move` function. The result is the maximum p...
def main(): with open('input_data.txt', 'r') as input_data: rows = [line.strip() for line in input_data.readlines()] valves = parse_input(rows) starting_point = 'AA' valves_to_open = find_valves_to_open(valves) # time_limit_p1 = 30 # last_visited_p1 = [Step({1: {starting_point: 0}}, 0, {}, set())] ...
def set_rocks(data): rocks = set() for line in data: last_point = None for point in line: point = point.split(',') x, y = int(point[0]), int(point[1]) point = (x, y) rocks.add(point) if last_point: x_last, y_last = last_point if x_last != x: dif_x = x...
The code reads input data representing rock formations, processes them into coordinates, identifies the lowest rock position, and simulates sand units falling until they rest. It calculates two results: part 1 counts sand units before they pile up, while part 2 adds an extra unit after adjusting the lowest rock positio...
def main(): with open('input_data.txt', 'r') as input_data: rows = [line.strip().split(' -> ') for line in input_data.readlines()] rocks = set_rocks(rows) lowest_rock = find_lowest(rocks) print('part 1:', sand_unit_counter(rocks, lowest_rock, part=1)) print('part 2:', sand_unit_counter(rocks, lowest_r...
def create_user(num=1): user = [{"full_name": fake.name()} for x in range(num)] return user def replace_dict(old_values, new_values): return dict(zip(old_values, new_values)) def overwrite_excel(file_name, sheets, data): sheets_dict = dict(zip(sheets, data)) book = openpyxl.load_workbook(file_name) ...
The main task of the code is to process and anonymize PEARS data exports by replacing real user and site information with fake data. It cleans user exports, generates synthetic data for sites, and applies consistent replacements across multiple modules (e.g., Program Activities, Partnerships, Coalitions). The cleaned d...
def main(export_dir=EXPORT_DIR, test_inputs_dir=TEST_INPUTS_DIR, test_pears_dir=TEST_INPUTS_PEARS_DIR, test_coalition_surveys_dir=TEST_COALITION_SURVEY_EXPORTS_DIR): creds = utils.load_org_settings() # Download all PEARS S3 objects for today utils.download_s3_exports(profile=creds['aws_profile'],...
def __possibleSplitValues(self, feature_values: np.ndarray): features_copy = np.copy(feature_values) features_copy.sort() possible_vals = [] for i in range(features_copy.shape[0] - 1): diff = (feature_values[i + 1] + feature_values[i]) / 2 if diff == feature_value...
The function identifies the optimal split value for a given feature in the training data by evaluating all possible split points. It calculates information gain for each split, selecting the value that maximizes this gain to discretize the feature domain. The process stops early if a perfect split (information gain = 1...
def __bestFeatureSplitValue(self, train_set: np.ndarray, feature_index): """ will choose the best value to split the the feature domain for discretisation :param train_set: training set :param feature_index: index of column in train_set to which you want to find the best aplit value ...
def train(self, train_set: np.ndarray): """ trains the model :param train_set train set given as a numpy.ndarray of dimension (#number of samples, number of features + 1) where the first column is the label (1/0). :returns: classifier of type PersonalizedDecisionT...
The function trains a model on the provided training data (with labels) and predicts classifications for the test data (without labels), returning a numpy array of predicted class labels for each test sample.
def fit_predict(self, train_set: np.ndarray, test_set: np.ndarray) -> np.ndarray: """ this function will train the model on the train_set and the return a classification for each item in the test_set :param train_set: train set given as a numpy.ndarray of dimension (#number of sample...
def train(self, train_set: np.ndarray): """ trains the model :param train_set train set given as a numpy.ndarray of dimension (#number of samples, number of features + 1) where the first column is the label (1/0). :returns: classifier of type DecisionTreeClassifie...
The main task of the code is to train a model on the labeled `train_set` (with features and class labels) and use the trained model to predict classifications for the unlabeled `test_set` (with only features). The function returns a numpy array containing predicted class labels for each sample in the test set.
def fit_predict(self, train_set: np.ndarray, test_set: np.ndarray) -> np.ndarray: """ this function will train the model on the train_set and the return a classification for each item in the test_set :param train_set: train set given as a numpy.ndarray of dimension (#number of sample...
def __countLabels(self, train_set: np.ndarray): num_true, num_false = 0, 0 for row in train_set: if row[0] == 0: num_false += 1 else: num_true += 1 return num_true, num_false def __chooseNextFeature(self, train_set: np.ndarray): """...
This function recursively constructs a decision tree node by checking if the training set is homogeneous (all same labels), creating a leaf node if true. Otherwise, it selects the optimal feature to split on, creates a decision node, splits the data, and recursively builds left/right child nodes. It returns the root no...
def __developNode(self, train_set: np.ndarray): """ recursive function that builds the Decision tree. :param train_set: set of examples for the current node :return: root node of the tree """ if train_set.shape[0] == 0: return None true_num, false_num ...
def get_command(): command = input(">>>") command = command.strip() return command def print_main_menu(): print("\nEnter a command:") print("conversions\tGo to conversions menu.") print("operations\tGo to operations menu.") print("\nexit\tExit the application.\n")...
The main task of the code is to handle user commands by routing them to appropriate handlers. It retrieves a command, checks its value, and executes corresponding actions like exiting, displaying help, or invoking specific command handlers for conversions and operations. If an invalid command is detected, it raises an ...
def main_command_handler(self): command = self.get_command() try: if command == "exit": exit() elif command == "help": self.print_main_menu() elif command == "conversions": self.conversions_command_handler() ...
def collect_instructions_with_sideeffects(instr): ''' This function recursively walks through `instr`'s fields (`instr` is gonna be removed by the caller for uselessness) looking for instructions with sideeffects to keep ''' instructions = [] for field_name, field in instr.__dict__.items(): # skippi...
This function optimizes SSA-form instructions by performing constant folding, replacing mathematical operations with faster equivalents, and removing useless operations while preserving those with side effects. It iterates through each block and instruction, checks for binary operations to fold, and applies optimizatio...
def constfolding_plus_math_replacing_plus_rm_useless(ssa): ''' This function walks through instructions (instructions in ssa form are tree-structured, so we even need to walk through instruction's fields) and replaces them with a folded version Secondary features: * Replaces some math operations with a simpl...
def delete_old_audio_files(output_folder): for filename in os.listdir(output_folder): file_path = os.path.join(output_folder, filename) try: if os.path.isfile(file_path): os.unlink(file_path) # Deletes the file except Exception as e: print(f"Error del...
This code records audio clips in batches, continuously looping to delete old files, record specified clips with pauses, analyze results, and send notifications. It uses a pause event to stop, updates UI/status, and logs analysis outcomes like majority results and file counts.
def record_audio_batch(output_folder, samplerate, record_sec, num_clips, pause_event): loop_number = 1 while True: delete_old_audio_files(output_folder) # Delete old files before starting a new loop for clip_number in range(1, num_clips + 1): if pause_event.is_set(): ...
def delete_old_audio_files(output_folder): for filename in os.listdir(output_folder): file_path = os.path.join(output_folder, filename) try: if os.path.isfile(file_path): os.unlink(file_path) # Deletes the file except Exception as e: print(f"Error del...
This function continuously records audio clips in batches, deleting old files before each loop. It records a specified number of clips per loop, checks for pause events, and sends notifications/status updates. After each loop, it analyzes the recorded clips, updates the GUI, and counts audio files, repeating the proces...
def record_audio_batch(output_folder, samplerate, record_sec, num_clips, pause_event): loop_number = 1 while True: delete_old_audio_files(output_folder) # Delete old files before starting a new loop for clip_number in range(1, num_clips + 1): if pause_event.is_set(): ...
def delete_old_audio_files(output_folder): for filename in os.listdir(output_folder): file_path = os.path.join(output_folder, filename) try: if os.path.isfile(file_path): os.unlink(file_path) # Deletes the file except Exception as e: print(f"Error del...
This function records audio clips in batches, deleting old files each loop. It records specified clips per batch, sends notifications, updates a GUI status, analyzes clips, and repeats until paused. It handles pausing, looping, notifications, and tracks audio file counts for each loop.
def record_audio_batch(output_folder, samplerate, record_sec, num_clips, pause_event): loop_number = 1 while True: delete_old_audio_files(output_folder) # Delete old files before starting a new loop for clip_number in range(1, num_clips + 1): if pause_event.is_set(): ...
def _opcode(self): if self._accept('INSTR'): return self.current_token.value else: return None def _eat_to_eol(self): while self.current_token and not self._accept('EOL'): self._advance() def _operand(self): if (self._accept('REG') or self._accept('LAB...
This code parses an instruction by validating the mnemonic and operand count. It retrieves the operation code, collects operands separated by commas, filters out null operands, and checks if the count matches the expected number for the operation. If valid, it returns the operation and operands; otherwise, it returns a...
def _instruction(self): operation_code = self._opcode() if not operation_code: self._eat_to_eol() return 'ERR:003:Invalid mnemonic' operands = [] operand = self._operand() operands.append(operand) while self._accept('COMMA'): operand =...
def _instruction(self): operation_code = self._opcode() if not operation_code: self._eat_to_eol() return 'ERR:003:Invalid mnemonic' operands = [] operand = self._operand() operands.append(operand) while self._accept('COMMA'): operand =...
This function processes a line by checking if it starts with 'E' and if the end-of-line is accepted. If not, it returns an error message for a newline; otherwise, it returns the line.
def _line(self): line = self._instruction() # Don't replace other errors or valid lines if not self._accept('EOL') and line and line[0] != 'E': self._eat_to_eol() return "ERR:001:Newline" else: return line
def generate_tokens(self, text): """String-to-token generator. Args: text (str): Input string of lines that are newline delimited Returns: list[Token]: a generated token list. """ for token in self.scanner.scan(text)[0]: if token.type != 'WS...
The code parses a text string into a MAL abstract syntax tree (AST) represented as a nested list structure. It tokenizes the input, advances through tokens, and constructs the AST via the `_program()` method, returning a list of lists containing strings and sublists to represent the parsed MAL code's hierarchical struc...
def parse(self, text): """Parses a text string into a the MAL ast. Args: text: The text to parse Returns: list[list[str, list[str]]]: An array representing the 'AST'. """ self.tokens = self.generate_tokens(text) self.current_token = None ...
def computeClosestVertexFromLatLonCoord(locationInCoords, locations): # initialize variables to keep track closest vertex as we interate through the city graph closestDist = float('inf') locationVertex = 0 # loop through all items in locations dictionary until we find the vertex that is closest to the ...
The code computes the least-cost path from a house to the University of Alberta using coordinates, identifies the closest LRT station, and returns the path, distance, and station details. It first finds nearest vertices for the house and university, then calculates the optimal route and distance, or returns an error if...
def computePathToUni(self, houseLocationInCoords): #find the corresponding vertex using the lat and lon coordinates of the house, as well as the university houseVertex = computeClosestVertexFromLatLonCoord(houseLocationInCoords, self.locations) uniVertex = computeClosestVertexFromLatLonCoord((53...
def startup(): explorerhat.light.blue.off() explorerhat.light.yellow.off() explorerhat.light.red.off() explorerhat.light.green.off() pygame.mixer.init() pygame.mixer.music.load("/home/pi/Documents/LED_project/ps1.mp3") pygame.mixer.music.play() explorerhat.light.blue.fade(0,100,2) ti...
The main task of the code is to control a robot's movement using a PID controller based on color sensor input, adjusting motor throttles to maintain a straight path. It also incorporates obstacle avoidance via a distance sensor, stopping the robot if an object is detected within 10 cm. The loop continuously reads color...
def main(): # initialize signal.signal(signal.SIGINT, signal_handler) print("Hello, world!") startup() # instantiate a PID controller with kp=20, ki=4, kd=2.5, and setpoint=0 pid_controller = simple_pid.PID(20, 4, 2.5, setpoint=0) base_throttle = 30 offset = 1 # the motors do not have...
def startup_sequence(): """Perform the startup sequence with lights and sound.""" light.blue.off() light.yellow.off() light.red.off() light.green.off() play_sound("startup") light.blue.fade(0,100,2) time.sleep(2) light.yellow.fade(0, 100, 2) time.sleep(2) light.red.fade(0, 10...
The code implements a robot control system using PID control for movement adjustment based on color sensor input, obstacle avoidance via distance sensing, and shutdown handling. It initializes sensors, motors, and a PID controller, then loops to read color data, calculate scores, adjust motor throttles dynamically, det...
def main(): # Signal handler for clean shutdown signal.signal(signal.SIGINT, signal_handler) print("Hello, world!") startup_sequence() # PID controller setup pid_controller = PID(20, 4, 2.5, setpoint=0) pid_controller.sample_time = 0.01 pid_controller.output_limits = (-40, 40) ...
def blink183(times = 10, wait_time = 0.5): clock = time.time() bolli = True for i in range(1, times + 1): bolli = True while True: if time.time() - clock >= wait_time * i - (wait_time/2): explorerhat.output.one.on() while True: ...
The main task of the code is to control an Explorer HAT device via touch sensor inputs, executing actions like running external code, blinking LEDs, line-following with specified colors, and stopping the loop. It uses conditional checks on four touch sensors to trigger different functions, including motor control (comm...
def main(): explorerhat.light.on() keep_running = True red, green, blue = 0, 0, 0 while keep_running: if explorerhat.touch.one.is_pressed(): joshuas_code.main() elif explorerhat.touch.two.is_pressed(): # set the color blink183(1, 0.2) elif explorerhat.t...
def scorecam_vis(models, config, loaders, device, prefixes): """ Calls ScoreCam on various model layers, then returns those images. Arguments: models: list of models, which will be called individually config: the keys (idx_vis_layers, idx_vis_layers, num_scorecam_images, is_auto...
The `vis_model` function generates and logs visualizations for machine learning models, including ScoreCam heatmaps, sorted output results, embedding visualizations, and CNN filter images. It processes multiple models, datasets, and configurations to create diagnostic images, which are logged using `wandb` for analysis...
def vis_model( models, config, loaders, device, prefixes, results, embeddings, sampled_paths=None ): """ Call a series of visualizations. Arguments: models: list of models, which will be called individually config: the keys (idx_vis_layers, idx_vis_layers, num_scorecam_images, ...
def GetSegmentationMask(self, region): seg = itk.array_view_from_image(self.segmentation) inmask = np.full(seg.shape, 1, dtype=np.int16) if not self.mask is None: inmask[ itk.array_view_from_image(self.mask)==0]=0 if region in self.segmentationRules.keys(): rule...
The main task of the code is to update the output by summarizing multiple labeling systems using specified measures. It precomputes segmentation masks, checks data validity, aggregates statistics from each labeling system, converts results to DataFrames, and concatenates them into a unified output. The function returns...
def Update(self): if None in [self.mask, self.segmentation]: return False if len(self.labels)==0: return False # Precompute segmentation region masks for i in self.segmentationRegions: self.regionMasks[i] = self.GetSegmentationMask(i) stats ...
def for_propagation(self, X): self.n[0:self.ind_n([1, 0])] = X for i in range(1, len(self.layers)): self.n[self.ind_n([i, 0]):self.ind_n([i+1, 0])] = self.activation_func( np.sum(self.node([i-1]) * self.weight([i]), axis=1) + self.bias([i]), i ) return def back_propagation(self, y_...
This code trains a neural network using mini-batch gradient descent, tracking training and validation losses across epochs. It includes early stopping based on validation loss improvement, weight/bias updates with learning rate, and handles data shuffling. The model's parameters are adjusted iteratively, with the best ...
def fit(self, X_train, Y_train, X_val, Y_val, epochs, batch_size=100, learn_rate=0.01, patience=10, min_improvement=0, shuffle=True): loss_t, loss_v = np.zeros(epochs), np.zeros(epochs) n_train = len(X_train) n_val = len(X_val) self.epochs = epochs self.lr = learn_rate ...
def M(image_id): # __author__ = amaia # https://www.kaggle.com/aamaia/dstl-satellite-imagery-feature-detection/rgb-using-m-bands-example filename = os.path.join(inDir, 'sixteen_band', '{}_M.tif'.format(image_id)) img = tiff.imread(filename) img = np.rollaxis(img, 0, 3) return img def stretch_n(b...
This code combines multiple images into a 5x5 grid (each image resized to 835x835) and generates class-specific masks for each image, then saves the concatenated image grid and masks as NumPy arrays for training a machine learning model. It processes 25 images, extracts features, and creates labeled data for classifica...
def stick_all_train(): print ("let's stick all imgs together") s = 835 x = np.zeros((5 * s, 5 * s, 8)) y = np.zeros((5 * s, 5 * s, N_Cls)) #col_x = np.zeros((5 * s, 5 * s, 8)) ids = sorted(DF.ImageId.unique()) print( len(ids)) for i in range(5): for j in range(5): i...
def listen_to_voice_command(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) audio = r.listen(source) try: command = r.recognize_google(audio).lower() print("You ...
The function processes voice commands to set timers, countdowns, or sleep cycles by extracting numerical durations from user input. It checks for specific keywords, parses the duration, and triggers corresponding actions. If parsing fails, it alerts the user to retry with valid input.
def listen_to_voice_command_btn(): command = listen_to_voice_command() if "timer" in command: try: timer_duration = int(command.split("for")[1]) set_timer(timer_duration) except: speak("Invalid input, please try again") elif "countdown" in command: ...
def _parse_args(): """ Parses command-line arguments. The function returns an object that has the added arguments as attributes. To add a new argument, add another entry of 'parser.add_argument(...)' and specify the details you want. The docs for argparse are at: https://docs.python.org/3/libra...
The main task of the code is to convert an image into ASCII art using a specified key, validate input file paths, and either save the result to a text file, an image file, or print it directly based on command-line arguments.
def main(): args = _parse_args() image_file_path = validate_file_extension(args.image) image_file_path = validate_file_path(image_file_path) print(image_file_path) ascii_key_path = args.key print(ascii_key_path) ascii_img = handle_image_conversion(image_file_path, ascii_key_path) if args...
def capture_string(stream: peekable[Char], delimiter: str) -> str: """ Walk through the iterable and pull out a string literal sequence from the source code. """ token = [] while (item := next(stream))[1] != delimiter: pos, char = item if char != "\\": token.append(ch...
The main task of the code is to tokenize a program's source code into structured tokens like symbols, strings, interpolations, and bare words. It processes characters sequentially, handling whitespace, punctuation, string literals, and identifiers, using context-free grammar rules to split the input into meaningful lex...
def tokenize(program: str) -> List[Token]: """First pass of the source code, transform raw text into tokens""" tokens: List[Token] = [] stream: peekable[Char] = peekable(enumerate(program)) while next_item := next(stream, None): position, character = next_item # skip whitespace ...
def _load_wiki(line): report = json.loads(line) document_paragraphs, _ = _recursive_load(report["report"], keep_letter=True) summary_paragraphs = report["summary"] return document_paragraphs, summary_paragraphs, report['id'] def _load_qs(line): report = json.loads(line) document_paragraphs, _ = ...
This function generates training examples by parsing structured documents and summaries from different datasets (e.g., Wikipedia, government reports). It reads JSONL files, processes document sections, hierarchical metadata, and summaries, then yields structured examples with paragraph sequences, section hierarchies, a...
def _generate_examples(self, split_name): if self.config.name == 'wiki_bio_sum': with open(os.path.join(self.config.data_dir, 'wikibiosum', f'{split_name}.jsonl')) as f: for line in f: document_sections, summary_paragraphs, wiki_id = _load_wiki(line) ...
def get_max(arr): max_temp = arr[0] for i in range(len(arr)): if(arr[i] > max_temp): max_temp = arr[i] return max_temp def get_min(arr): min_temp = arr[0] for i in range(len(arr)): if(arr[i] < min_temp): min_temp = arr[i] return min_temp def inse...
The main task of the code is to demonstrate and compare various sorting algorithms by applying them to a predefined input array. It prints the original array, then outputs the results of insertion sort, counting sort, radix sort, heap sort, bubble sort, selection sort, merge sort, and quick sort, each operating on a co...
def main(): arr = [5, 4, 1, 9, 7, 6, 3, 2, 10, 8, 12, 11] print('Input array: ', arr) print('--Outputs--') print('Get max: ', get_max(arr)) print('Get min: ', get_min(arr)) print('Insertion sort: ', insertion_sort(arr.copy())) print('Counting sort: ', counting_sort(arr.copy())) print('R...
def extract_activity_labels(bpmn_file): try: tree = etree.parse(bpmn_file) tree_root = tree.getroot() bpmn_namespace = {'bpmn': 'http://www.omg.org/spec/BPMN/20100524/MODEL'} activity_xpath = '//bpmn:task | //bpmn:userTask | //bpmn:serviceTask | //bpmn:manualTask |' \ ...
The code analyzes a BPMN file by extracting activity labels, calculating their scores, determining invalid tasks, and saving results with user data. It returns an analysis result containing filename, average score, task counts, invalid tasks, and label-specific scores for further processing or reporting.
def analyze_file(bpmn_file, user_id): labels = extract_activity_labels(bpmn_file) total_tasks = len(labels) score_by_labels = calculate_labels_score(labels) if total_tasks > 0 else [] total_score = get_total_labels_score(score_by_labels) invalid_tasks = get_invalid_labels_count(score_by_labels) ...
def print_menu(self): """Print main menu """ self.clear_console() for index, operation in enumerate(self.operations): print(f'[{index}] {operation}') def ask_for_operation(self): """Ask the user for an operation to exceute Returns: int: Operation ...
The code defines a `run` method that manages a basic application lifecycle by displaying a menu, capturing user input, and executing corresponding operations like exiting, viewing balance, displaying depot contents, depositing, or purchasing a product based on the selected option.
def run(self): """Run the base application lifecycle """ self.print_menu() operation = self.ask_for_operation() if operation == 0: exit() elif operation == 1: self.print_balance() elif operation == 2: print('asdasdasdasdasdasdas...
def _scrape_dataset_description_texts(self) -> list: """ Scrapes the description given for the dataset. Raises: Warning: If the section could not be identified to have an audience. Exception: If an element could not be located. Returns: (list): List ...
This function aggregates metadata from a dataset by scraping description, keywords, subjects, audience, temporal coverage, and resources, storing them in a dictionary along with the dataset URL. It handles exceptions during scraping attempts, printing warnings or error messages without interrupting the process.
def _get_all_data(self) -> dict: """ Returns all necessary information from the dataset. """ dataset = {} dataset["dataset_url"] = self._dataset_url try: dataset["dataset_description"] = self._scrape_dataset_description_texts() except Warning as e: ...
def exclude_digits_from_rows_where_nothing_is_right(possibilities, constraints): for row in constraints: if row['valid_on_invalid_places'] == 0 and row['valid_and_placed'] == 0: for digit in row['digits']: exclude_number(possibilities, digit) def exclude_digits_existing_with_plac...
The code generates possible digit combinations for each position based on constraints, eliminates invalid digits using two filtering functions, and then performs a brute-force search to determine the correct code that satisfies all constraints.
def crack_code(constraints): possibilities = [] for place in range(len(constraints[0]['digits'])): possibilities.append([0,1,2,3,4,5,6,7,8,9]) exclude_digits_from_rows_where_nothing_is_right(possibilities, constraints) exclude_digits_existing_with_place_contradiction(possibilities, constraints...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--log_name", type=str, default="experiment_log.txt") parser.add_argument("--input_dir", type=Path, default="./input/clean") parser.add_argument("--sigmas", type=int, nargs="+", help = "noise level of images") parser.add_argu...
The main task of the code is to evaluate a two-stage denoising algorithm across multiple hyperparameters (K, L, c, c_s) and noise levels (sigma). It processes 3D medical images by adding synthetic noise, applying the denoising stages, calculating PSNR/SSIM metrics, and logging results. The code normalizes images, itera...
def main(): args = parse_args() # Configure the logging logging.basicConfig( level=logging.INFO, filename = args.log_name, format='%(message)s', filemode='w') in_images_rel = [f for f in os.listdir(args.input_dir)] hyper_param_product = list(product(args.Ks, args.Ls, args.cs...
def initializeFeedbackGlobals(): global g_Beat, g_LastTime, g_LastNote, g_TotalNotes, g_CorrectNotes, g_TimeThreshold, g_Accuracy, g_Streak, g_CurrentStreak g_Beat = 'Get ready!' g_LastTime = 0.0 g_LastNote = [''] g_TotalNotes = 0 g_CorrectNotes = 0 g_Accuracy = 0.0 g_Streak = 1 g_Cu...
The main task of the code is to initiate a playback sequence for a pattern, either in regular mode or training mode. It configures hardware, displays instructions via a thread queue, executes the pattern, calculates feedback, and cleans up resources. In training mode, it provides step-by-step guidance ('Watch first!', ...
def beginPlayback(thread): global g_Playback, g_Training print('Begin Playback') initializeFeedbackGlobals() configure_pins() if(g_Training == False): countOff(thread) startPattern(thread) g_Playback = False calculateFeedback() GPIO.cleanup() else: #traini...
def create_testfile(dataset: str, chunksize: int): """ This function creates a testfile with 10000 entries to test a maximal frequent itemset algorithm. """ try: os.remove("testfile.xml") except OSError: pass gen_entry_string = entry_string(dataset, chunksize * 1024 * 1024) ...
The main task of the code is to identify maximal frequent author itemsets from a dataset using a modified Apriori-like algorithm. It processes input data, counts singleton author frequencies, iteratively generates and evaluates candidate itemsets of increasing size (k=2, 3, ...), filters those meeting a support thresho...
def main(): args = arg_parser.parse_args() if args.testfile: create_testfile(args.dataset, args.chunksize) exit() author_set_list = [] #current_hash_dict = dict() support = 25 try: gen_entry_string = entry_string(args.dataset, args.chunksize * 1024 * 1024) for ...
def handle_multiple_files(directory_path): """ Processes all CSV files within the specified directory, aggregating data. Checks for the presence of timers or data observations and handles accordingly. """ aggregated_data = { "Parameters": {}, "Single Observation Timers": {}, ...
The main task of the code is to process log CSV files from a specified directory by aggregating data, analyzing it to generate results, and printing key statistics like maximum and minimum values. It uses command-line arguments for input, processes multiple files, and outputs structured analysis results with pretty-pri...
def main(): parser = argparse.ArgumentParser(description="Process log CSV files from a directory.") parser.add_argument("directory", type=str, help="Directory containing the CSV files.") args = parser.parse_args() # Process files in the specified directory aggregated_data = handle_multiple_files(ar...
def handle_multiple_files(directory_path): """ Processes all CSV files within the specified directory, aggregating data. Checks for the presence of timers or data observations and handles accordingly. Parameters are assumed to be consistent across files and are captured only from the first file. """...
The main task of the code is to process log CSV files from a specified directory by aggregating, validating, and analyzing their data. It generates analysis results, identifies maximum/minimum values, and visualizes running statistics for diagnostics. The script creates a 'plots' directory, handles multiple files, ensu...
def main(): parser = argparse.ArgumentParser(description="Process log CSV files from a directory.") parser.add_argument("directory", type=str, help="Directory containing the CSV files.") args = parser.parse_args() # Process files in the specified directory aggregated_data = handle_multiple_files(ar...
def backprop(self, input_x,output_x): delta_b = [np.zeros(b.shape) for b in self.biases] delta_w = [np.zeros(w.shape) for w in self.weights] activation = input_x activations = [input_x] zs = [] for weight,bias in zip(self.weights,self.biases): z = weight.dot...
(SGD trains a neural network using stochastic gradient descent. It iterates over epochs, shuffling the training data each time. For each sample, it computes gradients via backpropagation, updates weights and biases using the learning rate, and optionally evaluates performance on a test set. The model saves its state af...
def SGD(self,training_dataset,epochs,learning_rate,test_set=None,): for i in range(epochs): random.shuffle(training_dataset) for x,y in training_dataset: d_w,d_b = self.backprop(x,y) self.weights = [w-(nw*learning_rate) for w,nw in zip(self.weights,d_w)] ...
def backprop(self, input_x,output_x): delta_b = [np.zeros(b.shape) for b in self.biases] delta_w = [np.zeros(w.shape) for w in self.weights] activation = input_x activations = [input_x] zs = [] for weight,bias in zip(self.weights,self.biases): z = weight.dot...
This code implements Batch Gradient Descent (BGD) for training a neural network. It iterates over epochs, accumulates gradients from the entire training dataset via backpropagation, averages them, and updates weights/biases using the learning rate. It saves model parameters after each epoch and evaluates performance on...
def BGD(self,training_dataset,epochs,learning_rate,test_set=None,drunk=True): for i in range(epochs): dummy_li = ["_","\\","|","/"]#this is dummy list no special uses delta_nebla_w = [np.zeros(w.shape) for w in self.weights] delta_nebla_b = [np.zeros(b.shape) for b in self.bi...
def update_mini_batch(self,mini_batch,eta): delta_nebla_w = [np.zeros(w.shape) for w in self.weights] delta_nebla_b = [np.zeros(b.shape) for b in self.biases] for x,y in mini_batch: d_w,d_b = self.backprop(x,y) delta_nebla_w = [dnw+w for dnw,w in zip(delta_nebla_w,d_w)] ...
The code implements mini-batch gradient descent training for a neural network. It iterates over epochs, splits the training dataset into mini-batches, updates model parameters using each mini-batch, saves the model after each epoch, and optionally evaluates performance on a test set. The dummy list and 'drunk' paramete...
def MGD(self,training_dataset,epochs,learning_rate,mini_batch_size,test_set=None,drunk=True): for i in range(epochs): dummy_li = ["_","\\","|","/"]#this is dummy list no special uses mini_batches = [training_dataset[k:k+mini_batch_size] \ for k in range(0,len(train...
def calculate_entropy(d: Data, data : []): result = 0 map_class = {} for value in data: class_value = value[d.attributes.index(d.class_variable)] if class_value not in map_class: map_class[class_value] = 1 else: map_class[class_value] += 1 total_size = l...
This function calculates information gain for each attribute in a dataset to determine the optimal splitting attribute. It computes total entropy, evaluates entropy reduction for both numerical (via best split) and categorical attributes, and selects the attribute with maximum gain exceeding a threshold. Returns the at...
def selectSplittingAttribute_information_gain(d: Data, data: [], a: [],threshold: float): total_enthropy = calculate_entropy(d, data) enthropy_map = {} alpha_attribute = {} for attr in a: categorical = d.categorical_numerical[attr] if categorical == 'numerical': #numerical al...
def calculate_entropy(d: Data, data : []): result = 0 map_class = {} for value in data: class_value = value[d.attributes.index(d.class_variable)] if class_value not in map_class: map_class[class_value] = 1 else: map_class[class_value] += 1 total_size = l...
This function calculates the information gain ratio for selecting the optimal attribute to split data in a decision tree. It computes entropy for each attribute, determines gain, and applies the gain ratio (gain/attribute entropy) to prioritize attributes with higher predictive power. Numerical attributes use a best-sp...
def selectSplittingAttribute_information_gain_ratio(d: Data, data: [],a: [],threshold: float): total_enthropy = calculate_entropy(d, data) enthropy_map = {} gain_ratio = {} alpha_attribute = {} for attr in a: categorical = d.categorical_numerical[attr] if categorical == 'numerical': ...
def find_most_frequent_label(d): map_class = {} for value in d: if value not in map_class: map_class[value] = 1 else: map_class[value] += 1 return max(map_class, key=map_class.get) def selectSplittingAttribute_information_gain_ratio(d: Data, data: [],a: [],threshold:...
The code implements the C4.5 decision tree algorithm to recursively construct a classification tree. It selects splitting attributes using information gain or gain ratio, creates leaf nodes for homogeneous data or absent attributes, and partitions data based on categorical domains or numerical thresholds. The function ...
def algorithm_c45(d: Data, data: [], a: [], threshold: float, t: Node, gain_ratio : bool): d_value = data d_class = list(map(lambda x: x[d.index_class_variable], d_value)) # import pdb; pdb.set_trace() #homogenous if len(set(d_class)) == 1: leaf_node = LeafNode(d_class[0], 1.0) t = ...
def get_model_path(algorithm, start_year, eco_region): ''' Function for automatically generating the location of a saved model :param algorithm: The algorithm used for creating the model, sometimes also refered to as 'model_name' :param start_year: The year at which the training data started :param ...
The main task of the code is to evaluate time series models (e.g., SARIMA) for ecological regions by iteratively training models on historical data (2000–2016) and testing them on future data (2017–2020). It handles model loading/training, performance evaluation, and result aggregation, saving metrics and synthetic for...
def test_eco_region(eco_dat, model_name): region, data = eco_dat results_df = pd.DataFrame() sf_data = [None] * 17 #Set aside the testing data. Using the classical 80%-20% split test_ds = data.loc[dict(time=slice("2017", "2020"))] region_dat = data.loc[dict(time=slice("2000", "2016"))] for ...
def load_sf_data(self, region): sf_file = self.get_sf_path(region) with xr.open_dataset(sf_file) as loaded_ds: sf_ds = loaded_ds return sf_ds def get_model_path(self, start_year, eco_region, save_type='pkl'): """ Function for automatically generating the location of ...
This function generates predicted scaling factors for an ecoregion by training models on historical data, predicting with them, and combining results. It loads existing models if available, otherwise trains new models using an 80%-20% train-test split. The output is a dataset of predicted scaling factors for varying tr...
def pred_eco_region(self, eco_data): ''' Generate the predicted scaling factors for an ecoregion. :param eco_data: All the analyzed scaling factor of a single ecoregion :return: Dataset with the predicted scaling facter per number of training years used. ''' region = floa...
def __generate_action(self): """ Determines if the algorithm should take a greedy action (take the highest estimated value) or explore the possible actions available. Notes ----- A simple alternative is to behave greedily most of the time, but sometimes, with sm...
The code runs an experiment by generating actions, checking if they match the optimal action (q-star), recording actions, rewards, and whether each action was optimal, then updating the experiment state. It returns lists of actions, rewards, and binary indicators of optimal choices for analysis.
def run_experiment(self, num_choices): actions = [] rewards = [] best_action = [] for choice in range(0, num_choices): action = self.__generate_action() if action == self.get_q_star_action(): best_action.append(1) else: ...
def normalize(self, X): X = (X - self.array_mean(X, axis=0)) / self.array_std(X, axis=0) return X def _sigmoid(z): return 1.0 / (1 + np.exp(-z)) def dot_product(self, A, B): assert A.shape[1] == B.shape[0], f'{A.shape} and {B.shape} incompatible for dot product' output = np.zero...
This code trains a logistic regression model using stochastic gradient descent (SGD) with batch processing. It initializes weights and bias, normalizes input data, iterates over epochs, processes data in batches, computes predictions and gradients, updates parameters via gradient descent, and tracks loss values over tr...
def train(self, X, y): m, n = X.shape # Initializing weights and bias to zeros. self.w = np.zeros((n, 1)) self.b = 0 # Reshape y. y = y.reshape(m, 1) # Normalize inputs x = self.normalize(X) # Store losses self.losses = [] # T...
def normalize(self, X): X = (X - self.array_mean(X, axis=0)) / self.array_std(X, axis=0) return X def _sigmoid(z): return 1.0 / (1 + np.exp(-z)) def dot_product(self, A, B): assert A.shape[1] == B.shape[0], f'{A.shape} and {B.shape} incompatible for dot product' output = np.zero...
The code performs logistic regression prediction by normalizing input features, computing linear predictions via dot product with weights, applying a sigmoid function to obtain probabilities, and thresholding at 0.5 to classify outputs into binary labels (0 or 1). Your return
def predict(self, X): assert self.w is not None # Normalizing the inputs. X = self.normalize(X) # Calculating presictions/y_hat. preds = self._sigmoid(self.dot_product(X, self.w) + self.b) # if y_hat >= 0.5 --> round up to 1 # if y_hat < 0.5 --> round up to 1 ...
def toggleUI(self, state: bool): """Allows you to disable all input ui, useful when downloading""" self.ui.searchButton.setEnabled(state) self.ui.browseButton.setEnabled(state) self.ui.beginButton.setEnabled(state) self.ui.ckBoxSaveURLs.setEnabled(state) self.ui.ckboxDown...
The main task of the code is to initiate a download process by gathering and validating posts from a source (likely r34), disabling the UI during execution, running the download in a separate thread, and updating the UI with progress/status. It also handles post-download actions like updating labels, progress bars, and...
def begin(self): """Prepares the postList and starts the download""" print("Begin button pressed") self.ui.currentTask.setText("Gathering and validating posts") # disable the ui so user cant modify anything self.toggleUI(False) self.cacheUI() # gathers posts from...
def code_gen(): exists = True while exists == True: code = int(random()*(10**8)) exists = check_exists(code)["code_exists"] return code def check_exists(code): items = read_items() code_exists = False stock_exists = False stock_pcs = 0 for i in items["items"]: if ...
The code generates a cash memo for sales by allowing users to add items with validation checks (existence, stock availability, and quantity limits). It calculates the total amount, prints a structured receipt, and confirms billing. If confirmed, it updates inventory stock and records the sale in a database. If canceled...
def bill(): datetime = dt.now().strftime("%d/%m/%y %H:%M:%S") cash_memo = {"date":datetime, "number":code_gen()} purchased_items = [] c = 0 total_amt = 0 while 1: if input("ADD ANOTHER ITEM? (Y/N [Default : Y]) : ") in "Yy": print(''' ADD ITEM ======== ''') i...
def check_document_file(self,entry,name): for document in document_extensions: if name.endswith(document) or name.endswith(document.upper()): move_file(dist_dir_pdf,name,entry) logging.info(f"Moved document file: {name}") def check_image_file(self,entry,name): ...
The code defines a method `on_modified` that triggers when a file is modified. It scans the `source_dir` directory, iterates through each file entry, and checks if the file is a document, image, or video using respective methods. The primary task is to monitor file changes and validate or process specific file types in...
def on_modified(self, event): with scandir(source_dir) as source: for entry in source: name=entry.name self.check_document_file(entry,name) self.check_image_file(entry,name) self.check_video_file(entry,name)
def filePrint(file,state): row = len(state) for i in range(row): for j in range(row): file.write(str(state[i][j])+" ") file.write("\n") file.write("\n") def getAction(x,y): lmt = row-1 rslt = [] if x<lmt: rslt+=["down"] if x>0: rslt+=["up"] if ...
The code implements Iterative Deepening Search (IDS) to find a goal state from an initial state. It incrementally increases depth limits, using DLS (Depth-Limited Search) for each. If a solution is found, it logs the depth, node count, time, and reconstructs the path via parent pointers. If no solution is found within ...
def call_IDS(tmpState): file = open("output_IDS.txt", "w") # prntState(tmpState) file.write("Initial state :\n") filePrint(file, tmpState) global call call = 0 nodeCount = 0 cutOffNode = node(state=tmpState, parent=-5, action=getAction(srtX, srtY), g_cost=-1, depth=-1, h_cost=-1, x=srt...
def _update_screen(self): # Draw background self.screen.blit(settings.bg, (0, 0)) self._draw_objects() self._draw_possesions() # Draw buy menu self.buy_menu.draw(self.screen) pygame.display.update() def _check_events(self): for event in pygame.event.get()...
The code runs a game loop that updates the screen, manages events, spawns enemies and powerups at intervals, handles game objects, checks for loss conditions, and maintains a 60 FPS limit. It plays background music, processes tower actions, and exits when the game ends.
def run(self): """Function to run game""" self._update_screen() clock = pygame.time.Clock() pygame.mixer.music.play(1) while self.active: clock.tick(60) # Limit framerate self._check_events() if not self.pause: # spawn powerboo...
def find_player_id(self): players = get(self.poker.deck_state(), 'Ok', 'players') if not self.near.account_id in players: logging.debug( f"{self.near.account_id} is not in game {self.room_id}. Found: {players}") return True else: self.player_i...
The code's main task is to execute a step in a game or simulation process. It first identifies the player's ID if not already set, updates the game state, checks for deck shuffling requirements, and handles revealing actions. These steps ensure proper game progression and state management.
def step(self): if self.player_id is None: if not self.find_player_id(): return self.update_state() self.check_deck_shuffling() self.check_revealing()
def calculatePitLocation(app,pit): # pit is an object of class Pit x0,y0,x1,y1= getPitRegion(app) width = (x1-x0)/(app.pitCount/2) height = (y1-y0)/2 if pit.number <=app.pitCount/2: cx = x0+((pit.number-1)* width) +(width/2) cy = y0+(height/2) else: cx = x0+((app.pitCount-pi...
The main task of the code is to adjust the positions and sizes of game elements (pits, mancalas, and seeds) when the app window resizes. It recalculates pit and mancala locations based on updated dimensions, sets seed coordinates to their final positions, and ensures visual alignment consistency during resizing.
def sizeChanged(app): app.pitRadius = (app.height-(2*app.margin))/(5) for pit in app.pitList: calculatePitLocation(app,pit) for m in app.mancalaList: calculateMancalaLocations(app,m) for seed in app.seedList: a,b= getSeedCoordinates(app,seed.pit) seed.finalX = a s...
def createPits(app): for i in range(1,app.pitCount+1): if i in range(1,app.pitCount//2+1): sequence = app.pitCount-i+1 else: sequence = app.pitCount-i pit = Pit(0,0,app.initialSeedCount,i,sequence) calculatePitLocation(app,pit) app.pitList.append(...
This code initializes a Mancala game by setting up game parameters, creating pits, mancalas, and seeds, organizing game elements into lists, and preparing the board for play. It configures player turns, seed distribution, and game state tracking, while structuring the board layout and movement queue for gameplay.
def appStarted(app): app.pitCount = 12 app.gameMessage = "Player1" app.initialSeedCount = 4 app.margin = (app.height)*0.1 app.pitList = [] # change to set if does not serve too many purposes # and write hash function for the object app.seedList=[] app.seedColorOptions = ["SeaGreen1","o...
def DrawGrid(): win = pygame.display.set_mode((WIDTH, WIDTH)) win.fill(background_color) my_font = pygame.font.SysFont('Comic Sans MS', 35) for i in range(0, 9): for j in range(0, 9): if grid[i][j] != 0: value = my_font.render(str(grid[i][j]), True, original_grid_ele...
The main task of the code is to initialize a Pygame window for a Sudoku solver, draw a grid, solve the Sudoku puzzle using the `solve_sudoku()` function, and display the solved grid. The code sets up the game window, handles basic rendering, and enters an infinite loop to maintain the window, though the `escape()` func...
def main(): pygame.font.init() win = pygame.display.set_mode((WIDTH, WIDTH)) pygame.display.set_caption("CH02") win.fill(background_color) DrawGrid() solve_sudoku() DrawGrid() while True: escape()
def load_data(): data = pd.read_csv("TT_whisky_v2.csv") return data def preprocess_data(data): data = data[['BottleName', 'Nose', 'Taste', 'Finish']] data['review'] = data['Nose'].astype(str) + " " + data['Taste'].astype(str) + " " + data['Finish'].astype(str) data['review_clean'] = data['review'].a...
The code's main task is to recommend personalized whisky options based on user-selected comfort foods by analyzing whisky reviews using a Word2Vec model. It preprocesses review data, calculates sentence vectors, matches food descriptions with similar reviews via cosine similarity, and displays top 5 whisky recommendati...
def main(): st.title("Whisky Savant") # Load data data = load_data() data = preprocess_data(data) # Train Word2Vec model global w2v_model w2v_model = train_word2vec_model(data) # Calculate sentence vectors and store them in the DataFrame data['sentence_vector'] = data['review_lemm...
def load_data(): data = pd.read_csv("whisky_clean.csv") return data def remove_punct(text): text_nopunct = "".join([char for char in text if char not in string.punctuation]) return text_nopunct def tokenize(text): tokens = re.split('\W+', text) return tokens def find_closest_sentence(input_text,...
This code creates a Streamlit web app that recommends whisky reviews based on selected food descriptions. It preprocesses whisky review text, trains a Word2Vec model, calculates sentence vectors, and uses cosine similarity to find the closest matching reviews for individual and combined food selections. The main task i...
def main(): st.title("Whisky Review Recommender") # Load data data = load_data() # Preprocessing data = data[['Title', 'Nose', 'Taste', 'Finish']] data['combined_text'] = data['Nose'].astype(str) + " " + data['Taste'].astype(str) + " " + data['Finish'].astype(str) data['combined_text_clean...
def load_data(): data = pd.read_csv("whisky_clean.csv") return data def remove_punct(text): text_nopunct = "".join([char for char in text if char not in string.punctuation]) return text_nopunct def tokenize(text): tokens = re.split('\W+', text) return tokens def find_closest_sentence(input_text,...
The code creates a whisky review recommender app using Streamlit. It preprocesses text data, trains a Word2Vec model, generates review vectors, and recommends whisky reviews by comparing selected food descriptions with reviews via cosine similarity. The app displays top matches for individual foods and a combined food ...
def main(): st.title("Whisky Review Recommender") # Load data data = load_data() # Preprocessing data = data[['Title', 'Nose', 'Taste', 'Finish']] data['combined_text'] = data['Nose'].astype(str) + " " + data['Taste'].astype(str) + " " + data['Finish'].astype(str) data['combined_text_clean...
def get_file(inputfile): with open(inputfile) as file: return file.readlines() def get_runtime_error(runtime_error_file): with open(runtime_error_file) as file: return file.read() def find_test_result_error_message(result_list): test_list = [] test_result = [] test_error = [] er...
The code processes command-line arguments to extract input files and metadata, retrieves test results and runtime errors from specified files, generates a summary of test outcomes, and sends this summary along with user/project details via a request.
def main(argv): inputfile = '' username = '' project_name = '' pipeline_id = '' args = sys.argv inputfile = args[1] runtimeErrorFile = args[2] username = args[3] project_name = args[4] pipeline_id = args[5] # mengambil file file_text = get_file(inputfile) # baca ru...
def transform_point_cloud(self): raise NotImplementedError( "Updating the source point cloud should be defined in child classes.") def iterate(self): self.expectation() self.maximization() self.iteration += 1 def get_registration_parameters(self): raise NotImplemented...
The code performs iterative point cloud registration until convergence, updating parameters and invoking a callback with progress details like iteration count, error, and current transforms. It returns the final transformed points and registration parameters after completing the specified iterations or meeting toleranc...
def register(self, callback=lambda **kwargs: None): self.transform_point_cloud() while self.iteration < self.max_iterations and self.diff > self.tolerance: self.iterate() if callable(callback): kwargs = {'iteration': self.iteration, 'erro...
def _get_pcl_XYZ(filePath): ''' Get a bin file address and read it into a numpy matrix Converting LiDAR coordinate system to Camera coordinate system for pose transform ''' f = open(filePath, 'rb') i = 0 j = 0 pclpoints = list() # Camera: x = right, y = down, z = forward # Velody...
This function processes consecutive point cloud (pcl) frames and their poses to compute relative transformations between frames. It extracts 3D point data, calculates rotation (yaw/pitch/roll) and translation (dX/dY/dZ) parameters, generates depth images, and writes these features to a file for training a network. The ...
def process_dataset(startTime, durationSum, pclFolder, seqID, pclFilenames, poseFile, tfRecFolder, i): ''' pclFilenames: list of pcl file addresses poseFile: includes a list of pose files to read point cloud is moved to i+1'th frame: tMatAo (i): A->0 tMatBo (i+1): B->0 tMatAB (ta...
def schedule(self): executor = next(iter(self.exec_to_schedule)) source = executor.job_dag if executor.node is None else executor.node # schedule executors from the source until the commitment is fulfilled while len(self.exec_commit[source]) > 0 and \ len(self.exec_to_sche...
This code manages executor allocation and scheduling in a job DAG system. It commits executors to nodes, tracks task completions, handles new job arrivals, and schedules executors based on events. It updates job states, computes rewards, and checks if all jobs are completed or time has expired, returning the reward and...
def step(self, next_node, limit): # mark the node as selected assert next_node not in self.node_selected self.node_selected.add(next_node) # commit the source executor executor = next(iter(self.exec_to_schedule)) source = executor.job_dag if executor.node is None else ex...
def decompose(n, primes, unreachable): """ Decompose the given number n in 2 or 3 primes assuming it's possible. :param n: target number to be decomposed (must ensure n < MIN_NON_DECOMPOSABLE) :param primes: set with all usable primes :param unreachable: set with all non-decomposable numbers in this...
The function `find_expression` decomposes a target number `n` using primes from a list (excluding a specified prime) to form an arithmetic expression. It returns the expression and the count of primes used. The algorithm prioritizes minimal prime usage, exploring combinations of operations (+, -, *) and recursively dec...
def find_expression(n, primes, prime): """ Main algorithm to solve the problem. Finds the expression with primes in primes excluding prime that evaluates to n. Returns the string with the formula and the number of primes involved. :param n: target number to be decomposed :param primes: ordered list ...
def read_file(filename): """ Reads the file given the filename assuming it has the contest structure. :param filename: name of the file to be read :return: a list of triplets (ID, TARGET, PRIME) """ result = [] with open(filename, 'r') as file: for line in file: if "ID" i...
The main task of the code is to read input data, process each entry using an algorithm to find mathematical expressions, and write results to an output file with timestamps. It manages time constraints by flushing output buffer when nearing the time limit, ensuring efficient execution while handling multiple threads fo...
def main(): """ Function that read the file, launches the algorithm on multiple threads and writes the result. :return: nothing """ start_time = time() entries = read_file(IN_FILENAME) with open(OUT_FILENAME, 'w') as out_file: write_timestamp(out_file, START_MOMENT) for test_...
def addNewCommunityNews(self, message): """ Adds a new steam community to the json config file if a valid URL is provided. The json configuration file is updated with the new community information. If a valid URL is provided the name of the community associated with the URL will be retur...
The main task of the code is to process incoming messages in a Discord bot, checking if the bot is tagged. If tagged, it parses commands (add, remove, list, latest) from the message content, executes corresponding actions like managing communities or fetching updates, and generates response messages to send back to the...
def handleIncomingMessage(self, message): """ Called when a new message is recieved by the bot. It first determines if the bot has been tagged. If the bot is not tagged, then nothing happens. If the bot is tagged, then the subsequent text is parsed for the available commands that the bot offers ...
def AND_logicFunction(x): w = np.array([1, 1]) bAND = -1.5 return perceptronModel(x, w, bAND) def OR_logicFunction(x): w = np.array([1, 1]) bOR = -0.5 return perceptronModel(x, w, bOR) def NOT_logicFunction(x): wNOT = -1 bNOT = 0.5 return perceptronModel(x, wNOT, bNOT)
The code implements an XOR logic function by combining AND, OR, and NOT operations. It first computes the AND of the input, then the OR, applies NOT to the AND result, and finally performs an AND between the OR result and the negated AND result, effectively realizing the XOR logic.
def XOR_logicFunction(x): y1 = AND_logicFunction(x) y2 = OR_logicFunction(x) y3 = NOT_logicFunction(y1) final_x = np.array([y2, y3]) finalOutput = AND_logicFunction(final_x) return finalOutput
def l1_scenes_to_process( outfile: Path, products: List[str], brdfdir: Path, wvdir: Path, region_codes: Dict, scene_limit: int, interim_days_wait: int, days_to_exclude: List, find_blocked: bool, config: Optional[Path] = None, ) -> Tuple[int, List[str]]: """Writes all the file...
The function `scene_select` processes USGS Level-1 files to identify scenes for ARD (At-Satellite Radiometric Data) processing. It creates a job directory, filters scenes based on configuration and region codes, generates an archive list of UUIDs, and writes a PBS script for ARD execution. If enabled, it runs the scrip...
def scene_select( usgs_level1_files: click.Path, allowed_codes: click.Path, config: click.Path, products: list, logdir: click.Path, brdfdir: click.Path, wvdir: click.Path, stop_logging: bool, log_config: click.Path, scene_limit: int, interim_days_wait: int, days_to_exclud...
def ensure_winsetup_dir(): if not os.path.exists(winsetup_dir): os.mkdir(winsetup_dir) if not os.path.exists(winsetup_dir + "\\aliases"): os.mkdir(winsetup_dir + "\\aliases") if not "winsetup" in os.environ["PATH"]: os.environ["PATH"] += os.pathsep + os.path.join(winsetup_dir, "alia...
The function creates or replaces a batch script alias file in the 'aliases' directory. It checks if the alias name is empty or already exists, prompts for confirmation if replacing, inserts '@echo off' at the start of the script, and writes the content to a .bat file. It also updates the file selector and provides stat...
def create_alias(text_widget, file_name, status_label): ensure_winsetup_dir() if os.path.exists(winsetup_dir + f"\\aliases\\{file_name.get()}.bat"): answer = tkmsg.askyesno(_("Winsetup Script"), _("There already exists an alias with the name '%s'.\nAre you sure you want to replace it?", f=[file_name.ge...
def ensure_winsetup_dir(): if not os.path.exists(winsetup_dir): os.mkdir(winsetup_dir) if not os.path.exists(winsetup_dir + "\\aliases"): os.mkdir(winsetup_dir + "\\aliases") if not "winsetup" in os.environ["PATH"]: os.environ["PATH"] += os.pathsep + os.path.join(winsetup_dir, "alia...
This function deletes a specified alias file after user confirmation, updates status messages, and handles file existence checks.
def delete_alias(file_name, status_label): ensure_winsetup_dir() alias_path = winsetup_dir + f"\\aliases\\{file_name.get()}.bat" if os.path.exists(alias_path): answer = tkmsg.askyesno(_("Winsetup Script"), _("Are you sure you want to permanently delete this alias?")) if answer: o...
def get_folder_name(self): """Get the name of the folder that will contain the new files. Based on the current extension selection.""" retstr = "" # Return string # Get info from extension tab view if self.fileTypeTab.get() == "Simple": retstr = folder_prefix + sel...
This code executes a file copy/move operation based on user-defined extensions, with progress tracking. It validates inputs, disables the run button, displays a stop button, creates a destination folder, processes files using glob, updates a progress bar, handles manual cancellation, and resets UI elements post-operati...
def run(self): "Run the copy/move algorithm." if self.fileTypeTab.get() == "Custom" and self.extTypeInput.get().strip() == "": print("ERROR: No selection was made, aborting!") return # Disable run button self.runBtn.grid_forget() # Show stop button ...
def preprocess_input(self, data): # create one-hot label map label_map = data['label'] bs, _, h, w = label_map.size() nc = self.opt.label_nc + 1 if self.opt.contain_dontcare_label \ else self.opt.label_nc input_label = jittor.zeros((bs, nc, h, w)) src = jitto...
The code executes different tasks based on the 'mode' parameter: it preprocesses input data, computes generator or discriminator losses for training, or generates fake images for inference. It returns corresponding outputs like loss values or generated images, handling GAN training and inference phases.
def execute(self, data, mode): input_semantics, real_image = self.preprocess_input(data) if mode == 'generator': g_loss, generated = self.compute_generator_loss( input_semantics, real_image) return g_loss, generated elif mode == 'discriminator': ...
def get_api(): if local: import credentials consumer_key = credentials.CONSUMER_KEY consumer_secret = credentials.CONSUMER_SECRET access_token = credentials.ACCESS_TOKEN access_secret = credentials.ACCESS_SECRET else: consumer_key = environ['CONSUMER_KEY'] consumer_secret = environ['CONSUMER_SECRET'] ...
The code schedules daily tweets at 14:00 and 20:00 UTC using the `schedule` library, continuously monitors Twitter mentions via the API, and prints timestamps. It uses a `since_id` to track the most recent tweet ID for mention checking, looping indefinitely with 10-second intervals between checks.
def main(): api = get_api() since_id = get_since_id(api) print("most recent id", since_id) prev = time.time() # schedule jobs # utc time! is eastern + 4 (pre-daylight savings...) # 10am, 4pm=16:00 tweet_times = ['14:00', '20:00'] for tt in tweet_times: schedule.every().day.at(tt).do(tweet_title, api) ...
def _InitializeProb(self, x_size, y_size, yhat_size): s_size = copy.copy(x_size) s_size.append(y_size) ps_x_y = np.zeros(s_size) pt_x_yhat = np.zeros(s_size) ps_x_yhat = np.zeros(s_size) s_size = copy.copy(x_size) s_size.append(yhat_size) ...
This function estimates the error by iterating over subsets of features, calculating probabilities for source and target distributions, and accumulating the average error across subsets. It uses random sampling or fixed subsets, updates probabilities, and checks for early stopping if the error exceeds a tolerance thres...
def EstimateError(self, source, source_y, target, source_yhat, target_yhat, W, this_set, s_subset, tol, use_random=...
def _InitializeProb(self, x_size, y_size, yhat_size): s_size = copy.copy(x_size) s_size.append(y_size) ps_x_y = np.zeros(s_size) pt_x_yhat = np.zeros(s_size) ps_x_yhat = np.zeros(s_size) s_size = copy.copy(x_size) s_size.append(yhat_size) ...
The function `_estimate_shift` estimates domain shift between source and target data by analyzing feature distributions and predicted labels. It identifies shifted features via iterative pruning of feature subsets, computes weight distributions, and calculates performance differences (target accuracy minus source accur...
def _estimate_shift(self, source=None, target=None, source_yhat=None, target_yhat=None, source_proba = None, target_proba = None, source_y = None, verbose=False, ...
def read_data(): # list the files filelist = os.listdir('data/true_claims') # read them into pandas df_male = pd.DataFrame(filelist) # Adding the 1 label to the dataframe representing male df_male['label'] = '1' # Renaming the column name to file df_male = df_male.rename(columns={0: 'fil...
The main task of the code is to train three neural network models (NN, CRNN, CNN) using provided training and validation datasets, then visualize their training and validation loss curves over epochs with a labeled plot showing categorical crossentropy as the metric.
def main(): df_tarin, df_val = read_data() trainNN(df_tarin,df_val) trainCRNN(df_tarin,df_val) trainCNN(df_tarin,df_val) # Set figure size. plt.figure(figsize=(12, 8)) # Set title plt.title('Training and Validation Accuracy by Epoch', fontsize=25) plt.xlabel('Epoch', fontsize=18) ...
def get_content(name, version=None, snippet=False): """ throws FileNotFoundError """ if snippet: fp = os.path.join('snippets', name + '.html') elif version is None: fp = os.path.join('templates', name + '.html') else: fp = os.path.join('templates', name, version + '.html') tr...
This function creates a new template using a default version, applies development-specific modifications (if enabled), and returns the template ID along with its version. It handles API interactions for template creation, version retrieval, and updates, logging errors or success. Development mode alters the template na...
def create_template(self, template, development=True): """ create new templates with the general version returns template id and array of created versions """ try: html = get_content(template, version=DEFAULT_TPL_VER) subject = self.local_templates[template]['subject'...
def get_content(name, version=None, snippet=False): """ throws FileNotFoundError """ if snippet: fp = os.path.join('snippets', name + '.html') elif version is None: fp = os.path.join('templates', name + '.html') else: fp = os.path.join('templates', name, version + '.html') tr...
This function creates a new version of an existing template by fetching its HTML content, applying development-specific transformations (like subject and name modifications) if enabled, and using an API to save the new version. It returns True on success or False if an error occurs, logging relevant details in both cas...
def create_template_version(self, template, tid, version, development=True): """ adds a new template version to an existing template returns boolean """ try: html = get_content(template, version=version['name']) subject = version['subject'] if subject is N...
def get_content(name, version=None, snippet=False): """ throws FileNotFoundError """ if snippet: fp = os.path.join('snippets', name + '.html') elif version is None: fp = os.path.join('templates', name + '.html') else: fp = os.path.join('templates', name, version + '.html') tr...
This function creates new SendWithUs snippets for local snippets without existing SendWithUs copies. It generates development-specific names if enabled, retrieves HTML content, parses it in development mode, and uses the API to create snippets. Successful creations are logged with IDs, while errors are reported. Return...
def add_new_snippets(self, development=True): """ creates new snippets for any local snippets that don't have sendwithus copies """ created_snippets = {} for snippet in self.local_snippets: name = DEV_NAME_TPL(snippet) if development else snippet if not name i...
def add_new_snippets(self, development=True): """ creates new snippets for any local snippets that don't have sendwithus copies """ created_snippets = {} for snippet in self.local_snippets: name = DEV_NAME_TPL(snippet) if development else snippet if not name i...
This function updates SendWithUs snippet copies with locally stored snippets. It processes provided or default local snippets, skips existing ones, retrieves HTML content, applies development-specific parsing, and uses the SendWithUs API to update snippets. Errors during updates are logged, while successful updates are...
def update_snippets(self, snippets=[], development=True): """ overwrites sendwithus snippet copies with locally held snippets """ if len(snippets) == 0: snippets = self.local_snippets created_snippets = self.add_new_snippets(development=development) for snippet in snippets: ...
def add_new_templates(self, development=True): """ creates new templates for any local templates that don't have sendwithus copies; throws FileNotFoundError """ created_templates = {} for key, value in self.local_templates.items(): name = DEV_NAME_TPL(key) if development ...
This function updates existing Sendwithus templates by synchronizing local template versions with the platform. It checks for existing templates/versions to avoid duplication, retrieves content, applies development-specific name/subject transformations, and uses the API to update versions. Errors during this process ar...
def update_templates(self, development=True): """ updates the templates copies on sendwithus throws KeyError and FileNotFoundError """ created_templates = self.add_new_templates(development=development) for key, value in self.local_templates.items(): name = DEV_NAME_TPL(k...
def setBroswerAndGetSoup(self): self.browser.get(self.profile_url) Helper.scroll(self.browser) src = self.browser.page_source soup = BeautifulSoup(src, 'lxml') return soup def getBasicProfileInfo(self): bs = self.bs info = {} info['Name'] = self.getProfile...
This code initializes a LinkedIn profile object by either scraping data from a logged-in browser (using a profile URL) or importing pre-extracted JSON data. It stores profile details like ID, basic info, work experience, education, and connection status, while determining if the profile belongs to a faculty/student fro...
def __init__(self, *args): if len(args) == 2: profile_url = args[0] logged_in_browser = args[1] self.imported = False self.profile_id = Helper.get_profile_id_from_linkedin_url(profile_url) self.profile_url = profile_url self.browser = logge...
def get_blank_board(self): """ create and return a new blank board data structure """ board = [] for i in range(BOARD_WIDTH): board.append([BLANK] * BOARD_HEIGHT) return board def calculate_level_and_fall_freq(self, score): """ Based on the sco...
This code implements the main game loop for a Tetris game, handling user input for piece movement and rotation, automatic piece falling, collision detection, scoring, level progression, and rendering the game board and UI elements. It manages piece placement, line clearing, and game-over conditions within an infinite l...
def _execute_actions(self): """ setup variables for the start of the game """ board = self.get_blank_board() last_move_down_time = time.time() last_move_sideways_time = time.time() last_fall_time = time.time() moving_down = False # note: there is no moving...
def init_placeholders(self): # encoder_inputs: [batch_size, max_time_steps] self.encoder_inputs = tf.placeholder(dtype=tf.int32, shape=(None, None), name='encoder_inputs') # encoder_inputs_length: [batch_size] self.encoder_inputs_length = tf.placeholder( d...
The code defines a method to construct a neural network model by initializing placeholders, building encoder and decoder components, and merging all summary operations for logging during training.
def build_model(self): print("building model..") self.init_placeholders() self.build_encoder() self.build_decoder() self.summary_op = tf.summary.merge_all()
def add_movies(api_key, start, end): """Add movies to dataframe. Args: api_key: API key for OMDB start: starting movie ID number end: ending movie ID number Returns: dataframe of movies with data """ start, end = validate_input(start, end) dataframe = get_movie...
The main task of the code is to retrieve movie data from the OMDB API within a specified IMDb ID range, filter out movies already present in RYM (Ratings Yield Matrix), and generate a structured DataFrame containing only the movies not found in RYM. The function uses three helper functions: `add_movies` to fetch OMDB d...
def main(api_key, start, end): """Get movies in omdb not in RYM. Args: api_key: key to use omdb api start: starting movie id number in imdb end: ending movie id number in imdb Returns: dataframe with movie info for movies not in RYM """ movie_list = add_movies(api_k...
def getCurrentState(self): snake = copy.deepcopy(self.snake) board = copy.deepcopy(self.board) dir_x = copy.deepcopy(self.dir_x) dir_y = copy.deepcopy(self.dir_y) last_move = copy.deepcopy(self.last_move) sensor = copy.deepcopy(self.sensor) default_health = copy.d...
The main task of the code is to temporarily update the snake's state based on the given direction, then revert to the original state before returning the update result, ensuring state consistency during testing.
def testSnake(self, direction=SnakeDirections.LAST): old_state = self.getCurrentState() data_return = self.updateSnake(direction) self.setCurrentState(old_state[0], old_state[1], old_state[2], old_state[3], old_state[4], old_state[5], old_state[6], old_state[7], old_state[8], old_state[9]) ...