dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def GameBoard(I=None, J=None): # Display the Actions / coordinates. # x=0, y=500, w=500, h=200 action_rect = Rect(0, 500, 500, 200) # Lower rectangle. pygame.draw.rect(screen, GRAY, action_rect) # The main screen # For game screen # x=0, y=0, w=500, h=500 game_rect = Rect(0...
The main task of the code is to run a reinforcement learning simulation where an agent navigates a grid-based environment to pick up and drop off a passenger. It initializes game states, handles user input for movement, updates rewards, and tracks cumulative rewards. The agent's actions (UP/DOWN/LEFT/RIGHT) are determi...
def mainGame(get_actions, counter, run, input_): global pickup_position global dropoff_position global PASSENGER_PICKED global ACTION global CUMULATIVE_REWARD global REWARD global NEW_GAME global CUMULATIVE_REWARD_LIST, C GameBoard() # place the car ...
def replace_missing_data(data): for col in data.columns: expected = statistics.mode(data[col]) data[col] = np.where((data[col].values == '?'), expected, data[col].values) return data def split_to_train_test(data, train_size): if isinstance(train_size, float): train_size = round(train...
The main task of the code is to evaluate a decision tree classifier's performance across varying training data ratios. For each ratio, it iteratively splits data into training and test sets, trains a tree, predicts test outcomes, and calculates accuracy metrics (max, min, mean). The process repeats for each ratio to as...
def testing(df, ratios): iterations = len(ratios) for size in ratios: print("For training ratio: ", size) accuracy = [] for j in range(iterations): prepared_data = replace_missing_data(df) train, test = split_to_train_test(prepared_data, size) train_ar...
def input_layer(self): self.input_ids = tf.placeholder(tf.int32, [None, self.seq_length]) self.input_mask = tf.placeholder(tf.int32, [None, self.seq_length]) self.segment_ids = tf.placeholder(tf.int32, [None, self.seq_length]) self.label_ids = tf.placeholder(tf.int32, [None]) def loss(se...
This code initializes a model training configuration with parameters like batch size, learning rate, and GPU settings. It sets up BERT architecture, defines input layers, computes loss, and prepares for distributed training across multiple GPUs by dividing the batch size. The class also checks available GPUs and prints...
def __init__(self, batch_size, learning_rate, num_train_steps, num_warmup_steps, num_labels, seq_length, query_length, bert_config, use_one_hot_embeddings, is_training, is_fine_tuning, gpu_num): self.batch_size = batch_size self.learning_rate = learning_rate self.num_train_steps...
def ensure_model_is_loaded(self): if not self.__model: self.load_model() def warm_up(self): self.ensure_model_is_loaded() if self.__model_warm: return # a dummy variable for labels the will be given as an input to the network but will be ignored dummy_la...
The code detects objects in an input image by processing regions of interest (ROIs) through a preloaded model. It resizes and pads the image, extracts ROIs, runs the model to predict ROI labels and probabilities, applies non-max suppression to refine detections, filters out background labels, and returns the final obje...
def detect(self, img): self.ensure_model_is_loaded() self.warm_up() resized_img, img_model_arg = self.resize_and_pad(img) test_rois, original_rois = self.get_rois_for_image(img) roi_padding_index = len(original_rois) # a dummy variable for labels the will be given as...
def register_shape(self, puzzle_dict: str): """ Function - register_shape call from puzzle database to load all path from puz file register all the shape from these path to turtle screen object """ self.puzzle.load_puzzle(puzzle_dict) for path in self.puzz...
This method loads a map by registering puzzle shapes, creating a matrix based on the given order, stamping the matrix with boxing effects enabled, and generating a thumbnail. It combines multiple class methods to initialize and visualize the map structure.
def load_map(self, puzzle_dict: str, order: bool): """ Function - load_map combination for a series of method in this class to load a map, this method enable boxing effect drawing by default """ self.register_shape(puzzle_dict) self.create_matrix(order) ...
def create_matrix(self, order: bool): """ Function - create_matrix create matrix which represent the whole tile map if the matrix ordered, just create a increment series for it otherwise call generate_valid function to generate a solvable random one """ ...
The main task of the `refresh_map` function is to reset and refresh the matrix by invoking a series of methods (`create_matrix`, `clear`, `stamp_matrix`) without clearing thumbnails or redrawing grid/boxing effects, ensuring an ordered matrix state is re-established efficiently.
def refresh_map(self): """ Function - refresh_map combination for a series of method in this class to refresh the matrix (implement reset button) this will create a ordered matrix but do not clear the thumbnail by calling clear and stamp new ti...
def key_expansion(self, cipher_key): self.key_symbols = [ord(symbol) for symbol in cipher_key] if len(self.key_symbols) < 4 * self.nk: for i in range(4 * self.nk - len(self.key_symbols)): self.key_symbols.append(0x01) key_schedule = [[] for i in range(4)] for ...
The code implements AES encryption by transforming input bytes through multiple rounds of substitution, shifting, mixing, and key addition using a provided cipher key, then returning the encrypted output bytes.
def encrypt(self, input_bytes, cipher_key): state = [[] for j in range(4)] for r in range(4): for c in range(self.nb): state[r].append(input_bytes[r + 4 * c]) key_schedule = self.key_expansion(cipher_key) state = self.add_round_key(state, key_schedule) ...
def key_expansion(self, cipher_key): self.key_symbols = [ord(symbol) for symbol in cipher_key] if len(self.key_symbols) < 4 * self.nk: for i in range(4 * self.nk - len(self.key_symbols)): self.key_symbols.append(0x01) key_schedule = [[] for i in range(4)] for ...
This code decrypts a cipher text using AES decryption. It initializes the state matrix, applies the inverse key schedule, and iteratively performs inverse transformations (shift rows, sub bytes, mix columns) in reverse encryption order, applying round keys at each step. The final output is a decrypted byte array constr...
def decrypt(self, cipher, key): state = [[] for i in range(self.nb)] for r in range(4): for c in range(self.nb): state[r].append(cipher[r + 4 * c]) key_schedule = self.key_expansion(key) state = self.add_round_key(state, key_schedule, self.nr) rnd ...
def getRoadMask(self, blackout_flag, dead_end_flag, dead_end_flag_2): depthGrad = self.depthGradient(blackout_flag, dead_end_flag, dead_end_flag_2) avg_depth_grad = depthGrad.mean() if avg_depth_grad < 80.0: blackout_flag = 1 print("Image Blackout!! {}".format(avg_depth_g...
The main task of the code is to determine a target direction vector and angle for a vehicle navigation system by analyzing road masks, detecting the car's position, identifying road boundaries, and calculating a target offset relative to the car's forward direction. It processes image data to find a valid target point ...
def targetVector(self, blackout_flag, dead_end_flag, dead_end_flag_2): roadMask, nComp, blackout_flag = self.getRoadMask(blackout_flag, dead_end_flag, dead_end_flag_2) pt1, pt2, box, flag = self.carDetect(roadMask, nComp) carForward = pt1 - pt2 # print(pt1, pt2, pt2-pt1) croad...
def build_topic_pdf ( topic_row, software_name, solution_name='solution', min_proportion=0.5 ): site_url = 'https://how-to-data.org/' # make first page with TOC that links to all later pages description_and_toc = make_all_task_names_links( topic_row['content'] ) tasks = tasks_df[tasks_df.permalink.apply...
The function generates a markdown topic page by compiling downloadable PDF links for software solutions, using data from dataframes. It iterates through software and solution pairs, constructs PDF filenames, and appends markdown links to a downloads section. If no PDFs exist, it sets a default message. Finally, it writ...
def build_topic_page ( row ): pdf_downloads = '' for sindex, srow in software_df.iterrows(): possible_packages = solutions_df[solutions_df['software'] == srow['name']] possible_packages = possible_packages['solution name'].unique().tolist() for package in possible_packages: p...
def sections ( markdown ): result = OrderedDict() section = None content = '' for line in markdown.split( '\n' ): if line[:3] == '## ': if section is not None: result[section] = content section = line[3:] content = '' elif section is no...
The main task of the code is to convert existing solutions from one software (from_sw) to another (to_sw) by generating instructional files. It reads a solved task's markdown content, isolates sections specific to from_sw, and creates a new file for to_sw that includes the original solution alongside step-by-step guida...
def convert ( task_name, from_sw, to_sw, format ): # Get markdown content of software in which the task is already solved content = read_text_file( os.path.join( jekyll_input_folder, blogify( task_name )+'.md' ) ) sections_dict = sections( content ) # For each solution in the "from" software, cr...
def msg(self, Message): """ Print out the specified message if the print_messages flag is set. """ if (self.print_messages == True): print(Message) def get_curr_room(self): """ Get the current room that the player is in. """ return(se...
This function maps string-based action commands to corresponding method calls, executing actions like movement, shooting, picking up gold, or exiting. It returns the result of the executed method or False if the action is unrecognized.
def action_wrapper(self, ActionStr): """ Wrap up the actions as strings. """ self.msg("ActionWrapper: {}".format(ActionStr)) if (ActionStr == "GetRoom"): return(self.get_curr_room()) elif (ActionStr == "PickupGold"): return(self.pickup_g...
def skip_whitespace(self, index): """ RETURN NEXT NON-WHITESPACE CHAR, AND ITS INDEX """ c = self.json[index] while c in WHITESPACE: index += 1 c = self.json[index] return c, index + 1 def simple_token(self, index, c): if c == b'"': ...
This function iterates through the properties of a JSON object, parsing key-value pairs by handling quotes for property names, colons, and values. It checks if "name" is in expected variables, updates the destination with parsed names, and processes values using _assign_token. The loop continues until closing braces ar...
def _decode_object_items(self, index, c, parent_path, query_path, expected_vars): """ ITERATE THROUGH THE PROPERTIES OF AN OBJECT """ c, index = self.skip_whitespace(index) num_items = 0 while True: if c == b",": c, index = self.skip_whitespace...
def hasTwoPair(self): hasTwoPair = False self.reset() self.line_up() # Find a list of all pairs, and from there easy to do high and low. pairsList = [] for val in self.freq: if self.freq[val] == 2: pairsList.append(val) pairsList.s...
This function determines the best poker hand from a given set of cards by sequentially checking for hand types from highest to lowest hierarchy (e.g., royal flush to high card). It evaluates each potential hand using dedicated methods, updates the 'best' variable when a valid hand is found, and returns the highest-rank...
def findHandType(self): # Find the best poker hand which is contained in this hand. best = None if self.hasHighCard() is not None: best = self.hasHighCard() if self.hasOnePair() is not None: best = self.hasOnePair() if self.hasTwoPair() is not None: ...
def creating_parking_lot_helper(self,instruction_breakup): if len(instruction_breakup)!=2: return "Invalid Arguement to create parking lot" try: size_of_parking = int(instruction_breakup[1]) except: return "parking lot size is not an integer" self.pa...
The code processes parking lot commands by validating input, splitting instructions, and delegating tasks to specific helper methods. It checks if the instruction is a non-empty string, splits it into parts, and routes the command (e.g., "Create_parking_lot", "Park", "Leave") to corresponding helper functions. If inval...
def perform_operation(self,instruction): if not type(instruction)==str or instruction=="": return False instruction_breakup = instruction.strip("\n").split(" ") if instruction_breakup[0]=="Create_parking_lot": return self.creating_parking_lot_helper(instruction_breakup)...
def sanitize_threshold(threshold: float) -> None: if threshold < 0.0 or threshold > 1.0: raise ValueError( 'Threshold must be within 0-1 range, got instead: {}'.format( threshold)) def get_basename_without_extension(path: str): basename = os.path.basename(path) return os....
The main task of the code is to perform hard clipping on a mono audio signal from a WAV file using a moving window, normalize the processed signal, and save the result as a new WAV file with a modified filename indicating the applied threshold and window length.
def main(wav_input_file, threshold, window_length): """Performs hard clipping on mono signal from WAV_INPUT_FILE. """ sanitize_threshold(threshold) in_file_base = get_basename_without_extension(wav_input_file) in_samples = read_samples_from_mono_wav(wav_input_file) out_samples = hard_clip_sym...
def format_preset(preset): """Parses preset information to be in a YAML-friendly format. :param preset: a dictionary of tabs information :return: a list containing the same information, ready for export to an overview YAML file """ states = merge_states(preset['states']) return [ forma...
The function `compile_overview` generates a single YAML file for an EVE overview by merging input data (`ov`) with external YAML files. It processes keys like "tabs" and "presets," handling pluralization, loading files, and formatting presets. Errors like missing files are raised. The merged data, including formatted p...
def compile_overview(path, ov): """Combines all given information to produce a single YAML file formatted to be imported as an EVE overview. :param path: the destination path for the new overview file (will over-write existing files) :param ov: dictionary of overview information """ merged_overview...
def GetCoverageArtifacts(repo, run_id): # Fetch all artifacts from this run ID. api_path = "actions/runs/%s/artifacts" % run_id results = GitHubApi(repo, api_path)["artifacts"] # Get the one that is named "coverage" (should be the only one). artifact = list(filter(lambda x: x["name"] == "coverage", results))[...
The code computes incremental code coverage for a GitHub PR by parsing arguments, fetching coverage artifacts from a workflow run, extracting PR details, and calculating coverage changes. It outputs the PR number and coverage percentage or a message if no instrumented code was modified.
def main(): parser = argparse.ArgumentParser( description="Compute incremental code coverage for a PR", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( "--repo", required=True, help="The GitHub repo, such as shaka-project/shaka-player") parser.add_argumen...
def get_appspot_versions(): output = subprocess.check_output([ 'gcloud', '--project=shaka-player-demo', 'app', 'versions', 'list', '--format=json', ], text=True) return list(map(lambda v: v['id'], json.loads(output))) def get_release_tags(): output = subprocess.check_output(['git', 'tag'], text=...
The main task of the code is to generate an HTML index file listing software versions with metadata, prioritizing latest and nightly builds. It retrieves deployed versions, sorts release tags, extracts metadata, marks latest versions per branch, adds a "nightly" entry, and renders the data using Jinja2 templates into a...
def generate(): # Get all deployed appspot versions. This global list is used in various # methods above as we process the metadata. global DEPLOYED_APPSPOT_VERSIONS DEPLOYED_APPSPOT_VERSIONS = get_appspot_versions() # Get all release tags. versions = get_release_tags() # Now sort, putting prerelease ve...
def place_random_val(self, cells: Cells) -> Cells: used_xys = self.get_used_xys(cells) dim = len(cells[0]) xy = self.get_rand_xy(dim, excludes=used_xys) if xy == (-1,-1): return cells set_val = lambda x, y: self.get_next_rand_val() if (x,y) == xy else cells[y][x] ...
This function performs a game move in a specified direction by applying a movement function `f` to the game cells, updates the score if valid, places a new random tile if the move was valid, and returns a new game state with updated cells, score, and status checks for achieving 2048 or available moves.
def move(self, state: State, dir: Dir, f) -> State: new_cells, score, valid = f(state.cells, dir) new_cells = self.place_random_val(new_cells) if valid else new_cells new_score = score + state.score return State(new_cells, new_score, has_2048=self.has_2048(new_cells), has_moves=self.has_...
def df_to_json_history(self): df = self.fetch_data_history() if(df.empty == False): df['data'] = df['data'].astype(str) datas = df.to_json(orient='records') json_data = json.loads(datas) with open(self.file_path_history, 'w') as f: ...
The function loads data from Firebase into BigQuery by converting it to JSON, uploading it to GCS, and then loading it into a partitioned BigQuery table. It deletes the local JSON file and Firebase history data post-load. If no data is found, it returns a 'No data!!' message.
def load_data_to_bq_history(self): """ loads or initalizes the job in BQ from firebase child :param df1: dataframe returned from the get_childs_from_db method :return: load job success notification """ # Extract and Transform from Local if(self.df_to_json_history...
def find_part(coords): for part in part_list: if part.find_at(coords) is not None: return part_list.index(part) return None def try_split_part(part_id): main_part_id = part_id for cube in part_list[main_part_id].cubes: new_part(cube) part_list.pop(main_part_id) for p...
The code's main task is to delete a part identified by coordinates from a list, then attempt to split the remaining part. It first locates the part using `find_part`, deletes it via `delete`, and triggers a split operation with `try_split_part` to handle any remaining fragments or structural adjustments.
def delete(coords): part_id = find_part(coords) part_list[part_id].delete(coords) try_split_part(part_id)
def value2ROI(ROI_value: list): ROI = (slice(ROI_value[0][0], ROI_value[0][1]), slice(ROI_value[1][0], ROI_value[1][1])) return ROI def getPostProcessedData(self, snap_idx: int, module_idx: int = None, module...
This method generates plots of calibrated detector data, either for the entire detector (when module_idx is None) or a specific module. It uses ROI parameters, ADU conversion, and optional transpose/figure size settings to visualize data, leveraging helper functions for data retrieval and plotting.
def plot(self, snap_idx: int, module_idx: int = None, ROI_value: list = None, module_mask: ndarray = None, ADU: bool = True, transpose: bool = False, figsize=None, **kwargs): if ROI_value is None: ...
def get_logger(log_path): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.FileHandler(os.path.join(log_path, 'logs.log')) handler.setLevel(logging.INFO) logger.addHandler(handler) return logger def set_random_seed(): if FLAGS.random_seed_tf != 0: ...
This code initializes a TensorFlow model by setting up logging, configuring input data, building the neural network architecture, defining loss and accuracy metrics, configuring the optimizer, and preparing training operations. It also initializes variables, creates a model saver, and finalizes the computation graph fo...
def __init__(self): self.logger = get_logger(FLAGS.log_dir) now = datetime.datetime.now() self.logger.info('{} Model Created '.format(now.strftime("%Y-%m-%d %H:%M")).center(150, '*')) self.logger.info('CONFIG FLAGS:') self.logger.info(ALL_FLAGS) self.logger.info('') ...
def get_data(): root_dir = os.getcwd() data_dir = os.path.join(root_dir, 'cifar-10-batches-py') maybe_download_and_extract(root_dir, data_dir) train_data_files = [os.path.join(data_dir, 'data_batch_' + str(i)) for i in range(1, 6)] test_data_files = [os.path.join(data_dir, 'test_batch')] trai...
The function creates TFRecords files for training and testing datasets. It generates a 'tfrecords' directory if it doesn't exist, retrieves data, and writes multiple versions: full train/test sets, and smaller subsets (100/1000 samples) for overfitting and evaluation, using different seeds for reproducibility.
def maybe_create_tfrecords_train_test(): root_dir = os.getcwd() tfrecords_dir = os.path.join(root_dir, 'tfrecords') if not os.path.exists(tfrecords_dir): os.makedirs(tfrecords_dir) train_images, train_labels, test_images, test_labels = get_data() create_tfrecords(tfrecords_dir, tra...
def initialize(dim): w = np.zeros((dim,1)) b = 0 assert (w.shape == (dim,1)) assert (isinstance(b, float) or isinstance(b,int)) return w,b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations): ...
The code defines a machine learning model training function that initializes parameters, optimizes them using gradient descent on training data, and evaluates performance on both training and test datasets. It calculates prediction accuracy, stores costs, parameters, and results in a dictionary, then returns these valu...
def model (X_train, Y_train, X_test, Y_test, num_iterations = 1000, learning_rate = 0.5, print_cost = False): w, b = initialize(X_train.shape[0]) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) w = parameters["w"] b = parameters["b"] ...
def get_intent(self): return self.load_file("Dataset.csv")["Intent"] def get_unique_intent(self): return list(set(self.get_intent())) def get_sentences(self): return list(self.load_file("Dataset.csv")["Sentence"])
The main task of the code is to load a dataset by returning three components: the intent, unique intents, and sentences. The `load_dataset` method retrieves these elements using internal methods (`get_intent`, `get_unique_intent`, `get_sentences`) and returns them as a tuple, likely for training or processing a dataset...
def load_dataset(self, filename): return (self.get_intent(), self.get_unique_intent(), self.get_sentences())
def encoding_doc(self, token, words): return(token.texts_to_sequences(words)) def get_output_tokenizer(self): return self.create_tokenizer(self.get_unique_intent(), filters='!"#$%&()*+,-/:;<=>?@[\]^`{|}~') def get_intent(self): return self.load_file("Dataset.csv")["Intent"]
This method encodes text data using a tokenizer and intent, converts the result to a NumPy array, reshapes it into a 2D column vector, and returns it for machine learning model compatibility.
def get_encoded_output(self): encoded_output = self.encoding_doc( self.get_output_tokenizer(), self.get_intent()) encoded_output = np.array(encoded_output).reshape( len(encoded_output), 1) return encoded_output
def encoding_doc(self, token, words): return(token.texts_to_sequences(words)) def get_word_tokenizer(self): return self.create_tokenizer(self.get_cleaned_words(), '!"#$%&()*+,-./:;<=>?@[]\\^_`{|}~') def get_cleaned_words(self): return self.cleaning(self.get_sentences())
The main task of the code is to generate an encoded document by applying the `encoding_doc` method to tokenized words and cleaned text. It utilizes `get_word_tokenizer` for tokenization and `get_cleaned_words` for preprocessing, then returns the encoded result, likely for downstream tasks like model input preparation o...
def get_encoded_doc(self): return self.encoding_doc(self.get_word_tokenizer(), self.get_cleaned_words())
def dice_metric(y_pred, y_true, sigmoid=True, mean=False, eps=1e-6): ### Not loss !!!!! Is Metric !!!!! ''' y_pred, y_true -> [N, C=1, H, W] perform argmax and convert the predicted segmentation map into on hot format, then calculate the dice metric compare with true label ''' if sigmoid: ...
The code trains a selection model (`sel_model`) using a pre-trained segmentation model (`seg_model`) as a reference. It computes the MMD (Maximum Mean Discrepancy) loss between the selection model's outputs and the segmentation model's performance (measured via Dice metric) on each data sample. The goal is to align the...
def train_sel_net_baseon_seg_net(sel_model, seg_model, sel_loader, sel_optimizer, device='cpu'): # remember the loader should drop the last batch to prevent differenct sequence number in the last batch sel_model.train() seg_model.eval() sel_model.to(device) seg_model.to(device) step = 0. los...
def dice_metric(y_pred, y_true, sigmoid=True, mean=False, eps=1e-6): ### Not loss !!!!! Is Metric !!!!! ''' y_pred, y_true -> [N, C=1, H, W] perform argmax and convert the predicted segmentation map into on hot format, then calculate the dice metric compare with true label ''' if sigmoid: ...
The function evaluates a selection model (`sel_model`) using a segmentation model (`seg_model`) on a holdout dataset. It calculates the MMD (Maximum Mean Discrepancy) loss between the selection model's scores and the segmentation model's performance (via dice metric). The goal is to assess how well the selection model ...
def eval_sel_net_baseon_seg_net(sel_model, seg_model, holdout_loader, device='cpu'): # remember the loader should drop the last batch to prevent differenct sequence number in the last batch sel_model.eval() seg_model.eval() sel_model.to(device) seg_model.to(device) step = 0. loss_a = 0. ...
def sendATComm(self, command, desired_response, timeout=None): if timeout is None: timeout = self.timeout self.sendATCommOnce(command) f_debug = False timer = millis() while 1: if(millis() - timer > timeout): self.sendATCommOnce(command) ...
The main task of the code is to send HTTP POST requests to a specified server endpoint using AT commands. It configures HTTP settings, constructs a URL and request payload with headers (including authentication token), and executes the POST request with data. The function handles AT command setup, payload formatting, a...
def sendDataSixfabConnect(self, server, token, data): self.compose = "AT+QHTTPCFG=\"contextid\",1" self.sendATComm(self.compose, "OK") self.clear_compose() self.compose = "AT+QHTTPCFG=\"requestheader\",1" self.sendATComm(self.compose, "OK") self.clear_compose() ur...
def sendATComm(self, command, desired_response, timeout=None): if timeout is None: timeout = self.timeout self.sendATCommOnce(command) f_debug = False timer = millis() while 1: if(millis() - timer > timeout): self.sendATCommOnce(command) ...
This code sends a POST request to IFTTT's API endpoint to trigger an event using AT commands. It configures HTTP settings, constructs the request URL with event name and API key, sends the HTTP POST with JSON payload, and handles modem communication for data transmission.
def sendDataIFTTT(self, eventName, key, data): self.compose = "AT+QHTTPCFG=\"contextid\",1" self.sendATComm(self.compose, "OK") self.clear_compose() self.compose = "AT+QHTTPCFG=\"requestheader\",1" self.sendATComm(self.compose, "OK") self.clear_compose() self.comp...
def sendATComm(self, command, desired_response, timeout=None): if timeout is None: timeout = self.timeout self.sendATCommOnce(command) f_debug = False timer = millis() while 1: if(millis() - timer > timeout): self.sendATCommOnce(command) ...
This function sends data to the Thingspeak API via HTTP GET using AT commands on a modem. It configures HTTP settings, constructs a URL with the provided API key and data, initiates a connection, transmits the request, waits for a response, and retrieves the HTTP GET result. The process involves setting timeouts, clear...
def sendDataThingspeak(self, key, data): self.compose = "AT+QHTTPCFG=\"contextid\",1" self.sendATComm(self.compose, "OK") self.clear_compose() self.compose = "AT+QHTTPCFG=\"requestheader\",0" self.sendATComm(self.compose, "OK") self.clear_compose() url = str("http...
def saveConfigurations(self): self.sendATComm("AT&W", "OK\r\n") def delay(ms): time.sleep(float(ms/1000.0)) def disable(self): GPIO.output(self.BG96_ENABLE, 0) debug_print("BG96 module disabled!") def enable(self): GPIO.output(self.BG96_ENABLE, 1) debug_print("Telit module en...
The main task of the code is to reset a module by first saving its current configurations, introducing a 200ms delay, disabling the module, waiting another 200ms, and then re-enabling it. This sequence ensures controlled state transitions during the reset process.
def resetModule(self): self.saveConfigurations() delay(200) self.disable() delay(200) self.enable()
def debug_print(message): print(message) def sendATComm(self, command, desired_response, timeout=None): if timeout is None: timeout = self.timeout self.sendATCommOnce(command) f_debug = False timer = millis() while 1: if(millis() - timer > timeout): ...
The code's main task is to attempt connecting to an operator's base station by sending an AT command (`AT+CGATT?`) to check the attachment status, expecting a response indicating successful attachment (`+CGATT: 1`), followed by retrieving signal quality data to assess the connection's strength and reliability.
def connectToOperator(self): debug_print("Trying to connect base station of operator...") self.sendATComm("AT+CGATT?", "+CGATT: 1\r\n") self.getSignalQuality()
def update(self, row, col, num): if type(self.board[row][col]) != int and num in self.board[row][col]: self.board[row][col] = num self.nums_placed += 1 changed = [] for c in range(len(self.get_row(row))): if type(self.board[row][c]) != int and num in self.board[row][c]: self.board[row][c].rem...
This code generates a valid Sudoku puzzle by initializing a 3D board, placing numbers randomly while ensuring each placement allows a unique solution through recursive solving, then removing numbers (guesses) only if the puzzle remains uniquely solvable.
def set_start_squares(self): self.board = [[[num + 1 for num in range(self.SIZE)] for _ in range(self.SIZE)] for _ in range(self.SIZE)] self.nums_placed = 0 free_squares = [(r, c) for r in range(len(self.board)) for c in range(len(self.board[r]))] random.shuffle(free_squares) for (r, c) in free_squares: ...
def check_horizontal_matches(self): for row in range(self.rows): self.check_row(row) def check_vertical_matches(self): for col in range(self.cols): self.check_column(col) def remove_marked(self): for row in range(len(self.grid)): for col in range(len(self.grid...
This method checks for horizontal and vertical matches in a game grid, removes marked balls, applies gravity to fill gaps, calculates the score based on removed balls, and recursively handles chain reactions by rechecking matches if balls were removed. It returns the total score including any subsequent matches from th...
def check_matches(self): score = 0 self.check_horizontal_matches() self.check_vertical_matches() self.remove_marked() self.gravitation() score += self.balls_removed if self.balls_removed > 0: self.balls_removed = 0 score += 2 * self.check_m...
def __clear(self): """ Clear error info """ self.__errcode__ = 0 self.__err__ = '' def __get_path_suffix(self, type, number): """ Get path suffix :param type: search number type as Number.xxx value :type type: Number :param number: search ...
The main task of the code is to retrieve and parse VIES (European Union's VAT Information Exchange System) data for a given EU VAT number. It validates the input, constructs a URL, sends an HTTP request, and extracts structured information (e.g., validity, trader details, country code) from the XML response into a `VIE...
def get_vies_data(self, euvat): """ Get VIES data for specified number :param euvat: EU VAT number with 2-letter country prefix :type euvat: str :return: VIESData object or False :rtype: VIESData or False """ # clear error self.__clear() ...
def __clear(self): """ Clear error info """ self.__errcode__ = 0 self.__err__ = '' def __get(self, url): """ Get result of HTTP GET request :param url: target URL :type url: str :returns: result as XML document :rtype: ElementTree ...
The main task of the code is to retrieve and parse a user's account status from an API endpoint by sending a GET request, extracting structured data (e.g., user ID, validity, billing plan details, feature access), converting values to appropriate types (int, float, bool), and returning an AccountStatus object. If the r...
def get_account_status(self): """ Get user account's status :return: AccountStatus object or False :rtype: AccountStatus or False """ # clear error self.__clear() # prepare url url = self.__url__ + '/check/account/status' # send request ...
def extract_topo_no(str1): toposheet_numbers = [] toposheet_pattern = r'\b\d+[a-zA-Z]+\d+\b' toposheet_numbers = re.findall(toposheet_pattern,str1) return toposheet_numbers def extract_elements(query): # Initialize an empty list to store the extracted elements elements = [] # Convert the se...
The code processes a query for spatial data analysis by replacing specific phrases, extracting toposheet numbers and elements, and validating inputs. It generates maps (kriging/IDW) or identifies extreme values (max/min) based on keywords, ensuring single-element/toposheet requests and handling errors for invalid input...
def process_subqueries(query, threshold_percentile): query = re.sub(r'\b(?:can|could|will|would|shall|should|may|might|must|to)\s+be\b', 'exists', query, flags=re.IGNORECASE) query = re.sub(r'\binverse\s+distance\s+weighted\b', 'idw', query, flags=re.IGNORECASE) # replace inverse distance weighted to idw wo...
def setup(x, y, w, is_cat = False): assert len(x) == len(y) if w is None: w = np.ones(len(x)) data = pd.DataFrame.from_dict({"W": w, "X": x, "Y": y}) if is_cat: data = data.groupby("X").sum().reset_index() data = data.sort_values("Y") else: data = data.sort_values("X"...
This function performs numerical feature engineering by iteratively splitting and merging intervals of a variable based on population thresholds, ensuring optimal binning for modeling. It splits ranges when population exceeds a ratio threshold, merges adjacent bins if they meet population and monotonicity criteria, and...
def num_feat_eng_single(x, y, w = None, min_pop = 10000, max_split = np.inf, split_pop_ratio = 10, merge_pct_factor = 1.2, check_mono = True): data = setup(x, y, w) lst = [(0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1)] # Gather Info info_lst = [] for elem in lst: pop, y_pct = get_info(...
def setup(x, y, w, is_cat = False): assert len(x) == len(y) if w is None: w = np.ones(len(x)) data = pd.DataFrame.from_dict({"W": w, "X": x, "Y": y}) if is_cat: data = data.groupby("X").sum().reset_index() data = data.sort_values("Y") else: data = data.sort_values("X"...
This function performs categorical feature engineering by processing input features (x) and target (y) to identify and merge categories based on population thresholds, split ratios, and monotonicity checks. It gathers category statistics, checks for merges, and returns processed feature lists along with their metadata ...
def cat_feat_eng_single(x, y, w = None, min_pop = 10000, max_split = np.inf, split_pop_ratio = 10, merge_pct_factor = 1.2, check_mono = True): data = setup(x, y, w, is_cat = True) lst = [[x] for x in list(data["X"])] # Gather Info info_lst = [] for elem in lst: ...
def num_feat_eng_single(x, y, w = None, min_pop = 10000, max_split = np.inf, split_pop_ratio = 10, merge_pct_factor = 1.2, check_mono = True): data = setup(x, y, w) lst = [(0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1)] # Gather Info info_lst = [] for elem in lst: pop, y_pct = get_info(...
This function performs iterative feature engineering on numerical or categorical data by adjusting a merge percentage factor (pct_factor) to find optimal splits. It repeatedly applies either numerical or categorical feature engineering (depending on `is_cat`), checks the number of resulting splits, and adjusts `pct_fac...
def feat_eng_single_tuning(x, y, w = None, is_cat = False, min_pop = 10000, max_split = np.inf, split_pop_ratio = 10, merge_pct_factor = 1.2, max_retry = 5, step_size = 0.05, check_mono = True): assert step_size > 0 pct_factor = merge_pct_factor proceed = True retry = 0 ret = None ret_pct =...
def profile(): if _doProfile == True: pr = cProfile.Profile() pr.enable() return pr def stat(pr): if _doProfile == True: pr.disable() ps = pstats.Stats(pr) ps.strip_dirs() ps.sort_stats("time") ps.print_stats() def test_amap(data, U, umix_source, p...
This function tests the PPI (Pixel Purity Index) algorithm for endmember extraction in hyperspectral data. It initializes the PPI object, extracts endmembers from input data (with optional masking), prints diagnostic information, generates abundance maps using three methods (UCLS, NNLS, FCLS), and saves visualizations....
def test_PPI(data, wvl, path, mask=None): print("Testing PPI") ppi = eea.PPI() pr = profile() if mask is None: U = ppi.extract(data, 4, normalize=True) else: U = ppi.extract(data, 4, normalize=True, mask=mask) print(str(ppi)) stat(pr) print(" End members indexes:", ppi....
def profile(): if _doProfile == True: pr = cProfile.Profile() pr.enable() return pr def stat(pr): if _doProfile == True: pr.disable() ps = pstats.Stats(pr) ps.strip_dirs() ps.sort_stats("time") ps.print_stats() def test_amap(data, U, umix_source, p...
The main task of the code is to test the ATGP algorithm by extracting end members from hyperspectral data, optionally using a mask, then visualizing the results through plots and generating a map. It initializes the ATGP model, processes the data, retrieves end member indices, and saves visualizations to specified path...
def test_ATGP(data, wvl, path, mask=None): print("Testing ATGP") atgp = eea.ATGP() pr = profile() if mask is None: U = atgp.extract(data, 8, normalize=True) else: U = atgp.extract(data, 8, normalize=True, mask=mask) stat(pr) print(str(atgp)) print(" End members indexes:"...
def profile(): if _doProfile == True: pr = cProfile.Profile() pr.enable() return pr def stat(pr): if _doProfile == True: pr.disable() ps = pstats.Stats(pr) ps.strip_dirs() ps.sort_stats("time") ps.print_stats() def test_amap(data, U, umix_source, p...
The main task of the code is to test the FIPPI (Fast Image Processing and Pixel Purity Index) algorithm by extracting endmembers from hyperspectral data, optionally using a mask, and visualizing results. It initializes the FIPPI model, processes input data, retrieves endmember indices, generates plots, and evaluates pe...
def test_FIPPI(data, wvl, path, mask=None): print("Testing FIPPI") fippi = eea.FIPPI() pr = profile() if mask is None: U = fippi.extract(data, 4, 1, normalize=True) else: U = fippi.extract(data, 4, 1, normalize=True, mask=mask) print(str(fippi)) stat(pr) print(" End mem...
def profile(): if _doProfile == True: pr = cProfile.Profile() pr.enable() return pr def stat(pr): if _doProfile == True: pr.disable() ps = pstats.Stats(pr) ps.strip_dirs() ps.sort_stats("time") ps.print_stats() def test_amap(data, U, umix_source, p...
The code tests the NFINDR algorithm for endmember extraction from hyperspectral data, using a mask if provided. It extracts 8 endmembers, prints statistics, iterations, and endmember indices, plots results, and generates abundance maps via UCLS, NNLS, and FCLS methods for validation.
def test_NFINDR(data, wvl, path, mask=None): print("Testing NFINDR") nfindr = eea.NFINDR() pr = profile() if mask is None: U = nfindr.extract(data, 8, maxit=5, normalize=False, ATGP_init=False) else: U = nfindr.extract( data, 8, maxit=5, normalize=False, ATGP_init=False, ...
def display_info(self): displayed_message = "" # 1 - Valid request ? valid=True try: request_result = self.send_request() except ovh.exceptions.ResourceNotFoundError as e: valid=False displayed_message += "\t1)\t%s %s %s a valid request" \ ...
The code handles OVH API requests by displaying requested information if specified, sending the request, catching exceptions like invalid URLs or bad parameters, and printing results if enabled. It ensures error handling and user-specific output control.
def request(self, display=True): # If the user asked for information, only display that information if (self._ovh_request.showInfo): self.display_info() exit(0) # Handle specific treatment and generic exceptions (eg invalid URL) try: response = self.s...
def _take_action(self, action): # Make changes to our environment room, action_id = action state_variable, value = self.action_ids[action_id] prev_value = self.current_state[room][state_variable] if state_variable == "pos": self.current_state[room]["pos"] = self._cli...
The code executes one time step in the environment by processing the given action, updating the state, calculating the reward, determining if the episode is done, and returning the next observation, reward, done status, and additional info.
def step(self, action): # Execute one time step within the environment self._take_action(action) self.current_step += 1 reward = self._compute_reward() done = self.current_step >= self.steps_per_episode info = self._get_info() obs = self._get_obs() return...
def create_xml_file(xml_path): print("=== Starting PKP Alumni Data Parsing ===") # Parse the foundation data and set some global dictionaries for lookups foundation_xml = parse_foundation() set_dicts(foundation_xml) perform_corrections(foundation_xml) set_dicts(foundation_xml) # Add all su...
The main task of the code is to generate an XML file at the specified path (`new_output/assimilated_foundation.xml`) by calling the `create_xml_file` function, as the `do_parse` flag is set to `True`. Other conditional tasks (dumping address data or retrieving statistics) are inactive due to their corresponding flags b...
def main(): xml_path = os.path.join("new_output", "assimilated_foundation.xml") do_parse = True dump_addr_data = False get_stats_dat = False # tree = ET.parse(xml_path) # root = tree.getroot() # add_mailchimp_data(root) # return # (a) If parsing if do_parse: create_xm...
def parse_baseline(): global gbl_headers ## Extract unique list of headers between all three files # region headers = [] add_to_header(headers, mn_beta_all_time) add_to_header(headers, mn_beta_alumni) add_to_header(headers, mn_gam_delt_alumni) add_to_header(headers, twin_cities_alumni) ...
The main task of the code is to parse alumni data from two sources—baseline and Pennington—then export the results to CSV files. It first prints a start message, parses baseline data, dumps alumni info to "new_dumper.csv", parses Pennington data, and exports a second CSV ("new_dumper_penn.csv") including Pennington-spe...
def main(): print("==== Starting Alumni Parse ==== ") print("\n = Parsing Baseline =") parse_baseline() dump_alumni_to_csv(r"new_dumper.csv") print("\n = Parsing Pennington Data =") parse_pennington_data() # for h in gbl_headers: # print(h) dump_alumni_to_csv(r"new_dumper_pe...
def check_username(username): user=R6Final.objects.filter(username=username) if len(user)==0: return 0 return 1 def update_user(username,val): user=R6Final.objects.get(username=username) if val==False: user.count_no_smurf+=1 else: user.count_smurf+=1 if user...
This Django view handles form submissions for adding/updating user data. On POST, it validates input, checks if the username exists, and either updates existing data or adds new users. It redirects to the homepage with status messages. On GET, it renders the form page for user input.
def Rainbow_handler(request): if request.method == 'POST': form = rainbow_6form(data=request.POST) if form.is_valid(): username=form.cleaned_data['username'] val=form.cleaned_data['smurf'] if(check_username(username)==1): up...
def r6predictor(username): user=R6Final.objects.filter(username=username) # if len(user)==1: # return (user.count_smurf*100/(user.count_no_smurf+user.count_smurf)) data=extract_data(username) if data==0: return -1 data=convert_type(data) temp=norm(data) columns=['leve...
The code processes POST/GET requests to handle a prediction form. It validates input, checks the selected website (R6/Cf), and uses corresponding predictors to generate scores/predictions. Valid inputs trigger data retrieval, error handling, and rendering of results with visualizations in templates. GET requests displa...
def selector(request): if request.method=='POST': form = predictform(data=request.POST) if form.is_valid(): website=form.cleaned_data['website'] username=form.cleaned_data['username'] form = predictform() if website!='R6' and ...
def _sendCmd(self, cmd_request, response_size=6, delay_ms=100): """ Send a command to the sensor and read (optionally) the response The response data is validated by CRC """ try: # print("sendCmd: cmd = ",hex(cmd_request[0]),hex(cmd_request[1])) self.i2c.w...
This function retrieves temperature and humidity measurements from a sensor, returning raw byte data or processed values in Celsius and percent. It configures measurement settings via parameters like clock stretching and repeatability, calculates CRC for commands, sends them, and processes responses. If 'raw' is True, ...
def getTempAndHumi(self, clockStretching=None, repeatability=None, raw=False, timeout=100): """ If raw==True returns a bytearray(6) with sensor direct measurement otherwise It gets the temperature (T) and humidity (RH) measurement and returns them. The units are Celsius and perc...
def _sendCmd(self, cmd_request, response_size=6, delay_ms=100): """ Send a command to the sensor and read (optionally) the response The response data is validated by CRC """ try: # print("sendCmd: cmd = ",hex(cmd_request[0]),hex(cmd_request[1])) self.i2c.w...
The function `readAlert` constructs a command to read sensor alerts based on parameters `high` and `set`, computes a CRC checksum, sends the command, and returns raw sensor data or processed temperature/humidity values. It modifies a command byte, calculates a CRC, sends the command via `_sendCmd`, extracts temperature...
def readAlert(self,high=True,set=True,raw=False): readAlertCmd = bytearray(self.CMD_ALERT_READ) if high: if set: readAlertCmd[1] |= 0x018 else: readAlertCmd[1] |= 0x010 else: if not set: readAlertCmd[1] |= 0x08 ...
def stopPeriodicMeas(self): self._sendCmd(self.CMD_BREAK, None,delay_ms=2); return def startPeriodicMeas(self, mps=0.5, repeatability=None): measCmd = bytearray(self.CMD_MEAS_PERIODIC) if not repeatability: repeatability = self.REP_P_HIGH # print("base meas cmd: ",...
The function performs periodic temperature and humidity measurements using an I2C sensor. It initializes measurements, fetches data at specified intervals, validates CRC checksums, processes raw sensor data, and optionally invokes a callback with converted values or raw bytes. Results are collected in a list and return...
def measPeriodic(self,mps=0.5, repeatability=None, raw=False, noOfMeas=50,callback=None): self.stopPeriodicMeas() delay = 1/mps print("Interval: ",delay) self.startPeriodicMeas(mps, repeatability) result=[] for i in range(noOfMeas): try: time.s...
def click_element_by_id_and_wait(driver, element_id): element = WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.ID, element_id)) ) element.click() time.sleep(1) def model(sql_statement, status, data): server = "" database = "" username = "" password = "" r...
The main task of the code is to automate data extraction from a web application by iterating through states, RTOs, years, and months. It interacts with a browser driver to select and refresh data, queries a database to identify missing entries, and navigates paginated results to collect required information, ensuring a...
def run_primary_loop(driver): for STATE in STATE_DATA: click_element_by_id_and_wait(driver, STATE_LABEL) click_element_by_id_and_wait(driver, STATE[0]) time.sleep(1) click_element_by_id_and_wait(driver, REFRESH_BTN_LABEL) time.sleep(1) GET_OLD_RTOS = model( ...
def receive_command(self): buffer = '' while True: if self.comport.inWaiting(): rx_char = str(self.comport.read(), 'utf-8', errors='ignore') buffer += rx_char else: break buffer.strip('\r\n') print('Rx: {}'.format(b...
The code defines a reception loop that continuously monitors a serial port for incoming commands. When data is detected, it retrieves the command and routes it through a main switch for processing. The loop also periodically checks system states like registration, idle status, PSM (Power-Saving Mode), and messages to m...
def reception_loop(self): while self.run: if self.comport.inWaiting(): command = self.receive_command() self.main_switch(command) self.check_registration() self.check_idle() self.check_psm() self.check_messages() ...
def init_maze(input_path): with open(input_path) as f: lines = f.readlines() maze = [[ll for ll in l.strip()] for l in lines] width = len(maze[0]) height = len(maze) for i in range(0, height): for j in range(0, width): if maze[i][j] == 'S': sta...
The code solves a maze problem using BFS. Part 1 calculates the shortest path length from a single start to the end. Part 2 finds the minimum path length among multiple starting points to the same end, returning both results in a structured format. Your return
def day12(input_path): maze, start, end = init_maze(input_path) path = bfs(start, end, maze) part1 = len(path) - 1 maze, starts, end = init_maze_part2(input_path) paths = [] for s in starts: paths.append(len(bfs(s, end, maze))-1) paths = [p for p in paths if not p == -1] pat...
def destroy_account_buttons(self): """ Destroys user account buttons in the scrollable frame. """ for widget in self.scrollable_frame.winfo_children(): widget.destroy() def show_details(self, account_index): """ Displays details for a selected user account. ...
(The function retrieves user account data from a database, destroys existing buttons, and dynamically generates new buttons for each account. Each button displays the account name, triggers a details view when clicked, and initializes entry widgets for user interaction. The buttons are positioned in a scrollable frame ...
def create_account_buttons(self): """ Retrieves data and creates account entry buttons. """ logger.debug("The value inside Storage is: %s", self.user_id) with DataBase() as db: account_names = db.storage_create_account_buttons(self.user_id) self.destroy_acc...
def import_data(): os.chdir('../../data/MachineLearning') with open('Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, test_features , train_labels, test_labels = split(data) train_features, train_labels = ...
The code trains a Gaussian Mixture Model (GMM) classifier on training data, predicts labels for test data, computes performance metrics (e.g., accuracy, confusion matrix, F1-score), and saves results. It measures classification time, evaluates prediction quality using metrics like FAR, DR, and hamming loss, then return...
def process(): train_features, train_labels, test_features,test_labels = import_data() #training the data t0 = time() clf = GaussianMixture(n_components=2, reg_covar=1) clf.fit(train_features) tt = time()-t0 print("Classified in {} seconds".format(round(tt,3))) label_prediction = clf.pre...
def import_training_data(): os.chdir('../../data/MachineLearning') with open('Monday-WorkingHours.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, train_labels = split_divide(data) convertAndClean(train_features,train_labels,'train') tr...
The code trains a semi-supervised Label Propagation model on training data, evaluates its performance on test data by predicting labels, calculates accuracy, detection rate, and false alarm rate, saves these metrics along with timing and dataset sizes, and returns test features and predictions. The main task is to perf...
def process(): train_features, train_labels = import_training_data() test_features,test_labels = import_testing_data() #training the data t0 = time() label_prop_model = LabelPropagation() label_prop_model.fit(train_features,train_labels) tt = time()-t0 print("Classified in {} seconds".fo...
def import_data(): os.chdir('../../data/MachineLearning') with open('Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv') as csvfile: data = pd.read_csv(csvfile, header= 0, sep=',') train_features, test_features , train_labels, test_labels = split(data) train_features, train_labels = ...
The code trains a LinearSVC classifier on training data, evaluates its performance on test data by calculating accuracy, detection rate, and false acceptance rate (FAR), prints the classification time and metrics, saves results, and returns test features and predictions.
def process(): train_features, train_labels, test_features,test_labels = import_data() #training the data t0 = time() clf = svm.LinearSVC() clf.fit(train_features,train_labels) tt = time()-t0 print("Classified in {} seconds".format(round(tt,3))) #testing the data label_prediction = ...
def _write_activation(activations, layer, path_outdir, path_logdir): is_success = True act_shape = activations.shape if len(act_shape) == 2: grid_activations = [np.expand_dims(image_normalization(convert_into_grid(im[:,np.newaxis,np.newaxis,np.newaxis], padding=0)), axis = 0) for im in activations]...
The function `write_results` determines the method (activation, deconvolution, or deepdream) to process neural network results, delegates the task to the corresponding helper function, and returns a boolean indicating success. It saves outputs to specified directories based on the method and layer, ensuring results are...
def write_results(results, layer, path_outdir, path_logdir, method): is_success = True if method == "act": is_success = _write_activation(results, layer, path_outdir, path_logdir) elif method == "deconv": is_success = _write_deconv(results, layer, path_outdir, path_logdir) elif method =...
def _save_model(graph_or_sess): """ Save the given TF session at PATH = "./model/tmp-model" :param sess: TF sess :type sess: tf.Session object :return: Path to saved session :rtype: String """ if isinstance(graph_or_sess, tf.Graph): ops = graph_or_sess.get_oper...
The function _get_visualization visualizes specified layers (e.g., ReLU, pooling) of a TensorFlow model by importing a session/graph, processing input tensors, and generating visual outputs. It handles various input formats (session, graph, path), applies custom gradients for methods like deconvolution, and saves resul...
def _get_visualization(sess_graph_path, value_feed_dict, input_tensor, layers, path_logdir, path_outdir, method = None): """ cnnvis main api function :param sess_graph_path: TF session (open) or <Path-to-saved-sessiion> as String or TF graph (either FROZEN - training variables set t...
def check_for_files(self) -> None: in_files = self.get_input_files_definitions(only_latest_files=True) if in_files: logging.warning("Files found instead of tables, if you want them processed, " "please first use the move files processor to move the files to tables...
The main task of the code is to validate configuration and image parameters, check for input files, move files to output, and process tables. It identifies tables to anonymize using patterns, applies anonymization with a salt value if matched, or moves non-anonymized tables to output. It ensures proper handling of conf...
def run(self) -> None: self.validate_configuration_parameters(REQUIRED_PARAMETERS) self.validate_image_parameters(REQUIRED_IMAGE_PARS) params = self.configuration.parameters salt = params.get(KEY_SALT, "") salt_location = params.get(KEY_SALT_LOCATION, DEFAULT_SALT_LOCATION) ...
def setup_gee(self): # self.gee.ee.Authenticate() self.gee.ee_initialize() def load_bases(self): # load csv data with places of interest self.bases = pd.read_csv("poi/poi_df.csv") def init_imagery(self): self.imagery = Imagery() self.imagery.get_collection() def init_gui(self): # load custom...
The code's main task is to initialize and configure a geospatial application by setting up Google Earth Engine (GEE), loading foundational data, initializing imagery processing, and creating a graphical user interface (GUI). This prepares the system for geospatial analysis and visualization tasks, ensuring all necessar...
def run(self): self.setup_gee() self.load_bases() self.init_imagery() self.init_gui()
def get_input_data(): data = [] with open(DATA_PATH) as f: lines = f.read().splitlines() for line in lines: data.append(list(line)) return data def get_part_two(grid): start_coord = get_coord(grid, 'S') grid[start_coord[0]][start_coord[1]] = 'a' a_coords = get_coords(grid, 'a') ...
The code processes a grid to compute minimum distances using `get_part_two`, then calculates the distance to the end point using `get_distance_to_end`, printing both results. The main task involves analyzing a grid structure to determine optimal paths or distances, likely for a pathfinding or maze-solving algorithm, by...
def main(): grid = get_input_data() # min_distances = get_min_distances(grid) # print(min_distances) # distance_to_end = get_distance_to_end(grid, min_distances) # print(distance_to_end) min_distances = get_part_two(grid) print(min_distances) distance_to_end = get_distance_to_end(grid, min_dis...
def get_grid(): grid = [] with open(DATA_PATH) as f: lines = f.read().splitlines() for line in lines: grid.append(list(map(int, line))) return grid def get_visibility_grid(grid): is_visible = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))] for i in range(len(grid)):...
The code's main task is to analyze a grid of trees by first determining which trees are visible from the edges (counting visible trees) and then calculating the best viewing distance for a scenic view within the grid. It retrieves the grid, computes visibility, counts visible trees, and identifies the optimal viewing p...
def main(): grid = get_grid() is_visible_grid = get_visibility_grid(grid) visibility_count = count_visible_trees(is_visible_grid) print(visibility_count) best_viewing_distance = get_best_viewing_distance(grid) print(best_viewing_distance)
def get_input_data(): data = {} with open(DATA_PATH) as f: lines = f.read().splitlines() for line in lines: s = re.split(' |=|;|,|:', line) sensor = tuple(map(int, [s[6], s[3]])) beacon = tuple(map(int, [s[16], s[13]])) data[sensor] = beacon return data def get_s...
The main task of the code is to process input data by mapping sensors to their ranges, identify frontier points from these ranges, and compute a solution based on the frontier points and sensor ranges. The code retrieves input data, generates a sensor-to-range mapping, calculates frontier points, and determines a solut...
def main(): data = get_input_data() sensor_to_range = get_sensor_to_range(data) print(sensor_to_range) all_frontier_points = get_all_frontier_points(sensor_to_range) print(len(all_frontier_points)) soln = get_soln(all_frontier_points, sensor_to_range) print("SOLN", soln)
def print_help_screen(): table = Table(title="List of commands", expand=True, title_style=TITLE, header_style=HEADER, border_style=TABLE, title_justify="center", caption_justify="center", show_lines=True, min_width=120) table.add_column("Command", justify="right", style=INFO, no_wrap=True, w...
This code implements a bot-assistant for managing a contact book via command-line interface. It allows users to view all contacts, add new entries, search by name/phrase, check birthdays within a specified number of days, filter by notes/tags, and exit. The bot provides interactive guidance, validates inputs, and displ...
def bot_contact_book(): console.print("") console.print(Panel(title=f"Welcome to Contact-book", renderable= f"I am your Bot-Assistant.\nLet me know how can I help you?"), style = INFO, justify = "center") console.print("made by: *****", style=HEADER, justify="right") console.rule(style = RULER) whi...
def is_valid_card(card_index): return 0 <= card_index < len(cards) def is_card_hidden(card_index): global card_states return card_states[card_index] == "" def flip_card(player_id, card_index): global turned_cards card_states[card_index] = cards[card_index] broadcast(f"UPDATE {player_id} {card_i...
The function processes a player's "TURN" action by validating and flipping a specified card. If valid and hidden, it increments the player's flipped card count. When two cards are flipped, it triggers a check for matches, resets the counter, and handles errors during card flipping.
def process_player_action(data, player_id): global turned_cards, player_turn, turned_cards_player action = data.strip().upper() parts = data.strip().split() print("Action", action) if parts[0] == "TURN": try: card_index = int(parts[1]) print("Card Valid Card", is_va...
def perms_are_conjugate(perm1, perm2): return (get_cycle_lengths(perm1) == get_cycle_lengths(perm2)) def multiply_permutations(perm_1, perm_2): result = [] assert(len(perm_1) == len(perm_2)) for value in perm_2: result.append(perm_1[value]) return tuple(result) def perm_inverse(perm): i...
The main task of the code is to identify all permutation conjugators from a candidate list that transform perm1 into perm2 via conjugation. It checks if perms_are_conjugate first, then verifies each candidate by applying the conjugation formula: perm2 = conjugator_candidate * (perm1 * conjugator_candidate⁻¹), collectin...
def get_perm_conjugators(perm1, perm2, conjugator_candidates): conjugators = set() if perms_are_conjugate(perm1, perm2): for conjugator_candidate in conjugator_candidates: if perm2 == multiply_permutations(conjugator_candidate, multiply_permutations(perm1, perm_inverse(conjugator_candidate))...
def _get_publish_path() : if(_check_debug_build()) : return os.path.join(_project_root_directory, "Publish/Debug", _get_framework_name() ) else : return os.path.join(_project_root_directory, "Publish/Release", _get_framework_name()) def _get_plugin_name(project_name) : if(project_nam...
This function copies specific plugin files from a source directory to a designated plugins folder within a target path. It iterates over predefined file extensions (.dll, .deps.json, .pdb, .xml), constructs source and destination paths, and copies each file if it exists. The task ensures plugin components are replicate...
def _copy_plugin_to_dest_plugins_path(project_name, target_path) : output_dir = _get_publish_path() output_plugins = os.path.join(target_path, "plugins", _get_plugin_name(project_name)) exts = [".dll", ".deps.json", ".pdb", ".xml"] for ext in exts : source_path = os.path.join(_target_dir, proje...
def load(self): if self.name == "none": self.hasMask = False return mask_file_origin = self.name + "/" + self.name if self.modify_xml != None: mask_file_origin = self.modify_xml.getAttribute("mask") mask_file_origin = mask_file_origin + "/" + mask_...
This code generates a composite image from an input file based on XML node attributes, applying transformations, colorization, and blending (composite/mix) with masks. It processes images at multiple resolutions, handles input/output paths, and saves results while respecting parameters like blur, transform, and mix rat...
def generateComposite(self, xmlNode): if self.isDirty: self.load() input_file = xmlNode.getAttribute("input") output_file = xmlNode.getAttribute("output") blur = True if xmlNode.hasAttribute('blur'): blur = xmlNode.getAttribute("blur") == "true" co...
def play_games(agent, k_games): """ Play k_games using the agent to give probability distributions on each move. """ board = np.zeros((k_games, M), dtype=np.float32) moveid = torch.eye(M) for step in range(M): if step >= M-15: board[:, step] = np.ones(k_games) else: ...
The code iteratively generates new games, evaluates their scores, selects top-performing games, and trains a reinforcement learning model using these games. It maintains a collection of the best games, displays progress every 10 rounds, and appends games meeting specific score criteria to a list. The loop refines game ...
def run(): # Keep only the top so many games here. global top_games global collection for i in range(201): # Play some new games. new_games = play_games(model, K_GAMES) # Mix these games into our pot of the best games so far. games = np.concatenate([top_games, new_games]...
def play_games(self): """ Play games_per_epoch using the agent to give probability distributions on each move. """ games_per_epoch = self.games_per_epoch input_size = self.input_size output_size = self.output_size dim = self.dim board ...
The code implements a reinforcement learning algorithm to train a neural network by iteratively generating games, selecting top-performing game states based on scores, and updating the model parameters. It handles restarts, model resets, and learning rate scheduling, using top games to reinforce the network over multip...
def run(self, epochs=50, restart=False, reset_model=False, use_scheduler=True): dim = self.dim n_vertices = self.n_vertices input_size = self.input_size output_size = self.output_size games_per_epoch = self.games_per_epoch if restart: ...
def split_the_data(features, labels, test_to_rest_ratio, validation_to_test_ratio, random_state): '''Splits data into train:validation:test subsets. Args: features: features subset of data as list labels: labels subset of data as list test_to_rest_ratio: the proportion of the data to b...
The function evaluates multiple regression models (Baseline, Decision Tree, Random Forest, XGBoost) across predefined iterations using randomized data splits. It collects model parameters and performance metrics, aggregates results, identifies common optimal parameters via mode, and saves the best-performing models wit...
def evaluate_models_multiple_times(num_iter, seed): """ Iterates through the modelling process a predermined number of times based on a pseudorandom seed Args: num_iter: number of iterations seed: the pseudorandom order of random states to iterate through in sequence """ BL_metrics_list...
def get_sudo(self): """ Get superuser privileges. """ if self.test_run: return print("I'm going to need superuser privileges for this...") subprocess.run( ["sudo", "echo", "Superuser privileges: activate!"], check=True ) def move_to_target_dir(...
The code's main task is to execute a software installer by performing essential setup steps, handling elevation privileges, moving files to a target directory, and executing non-essential components if not in minimal mode. It checks for success at each stage, prints progress/status messages, and returns a boolean outco...
def run(self): """ Run the software installer. """ print("Running His Majesty's Software Installer...") self.get_sudo() self.move_to_target_dir() if not self.run_essentials(): print("\nFinished.\n\n") self.print_outcome(False, False) return Fal...
def swsh(s, modes, theta, phi, psi=0): """ Return a value of a spin-weighted spherical harmonic of spin-weight s. If passed a list of several modes, then a numpy array is returned with SWSH values of each mode for the given point. For one mode: swsh(s,[(l,m)],theta,phi,psi=0) For se...
This function computes a weighted sum of spin-weighted spherical harmonics (swsh) evaluated at specified points, using weights derived from an HDF5 file (h5). It handles 2D (theta, phi) or 3D (theta, phi, psi) point inputs, applies eth-dependent scaling factors to weights, and returns the complex-valued result of the d...
def get_at_points_work(h5, times, points, s=-2, R=None, eth=0): if np.array(points).shape[1] == 2: swshes = np.array( [swsh(s + eth, get_modes(h5), theta, phi, 0) for (theta, phi) in points] ) elif np.array(points).shape[1] == 3: swshes = np.array( ...
def preproc_phrases(strings): global _grammar, _parse_memo if len(strings) < 2: return strings elif strings[0].strip() == "": return preproc_phrases(strings[1:]) else: ind_tree = parse(strings[0], _grammar) dep_tree = parse(strings[1], _grammar) if is_noun_phras...
This function processes a list of strings by combining noun phrases and verb phrases into clauses. It recursively parses and merges elements, memoizing parsed structures for efficiency. If the first string is empty, it skips it; otherwise, it checks if the first is a noun phrase and the second a verb phrase. If so, it ...
def preproc_clauses(strings): global _grammar, _parse_memo if len(strings) < 2: return strings elif strings[0].strip() == "": return preproc_phrases(strings[1:]) else: ind_tree = parse(strings[0], _grammar) dep_tree = parse(strings[1], _grammar) if is_noun_phras...
def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _update_rain(self): """ ...
The code defines a method `run_game` that starts an infinite loop to continuously check for events, update rain elements, and refresh the screen, forming the core game loop for real-time interaction and rendering.
def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self._update_rain() self._update_screen()
def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pyg...
The code defines a method `run_game` that initiates the game's main loop, continuously checking for events, updating the player's ship and bullets, and rendering the game screen. This loop maintains real-time interaction, movement, and visual feedback, ensuring the game runs smoothly until manually stopped.
def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.ship.update() self._update_bullets() self._update_screen()
def get_all_empty_pos(self): empty_pos = [] for row in range(self.N): for col in range(self.N): if self.is_empty_pos(row, col): empty_pos.append((row, col)) return empty_pos def get_count_related_empty_pos(self, row, col): return len(set(se...
This function identifies an empty position in a grid. If 'ordered' is True, it selects the empty cell with the fewest adjacent empty cells to optimize solving strategies; otherwise, it returns the first encountered empty cell in row-major order.
def get_empty_pos(self, ordered=True): if ordered: empty_pos = self.get_all_empty_pos() min_related_empty = self.N * self.N min_empty_pos = None for x, y in empty_pos: num_empty_pos = self.get_count_related_empty_pos(x, y) if min_re...
def get_empty_pos(self, ordered=True): if ordered: empty_pos = self.get_all_empty_pos() min_related_empty = self.N * self.N min_empty_pos = None for x, y in empty_pos: num_empty_pos = self.get_count_related_empty_pos(x, y) if min_re...
This function solves a Sudoku puzzle using backtracking. It finds an empty cell, attempts valid numbers (1–N), and recursively solves the puzzle. If a number leads to a solution, it returns True; otherwise, it backtracks by resetting the cell and trying the next number. The process continues until the grid is fully fil...
def solve_sudoku(self): pos = self.get_empty_pos() if pos is None: return True row, col = pos for num in range(1, self.N+1): if self.is_valid_num(num, row, col): self.data[row][col] = num if self.solve_sudoku(): ...
def _handle_device_disconnected(self, payload: dict) -> None: if payload.get("event") != "disconnect": l.warning("Invalid or unhandled event received: %s", payload.get("event")) return data = payload.get("data") client_id = data.get("client_id") username = data.ge...
The function processes incoming messages by routing them based on their topic. It handles disconnection control messages, NAT-bridged messages (if enabled), appliance publication topics, and agent-specific messages. For each case, it delegates processing to specialized methods (e.g., device disconnection, payload forwa...
def _handle_message(self, topic: str, payload: bytes): try: # TODO: Implement message signature checks. # For now, we trust the message regardless of its signature. # Handling DISCONNECTION control messages disconnection_match = DISCONNECTION_TOPIC_RE.match(topi...
def get_videos(self, input: str): """ Utilizes HTML parsing to find the video urls. """ try: video_urls = [] video_tags = input.find_all('video') for video in video_tags: src = video.get('src') if src: ...
This function handles user input to decide whether to download media (videos/images) from a Telegram post. If 'Y' is chosen, it offers options to download videos, images, or both, aggregates URLs, and triggers media download. It then processes text content. If 'N' is chosen, it skips media and processes text directly. ...
def media_download_handler(self, postData: str): match(input('[TG Scraper] Do you want to download the media from the post? [Y/N]\n > ').lower()): case 'y': match(input(f'[TG Scraper]\n1. Download Videos ({self.videoCt})\n2. Download Images ({self.imgCt})\n3. Download All ({self.imgC...
def get_links(self): """ Link sanitizing and parsing. """ pullLink = self.parse_args() if pullLink: link_arg = pullLink.replace('?single', '') return [link + '?embed=1&mode=tme' for link in link_arg.split(',')] if pullLink is None: link...
The code processes a list of URLs by scraping Telegram posts, extracting metadata (date, author, content) and media counts (videos/images). If media exists, it triggers a download handler; otherwise, it processes text content. It handles exceptions for posts requiring Telegram access and cleans up temporary variables a...
def run(self): urlList = self.get_links() for link in urlList: try: self.workingURL = link post_data = self.get_post_data(link) self.date = self.get_post_date(post_data) self.auth = self.get_author(post_data) sel...
def ellipsoidal_variation(self, pv): pv = atleast_2d(pv) a = ev_amplitude(10 ** pv[:, 1:2], pv[:, 2:3], 10, 0.55, 0.3) return squeeze(a * self._evf) def boosting(self, pv): pv = atleast_2d(pv) a = boosting_amplitude(10 ** pv[:, 1:2], pv[:, 2:3], self.period, alpha=8.5) re...
The code defines a method `phase_model` that computes a composite light model by summing four components: ellipsoidal variation, boosting, reflected light, and emitted light, all applied to input `pv`. It ensures `pv` is at least 2D, sums the components, and returns the result with singleton dimensions removed.
def phase_model(self, pv): pv = atleast_2d(pv) return squeeze( self.ellipsoidal_variation(pv) + self.boosting(pv) + self.reflected_light(pv) + self.emitted_light(pv))
def config_dataset(tokenizer): instr = 'Generate a summary of what triggered {} in this post: {}' def verify_data_dict(dd): key_set = ['post', 'emo', 'summ'] assert list(dd.keys()) == key_set, f'Invalid key set: {dd.keys()}' len_dict = {k: len(dd[k]) for k in key_set} assert len...
The code conducts a unit test for a Seq2Seq model (BART) by loading a pre-trained model and tokenizer, configuring a balanced training dataset, creating a dataloader, and printing the shapes of tensors in the first batch to verify data processing correctness.
def unit_test(argv): import os from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from utils import set_randomness os.environ['TRANSFORMERS_NO_ADVISORY_WARNINGS'] = 'true' os.environ['TOKENIZERS_PARALLELISM'] = 'false' rng = set_randomness(FLAGS.seed) ckpt = 'facebook/bart-base...
def get_file_f0(self): return self._file_f0 def get_f0_coeffs_from_dabax_file(self, entry_name="Y3+"): filename = self.get_file_f0() file1 = self.get_dabax_file(filename) if self.verbose(): print("Accessing file: %s" % file1) sf = SpecFile(file1) flag_found = False ...
The function retrieves f0 coefficients for a given atomic symbol (Z) and fractional charge from a database file. If charge is 0, it directly fetches precomputed values. For non-zero charges, it scans the file to find entries matching the symbol, extracts their charge values and coefficients, then interpolates the coeff...
def f0_with_fractional_charge(self, Z, charge=0.0): filename = self.get_file_f0() symbol = atomic_symbols()[Z] if charge == 0.0: return self.get_f0_coeffs_from_dabax_file(entry_name=symbol) else: # retrieve all entries filename = self.get_dabax_file(...
def Bragg_angle(self, cryst, E_keV, h, k, l): dspacing = self.Crystal_dSpacing(cryst, h, k, l) # in A wavelength = codata.h * codata.c / codata.e / (E_keV * 1e3) * 1e10 # in A return numpy.arcsin(wavelength / 2 / dspacing) def Fi(self, Z, energy): return self.FiAndFii(Z, energy)[0] def...
The code calculates the structure factor (F_H) for a crystal's diffraction pattern at a given X-ray energy. It computes atomic contributions using Miller indices, scattering factors (f0, Fi, Fii), and coordinates, then sums them with exponential terms for spatial periodicity. The Debye-Waller factor accounts for therma...
def Crystal_F_H_StructureFactor(self, crystal_id, energy_in_kev, millerH, millerK, millerL, debyeWaller,...
def Bragg_angle(self, cryst, E_keV, h, k, l): dspacing = self.Crystal_dSpacing(cryst, h, k, l) # in A wavelength = codata.h * codata.c / codata.e / (E_keV * 1e3) * 1e10 # in A return numpy.arcsin(wavelength / 2 / dspacing) def Fi(self, Z, energy): return self.FiAndFii(Z, energy)[0] def...
This function calculates the structure factors F₀, F_H, and F_H̄ for a crystal using its atomic composition, energy, and Miller indices. It computes scattering amplitudes by summing contributions from each atom, incorporating Debye-Waller factors, atomic form factors, and exponential terms based on Bragg angles and cry...
def Crystal_F_0_F_H_F_H_bar_StructureFactor(self, crystal_id, energy_in_kev, millerH, millerK, millerL, ...
def selecting_tables_milestones(url): ''' This function extracts the commitment date (Effectivity date) from Milestones table ''' response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") table = soup.find('table', attrs={"class": 'milestones'}) headers = [] row...
The function `combine_all_dict` consolidates data from multiple sources into a unified dictionary. It retrieves data by calling three functions (`remove_unnecessary_fields`, `selecting_tables_milestones`, and `selecting_tables_financing`) with the provided URL. If `selecting_tables_milestones` returns a valid result, i...
def combine_all_dict(url): ''' This function combines all results of extracted data from different tables into one dictionary ''' if selecting_tables_milestones(url) is not None: dict_1 = remove_unnecessary_fields(url) dict_2 = selecting_tables_milestones(url) dict_3 = selecting...
def collecting_project_urls(current_url): """ This function collects all the project urls on a current page of ADB website and stores urls in a list Input: current_url(str): The url of the current page Returns: list of all project urls to scrape on page """ urls = [] res...
This function scrapes ADB project URLs from paginated web pages, collecting project data until the specified end date (month_year) is reached. It stores the scraped data in a JSON file named after the 'name' parameter, using pagination navigation and date checks to determine when to stop scraping.
def crawl(month_year, name): """ This function applys the previous scraping functions to scrape the ADB projects url. It places output into a jason file. Input: month_year(str):stop condition month (month abreviated) and year example("Nov 2011") Returns: jso...
def get_all_recipes(): # https://qr.ae/prwWFb script_dir = os.path.dirname(__file__) recipe_df_path = os.path.join(script_dir, '../recipe_scraper/recipe_scraper/spiders/recipes.csv') recipe_block_path = os.path.join(script_dir, '../recipe_scraper/recipe_scraper/spiders/master_blocked_recipes.csv') m...
The main task of the code is to generate or update a menu based on the input. If the menu is empty, it creates a new menu using all recipes from `get_all_recipes()`. If not empty, it updates the existing menu with new recipes. It then resets the index of the menu's recipe DataFrame and returns both the original recipe ...
def __main__(menu): # if menu is empty, make new menu. # is menu isn't empty, recalculate menu df = get_all_recipes() if menu.empty: menu = make_menu(df) else: update_menu(menu, df) # print('updated menu df') # print(menu.recipes_df) menu.recipes_df = menu.recipes...
def get_all_q_expands(x): direct_expands = get_qhat_zt_expand_direct(x) previous_expands = None all_expands = [] for n in range(5): effective_n = 5-n previous_expands = get_qhat_zn_expand_znt_expand( direct_expands['qhat_zt_expand_direct{}'.format(effective_n)], ...
The function `get_qhat_z` computes a value `qhat_z` by first generating expansions from input `x`, reordering them, and then processing the reordered expansions to derive the final result.
def get_qhat_z(x): all_expands = get_all_q_expands(x) reorderd_expands = reorder_all_expands(all_expands) qhat_z = get_all_qhat_z(reorderd_expands) return qhat_z
def get_qhat_z(x): all_expands = get_all_q_expands(x) reorderd_expands = reorder_all_expands(all_expands) qhat_z = get_all_qhat_z(reorderd_expands) return qhat_z def get_qhat_g(x): g_expand = get_qhat_zt_expand_direct(x,'g') qhat_g = get_all_qhat_g(g_expand) return qhat_g def time_z...
This code performs a prediction task by generating latent representations (qhat_z and qhat_g) from concatenated inputs, expanding these representations across time steps, decoding them to reconstruct input data, and computing losses (cross-entropy and KL divergence) for evaluation. It returns reconstructed outputs and ...
def predict(inputs,gen): t0,t1,t2,t3 = inputs x = tf.concat([t0,t1,t2,t3],axis = 0) qhat_z = get_qhat_z(x) qhat_g = get_qhat_g(x) g_info = time_zero_information(qhat_g,var = 'g',gen = gen) znm_info = [] znm_info.append(time_zero_information(qhat_z,gen = gen)) for bucket in range(1,BUCKETS): ...
def allowed_transition(state_1, state_2, **kwargs): dL = state_2.L - state_1.L dS = state_2.S - state_1.S dM = state_2.M - state_1.M dEn = energy(state_2) - energy(state_1) if abs(dL) == 1 and \ dS == 0 and \ dM in kwargs.get('dM_allow', [0,+1,-1]): return True else: ...
This function calculates the spontaneous emission rate between two quantum states using the Einstein A coefficient. It checks if the transition is allowed, computes energy difference and transition dipole moment, applies the formula involving Planck's constant, speed of light, and electric constant, then converts the r...
def spontaneous_emission_rate(state_1, state_2, **kwargs): if not(allowed_transition(state_1, state_2, **kwargs)): return 'Not allowed transition' en_1 = energy(state_1, units='j') en_2 = energy(state_2, units='j') omega_transition = 2*pi*np.abs(en_1 - en_2)/h # E=hf=h(w/2pi), w=2pi*E/h ...