dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def cards_values(cards: List[Card]) -> List[int]: values: List[int] = [0] for card in cards: rank = card[0] if ((rank >= '2' and rank <= '9') or rank == '10'): values = [value + int(rank) for value in values] elif rank in ('J', 'Q', 'K'): values = [value + 10 for ...
The function determines the winner between the player and the casino in a card game. It checks if the player's hand has a higher value than the casino's (considering "bust" thresholds) or if the casino's hand is stronger. Based on conditions, it triggers methods to declare a player win, casino win, or a draw, using car...
def _choose_winner(self) -> None: player_win = min(cards_values(self._casino_cards)) > BUSTS or best_value( cards_values(self._player_cards)) > best_value(cards_values(self._casino_cards)) casino_win = min(cards_values(self._player_cards)) > BUSTS or best_value( cards_values(self...
def set_player_turn(self, player_turn) -> bool: self._player_turn = player_turn self.player_turn_changed.emit(player_turn) def _casino_play(self): while 0 < best_value(cards_values(self._casino_cards)) < CASINO_STOP: self._add_card_for_casino() self._delay(SLEEP_SEC) def ...
The main task of the code is to handle the player's "stand" action in a game, disabling the player's turn, executing casino play logic, determining the winner, initializing a new hand, and re-enabling the player's turn for the next round.
def stand(self): self.set_player_turn(False) self._casino_play() self._choose_winner() self._init_new_hand() self.set_player_turn(True)
def LoadFeatureContainer(path_feat_list): featureContainer = FeatureContainer() featureContainer.load(path_feat_list) print() print(f"There are {sum(1 for f in featureContainer.feature_list if f.enabled)} enabled Features!") print("Features with parameters:") print(f" {', '.join(f.name for f i...
The main task of the code is to optimize feature selection for time series data using a sliding window approach combined with SMAC (Sequential Model-Based Algorithm Configuration). It iteratively enables subsets of features within a window, computes their performance, and updates the optimal configuration. The process ...
def smac_tsfresh_window_opt(timeseries, y, pathDict, scenarioDict, window_size, overlap): print(f"Starting Optimization window_size: {window_size}, overlap: {overlap}") featureContainer = LoadFeatureContainer(pathDict["features"]) print("Compute feature state for parameterless features") featureContaine...
def load_feature_container(path_feat_list: Union[Path, str], path_random_forest: Union[Path, str], logger: logging.Logger) -> FeatureContainer: """Create the feature container using a tsfresh feature list """ feature_container = FeatureContainer(logger=logger) feature_container.load(path_feat_list, path...
The code performs feature optimization on time series data using SMAC (Successive Halving Algorithm for Configurations) and TSFresh, employing a sliding window approach. It iteratively selects subsets of features (windows), optimizes them, and updates the best parameters (incumbent). The function slides a window over f...
def smac_tsfresh_window_opt( timeseries: pd.DataFrame, test_settings: pd.DataFrame, y: pd.DataFrame, path_dict: dict, scenario_dict: dict, window_size: int, overlap: int, seed: float, window_size_ratio: float, ) -> Tuple[dict, FeatureContainer]: """ Performs the optimization ...
def my_remove_adjacent(self,nums): return [a for a, b in zip(nums, nums[1:] + [not nums[-1]]) if a != b] def ctc_beam_search_length_control_initialization(self, logits, desired_length, device, beam_size=1): prob_sequence = torch.nn.functional.softmax(logits, dim=-1) # Get the log probability from l...
This function performs CTC beam search with length control to generate a token sequence of a specified length from logits. It initializes constraints, checks for early termination, and uses dynamic programming with beam search to select optimal paths. The output is a filtered, length-controlled sequence of tokens, ensu...
def ctc_beam_search_length_control(self, source_sentence, logits, desired_length, beam_size=3, k=10, ctc_pad_token_id=1, ctc_bos_token_id=0, ctc_eos_token_id=2, device=torch.device('cuda'), ctc_unk_token_id=3, ctc_blank_token_id=4, underflow_mag_ratio=1000, use_leng...
def ctc_length_control(self, logits, length_control, desired_length, scope=1, k=10, marg_criteria="mean", ctc_pad_token_id=1, ctc_bos_token_id=0, ctc_eos_token_id=2, device=torch.device('cuda'), ctc_unk_token_id=3, ctc_blank_token_id=4, underflow_mag_ratio=1000): ...
This function performs CTC-based decoding with length control strategies (greedy DP, forward-backward, beam search) to generate output tokens from logits. It modifies decoder outputs by applying specified methods, updates token sequences, and maintains decoding history. Different branches handle custom/plain CTC or bea...
def forward_decoder(self, source_sentence, decoder_out, encoder_out, decoding_format=None, **kwargs): # set CTC decoder beam size # try: # self.ctc_decoder._beam_width = self.args.ctc_beam_size # except: # pass step = decoder_out.step output_tokens = deco...
def move_cards_to_ace_pile(self) -> int: n_moved = 1 while n_moved > 0: n_moved = 0 for p in self.piles: n_moved += self.move_cards_in_pile_to_ace_pile(p) return n_moved def move_cards(self,from_pile:Pile,to_pile:Pile,index:int): ...
The main task of the code is to process a game round by moving cards between piles according to specific rules: moving Aces to the ace pile, moving cards to valid target piles based on color and value sequence, and moving Kings to empty piles if no other moves are possible. The function returns whether any card movemen...
def play_round(self): self.move_cards_to_ace_pile() did_something = False for p in self.piles: if len(p.up_cards) == 0: continue c = p.up_cards[-1] if c.value == 1: self.move_cards_to_ace_pile() ...
def unit_prop(self): while self.unit: i = self.unit.pop() clause = self.clauses[i] if clause.is_true(): continue # assert(clause.is_unit()) literal = next(iter(clause.undecided)) # assert(not (-literal in self.v...
This code implements a SAT solver using DPLL algorithm with backtracking and clause learning. It performs unit propagation, checks for conflicts, and backtracks with learned clauses when conflicts arise. The loop continues until a solution is found (returning True) or all possibilities are exhausted (returning False).
def run(self): preprocess = True while True: #print(self.unit) #print(f"Current Solution: {self.vmap}") #print(f"Assignments: {self.assignment}") conflict = self.unit_prop() #print(f"Clauses: {self.clauses}") #input() ...
def parse_args(): description = """ Slice the large TIFF files into tiles for training, validation, and testing datasets. NOTE: All TIFF files must have the same dimensions. I only have one large image (with 4 layers) for training, validation, and testing. The strategy is t...
The main task of the code is to process and partition data into training, validation, and test sets based on parsed arguments. It logs the start, retrieves row indices using `get_rows`, groups them with `get_row_groups`, and writes the structured data as "stripes" via `write_stripes`. The process concludes with a log i...
def main(): log.started() args = parse_args() train_indexes, val_indexes, test_indexes = get_rows(args) train_groups, val_groups, test_groups = get_row_groups( train_indexes, val_indexes, test_indexes ) write_stripes(args, train_groups, val_groups, test_groups) log.finished()
def show_menu(): print ("\nExample menu") print ("-----------------") print ("1) Backup VMS") print ("2) Restore VMS") print ("3) Delete VMS") print ("Q) Exit\n") def get_values(today_date): print("") vm_list = subprocess.run(["VBoxManage.exe", "list", "vms"], capture_output=True, text=T...
The code defines a `menu` function that presents a menu to the user, takes input, and executes corresponding actions: calling `get_values(today_date)` for option '1', `file_creation()` for option '2', or exiting on 'q'. The loop is commented out, so the function runs once unless reactivated. It handles user choices to ...
def menu(today_date): # while True: show_menu() choice = input('Enter your choice: ').lower() if choice == '1': get_values(today_date) elif choice == '2': file_creation() elif choice == 'q': exit()
def setnextinput(self): ''' Set input of MLP to next input of dataset ''' sample, gt = self.inputs.next_sample() self.gt = gt for i in range(len(self.layers[0])): self.layers[0][i] = sample[i] def feedforward(self): ''' Feedforward function (ju...
The code trains a neural network for one epoch by iterating through each input sample, performing forward propagation, and backpropagating the error using the provided learning rate to update model parameters.
def train_one_epoch(self, learning_rate): ''' Train for one epoch ''' for i in range(len(self.inputs)): self.setnextinput() # Use next sample of dataset as next input self.feedforward() # Feed forward... self.backpropagate(learning_rate)
def train_one_epoch(self, learning_rate): ''' Train for one epoch ''' for i in range(len(self.inputs)): self.setnextinput() # Use next sample of dataset as next input self.feedforward() # Feed forward... self.backpropagate(learning_rate) def print_accu...
The code trains a neural network model over a specified number of epochs using a given learning rate and decay factor. It iteratively calls `train_one_epoch` to update model parameters, adjusts the learning rate by multiplying it with the decay factor each epoch, and optionally prints training accuracy at regular inter...
def train(self, n_epochs, learning_rate, decay=1.): ''' Train function (with specified number of epochs, learning rate and decay) ''' # previous_weights = [] # for l in self.layers[1:]: # for n in l.neurons: # previous_weights.append(n.weights) ...
def get_json(url): response = requests.get(url) if response.status_code == 200: try: return json.loads(response.content) except json.decoder.JSONDecodeError as e: sys.stderr("Invalid JSON returned from Trello API: {}, JSON: {}".format(e, response.content)) sys.exit(1) else: sys.stder...
This function assigns hosts to Trello cards for a podcast workflow. It rotates assignees between intro, question, and Patreon cards by fetching previous assignments, selecting a new host from a list, and applying them to newly created cards using the Trello API.
def assign_hosts_to_cards(key, token, created_cards, most_recent_episode_list_id): print('Assigning hosts to each card...') # Assign host to the intro for the next episode previous_episode_cards = get_json(f'https://api.trello.com/1/lists/{most_recent_episode_list_id}/cards?key={key}&token={token}') previous_ep...
def get_json(url): response = requests.get(url) if response.status_code == 200: try: return json.loads(response.content) except json.decoder.JSONDecodeError as e: sys.stderr("Invalid JSON returned from Trello API: {}, JSON: {}".format(e, response.content)) sys.exit(1) else: sys.stder...
This function manages Trello cards for an episode list by fetching existing cards, appending a source card, adding Patreon shoutouts, and assigning hosts. It uses the Trello API to retrieve cards, then processes them with helper functions to update the list and organize episode-related data. The task involves interacti...
def populate_next_episode_list(key, token, episode_list, most_recent_episode_list_id): episode_list_id = episode_list['id'] created_cards = get_json(f'https://api.trello.com/1/lists/{episode_list_id}/cards?key={key}&token={token}') print(f'Created list for episode with {len(created_cards)} cards') append_source...
def find_most_recent_episode_list(key, token): current_lists = get_json(f'https://api.trello.com/1/boards/{BOARD_ID_SHORT}/lists?key={key}&token={token}') most_recent_episode_number = 0 most_recent_episode_list_id = None for lst in current_lists: matches = re.search(r'episode (\d+)', lst['name'].lower()) ...
The function checks if the most recent Trello episode list is completed. If so, it creates a new episode list for the next episode using a template and populates it. If the current episode isn't finished, it skips creation. The task involves conditional Trello list management for episode tracking.
def create_next_episode_list_if_needed(key, token): print(f'Getting most recent episode from Trello...') most_recent_episode_number, most_recent_episode_list_id = find_most_recent_episode_list(key, token) # Need to create a new card? if is_episode_list_already_done(key, token, most_recent_episode_list_id): ...
def get_data_from_request(request: Request) -> Dict[str, Any]: if isinstance(request.json, str): data: Dict[str, str] = json.loads(request.json) else: data: Dict[str, str] = request.json return data def check_roreign_keys(data: Dict[str, Any], foreings_keys): for id_to_check in fore...
The main task of the code is to create a new member by validating foreign keys and required fields, inserting data into the database, handling participant relationships, updating camp IDs, and returning a CORS-enabled Flask response with the member data.
def create_member(): data = get_data_from_request(request) try: check_roreign_keys(data, Member.FOREIGN_KEYS) except NonExistingKey as error: return str(error) member = Member(request=data) try: sql_insert, sql_insert_values = member.generate_insert_query() except M...
def get_data_from_request(request: Request) -> Dict[str, Any]: if isinstance(request.json, str): data: Dict[str, str] = json.loads(request.json) else: data: Dict[str, str] = request.json return data def check_roreign_keys(data: Dict[str, Any], foreings_keys): for id_to_check in fore...
This function updates a member's information in the database by validating the member ID, checking foreign key constraints, generating an SQL update query, executing the update, and handling participant changes if camp IDs are provided. It returns success or error messages based on the operation's outcome.
def update_member(id: str): if id==None or not DATABASE.check_if_id_exist(MEMBERS_DATABASE, int(id)): return str(NonExistingKey(ID, id)) data = get_data_from_request(request) try: check_roreign_keys(data, Member.FOREIGN_KEYS) except NonExistingKey as error: return str(error) ...
def _app_bismillah(self, flask_app): app_config = self._get_app_config() self._register_environment(flask_app, app_config) self._init_database(flask_app) with flask_app.app_context(): app_config.register_model(flask_app) app_config.register_controller(flask_app) def _...
The main task of the code is to configure and initialize a Flask application by setting up necessary components like Marshmallow (for data validation), Swagger (for API documentation), registering the root URL route, and cleaning uploaded files. The method orchestrates these steps to prepare the Flask app for operation...
def load_app(self, flask_app): self._app_bismillah(flask_app) self._init_pf_marshmallow_swagger(flask_app) self._register_root_url(flask_app) clean_upload()
def propagate_instance_through_network(self, instance_matrix, debug=False): # log.debug('Propagating: {}'.format(instance_matrix)) activation_matrix = [instance_matrix] for layer_index, layer_matrix in enumerate(self.layers_matrices): if layer_index == 0: matrices_pr...
This function calculates the average cost (loss) for a list of instances using a neural network's predictions, comparing them against true class labels. If `applyReg` is True, it adds a regularization term based on the sum of network weights to prevent overfitting. The cost is computed by iterating through each instanc...
def calculate_cost_function(self, instances, applyReg=False): """ Calcultes the cost for a list of instances. applyReg: if true, the sum of network weights will be used (regulariza.) """ j_value = 0 number_of_instances = len(instances) for instance in instances: ...
def propagate_instance_through_network(self, instance_matrix, debug=False): # log.debug('Propagating: {}'.format(instance_matrix)) activation_matrix = [instance_matrix] for layer_index, layer_matrix in enumerate(self.layers_matrices): if layer_index == 0: matrices_pr...
This code trains a neural network using backpropagation with batch processing. It calculates output layer deltas, propagates errors through hidden layers, computes gradients with regularization, and updates weights iteratively. Training stops when error changes stabilize. It also supports gradient checks and plots lear...
def train(self, data, batchSize=0, checkGradients=False, alpha=1, plotError=True): """ Trains the neural network using the backpropagation algorithm. """ totalLayers = len(self.layers_matrices) + 1 delta = [0]*totalLayers numInstances = len(data.instances) ...
def get_next_token(self): if self.pos > len(self.text) - 1: return Token(EOF) try: if self.current_char is None: raise kind = TOKEN_KIND_FOR_SYMBOL[self.current_char] self.advance() return Token(kind) except KeyError: ...
This code parses an expression by matching a left token with its corresponding reverse token, handling nested structures recursively. It checks if the current token matches the expected reverse of the left token, and if not, recursively processes nested expressions. The function returns 'YES' if the expression is valid...
def expr(self, provided_left=None): try: if provided_left is not None: left = provided_left else: self.current_token = self.get_next_token() left = self.current_token self.eat(OPEN_TOKENS) right = self.current_toke...
def find_point_groups(points, debug_img, debug): point_groups = [] all_points_have_group = False while not all_points_have_group: point_index = 0 while point_index < len(points) and points[point_index].have_group: point_index += 1 if point_index < len(points) and not poin...
The function processes an input image to extract and refine Braille characters by detecting key points, grouping them into clusters, creating character representations, resizing for consistency, and removing overlapping regions, with optional debug visualizations.
def get_braille_chars(input_img, debug_img, debug): points = roiFinderV3.get_points(debug_img, debug) if debug: roiFinderV3.display_points_id(input_img, points) point_groups = find_point_groups(points, debug_img, debug) braille_chars = create_braille_chars(point_groups, debug_...
def get_potential_points(thresholded_image): contours, _ = cv2.findContours( thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) return list(brailleReader.Point(contour) for contour in contours) def find_valid_points(points, image, debug): h, w = image.shape count = 1 best_points...
The main task of the code is to process a thresholded image to identify and refine potential points by validating them, sorting by area, removing large points, and returning the filtered list of points. Debugging outputs the count of points if enabled.
def get_points(thresholded_image, debug): points = get_potential_points(thresholded_image) best_points = [] if points: best_points = find_valid_points(points, thresholded_image, debug) if best_points: area_asc_sort(best_points) remove_big_points(best_points, thresholde...
def getSparkSession(collection): log.info("Getting Spark Session") log.debug("Setting Spark properties: MongoDB url: mongodb://{}:{}@{}:27017/{}.{}?authSource=admin".format(mongodbUsername, "***password***", mongodbHost, mongodb, collection)) # get Spark Session spark = SparkSession \ .builder ...
This function processes a MongoDB dataset using specified rules to filter or modify columns, saves the processed data in a chosen format (e.g., parquet/csv), uploads it to an FTP server, sends an acknowledgment, and cleans up resources. It uses Spark for distributed processing, applies rules for data transformation, an...
def vdc(dataset_id, rules, fileFormat, datasetname = None): log.info("Starting VDC") # get Spark Session spark = getSparkSession(dataset_id) # load dataframe log.info("Reading dataset") log.debug("dataset_id: {}".format(dataset_id)) df = spark.read.format("mongo").load() # drop mongoD...
def update_links(self,Rr=1,**kwargs): # Link length parametrization if ("A" in kwargs and "B" in kwargs and "C" in kwargs and "D" in kwargs): self.A0,self.B0,self.C0,self.D0 = kwargs["A"],kwargs["B"],kwargs["C"],kwargs["D"] theta_CA = self.__law_of_cos(self.B0,2*self.A0,self.C0) ...
This code initializes a mechanical or structural model with geometric parameters, defining links, node connections, and transformation matrices. It sets initial angles (theta, phi) to zero, configures link/node radii, and prepares transformation matrices for 3D space. The method then updates the model's geometry, state...
def __init__(self,Rr=1,**kwargs): # Initialize drive link to zero state self.theta = 0 self.phi = 0 self.theta_max = np.deg2rad(25) # Link and node geometry self.link_r = 0.75 self.node_r = 1 # Create node pair assigments self.links = ["A0","A1","...
def mandatory_properties(self): """ MANDATORY FUNCTION.This function will compute all mandatory properties. These properties will be used for OCTP outputs and include: 1. The volume of the OCTP production run (average result of NPT run) in m^3. 2. The box size of the OC...
The function computes self-diffusion coefficients (in m²/s) for independent species using mean squared displacement (MSD) data, applying Yeh-Hummer viscosity corrections if enabled, checking box size validity, and optionally generating plots. It processes multiple files, converts units, and stores results in a datafram...
def self_diffusivity(self, YH_correction=False, box_size_check=False, plotting=False): """ OPTIONAL FUNCTION: The self-diffusion coefficients of the independent species are computed in m^2/s. Parameters ---------- YH_correction : Boolean, optiona...
def get_train_set(train_size): path = '/Users/bbbblues/Desktop/GT_train_notes_new.pickle' notes = pickle.load(open(path, 'rb')) notes_set = [] for song in notes: song_notes = [] for i, item in enumerate(song): song_notes.append((int(item[0]-36), beat_dict[item[1]])) ...
The code trains an encoder-decoder model using Adam optimizer on a musical note dataset. It initializes encoder/decoder networks, combines their parameters, and iterates over epochs to train the model. Losses are tracked, visualized, and saved. Models are periodically saved if loss meets thresholds or at fixed interval...
def start(): encoder = Note_encoder(hidden_size, pitch_input_size, dur_input_size, pitch_embedding_size, dur_embedding_size) decoder = Note_decoder(hidden_size, pitch_input_size, dur_input_size, pitch_embedding_size, dur_embedding_size) all_parameters = list(encoder.parameters()) + list(decoder.parameters()...
def make_blob(start, output, end=None): return { "start": start, "output": output, "end": end if end else start } def make_address_comment(address): return ": ; {:x} ({:x}:{:x})\n".format(address, get_bank(address), get_relative_address(address)) def get_pointer(address, bank=None): raw_pointer = rom[address + 1] * ...
This function generates a list of data blobs representing a movement table structure starting at the given address. It creates a label, adds pointers to nested movement entries, and recursively processes each pointer to build a hierarchical representation of the movement table and its components.
def dump_movement_table(address): blobs = [] label = "NPCMovementTable_{:x}".format(address) if address in symbols: label = symbols[address] blobs.append(make_blob(address, label + make_address_comment(address))) for i in range(4): pointer = get_pointer(address) blobs.append(make_blob(address, "\tdw NPCMovem...
def make_blob(start, output, end=None): return { "start": start, "output": output, "end": end if end else start } def make_address_comment(address): return ": ; {:x} ({:x}:{:x})\n".format(address, get_bank(address), get_relative_address(address)) def get_pointer(address, bank=None): raw_pointer = rom[address + 1] * ...
This function dumps game script data from a ROM by parsing commands and parameters, handling different data types (e.g., bytes, strings, pointers), generating labeled output blobs, and recursively processing branching addresses to avoid loops. It formats command details, resolves symbols, and manages nested structures ...
def dump_script(start_address, address=None, visited=set()): blobs = [] branches = set() if address is None: label = "Script_{:x}".format(start_address) if start_address in symbols: label = symbols[start_address] blobs.append(make_blob(start_address, label + make_address_comment(start_address))) address =...
def Lightcurve_indiv(pars, time, FitParams, SpecNo=99): t = numpy.copy(time).astype(float) params = batman.TransitParams params.t0 = FitParams['FixedPars']['tc'] params.per = 10.**FitParams['FixedPars']['logp'] params.inc = (180./math.pi) * numpy.arccos(FitParams['FixedPars']['cosi']) params.a = 10.**FitParams['...
The code defines a function to generate light curve models and detrending components based on specified fitting parameters. It creates a light curve model (lcmodel) using either individual spectra or section-based fitting. Depending on the specified ramp type (PolyRamp or GPRamp), it constructs a full model (fullmodel)...
def ParamModel(pars, data, visit, FitParams, SpecNo=99): if FitParams['FitType']=='Spectra_Indiv': lcmodel = Lightcurve_indiv(pars, data['time'], FitParams, SpecNo=SpecNo, visit=visit) else: lcmodel = Lightcurve(pars, data['time'], Section=FitParams['Section'], SpecNo=SpecNo, Telescope='HST', visit=visit) if FitPar...
def Lightcurve_indiv(pars, time, FitParams, SpecNo=99): t = numpy.copy(time).astype(float) params = batman.TransitParams params.t0 = FitParams['FixedPars']['tc'] params.per = 10.**FitParams['FixedPars']['logp'] params.inc = (180./math.pi) * numpy.arccos(FitParams['FixedPars']['cosi']) params.a = 10.**FitParams['...
The main task of the code is to generate and detrend light curve models for astronomical data. It creates a lightcurve model (lcmodel) based on the specified fit type, constructs a full charge model (fullmodel), and computes a detrended version (detrendmodel) by dividing fullmodel by lcmodel. The function returns all t...
def RECTEModel(pars, data, visit, FitParams, SpecNo=99): if FitParams['FitType']=='Spectra_Indiv': lcmodel = Lightcurve_indiv(pars, data['time'], FitParams, SpecNo=SpecNo, visit=visit) else: lcmodel = Lightcurve(pars, data['time'], Section=FitParams['Section'], SpecNo=SpecNo, Telescope='HST', visit=visit) fullmodel ...
def PhaseTimes(time, t0, period, t0center=False): if t0center: phase = numpy.mod((time-t0)-period/2.,period) / period else: phase = numpy.mod((time-t0),period) / period return phase def ParamModel(pars, data, visit, FitParams, SpecNo=99): if FitParams['FitType']=='Spectra_Indiv': lcmodel = Lightcurve_indiv(pars, da...
The function generates diagnostic plots for light curve detrending and parameter analysis. It creates subplots showing detrended light curves phased by period, comparing observed data with model predictions. If MCMC is enabled, it also plots parameter distributions (e.g., c1-c4, phaseF0, u1-u2) across spectra with erro...
def Phase_Spectra_Diag_Plots(inputpars, dataAll, FitParams, MCMC=False): if MCMC: # setup for output labels = list(inputpars.keys()) pars = {} for i in range(len(labels)): pars[labels[i]] = inputpars[labels[i]][0] else: pars = inputpars t0 = pars['tc'] period = 10.**pars['logp'] nspec = dataAll[1]['flux'].s...
def RECTEModel(pars, data, visit, FitParams, SpecNo=99): if FitParams['FitType']=='Spectra_Indiv': lcmodel = Lightcurve_indiv(pars, data['time'], FitParams, SpecNo=SpecNo, visit=visit) else: lcmodel = Lightcurve(pars, data['time'], Section=FitParams['Section'], SpecNo=SpecNo, Telescope='HST', visit=visit) fullmodel ...
The code generates detrended light curve and residual plots for astronomical data, using specified models (RECTE or Param) and orbital parameters. It handles two fit types: 'Broad' (plotting all visits) and 'Spectra_Indiv' (individual spectral channels). Plots show phased data with model curves, saving results as PNGs ...
def CombinedVisitPlots(pars, dataAll, FitParams): if FitParams['FitType'] == 'Spectra_Indiv': t0 = 2457306.97352 period = 10. ** 0.0854663976564351 else: t0 = pars['tc'] period = 10.**pars['logp'] if FitParams['FitType']=='Broad': fig = plt.figure() ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3) ax...
def RECTEModel(pars, data, visit, FitParams, SpecNo=99): if FitParams['FitType']=='Spectra_Indiv': lcmodel = Lightcurve_indiv(pars, data['time'], FitParams, SpecNo=SpecNo, visit=visit) else: lcmodel = Lightcurve(pars, data['time'], Section=FitParams['Section'], SpecNo=SpecNo, Telescope='HST', visit=visit) fullmodel ...
This code generates and saves plots of detrended light curves and residuals for a specific astronomical visit, using parameters from FitParams. It handles different model types (e.g., Broad, RECTE) and sections (Transit, Phase, Eclipse), plotting observed data, model fits, and residuals. Two figures are created: one sh...
def SingleVisitPlot(pars, data, FitParams, visit): if FitParams['FitType'] == 'Spectra': t0 = 2458329.200100647 period = 10. ** 0.780638562833854 else: t0 = pars['tc'] period = 10.**pars['logp'] fig = plt.figure() ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3) ax2 = plt.subplot2grid((4, 1), (3, 0), sha...
def blank_teamcomp(): return { 'type': None, 'players': [] } def search_player(team, action, team_comps, ignore_list): words = action.split(' ') if (action.find('misses') > 0) or (action.find('makes') > 0): add_player_to_comp(team_comps[team], words[0] + ' ' + words[1], ignore_list) elif action.find('enter...
The function identifies starting lineups for two teams by parsing data lines, populating each team's composition with up to 5 players while excluding substituted players tracked in ignore lists. It stops once both teams have 5 players, then sets their composition types based on positions and misses.
def find_starting_comp(lines, starting_line, team_comps, team1, team2, positions, misses): #players that have entered via substitution are stored in these 2 lists, so they dont #get counted in the starting comp t1_ignore_list = [] t2_ignore_list = [] team_comps[team1] = blank_teamcomp() team_comps[team2] = blank...
def change_player(comp, player_out, player_in): truePlayerOut = remove_noise(player_out) truePlayerIn = remove_noise(player_in) if truePlayerIn in comp['players'] and truePlayerOut in comp['players']: return # print(comp) # print('In <<<<', truePlayerIn) # print('Out >>>>', truePlayerOut) comp['players'].re...
The function processes game actions to update team compositions and track shooting statistics. It identifies substitutions, adjusts player data, and increments 2/3-point attempt/hit counters based on action keywords ('misses', 'makes'). Special handling applies for specific players, ensuring accurate tracking of team s...
def extract_line_data(team, other_team, action, team_comps, game_type_data, positions, misses): words = action.split(' ') #this section is in charge of substitutions if action.find('enters') > 0: player_in = words[0] + ' ' + words[1] #Mbah and Lemon are 2 players whose names do not follow the pattern, for som...
def get_team_names(line): columns = line.split(',') team1 = columns[1] team2 = columns[5][:-1] return team1, team2 def find_starting_comp(lines, starting_line, team_comps, team1, team2, positions, misses): #players that have entered via substitution are stored in these 2 lists, so they dont #get counted in the s...
The code processes a game event log file to extract and organize player position data and team compositions. It reads team names, identifies starting lineups, and iterates through event lines to populate a data structure with player actions and team configurations, using preloaded position mappings and handling missing...
def get_game_data(file, team_comps, data): player_position_file = open('results/player_team_position.txt') player_positions = json.load(player_position_file) #a miss file was manually created to fill misses in the dataset used to get player positions player_position_miss_file = open('results/player_team_position_m...
def KeyPressed(key): '''determines if key has just been pressed''' return keys[key] and not lastkeys[key] def loadWavFile(file): '''load given wave and set render wav and render data file - the wav file to load ''' global currSamples, currFreq, currSeconds, currbytesPerSample, sampleStart ...
This function handles user key inputs for an audio visualization application, enabling file selection (UP/DOWN/RETURN), sample navigation (LEFT/RIGHT), zoom adjustments (UP/DOWN), step control (Q/A), and toggling features like model line (B), overlay (O), and sampling (S). It updates display parameters while enforcing ...
def gameKeys(): ''' react to any specific user key presses ''' global sampleStart,scale,step, modeline, ldelay, samplingOn, overlay, fileChosen, selectingFile #file section keys if (selectingFile): if KeyPressed(pygame.K_UP) and fileChosen > 0: fileChosen -= 1 if KeyPressed(p...
def screenMetrics(): '''pre calculates some screen metrics''' global scrHeight,scrWidth,scrMid,scrThird,scrTwoThird,scrSixth,waveAmp, font global upperDisplay,lowerDisplay,modifiedDataPosition,originalDataPosition scrHeight = win.get_height() scrWidth = win.get_width() scrMid = scrHeight/2 ...
The main task of the code is to initialize the Pygame library, configure the game window and font, load necessary resources, record the game start time, and initiate the game loop to begin gameplay.
def main(): '''initialise pygame library, set window and font, start gameloop''' global win, font, gametime pygame.init() win = pygame.display.set_mode((1000, 800)) font = pygame.font.SysFont("monospace",20) screenMetrics() getwavFiles() gametime = pygame.time.get_ticks() gameLoop()
def _plot_stat_error_bar(self, ax: plt.Axes): """ Plot statistical test results per region. :return: axis instance with statistical test results per region :rtype: plt.Axes """ plt_settings = self.plot_settings.error_bar_plot_settings ax2 = ax.twinx() x_pos_ba...
The function generates a plot displaying statistical test results for each input region, sets the x-axis to the data's min/max range, adds error bars, saves the plot as an image, and separately saves the legend. It uses `_plot_stat_error_bar` for error visualization and handles file paths via `_plot_path` and `_save_le...
def plot_stats_per_region(self, ): """ The function plots results of the statistical tests per input region and saves the plot as an image. """ fig, ax = plt.subplots(constrained_layout=True) # set x axis limits to min and max of data ax.set_xlim(self.candidate_regions....
def _plot_stat_error_bar(self, ax: plt.Axes): """ Plot statistical test results per region. :return: axis instance with statistical test results per region :rtype: plt.Axes """ plt_settings = self.plot_settings.error_bar_plot_settings ax2 = ax.twinx() x_pos_ba...
The code generates a plot with two subplots: the top shows model predictions and regions, while the bottom displays statistical test results (ANEES/binom) with error bars, using input data and predictions. It ensures aligned x-axes, labels, and saves the visualization as a file.
def plot_stats_and_predictions(self, data, predictions: typing.Union[np.ndarray, UnivariateGaussian], test_type: str = 'anees',): """ Plot statistical test results and predictions. :param data: data used for predictions :type data: IOData :para...
def _plot_stat_error_bar(self, ax: plt.Axes): """ Plot statistical test results per region. :return: axis instance with statistical test results per region :rtype: plt.Axes """ plt_settings = self.plot_settings.error_bar_plot_settings ax2 = ax.twinx() x_pos_ba...
This function generates a two-panel plot visualizing statistical test results (ANEES/binom) and ground truth distribution. It plots distance-to-ground-truth data in the top panel with error bars, and test results as colored regions in the bottom panel, saving the figure with specified settings and legends.
def plot_stats_and_ground_truth_dist(self, data, dist_to_ground_truth: np.ndarray, test_type: str = 'anees',): """ Plot statistical test results and ground truth distribution. :param data: data used for predictions :type data: IOData :pa...
def is_present(self): if self.base is None: return False else: return True def publish_measured_js(self): msg = JointState() msg.name = 'ur5_ambf' msg.position = self.measured_js() msg.header.stamp = rospy.Time.now() self.pub_measured_js.pu...
This code continuously checks for robot presence, reconnects if disconnected, publishes measured joint states, computes forward kinematics, and controls joint motion via position or velocity commands based on a flag, repeating at a set rate until ROS shuts down.
def run(self): while not rospy.is_shutdown(): if not self.is_present(): self.base = self.client.get_obj_handle( self.name + '/base_link') print("Tried to reconnect") self.publish_measured_js() self.FK(self.measured_js()) ...
def normalize_data(data): max = data.max() min = data.min() if max==min: if min!= 0: # assume entire image is single volume normalized_data = data/min # here, else is implicit - image is all zero and will remain that way else: normalized_data = (data - min) / float(ma...
The main task of the code is to process an NRRD volume file by parsing command-line arguments, validating input paths, reading the NRRD data, normalizing and scaling it, then saving the processed volume as PNG images and a YAML file containing metadata like dimensions, origin, and scaling factors. The code ensures dire...
def main(): # Begin Argument Parser Code parser = ArgumentParser() parser.add_argument('-n', action='store', dest='nrrd_file', help='Specify Nrrd File') parser.add_argument('-p', action='store', dest='image_prefix', help='Specify Image Prefix', default='plane0') parser.add_ar...
def feed_forward(): global z1, a1, z2, a2 z1 = np.add(np.matmul(w1, inputs), b1) a1 = ReLU(z1) z2 = np.matmul(w2, a1) a2 = sigmoid(z2) def feed_forward_log(epoch_num, batch_num): log(f"Epoch {epoch_num}, Batch {batch_num}") log(f"inputs:\t{inputs}") log(f"label:\t{label}") log(f"w1:\t{w1}") log(f"w2:\t{w2}")...
The function trains a neural network batch by performing forward propagation, calculating cost and gradients, backpropagating errors, and updating model weights. It processes each data point in the batch, logs intermediate results, and accumulates epoch-wise costs for monitoring training progress.
def train_batch(batch, epoch_num, batch_num): global inputs, label, epoch_costs batch_labels, z1s, a1s, z2s, a2s = [], [], [], [], [] batch_inputs = [] for datapoint in batch: # Initialise inputs and label of datapoint inputs = datapoint[0] batch_inputs.append(inputs) label = datapoint[1] # Save label to...
def open_log(): global log_file log_file = open(log_filename, 'w') log("Log opened.") def load_dataset(): global dataset dataset = pickle.load(open(dataset_filename, 'rb')) log("Dataset loaded.") def initialise_model(): global w1, w2 w1 = initialise_weights(3, 3) w2 = initialise_weights(1, 3) def train_batch(b...
The code trains a machine learning model over multiple epochs using batches from a dataset, logs progress, tracks epoch costs, identifies the epoch with the minimum cost, and visualizes the cost trend. It initializes the model, processes each batch, updates parameters, saves the trained model, and outputs the optimal e...
def train(): open_log() load_dataset() initialise_model() for i in tqdm(range(num_epoch)): # Repeat for num_epoch times for j in range(len(dataset)): # Repeat for each batch in dataset train_batch(dataset[j], i, j) dump_model() close_log() global_min = min(epoch_costs) print(f"Global min: {global_min}") ...
def is_empty(rule, hold_state): d = 1 if rule[3] == 1: hold_ = hold_state.num_matrix[rule[0]][rule[1] + d] while hold_ >= 0: if hold_ == 0: return True d += 1 if rule[1] + d == hold_state.size: ...
The function generates valid permutations for empty cells in a board based on given rules. It checks if the board is empty, collects filled cells, filters available permutations to ensure they fit the filled cells, and returns the list of valid permutations.
def remained_values(self, rule, board_state): if not self.is_empty(rule, board_state): return [] hold_ = [] filled_cells = self.filled(rule, board_state.num_matrix) for i in self.available_perms(rule): hold_.append([i, filled_cells]) hold = [] for ...
def calculate_intersections(self): for rule in self.rules: d = 1 if rule[3] == 1: while self.intersection_matrix[rule[0]][rule[1] + d] >= 0: self.intersection_matrix[rule[0]][rule[1] + d] += 1 d += 1 if rule[1] +...
This code initializes a puzzle-solving system by setting up a board, processing rules, calculating intersections, and sorting rules based on remaining values. It copies the board's matrix, computes intersections, and organizes rules by their constraints and remaining possibilities to prioritize solving order.
def __init__(self, size, closed, rules): self.board_ = Board(size, closed, rules) hold_rules = [] self.rules = [] self.intersection_matrix = np.copy(self.board_.num_matrix) self.calculate_intersections() self.intersected_rules = [] self.result = [] for (i,...
def remained_values(self, rule, board_state): if not self.is_empty(rule, board_state): return [] hold_ = [] filled_cells = self.filled(rule, board_state.num_matrix) for i in self.available_perms(rule): hold_.append([i, filled_cells]) hold = [] for ...
This code implements a backtracking algorithm to solve a board game by exploring possible moves. It uses a stack to manage states, prioritizes rules based on remaining values, generates new states, and checks constraints. If a winning state is found, it prints the solution; otherwise, it exhaustively searches until all...
def backtrack(self): d = 1 stack = [self.board_] while stack: d += 1 # print(self.rules) hold_state = stack.pop() # hold_state.print_board() # time.sleep(2) # os.system('cls' if os.name == 'nt' else 'clear') # pr...
def update_height(node): node.height = max(height(node.left), height(node.right)) + 1 def height(node): if node is None: return -1 else: return node.height def left_rotate(self, x): y = x.right y.parent = x.parent if y.parent is None: self.root = y ...
This function rebalances an AVL tree by checking each node's height and performing rotations to maintain balance. It traverses upward from the given node, updating heights and applying left/right rotations based on subtree height differences. If a node's left subtree is significantly taller, it rotates left then right;...
def rebalance(self, node): while node is not None: update_height(node) if height(node.left) >= height(node.right) + 2: if height(node.left.left) < height(node.left.right): self.left_rotate(node.left) self.right_rotate(node) ...
def obj_to_pretty_str(o, no_clobber=False, no_wrap=False, column_width=None): """Serialize object to str - Create a normalized string representation of the object that is suitable for using in a diff. - XML and PyXB is normalized here. - Serialization that breaks long lines into multiple lines is...
The function `assert_match` compares the string representation of an object (`current_obj`) against a sample file's content. If they mismatch, it either raises an exception with a detailed diff, updates the sample file, or opens a diff tool (meld) to review the discrepancy. The core task is to validate consistency betw...
def assert_match( current_obj, file_post_str, sample_ext=".sample", no_wrap=False, # column_width=DEFAULT_DIFF_COLUMN_WIDTH, ): file_ext_str, current_str = obj_to_pretty_str(current_obj, no_wrap=no_wrap) sample_file_name = _format_file_name(file_post_str, sample_ext) log.info('Using samp...
def update_size(self, enc_size): self.enc_size_2d = enc_size self.enc_hw = self.enc_size_2d[0] * self.enc_size_2d[1] def add_reference_frame(self, enc_embs=None, mask=None, obj_nums=None): frame_step = self.frame_step self.last_mem_step = frame_step curr_enc_embs, curr_one_hot_m...
The code processes encoder features through an LSTT block, handling either the first frame (adding reference embeddings) or subsequent frames (matching/propagating features). It returns LSTT outputs including encoded embeddings, short-term, and long-term memory states for dynamic instance tracking in vision tasks.
def forward(self, enc_embs, id_mask=None, new_inst_exist=False): """Forward function of LSTT block. Args: enc_feat (Tensor): backbone encoder feature of images. id_mask (Tensor): idenfication mask of multiple instances in images shape (batch_size, max_obj_num+1, ...
def createData(self, uniqueValues): data = dict() for i in range(len(uniqueValues)): data[uniqueValues[i]] = np.zeros(len(uniqueValues)) data[uniqueValues[i]][i] = 1 return data def structToData(self, struct, nregistration, nbirthday, nscore): data = np.array([], dtype="float32") data = np.append(data, ...
The code initializes a class to load and preprocess training, testing, and label datasets for a machine learning task. It combines training and test data, encodes categorical features (country, product type, family), splits data into training/validation sets, and calculates claim-type probabilities for classification. ...
def __init__(self): print("load training data") self.dataframe_train = np.genfromtxt("input_train.csv", delimiter=",", names = True, dtype=types) print("load testing data") self.dataframe_test = np.genfromtxt("input_test.csv", delimiter=",", names = True, dtype=types) print("load labels data") self.datafram...
def get_routes(self): if not self.keen_auth(): raise RuntimeError("Cannot authorize") response = self.keen_request("rci/show/ip/route").json() routes = dict() for item in response: if item["interface"] == self.default_interface: dst = self.__strip...
This code adds a static IP route via an API, handling IPv4/IPv6 validation, checking for existing routes, and returning success/failure status with detailed logs. It uses a default interface if none is specified and ensures routes are only added once.
def add_ip_route(self, route_ip, interface=False): if not interface: interface = self.default_interface existing_routes = self.get_routes().keys() if route_ip in existing_routes: click.echo(f"Route already exists {route_ip}") return ip_type = self.__...
def parse(line=""): return line.split() def do_checktries(self): if WordleConsole.tries == 0: print("You lose; End of Game") print("Correct answer: {}".format(self.game.answer)) self.do_restart("") else: self.do_prompt(self.tries) return Wo...
This code processes user input in a Wordle-style game by validating the word's length and existence, then checking if it matches the target word. It updates game feedback, tracks remaining attempts, and triggers restarts or prompts based on success/failure.
def do_run(self, line): args = parse(line) arg = str(args[0]) #while WordleConsole.tries != 0: if wc.wlen(arg) == False: print("Invalid lenght: must be 5 letters long") return if wc.real(arg) == False: print("Invalid word: word doesn't exist")...
def check_audio_validity(concat_files, time_offset_mins): concat_len = len(concat_files) if concat_len < 4 or concat_len > 5: log_fatal('incorrect file count: ' + concat_files[0]) elif time_offset_mins < 0 or time_offset_mins > 14: log_fatal('invalid time offset: ' + str(time_offset_mins)) ...
The code creates an audio file by concatenating input files with a time offset, saves it in a directory structured by date, and handles existing files by renaming them with a timestamped backup suffix before generating a new file.
def create_audio_file(concat_files, time_offset_mins_int): global time_skew months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] # will exit if invalid params check_audio_validity(concat_files, time_offset_mins_int) file = concat_files[len(concat_files) - 1...
def make2digit(some_int): res = str(some_int) if some_int < 10: res = '0' + res return res def log_it(msg): print(msg, flush=True) def check_for_multi_silence(file): silence_end_idx = -1 cmd = 'ffmpeg -i {} -af silencedetect=n=-50dB:d=120.0 -f null -'.format(file) (output, err) = e...
(The code processes files for a specific date by locating partial archive files and checking each for multiple silence instances. It formats the date, logs the task, retrieves relevant files, and applies a silence-check function to each.)
def process_day(year, month, day): day_path = "{}-{}-{}".format(year, make2digit(month), make2digit(day)) log_it("Process day {}".format(day_path)) src_path = '{}/{}/{}/kzsu_archive*.partial'.format(base_path, year, day_path) files = glob.glob(src_path) for file in files: check_for_multi_sil...
def get_file_datetime(file): date_str = file[-17:-9] + '_' + file[-8:-4] date = datetime.datetime.strptime(date_str, '%Y%m%d_%H%M') return date def make2digit(some_int): res = str(some_int) if some_int < 10: res = '0' + res return res def log_it(msg): print(msg, flush=True) def execu...
This function creates an audio file by concatenating two audio files using FFmpeg, applying an optional time offset. It generates a date-based directory structure, constructs a filename with timestamp, and executes a command to merge files. If the output file exists, it backs up the existing file before overwriting. Th...
def create_audio_file(prev_file, file, time_offset_mins_int): date = get_file_datetime(file) year = date.year month = date.month day = date.day hour = date.hour time_offset_opt = '' if time_offset_mins_int != 0: total_seconds = (60 - time_offset_mins_int) * 60 mins = math.flo...
def log_it(msg): print(msg, flush=True) def get_src_files(year, month, day): month2d = make2digit(month) day2d = make2digit(day) path = '{}/{}/{}-{}-{}/kzsu_archive_{}{}{}_*.mp3'.format(SRC_PATH, year, year, month2d, day2d, year,month2d,day2d) files = glob.glob(path) return files def get_prev_fil...
The function processes audio files for a given date by retrieving source files, checking for a previous file, and concatenating valid consecutive files into audio segments. It manages file lists, ensures proper time alignment, and creates audio outputs while handling skips due to timing drift or invalid start times.
def process_day(year, month, day): log_it("Process day {}, {}, {}".format(year, month, day)) files = get_src_files(year, month, day) prev_file = get_prev_file(year, month, day) if prev_file: files.insert(0, prev_file) if len(files) == 0: log_it("no files for: {}-{}-{}".format(year, ...
def check_audio_validity(concat_files): if len(concat_files) != 4: log_fatal("Improper file count: " + concat_files[0]) prev_idx = -1 prev_hour = -1 for file in concat_files: (hour, idx) = get_file_params(concat_files[0]) if prev_hour != -1 and (hour != prev_hour or idx != prev_...
This function generates an audio file by concatenating provided audio files into a specified directory structure. It validates inputs, calculates start time, creates dated directories, names output files with timestamps, and uses ffmpeg to merge files. If the output file exists, it backs up the existing file before ove...
def create_audio_file(year, month, day, concat_files): global MONTHS # will exit if invalid params check_audio_validity(concat_files) start_hour, start_idx = get_file_params(concat_files[0]) start_hour = start_hour + math.floor(start_idx / 4) file = concat_files[len(concat_files) - 1] outd...
def log_it(msg): print(msg, flush=True) def get_src_files(year, month, day): month2d = make2digit(month) day2d = make2digit(day) path = '{}/{}/{}/{}/kzsu_archive_{}{}{}*'.format(SRC_PATH, year, months[month-1], day2d, year, month2d, day2d) print("path: " + path) files = glob.glob(path) return...
The function processes a specified date's files by checking if consecutive hourly audio files exist. If so, it merges them into a single audio file. If files are missing or not consecutive, it logs an error. The task involves retrieving files, validating hourly sequences, and combining valid pairs while handling edge c...
def process_day(year, month, day): log_it("Process day {}, {}, {}".format(year, month, day)) files = get_src_files(year, month, day) if len(files) == 0: log_it("no files for: {}-{}-{}".format(year, month, day)) return #0053 - 0153, 0153 - 0253 prev_hour = -100 prev_file = None...
def log_it(msg): print(msg, flush=True) def get_src_files(year, month, day): global MONTHS day2d = make2digit(day) path = '{}/{}/{}/{}/podkeeper *.mp3'.format(SRC_PATH, year, MONTHS[month-1], day2d) files = glob.glob(path) files.sort(key=lambda x: get_sort_key(x)) return files def get_file_pa...
The main task of the code is to process daily files by validating their chronological order (hour/index sequence), grouping them into batches of four consecutive files, and generating audio files from these batches. It logs errors if files are out of order and ensures proper concatenation of valid file sequences for au...
def process_day(year, month, day): log_it("Process day {}, {}, {}".format(year, month, day)) files = get_src_files(year, month, day) if not files or len(files) == 0: log_it("no files for: {}-{}-{}".format(year, month, day)) return concat_files = [] hour = -1 idx = -1 is_fi...
def sort_list(self,site): site = site or self.site if site is None: return '''sort the list''' if type(site) is str: site = [site] else: site = list(site) ssite = [] for s in site: s = str(s) while s...
(The login function decrypts stored credentials from a key file (~/.cylog.npz) using a Fernet key. It checks for the key file's existence and required encrypted data (ciphered_user/pass). If missing, it initializes and sets up credentials. If 'force' is True, it re-prompts for credentials. Returns decrypted (username, ...
def login(self,site=None,force=False): ''' Reads encrypted information from ~/{dest_path}/.cylog.npz Keyword arguments ---------- site = False (so self.site is default) string of anchor URL for site to associate with username and password fo...
def random_chromosome(size): #making random chromosomes return [ random.randint(1, size) for _ in range(size)] def fitness(chromosome, maxFitness): horizontal_collisions = sum([chromosome.count(queen)-1 for queen in chromosome])/2 left_diagonal_collisions_mat = sorted(reduce(lambda x,y: x + [y - len(x)], ch...
The code implements a genetic algorithm to solve the N-Queens problem. It initializes a population of random board configurations, evaluates their fitness (non-attacking queen pairs), and iteratively evolves the population through selection, crossover, and mutation. The goal is to reach a perfect solution where all que...
def solve(nq): start_time = time.time() maxFitness = (nq * (nq - 1)) / 2 # 8*7/2 = 28 population = [random_chromosome(nq) for _ in range(100)] ranks = sorted(population, key= lambda x: fitness(x, maxFitness), reverse= True) initial = {'state':[{'x':y + 1,'y':z} for (y,z) in enumerate(ranks[0])], 'f...
def build_logo_attachment(self): dataloop_image_id = 'dataloop_logo' dataloop_logo_file_content = open(assets_folder + '/logo-dataloop.png', 'rb').read() dataloop_logo_base64_utf8_str = base64.b64encode(dataloop_logo_file_content).decode('utf-8') return { "filename": "logo-da...
The main task of the code is to generate a customized HTML message by replacing placeholders like '##title##' and '##description##' with dynamic data from the input, embedding attachments (logo and icon) using CID references, and returning the compiled HTML along with the attachments for email or notification use.
def compile_html(self, html_template_string, application_input: ApplicationInput): attachments = [] compiled = html_template_string compiled = compiled.replace('##title##', application_input.notification_info.event_message.title) compiled = compiled.replace('##description##', application...
def TWratio(beta, alpha, q, WoSratio, Cdo, K, n, V, ROC, g, acc): return (beta / alpha) * ( ((q / beta) * (WoSratio) ** -1) * ( Cdo + K * ((n * beta * WoSratio) / (q)) ** 2) + ROC * V ** -1 + acc * g ** -1) def TWratioTakeoff(fobs, fms, fv, clmaxto, stofl, WSRatio, Cdo, rolling_coef): re...
The code generates a plot visualizing thrust-to-weight (T/W) ratio constraints against wing loading (W/S) for an aircraft. It iterates over 100 W/S values, calculating T/W for cruise, service ceiling, takeoff, and landing using specific parameters. Each constraint is plotted with distinct line styles, labeled, and a fi...
def plot(): for i in range(100): WoS_inc = 0.1 + i * 0.1 # Getting cruise constraint # ToWo_inc_cruise = TWratio(BETA, ALPHA, Q, WoS_inc, CDO, K, 1, V, 0, g, ACC) ToWo_inc_cruise = TWratio(0.9654, 0.62856, 76.88, WoS_inc, 0.01864, 0.0464, 1, 286.928, 0, g, 0) x_cruise.append(...
def find_adjacent(tiles: Tiles): for tile in tiles.values(): for possible_neighbor in tiles.values(): if ( tile.id != possible_neighbor.id and tile.id not in possible_neighbor.adjacent_tiles ): if is_adjacent(tile, possible_neighbor): ...
The code assembles a puzzle image from tiles, identifies a monster pattern, and calculates remaining water markers after accounting for all monster occurrences. It constructs the image, removes borders, searches for the monster in all rotations/flips, and returns the difference between total water and monster water cou...
def part2(): tiles = deepcopy(tiles_input) size = int(sqrt(len(tiles))) tiles = find_adjacent(tiles) corners = find_corners(tiles) top_left = next(iter(corners.values())) image: List[List[Tile]] = [] for _ in range(size): row = [] if len(image) == 0: row.append(t...
def equalise_table(table): """makes sure there are no rows with less columns than other rows""" max_row_length = 0 for row in table: row_length = len(row) max_row_length = max(max_row_length, row_length) for row in table: row_length = len(row) if row_length < max_row_len...
The main task of the code is to convert a 2D list table into a formatted raw text table with aligned columns. It equalizes row lengths, calculates column widths, constructs lines with proper spacing and separators ("|"), handles multi-line rows, and ensures output adheres to a line length limit while warning of formatt...
def format_table(table): """Formats a table from a list into raw text""" output = "" equalise_table(table) column_widths = get_column_widths(table) for row in table: str_line = add_row_break(column_widths) row_lines, num_lines = get_lines(row, column_widths) for i in range(n...
def get_pre_topic_text(version: Version) -> tuple[str, dict[str, int]]: file_sql = Path("input/starting_sql.sql").read_text(encoding="utf-8") categories, category_info = generate_categories(version) pre_topic_text: str = file_sql + "\n" + "".join(categories) + "\n" return pre_topic_text, category_info...
The function generates a help table by combining pre-topic text with processed CSV data, linking categories, and formatting into a string. It reads version-specific CSV information, connects it to category details, and constructs a table using parameters like version, concat_size, port, and verbose. The result is a con...
def generate_help_table(version: Version, concat_size: int, port: int, verbose: bool) -> str: pre_topic_text, category_info = get_pre_topic_text(version) csv_information = read_csv_information(version, port) link_help_categories(csv_information, category_info) table_information = make_table_information(...
def recall(self): # Recall of each class. # Same as true positive rate. See truePositiveRates() return self.truePositiveRates() def precision(self): # Precision of each class # Number of true positive predictions divided by the total number of positive predictions TP = se...
The code generates a formatted string representation of a confusion matrix, including abbreviated labels, observed/predicted counts, class recalls, precisions, and overall accuracy. It dynamically adjusts formatting based on data size and label lengths, creating a human-readable table with headers, separators, and stat...
def __str__(self): numExamples = np.sum(self.confMat) width = np.maximum(5, np.ceil(np.log10(numExamples))) if self.labels is not None: min_label_len = np.min([len(l) for l in self.labels]) label_abv_len = min_label_len for k in range(0, min_label_len): ...
def sanitize_address(addr: str | tuple[str, str], encoding: str = "utf-8") -> str: if isinstance(addr, str): addr = parseaddr(force_text(addr)) nm, addr = addr try: nm = Header(nm, encoding).encode() except UnicodeEncodeError: nm = Header(nm, "utf-8").encode() try: ...
The code's main task is to verify and send an email message via a configured SMTP host. It validates recipients, sender, and headers, sets the message date, sanitizes addresses, and triggers an email event. It tracks sent emails, resets the counter when reaching a limit, and quits the SMTP connection if configured.
def send( self, message: Message, envelope_from: str | tuple[str, str] | None = None ) -> None: """Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command. """ assert message.send_to, "No recip...
def _mimetext(self, text: str | None, subtype: str = "plain") -> MIMEText: """Creates a MIMEText object with the given subtype (default: 'plain') If the text is unicode, the utf-8 charset is used. """ charset = self.charset or "utf-8" return MIMEText(text, _subtype=subtype, _char...
This code constructs an email message (MIMEBase) by handling text/plain, text/html, and attachments. It creates multipart structures when needed, sets headers (subject, sender, recipients), processes attachments with proper encoding, and ensures compliance with SMTP standards.
def _message(self) -> MIMEBase: """Creates the email""" ascii_attachments = current_app.extensions["mail"].ascii_attachments encoding = self.charset or "utf-8" attachments = self.attachments or [] msg: MIMEBase if len(attachments) == 0 and not self.alts: # No...
def _create_cells(self): for i in range(self._num_cols): col_cells = [] for j in range(self._num_rows): col_cells.append(Cell(self._win)) self._cells.append(col_cells) for i in range(self._num_cols): for j in range(self._num_rows): ...
This code initializes a maze structure with specified dimensions and cell sizes, creates cells, sets entrance/exit, generates random paths using a recursive backtracking algorithm, and resets visited flags for traversal. It uses a seed for reproducibility and handles window integration for visualization.
def __init__( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None ): self._x1 = x1 self._y1 = y1 self._num_rows = num_rows self._num_cols = num_cols self._cell_size_x = cell_si...
def gain(self): ''' If gain is already set, return it Otherwise, calculate gain from srcAudioFiles and return ''' if self._gain is not None: return self._gain print("Analyzing audio files for best possible gain increase...") best_gain = None f...
The method applies a volume gain to each audio file in `srcAudioFiles`, creating new files with a '_louder' suffix unless the gain is 1, which skips processing. It sets `new_audio_files` with the processed files, adds them to `files_to_clean` if not in 'LOUDEN' mode, and logs progress if verbose.
def loudenAudio(self): ''' Sets newAudioFiles Creates a copy of each file in srcAudioFiles and applies gain If gain == 1 then skips copying and just assigns newAudioFiles to srcAudioFiles ''' if self.gain() == 1: print("Gain is 1... no loudening needed") ...
def newAudioFiles(self): ''' If new audio file list is already set, return it Otherwise, copy and louden the source audio files and return the new list ''' if self._new_audio_files is not None: return self._new_audio_files self.loudenAudio() return se...
This function matches each video file to the best audio file by comparing scores, trims the matched audio to align with the video's timing, and stores the results. It preprocesses audio, extracts video audio if needed, iterates through video-audio pairs, identifies optimal matches, trims audio segments, and logs trimme...
def matchVideoToAudio(self): ''' Sets the matches array Find the best audio match for each video file, along with start/stop times and score ''' self.newAudioFiles() # Pre-gain audio if not self._video_audio_extracted: self.extractAudioFromVideo() # D...
def update_info_lines(self): return self.update_info(self.grid.get_line) def update_info_columns(self): return self.update_info(self.grid.get_column) def update_info_squares(self): return self.update_info(self.grid.get_square)
The main task of the code is to check if any of the three methods—update_info_lines, update_info_columns, or update_info_squares—have updated information. It combines their results using logical OR and returns a boolean indicating whether any update occurred.
def step(self): has_updated = self.update_info_lines() has_updated |= self.update_info_columns() has_updated |= self.update_info_squares() return has_updated
def create_sim(gym, gpu_physics=0, gpu_render=0, frict_coeff=7.83414394e-01): """Set the simulation parameters and create a Sim object.""" sim_type = gymapi.SIM_FLEX sim_params = gymapi.SimParams() sim_params.dt = 1.0e-4 # Control frequency sim_params.substeps = 1 # Physics simulation frequency (m...
The code simulates the mechanical behavior of flexible tubes under specified physical properties and environmental conditions. It parses input parameters, initializes a physics simulation, loads tube assets with material properties, sets up a scene with multiple environments, and runs a simulation loop to analyze tube ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--type', default='tube_32x40', type=str, help='Type of the tube. Choice of tube_47x54, tube_64x80, tube_91x106, tube_126x146') parser.add_argument('--resolution', default='sparse', type=str, help='Resolution of the tube. Choice of sparse, d...
def create_sim(gym, indent_dist, indent_steps, frict_coeff): """Set the simulation parameters and create a Sim object.""" sim_type = gymapi.SIM_FLEX sim_params = gymapi.SimParams() sim_params.dt = 1.0e-4 # Control frequency sim_params.substeps = 1 # Physics simulation frequency (multiplier) s...
This code simulates indentation experiments on a BioTac tactile sensor using various indenter geometries. It parses user-defined parameters (elasticity, friction, indentation steps), sets up a physics simulation environment, loads 3D assets, runs the indentation process, and optionally exports results to HDF5. The main...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--elast_mod', default=1.55223093e+06, type=float, help="Elastic modulus of BioTac [Pa]") parser.add_argument('--poiss_ratio', default=3.16454280e-01, type=float, help="Poisson's ratio of BioTac") parser.add_argument('--frict_coeff', de...
def _init_wrapped_env(self, env_name, env_kwargs, seed): if env_kwargs is None: env_kwargs = {} wrapped_env = gym.make(env_name, **env_kwargs) wrapped_env.seed(seed) return wrapped_env def _set_wrapped_time_limit(self, time_limit): assert isinstance(self._wrapped_env,...
This code initializes an environment wrapper by setting up a wrapped environment, configuring observation and action spaces (using provided or generated ones), applying a time limit, and initializing a random number generator. It also marks the environment as terminal initially, preparing it for interaction with custom...
def __init__(self, env_name, time_limit, env_kwargs=None, custom_obs_space=None, custom_action_space=None, seed=0): self._wrapped_env = self._init_wrapped_env(env_name, env_kwargs, seed) self._set_wrapp...
def print_auc_accuracy(self): accuracies = [self.train_accuracy, self.validate_accuracy, self.test_accuracy] max_accuracies = [max(accuracy) for accuracy in accuracies] max_index = [accuracy.index(max_accuracies[i]) for i, accuracy in enumerate(accuracies)] max_accuracies = [round(max_va...
The code generates visualizations of training metrics by creating a 2x2 subplot grid. It plots training loss from saved data, accuracy curves, ROC curves, and a confusion matrix. Each subplot is adjusted for layout, and results are derived from methods like load_losses, plot_accuracies, plot_roc, and plot_confusion_mat...
def make_plots(self, loss_dir="losses"): self.print_auc_accuracy() plt.figure(figsize=(8, 8)) plt.subplot(2, 2, 1) losses = self.load_losses(loss_dir=loss_dir) if losses.any(): plt.plot(losses) plt.xlabel("Loss") plt.title("Training Loss") ...
def other_player(player): """Return X if player is O else return O""" return "O" if player == "X" else "X" def display(board): """Display the given board""" separator = '+---+---+---+' print(separator) for row in board: print('|', end='') for col in row: print(' {} |'...
The main task of the code is to allow a human and computer player to take turns making moves on a board until the game ends (win or draw). It displays the board after each move, alternates between human and computer turns, and returns the final game result once the game concludes.
def play_game(human_player, board): """Play until a win or a draw""" computer = other_player(human_player) display(board) while game_over(board) is False: make_human_move(human_player, board) if winner(board) is None: display(board) make_computer_move(computer, bo...
def new_board(): """Generate and return a new empty board""" board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] return board def get_O_or_X(): """Ask the human if they want to play O or X and return their choice""" while(True): pick = input("Would you like to play O or X? ") ...
The main task of the code is to run a game of noughts and crosses. It initializes a game board, lets the human player choose their symbol (O or X), plays the game, displays the final board state, and announces the result. If a ValueError occurs during gameplay, it catches the exception and prints an error message, ensu...
def main(): """Play a game of noughts and crosses""" board = new_board() human_player = get_O_or_X() try: play_game(human_player, board) display(board) print(game_result(board)) except ValueError: print("The program has encountered an error and needs to die. Bye.")
def advance(self): try: self.current_char = next(self.text) except StopIteration: self.current_char = None def generate_number(self): decimal_point_count = 0 number_str = self.current_char self.advance() while self.current_char != None and (self.current_char == '.' or self.current_char in DIGITS): ...
This function tokenizes input characters into specific tokens like numbers, operators, identifiers, etc., by iterating through each character. It skips whitespace, handles digits, symbols (e.g., +, -, *, /), parentheses, and special cases like '.' or '='. When encountering '!', it skips until the end of input. It yield...
def generate_tokens(self): while self.current_char != None: if self.current_char == "!": while(self.current_char != None): self.advance() break if self.current_char in WHITESPACE: self.advance() elif self.current_char in DIGITS: yield self.generate_number() elif self.current_char == '...
def current_neighbourhood_string(self): """Produces string ready to print, with field's neighbourhood. :return: string """ n_nw = self._pick_rel_neighbour(-1, -1) n_n = self._pick_rel_neighbour(-1, 0) n_ne = self._pick_rel_neighbour(-1, 1) n_w = self....
The function analyzes two fields (self and n) to determine their shared and unique neighbors, and calculates the possible range of mines in their intersection. It returns the intersection set, differences in neighbors, and the minimum/maximum mines in the intersection, with 'exact' indicating if they are equal.
def _analyze_pair_with(self, n): """ Returns properties of a self and n pair :param n: Field :return: intersection : set a common set of (*) fields self_diff_n : set a set of neighbours of self, which aren't neighbour of n ...
def m_left(self): """Returns number of mines left to mark in self neighbourhood. :return: int """ mines_left = int(self.state) - len(self.get_nbours('m', 'pm')) if mines_left < 0: raise NegativeMinesLeftCountError(self, s...
This method identifies covered neighboring cells ('*') and marks them as potential mines ('pm') labeled "Obvious" when the count of these cells equals the remaining mines to be marked. It uses `self.m_left()` to check this condition and applies the mark via `mark_potentials` if true.
def mark_obvious_mines(self): """Marks mines as 'pm' when number of covered neighbours ('*') equals self mines left to mark. :return: None """ if self.m_left() == len(self.get_nbours('*')): self.mark_potentials(self.get_nbours('*'), 'pm', "Obvious")
def get_nbours(self, *args): """Returns set of neighbours filtered by passed parameter. :param args: all regular states, plus additionally 'n' as number, 'pn' as potential number, 'pm' as potential mine :return: set """ neighbours = set() args ...
The function analyzes intersections of numeric neighbors to determine mine placements ('pm' or 'pn') based on remaining mine counts and intersection sizes. It iterates through neighbors, checks conditions on mine leftovers, and marks fields accordingly when intersections match specific criteria, such as exact mine coun...
def iterate_over_num_neighbours(self): """Marks appropriately fields as 'pm' or 'pn', based on specific conditions. Iterates over numeric neighbours and analyzes the intersections of each pair. :return: None """ fields_to_cooper = set() for cov_neighbour in self....
def _has_new_word(self, text): """ Return True if text contains the beginning of a new word. """ if not self.last_word: return True if " " in text: return True if re.match(f'{self.word_delimiter}+[^{self.word_delimiter[1:]}+{self.word_delimiter}*$', text...
The main task of the code is to position and display input text on a screen, handling line breaks when space is limited. It checks for available space, manages text layout using a diffbox manager, updates word tracking, calculates drawing coordinates, generates an image from the text, and pastes it onto a frame buffer ...
def place_written_text(self, text): """ Place written text """ text_width, _ = self.font.getsize(text) text_height = self.font_size if self.diffbox_manager.no_more_space(text_width) and not self._has_new_word(text): self.move_word_on_new_row(text) return ...
def generate_application_graph( n_components: int, seed: int ) -> Tuple[dict, nx.DiGraph]: # generate DAG object (edges have random weights) p = 0.8 if n_components > 4 else 1.0 done = False while not done: G = nx.gnp_random_graph(n_components-2, p, seed=seed, directed=True) ...
The function generates a system instance by creating a Directed Acyclic Graph (DAG), components with data sizes, resource allocations, compatibility/performance matrices, local/global constraints, and network domains based on a configuration. It validates the DAG, logs progress, and saves the structured system data as ...
def generate_instance( config: dict, instance_dir: str, seed: int, logger: space4ai_logger.Logger ) -> dict: # initialize system system = {} # generate DAG logger.log("Generate DAG", 1) n_components = config["n_components"] system["DirectedAcyclicGraph"], DAG = gene...
def get_workload_profile(dir: str) -> pd.DataFrame: lambdas = [] workload_file = os.path.join(dir, "LambdaValues.json") with open(workload_file, "r") as istream: lambdas = json.load(istream)["LambdaVec"] workload_profile = pd.DataFrame({ "time": [i * TIME_STEP for i in range(len(lambdas))]...
The function evaluates heuristic-based resource allocation solutions against a design-time benchmark for a given workload instance. It generates workload profiles, computes costs for specified heuristics (including "figaro"), and calculates cost reduction percentages relative to a target. Visualizations of costs and re...
def evaluate_instance( instance_dir: str, heuristics: list, target: str, min_utilization: float, max_utilization: float, skip: dict ) -> Tuple[dict, dict, dict]: # create directory to store figures plot_dir = os.path.join(instance_dir, "figures") os.make...
def read_configuration_file(config_file: str) -> dict: config = {} with open(config_file, "r") as istream: config = json.load(istream) return config def check_configuration(config: dict) -> Tuple[int, str]: err_code = 0 err = "" # get parameters n = config["n_components"] noe = c...
The main task of the code is to generate multiple instances based on a configuration file. It reads and validates a JSON config, then iterates over specified instances, creating directories for each and generating instance data using the `generate_instance` function, while logging progress and errors. The process exits...
def main( application_dir: str, seed: int, logger: space4ai_logger.Logger ): # read configuration file config_file = os.path.join(application_dir, "config.json") config = read_configuration_file(config_file) # check if configuration is valid err_code, err_msg = check_configur...
def evaluate_instance( instance_dir: str, heuristics: list, target: str, min_utilization: float, max_utilization: float, skip: dict ) -> Tuple[dict, dict, dict]: # create directory to store figures plot_dir = os.path.join(instance_dir, "figures") os.make...
The code evaluates multiple instances within a scenario by processing each instance's results, aggregating metrics like costs and percentage cost reduction, generating visualizations, and returning aggregated data including average costs, violations, and per-instance results.
def evaluate_scenario( scenario_dir: str, heuristics: list, target: str, min_utilization: float, max_utilization: float, skip: dict ) -> Tuple[dict, dict, dict, pd.DataFrame]: # create directory to store figures plot_dir = os.path.join(scenario_dir, "figures...
def pprint(self, msg): self.stdout.write(self.style.SUCCESS(msg)) def parse_orbit_code_entry_from_line(self, line): symbols = line.strip("\n").split(' = ') return { "code": symbols[0], "name": symbols[1] } def debug_pprint(self, msg): self.debug_print(ppri...
The code's main task is to parse orbital code entries from a specified file by reading each line, converting it into structured data using `parse_orbit_code_entry_from_line`, updating a database with the parsed entries, and logging progress. It counts the total entries processed and reports the result.
def parse(self): self.pprint(f"Parsing Orbital Codes from File: {self.filepath}") with open(self.filepath, 'r') as orbit_codes_file: orbit_code_lines = orbit_codes_file.readlines() count = 0 for orbit_code_line in orbit_code_lines: orbit_code_entry = self.parse_o...
def pprint(self, msg): self.stdout.write(self.style.SUCCESS(msg)) def parse_site_code_entry_from_line(self, line): symbols = line.strip("\n").split(' = ') return { "code": symbols[0], "name": symbols[1] } def debug_pprint(self, msg): self.debug_print(pprin...
The main task of the code is to parse site code entries from a specified file by reading each line, converting it into structured data using `parse_site_code_entry_from_line`, logging debug information, updating a database with each entry via `update_site_code_db_with_entry`, and finally reporting the total number of p...
def parse(self): self.pprint(f"Parsing Site Codes from File: {self.filepath}") with open(self.filepath, 'r') as site_codes_file: site_code_lines = site_codes_file.readlines() count = 0 for site_code_line in site_code_lines: site_code_entry = self.parse_site_code_...
def parse_launch_log_line_into_entry(self, line, index): replace_regex = r'[\s]{2,}' # regex for finding spots using more than one 'space' replace_symbol = '||' # replace them with this character (makes `split()` easier) subbed_line = re.sub(replace_regex, replace_symbol, line) # do the actual r...
This function processes launch log lines by parsing each entry into structured data, extracting details like date, vehicle, payload, site codes, and orbit information. It constructs a dictionary representing a launch and inserts it into a database, with conditional printing for manually corrected entries.
def populate_db_from_launch_log(self, lines): # self.debug_print(pprint.pformat(lines)) for index, line in lines.items(): if line.strip() == '': continue entry, had_manual_correction = self.parse_launch_log_line_into_entry(line, index) self.debug_pprin...
def set_verbosity(self, options): if options['verbosity'] > 1: self.pprint(f"Verbosity set to {options['verbosity']}. Enabling DEBUG output.") self.IS_DEBUG_MODE = True def debug_print(self, msg): if self.IS_DEBUG_MODE: self.pprint(msg) def parse_file(self, filepath, ...
This code processes data files by either parsing a specified statsfile or iterating through files in the 'initial_data' directory, invoking `parse_file` on each to handle their contents, with debug options and verbosity settings controlled via command-line arguments.
def handle(self, *args, **options): self.set_verbosity(options) self.debug_print(options) if options['statsfile']: path = Path(options['statsfile']) self.parse_file(str(path), path.name) else: with scandir('spacetrends/initial_data') as entries: ...
def debug_print(self, msg): if self.is_debug_mode: self.pprint(msg) def get_launch_log_lines(self, lines): match_string = 'LAUNCH LOG' if self.is_old_stats_style else 'SPACE LAUNCH LOG' self.debug_print(f"Using match string: {match_string}") last_match_index = -1 for...
The main task of the code is to parse a file containing launch logs and notes, extract the year from the filename, populate a database with launch log entries, and process launch notes using a dedicated parser if present.
def parse(self): with open(self.filepath) as statsfile: self.debug_print(f"reading file: {statsfile}") statsfile_lines = statsfile.readlines() # Set the 'year' this file was made in year_regex = r'\d{4}' match = re.search(year_regex, self.filename) if mat...
def get_links(url): page = requests.get(url) soup = BeautifulSoup(page.content, 'lxml') for link in soup.findAll('a', attrs={'href': re.compile("^http://")}): link = link.get('href') links_list.append(link) def get_company_profile(driver, url): try: driver.get(url) WebDri...
The main task of the code is to scrape company profiles from links extracted from a given URL using Selenium, handle potential connection timeouts, and periodically export the collected data to an Excel file. The function initializes a Chrome driver, iterates through a subset of links, retrieves company details, and en...
def master_func(url): get_links(url) driver = webdriver.Chrome(executable_path=chrome_driver_path) driver.get(url) for l in links_list[3255:]: try: get_company_profile(driver, l) except WebDriverException: print(f"Connection Timed Out for {url}") conti...
def get_name(url1): soup = setup(url1) try: name = soup.find(class_="owner-photo col-sm-5").h2 return str(name) except Exception: return "No Name" def get_phone(url1): soup = setup(url1) try: phone_number = soup.find('a', {'id': 'number_link'}).text return pho...
The main task of the code is to extract specific data fields (name, phone, email, website, address, state) from a given URL using helper functions, compile them into a structured dictionary with list-based values, and pass the dictionary to a `clean_dict` function for further processing. The dictionary organizes extrac...
def create_dict(url): name = get_name(url) phone = get_phone(url) email = get_email(url) website = get_website(url) address = get_address(url) state = get_state(url) my_dict = {"Name":[],"Phone":[],"Email":[],"Website":[],"Address":[],"State":[]} my_dict["Name"].append(name) my_dict[...
def insert_data(mydb): name = input("\nMasukan nama: ") address = input("Masukan absen: ") val = (name, address) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" mycursor.execute(sql, val) mydb.commit() print("{} data berhasil disimpan".format(mycurs...
The main task of the code is to display a menu-driven interface for database operations, allowing users to insert, view, update, delete, search data, manage loans, and remove visitor names via function calls based on their menu selection, with an exit option to terminate the program.
def show_menu(mydb): print("\n=== APLIKASI DATABASE PYTHON ===") print("1. Insert Data") print("2. Tampilkan Data") print("3. Update Data") print("4. Hapus Data") print("5. Cari Data") print("6. Cari Pinjaman") print("7. Hapus Pinjaman") print("8. Hapus Nama Pengunjung") print("0...
def create_clusters(self, centroids): clusters = [[] for _ in range(self.K)] for idx, sample in enumerate(self.X): centroid_idx = self.closest_centroid(sample, centroids) clusters[centroid_idx].append(idx) return clusters def plot(self): fig, ax = plt.subplots(fig...
The code performs K-means clustering on input data `X` by initializing centroids randomly, iteratively updating cluster assignments and centroids until convergence, then returning the final cluster labels. It includes steps for centroid initialization, cluster creation, centroid updates, convergence checks, and optiona...
def predict(self, X): self.X = X self.n_samples, self.n_features = X.shape # initialize centroids random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False) self.centroids = [self.X[idx] for idx in random_sample_idxs] # optimization ...