dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_media_type(file_name): file_extension = pathlib.Path(file_name).suffix file_extension = file_extension[1:] if file_extension.lower() in photo_ext: return Media_Type.PHOTO elif file_extension.lower() in video_ext: return Media_Type.VIDEO else: return Media_Type.NON_MED...
The code extracts metadata from a file, including its media type, creation time, file extension, name, size, directory path, and signature. It compiles these details into a dictionary with predefined keys like 'run_id', 'media_type', and 'creation_time', then returns this structured data.
def get_file_metadata(file): output = dict() #print("Getting metadata for file:{}...".format(file)) media_type = get_media_type(file) creation_time = getLikelyCreateDate(file) file_extension = pathlib.Path(file).suffix input_file_name = os.path.basename(file) file_size = os.path.getsize(fil...
def get_media_type(file_name): file_extension = pathlib.Path(file_name).suffix file_extension = file_extension[1:] if file_extension.lower() in photo_ext: return Media_Type.PHOTO elif file_extension.lower() in video_ext: return Media_Type.VIDEO else: return Media_Type.NON_MED...
The code extracts metadata from a file, compiling details like media type, creation time, file size, path, extension, and signature into a dictionary. It includes a unique run ID, row counter, and file type标识, returning structured data for tracking or processing purposes.
def get_file_metadata(file, counter): output = dict() # print("Getting metadata for file:{}...".format(file)) media_type = get_media_type(file) creation_time = getLikelyCreateDate(file) file_extension = pathlib.Path(file).suffix input_file_name = os.path.basename(file) file_size = os.path.g...
def get_file_pattern_from_folder( input_root_dir ): if not os.path.exists(input_root_dir): #print(input_root_dir , " NOT EXISTS...") # logger.error(str(input_root_dir), ":NOT EXISTS...") #TODO: we need to throw an error.Test this raise Exception("Invalid input folder. Check your path"...
The main task of the code is to gather metadata for all files in a specified directory and its subdirectories. It uses a file pattern to identify files, iterates through them, retrieves metadata (signature, creation time, etc.), logs progress periodically, and returns a list of metadata dictionaries. The function also ...
def create_files_metadata_list(root_dir): pattern_root_dir = get_file_pattern_from_folder(root_dir) tree_metadata = [] files = glob.glob(pattern_root_dir, recursive = True) counter = 0 files_count = len(files) logger.info('Gathering files metadata for directory:{}, that h...
def read_backup_status_metadata_from_file(backup_status_file): with open(backup_status_file, 'r') as f: header = f.readline() tree_metadata =[] for line in f: media = {} for key, value in zip(header.split('|'), line.split('|')): media[key.strip()] = va...
The function creates a metadata map of prior backup files by either reading from an existing backup status file or generating it from the output directory's files if no prior backup exists. It logs the process, file counts, and time taken, then returns the metadata map for backup management.
def create_prior_backup_metadata_map(output_root_dir): prior_backup_status_file = os.path.join(output_root_dir, BACKUP_STATUS_FILENAME) local_start_time = datetime.now() logger.info('Reading prior backup status file:' + str(prior_backup_status_file)) if os.path.exists(prior_backup_status_file): ...
def _get_stream_name(name): return '[{}]'.format(name) def _get_filter_arg(filter_nodes, outgoing_edge_maps, stream_name_map): _allocate_filter_stream_names(filter_nodes, outgoing_edge_maps, stream_name_map) filter_specs = [_get_filter_spec(node, outgoing_edge_maps[node], stream_name_map) for node in filter...
This function generates command-line arguments for ffmpeg based on a stream specification. It processes input, output, global, and filter nodes, sorts them topologically, constructs filter chains, and combines all components into a list of ffmpeg arguments, optionally adding the `-y` flag to overwrite outputs.
def get_args(stream_spec, overwrite_output=False): """Get command-line arguments for ffmpeg.""" nodes = get_stream_spec_nodes(stream_spec) args = [] # TODO: group nodes together, e.g. `-i somefile -r somerate`. sorted_nodes, outgoing_edge_maps = topo_sort(nodes) input_nodes = [node for node in s...
def load_component_pfb(self, var_meta, name): """ These filetypes have dimensions (component, x, y, z) where component represents an anisotropy """ all_da = {} if var_meta['domain'] == 'surface': dims = ('x', 'y') elif var_meta['domain'] == 'subsurface...
This function loads PFB data based on metadata, determining the data type (e.g., component, time-varying) and calling specialized loaders like `load_component_pfb` or `load_time_varying_pfb`. It handles file paths, checks for existence, and returns a dataset. Different base types like 'clm_output' or 'pfb 2d timeseries...
def load_pfb_from_meta(self, var_meta, name='_', parallel=False): base_type = var_meta['type'] if base_type == 'pfb': # Is it component? if len(var_meta['data']) > 1 and 'component' in var_meta['data'][0]: ret_das = self.load_component_pfb(var_meta, name) ...
def read_header(self): """Reads the header""" self.f.seek(0) header = {} header['x'] = struct.unpack('>d', self.f.read(8))[0] header['y'] = struct.unpack('>d', self.f.read(8))[0] header['z'] = struct.unpack('>d', self.f.read(8))[0] header['nx'] = struct.unpack('>i...
This code initializes an object by reading a binary file's header, setting grid parameters (p, q, r) from input or computed values, and optionally precomputing subgrid information. It handles header parsing, parameter fallback logic, and subgrid metadata preparation for subsequent operations.
def __init__( self, file: str, precompute_subgrid_info: bool=True, p: int=None, q: int=None, r: int=None, header: Mapping[str, Number]=None ): self.filename = file self.f = open(self.filename, 'rb') if not he...
def is_meta_or_pfb(self, filename_or_obj, strict=True): def _check_dict_is_valid_meta(meta): assert 'parflow' in meta.keys(), \ ('Metadata file missing "parflow" key - ', 'are you sure this is a valid Parflow metadata file?') if not strict: # Jus...
The main task of the code is to load data from either a PFB binary file or a PF metadata file into an xarray Dataset. It determines the file type, reads the data with optional parameters like dimensions, chunking, and input/output handling, then returns the structured dataset for analysis.
def open_dataset( self, filename_or_obj, *, base_dir=None, drop_variables=None, name='parflow_variable', read_inputs=True, read_outputs=True, parallel=False, inferred_dims=None, inferred_shape=None, chunks={}, strict...
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The function `clickNormal` appends a placeholder ("-") to the data list, writes it to a CSV file, and checks annotations. It first verifies if the image file list is empty, triggering an alert and exiting if true. Otherwise, it processes data, saves it, and validates annotations.
def clickNormal(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("-") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The code's main task is to handle a "Blow out" annotation action by checking if image files exist, appending "Blow out" to a data list, saving the data to a CSV file, and verifying annotations. It prevents execution when no images are available and triggers an alert in such cases.
def clickBlowout(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Blow out") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The method `clickStringing` appends "Stringing" to a data list, writes it to a CSV file, and checks annotations, but first verifies if the image file list is non-empty; if empty, it alerts the user and exits.
def clickStringing(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Stringing") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The code's main task is to validate the presence of image files, append "Lines of Print" to data, save it to a CSV file, and trigger annotation checks if the file list is non-empty. If the list is empty, it alerts the user and exits.
def clickLinesofPrint(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Lines of Print") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The code's main task is to handle user interaction for marking "Gaps" in image data. It checks if image files exist, alerts if none are present, appends "Gaps" to a data list, writes the updated data to a CSV file, and triggers an annotation check. This likely supports an image annotation workflow where users label gap...
def clickGaps(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Gaps") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The code's main task is to handle image separation operations by checking for available image files, appending a "Separation" marker to the data list, writing this data to a CSV file, and verifying annotations. If no images are present, it alerts the user and exits. The method ensures proper data logging and validation...
def clickSeparation(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Separation") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The main task of the code is to handle the "Warping" process by validating the presence of image files, logging the action to a data list, writing the data to a CSV file, and triggering an annotation check. It ensures no operations proceed without valid image files and sequentially executes warping-related tasks.
def clickWarping(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Warping") self.writeCSV() self.checkAnotation()
def alert_box(self): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Please Load the File") msg.setWindowTitle("Information") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) retval = msg.exec_() def writeCSV(self): self.d...
The main task of the code is to handle an "Etc_Print Error" scenario by appending an error message to a data list, writing it to a CSV file, and checking annotations. It first verifies if image files exist; if not, it shows an alert and exits. If files exist, it records the error, saves data, and triggers annotation ch...
def clickEtc(self): if len(self.imageFileList) == 0: self.alert_box() return self.data.append("Etc_Print Error") self.writeCSV() self.checkAnotation()
def show_view_author(): print("+-------------------------------+") print("| View Author |") print("+-------------------------------+") int("caca") while True: try: id = int(input("Enter the Author's id to view: ")) show_details(id) return...
The code displays an authors management menu, allowing users to view, find, add, edit, delete authors, list all entries, or return to the previous menu. It processes user input to trigger corresponding functions, supporting both letter and numeric options, and exits on 'Q' or 'q'
def show_authors_menu(): while True: print("+-------------------------------+") print("| Authors Menu |") print("+-------------------------------+") print("Select an option\n") print("\tV) View") print("\tF) Find") print("\tA) Add") ...
def clean_message(s: str) -> str: """Return a cleaned version of string s with only uppercase letters inside. >>> clean_message('a.wG135') 'AWG' >>> clean_message('hfuaohfo') 'HFUAOHFO' """ new = '' for char in s: if char.isalpha(): new = new + char return ne...
The function processes a list of messages by encrypting or decrypting each character using a deck of numbers as a keystream. It applies the specified operation (ENCRYPT/DECRYPT) to each message, transforming letters with corresponding keystream values from the deck, and returns the modified list of messages.
def process_messages(deck: List[int], message: List[str], operation: str) \ -> List[str]: """Return a list of message with a list of deck of cards after operation applied to list of message. """ new_list = [] if operation == ENCRYPT: for sentence in message: mes = '' ...
def decompose_as_power_of_two(n: int) -> Power2: """ see the decription of Power2 namedtuple for a description """ # find if n is odd or not and adjust i in consequence i = 1 if n % 2 != 0 else 0 # adjust n to be even n -= 1 * i # find the biggest power of 2 that divides n # T...
This function factorizes an integer $ n $ into its prime factors using a combination of primality testing (e.g., Miller-Rabin) and Pollard's rho algorithm. It recursively decomposes non-prime factors, handles even numbers by extracting powers of 2, and verifies the factorization's correctness. The result is a dictionar...
def naive_factorize_rho_method(n: int, k_primality=10, primality_test=None, rho_limit=50, rho_tries=10): # go find the primes global PRIMES print( f"INFO: trying to factorize {n}, k_primality: {k_primality}, rho_limit: {rho_limit}, rho tries limit: {rho_tries}, primality_test: {primality_test}") ...
def letter_distance(start: str, end: str, alphabet: str) -> int: alpha_list = list(alphabet) start_index = index_no_error(start, alpha_list) end_index = index_no_error(end, alpha_list) if start_index == -1 or end_index == -1: return -1 else: return end_index - start_index if (start...
This function encodes or decodes a message using a Caesar cipher with a rotation value derived from user input or a letter pair hint. It handles case sensitivity based on the 'respect_uppercase' parameter, applying the rotation to each character in the message while preserving original casing if specified.
def enc_dec_message_az(message: str, rotation: Optional[int] = None, hint: Optional[Tuple[str, str]] = None, encode=True, respect_uppercase=False) -> str: # alphabet alphabet = "abcdefghijklmnopqrstuvwxyz" if rotation is not None: rotation = rotation elif hint is not None: # compute the...
def learn_vocabulary(): print('learn vocabulary from train file') for a in range(vocabulary_hash_size): vocabulary_hash[a] = -1 fin = open(train_file,'r') global vocabulary_size global train_words add_word_to_vocabulary("</s>") word = "" while True: if train_words > 150000: b...
The code trains a word embedding model (likely Word2Vec) using multithreading. It initializes the network, processes vocabulary, and trains model parameters in parallel threads. After training, it saves learned word vectors to a file, either in binary/text format. If class clustering is enabled, it groups words into cl...
def train_model(): print('train model') t = [] global start_alpha global vocabulary_size global itr starting_alpha = alpha if read_vocabulary_fg != 0: Read_vocabulary() else: learn_vocabulary() if save_vocabulary_file[0] != 0: save_vocabulary() if output_file[0] == 0: return initia...
def __get_style_net(self): style_net = Net.HRNet() return style_net.to(self.device) def __get_optimizer(self, style_net): optimizer = optim.Adam(style_net.parameters(), lr=5e-3) return optimizer def __get_scheduler(self, optimizer): return optim.lr_scheduler.StepLR(optimizer, ste...
This code performs neural style transfer by iterating through epochs to optimize a target image. It uses a style network to generate stylized outputs, computes content and style losses, combines them with weighted coefficients, and updates the model via backpropagation. The optimizer and scheduler manage training dynam...
def transfer(self): style_net = self.__get_style_net() optimizer = self.__get_optimizer(style_net) scheduler = self.__get_scheduler(optimizer) for epoch in range(0, self.steps+1): target = style_net(self.content_img).to(self.device) target.requires_grad_(True) ...
def list_connections(): if len(arrConnection) > 0: strClients = "" for intCounter, conn in enumerate(arrConnection): strClients += str(intCounter) + 4*" "+str(arrAddresses[intCounter][0]) + 4*" " + str(arrAddresses[intCounter][1]) + 4*" " + str(arrAddresses[intCounter][2]) + 4*" " + str(arrAddresses[intCount...
The code defines a main menu loop that processes user commands: "--l" lists connections, "--i" interacts with selected connections by sending commands, "--x" exits the program, and invalid inputs trigger help. It manages network connection interactions through command-line interface options.
def main_menu(): while True: strChoice = input("\n"+">>") if strChoice == "--l": list_connections() elif strChoice[:3] == "--i" and len(strChoice) > 3: conn = select_connection(strChoice[4:],"True") if conn is not True: send_commands() elif strChoice == "--x": close() break else: ...
def create_socket(): global objSocket try: objSocket = socket.socket() objSocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) except socket.error() as strerror: print("error creating socket"+str(strerror)) def socket_bind(): global objSocket try: print("listening to the port: "+str(intPort)) objS...
The code defines a function 'work()' that processes items from a queue. If the item is 1, it initializes a socket server (create_socket(), socket_bind(), socket_accept()). If the item is 2, it periodically checks for non-empty 'arrAddresses' to trigger 'main_menu()'. After processing, it marks tasks as done (twice) and...
def work(): while True: intValue = queue.get() if intValue == 1: create_socket() socket_bind() socket_accept() elif intValue==2: while True: time.sleep(0.2) if len(arrAddresses)>0: main_menu() break queue.task_done() queue.task_done() sys.exit(0)
def get_heading(self, euler = True): msg = rospy.wait_for_message("/odom" , Odometry) orientation = msg.pose.pose.orientation roll, pitch, yaw = tf.transformations.euler_from_quaternion(( orientation.x ,orientation.y ,orientation.z ,orientation.w ))...
The code constructs a rectangular path by generating coordinates for its perimeter and controls a robot's movement along this path. It creates a list of points forming a rectangle, then continuously checks the robot's position relative to an origin. If the robot is beyond a threshold distance, it moves forward; otherwi...
def run(self): origin = Point() origin.x = 2 origin.y = 0 rectangle = [] X1 = np.linspace(-2, 2 , 100) for x in X1: rectangle.append([x,3]) Y2 = np.linspace(3, -3 , 100) X2 = np.array([3]*100) for y in Y2: rectangl...
def take_step(self, mode='train'): if mode == 'explore': action = self.env.action_space.sample() else: s_0 = np.stack([self.state_buffer]) action = self.network.get_action(s_0, epsilon=self.epsilon) self.step_count += 1 s_1, r, done, _ = self.env.s...
This code trains a Deep Q-Network (DQN) agent using experience replay and target network synchronization. It populates a replay buffer, runs episodes with exploration, updates the neural network periodically, syncs the target network, tracks rewards, and saves model weights when performance improves. Training stops upo...
def train(self, epsilon=0.05, gamma=0.99, max_episodes=None, batch_size=32, network_sync_frequency=5000, update_freq=4): self.gamma = gamma self.epsilon = epsilon save_freq = 100 self.fps_buffer = [] best_ep_avg = 0 # Populate replay buffer print("Populati...
def reshape_theta(theta: np.array, layer_sizes: np.array) -> [np.array, ]: """ Reforms individual layers as defined by layer sizes. theta: unrolled array containing all layers layer_sizes: array indicating the size of layers """ layers = [] for layer in layer_sizes: layer_size = lay...
This function computes the cost (log loss with regularization) and gradients for a neural network using softmax activation. It reshapes weights, performs forward propagation, calculates cross-entropy loss, applies L2 regularization, and returns the cost and gradient for parameter updates during training.
def cost(theta: np.array, layer_sizes: np.array, labels_end: int, x: np.array, y: np.array, reg: float = 0, labels_start: int = 0) -> (float, np.array): """ theta: unrolled array containing all layers layer_sizes: array indicating the size of layers labels_end: integer indicating the largest la...
def switch_case(text: str) -> str: """ This functions switches the case of every individual character in a string. Parameters: text - str - string to be switched Return: str - switched version of the input """ return text.swapcase() def bad_tokenize(text: str) -> list: """ To...
The code demonstrates text processing tasks: tokenizing, normalizing (case folding), counting word frequencies using dictionaries/Counters, and calculating vocabulary size. It loads a large text file, tokenizes it, applies frequency counting, and tests Heaps' Law on the tokenized data to analyze vocabulary growth patte...
def main(): print("Running standalone functions") print("original text: " + text) print("switch_case: " + switch_case(text)) print("bad_tokenize: " + str(bad_tokenize(text))) print("original word list: " + str(ls)) print("case_fold: " + str(case_fold(ls))) print("count_dict: " + str(count_...
def get_key_pair(self, profile_name: str) -> Tuple[str, str]: """ Get an API key pair for authenticating. Args: profile_name (str): The name of the API key profile to get. Returns: Tuple[str, str] """ api_key = _get_password(f"{profile_name}-api...
This method renames an API key profile by retrieving its credentials, updating the profile name in storage, and deleting the old entry. If the renamed profile was the default, it updates the default reference in the management configuration.
def rename_key_pair(self, old_name: str, new_name: str): """ Rename an API key profile. Args: old_name (str): The name of the profile to change. new_name (str): The new name of the profile. """ api_key, api_secret = self.get_key_pair(old_name) sel...
def parse_cmdline(): """Parse command-line options.""" parser = ArgumentParser(add_help=True) # Required args. input_group = parser.add_mutually_exclusive_group(required=True) input_group.add_argument( '--boot_img', help='path to the boot image to certify') input_group.add_argument( ...
The main task of the code is to parse command-line arguments and certify a boot image. It checks if a boot image archive is provided; if so, it certifies the archive using `certify_bootimg_archive`, otherwise it certifies the direct boot image via `certify_bootimg`, applying specified algorithms, keys, and additional p...
def main(): """Parse arguments and certify the boot image.""" args = parse_cmdline() if args.boot_img_archive: certify_bootimg_archive(args.boot_img_archive, args.output, args.algorithm, args.key, args.extra_args, args.extra_footer_arg...
def generate_test_boot_image_archive(archive_file_name, archive_format, boot_img_info, gki_info=None): """Generates an archive of test boot images. It also adds a file gki-info.txt, which contains additional settings for for `certify_bootimg --extra_args`. Args: ...
This test case verifies the certification of a boot image archive using the `certify_bootimg` tool. It generates a test archive with specific configurations, applies RSA4096 signing, and checks for correct AVB footers, image sizes, and expected signatures in the output. The process ensures the tool properly adds securi...
def test_certify_bootimg_archive(self): """Tests certify_bootimg for a boot images archive..""" with tempfile.TemporaryDirectory() as temp_out_dir: boot_img_archive_name = os.path.join(temp_out_dir, 'boot-img') gki_info = ('certify_bootimg_extra_args=' '--...
def generate_test_boot_image_archive(archive_file_name, archive_format, boot_img_info, gki_info=None): """Generates an archive of test boot images. It also adds a file gki-info.txt, which contains additional settings for for `certify_bootimg --extra_args`. Args: ...
The test verifies the `certify_bootimg` tool's functionality for boot image archives, both with and without GKI info. It generates test archives, applies RSA4096 signing, checks AVB footers, and validates output sizes and signatures. The process ensures correct certification behavior across different archive formats (z...
def test_certify_bootimg_archive_without_gki_info(self): """Tests certify_bootimg for a boot images archive.""" with tempfile.TemporaryDirectory() as temp_out_dir: boot_img_archive_name = os.path.join(temp_out_dir, 'boot-img') # Checks ceritfy_bootimg works for a boot images arc...
def sphinx_builder(): try: from sphinx.setup_command import BuildDoc except ImportError: class NoSphinx(Command): user_options = [] def initialize_options(self): raise RuntimeError('Sphinx documentation is not installed, run: pip install sphinx') ...
This code defines a Python package setup function that configures documentation building (via Sphinx), test execution (via pytest with coverage options), and package metadata. It sets up command-line tools, versioning using environment variables, dependency management, and packaging parameters for distribution. The fun...
def setup_package(): # Assemble additional setup commands cmdclass = {} cmdclass['docs'] = sphinx_builder() cmdclass['doctest'] = sphinx_builder() cmdclass['test'] = PyTest # Some helper variables version = os.getenv('GO_PIPELINE_LABEL', VERSION) docs_path = os.path.join(__location__, ...
def rectangle(): print('Rectangle:') l = int(input("Enter length: ")) b = int(input('Enter breadth: ')) perimeter = 2 * (l + b) area = l * b print('Area:', area) print('Perimeter:', perimeter) time.sleep(0.5) def square(): print('Square:') a = int(input('Enter a number: ')) s...
The code presents a 2D shape dimension calculator menu, allowing users to select Rectangle, Square, Circle, or Exit. It loops until "Exit" (option 4) is chosen, calling corresponding functions for calculations. Invalid inputs trigger error messages. The "Exit" option invokes `execute_option()` before terminating.
def plane_dimension(): while True: print('Main Menu (2D)') print('1. Rectangle') print('2. Square') print('3. Circle') print('4. Exit') selected = input('Enter your choice (1-4): ') if selected == '1': rectangle() elif selected == '2': ...
def disable_owner_controls(self): """ Disables the owner controls (e.g. data and detail setting). """ disabled_color = ('#D0E9DD','#D0E9DD') if self.owner != Window_View.user: self.window['-DATASET-'].update(disabled=True) self.window['-DATASET-'].update(b...
The main task of the code is to configure the DES screen's UI elements by updating the owner information, initializing chart selection options, disabling owner controls if not the current user, setting chat data, and preparing chart data for display. It ensures the interface reflects user permissions and loads necessar...
def set_data(self): """ Sets the data for the DES screen. """ # Set owner self.window['-USER-'].update(f'Managed by {self.owner}') # Set chart options self.window['-CHART_LIST-'].update(values=list(self.chart_dict)) self.window['-CHART_LIST-'].update(valu...
def check_input_string(self, input): if len(input) == 0: raise StringIsEmptyError if input.count('(') != input.count(')'): raise ParenthesisError supported = list('*/+-()1234567890') if any((c not in supported) for c in input): raise UnsupportedCharError def fix_separated_nu...
The function `convert_string_to_exprs` processes a mathematical string to convert it into a list of `Expression` objects. It validates the input, fixes number and subtraction formatting, extracts parentheses, adjusts operator priorities, and constructs expressions from the cleaned data. On success, it returns the list ...
def convert_string_to_exprs(self, string:str) -> List[Expression]: try: self.check_input_string(string) self.exp_full_str = list(string) self.exp_full_str = self.fix_separated_numbers(self.exp_full_str) self.exp_full_str = self.fix_subtraction_operations(self.exp_...
def log(text): with log_path.open('at', encoding='utf-8') as log_file: print(text, file=log_file) def set_elec_setting(setting_name, value): call_profile_func('set_ee_setting', setting_name, value) def jslisten_stop(): #call_profile_func('jslisten', 'stop') subprocess.check_call(['systemctl', 'stop', 'jslisten'])...
The main task of the code is to parse command-line arguments, configure an emulator with specified ROM/platform settings, initialize logging, execute the emulator process, handle potential errors (e.g., BIOS checks for specific systems), and clean up resources. It processes inputs, sets up emulator parameters, runs the...
def main(): time_started = perf_counter() i = 0 args: dict[str, str] = {} while i < len(sys.argv)-1: if sys.argv[i].startswith('--'): args[sys.argv[i][2:]] = sys.argv[i + 1] i += 1 continue if sys.argv[i].startswith('-'): args[sys.argv[i][1:]] = sys.argv[i + 1] i += 1 continue i += 1 rom ...
def get_retroarch_command(self, shader_arg: str) -> 'Sequence[Union[str, Path]]': if log_level != 'minimal': log('Running a libretro core via RetroArch') log(f'platform: {self.platform}') log(f'core: {self.core}') retroarch_binary = 'retroarch' #if self.core in {'pcsx_rearmed', 'parallel_n64'}: # retro...
This function determines and returns the appropriate command sequence to execute an emulator or script based on the system's context, such as the type of emulator (e.g., RetroArch, MAME), whether the ROM is a shell script, or if it's a Libretro port. It delegates to specific helper methods like get_retroarch_command or...
def get_command(self, shader_arg: str='') -> 'Sequence[Union[str, Path]]': is_libretro_port = self.core and not self.emulator #If true this was called from the inside of a port .sh that runs a libretro port (e.g. 2048, tyrQuake, etc), it makes no sense otherwise if self.rom and (self.rom.suffix == '.sh' or se...
def get_args(): parser = argparse.ArgumentParser( description='Arguments for picking up release') parser.add_argument('--org', default="AmberELEC", help='Github organization. Allows testing with fork releases other than AmberELEC') parser.add_argument(...
The code's main task is to check for available software updates, verify system requirements (networking, disk space, boot partition), and download/update firmware if necessary. It handles error checking, user-defined parameters, and ensures proper conditions for a safe update process.
def main(): args = get_args() initialize_directories(args.update_dir, args.check) message_stream(CONSOLE.CLEAR) message_stream( f"{CONSOLE.AMBER}Amber{CONSOLE.WHITE}ELEC{CONSOLE.ENDC} Update Utility - Starting Update...\n") if not online_status(): message_stream( "\nE...
def _get_resource_topics(self, resources): """Return a set of every author used by at least one resource.""" # python can pass a dict to jinja, but jinja can't pass a dict to python. it just passes a # string representation of the dict if type(resources) is str: resources = a...
The main task of the code is to generate organized files by categorizing training materials and digital security guides based on extracted metadata (topics, languages, authors) from JSON files. It loads two JSON datasets, extracts relevant attributes, and uses them to create structured output files under specified dire...
def generate_files(self): with open(os.path.join(self.env.project.tree, 'databags', 'community-training-materials.json'), 'r') as f: training_resources = json.load(f) with open(os.path.join(self.env.project.tree, 'databags', 'digital-security-guides.json'), 'r') as f: safety_gui...
def addrec(): name = input("\nEnter student's full name ") sub = int(input("\nEnter number of subjects taken ")) subjects={} for i in range(sub): s=input("\nEnter subject ") m=input("\nEnter percentage in {0} ".format(s)) subjects[s]=m student_records[name]=(subjects) printmenu() def viewrec(): k=list(stu...
The code defines a menu function that repeatedly prompts the user for a numeric choice (1-4). It executes corresponding actions: adding, viewing, or deleting records (via addrec(), viewrec(), delrec()) or exiting (choice 4). Non-numeric inputs trigger error messages, enforcing valid numeric input for menu navigation.
def menu(): while True: choice = input("Enter your choice : ") if choice.isnumeric(): if int(choice)==1: addrec() elif int(choice)==2: viewrec() elif int(choice)==3: delrec() elif int(choice)==4: break else: print("Enter 1, 2,3 or 4... How hard can that be...") else: print("...
def extractHourlyLoad(loadURL): loadData = csv.reader(open(loadURL, 'r'), delimiter=',') hourlyLoad = [] for hour in loadData: # loop through csv file and place kwh load values in an array hourlyLoad.append(float(hour[2])) return hourlyLoad def calcMonthlyLoad(hourlyLoad, daysInMonth): mont...
The function calculates the total electricity charge based on a specified rate structure (e.g., flat, seasonal, tiered, time-of-use). It loads hourly energy consumption data, applies the selected billing model with corresponding prices and thresholds, computes monthly charges, and adjusts the subtotal by a fixed percen...
def getTotalCharge(rateStructure = 7): # define which utility rate is used # rateStructure = 7 ''' 1 = flat rate 2 = seasonal rate 3 = monthly rate 4 = tiered rate 5 = seasonal tiered rate 6 = monthly tiered rate 7 = time of use rate ''' # Months months = np.zeros(12...
def updateQueue(): global jobs # import update from database connection = sqlite3.connect("test.db") cursor = connection.cursor() cursor.execute("SELECT * FROM jobs") rows = cursor.fetchall() jobs = pd.read_sql("SELECT * FROM jobs", connection) if jobs.empty: return print("Cu...
The main task of the code is to continuously monitor and manage a job queue by updating job predictions, targets, and deadlines, printing optimized execution times, and waiting for 60 seconds before repeating the process. It runs in an infinite loop, checking for jobs, updating system states, and recursively restarting...
def main(): updateQueue() while not (jobs.empty): updateQueue() updatePredictions() updateTargets() executeDeadlines() print("Current job optimized execution times (id, execution time): \n") for run in runTimes: print(run) print("\n") p...
def succ(self, targetID, state=board): """A function used to find all successor states of the current state. This function will be used to calculate possible moves and assess them to select the best possible move. Assessment will be conducted by the heuristic function. Args: ...
The main task of the code is for an AI player to evaluate all possible game states using a heuristic function, select the move with the highest heuristic value, update its board state, and return the next InnerBoard for the human player to move.
def take_turn(self, inner): """Executes the AI's next calculated move. In order to take its turn, the AI player will use this function to compare game theoretic values for each state using its heuristic and determine which move is optimal. Args: inner: The specified InnerB...
def first_turn(self): """ Helper function for take_turn to randomly select the first turn. This function will randomly select a first move for the AI player. Return: The innerboard index that the human player must move to. """ inner = random.choice(range(9)) ...
The main task of the code is to initiate and manage a turn-based game between a human and AI player. It randomly selects the starting player, then alternates turns using a loop until a winner is determined. The AI or human takes turns making moves, with the board validated after each move to check for a win. The loop c...
def start_game(self): """The driver method for the class. The application will begin by randomly selecting which player goes first, and alternating turns from then onward. """ player = random.choice([0, 1]) inner = -1 # Print which palayer will move first ...
def get_actor_blueprints(world, filter, generation): bps = world.get_blueprint_library().filter(filter) if generation.lower() == "all": return bps # If the filter returns only one bp, we assume that this one needed # and therefore, we ignore the generation if len(bps) == 1: return ...
This code simulates a CARLA-based autonomous driving scenario involving a construction site. It sets up a virtual environment with weather, traffic, and vehicles, disables the ego-vehicle's autopilot upon approaching barriers, measures handover performance (lane offset, collisions), and manages TTS for reading tasks. T...
def run(CONTENT_FOLDER_PATH): ################## Signal Reading and software logging ################## SIGNAL_FILE_PATH = "{}{}".format(CONTENT_FOLDER_PATH, "/ConfigFiles/SignalFile.txt") DATA_FOLDER_PATH = "{}{}".format(CONTENT_FOLDER_PATH, "/DataFiles") CONFIG_FILE_PATH = "{}{}".format(CONTENT_FOLDER...
def url(self, endpoint: str) -> str: """ Return full Grouper URL endpoint :param endpoint: The URL endpoint to append to ``self.endpoint`` :return: Complete HTTPS URL """ return join(self.endpoint, endpoint) def check_group_exists(self, group: str, group_type: str) -> ...
This function adds specified privileges to a Grouper access group, enabling it to interact with a target Grouper group. It validates privileges, checks target group existence, and uses the Grouper API to assign permissions like 'read' or 'admin'. It returns True on success or raises exceptions for invalid inputs or API...
def add_privilege(self, access_group: str, target_group: str, target_group_type: str, privileges: Union[str, List[str]]) -> bool: """ Add privilege(s) for a Grouper group to access target See `Grouper API "...
def query_2(conversation_history, initial_message, query, initial_prompt, chunks): print("creating prompt") messages = create_prompt_2(conversation_history, initial_message, query, initial_prompt, chunks) print("querying model") return query_model_2(messages...
The function processes a user query by retrieving domain and conversation settings, fetching relevant context chunks (if enabled), generating an answer using a specified model (new/old), updating conversation history, and returning the response along with metadata like chunks used. It handles both new and existing conv...
def get_answer(conversation_id, domain_id, query, initial_prompt, temp, user_id, use_new_model): print('get_answer -------------------------------->') use_context = False chunks = {} initial_message = conf.DEFAULT_INITIAL_MESSAGE conversation_history = [] print("getting domain s...
def initGPIO(): chip = gpiod.chip(0) # 0 chip pin = 4 gpiod_pin = chip.get_line(pin) config = gpiod.line_request() config.consumer = "Blink" config.request_type = gpiod.line_request.DIRECTION_OUTPUT gpiod_pin.request(config) return gpiod_pin def setUpdateStatus(gpiod_pin, busy): if ...
The main task of the code is to update a display with weather information using a GPIO pin and an Inky display. It initializes the hardware, retrieves weather data, generates an image with the information, sends it to the display, and updates the status to indicate completion.
def update(): gpio_pin = initGPIO() setUpdateStatus(gpio_pin, True) wi = weatherInfomation() cv = Image.new("RGB", canvasSize, getDisplayColor(WHITE) ) #cv = cv.rotate(90, expand=True) drawWeather(wi, cv) # cv.save("test.png") #cv = cv.rotate(-90, expand=True) inky = Inky() inky....
def __changeState(self, newState): self.__state = newState self.__justChangedState = True def __resetGameGUI(self): for buttonDict in self.__GameButtons: buttonDict["Object"].buttonColor = ColorEnums.TILE_ORANGE buttonDict["Object"].beText(self.__tilefont, "") # if the player hit Quit, there are rema...
This method initializes a new game by resetting the game state, updating the GUI, and creating a MainService instance. If the human does not start first, it triggers the AI's initial move and updates the game tiles accordingly.
def __startGame(self, HumanStarts: bool): self.__gameState = "" self.__changeState("Game") self.__resetGameGUI() self.__service = MainService.MainServiceClass() if not HumanStarts: self.__service.AIFirstMove() self.__updateAllTiles()
def parse_data(): data = httpx.get(ITEM_URL).json() collections = {} items = {} for long_code, name in data.items(): col_item_code, _, attrib = long_code.partition('.') if attrib != 'name': continue col_code = col_item_code.split('_', 1)[0] try: ...
The main task of the code is to retrieve an item by name from a dataset, optionally filtered by a specified collection. It parses data into collections and items, filters items by collection if provided, and then searches for a matching item name using a guessing mechanism.
def get_item(item_name, collection_name=None): collections, items = parse_data() if collection_name: items = items_for_collection(collection_name, items) return guess_by_name(item_name, items)
def process_create_events(date: str) -> None: table_name = "create_events" cols_to_drop = ["data", "event", "on"] cols_renaming_map = { "at": "created_at", "id": "operating_period_id", } cols_to_dt = ["created_at", "start", "finish"] _raw_to_stg_etl("create", table_name, date, co...
This function routes event processing by delegating to specific handlers based on the provided event_type. It logs the event type and date, then calls corresponding functions for 'create', 'delete', 'deregister', 'register', or 'update' events. If an unrecognized event_type is provided, it raises a ValueError to indica...
def process_events(event_type: str, **context): """router for event processing Args: event_type (str): type of event Raises: ValueError: In case event type passed is not defined """ date = context["ds"] logging.info(f"Processing {event_type} events from {date}") if event_ty...
def parameter_generation(): p,q = generatepq() # print("Prime divisor(q) : ",q) # print("Prime modulus(p) : ",p) flag=True while(flag): h = random.randint(1,p-1) if(1<h<(p-1)): g=1 while(g==1): g=pow(h,int((p-1)/q))%p flag=False ...
The code generates a digital signature for a given text using a cryptographic algorithm. It computes parameters, derives keys, hashes the input text, and iteratively calculates signature components 'r' and 's' via modular arithmetic until valid non-zero values are obtained. The function returns the signature along with...
def signature(text): global keys global parameters parameters = parameter_generation() keys = gen_keys(parameters[0],parameters[1],parameters[2]) p, q, g, x = parameters[0],parameters[1],parameters[2],keys[0] hash = hash_function(text) r,s=0,0 while(not s or not r): k=random...
def get_lines_and_word(ls, params) -> Tuple[List[str], str]: return (get_lines(ls, params), get_word(ls, params)) def complete_need_link( ls, params: CompletionParams, lines: List[str], line: str, word: str ): # specify the need type, e.g., # ->req if word.count(">") == 1: return CompletionL...
This function provides code completion by analyzing input context. It checks if a list needs initialization, extracts lines and words from parameters, and triggers specific completion logic based on word prefixes: "→" for need links, ":" for roles/options, and ".." for directives. If conditions aren't met, it returns a...
def completions(ls, params: CompletionParams = None): """Returns completion items.""" if not ls.needs_store.needs_initialized: return [] lines, word = get_lines_and_word(ls, params) line_number = params.position.line if line_number >= len(lines): ls.show_message_log( f"...
def _get_session(self, sess=None): """Restore parameters if no session given.""" if sess is None: sess = tf.Session(graph=self.graph) filename = tf.train.latest_checkpoint(self._get_path('checkpoints')) self.op_saver.restore(sess, filename) K.set_session(sess)...
The code trains a neural network model using training data and targets, with optional validation. It supports masking L1 regularization, which plots mask weights each epoch. Training includes early stopping based on validation loss, checkpoint saving, and evaluation metrics. The function handles both initialization and...
def fit(self, train_data, train_targets, val_data = None, val_targets = None, continue_training = False, train_cova = None, val_cova = None): """ Training time. train_data: size N1 x M x (H+1) N1: number of signals (samples) in training set M: number of vertices (feature...
def load_chat_history(): with shelve.open("chat_history") as db: return db.get("messages", []) def get_response(intents_list, intents_json): tag = intents_list[0]['intent'] list_of_intents = intents_json['intents'] for i in list_of_intents: if i['tag'] == tag: result = random...
This code manages a chat interface with persistent history. It loads chat messages, displays them with user/bot avatars, handles user input, generates responses, and updates session state. It also applies CSS for a sticky header and saves updated chat history after each interaction.
def main(): if "messages" not in st.session_state: st.session_state.messages = load_chat_history() header = st.container() header.title("Parkit") header.write("""<div class='fixed-header'/>""", unsafe_allow_html=True) st.markdown( """ <style> div[data-testid="stVerticalBloc...
def negamax_captures(board: chess.Board, alpha: float, beta: float) -> float: v = calc_eval(board) if board.turn else -calc_eval(board) if v > beta: return beta alpha = max(alpha, v) for move in ordered_moves(board, only_captures=True): board.push(move) v = -negamax_capture...
The code implements the negamax algorithm with alpha-beta pruning and a transposition table to evaluate chess positions. It recursively explores possible moves, updates the best score (v), and uses the transposition table to store/exclude results for efficiency. The function returns the optimal score for the current pl...
def negamax(board: chess.Board, depth: int, alpha: float, beta: float, tt: TranspositionTable = None) -> float: if tt is not None: hashcode = hash(board._transposition_key()) alpha_org = alpha tt_entry = tt.get(hashcode) if tt_entry is not None and tt_entry.depth >= dept...
def print_board(board: list): for index, row in enumerate(board): print(" | ".join(row)) if index != 2: print("-" * 9) def decide_move(board: list, player_symbol: str, exploitation_rate: float, q_values: dict): key = create_key(board, player_symbol) try: if np.random.rand...
The main task of the code is to simulate a player's move on a game board using Q-values for decision-making. It prints the original board, determines the optimal move via exploitation (no exploration), updates the board, retrieves and displays the corresponding Q-value, and prints the modified board state. The function...
def test_board(board: list, player_symbol: str, q_values: dict): copy_board = copy.deepcopy(board) print_board(board) row, col = decide_move(board=board, player_symbol=player_symbol, exploitation_rate=1, q_values=q_values) place_player_move(board=board, player_symbol=player_symbol, col=col, row=row) ...
def draw_box(fp, ax, color="b"): fp.seek(0) row = fp.readline() while row: row = fp.readline() xrect, yrect = [], [] while row and row[0]!="#": ca, a, cb, b, score = row.split() xrect.append(int(a)), yrect.append(int(b)) row = fp.readline() ...
This code generates a dot plot visualizing genomic alignment data from two BED files (qbed and sbed) against a QA file, plotting positions as scatter points. It labels chromosomes, adjusts axes scales, formats labels with LaTeX, and saves the resulting image. The plot includes chromosome breaks as green lines and genom...
def dotplot(qa_file, qbed, sbed, image_name, bpscale=False, remove=None): qa = Raw(qa_file) qa_fh = file(qa_file) fig = plt.figure(1,(8,8)) root = fig.add_axes([0,0,1,1]) # the whole canvas ax = fig.add_axes([.1,.1,.8,.8]) # the dot plot # the boxes surrounding each cluster draw_box(qa_fh...
def pretty_timestamp(t=None, style=0): if t is None: t = time.localtime() if style == 0: return time.strftime("%Y-%m-%d", t) else: return time.strftime("%Y%m%d%H%M%S", t) def column_help(keyword_width=10, total_width=70): help = [] for entry in PS_FIELD_HELP: desc = t...
The main task of the code is to create a command-line interface (CLI) tool for monitoring and profiling process resource usage. It allows users to track processes by PID, command, or memory usage, execute commands while logging their output, and customize output formatting, logging, and polling intervals. The tool supp...
def main(): """ Main CLI handler. """ default_title = "syrupy_" + pretty_timestamp(style=1) parser = OptionParser(usage=_program_usage, add_help_option=True, version=_program_version, description=_program_description) parser.add_option('-q', '--quiet', ...
def solve(grid, n_rows, n_cols): ''' Solve function for Sudoku coursework. Comment out one of the lines below to either use the random or recursive solver ''' # return random_solve(grid, n_rows, n_cols) return recursive_solve(grid, n_rows, n_cols) def show_solution(solutions): for data in s...
The code tests a grid-solving function by iterating through multiple grids, solving each one, timing the solution, verifying correctness, and awarding points. It prints progress, solution details, and results, accumulating 10 points per correct grid. The test script evaluates both the accuracy and efficiency of the sol...
def test(): points = 0 print("Running test script for coursework 1") print("====================================") for (i, (grid, n_rows, n_cols)) in enumerate(grids): print("Solving grid: %d" % (i+1)) start_time = time.time() solution = solve(grid, n_rows, n_cols) ela...
def keep_delete_single(grid, n_rows, n_cols): flag = True new_grid = copy.deepcopy(grid) while flag: alternative_grid = convert_grid(new_grid, n_rows, n_cols) #show_solution(alternative_grid) new_grid, flag = delete_single_possible(new_grid, alternative_grid) #show_solution(n...
The function `recursive_solve_alternative` solves a grid puzzle recursively using backtracking. It searches for empty cells, tries possible values, and validates solutions. If a valid solution is found, it returns the solved grid; otherwise, it returns `None`. The algorithm explores all possibilities systematically, ba...
def recursive_solve_alternative(grid, n_rows, n_cols): ''' This function uses recursion to exhaustively search all possible solutions to a grid until the solution is found args: grid, n_rows, n_cols return: A solved grid (as a nested list), or None ''' grid = keep_delete_single(grid, n_rows...
def keep_delete_single(grid, n_rows, n_cols, max_hint=-1, explain=False, output=sys.stdout): ''' keep deleting the single possible locations grid: the original grid n_row: the row number n_cols: the col number max_hint: max of the hint explain: if need to provide inst...
The code implements a recursive backtracking algorithm to solve a grid puzzle by exhaustively trying possible values in cells with the fewest options. It selects cells with the smallest number of possibilities, tests each value, and recursively checks if a solution is valid. If a value leads to a contradiction, it back...
def alternative_solve(grid, n_rows, n_cols, max_hint=-1, explain=False, output=sys.stdout): ''' This function uses recursion to exhaustively search all possible solutions to a grid until the solution is found args: grid, n_rows, n_cols,max_hint,explain,output return:...
def recursive_solve(puzzle, r, c, max_hint=-1, explain=False, output=sys.stdout): # puzzle is the list of lists where each innner list is a row in the puzzle # return whether solutin exists # mutates puzzle if solution exists # step1: choose somewhere on the puzzle to make a guess ...
The main task of the code is to compare the performance of two Sudoku solvers (recursive and alternative) by measuring their runtimes on multiple grids. It records execution times for each solver, verifies solution correctness, and generates a plot visualizing the comparison. The results are saved as "profile.png" and ...
def run_profile(): used_times = dict() used_times["recursive"] = [] used_times["alternative"] = [] grids2 = copy.deepcopy(grids) # calculate the recursive solver running time for (i, (grid, n_rows, n_cols)) in enumerate(grids): # print("Solving grid: %d" % (i+1)) start_time = ti...
def run_profile(): used_times = dict() used_times["recursive"] = [] used_times["alternative"] = [] grids2 = copy.deepcopy(grids) # calculate the recursive solver running time for (i, (grid, n_rows, n_cols)) in enumerate(grids): # print("Solving grid: %d" % (i+1)) start_time = ti...
The main task of the code is to parse command-line arguments, read a grid from an input file if specified, determine grid dimensions, solve the grid using a solver function, and output the solution to a file or console based on flags like `-explain`, `-hint`, and `-profile`.
def main(): # add the arguments parser parser = argparse.ArgumentParser() parser.add_argument("-file", dest="file", nargs=2) parser.add_argument("-hint", dest="hint", type=int) parser.add_argument("-explain", dest="explain", action="store_true", default=False) parser.add_...
def get_lenet_like_embedder( input_shape, act='elu', l2_reg=1e-3, filter_sz=5, num_filters=24, num_dense_neurons=512, ): """ Returns a 2-tuple of (input, embedding_layer) that can later be used to create a model that builds on top of the embedding_layer. """ x = inp = Input(input_shape) ...
The code trains a neural network model for a control system (e.g., autonomous driving), using dynamic weight calculation, custom loss functions, and early stopping. It processes training data in episodes, evaluates model performance on test data, saves checkpoints, and retains the best model based on validation error. ...
def main(): argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument( '-p', '--patience', default=100, type=int, dest='patience', help='Early stopping patience') argparser.add_argument( '-r', '--results_dir', default=dt.today().s...
def _get_categorical(self, df): one_hot_encoded_columns = [] for column in df.columns: unique_values = df[column].dropna().unique() if set(unique_values).issubset({0, 1}) and len(unique_values) == 2: one_hot_encoded_columns.append(column) ret...
The code trains a model using either edited or condensed k-nearest neighbors (KNN) based on the specified method. It first adds the target variable to the input data, identifies categorical columns for encoding, and then applies the chosen KNN variant (edited or condensed) to generate the training dataset. If no method...
def fit(self, X, y): X['target'] = y self.one_hot_encoded_columns = self._get_categorical(X) if self.method == "edited": self.train_df = self.edited_k_nearest_neighbors(X, self.k, self.task, self.epsilon, self.gamma) elif self.method == "condensed": self.train_df ...
def set_state(self, state: GoalState): if state not in GoalState: raise ValueError('Not a valid state was given') self._state = state self._report_state() def on_enter(self): pass def run_until_exit(self): ts_start = time.time() while self._state not in (GoalS...
The main task of the code is to execute a goal's entry process by transitioning its state to RUNNING, invoking entry actions, running until completion, logging the exit status, and returning the final state. It tracks the goal's status as completed or not, updates internal state variables, and provides feedback through...
def enter(self): print(f'Entering Goal <{self._name}:{self.__class__.__name__}>') self.set_state(GoalState.RUNNING) self.on_enter() self.run_until_exit() status = 1 if self.state == GoalState.COMPLETED else 0 print(f'Goal <{self._name}:{self.__class__.__name__}>' + \ ...
def equivalentPrimeIdeal(self, I, banned = []): r"""Given an integral ideal I, outputs a small (< p^(1/1.8)) prime-normed ideal in [I] If no such ideal is found, returns the smallest one found (with a warning) """ verbose(f"trying to find of log(N) < (1/1.8)log(p) = {((1/1.8)*log(self.p,...
The code computes an equivalent left ideal J of an input ideal I, such that the norm of J divides a specified target norm T (or is minimized for isogeny translation cost if T is not provided). It iteratively finds suitable ideals, applies norm constraints, and returns the adjusted ideal along with parameters for furthe...
def KLPT(self, I, T=None, returnElem=False, variant=None): r""" Given an integral ideal I, and a target norm T, outputs an equivalent left ideal J~I, with nrd(J) dividing T. If target norm T is not given, T will be chosen to minimize the cost of translating J to its correspondin...
def cost_model(p, newconst=None): r""" Given a prime characteristic p, return a function in two arguments l^e and k which roughly describes the cost of the Deuring algorithm when using l^e-torsion in GF(p^(2k)). """ logp = p.log(2).n() loglogp = logp.log(2).n() log3 = log(3,2).n() #...
The function `choose_torsion` greedily selects pairs $(l^e, k)$ to minimize the cost of the Deuring algorithm for given parameters $p, q, N$, using a cost model. It iteratively identifies valid $l$ values (checking pseudoprimes and divisibility), computes their multiplicative orders, and updates the dictionary `facToEx...
def choose_torsion(p, q, N, lowbound, newconst=None): r""" Given p,q,N as in the Deuring correspondence, greedily find a set of pairs (l^e,k) for the specific characteristic which minimize the cost of the Deuring algorithm according to the cost_model(). """ facToExt = dict() # establish a b...
def double_dead_end_edges(graph): single_vertices = graph.get_single_vertices() edges_to_double = [] for v in single_vertices: for src, dst, dist in graph.edges: if v in (src, dst): edges_to_double.append((src, dst, dist)) graph.add_edges(list(set(edges_to_double)))...
The function converts a given graph into an Eulerian graph by doubling edges at dead ends for undirected graphs and adding minimum path edges to ensure connectivity and balance in degrees, enabling an Eulerian trail or circuit.
def make_eulerian_graph(graph): if not graph.directed: double_dead_end_edges(graph) return add_min_path_edges(graph, find_minimum_path(graph))
def parse_uid(href): n = len(href) for i in range(n): if (href[n-1-i] == '-'): return href[n-i:n] def write_html(filename, data, pk): output = open(filename, 'w', encoding='utf-8') output.write(data.content.decode('utf-8')) output.close() def parse_comment(page, uid, pk, url): ...
The function `parse` fetches a webpage using the provided URL (`href`), caches its HTML content, extracts comment data, and parses article information if comments exist. It uses `pk` for caching and `uid` derived from `href` or provided `id` to organize files. The task involves web scraping, caching, and data extractio...
def parse(href, pk, id=None): if not id: uid = parse_uid(href) else: uid = id try: page = requests.get(href, allow_redirects=True, timeout=1) except: return write_html('cache/html/'+str(pk//1000)+'/'+str(pk)+"_"+ str(uid) +".html", page, pk) count = parse_comment(...
def _init_db_schemas(): """Table to store columns data.""" if 'columns_data' in [table[0] for table in _get_list_of_tables()]: return session = get_db_session() session.execute( "CREATE TABLE columns_data (table_name text, column_name text, type text, min text, max text);" ) def _cr...
The main task of the code is to initialize database schemas, create table structures, save data for each table in the provided `DataBase` object, and commit the changes to a database session. It ensures proper setup and persistence of database tables and their associated data.
def save_data_base(db: DataBase): _init_db_schemas() for table in db.tables: _create_table_schema(table) _save_table_data(table) session = get_db_session() session.commit()
def preprocessing(df): """ preprocess data and remove unnecessary columns, remove null and undefined values, and normalize the dataset. @param df: dataset as dataframe pandas """ # drop unnecessary cols/attributes attributes = df.columns.tolist() if 'Date' in attributes: df...
The main task of the code is to generate an epsilon graph for determining the epsilon parameter in clustering algorithms. It reads and filters data, computes nearest neighbor distances, sorts them in descending order, and plots the sorted distances to visualize the epsilon threshold for clustering. The plot is saved as...
def plot_epsilon_graph(): """ plot an epsilon graph @return: list of cluster labels """ warnings.filterwarnings("ignore") df = pd.read_csv('houshold2007.csv') df = df[df['Date'].apply(lambda x: x.endswith('1/2007'))] preprocessing(df) attributes = df.columns.tolist() data = d...
def save_exported_data(self): with open("exported_data.json", "w") as json_file: json.dump(self.data, json_file) self.execution_option_reload() def display_message(self,message): def inner_separator(widget,separator_object,middle_object): # Get the font size used in the t...
This method deletes a selected action set from the data dictionary, saves the updated data, clears the selection, reloads the UI, and displays a confirmation message if the action set exists. If not found, it notifies the user.
def delete_action_set(self): self.selected_name = self.import_name_var.get() if self.selected_name in self.data: del self.data[self.selected_name] self.save_exported_data() self.display_message(f"Deleted action set '{self.selected_name}'") # Clear the name...
def check_data_for_export(self): fault_list = [] i = 0 for key, value in self.current_actions_nested_list: i += 1 if key == "Sleep": if re.match(r'^\s*-?\d+(\.\d+)?\s*$',value): continue else: self.d...
This function collects user input from comboboxes and entries into a structured list, associates it with a name, validates data, stores it in a dictionary, displays confirmation, and closes the window. If no name is provided, it prompts the user to enter one.
def save_action_set(self): self.current_actions_nested_list = [] for each in range(len(self.action_type_comboboxes)): action_type = self.action_type_comboboxes[each].get() action_value = self.action_value_entries[each].get() self.current_actions_nested_list.append((ac...
def simplify_actions(self, actions, time_threshold=0.5): simplified_actions = [] i = 0 while i < len(actions): action, value = actions[i] try: action_prefix = action.split()[0] action_suffix = action.split()[1] if len(action.split()) > 1 el...
The function processes recorded data by simplifying it, prepends a 'Hotkey' entry, timestamps the data, stores it in a dictionary, displays a confirmation message, and triggers export and reload operations to update the data structure.
def save_recorded_set(self): self.recorded_data = self.simplify_actions(self.recorded_data) self.recorded_data.insert(0, ['Hotkey', 'space']) name = f"recorded_set_{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" self.data[name] = self.recorded_data self.display_message(f...
def name(): key_name = input("Enter the product name: ") New_name = input("Insert new name of the product: ") for product in products: if product["name"] == key_name: product["name"] = New_name print(product) print("The operation was successful") show_...
The code defines a function `edit()` that prompts the user to select an option (1-3) to edit either 'name', 'price', or 'count'. Based on the input, it calls corresponding functions `name()`, `price()`, or `count()` to handle the specific edit task.
def edit(): a = input("what do you want to edit: ") print("1- name", "2- price: ", "3- count: ") if a == "1": name() elif a == "2": price() if a == "3": count()
def _replace_fp_forward(self, model: torch.nn.Module) -> None: for _, m in model.named_modules(): if isinstance(m, BaseGroupedFeatureProcessor): self._context.feature_processor_forwards.append(m.forward) # pyre-ignore[8]: Incompatible attribute type m....
This code establishes asynchronous data and model pipeline connections for distributed training. It processes two consecutive batches using CUDA streams, replaces the model's forward method, rewrites the model for data distribution, and initializes pipeline modules to enable overlapping data transfer with computation. ...
def _connect(self, dataloader_iter: Iterator[In]) -> None: self._replace_fp_forward(cast(torch.nn.Module, self._model.module)) # batch 1 with torch.cuda.stream(self._memcpy_stream): batch_i = next(dataloader_iter) self._batch_i = batch_i = _to_device( batc...
def _connect(self, dataloader_iter: Iterator[In]) -> None: self._replace_fp_forward(cast(torch.nn.Module, self._model.module)) # batch 1 with torch.cuda.stream(self._memcpy_stream): batch_i = next(dataloader_iter) self._batch_i = batch_i = _to_device( batc...
The code's main task is to process a batch through a model's forward pass, manage data distribution (especially for sparse data), and execute training steps (backward pass and optimizer update) with detailed timing measurements. It handles GPU data transfer, stream synchronization, gradient zeroing, and model updates, ...
def progress(self, dataloader_iter: Iterator[In], zero_grad_start, zero_grad_stop, copy_batch_to_gpu_start, copy_batch_to_gpu_stop, wait_for_batch_start, wait_for_batch_stop, f...
def execute_begin(self, operation): """ Initialize operation for manipulate :param operation: specific data from operations. :return: True or False """ tid = operation.get_tid() time_stamp = operation.get_time() self.transactions[tid] = Transaction(tid, t...
The main task of the code is to route operations to corresponding execution methods based on their type. It checks the operation's type and calls functions like execute_begin, execute_write, execute_read, etc., passing parameters such as `is_retry` where relevant, to handle tasks like transaction initiation, data modif...
def assign_task(self, operation, is_retry=False): if OperationType.BEGIN == operation.get_type(): return self.execute_begin(operation) elif OperationType.BEGINRO == operation.get_type(): return self.execute_begin_read_only(operation) elif OperationType.WRITE == operation....
def retry(self): """ retry blocked operations :return: None """ blocked_list = [] blocked_trans = set() for op in self.waiting_list: if not self.assign_task(op, True): blocked_list.append(op) if op.get_type() == Operati...
The main task of the code is to process a new operation by retrying it, assigning it to a task, and handling failures by queuing the operation. It also detects deadlocks in the wait-for graph and aborts the youngest transaction involved in a deadlock cycle to resolve it.
def execute_operation(self, operations): """ Process the new operation :param operations: new operation :return: None """ # retry self.retry() is_succeed = self.assign_task(operations) if not is_succeed: self.waiting_list.append(operat...
def get_score(self, board): score = 0 for row in board: for piece in row: if piece is not None: score += piece.value if piece.color else -piece.value return score def in_check(self): king = self.find(self.board, "king", self.whites_tu...
This method prints the current game state in chess, including move history, turn, piece score, check/checkmate/stalemate status, en passant availability, castle rights, and available moves.
def print_info(self): turn = "white" if self.whites_turn else "black" score = str(self.get_score(self.board)) check = "True" if self.in_check() else "False" checkmate = "True" if self.checkmate() else "False" stalemate = "True" if self.stalemate() else "False" print("---...
def board_changed(self): """ Checks if board changed (Someone moved) Returns: (bool) """ if self.move_history_lenght != len(self.move_history): self.move_history_lenght = len(self.move_history) return True return False def g...
The method `update` checks if the board has changed; if so, it updates the board's moves by calling `get_moves` and prints information via `print_info` to reflect the current state.
def update(self): if self.board_changed(): self.board_moves = self.get_moves() self.print_info()
def drawHead(self, app): self.newX, self.newY = self.getRealTime3DLocation(app) x = self.x y = self.y newX = self.newX newY = self.newY width = self.size height = self.size # hitbox self.headCoordinates = self.hitboxPolygon(x, y, newX, newY, widt...
The code draws a human figure (head, arms, body, legs) in different orientations based on the target's quadrant position relative to the background's center. It changes the drawing order of limbs depending on whether the target is in the upper or lower half of the background area.
def draw(self, app): cx = app.bg.LeftTopX + app.bg.rectWidth / 2 cy = app.bg.LeftTopY + app.bg.rectHeight / 2 # Middle of the target x = self.x + self.size / 2 y = self.y + self.size / 2 # first quadrant or second quadrant if (x > cx and y < cy) or (x < cx and ...
def readInput(): text_file = open("input.txt", "r") lines = text_file.readlines() input = [] for line in lines: com = {} i = line.strip().split(" = ") if i[0] == "mask": com["command"] = i[0] else: com["command"] = int(i[0][4:-1]) com["val"...
The code processes a list of commands to update memory values with a mask applied. It reads input, applies the mask to values, stores them in memory, and sums all memory values for output.
def main(): input = readInput() mem = {} mask = "" for com in input: if com["command"] == "mask": mask = com["val"] else: for addr in getAddresses([applyMask(valTo36(com["command"]),mask)]): mem[valToDec(addr)] = int(com["val"]) sum = 0 for...
def readInput(): text_file = open("input.txt", "r") lines = text_file.readlines() input = [] for line in lines: com = {} i = line.strip().split(" = ") com["command"] = i[0] com["val"] = i[1] input.append(com) text_file.close() return input def valToDec(val...
The main task of the code is to process a list of memory commands and a mask, apply the mask to memory values, convert them to decimal, store them in a dictionary, and finally compute and print the sum of all stored values.
def main(): input = readInput() #print(input) mem = {} mask = "" #print(valToDec(valTo36(73))) #print(applyMask("000000000000000000000000000001100101","XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")) for com in input: if com["command"] == "mask": mask = com["val"] else: ...
def is_session_active(self, pkt): return True def is_source_host(self): return self.source_host def get_vIP(self, ip): self.clear_mapping_after_interval(ip) if self.rIP_to_vIP[ip]: return self.rIP_to_vIP[ip] else: return self.generate_vIP(ip)
The function encodes a packet by modifying its source IP address if it's not from the source host, using a virtual IP mapping. It checks for IP presence, validates session activity, updates the source IP, removes the checksum, and returns the modified packet. If IP is missing or mapping fails, it logs errors and return...
def encode_packet(self, pkt): if IP in pkt: logging.debug("[encode] Received packet from " + pkt[IP].src + " to " + pkt[IP].dst) else: logging.debug("[encode] Received packet with no IP!") return False if not self.is_session_active(pkt): pass ...
def tf_inference(model, loader): track_ids = loader.track_ids tracks_embeds = model.predict(loader) embeds = {k: v for k, v in zip(track_ids, tracks_embeds)} return embeds def get_ranked_list(embeds, top_size=100, annoy_num_trees=128, annoy_metric="angular"): annoy_index = None annoy2id = [] ...
The code evaluates a model's performance on a validation set by computing Normalized Discounted Cumulative Gain (NDCG). It processes input data using a configured image loader, generates embeddings via the model, ranks them using Annoy with specified metrics, and calculates NDCG for the top 100 results. The result quan...
def compute_val_dcg(model, df, cfg, annoy_metric="angular"): features_loader = TestLoader( df=df, data_loader=ImageLoader( target_size=cfg.img_size, augment=False, center_crop=cfg.center_crop, norm=cfg.norm, n_channels=cfg.n_channels, ...
def update_val(self, B=[], alpha_g=None, beta_g=None, alpha_e=None, beta_e=None, f=None, lambda_g=None, lambda_e=None, ups_gx=None, ups_gy=None, ups_ex=None, ups_ey=None, Delta_eg=None): """ This function updates all values in the full, ground, and excited Hamiltonians you specify. If...
The function `optimize_this` calculates a combined error metric by comparing simulated transitions and branching ratios against measured data, aiming to optimize parameters (alpha_g, beta_g, alpha_e, beta_e). It computes transition error via squared differences between simulated and measured transitions, and branching ...
def optimize_this(x): self.update_val(alpha_g=x[0], beta_g=x[1], alpha_e=x[2], beta_e=x[3]) transitions = self.sweep_B_field_transitions(B_tr, frozen=True, plot=False) transitions.sort(axis=0) tr_error = np.sum(np.sum(np.square(transitions-measured_transitions))) ...
def get_moves(filename): input_content = get_input(filename) els = input_content.split() directions = els[::2] lengths = [int(x) for x in els[1::2]] return list(zip(directions, lengths)) def get_unique_places(head_position, tail_position, moves): head_visited_places = get_head_positions(head_pos...
Your returnThe code's main task is to calculate the number of unique positions visited by a rope's tail during movement simulations. Part 1 tracks a single tail, while Part 2 extends this to a 9-segment rope, outputting the count of unique positions for the last tail. It reads movement instructions from a file, process...
def main(): moves = get_moves(inputFile) h = (0, 0) t = (0, 0) # part 1 res1 = get_unique_places(h, t, moves) print(res1) # part 2 res2 = get_positions_for_last_tail(h, t, 9, moves) print(len(set(res2)))
def next_arg(self) -> str: try: self.current_arg = next(self._args_iter) except StopIteration: self.current_arg = None def parse_argument(self, argument: CompilerArgument): self.parse_action(argument.action) def parse_option(self, option: CompilerOption): if isins...
This function parses command-line arguments by iterating through them, handling options, subcommands, and positional arguments. It processes arguments until encountering "--", which terminates option parsing. It identifies subcommands, parses options, and handles remaining arguments, ultimately returning the next subco...
def parse_command(self): end_opts = False iter_compiler_arg = iter(self.compiler_command.arguments) next_command = None self.next_arg() while self.current_arg: if self.current_arg == "--": end_opts = True self.next_arg() i...
def R_check_maneu(distance): right_turn() forward(distance) left_turn() time.sleep(2) def Lidar(): ser.flushOutput() ser.flushInput() time.sleep(0.1) while(ser.in_waiting >= 9): if(('Y' == ser.read()) and ('Y' == ser.read())): Dist_L = ser.read() Dist_H =...
The code performs path planning for a vehicle, using Lidar to check for obstacles. It attempts forward movement, right turns, and location-specific maneuvers (e.g., `goto_location`). If obstacles persist after multiple checks, it lands; otherwise, it switches the vehicle to "AUTO" mode. The loop retries up to 6 times b...
def path_planning(brake_location): global end, pp_code fwd_time = 7 #7s location_travel_time = 5 #5s count = 0 clear = 0 while ((count<6) and (not clear)): print( "path planning algo count = ",count) if(count<3): R_check_maneu(fwd_time) if(Lidar()>thr_di...
def arm_and_takeoff(aTargetAltitude): print ("Basic pre-arm checks") while not vehicle.is_armable: print (" Waiting for vehicle to initialise...") time.sleep(1) print( "Arming motors") vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True while not vehicle.armed: pr...
The main task of the code is to control a drone for autonomous navigation using Lidar obstacle detection. It initializes the drone, takes off, and continuously monitors distance. If an obstacle is within 20 units, the drone switches to BRAKE mode, halts until velocity nears zero, then resumes GUIDED mode with path plan...
def main(): print('Starting main program') global pp_code, end, clear, thr_dist thr_dist = 20 end = 0 distance = 0 pp_code = 0 cmds = vehicle.commands cmds.clear() vehicle.flush() arm_and_takeoff(5) while (not end and vehicle.location.global_relative_frame.a...
def fetch_video_info(url): """Fetches the information of a given YouTube video URL.""" video_id = re.search(r"(?<=v=)[^&#]+", url) if not video_id: raise ValueError("Invalid YouTube URL") video_id = video_id.group(0) youtube = build('youtube', 'v3', developerKey=os.environ["GOOGLE_API_K...
The code's main task is to fetch and format chapter data from a YouTube video using Google's API, then print the formatted chapters. It retrieves video information, extracts chapter details, processes them into a structured format, and outputs the result.
def main(): openai_api_key = os.getenv(OPENAI_API_KEY_ENV, 'Your OpenAI API Key Here') google_api_key = os.getenv(GOOGLE_API_KEY_ENV, 'Your Google API Key Here') youtube_video_url = 'https://www.youtube.com/watch?v=KopLe5NZBJc' # This can also be passed as an argument or read from a config file vi...
def create_loss_func(self, betas, sigmas, args, reg, orig_risk, environments): w0 = torch.ones(betas[0].size(0), 1) w0.requires_grad = True def get_loss(phi, w=w0): error = 0; penalty = 0; err = 0 if "popul" in args["method_reg"]: # population risk minimi...
This code initializes a model by optimizing parameters using empirical risk minimization or population-based methods. It iterates over regularization strengths, trains models with different loss functions, evaluates validation errors, and retains the best parameters (weights, betas) and gradients. The method selects th...
def __init__(self, environments, args, orders=None, betas = None, orig_risk=False, sigmas=None): best_reg = 0; env = [] best_err = float('inf') population = "popul" in args["method_reg"] if population != True: # train from data - empricial risk minimization envir...
def eval_boolean_logic(p): global env # print(f'here: {p}') if type(p) == tuple: if p[0] == ">": return eval_boolean_logic(p[1]) > eval_boolean_logic(p[2]) elif p[0] == "<": return eval_boolean_logic(p[1]) < eval_boolean_logic(p[2]) elif p[0] == ">=": ...
The `eval_print` function evaluates and returns string representations of values based on the structure of input `p`, using a global environment `env`. It handles different data types (`struct`, `str`, `exp`, `type`), retrieves values from `env`, evaluates expressions, and processes errors. For `struct`, it accesses ne...
def eval_print(p): global env try: if p[3] == 'last': value = "" if p[1] == 'struct': if p[2][0] in env: temp_dict = env[p[2][0]] # print(f'temp_dict: {temp_dict}') # print(f'p[2][1]: {p[2][1]}') ...
def eval_exp(p): global env if type(p) == tuple: if p[0] == "+": return eval_exp(p[1]) + eval_exp(p[2]) elif p[0] == "-": return eval_exp(p[1]) - eval_exp(p[2]) elif p[0] == "*": return eval_exp(p[1]) * eval_exp(p[2]) elif p[0] == "/": ...
The code evaluates a variable assignment by checking the type of the value against the declared type (int, double, bool, char, string), ensuring no redeclaration, and storing the variable in the environment if valid. It uses specific evaluation functions for each type and prints errors for type mismatches or redeclarat...
def eval_assignment(p): global env item = p[0] value = eval_exp(p[1][2]) if item == "int": if type(value) == int: if p[1][0] == "=": if p[1][1] in env: print("Redeclaration error") else: env[p[1][1]] = ('...
def eval_print(p): global env try: if p[3] == 'last': value = "" if p[1] == 'struct': if p[2][0] in env: temp_dict = env[p[2][0]] # print(f'temp_dict: {temp_dict}') # print(f'p[2][1]: {p[2][1]}') ...
This function evaluates and executes operations based on the type of input `p`. If `p` starts with 'print', it evaluates and prints the result, exiting on errors. For "++" or "--", it handles increment/decrement operations. Otherwise, it processes assignments. The function uses global environment `env` for variable man...
def eval_assignment_and_print(p): global env if p[0] == 'print': value = eval_print(p) if value == 'TypeError': print(value) exit(1) else: print(value) elif p[0] == "++" or p[0] == "--": return eval_increment_decrement(p) else: ...
def eval_adding_struct_values(p): global temp if p[2] == 'last': if p[0] == 'bool': temp[p[1][1]] = ('bool', True) elif p[0] == 'int': temp[p[1][1]] = ('int', 0) elif p[0] == 'double': temp[p[1][1]] = ('double', 0.0) elif p[0] == 'string': ...
The code evaluates and executes statements in a structured programming language, handling assignments, struct operations, and conditional logic. It modifies environment variables (`env`), manages struct definitions (`structs`), and processes `if-else` conditions by evaluating boolean expressions. The function supports ...
def eval_all_statement(p): global env global temp global structs if p[0] == 'assign_struct': # print('assign_struct') if p[1] in env: if p[2] in env[p[1]]: temp_dict = env[p[1]].copy() if type(p[4]) == bool: temp_dict[p[2]]...