dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_stat(html): soup = BeautifulSoup(html, 'lxml') main_url = 'http://data.nowgoal.group' champ_title = strip_parentheses( soup.find('span', class_='LName').find('a').text) weather = get_weather_info(soup) teams_titles = [ [a.text for a in soup.select('span.sclassName a')][0], ...
This code processes a list of URLs to extract match statistics. For each URL, it retrieves HTML data, extracts statistical information, and writes the results to CSV files. If the data contains fewer than 92 keys, it saves to 'match_stat_40000_74622_short.csv'; otherwise, to 'match_stat_40000_74622.csv'. Exceptions dur...
def main(urls): for url in tqdm(urls): try: data = get_stat(get_html(url)) order = list(data.keys()) if len(order) < 92: write_csv(data, 'match_stat_40000_74622_short.csv', order) else: write_csv(data, 'match_stat_40000_74622.cs...
def num_tx_elev_antenna(cfg, mask=(False, True, False)): return num_tx_antenna(cfg, mask) def fft_doppler_scale_compensation(fft_min_size, fft_size): slin = 1.0 * fft_min_size / fft_size return slin def num_range_bin(cfg): return int(pow2_ceil(cfg['profileCfg']['adcSamples']))
The main task of the code is to parse and configure input settings, filling in default values for parameters like channel masks, range bias, and ADC settings, while computing compensation factors (log-linear scale, FFT scaling) for signal processing. It modifies the input dictionary by removing metadata keys and return...
def get_conf(cfg): c = dict(cfg) p = {'loglin': float('nan'), 'fftcomp': float('nan'), 'rangebias': float('nan')} if '_comment_' in c: c.pop('_comment_', None) # remove entry if '_apps_' in c: _meta_['app'] = c['_apps_'] c.pop('_apps_', None) # remove entry ...
def model_inputs(real_dim, z_dim): inputs_real = tf.placeholder(tf.float32, (None, *real_dim), name='inputs_real') inputs_z = tf.placeholder(tf.float32, (None, z_dim), name="input_z") learning_rate_G = tf.placeholder(tf.float32, name="learning_rate_G") learning_rate_D = tf.placeholder(tf.float32, name="...
This function trains a Generative Adversarial Network (GAN) by initializing model components (generator/discriminator), defining loss functions, and setting up optimizers. It restores a pre-trained model from a saved checkpoint, then generates and returns a sample image using the generator network with specified parame...
def train(show,example_z,epoch_count, batch_size, z_dim, learning_rate_D, learning_rate_G, beta1, get_batches, data_shape, data_image_mode, alpha): input_images, input_z, lr_G, lr_D = model_inputs(data_shape[1:], z_dim) d_loss, g_loss = model_loss(input_images, input_z, data_shape[3], alpha) d_opt, g_opt = ...
def player_won(self): if self.equipped_enemy_nitzamon.hp <= 0: if type(self.enemy_nitzamons) == list: for nitzamon in self.enemy_nitzamons: if nitzamon.hp > 0: return False self.equipped_enemy_nitzamon.hp = 0 ...
This function handles a fight encounter in a game, managing win/lose states, evolution, attacks, and UI updates. It checks if the player or enemy has won, triggers level-ups or evolution, displays "YOU WIN" or "YOU LOSE" messages, updates animations, and renders appropriate screens based on game states like inventory c...
def handle_fight_encounter(self): font = pygame.font.SysFont("Comic Sans MS", 128) if self.player_won() and not self.win_screen or self.evolve_screen: self.level_up_nitzamons() self.win_screen = True elif self.enemy_won() and not self.lose_screen or self.evolve_screen: #...
def _check_keydown_events(self, event): """ continuous movement to the right """ if event.key == pygame.K_RIGHT: self.ship.moving_right = True """ continuous movement to the left """ if event.key == pygame.K_LEFT: self.ship.moving_left = True """ quit func...
The main task of the code is to handle real-time user inputs in a Pygame application. It processes events like window closure (QUIT), keyboard key presses (KEYDOWN/KEYUP), and mouse clicks (MOUSEBUTTONDOWN). For each event, it triggers corresponding methods: exiting the game on quit, managing key states via _check_keyd...
def _check_events(self): """ respond to keypress and mouse events """ for event in pygame.event.get(): if event.type == pygame.QUIT: # reads inputs in real time sys.exit() # quits when detect quit call elif event.type == pygame.KEYDOWN: self._che...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): if self.stats.ships_left > 0: self.stats.ships_left -= 1 self.sb.prep_ships() ...
The function updates alien movement, checks for collisions between the ship and aliens, and detects if aliens reach the screen's bottom, triggering responses like ship damage or game-over conditions.
def _update_aliens(self): self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): # print(f'\nShip has been destroyed.' # f'\nLives left:{self.stats.ships_left}') """ check if ship has been hit """ ...
def _check_events(self): """ respond to keypress and mouse events """ for event in pygame.event.get(): if event.type == pygame.QUIT: # reads inputs in real time sys.exit() # quits when detect quit call elif event.type == pygame.KEYDOWN: self._che...
The code runs the game loop by continuously checking events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen. It starts game music and maintains the loop until exited, ensuring real-time interaction and visual updates.
def run_game(self): """ start main loop of the game """ self.settings.game_music_play(True) while True: self._check_events() """ check if False or True and start """ if self.stats.game_active: # self.settings.game_music_play(False) ...
def create_coalitions(self) -> list: """ Initialise the coalitions returns: The coalitions """ self.coalitions = self.find_coalitions() self.coalitions.sort( key=lambda coalition: coalition.feasibility, reverse=True) return self.c...
The main task of the code is to simulate an election process by aggregating voter preferences, calculating seat distribution based on votes, and tracking strategic voting behavior. It returns the final seat allocation, vote-switching patterns between parties, and the percentage of strategic votes cast.
def start(self): """ Start the election returns: The distribution of seats after the election """ self.coalitions = self.create_coalitions() strategic_vote_count = 0 n_parties = len(self.parties) votes = {i: 0 for i in range(n_parties)} ...
def get_phrase_letter_map(self, phrase: str) -> dict: map = dict() for index, letter in enumerate(phrase): if letter == ' ' or letter == '\n': continue if letter not in map.keys(): map[letter] = [] map[letter].append(index) ...
The code deciphers input data using a given phrase by mapping letters, processing each case to find matching letters, and generating plaintext results. If letters are found, it deciphers them; otherwise, it adds "No solution." to the output. The result is an Output object containing decrypted text or error messages.
def decypher(self, data: Input, phrase: str) -> Output: result = Output() letter_map = self.get_phrase_letter_map(phrase) for case in data.cases: letters = self.find_letters(case, phrase, letter_map) if letters: result.add_plaintext(self.decypher_case(l...
def prior_z(self) -> tfd.MultivariateNormalDiag: """ Prior of latent variable (p(z)) Usually just standard normal. Returned distribution is used for KL divergence :return: tfd.MultivariateNormalDiag """ mu = tf.zeros(self.latent_dim) rho = tf.ones(self.latent_dim)...
The code calculates the VAE/DVIB loss by combining reconstruction errors (log probabilities of inputs x and y), KL divergence between posterior and prior distributions, and cycle consistency loss. It computes the negative ELBO (Evidence Lower Bound) as the primary loss, adds a scaled cycle consistency term, and returns...
def calc_losses(self, x, y, num_samples=1) -> Tuple[Loss, tfd.Distribution]: """ Calculate VAE / DVIB Loss. I.e.: z_posterior = encoder(x) pdf_y_hat = decode(z_posterior.sample()) loss_vae = -pdf_y_hat.log_prob(y) + lambda * KL(z_posterior, z_prior) = -ELBO z_sam...
def target_transform(self, y: tf.Tensor): """ Could include e.g. onehot transformation for classification. Usually just the identity for regression. Args: y: Returns: """ return y def calc_losses(self, x, y, num_samples=1) -> Tuple[Loss, tfd.Distribu...
This function performs one optimization step during training by computing losses, applying gradient descent to update model weights, and logging metrics. It transforms target labels, calculates losses and predictions, computes gradients, updates weights via the optimizer, and updates both built-in and custom metrics. T...
def train_step(self, data: Tuple[tf.Tensor, tf.Tensor, tf.Tensor]): """ One optimization step. Calculates losses, performs gradient descent step & logs metrics. :param data: :return: """ x, y, _ = data y_transformed = self.target_transform(y) with...
def target_transform(self, y: tf.Tensor): """ Could include e.g. onehot transformation for classification. Usually just the identity for regression. Args: y: Returns: """ return y def calc_losses(self, x, y, num_samples=1) -> Tuple[Loss, tfd.Distribu...
The code computes validation metrics during testing by processing input data, calculating losses, generating predictions, updating metrics, and returning a loss dictionary.
def test_step(self, data): """ Step used by Keras for validation metrics :param data: :return: """ x, y, _ = data y_transformed = self.target_transform(y) # calculate losses losses, pdf_y_hat = self.calc_losses(x, y_transformed, 30) # the ...
def encoder(x, params): # Assuming param shape of (784x500, 500x4) w1, b1, w2, b2 = params z1 = torch.tanh(torch.mm(x, w1)+b1) z2 = torch.mm(z1, w2)+b2 mean = z2[:, :2] log_std = z2[:, 2:] return mean, log_std def joint_log_density(z, x, params): #print("Log Prior: {}, LL: {}".format(log_prior(z).data, log_l...
This function computes the Evidence Lower Bound (ELBO) for a variational autoencoder. It samples latent variables using the reparameterization trick, calculates the joint log density of data and latents via the decoder, subtracts the log probability of latents under the encoder's distribution, and returns the normalize...
def elbo(x, encoder_params, decoder_params, display=False): eps = np.random.normal(size=(x.shape[0], 2)) eps = torch.from_numpy(eps).double() mu, log_std = encoder(x, encoder_params) reparam_z = eps*torch.exp(log_std)+mu # Of (Bx2) shape # Assuming pre-mean elbo to be of Bx1 shape elbo = torch.mean(joint_log_d...
def save_recording(recording, path_recordings, fnt_og_recording, fnt_recording, VD, fs=16000): """ Save the given recording and a version of it with a sample rate of 16000hz. """ fn_og_recording = fnt_og_recording.format(VD['ith_rec']) fn_recording = fnt_recording.format(VD['ith_rec']) if fs =...
The function processes an audio recording by saving it, merging it with previous recordings, running inference to extract text, and managing merge resets. It checks conditions to determine if silence detection or merging is needed, updates counters, and handles file renaming/trimming during resets to ensure proper audi...
def process_recording(rec, VD, CD): """ Save the given recording, check whether to look for silence or whether to merge, and do so if necessary. """ save_recording(rec, CD['path_temp_recordings'], CD['fnt_og_recording'], CD['fnt_recording'], VD, CD['fs']) VD['ith_rec'] += 1 ...
def getData(self, client_socket) -> str: try: # Read header packet which gives length of payload msg_header = client_socket.recv(self.HEADER_BYTES) msg_len = int.from_bytes(msg_header, byteorder="big") # Read message payload from client pa...
The code implements a chat server that listens for client connections and messages. It handles new clients by retrieving usernames, sending welcome notifications, and broadcasting previous messages. It processes client messages, updates chat history, and notifies all users of new entries or disconnections, maintaining ...
def chatMain(self): while True: # OS level polling for activity on the listed sockets (listens for data packet on sockets) active_sockets, _, _ = select.select(self.socketList, [], self.socketList) # Iterate over sockets where activity has been found for active_s...
def write(text, color=None): global COLOR if COLOR: text = text.replace('==>', '\033[90m==>\033[0m') text = text.replace(' +', ' \033[32m+\033[0m') text = text.replace('XX>', '\033[31mXX>\033[0m') if text[:6] == 'Error:': text = '\033[41mError:\033[0m\033[91m%s\...
The main task of the code is to parse command-line arguments, detect the CI environment, gather code coverage reports, and upload them to Codecov. It handles various CI providers (Jenkins, Travis CI, etc.), processes gcov files, collects reports, and sends data via S3 or direct upload, with options for debugging and en...
def main(*argv, **kwargs): root = os.getcwd() # Build Parser # ------------ parser = argparse.ArgumentParser(prog='codecov', add_help=True, formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Upload reports to Codecov...
def update_gui_cell(screen, screen_width: int, screen_height: int, crossword: crossword.Crossword, gui_cell: GUI_Cell, selected_gui_cell: int, clues: list[clue.Clue]): if gui_cell.cell.conte...
This function handles keyboard events for a crossword puzzle interface, updating GUI cells, navigating selections, modifying content, and redrawing the board based on key presses like ESC, ENTER, TAB, BACKSPACE, and arrow keys. It returns the updated selected cell index after processing the input.
def handle_keydown(screen, screen_width: int, screen_height: int, event, crossword: crossword.Crossword, gui_cells: list[GUI_Cell], selected_gui_cell: int, clues: list[clue.Clue]) -...
def initialize_gui_cells(screen, screen_width: int, screen_height: int, crossword: crossword.Crossword) -> list[GUI_Cell]: padding_bottom = 200 padding_top = 25 gui_cell_size = (screen_height - padding_top - padding_bottom) // crossword.width padding_x = (screen_width - (gui_cell_size * crossword...
The main task of the code is to create a graphical crossword puzzle solver interface using Pygame. It initializes a fullscreen window, loads crossword data, and handles user interactions (mouse clicks, keyboard input, and text entry) to allow solving the puzzle. The code updates the selected cell, processes input, and ...
def main(crossword: crossword.Crossword): pygame.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) screen_width, screen_height = screen.get_rect().width, screen.get_rect().height clock = pygame.time.Clock() cells = crossword.cells gui_cells = initialize_gui_cells(screen, sc...
def checkKey(dict, key): if key in dict.keys(): return True else: return False def is_command(text_message): text_message = text_message.strip() if text_message[:1] == "!": return True else: return False def run_command(command_text, url, api_key, channel, user, bot_h...
The code processes an event by extracting user, channel, and message data, removes the bot's handle from the text, identifies if the message is a command, and responds accordingly. If a command is detected, it executes the command and sends the result; otherwise, it sends a greeting message.
def event_test(body,say): if checkKey(body['event'], 'user'): user = body['event']['user'] else: user = body['event']['bot_id'] text = body['event']['text'] channel = body['event']['channel'] bot_handle = body['authorizations'][0]['user_id'] text = text.replace(f"<@{bot_handle}>"...
def parse_oh_data(self): n_players = len(self.name_map) out = [] better_data = self.raw_data['g']['n'] is_new_round = False the_round = 0 hand_number = None for row_num, row in enumerate(better_data): if 'c' in row: the_round += 1 ...
The main task of the code is to process and upload OH Hell game data to a SQL database. It parses game data, filters and prepares bid and non-bid rounds, enhances score data with bid information, and uploads three datasets—bids, rounds, and scores—using a helper method. The function returns the upload responses.
def upload_to_sql(self): oh_hell_data = self.parse_oh_data() score_df = self.make_score_dataframe().query("round > 0") bid_only = oh_hell_data.query("bid.notna()").dropna(axis=1).drop( columns=['tram', 'bad_card', 'is_trump']) no_bids = oh_hell_data.query("bid.isna()").drop(c...
def load_conf(self): conf_file = self.get_config_file_path() if not os.path.exists(conf_file): return config = configparser.RawConfigParser() with open(conf_file) as stream: config.readfp(stream) self._config = config self._parse_config(self._...
The code initializes a working directory by creating it if it doesn't exist, loads configuration from it, and sets up a database. It checks if the database exists; if not, it creates the database, disables echo mode, and applies schema migrations using a repository. The primary tasks are directory creation, configurati...
def init_dir(self): """ 1. creates the WD if it doesn't exist 2. Reads data from the working dir 3. creates the db if it doesn't exist """ # 1. exists = os.path.exists(self._working_dir) if not exists: os.makedirs(self._working_dir) el...
def _db_migrate_repo(self): return os.path.join(self._working_dir, "db_repository") def _db_uri(self): return "sqlite:///" + self._db_path() def get_db(self): thread_id = _thread.get_ident() if not (thread_id in list(self._db_map.keys())): db = self.make_db_session() ...
The code generates a new database migration script by comparing the current database schema with the old model, writes the script to a migration file, and applies the migration to update the database schema. It retrieves the migration repository, database URI, and version, creates a new migration file, executes the old...
def migrate(self): repo = self._db_migrate_repo() uri = self._db_uri() db = self.get_db() migration_name = "%04d_migration.py" % (api.db_version(uri, repo) + 1) migration = repo + "/versions/" + migration_name tmp_module = imp.new_module("old_model") old_model = a...
def select_post(self): '''finds the first post in the most recent section, if there is no recent section it will chage tag''' sleep(1) try: self.handle_nonclickable_error() except: self.go_to_tag() sleep(0.5) self.select_post() def like_and_comment(self): #check if post is liked or not post_liked...
This code automates social media interactions by selecting a post, liking/commenting, navigating to the next post, and randomly changing tags with variable delays to mimic human behavior and avoid detection.
def botting(self): self.select_post() sleep(1) self.like_and_comment() self.driver.find_element_by_link_text("Next").click() sleep(0.3) self.like_and_comment() randSleep = random.randrange(0,18) if (randSleep >= 9): #some random condtion to change the tag self.go_to_tag() sleep(randSleep)
def login(self): '''assumes you're at the login url''' try: usern = self.driver.find_element_by_name('''username''') passw = self.driver.find_element_by_name('''password''') usern.send_keys(self.username) passw.send_keys(self.password) self.driver.find_element_by_xpath('''//*[@id="react-root"]/secti...
The code automates Instagram login, navigates to a tag page, and continuously checks for login interruptions (e.g., CAPTCHA/session expiry), triggering botting actions when detected. It uses Selenium for browser automation, with a placeholder for improved page-load waiting instead of fixed sleep delays.
def caller(self): url = "https://www.instagram.com/accounts/login/" self.driver.get(url) self.login() self.go_to_tag() sleep(1.5) #replace sleep with something that tells u when the page loads rather than waiting for it to hopefull load while True: if self.sudden_login(): self.botting()
def flatten(config, except_keys={'dont_flatten'}): def recurse(inp): if isinstance(inp, dict): for key, value in inp.items(): if key in except_keys: yield (key, value) if isinstance(value, dict): yield from recurse(value) ...
The function `get_config` generates a model configuration by merging default settings, model-specific versions, dataset adjustments, and user-provided overrides. It prioritizes `overwrite_kwargs`, followed by `config_version`, `model_version`, and common defaults. Dataset-specific parameters are merged if provided, and...
def get_config(model_name, mode='train', dataset=None, **overwrite_kwargs): """Main entry point to get the config for the model. Args: model_name (str): name of the desired model. mode (str, optional): "train" or "infer". Defaults to 'train'. dataset (str, optional): If specified, the c...
def load_state_dict_from_url(model, url, **kwargs): state_dict = torch.hub.load_state_dict_from_url(url, **kwargs) return load_state_dict(model, state_dict) def load_wts(model, checkpoint_path): ckpt = torch.load(checkpoint_path) return load_state_dict(model, ckpt) def pattern_to_local_resource(pattern,...
This function loads pretrained model weights into a given PyTorch model from various resource types (URL, local path, or remote path) specified by prefixes in the resource string. It identifies the resource type, processes the path, and uses appropriate helper functions to load weights, returning the updated model with...
def load_state_from_resource(model, resource): """Loads weights to the model from a given resource. A resource can be of following types: 1. URL. Prefixed with "url::" e.g. url::http(s)://url.resource.com/ckpt.pt 2. Local path. Prefixed with "local::" e.g. local::/p...
def access_token_from_file(): with open("access_token.txt", "r") as f: access_token = f.read() return access_token def request_spotify_authorization(code=None): if code != None: # Ask for a refresh token and access token using code received from Spotify in /login # (Step 2 of 'Author...
This function sends authenticated HTTP requests to Spotify's API endpoints, handling token refresh on 401 errors. It constructs URLs with parameters, uses Bearer tokens for authorization, and retries requests with a new token if unauthorized. It logs requests/responses and supports both GET/PUT methods for interacting ...
def spotify_request( endpoint, http_method="PUT", data=None, force_device=False, token=None, url_params={}, retries_attempted=0, ): app.logger.info("Request to endpoint '/" + endpoint + "' attempted") if token is None: token = access_token_from_file() if force_device: ...
def get_volume(): output = check_output(["amixer", "get", "Master"]) match = re.search(r"\[(\d+)%\]", output.decode()) if match: return int(match.group(1)) else: return None def set_volume(volume, balance=-1): global g_balance # volume is a float from 0 -1 volume = max(min(f...
The main task of the code is to gradually reduce system volume to zero over a specified duration (default: 1 minute), then stop radio playback and pause Spotify. It calculates sleep intervals based on current volume level, decrements volume step-by-step with timed intervals, and handles errors by logging exceptions.
def fade_volume_out(fade_duration_mins=1): try: fade_duration_secs = fade_duration_mins * 60 current_volume = get_volume() sleep_time = fade_duration_secs / current_volume for i in range(current_volume, 0): set_volume(i) time.sleep(sleep_time) except: ...
def start_fade_volume_out(fade_duration_mins=1.0): # start fade_volume_in in a new thread try: fade_thread = threading.Thread( target=fade_volume_out, args=(fade_duration_mins,) ) fade_thread.start() except: app.logger.info("Failed to start fade_volume_out thread"...
The function stops playback, either by fading out over a specified duration if provided, or immediately stopping and pausing playback if no fade duration is given.
def stop(fade_duration_mins=0): if fade_duration_mins > 0: start_fade_volume_out(fade_duration_mins) return "Fading out playback over " + str(fade_duration_mins) + " minutes" else: radiostop() spotipause() return "Playback stopped"
def get_subcube(cube: SpectralCube, freq_range: Optional[u.Quantity] = None, vel_range: Optional[u.Quantity] = None, chan_range: Optional[List[int]] = None, win_halfwidth: Optional[int] = None, vlsr: Optional[u.Quantity] = None, ...
The function computes a spectral moment map (e.g., intensity, velocity, linewidth) from a cube, applying flux masks using user-defined limits or RMS, converting to velocity space, and saving the result as a FITS file. It handles subcube creation, beam consistency checks, and outputs the moment map with metadata, suppor...
def get_moment(cube: SpectralCube, mom: int, linefreq: Optional[u.Quantity] = None, filenamebase: Optional[Path] = None, filename: Optional[Path] = None, lower_limit: Optional[u.Quantity] = None, upper_limit: Optional[u.Quantity] ...
def diffuse(self, x, x0, diff): if diff != 0: a = self.dt * diff * (self.size - 2) * (self.size - 2) self.lin_solve(x, x0, a, 1 + 6 * a) else: # equivalent to lin_solve with a = 0 x[:, :] = x0[:, :] def project(self, velo_x, velo_y, p, div): # numpy equivalen...
The main task of the code is to simulate a fluid dynamics step by performing diffusion, advection, and projection operations on velocity and density fields. It first diffuses velocity, projects velocity fields to enforce incompressibility, advects velocity components, re-projects updated velocities, and then diffuses a...
def step(self): self.diffuse(self.velo0, self.velo, self.visc) # for velocity # x0, y0, x, y self.project(self.velo0[:, :, 0], self.velo0[:, :, 1], self.velo[:, :, 0], self.velo[:, :, 1]) # advect for each component (x, y) of velocity self.advect(self.velo[:, :, 0], sel...
def training_step(model, batch): images, labels = batch out = model(images) # Generate predictions loss = F.cross_entropy(out, labels) # Calculate loss return loss def evaluate(model, val_loader): outputs = [validation_step(model,batch) for batch in val_loader] return validatio...
This function trains a neural network model over multiple epochs using a specified optimizer and learning rate, logs training and validation metrics (loss, accuracy) with TensorBoard, saves model checkpoints at each epoch, and returns a history of validation results. It performs forward/backward passes on training data...
def fit(epochs, lr, model, train_loader, val_loader,writer,opt_func): model_dir=config.MODELCHECKPOINT_PATH history = [] optimizer = opt_func(model.parameters(), lr, weight_decay=lr/10.0) for epoch in range(epochs): # Training Phase running_loss=[] cnt=0 for batch in tra...
def load_query(args): with open(args.query, "r") as fin: queries = [] for line in fin: queryInfo = json.loads(line.strip()) queries.append([queryInfo['qid'], queryInfo['query'], queryInfo["ana"]]) return queries def load_kb(args): if not args.kb: return {} else: eid2types = {} # ei...
The code processes queries by loading them and a knowledge base, extracts entities from each query, ranks documents using a `setRank` function with specified parameters, and saves the ranked results. It iterates through queries, constructs entity strings, applies ranking, and appends results with query IDs, scores, and...
def main(args): queries = load_query(args) kb = load_kb(args) result_all = [] params = {ele.split(":")[0] : float(ele.split(":")[1]) for ele in args.params.split(",")} # print("kb=%s" % kb) for query in queries: query_id = query[0] query_string = query[1] query_entities_list = [] for k, v i...
def cnfSentence(self, sentences): listSentence=[] for s in sentences: newS = sorted(list(set(deepcopy(s))), key=lambda x: x[-1]) if self.checkSentence(newS) and newS not in listSentence: listSentence.append(newS) return listSentence def negationSentence(se...
The code implements a resolution algorithm to determine if a logical statement (alpha) is entailed by a knowledge base (KB). It negates alpha, converts it to CNF, and iteratively resolves clauses in the KB with the negated alpha. If a contradiction (empty clause) is derived, it writes "YES" and the resolution steps to ...
def resolution(self, filename): f = open(filename, 'w') listSentence = deepcopy(self.KB) negOfAlpha = self.cnfSentence(self.negationSentence(self.alpha)) for sentence in negOfAlpha: if sentence not in listSentence: listSentence.append(sentence) while T...
def TransmissionEstimate(self, cv_image64): A = self.AtmLight(cv_image64) omega = 0.95 im3 = np.empty(cv_image64.shape,cv_image64.dtype) for ind in range(0,3): im3[:,:,ind] = cv_image64[:,:,ind]/A[0,ind] dark = self.DarkChannel(im3) transmission = 1 - omega *...
The code dehazes an input image by estimating and refining the transmission map, then recovering the haze-free image. It normalizes the input image, applies transmission estimation and refinement, recovers the image using a recovery function, and converts the result to an 8-bit unsigned integer format for output.
def get_image_dehaze(self, cv_image): I = cv_image.astype('float64')/255 te = self.TransmissionEstimate(I) t = self.TransmissionRefine(cv_image, te) J = self.Recover(I,t,0.1) raw64 = J * 255 raw8 = np.maximum(np.minimum(raw64, 255), 0).astype(np.uint8) return raw8
def parse(bytes: bytes): """ >>> parse(b'*2\r\n$4\r\nECHO\r\n$3\r\nhey\r\n') [b"ECHO",b"hey"] """ return parseStream(io.BytesIO(bytes)) def simple_string(string: str): return f"+{string}\r\n".encode() def bulk_string(bytes: bytes): if str == b"": return b"$-1\r\n" n = len(bytes) ...
This code processes Redis-like commands from a byte payload, handling PING, ECHO, SET (with optional expiration), GET (with TTL check), CONFIG (dir/dbfilename), and KEYS. It returns appropriate responses like PONG, echoed strings, OK, stored values, configuration details, or key lists, or errors for unknown commands.
def reply(payload: bytes): l = parse(payload) command = l[0].upper() if command == b'PING': return simple_string("PONG") elif command == b'ECHO': return bulk_string(l[1]) elif command == b'SET': if len(l) > 3 and l[3].upper() == b'PX': command_set(l[1],l[2],dateti...
def reply(payload: bytes): l = parse(payload) command = l[0].upper() if command == b'PING': return simple_string("PONG") elif command == b'ECHO': return bulk_string(l[1]) elif command == b'SET': if len(l) > 3 and l[3].upper() == b'PX': command_set(l[1],l[2],dateti...
The code tests if the `reply` function correctly formats a Redis RESP bulk string. It checks if passing an array containing the command `b"ECHO"` and argument `b"hey"` results in the expected byte string `b"$3\r\nhey\r\n"`, ensuring proper RESP serialization for Redis protocol compliance.
def test_resp_reply(self): self.assertEqual(reply(array([bulk_string(x) for x in [b"ECHO",b"hey"]])), b"$3\r\nhey\r\n")
def reply(payload: bytes): l = parse(payload) command = l[0].upper() if command == b'PING': return simple_string("PONG") elif command == b'ECHO': return bulk_string(l[1]) elif command == b'SET': if len(l) > 3 and l[3].upper() == b'PX': command_set(l[1],l[2],dateti...
The code tests the Redis CONFIG GET command's response handling by verifying that the reply function correctly parses the Redis protocol response for the 'dir' configuration parameter, ensuring it returns the expected key-value pair in both raw byte string and structured array formats.
def test_config(self): self.assertEqual(reply(array([bulk_string(x) for x in [b"CONFIG",b"GET",b"dir"]])), b"*2\r\n$3\r\ndir\r\n$16\r\n/tmp/redis-files\r\n") self.assertEqual(reply(array([bulk_string(x) for x in [b"CONFIG",b"GET",b"dir"]])), array([bulk_...
def ReadFileNA(filename): # reads the file and fills the NA with 0's. df = pd.read_csv(filename, sep='\t', index_col=0) M=df.values NA_position=np.argwhere(M==3) for j in NA_position: M[j[0],j[1]]=0 return M.astype(bool) def ReadFasis(filename): # reads a matrix from file a...
The code reconstructs a matrix from input data, handling false positives and missing elements using specified algorithms (FN/FPNA). It supports automatic parameter tuning via multi-threading, optimizing parameters like overlap and histogram coefficients. Post-processing refines results using maximum likelihood. Tempora...
def Reconstruct(input_file,output_file,Algchoice="FPNA",auto_tune=1,overlapp_coeff=0.3,hist_coeff=20,postprocessing=0,fnfp=100,fnc=1,postprcoef=5,post_fp=0.0001,post_fn=0.1,n_proc=7): # Main Reconstruction function, this is called by __main__. The parameters are explained in the readme file. global prfp prfp=p...
def assert_valid_plugin(plugin: Plugin): assert_valid_name(plugin) assert_valid_description(plugin) assert_valid_connection_type(plugin) assert_valid_tool_scope_type(plugin) assert_valid_scope_config_type(plugin) assert_valid_streams(plugin) def assert_valid_connection(plugin: Plugin, connection...
This function validates the execution environment of a plugin by checking its configuration, connection, remote scopes, and streams. It ensures the plugin, connection, and scope are valid, constructs necessary scope configurations, verifies the pipeline plan, and confirms each stream can run with the provided parameter...
def assert_plugin_run(plugin: Plugin, connection: Connection, scope_config: Optional[ScopeConfig] = None): assert_valid_plugin(plugin) assert_valid_connection(plugin, connection) groups = assert_valid_remote_scope_groups(plugin, connection) scope = assert_valid_remote_scopes(plugin, connection, groups[0...
def under_non_alpha_ratio(text: str, threshold: float = 0.5): """Checks if the proportion of non-alpha characters in the text snippet exceeds a given threshold. This helps prevent text like "-----------BREAK---------" from being tagged as a title or narrative text. The ratio does not count spaces. Para...
This function checks if a given text meets criteria to be considered a valid title, including length constraints, non-alphabetic character thresholds, language-specific rules, and structural rules like avoiding commas or excessive sentences. It returns True if all checks pass, False otherwise.
def is_possible_title( text: str, sentence_min_length: int = 5, title_max_word_length: int = 12, non_alpha_threshold: float = 0.5, languages: List[str] = ["eng"], language_checks: bool = False, ) -> bool: """Checks to see if the text passes all of the checks for a valid title. Parameter...
def getCombinations(self, lst, index, combinations, deleted): # base if index == len(lst): combined = [lst.copy(), deleted.copy()] combinations.append(combined) return combinations # logic # not making the particular node down combinations = se...
The main task of the code is to evaluate all possible node combinations in a graph, check their connectivity states using two methods, detect inconsistencies in system status checks, and collect valid configurations where both connectivity checks pass. It returns a list of valid system states with counts of connected a...
def helper(self, adjList, nodes, range, increment): # getting 2^n combinations combinations = self.getCombinations(nodes, 0, [], set()) upSystems = [] for i in combinations: connected, deleted = i[0], i[1] flag1 = self.isConnected1(adjList, connected, deleted, nod...
def getadjList(self, edges): adjList = defaultdict(list) for i in edges: adjList[i[0]].append(i[1]) adjList[i[1]].append(i[0]) return adjList def helper(self, adjList, nodes, range, increment): # getting 2^n combinations combinations = self.getCombinations...
The code calculates and plots network reliability over a range of probabilities (p). It constructs an adjacency list, identifies system configurations via a helper function, iterates through p values, computes cumulative reliability for each configuration, and visualizes the results with a reliability vs. p graph.
def getReliability(self, edges, range, increment): adjList = self.getadjList(edges) nodes = list(adjList.keys()) upSystems = self.helper(adjList, nodes, range, increment) x = [] y = [] start = range[0] end = range[1] p = start while p <= end: ...
def get_app_id(self): if self.flow_app_id is None: raise ValueError("Flow app id is not set") return self.flow_app_id def get_app_endpoint(self): app = self.get_app_data() return app["app_manifest"]["endpoint"] def get_credential_header(self): if self.flow_api_token i...
This function downloads specific instance data (input/output view) based on data type and language for a given app, using HTTP POST request, then saves the retrieved binary data to a specified file path.
def download_instance_data( self, instance_id, data_type: DataType, language: LangType, out_path: str ): # download the input or output view data (same as the ui view data) app_id = self.get_app_id() app_endpoint = self.get_app_endpoint() _url = self.flow_host_url + "/" + app...
def face_split_download(): face_split_url = "https://github.com/kadirnar/wideryolo/releases/download/widerface/wider_face_split.zip" face_split_url_download = "wider_face_split.zip" download(face_split_url, face_split_url_download) def val_download(): val_url = "https://github.com/kadirnar/wideryolo/rel...
The main task of the code is to download facial dataset components (face splits and validation data), create directories for training/val annotations, and move the "wider_face_split" folder into the specified data directory. It prepares dataset structure for WIDER dataset processing by organizing downloaded files into ...
def download_run(data): face_split_download() val_download() wider_create_dir(data + "./WIDER_train_annotations", data + "./WIDER_val_annotations") shutil.move("wider_face_split", data)
def _init_covariance(self, n_features): if self.covariance_type == 'spherical': return np.random.rand(self.n_clusters) elif self.covariance_type == 'diagonal': return np.random.rand(self.n_clusters, n_features) def _overall_log_likelihood(self, features): denom = [ ...
This code implements the Expectation-Maximization (EM) algorithm for a Gaussian Mixture Model (GMM). It initializes cluster centroids via KMeans, then iteratively refines the model parameters (means, covariances, mixing weights) through E-step (responsibility assignment) and M-step (parameter updates) until convergence...
def fit(self, features): if self.means is None: kmeans = KMeans(self.n_clusters) kmeans.fit(features) print('finished initial clustering') self.means = kmeans.means np.save('means.npy', self.means) self.covariances = self._init_covariance(feat...
def sum_of_squares(self, x): norm = Ciphertext() self.evaluator.square(x, norm) self.evaluator.relinearize_inplace(norm, self.relin_keys) self.evaluator.rescale_to_next_inplace(norm) norm = self.partial_add(norm) norm = self.re_encrypt(norm) return norm def inv_norm_approx(self, norm): guess = se...
The code implements the Goldschmidt algorithm to compute the reciprocal of a norm using homomorphic encryption. It iteratively updates ciphertexts x and h through multiplication, relinearization, and rescaling to approximate the reciprocal, returning the result in x and h after four iterations.
def goldschmidt(self, X): temp = 0 norm = self.sum_of_squares(X) y = Ciphertext(); x = Ciphertext(); r = Ciphertext(); h = Ciphertext() y_result = Plaintext(); half = Plaintext(); neg_one = Plaintext() y = self.inv_norm_approx(norm) y = self.re_encrypt(y) #x = norm*y self.evaluator.mod_switch_to_i...
def init_vector(self): temp = np.random.random(self.vec_len) init_vec = np.array([]) for i in range(self.incr): init_vec = np.append(init_vec, temp) temp_vec = DoubleVector(init_vec) return temp_vec def vect_mat_product(self, X_j, r): x = Ciphertext() self.evaluator.multiply(X_j, r, x) self.evalu...
This code performs homomorphic encryption-based power iteration to compute eigenvalues and eigenvectors of a matrix X. It uses encrypted operations (mod switching, scaling, multiplication) and the Goldschmidt algorithm to iteratively approximate dominant eigenpairs while maintaining data privacy. The result is a list o...
def power_iteration(self, X): eig = []; eig_vec = [] iterations = 4 temp_vec = self.init_vector() for d in range(self.dims): print("Eigen vector :", d+1) r_plain = Plaintext(); r = Ciphertext() self.encoder.encode(temp_vec, self.scale, r_plain) self.encryptor.encrypt(r_plain, r) eig_val = 0 ...
def bot_sleep(time): sleep(time * SLEEP_SPEED + random.uniform(0, SLEEP_NOISE)) def do_search(self, reset_url: str, pages: int) -> list: scraped_links = [] for i in range(1, pages + 1): if i != 1: page = '' if i == 0 else '&page=' + str(i) self.driver.get(...
The code scrapes LinkedIn profiles for individuals from specified firms and roles, collecting data like names, roles, and education. It filters profiles using fuzzy matching to ensure firm alignment, avoids duplicates, and stores results in a pandas DataFrame. The function handles errors, allows interruption, and optio...
def scrape_data(self) -> pd.DataFrame: queries = self.inputs.get_queries() arr = [] visited_links = set() try: for firm_num, firm_name, firm_id, roles in queries: print("Scraping {}, firm {} of {}".format(firm_name, firm_num + 1, len(queries))) ...
def unionfind_root(pointers, u): """ Union find root operation with path-compression Parameters ---------- pointers: list A list of pointers to representative nodes u: int Index of the node to find Returns ------- Index of the representative of the component...
The code constructs an H0 persistence diagram (merge tree) from a 1D time series using union-find. It processes points in ascending order, merging neighboring components and recording birth-death intervals (persistence pairs). The diagram captures topological features of the time series, with optional inclusion of an e...
def init_from_timeseries(self, y, include_essential=False, circular=False): """ Uses union find to make a merge tree object from the time series x (NOTE: This code is pretty general and could work to create merge trees on any domain if the neighbor set was updated) Parameters ...
def octconv_encoder_block(input_tensor, num_filters, alpha, n_repeat, kernel_size=(3, 3), strides=(1, 1), padding="same"): encoder = octconv_residual_block(input_tensor, num_filters, alpha, n_repeat, kernel_size, strides, padding) encoder_pool = average_pooling_octconv(encoder) return encoder_pool, encoder ...
The code constructs a U-Net model using OctConv layers, pre-activation shortcuts, and average-pooling for image segmentation. It processes high and low-resolution features in parallel, progressively encoding spatial information through downsampling blocks, decoding via upsampling with skip connections, and combining ou...
def UNet_octconv(alpha, in_shape): """ Construct U-Net with OctConv layers, pre-activation shortcut, and average-pooling ARGUMENTS: :param alpha: Low to high channels ratio (alpha=0 -> High channels only, alpha=1 -> Low channels only) :param in_shape: input shape OUTPUT: :return: the U-Net...
def crossover_population(pair, solution_space): crossover_pop ={} j = 0 for i in range(len(pair)): print("Pair") print(pair[i]) top_2 = crossover(pair, i, solution_space) crossover_pop[j] = top_2[0] crossover_pop[j+1] = top_2[1] j = j+2 return crossover_po...
The code builds a new population by applying crossover and mutation to generate offspring. It evaluates these offspring, ranks them using a linear ranking scheme, selects the elite individual, and chooses the top-ranked offspring (up to 20) to form the final population for the next generation.
def build_new_pop(pair, current_sol): new_pop = {} elite_pop = {} final_pop = {} cross_pop = crossover_population(pair, current_sol) for j in range(len(cross_pop)): offspring = mutation(cross_pop[j]) new_pop[j] = offspring S_dict = {} for s in range(len(new_pop)): ...
def test( self, dist_metric='euclidean', normalize_feature=False, visrank=False, visrank_topk=10, save_dir='', use_metric_cuhk03=False, ranks=[1, 5, 10, 20], rerank=False ): r"""Tests model on target datasets. .. note:: ...
The main task of the code is to provide a unified training and evaluation pipeline for a model. It handles training over specified epochs, periodic evaluation, model saving, and visualization. If `test_only` is True, it skips training and runs evaluation directly. The function also supports configuration options for di...
def run( self, save_dir='log', max_epoch=0, start_epoch=0, print_freq=10, fixbase_epoch=0, open_layers=None, start_eval=0, eval_freq=-1, test_only=False, dist_metric='euclidean', normalize_feature=False, visrank=Fals...
def shape_to_np(self,shape, dtype="int"): #Initialized coords = np.zeros((68, 2), dtype=dtype) #Loop for 68 to specify the coordinates of the keypoints for i in range(0, 68): #Convert to tuples of (x,y) coords[i] = (shape.part(i).x, shape.part(i).y) retur...
The main task of the code is to detect faces in a frame, extract facial landmarks, and initialize left and right Eye objects for tracking. It converts the frame to grayscale, uses a face detector to locate faces, predicts 68-point facial landmarks, and creates Eye instances for blink detection. If no face is detected, ...
def detector(self): """Detects the face and initialize Eye objects""" frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY) faceRect = self.face_detector(frame) if(len(faceRect)<1): cv2.putText(self.frame,"No face found. Make sure you are facing the camera",(int(self.frame.sha...
def train(train_loader, model, criterion, optimizer, epoch, normalizer, n_p, properties_loss_weight, print_checkpoints=False): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() avg_errors = AverageMeter() # error_vector is an average error we see per property. Its dim is (1,n_p) e...
The main task of the code is to train and evaluate a Graph Convolutional Neural Network (MTCGCNN) for predicting material properties from a dataset. It loads data, initializes the model, trains it using specified hyperparameters, validates performance, and optionally saves checkpoints. The code includes pre-trained mod...
def main(root_dir, save_dir, disable_cuda=True, workers=0, epochs=30, start_epoch=0, batch_size=256, lr=0.01, lr_milestones=[100], momentum=0.9, weight_decay=0.0, print_freq=10, resume='', train_size=None, val_size=1000, test_size=1000, optimizer='SGD', atom_fea_len=64, h_fea_len=128, n_conv=3, n_hp=1, ...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
The main task of the code is to retrieve the current time from a PLC via EtherNet/IP protocol. It constructs a specific attribute request packet, sends it to the PLC, parses the response, and returns the timestamp either as a raw 64-bit integer or converted to a datetime object, along with an error code if the request ...
def _getPLCTime(self, raw=False): ''' Requests the PLC clock time ''' if not self._connect(): return None AttributeService = 0x03 AttributeSize = 0x02 AttributeClassType = 0x20 AttributeClass = 0x8B AttributeInstanceType = 0x24 AttributeI...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
This function requests the PLC's clock time by constructing and sending an EIP packet containing the current timestamp. It first establishes a connection, prepares attribute parameters for the EIP request, packs them into a byte sequence, builds an EIP header, and transmits the packet. The function returns the current ...
def _setPLCTime(self): ''' Requests the PLC clock time ''' if not self._connect(): return None AttributeService = 0x04 AttributeSize = 0x02 AttributeClassType = 0x20 AttributeClass = 0x8B AttributeInstanceType = 0x24 AttributeInstance = 0...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
The main task of this code is to retrieve a list of controller tags (LgxTag type) by repeatedly querying the controller with pagination (using `self.Offset`). It first fetches tags for the default program, then iterates over all programs if `allTags` is True. The function returns the aggregated tags list or an error co...
def _getTagList(self, allTags): ''' Requests the controller tag list and returns a list of LgxTag type ''' if not self._connect(): return None self.Offset = 0 tags = [] request = self._buildTagListRequest(programName=None) eipHeader = self._buildEIPHeade...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
This function retrieves a list of LgxTag objects for a specified program by sending paginated requests. It initializes a connection, builds requests with offset increments, processes responses, and aggregates tags. If errors occur, it returns None and an error code. The loop continues until all tags are fetched or an e...
def _getProgramTagList(self, programName): ''' Requests tag list for a specific program and returns a list of LgxTag type ''' if not self._connect(): return None self.Offset = 0 tags = [] request = self._buildTagListRequest(programName) eipHeader = self....
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
The main task of the code is to retrieve attributes of a User-Defined Type (UDT) by establishing a connection, constructing a read request, generating an EIP header, sending the request, and returning the received data. The function first checks connectivity, builds the request and header, sends it via _getBytes, and r...
def _getTemplateAttribute(self, instance): ''' Get the attributes of a UDT ''' if not self._connect(): return None readRequest = self._buildTemplateAttributes(instance) eipHeader = self._buildEIPHeader(readRequest) status, retData = self._getBytes(eipHead...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
The function `_getTemplate` retrieves members of a UDT (User-Defined Type) by establishing a connection, constructing a read request with the specified instance and data length, generating an EIP header, and fetching the corresponding data bytes. It returns the retrieved data if successful, or `None` if the connection ...
def _getTemplate(self, instance, dataLen): ''' Get the members of a UDT so we can get it ''' if not self._connect(): return None readRequest = self._readTemplateService(instance, dataLen) eipHeader = self._buildEIPHeader(readRequest) status, retData = se...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
The function retrieves module properties for a specified slot using CIP/EIP protocol by sending a structured request packet, parsing the response, and returning an LgxDevice object or a default LGXDevice if the request fails.
def _getModuleProperties(self, slot): ''' Request the properties of a module in a particular slot. Returns LgxDevice ''' if not self._connect(): return None AttributeService = 0x01 AttributeSize = 0x02 AttributeClassType = 0x20 Attrib...
def _parseTagName(tag, offset): ''' parse the packet to get the base tag name the offset is so that we can increment the array pointer if need be ''' bt = tag ind = 0 try: if tag.endswith(']'): pos = (len(tag)-tag.rindex("["))# find position of [ bt = tag[:-po...
This function parses PLC replies, handles BOOL arrays and bit extraction, converts words to bits when necessary, and returns the appropriate values. It processes tag data, determines data type and bit count, and adjusts the response format based on whether the request involves bits of a word or specific data types, ens...
def _parseReply(self, tag, elements, data): ''' Gets the replies from the PLC In the case of BOOL arrays and bits of a word, we do some reformating ''' tagName, basetag, index = _parseTagName(tag, 0) datatype = self.KnownTags[basetag][0] bitCount = se...
def _connect(self): ''' Open a connection to the PLC ''' if self.SocketConnected: return True # Make sure the connection size is correct if not 500 <= self.ConnectionSize <= 4000: raise ValueError("ConnectionSize must be an integer between...
This code processes a multiple read request by constructing and sending a service request to read multiple tags, assembling their data segments, and parsing the returned data. It handles tag parsing, data type determination, segment offset calculation, and response processing to retrieve values for all specified tags i...
def _multiRead(self, tags): ''' Processes the multiple read request ''' serviceSegments = [] segments = b"" tagCount = len(tags) self.Offset = 0 if not self._connect(): return None for tag in tags: if isinstance(tag, (list, tuple)): ...
def _getTagList(self, allTags): ''' Requests the controller tag list and returns a list of LgxTag type ''' if not self._connect(): return None self.Offset = 0 tags = [] request = self._buildTagListRequest(programName=None) eipHeader = self._buildEIPHeade...
This function retrieves a list of tags for a specified PLC program. If the program name exists, it fetches and processes the tags, including UDTs, and returns them. If the program is not found, it returns an error message.
def GetProgramTagList(self, programName): ''' Retrieves a program tag list from the PLC programName = "Program:ExampleProgram" ''' # Ensure programNames is not empty if not self.ProgramNames: tags = self._getTagList(False) # Get a single prog...
def det_2x2(A): #split up the a_1 = A[0][0] a_2 = A[1][0] b_1 = A[0][1] b_2 = A[1][1] #perform calculation detA = ((a_1)*(b_2)-(a_2)*(b_1)) return detA def cramer_2x2(A,b): #create temp values when replacing b into A tempA = A*1 tempB = A*1 tempA[0:,0,] = b[:,0] temp...
The main task of the code is to compute determinants of 2x2 and 3x3 matrices using custom functions and NumPy, solve linear systems via Cramer's Rule, and compare results. It defines matrices A (2x2) and C (3x3) with their respective vectors b and d, calculates determinants with both custom and NumPy methods, applies C...
def main(): #enter array for 2x2 A = np.array([[1.,2.], [3.,4.]]) b = np.array ([[5.], [6.]]) #enter array for 3x3 C = np.array ([[4. , -1. , 0.], [-2. , 7. , -4.], [0. , -3. , 4.]]) d = np.array ([[6.], [0.], [0.]]) #find the...
def Darknet(name=None): x = inputs = tf.keras.layers.Input([None, None, 3]) x = Conv(x, 32, 3) x = DarknetRes(x, 64, 1) x = DarknetRes(x, 128, 2) x = x1 = DarknetRes(x, 256, 8) x = x2 = DarknetRes(x, 512, 8) x = x3 = DarknetRes(x, 1024, 4) return tf.keras.Model(inputs, (x1, x2, x3), name...
This code defines a YOLOv3 object detection model with three output heads for multi-scale predictions. It processes input through a Darknet backbone, then applies YoloConv and YoloOut layers to generate detection outputs (small, medium, big) at different grid resolutions. The model returns a Keras Model with three outp...
def Yolov3(size=None, channels=3, anchors=anchors, masks=anchor_masks, classes=80): x = input = tf.keras.layers.Input([size, size, channels], name='input') x1, x2, x3 = Darknet(name='yolo_darknet')(x) x = YoloConv(512, name='conv_small')(x3) x_small = YoloOut(512, len(masks[0]), classes, na...
def parse_results(paths): return pycoevolity.parsing.get_dict_from_spreadsheets( paths, sep = "\t", offset = 0) def generate_scatter_plots( data_grid, plot_file_prefix, parameter_symbol = "t", column_labels = None, row_labels = None, ...
The main task of the code is to generate comparative visualizations of simulation results for evolutionary models. It parses data from full, exonic, and doubled-simulation scenarios, then creates scatter plots and histograms to evaluate parameters like event time, population size, effective sample size (ESS), and poten...
def main_cli(argv = sys.argv): brooks_gelman_1998_recommended_psrf = 1.2 plot_width = 2.5 plot_height = 2.4 pad_left = 0.15 pad_right = 0.94 pad_bottom = 0.2 pad_top = 0.90 axis_label_size = 14.0 full_results = parse_results(glob.glob( os.path.join(project_util.ECOEVOLI...
def get_parameter_names(dpp = True): p = ["ln_likelihood"] if dpp: p.append("concentration") else: p.append("split_weight") p.append("number_of_events") comparison_labels = [ "catn", "cats", "modn", "mods", "poen", ...
This function parses simulation results from multiple runs by processing log files, aggregating posterior, true values, and stdout data, and saving aggregated results to CSV files. It handles batch directories, checks for existing outputs, and ensures expected file counts before parsing and writing results.
def parse_simulation_results( number_of_comparisons = 6, expected_number_of_runs = 4, expected_number_of_samples = 1501, burnin = 501): batch_number_pattern = re.compile(r'batch(?P<batch_number>\d+)') sim_number_pattern = re.compile(r'-sim-(?P<sim_number>\d+)-') val_sim_dirs ...
def isGameOver(self): if len(self.playerCheckers) == 0 or len(self.opponentCheckers) == 0: return True else: return (not self.playerCanContinue()) and (not self.opponentCanContinue()) def getGameSummary(self): self.GUI.pauseGUI() print("Game Over!") player...
The main task of the code is to handle game turn progression. If the game is over, it retrieves the summary. Otherwise, it switches turns: if it's the player's turn, it exits early; if it's the AI's turn, it triggers the AI to make a move.
def next(self): if self.isGameOver(): self.getGameSummary() return self.changePlayerTurn() if self.playerTurn: # let player keep going return else: # AI's turn self.AIMakeMove()
def _find_index_of_diff_flag(bad_rates: List[Dict]) -> int: """Find the index of the bad rate with the smallest difference in woe. Args: bad_rates (List[Dict]): List of bad rates. Returns: int: Index of the bad rate with the smallest difference in woe.""" bad_rate_diffs = np.diff([bad_r...
The function `_merge_bins_chi` merges bins using the chi-squared statistic to optimize bad rate calculations. It identifies a bin index requiring adjustment, removes specific bins based on the index position, and applies chi-squared-based bin extraction if needed. Finally, it recalculates bad rates with the updated bin...
def _merge_bins_chi(x, y: np.ndarray, bad_rates: List[Dict], bins: List) -> List[Dict]: """Merge the bins with the chi-squared statistic. Args: x (pd.DataFrame): Input data. y (np.ndarray): Output data. bad_rates (List[Dict]): List of bad rates. bins (List): List of bins. Ret...
def _find_index_of_diff_flag(bad_rates: List[Dict]) -> int: """Find the index of the bad rate with the smallest difference in woe. Args: bad_rates (List[Dict]): List of bad rates. Returns: int: Index of the bad rate with the smallest difference in woe.""" bad_rate_diffs = np.diff([bad_r...
This function merges bins in a dataset based on the Information Value (IV) statistic to optimize binning for feature importance. It identifies a bin index for merging, adjusts the bins list by removing or extracting bins, recalculates bad rates using updated bins, and returns the refined bad rates and adjusted bins. Th...
def _merge_bins_iv(x, y: np.ndarray, bad_rates: List[Dict], bins: List) -> List[Dict]: """Merge the bins with the IV statistic. Args: x (pd.DataFrame): Input data. y (np.ndarray): Output data. bad_rates (List[Dict]): List of bad rates. bins (List): List of bins. Returns: ...
def _calc_max_bins(bins, max_bins: float) -> int: """Calculate the maximum number of bins. Args: bins (List): List of bins. max_bins (float): Maximum number of bins. Returns: int: Maximum number of bins.""" return max(int(len(bins) * max_bins), 2) def _bin_bad_rates( x: np.n...
This function bins categorical features by grouping similar categories into bins based on their bad rates, ensuring the number of bins doesn't exceed the specified maximum. It handles missing values by creating a separate bin, merges bins with similar WOE values, and adjusts bins to meet minimum percentage thresholds, ...
def _cat_binning( x, y: np.ndarray, min_pct_group: float, max_bins: Union[int, float], diff_woe_threshold: float, ) -> Tuple[pd.DataFrame, np.ndarray]: """Bin the categorical features. Args: x (pd.DataFrame): Input data. y (np.ndarray): Output data. min_pct_group (flo...
def _calc_max_bins(bins, max_bins: float) -> int: """Calculate the maximum number of bins. Args: bins (List): List of bins. max_bins (float): Maximum number of bins. Returns: int: Maximum number of bins.""" return max(int(len(bins) * max_bins), 2) def _bin_bad_rates( x: np.n...
This function performs numerical binning on a feature 'x' with target 'y', creating intervals to analyze bad rates. It adjusts bins for missing values, merges intervals using chi2/iv methods to ensure monotonicity, and enforces min percentage thresholds and WOE differences. The result includes binning intervals and han...
def _num_binning( x, y: np.ndarray, min_pct_group: float, max_bins: Union[int, float], diff_woe_threshold: float, merge_type: str, ) -> Dict: """Num binning function. Args: x: feature y: target min_pct_group: min pct group max_bins: max bins diff_w...
def _draw_start_screen(self, surface: pygame.Surface) -> None: """Draws the start screen""" # drawing the button self._draw_start_button(surface) # drawing the instructions for the game self._blit_start_instructions(surface) def _draw_game(self, surface: pygame.Surface) -> None: ...
The main task of the code is to redraw the game screen based on the current phase. It clears the display, draws the start screen, game elements (board, snake, score), or game-over screen depending on `self._phase`, then updates the display with `pygame.display.flip()` to reflect changes visually.
def _redraw(self) -> None: """Draws the board""" surface = pygame.display.get_surface() surface.fill(BACKGROUND_COLOR) if self._phase == "START": self._draw_start_screen(surface) elif self._phase in ("GAME", "GAME_OVER_ANIMATION"): self._draw_game(surface)...
def _resize_surface(self, size: tuple[int, int]) -> None: """Resizes the pygame window to the size.""" pygame.display.set_mode(size, pygame.RESIZABLE) def _update_score(self) -> None: """updates the score and last snake part version""" if self._current_score < self._game.get_snake_length...
The code initializes a Pygame window for a Snake game, sets up game parameters, and runs a loop to handle game logic, events, and rendering. It controls game progression via cycle counters, updates the score, transitions between game phases (e.g., "GAME" to "GAME_OVER"), and maintains a target frame rate. The loop cont...
def run(self) -> None: pygame.init() box_width = 50 self._resize_surface((16 * box_width, 9 * box_width)) clock = pygame.time.Clock() pygame.display.set_caption('Snake') pygame.display.set_icon(pygame.image.load(self._image_paths['icon'])) while self._running: ...
def _check_hover(self): # resets every button hover property to false first self._hover_reset() # logic is , if mouse position overlaps button rectangle, then it is hovered over if self.start_random.rect.collidepoint(pygame.mouse.get_pos()) and not self.start_random.selected: ...
The code defines a main application loop that continuously checks for user interactions on the home screen, executes pathfinding algorithms (Dijkstra or A*) based on user input, and updates the screen. It handles hover events, button clicks, and algorithm execution in a loop until the application terminates.
def run_app(self): """main program loop""" while True: if self.homescreen: # checks hover buttons for homescreen self._check_hover() self._checkevents() if self.homescreen and not self.helpscreen: # calls appropriate act...
def luminosity(self): return self.LUMINOSITY def surface_temp(self): return self.SURFACE_TEMP def radius(self): #I've absolutely forgotten where this equation came from, but it seems to generate very accurate radii. return (((self.surface_temp())**2)*(self.luminosity()**0.5)).value * u.a...
The code's main task is to display a star's properties by printing its luminosity, surface temperature, radius, color index, RGB color components, and spectral power at 1000 nm. It aggregates and outputs calculated values from methods like `luminosity()`, `surface_temp()`, and `spectral_power_at()`, providing a summary...
def display(self): print("Luminosity:", self.luminosity()) print("Surface Temp:", self.surface_temp()) print("Radius:",self.radius()) print("Color Index:",self.color_index()) print("RGB:", self.rgb_color()[0], self.rgb_color()[1], self.rgb_color()[2]) print("Spectral ...
def magn(stuff): if isinstance(stuff, list): return 3*magn(stuff[0]) + 2*magn(stuff[1]) return stuff def sn_reduce(sn): while True: expl, spl = find4(sn), find10(sn) if expl == -1 and spl == -1: return sn if expl != -1: sn = sn_explode(sn, expl-1) ...
The code reads lines from 'input.txt', computes all pairwise combinations of lines, adds them using `sn_add`, reduces the result with `sn_reduce`, evaluates the string to a list, calculates the magnitude with `magn()`, and tracks the maximum value. It returns the highest magnitude found among all pairs. Your return
def main(): with open('input.txt') as input_file: lines = [line.strip() for line in input_file.readlines()] # result = lines[0] # for i, line in enumerate(lines[1:]): # line = sn_add(result, line) # result = sn_reduce(line) # #eval string as list then calc magnitude ...
def invalid_input_error(): print("Invalid Input!") exit(1) def read_from_file(path): centroids = [] try: lines_in_file = open(path, 'r').readlines() except FileNotFoundError: invalid_input_error() except: general_error() for line in lines_in_file: if not line:...
The code processes input vectors based on a specified goal, performing tasks like spectral clustering (spk), affinity matrix calculation (wam), degree matrix computation (ddg), Laplacian norm (lnorm), or Jacobi algorithm (jacobi). It validates inputs, reads vectors from a file, and executes the corresponding algorithm ...
def main(args): #args = [k, goal ,filename] if len(args) != 3 and len(args) != 2: invalid_input_error() try: k = int(args[0]) except ValueError: invalid_input_error() goal = args[1] #check if goal is one of the options... and act accordingly input_path = args[2] vecto...
def _Parse(self, label): tmp = label.split(".") if len(tmp) == 1: # no dots return label, None, None elif len(tmp) == 2: return tmp[0], tmp[1], None else: return tmp[0], tmp[1], tmp[2:] def _GetKeys(self, cls): if not u"*" in self._rel_keys: ...
This code fetches GitHub data based on a label, parsing it into organization, sub-resource (e.g., repos, issues), and parameters. It uses the GitHub API to retrieve organization details, repositories, issues, pull requests, or commits, structuring results into a table with dynamic fields and values. The add_info parame...
def Fetch(self, label): ret = tb.RqTable() org_name, sub_name, add_info = self._Parse(label) # to break google.issues.something to org_name = 'google' sub_name = 'issues' add_info = 'something' org = self._github.get_organization(org_name) if sub_name == None: # eg. "google" ...
def reduce_tprecision(self,freq,tcol=None): """ Reduce timesamp precision of data in place. If a 'time_org' column does not exist the orginal 'time' column is renamed as such. The new timestamp data is given in the 'time' column. Parameters ---------- ...
The `classify` method categorizes trades as buyer- or seller-initiated using specified algorithms (e.g., FI variants, Lee-Ready, BVC). It adjusts timestamp precision based on `freq` and `reduce_precision`. For most methods, it adds columns (`Initiator`, `Step`) to indicate classification results; for 'bvc', it returns ...
def classify(self,method,freq,reduce_precision=True,**kwargs): """ Classifies trades into buyer- and seller-initiated. Parameters ---------- method : str Must be one of the following: 'ds_1', 'ds_2', 'ds_3' (different versions of the FI algorithm), 'lee_...
def _ensure_no_complex_data(array): if hasattr(array, 'dtype') and array.dtype is not None \ and hasattr(array.dtype, 'kind') and array.dtype.kind == "c": raise ValueError("Complex data not supported\n" "{}\n".format(array)) def _ensure_sparse_format(spmatrix, accept_spa...
This function validates and converts input arrays, ensuring they meet specified constraints such as dimensionality, data type, and sparsity. It checks for finite values, enforces 2D structure, handles sparse formats, and raises errors for invalid inputs, while allowing customization of dtype, sparse acceptance, and sam...
def check_array(array, accept_sparse=False, *, accept_large_sparse=True, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1, estimator=None): """Input validation on an array, lis...
def generated_the_product_graph(terms = parser()): def generated_the_product_graph_by_base(_terms, number_premu=0): G = nx.Graph() Gproduct = nx.Graph() edges_set = set() for (H1, H2) in product(_terms, _terms): if H1.tensorspace(H2)...
The function generates and optimizes quantum circuits by iteratively creating alternate paths, enforcing constraints on remaining terms, and selecting the circuit with minimal depth from multiple candidates. It returns the optimized circuit and associated terms.
def compose_alternate_enforce(): G, mainProductG, terms, permus = generated_the_product_graph() canidates = [ ] for _ in range(5): path, terms, color = alternate_path_v2( deepcopy(G), deepcopy(mainProductG), terms, permus, single_iteration=True) circuit = gen...
def hand_rank(hand:'It is a list of values in one hand')->'tuple': '''For 3-card poker ranks in order (highest to lowest) Straight flush Three of a kind Straight Flush Pair High card ''' ranks = card_ranks(hand) suits = card_suits(hand) if straight(ranks) and flush(suits): ...
The code determines the winner between two poker hands by evaluating their ranks using different ranking functions based on hand size (3, 4, or 5 cards). It compares the ranked values, identifies the higher-ranking hand, and returns the winner's index (1 or 2) or "HARD LUCK" if ranks tie under specific conditions (e.g....
def poker(hands:'It is a tuple conatining both the values of hands from the two players')->'list': '''Given two hands find out which one is the winner''' if(len(hands[0])==5 and len(hands[1])==5): l=[] for i in range(len(hands)): l.append(list(hand_rank(hands[i]))) elif...
def type_check(params): if (type(params).__name__=='list') == True: params = np.concatenate(params, axis = 0) return params def pr(y_true, y_pred): # Calculates the precision true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, ...
The function `calculat_f1` computes precision, recall, and F1 score for evaluating classification model performance. It converts predictions to class labels via argmax, ensures input consistency, and calculates metrics using helper functions. The returned tuple contains these three evaluation scores, essential for asse...
def calculat_f1(true_labels, predictions): true_labels = type_check(true_labels) predictions = type_check(predictions) pred_labels = np.argmax(predictions, axis=1).flatten() true_labels = true_labels.flatten() precision = pr(true_labels, pred_labels) recall = rc(true_labels, pred_labels) ...
def getHeuristic(self, x, y): x1, y1 = self.goal return (abs(x - x1) + abs(y - y1)) def expandNode(self, open, nodes): moves = [UP, DOWN, LEFT, RIGHT] x, y = nodes.head for i in range(4): dx, dy = moves[i] x1 = x + dx y1 = y + dy i...
The main task of the code is to implement the A* algorithm for pathfinding, using a heuristic (h) and confirmed cost (g) to navigate from a start node to a goal. It expands nodes via a priority queue (open list), avoids revisiting nodes (close list), and returns the optimal path if the goal is reached. Special handling...
def aStar(self): # h (Estimated weight from the confirmed weight to the goal) g (Confirmed assumption from the start node) h = self.getHeuristic(self.head[0], self.head[1]) g = 0 node = Node(self.board, self.coords, 0, 0, h, g, self.coords[0], self.direction) open = [] cl...
def clearBoard(self): for x in range(1, len(self.board) - 1, 1): for y in range(1, len(self.board[0]) - 1, 1): self.board[y][x] = 0 def denoteXY(self, coords, coord): self.coords.clear() x, y = self.getXY(coord) self.goal = x, y self.board[y][x] = 1 ...
The code's main task is to find a path on a board using the A* algorithm. It clears the board, marks the given coordinates, and executes the A* pathfinding method to determine the optimal route between specified points.
def findPath(self, coords, coord): self.clearBoard() self.denoteXY(coords, coord) self.path = self.aStar()
def generate_grid(self, fineness=100, check_flag=False): if check_flag: # The check grid has been calculated if self.check_grid_fineness == fineness: return self.check_grid elif self.check_grid_fineness != -1: self.reset_check_grid() el...
The code checks if a policy π is feasible by evaluating the maximum constraint violation across a generated grid. It computes a value based on grid data, the policy's q-values, and a discount factor γ. If the maximum violation is below a tolerance ε, the policy is deemed feasible.
def check_pi_feasible_true_P(self, pi, check_fineness, epsilon=1e-10): grid = self.generate_grid(fineness=check_fineness, check_flag=True) grid_c, grid_u = self.generate_grid_c_u(check_flag=True) feasible_flag = False q_pi = self.q_pi(pi) vals = (1. / (1. - self.gamma)) * np.sum(...
def generate_grid(self, fineness=100, check_flag=False): if check_flag: # The check grid has been calculated if self.check_grid_fineness == fineness: return self.check_grid elif self.check_grid_fineness != -1: self.reset_check_grid() el...
The code generates a heat map by computing values based on a grid and Q-values. It creates grids (grid, grid_c, grid_u), transforms input pi into Q-values (q_pi), calculates weighted sums, applies a discount factor (gamma), subtracts grid_u, and ensures non-negative results via np.maximum. The output 'vals' represents ...
def generate_heat_map(self, pi, check_fineness): grid = self.generate_grid(fineness=check_fineness, check_flag=True) grid_c, grid_u = self.generate_grid_c_u(check_flag=True) q_pi = self.q_pi(pi) vals = np.maximum((1. / (1. - self.gamma)) * np.sum(grid_c * q_pi, axis=(1, 2)) - grid_u, 0.)...
def generate_grid(self, fineness=100, check_flag=False): if check_flag: # The check grid has been calculated if self.check_grid_fineness == fineness: return self.check_grid elif self.check_grid_fineness != -1: self.reset_check_grid() el...
This code solves an extended Linear Stochastic Infinite Horizon (LSIP) problem using Gurobi optimization. It iteratively refines constraints by checking feasibility of occupancy measures (z) against a generated grid, adjusting the model to find a feasible policy (pi_hat) that maximizes rewards under MDP constraints. Th...
def SI_plan(self, iter_upper_bound, fineness, check_fineness, silent_flag=True): search_grid = self.generate_grid(fineness=fineness) search_grid_c, search_grid_u = self.generate_grid_c_u(check_flag=False) time_start = time.time() S = self.S A = self.A Y0 = [self.y0] ...
def SA_log_likelihood(self, tr, x, y = 0): if self.distribution == "normal": return self.SA_log_likelihood_normal(tr, x) else: return self.SA_log_likelihood_logistics(tr, x, y) def SA_mutate(self, x, y = 0): if self.distribution == "normal": return abs(normalv...
This code implements a Simulated Annealing algorithm to optimize logistics parameters. It initializes temperature and cooling rate, iteratively mutates solutions, evaluates their fitness, and accepts worse solutions probabilistically based on temperature. The best solution is updated as the algorithm converges, returni...
def SA_train_logistics(self, tr): x, y = self.x, self.y temperature = 10000 cooling_rate = 0.03 best = (self.SA_log_likelihood(tr, x, y), x, y) explore = best seed() while temperature > 1: x_new, y_new = self.SA_mutate(x, y) fitness_new = ...
def SA_log_likelihood(self, tr, x, y = 0): if self.distribution == "normal": return self.SA_log_likelihood_normal(tr, x) else: return self.SA_log_likelihood_logistics(tr, x, y) def SA_mutate(self, x, y = 0): if self.distribution == "normal": return abs(normalv...
This code implements a Simulated Annealing optimization algorithm to find the optimal parameter 'x' that minimizes the log-likelihood function SA_log_likelihood for input data 'tr'. It iteratively explores mutated solutions, accepts worse ones probabilistically based on temperature, and gradually reduces temperature to...
def SA_train_normal(self, tr): x = self.sigma temperature = 10000 cooling_rate = 0.03 best = (self.SA_log_likelihood(tr, x), x) explore = best seed() while temperature > 1: x_new = self.SA_mutate(x) fitness_new = self.SA_log_likelihood(tr,...
def initUI(self): mainSplitter = QSplitter(Qt.Horizontal) controlPanel = QWidget() controlLayout = QVBoxLayout() self.deviceCheckBox = QCheckBox("Use CUDA if available") self.deviceCheckBox.setChecked(True) controlLayout.addWidget(self.deviceCheckBox) # Batch Siz...
This code initializes a MainWindow GUI for a face detection application by setting up UI components, loading saved settings (target face, input, export paths) from QSettings, configuring the window, and displaying an initial target face image. It prepares the interface for further processing and configuration tasks.
def __init__(self): super(MainWindow, self).__init__() self.photoViewer = None self.targetFaceImageLabel = QLabel() self.targetFaceImageLabel.setAlignment(Qt.AlignCenter) self.targetFaceImageLabel.setFixedSize(100, 100) self.targetFaceImageLabel.setStyleSheet("border: 1px...
def dfs(graph, start, end): visited = set() all_paths = [] def dfs_recursive(node, path): if node == end: all_paths.append(path + [node]) return if node not in visited: visited.add(node) for neighbor in graph[node]: dfs_recursi...
The main task of the code is to create an interactive Streamlit web interface that demonstrates Depth-First Search (DFS) and Breadth-First Search (BFS) graph algorithms. Users can input custom graphs, specify start/end nodes, execute the algorithms, and view the traversal paths and computation times. The interface also...
def display_graph_algorithms(): st.header("Graph Algorithms") st.markdown("- **Graph algorithms are procedures or formulas for solving problems on graphs.**") st.markdown("- **Some common graph algorithms include:**") st.markdown(""" #### Depth-First Search (DFS) ...
def display_welcome_message(): st.title("Graph Coverage Prime Paths") st.write("Graph coverage prime paths is a software tool that generates test paths to satisfy graph coverage test criteria.") st.write("Graphs are essential data structures for representing connections between various entities.") st.wr...
The code defines a function `display_home_page()` that structures and renders a home page interface using Streamlit. It sequentially displays a welcome message, graph concepts, graph algorithms, and coverage criteria, with markdown dividers separating each section to organize the content visually and logically.
def display_home_page(): display_welcome_message() st.markdown("---") display_graph_concepts() st.markdown("---") display_graph_algorithms() st.markdown("---") display_coverage_criteria()
def preprocess_label(label): return [0.0, 1.0] if label == "negative" else [1.0, 0.0] def tokinize(s): s = review_clean(s).lower() splited = s.split() return splited[:MAX_LENGTH] def preprocess_review(s): cleaned = tokinize(s) embadded = embadding.get_vecs_by_tokens(cleaned) if embadded.shap...
The main task of the code is to preprocess a batch of reviews and labels into three components: label tensors (binary classification format), embedding tensors (concatenated processed reviews), and tokenized reviews. It processes each review by tokenizing, extracting embeddings, and converting labels to a PyTorch tenso...
def collact_batch(batch): label_list = [] review_list = [] embadding_list = [] for review, label in batch: label_list.append(preprocess_label(label)) ### label review_list.append(tokinize(review)) ### the actuall review processed_review = preprocess_review(review).detach() ...
def filling_phase_dynamic_matrix(self, t): """ :param t: time (s) :return: A matrix for filling phase """ """ WRITE CODE HERE """ el = self.elastance(t) del_dt = self.elastance_finite_difference(t) return [[del_dt / el - el / self.R2, el /...
The code computes time derivatives of cardiovascular state variables (ventricular/atrial/arterial pressures, aortic flow) by selecting the appropriate dynamic matrix based on the system's phase: filling (atrial > ventricular pressure), ejection (positive aortic flow or ventricular > arterial pressure), or isovolumic (d...
def get_derivative(self, t, x): """ :param t: time :param x: state variables [ventricular pressure; atrial pressure; arterial pressure; aortic flow] :return: time derivatives of state variables """ """ WRITE CODE HERE Implement this by deciding whether th...
def find_word (s, hash_table): idx = hash_word(s, len(hash_table)) if hash_table[idx] == s: return True elif hash_table[idx] != '': step = step_size(s, 13) num_steps = 1 while hash_table[(idx + step * num_steps) % len(hash_table)] != '': if hash_table[(idx + ste...
The function determines if a string `s` can be reduced to one of the vowels "a", "i", or "o" by recursively checking shorter words from a hash table. It uses memoization (`hash_memo`) to optimize repeated checks, returning `True` if any valid reduction path exists, otherwise `False.`
def is_reducible (s, hash_table, hash_memo): if len(s) == 1: return s == "a" or s =="i" or s =="o" elif find_word(s, hash_memo): return True elif not find_word(s, hash_table): return False else: short_words_lst = get_short_words(s, hash_table) for w...
def is_prime ( n ): if (n == 1): return False limit = int (n ** 0.5) + 1 div = 2 while (div < limit): if (n % div == 0): return False div += 1 return True def insert_word (s, hash_table): idx = hash_word(s, len(hash_table)) if hash_table[idx] == '': ...
The code reads words from input, appends specific short words, generates prime-sized hash tables, hashes words using double hashing, checks for reducibility recursively, collects reducible words, and prints the longest (10-letter) reducible words in alphabetical order. It combines hashing, prime-number calculations, an...
def main(): # create an empty word_list word_list = [] # read words from words.txt and append to word_list for line in sys.stdin: line = line.strip() word_list.append (line) # Add smallest possible words!! word_list.append("i") word_list.append("a") word_list.append("o")...