dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _serialize(self, data): ''' coerces data into one of the allowed BSON types Input: raw function output data to be cached Returns: data with coerced format ''' data = self._coerce_bson_recursive(data) return data de...
The main task of the code is to query a MongoDB collection using provided arguments, process the retrieved document, check if it's within a defined "shelf life" based on its timestamp, and return the processed document if valid. If no document is found or data is stale, it returns None. Exceptions trigger cache disabli...
def _query(self,args): try: query = {key: self._serialize(val) for key, val in zip(self.key_names, args)} cursor = self.collection.find(query) docs = list(cursor) # self.logger(docs) if len(docs) > 0: document = self._process_query(do...
def download(self): """Download the VCTK data if it doesn't exist in processed_folder already.""" from six.moves import urllib import tarfile if self._check_exists(): return raw_abs_dir = os.path.join(self.root, self.raw_folder) processed_abs_dir = os.path.j...
This code initializes a dataset class by setting parameters like root directory, data transformations, and download flags. It checks if data exists, downloads if needed, reads metadata, and loads preprocessed data (data and labels) from a PyTorch file. The dataset is cached in chunks, with attributes like chunk size an...
def __init__(self, root, downsample=True, transform=None, target_transform=None, download=False, dev_mode=False): self.root = os.path.expanduser(root) self.downsample = downsample self.transform = transform self.target_transform = target_transform self.dev_mode = dev_mode ...
def clock(icon, fmt: str, fg: str = colors["fg"], sep: bool = True) -> list: return wrap_widgets(icon, modify(widget.Clock, **base(fg=fg), format=fmt), sep=sep) def icon_font(bg: str = colors["bg"], fg: str = colors["fg"]) -> dict: return base(font="Font Awesome 6 Free Solid", fontsize=12, padding=2, bg=bg, fg=...
The code initializes a list of widgets for a desktop environment, including clocks, system monitors (CPU, memory, network), audio, systray, and group management. It customizes widgets with icons and colors, conditionally adding battery info for laptops. The list is returned for use in a status bar or panel.
def init_widgets_list(show_systray=True): widgets = [] widgets.extend( clock( modify(widget.TextBox, **icon_font(fg=colors["yellow"]), text=" "), fmt="%A, %B %d", fg=colors["yellow"], ) ) widgets.extend(audio()) if show_systray: widgets.a...
def get_parameters(self, data, prefix=''): ret = {} if isinstance(data, list): if prefix: prefix += '.' i = 1 for value in data: ret.update(self.get_parameters(value, prefix + str(i))) ...
This code generates AWS4-signed HTTP requests for API calls, handling both GET/POST methods. It constructs canonical requests, computes hashes, creates authorization headers with date/credentials, and sends requests with proper signing parameters for AWS service interactions.
def make_request(self, call, *args, **kwargs): date = datetime.datetime.utcnow() self.amz_date = date.strftime('%Y%m%dT%H%M%SZ') self.datestamp = date.strftime('%Y%m%d') request_parameters = self.get_parameters(data=kwargs) request_parameters['Action'] = call if 'Version...
def reset(self, size): """ Creates a start state, an empty board with given size. """ self.size = size self.NS = size + 1 self.WE = 1 self.last_move = None self.current_player = BLACK self.maxpoint = size * size + 3 * (size + 1) self.board ...
The code initializes a 7x7 Gomoku board, resets its state, and precomputes row/column/diagonal structures and groups of 5-7 consecutive positions to analyze potential winning lines during gameplay.
def __init__(self, size): """ Creates a Go board of given size """ assert size == 7 self.reset(size) self.calculate_rows_cols_diags() self.calculate_five_in_a_row_groups() self.calculate_six_in_a_row_groups() self.calculate_seven_in_a_row_groups()
def getDir(self): if(self.change_x == self.maxSpeed): return "Right" elif(self.change_y == -self.maxSpeed): return "Up" elif(self.change_x == -self.maxSpeed): return "Left" else: return "Down" def findLeftBox(self, SQUARE_SIZE, SCREEN_WIDTH...
The AIAction function decides movement direction 75% of the time by checking adjacent grid cells for collisions with harmful or identical numbers, avoiding them by randomly choosing left/right if detected. Otherwise, it makes random movement choices to navigate the grid while avoiding potential collisions with specific...
def AIAction(self, GRID, SCREEN_WIDTH, SCREEN_HEIGHT, SQUARE_SIZE): if random.randint(0, 3) >= 1: #Makes a smart decision 75% of the time, otherwise random if(self.getDir() == "Left" and self.findLeftBox(SQUARE_SIZE, SCREEN_WIDTH, SCREEN_HEIGHT) != None): num = GRID[self.findLeftBox(...
def clearGrid(num): #Wipes the grid to whatever number given (0 is reset) global GRID for x in range(0, len(GRID)): for y in range(0, len(GRID[0])): GRID[x, y] = num def assignPlayer(): global PLAYER_CONTROLLED, PLAYER if(PLAYER_CONTROLLED == "RANDOM"): PLAYER = randomPl...
The code implements a game loop where players (including AI-controlled elements like lava, poison, acid, and water) move on a grid based on input controls (arrow keys or letters) and game mode (binary/quad). It handles player interactions, collision detection, elimination of players, explosion effects, and rendering th...
def gameScreen(): global GRID, SCREEN_WIDTH, SCREEN_HEIGHT, PLAYER_SPEED, PLAYER, CONTROL, MODE, FPS hasWinner = False explosionList = [] currentInterval = 1 clearGrid(0) assignPlayer() lava = Element(PLAYER_SPEED, 0, SCREEN_WIDTH/2 + SQUARE_SIZE, SCREEN_HEIGHT/2, PLAYER_SPEED, LAVA, "L...
def backgroundInputCheck(eventList): #Constantly checks for quits and enters for event in eventList: if event.type == pg.QUIT: quitGame() elif event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: return False elif event.key...
The main task of the code is to display a main menu screen with animated elemental characters (LAVA, POISON, ACID, WATER) that move and leave trails, while rendering interactive buttons for starting the game, accessing settings, instructions, credits, or quitting. The loop handles user input, updates game elements, and...
def mainScreen(): onMain = True p1 = Element(PLAYER_SPEED, 0, SCREEN_WIDTH/8, SCREEN_HEIGHT/4, PLAYER_SPEED, LAVA, "LAVA", ORANGE) #LAVA p2 = Element(0, -PLAYER_SPEED, SCREEN_WIDTH, SCREEN_HEIGHT/2, PLAYER_SPEED, POISON, "POISON", PURPLE) #POISON p3 = Element(-PLAYER_SPEED, 0, SCREEN_WIDTH/2 - SQUARE_SI...
def _reindex_cols(self, df): for p in self.paths: cols = [ c for c in pq.read_schema(p).names if not (c.startswith("__index") or c in df.index.names) ] union = df.columns.union(cols) if union.difference(cols).shape[0...
This function extends a dataset by appending or merging input data (pandas/dask DataFrame), managing locks for concurrency, handling grouped operations, and ensuring record count compliance with `max_records`. It uses Dask for parallel processing when needed, checks for missing records, and updates storage with proper ...
def extend( self, df: Union[pd.DataFrame, "dd.DataFrame"], missdic=None, try_dask=True, ): if self._ensure_cols: df = self._reindex_cols(df) if not isinstance(df, pd.DataFrame): assert self._get_client_address(True), f"{type(df)} needs dask" ...
def _gb_handle(self, df: Union[pd.DataFrame, "dd.DataFrame"], fun, **kwargs): _gb = df.groupby(self.group_cols) if not isinstance(df, pd.DataFrame): _gb.apply(self._gapply, fun, meta={}, **kwargs).compute() else: _gb.apply(self._gapply, fun, **kwargs) def _get_full_paths(...
This function replaces records in Parquet files using a DataFrame's index. If `by_groups` is True, it processes data grouped by predefined columns. Otherwise, it filters duplicate indices, reads each file, drops overlapping indices, and rewrites the updated data. It tracks missing records and extends the input DataFram...
def replace_records(self, df: Union[pd.DataFrame, "dd.DataFrame"], by_groups=False): """replace records in files based on index""" if by_groups: if self.group_cols is None: raise TypeError("only works if group cols is set") return self._gb_handle(df, self.replace_...
def get_bucket(model_name, dataset_name, mat_type, relations): global universal_node_ids folder_to_rules = "D:\PhD\Work\EmbeddingInterpretibility\RulePatterns\data\Experiments\Rules\\" rules1 = ParseRule( filename=f"{folder_to_rules}{mat_type}\\{dataset_name}\\{model_name}\\{dataset_name.lower()}_{...
The code evaluates two knowledge graph embedding models, ComplEx and TransE, on the WN18 dataset using a materialized approach. It retrieves base and augmented data buckets, maps relations to rules, and runs analysis functions to assess model performance by entity types and heads, comparing results for each model.
def t(): dataset_name = "WN18" mat_type = "Materialized" n_relations = 18 relations = [i for i in range(n_relations)] model_name = "ComplEx" base_bucket, augment_bucket, networkx_to_rule_mapping = get_bucket(model_name=model_name, dataset_name=dataset_name, ...
def get_tokenizer_model_path(vocab_size): """ Returns path to the sentencepiece tokenizer model for a given vocab size vocab_size = 0 designates the default Llama 2 tokenizer, in that case None is returned. """ if vocab_size == 0: return None else: return os.path.join(DATA_CA...
This function processes a data shard by filtering, transforming, and tokenizing examples using specified functions (filtering, mixing/matching, adversarial training, refusal). It encodes text into tokens, saves them as a binary file, and returns the proportion of data retained after filtering.
def process_shard(args, vocab_size, filtering, dataset_name, mix_match, adversarial_training, refusal, instruction_subset): shard_id, shard = args tokenizer_model = get_tokenizer_model_path(vocab_size) enc = Tokenizer(tokenizer_model) with open(shard, "r") as f: data = json.load(f) all_token...
def create_connection(self, ip, port): CONN_ADDR = (ip, port) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect(CONN_ADDR) return connection def ask_random_node(self, conn, address, port): # test_askRandMsg = Message().short_msg(commands.ASK_RAND...
The main task of the code is to connect a new node to a network by first contacting a genesis node, retrieving a random node's address, and then discovering adjacent nodes. It broadcasts a "JOINED_IN_NETWORK" message, requests node lists, and adds new nodes to its network list while handling connection failures or miss...
def join_network(self, ip=None, port=None): if ip == None: ip = self.GENESIS_NODE_ADDR if port == None: port = self.GENESIS_NODE_PORT print(f"{ip}{port}") conn = self.create_connection(ip, port) """ Genesis node will return a ip address of a ...
def ask_user_what_speaker() -> str: """ask user what speaker is being tested""" return display_options(option_enum_class=SpeakerOptions, message="for speaker section") def ask_user_off_axis() -> str: """asks the user what off-axis degree is being tested""" off_axis = display_options(option_enum_class=Of...
The main task of the code is to prompt the user to specify the speaker and off-axis parameters for a test, then generate a filename using these inputs. The function `get_user_options` calls two helper functions to collect user inputs and combines them into a structured filename via `set_output_file_name`, ensuring the ...
def get_user_options() -> str: """asks user to define the test and solves output file name""" speaker: str = ask_user_what_speaker() off_axis: str = ask_user_off_axis() return set_output_file_name(speaker_section=speaker, off_axis_section=off_axis)
def handle_input(self): for event in pg.event.get(): if event.type == pg.QUIT or event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE: quit() self.keys = pg.key.get_pressed() if self.keys[pg.K_UP]: if self.player.rect.y - self.player.speed >= 0: ...
The main task of the code is to run an infinite game loop that continuously handles user input, updates game logic, and renders the game state. The loop repeats these three steps indefinitely, maintaining real-time interaction and visual feedback until the program is externally terminated.
def main_loop(self): while True: self.handle_input() self.process_game_logic() self.draw()
def eval_init(self, data_loader: DataLoader): """Used when evaluation starts. Args: data_loader: DataLoader the model is going to be evaluated on. """ def get_evals_from_dataset( self, data_loader: DataLoader, tqdm_message: str | None = "Evaluation", ...
Your returnThe function evaluates a model on a given dataset using a data loader, computes metrics, and returns aggregated results along with per-example metrics. It initializes evaluation, processes the dataset to collect outputs, calculates additional metrics, and finalizes the evaluation. The model is switched to ev...
def evaluate( self, data_loader: DataLoader, tqdm_message: str | None = "Evaluation", epoch: int | None = None, ) -> tuple[dict[str, float]]: """Evaluates model on `data_loader`. Args: data_loader: dataset to evaluate on. tqdm_message: what to...
def make_yolov3_model(): input_image = Input(shape=(None, None, 3)) # Layer 0 => 4 x = _conv_block(input_image, [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0}, {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, ...
This code performs object detection using a YOLOv3 model. It loads pre-trained weights, processes an input image, runs inference to detect objects, applies non-max suppression, and draws bounding boxes with labels on the image. The result is saved as a new image file with detected objects marked.
def _main_(args): weights_path = args.weights image_path = args.image # set some parameters net_h, net_w = 416, 416 obj_thresh, nms_thresh = 0.5, 0.45 anchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]] labels = ["person", "bicycle", "car", "motorbi...
def _get_default_interpreter(self) -> Optional[PythonInfo]: logging.debug('use default interpreter') # > If Python is unable to retrieve the real path to its # > executable, sys.executable will be an empty string or None. if sys.executable: return self._build_python_info(sys....
The main task of the code is to discover and return a Python interpreter's information (PythonInfo) based on specified string specifications or default settings. It prioritizes provided specs, falls back to a default interpreter if no specs are given, and raises errors if no valid interpreter is found. If all attempts ...
def _run(self) -> Optional[PythonInfo]: string_specs = self._string_specs if not string_specs: if not self.allow_default_interpreter: raise _Error( 'interpreter is not specified, use either -p/--python ' 'option or VIRTUALENV_PYTHON env...
def sha_256_hash(bytes): hasher = hashlib.sha3_256() hasher.update(bytes) digest = hasher.digest() return digest.hex() def block_to_JSON(block): return json.dumps(block) def verify_transaction(block_dict,block_hash): prev_hash = block_dict['prev_hash'] transactions = block_dict['payload']['t...
The main task of the code is to validate a blockchain block's structure, fields, and integrity. It checks for required fields, version compatibility, allowed hashes, payload validity, size limits, nonce/difficulty for version 1 blocks, transaction verification, and digital signatures. The function returns True if all c...
def check_block(block,block_string,allowed_versions=[0],allowed_hashes=[''],trust=False,diff=6,check_tx=True): block_hash = sha_256_hash(block_string.encode()) if trust: return True # Ensure all proper fields are in the block if not 'version' in block: raise BlockChainVerifyError("miss...
def chat_command(self, c, e, chan: Channel): """Parse chat commands.""" joined_args = " ".join(e.arguments) match joined_args.casefold().split(" "): case["!permit", user]: if user[0] == "@": user = user[1:] self.db.issuePermit(chan,...
This function processes incoming chat messages to enforce moderation rules. It checks if the bot is in the channel, identifies user roles, allows moderators to execute commands, and blocks non-allowed URLs in messages. If unauthorized URLs are detected, it deletes the message and sends a predefined reply.
def pubmsg_otherchannel(self, c, e): # Check if we're supposed to be in the channel and leave if not chan = self.db.getChannel(e.target[1:]) if chan is None: c.part(e.target) return # Extract the user's role role = GhirahimBot.parse_badges( ne...
def readVoltage(ps, length_packet=26): ''' Send empty stack to 0x26 and receive status stack. Decode bits 8 to 5 in little-endian format to convert hex to decimal. ''' bytes_written = ps.write(makeStack("0x26", 0)) response = ps.read(length_packet) voltage_digits = [response[8], response...
The main task of the code is to adjust a power supply's voltage gradually to a specified target value. It compares the new voltage with the current voltage, using rampUp or rampDown functions to increase or decrease the voltage stepwise if needed. After adjustment, it waits 3 seconds and prints the resulting voltage. I...
def changeVoltage(ps, voltage_offset, new_voltage): ''' Determine if voltage is higher than current voltage then raise or lower voltage gradually. ''' current_voltage = readVoltage(ps) if (new_voltage > current_voltage): print("Ramping voltage up...") rampUp(ps, new_voltage, vol...
def check_stalemate(self) -> None: if self.move_count >= get_max_move_count(): self.game_result = Result.STALEMATE def check_horizontal(self) -> None: for row in self.state: if self.check_three(row): return self.set_game_result(row[0]) def check_vertical(self) -> ...
The method `is_game_over` checks if a game has ended by evaluating stalemate and winning conditions across horizontal, vertical, diagonal, and anti-diagonal lines. It calls helper methods to validate these states and returns `True` if a result is determined via `fetch_game_result()`, indicating the game is over, otherw...
def is_game_over(self) -> bool: self.check_stalemate() self.check_horizontal() self.check_vertical() self.check_diagonal() self.check_anti_diagonal() return self.fetch_game_result() is not None
def move_contraint(self, move) -> None: if move is None: raise AttributeError("Invalid Move.") if self.is_game_over(): raise AttributeError("Game is already over.") if move not in self.get_available_moves(): raise AttributeError(f"Move {move} is not an avail...
The function `make_move` applies a specified move to the game state by validating the move, updating the board at the calculated coordinates with the current player's identifier, incrementing the move count, recording the move in history, switching to the next player, and checking if the game has ended.
def make_move(self, move: int) -> None: self.move_contraint(move) coord = np.unravel_index(move, (BOARD_ROWS, BOARD_COLS)) self.state[coord] = int(self.player_turn) self.move_count += 1 self.move_history.append(move) self.next_player() self.is_game_over()
def extract_species_dictionaries_from_reaction_strings(self, reaction_strings): """ Extract species dictionaries, rate constants, and names from a list of reaction strings. For reversible reaction, there will be two rate constants provided. Accordingly, the forward and backward reaction ...
The function `parse_reaction_strings` converts reaction strings into structured data: species names, rate constants, and stoichiometric matrices for reactants and products. It extracts species and rate constants from input strings, constructs matrices with stoichiometric coefficients, and allows sorting reactions/speci...
def parse_reaction_strings(self, reaction_strings, dtype=int, sort_reactions_by=None, sort_species_by="alphabetical", VERBOSE_MODE=False): """ Parse reaction strings into species names, rate constant names, reac...
def optimal_weights(n_points, er, cov): """ Get a list of weights for min and max returns""" # generate the target return give the min and max returns target_rtns = np.linspace(er.min(), er.max(), n_points) # for target rtns, loop through the function for what this would be and give me a set of weights ...
The code plots the efficient frontier for a portfolio of assets by generating optimal weights, calculating corresponding returns and volatilities, and visualizing them as a scatter plot. It optionally overlays key portfolios (equally weighted, GMV) and the Capital Market Line (CML) based on user inputs. The main task i...
def plot_EF_Portfolio(n_points, er, cov, style="", show_cml=False, riskfree_rate=0, show_ew=False,show_GMV=False): """ Plot Efficient portfolio for n assets """ weights = optimal_weights(n_points, er, cov) Returns = [portfolio_returns(w,er) for w in weights] Covariance = [portfolio_volatility(w,...
def optimal_weights(n_points, er, cov): """ Get a list of weights for min and max returns""" # generate the target return give the min and max returns target_rtns = np.linspace(er.min(), er.max(), n_points) # for target rtns, loop through the function for what this would be and give me a set of weights ...
The code computes optimal portfolio weights minimizing volatility by generating multiple weight configurations, calculating their returns and volatilities, and returning these values along with the final portfolio data in a DataFrame.
def Optimal_Portfolio_Min_Vol(n_points, er, cov): """ The final wewight values of the optimal portfolio """ weights = optimal_weights(n_points, er, cov) Returns = [portfolio_returns(w,er) for w in weights] Volatility = [portfolio_volatility(w,cov) for w in weights] Portfolio_final = pd.Data...
def optimal_weights_b(n_points, er, cov): """ Get a list of weights for min and max returns""" # generate the target return give the min and max returns target_rtns = np.linspace(er.min(), er.max(), n_points) # for target rtns, loop through the function for what this would be and give me a set of weight...
The function `Optimal_Portfolio_Min_VolB` computes the optimal portfolio weights that minimize volatility, given `n_points` (number of portfolio configurations), `er` (expected returns), and `cov` (covariance matrix). It calculates portfolio returns and volatility for each weight configuration, compiles them into a Dat...
def Optimal_Portfolio_Min_VolB(n_points, er, cov): """ The final wewight values of the optimal portfolio """ weights = optimal_weights_b(n_points, er, cov) Returns = [portfolio_returns_b(w,er) for w in weights] Volatility = [portfolio_volatility_b(w,cov) for w in weights] Portfolio_final = ...
def isSameClass(data): first_class = data[0][num_attributes] for row in data: if row[num_attributes] != first_class: return False return first_class def getClass(data): classes_freq = [] for i in range(num_classes): classes_freq.append(0) for row in data: cla...
This function recursively builds a decision tree by splitting data based on the best attribute and threshold. It handles base cases like empty data, uniform class labels, or attribute exhaustion, returning leaf nodes accordingly. If the tree depth exceeds a limit, it also returns a leaf. After creating child nodes, it ...
def createTree(data, attributes, high): sameClass = isSameClass(data) if (len(data) == 0): return Node(True, "Empty", None) elif (sameClass != False): return Node(True, int(sameClass) - 1, None) elif (len(attributes) == 0): return Node(True, int(getClass(data)) - 1, None) e...
def generate_entropies(psi, n_qubits, entropy_regions): entropy_results = [] for qubit_region in entropy_regions: entropy_results.append(renyi_entropy(psi, n_qubits, qubit_region)) return entropy_results def ApplyHam(psi, ham_type, n_qubits, periodic=True): if ham_type == "z0z1": retur...
The function `gradients_HEA` computes gradients or cost functions for quantum states using specified techniques (numeric, shift, or analytic). It returns inner products, gradients, or cost functions based on the `gradient_technique`, with optional analytic results including Rényi entropy. For numeric gradients, it uses...
def gradients_HEA( n_qubits, psi_list, gradient_technique, p, dtheta, return_analytic_suite, entropy_regions, ham_type, periodic, ): """ Given a psi_list and a gradient_technique, returns various useful inner products such as the gradients or cost function. If return...
def rotation_layer(n_qubits, psi, parameter, rotation): """ applies an identical rotation gate over all the qubits in psi. """ for q in range(n_qubits): psi = ApplyGate(rot(parameter, rotation), [q], psi) return psi def ApplyGate(U, qubits, psi): """'Multiplies a state psi by gate U act...
This function applies rotation gates to quantum states in psi_list. If gradient_index != current_param, it applies a standard rotation using parameters[current_param]. Otherwise, it creates three perturbed parameters (current_param ± dtheta) and applies rotation gates with these values to compute numerical gradients fo...
def layer_rot_numeric( n_qubits, psi_list, parameters, rotation, current_param, gradient_index, dtheta ): if gradient_index != current_param: for i in range(len(psi_list)): psi_list[i] = rotation_layer( n_qubits, psi_list[i], parameters[current_param], rotation ) ...
def initial_state(n_qubits): """Initializes the qubits on the computational basis""" zero = np.array([1, 0], dtype=np.complex64) psi = np.array([1, 0], dtype=np.complex64) for i in range(n_qubits - 1): psi = np.kron(psi, zero) return psi.reshape((2,) * n_qubits) def layer_H(n_qubits, psi_lis...
The function `HEA_uber_gradient_by_layer` computes the gradient of a quantum circuit's output (e.g., expectation values) with respect to its parameters, layer by layer. It constructs a variational quantum circuit using rotation and entanglement gates (CNOTs), applies measurements, and calculates gradients using techniq...
def HEA_uber_gradient_by_layer( n_qubits, n_layers, parameters, gradient_technique="numeric", gradient_index=0, measurements=None, dtheta=0.00001, return_analytic_suite=False, post_selected=False, entropy_regions=[[]], periodic=False, get_layered_results=False, ham_ty...
def initial_state(n_qubits): """Initializes the qubits on the computational basis""" zero = np.array([1, 0], dtype=np.complex64) psi = np.array([1, 0], dtype=np.complex64) for i in range(n_qubits - 1): psi = np.kron(psi, zero) return psi.reshape((2,) * n_qubits) def layer_y_rot_GG(n_qubits, ...
The main task of this code is to compute gradients of a quantum circuit's output with respect to its parameters using the GG ansatz. It supports numeric, analytic, and shift-based gradient techniques, applying rotation and CNOT gates layer-by-layer. The function returns gradients per layer or overall, depending on the ...
def GG_gradient_by_layer( n_qubits, n_layers, parameters, rotations, gradient_technique="numeric", gradient_index=0, measurements=None, dtheta=0.00001, return_analytic_suite=False, post_selected=False, entropy_regions=[[]], periodic=False, get_layered_results=False, ...
def layer_rot_none(n_qubits, psi_list, parameters, rotation, current_param): for i in range(len(psi_list)): psi_list[i] = rotation_layer( n_qubits, psi_list[i], parameters[current_param], rotation ) def layer_rot_shift( n_qubits, psi_list, parameters, rotation, current_param, gradien...
This function applies a rotation layer to a quantum circuit using different gradient calculation techniques. It dispatches to specific methods based on the 'gradient_technique' parameter: 'none', 'shift', 'analytic', or numeric. The rotation is applied to qubits with given parameters, and the chosen technique determine...
def layer_rot( n_qubits, psi_list, parameters, rotation, current_param, gradient_technique, gradient_index, dtheta, ): if gradient_technique is None: layer_rot_none(n_qubits, psi_list, parameters, rotation, current_param) elif gradient_technique == "shift": layer_...
def layer_paulixpauli_shift( n_qubits, psi_list, parameters, rotation, current_param, gradient_index ): raise NotImplementedError def layer_paulixpauli_analytical( n_qubits, psi_list, parameters, type_gates, current_param, gradient_index ): psi, del_psi = psi_list psi_list[0] = rotation_layer_HVA( ...
This function applies a layer of double Pauli gates (ZZ, YY, XX) to quantum states, as described in the Roeland paper, with support for odd/even gate types. It selects between shift, analytic, or numeric gradient techniques to compute derivatives, modifying the quantum state list (psi_list) based on parameters, gate ty...
def layer_paulixpauli( n_qubits, psi_list, parameters, type_gates, current_param, gradient_technique, gradient_index, dtheta, ): """ Puts down a layer of double pauli gates in the fashion of the Roeland paper. Type 1 is odd double ZZ gates, Type 2 is odd double YY and XX gat...
def initial_state(n_qubits): """Initializes the qubits on the computational basis""" zero = np.array([1, 0], dtype=np.complex64) psi = np.array([1, 0], dtype=np.complex64) for i in range(n_qubits - 1): psi = np.kron(psi, zero) return psi.reshape((2,) * n_qubits) def layer_H(n_qubits, psi_lis...
The code computes gradients of a quantum circuit's output with respect to its parameters, using techniques like numeric, shift, or analytic methods. It processes multiple layers of parameterized rotations (Ry gates) and entanglement (CNOTs), tracking probabilities and applying measurements. The function returns gradien...
def HEA_gradient_by_layer( n_qubits, n_layers, parameters, gradient_technique="numeric", gradient_index=0, measurements=None, dtheta=0.00001, return_analytic_suite=False, post_selected=False, entropy_regions=[[]], periodic=False, get_layered_results=False, ham_type="z...
def initial_state(n_qubits): """Initializes the qubits on the computational basis""" zero = np.array([1, 0], dtype=np.complex64) psi = np.array([1, 0], dtype=np.complex64) for i in range(n_qubits - 1): psi = np.kron(psi, zero) return psi.reshape((2,) * n_qubits) def layer_H(n_qubits, psi_lis...
This function computes gradients of a quantum circuit's output with respect to its parameters using specified techniques (numeric, analytic, or shift). It processes each layer of a quantum circuit with H, CNOT, and parameterized Ry gates, applies measurements, and calculates gradients for optimization. The function sup...
def HVA_gradient_by_layer( n_qubits, n_layers, parameters, gradient_technique="numeric", gradient_index=0, measurements=None, dtheta=0.00001, return_analytic_suite=False, post_selected=False, entropy_regions=[[]], periodic=False, get_layered_results=False, ham_type="z...
def parseInput(): input = [] with open('input.txt') as inputFile: for line in inputFile: contentsMatch = re.findall('[0-9] \w+ \w+', line) contents = [] if contentsMatch != []: for match in contentsMatch: m = match.split() ...
The main task of the code is to analyze bag containment rules parsed from input, compute two results: (1) the number of distinct bag colors that can eventually contain a "shiny gold" bag, and (2) the total count of bags required to hold a "shiny gold" bag including all nested bags. The increased recursion limit enables...
def main(): rules = parseInput() sys.setrecursionlimit(20000) partOne(rules, 'shiny gold') partTwo(rules, 'shiny gold')
def parseInput(): input = {} maskPattern = re.compile('([0-1]|X){36}') with open('input.txt') as inputFile: currentMask = '' for line in inputFile: if re.findall(maskPattern, line): currentMask = line[7:-1] elif re.findall('mem', line): ...
The main task of the code is to parse input data and execute two processing phases: `partOne` and `partTwo`, which likely perform distinct operations on the parsed input. The `main()` function orchestrates these steps, first retrieving and parsing the input, then sequentially applying the two parts to process or analyz...
def main(): input = parseInput() partOne(input) partTwo(input)
def parseInput(): input = [] with open('input.txt') as inputFile: for line in inputFile: input.append(line[:-1]) # Skip the newline character return input def partOne(input): result = simulate(input, 'adj') print("Part one: " + str(result)) return(result) def partTwo(input...
The main task of the code is to parse input data and sequentially execute two processing functions, `partOne` and `partTwo`, on the parsed input. The `main` function orchestrates this workflow by first retrieving and parsing the input, then applying the two distinct processing steps to analyze or transform the data as ...
def main(): input = parseInput() partOne(input) partTwo(input)
def CheckDir(): dirs = ["./restart", "./dump", "./log", "./output", "./init", "./config"] for dir in dirs: if not os.path.exists(dir): os.makedirs(dir) def Initial(i,pox,j,poy,temp): os.system("%s -in %s -v temp %d -v pbx %d -v pox %d -v pby %d -v poy %d"%(executable, inputfile1, temp, i...
The main task of the code is to generate multiple directories with unique parameter combinations (rate, temperature, position, strain) by iterating through predefined lists. For each directory, it copies specified files, executes simulation-related functions (CheckDir, Initial, FatigueLoad), and processes data under va...
def main(): try: maindir = "./data" filetocopy = ["in.crack.init.msm", "in.crack.load.msm", "Mishin-Ni-Al-2009.eam.alloy"] for rate in ratelist: inrate = rate+0.0001*rand1 for temp in templist: intemp = temp+3*rand1 for pox in positionx...
def run_dust_modules(self,indep=None,prop_list=None): """ Run all necessary modules to provide values of the dependent variables given the independent variables. The independent variable list can be provided directly or taken from initialization. Parameters (Optional) ------------------...
The function `calcDust` computes and optionally plots dust attenuation curves (dust opacity as a function of wavelength) using model parameters, accounting for diffuse and/or birth cloud dust. It generates curves for multiple samples, calculates averages and standard deviations of parameters (e.g., `n`, `tau`), and sav...
def calcDust(self,indep=None,prop_list=None,img_name=None,img_dir='DustAttnCurves',max_num_plot=10,plot_tau=True): """ Plot dust attenuation curves: this can be either a combination of diffuse and birth cloud dust or just diffuse/effective birth cloud dust. Parameters ---------- indep, ...
def get_lines_conversations(data_folder): """ Loads movie lines and conversations from the dataset. data_folder: Destination where conversations and lines are stored. movie_lines: Consist of movie lines as given by the dataset. movie_conversations: Consist of movie conversations as given b...
The main task of the code is to process the Cornell Movie Dialogs Corpus dataset to extract and prepare a vocabulary by loading movie lines and conversations, generating question-response pairs, trimming rare words, and returning the final vocabulary for language modeling or dialogue tasks.
def get_vocabulary(): path = "C:\\Users\\deepa\\Conversational Agents\\Datasets" dataset = "cornell movie-dialogs corpus" data_folder = os.path.join(path, dataset) print("The final data corpus folder: " + str(data_folder)) print("Extracting movie lines and movie conversations...") movie_lines...
def create_owner(self, name, investment): o_d[name] = name o_d[name] = Owner(name, investment=investment) print("Congratulations, we've created your profile!") return o_d[name] def create_property(self, owner): name = input("""What would you like to call this property? Individua...
This code collects user investment details, creates property objects, gathers rental income/expenses, and displays monthly financial summaries for each property while allowing input adjustments during setup.
def new_user(self, user): print("Fantastic! Ready for us to help you take over the world?") investment = input("First off we'd like to ask how much you've already invested: ") while True: try: investment = int(investment) break except: ...
def parse_md(md_path): if not os.path.isfile(md_path): raise FileNotFoundError("input .md not found: %s" % md_path) with open(md_path, 'r') as md: qa_strs = parse(md.readlines()) return qa_strs def write_mds(qa_strs, md_dir): for qa_id in qa_strs: md_file_fn = "%s/%s.md" % (md_d...
The function updates a SQLite database by processing markdown content. It parses a markdown file, writes its content to temporary markdown files, converts them to HTML, and updates the database with the new data, returning the count of updated entries.
def update_qa_db(md_path, md_dir, htm_dir, sqlite): # as "interface" function creates temporary files itself qa_strs = parse_md(md_path) write_mds(qa_strs, md_dir) convert_to_htm(md_dir, htm_dir) updated_cnt = update_db(md_dir, htm_dir, sqlite) return updated_cnt
def get_scale_factor_to_fit(im, max_w, max_h): h, w = im.shape[:2] if w <= max_w and h <= max_h: return im aspect_ratio = w / h new_w, new_h = round(max_h * aspect_ratio), max_h if new_w > max_w: new_w, new_h = max_w, round(max_w / aspect_ratio) return new_w / w def find_crop_di...
The code enables interactive cropping of an image using mouse clicks and keyboard inputs. It adjusts crop dimensions, applies overlays, resizes, and rotates the cropped area based on arrow key presses. The 'R' key resets to auto-detected crop dimensions, while Esc/Q exits. The final cropped image, optionally rotated, i...
def interactive_crop(filepath, plate, orig): filename = os.path.basename(filepath) h, w = orig.shape[:2] scale_factor = get_scale_factor_to_fit(orig, 1920, 1080) auto_h, auto_w = find_crop_dimensions(plate, orig) new_h, new_w = auto_h, auto_w overlaid = apply_crop_overlay(orig, new_h, new_w) ...
def var_pp(stuff): pass def __cluster_head_selection_phase(self, round_number): print('#################################################') print('############# cluster head election #############') print('#################################################') print() # Selectio...
This code simulates a multi-round wireless sensor network operation, handling initialization, cluster head selection, steady-state phase execution, dead node monitoring, and statistics collection. It iterates through rounds (1 to rmax), resets sensors, elects cluster heads, checks node status, and terminates when all n...
def __main_loop(self): print("#############################################") print("############# Main loop program #############") print("#############################################") print() for round_number in range(1, self.my_model.rmax + 1): self.r = round_nu...
def __create_sen(self): print("##########################################") print("############# Create Sensors #############") print("##########################################") print() # Create a random scenario & Load sensor Location # configure sensors self....
The main task of the code is to initialize and run a simulation involving sensor networks. It creates sensors, starts the simulation, executes the main loop for processing, and concludes the simulation. The code includes placeholders for plotting sensor data and energy levels, though these are noted as tasks for extern...
def start(self): print("#################################") print("############# Start #############") print("#################################") print() # ########################################## # ############# Create Sensors ############# # #################...
def getfiles(directory: str, file_folder: list[File]) -> list[File]: # print("Current working directory: {0}".format(directory)) for item in listdir(directory): # for each file in the listdir path: str = join(directory, item) # concat directory with the file if isdir(path): # determines if pa...
The code's main task is to scan a selected directory for files, process them to identify flagged items based on severity, and display results. It uses a GUI to select the directory, populates a file list, checks for severity levels, and prints flagged files or a "No Flagged files" message if none are found.
def main() -> None: file_folder: list[File] = [] # creates array tkinter.Tk(screenName="PII Containment Tool").withdraw() path: str = filedialog.askdirectory(title="PII Containment Tool") # fills filelist with all the files in the current working directory getfiles(path, file_folder) processfil...
def classification_loss(self, left_x, right_x, term_x, y, src=True): pred = self.predict(left_x, right_x, term_x, src=src) y = Variable(torch.LongTensor(y)) loss = self.criterion(pred, y) return loss def project(self, x, y): """ Project into shared space. """ ...
The code trains a model using batches of training data, updating parameters via backpropagation. It evaluates performance on development and target validation sets by computing F1 scores and cosine distances between embeddings. Metrics like loss, cosine similarity, and F1 scores are tracked. The model saves weights whe...
def fit(self, train_X, dev_X, trg_dev_X, weight_dir='models', batch_size=100, epochs=100): num_batches = int(len(train_X) / batch_size) best_cross_f1 = 0 num_epochs = 0 for i in range(epochs): idx = 0 nu...
def get_soup(link): """ Gets the soup object from a link. Inputs: link(str): the link Returns: soup(bs4 object): the associated soup object """ request = util.get_request(link) if request is not None: html = util.read_request(request) if html is not None: ...
The code scrapes data from a specified URL, extracts relevant links, compiles the data into a DataFrame, corrects county names in the DataFrame, and exports the cleaned data to a CSV file named `data_filename` without including an index column.
def go(data_filename): """ Final function to run everything. Inputs: data_filename(str): File name for exporting the dataframe. Returns: Nothing. Exports the data to a csv file. """ starting_url = ("https://livingwage.mit.edu/states/17/locations") limiting_domain = "livingwa...
def write_message(self, message, binary=False): """Sends the given message to the client of this Web Socket.""" if binary: opcode = 0x2 else: opcode = 0x1 message = tornado.escape.utf8(message) assert isinstance(message, bytes_type) if not self._s...
This method validates WebSocket handshake headers by checking the HTTP 101 response, 'Connection: Upgrade', 'Upgrade: websocket', and the Sec-WebSocket-Accept value derived from the client's key. If valid, it marks the connection as started, sends pending messages, triggers the on_open callback, and initiates frame rec...
def _on_headers(self, data): first, _, rest = data.partition(b'\r\n') headers = HTTPHeaders.parse(tornado.escape.native_str(rest)) # Expect HTTP 101 response. assert re.match('HTTP/[^ ]+ 101', tornado.escape.native_str(first)) # Expect Connection: Upgrade. ...
def _abort(self): """Instantly aborts the WebSocket connection by closing the socket""" self.client_terminated = True self.server_terminated = True self._started = False self.stream.close() self.close() def _async_callback(self, callback, *args, **kwargs): """Wrap...
This code processes WebSocket messages by handling different opcodes: decoding UTF-8 text (0x1), passing binary data (0x2), terminating the connection (0x8), responding to pings (0x9) with pongs, and triggering pong callbacks (0xA). It uses asynchronous callbacks for message events and aborts on decode errors or unsupp...
def _handle_message(self, opcode, data): if self.client_terminated: return if opcode == 0x1: # UTF-8 data try: decoded = data.decode("utf-8") except UnicodeDecodeError: self._abort() return self....
def _abort(self): """Instantly aborts the WebSocket connection by closing the socket""" self.client_terminated = True self.server_terminated = True self._started = False self.stream.close() self.close() def _handle_message(self, opcode, data): if self.client_termi...
This method processes WebSocket frame data, handling control frames, message fragmentation, and continuation frames. It validates control frames are unfragmented, accumulates fragmented data into a buffer, and triggers message handling upon final frame receipt. It aborts invalid sequences and ensures proper state trans...
def _on_frame_data(self, data): unmasked = array.array("B", data) if self._frame_opcode_is_control: # control frames may be interleaved with a series of fragmented # data frames, so control frames must not interact with # self._fragmented_* if not self._f...
def get_form_field(node): label = ' -> '.join(str(n.model._meta.verbose_name) for n in node.path) help_text = _('Which fields do you want to export?') return forms.MultipleChoiceField( label=label, help_text=help_text, widget=CheckboxSelectAll, choices=get_choices(node), ...
This code provides an admin action to export selected Django model instances as CSV data, allowing customization of CSV formatting (delimiters, quoting), field selection, and unique identifier handling. It dynamically generates form fields based on model relationships, validates user input, and either renders a configu...
def csvexport(modeladmin, request, queryset): """ Admin-action to export items as csv-formatted data. """ # initiate the format-form if 'csvexport' in request.POST and settings.CSV_EXPORT_FORMAT_FORM: format_form = CSVFormatForm(request.POST) else: format_form = CSVFormatForm(dic...
def forwardChecking ( self ): modified = {} assignedVars = [] for c in self.network.constraints: for v in c.vars: if v.isAssigned(): assignedVars.append(v) while len(assignedVars) != 0: av = assignedVars.pop(0) for n...
This function determines the appropriate consistency check method based on the 'cChecks' attribute and returns the result of that method. It acts as a dispatcher, selecting between forward checking, Norvig's check, TournCC, or a default assignments check, and returns the second element of the result tuple (or the direc...
def checkConsistency ( self ): if self.cChecks == "forwardChecking": return self.forwardChecking()[1] if self.cChecks == "norvigCheck": return self.norvigCheck()[1] if self.cChecks == "tournCC": return self.getTournCC() else: return self...
def selectNextVariable ( self ): if self.varHeuristics == "MinimumRemainingValue": return self.getMRV() if self.varHeuristics == "MRVwithTieBreaker": return self.MRVwithTieBreaker()[0] if self.varHeuristics == "tournVar": return self.getTournVar() e...
This code implements a backtracking algorithm with time constraints to solve a constraint satisfaction problem. It selects variables, assigns values, checks consistency, and recursively explores solutions while tracking time. If a solution is found, it returns 0; if time expires, it returns -1. Backtracking undoes assi...
def solve ( self, time_left=600): if time_left <= 60: return -1 start_time = time.time() if self.hassolution: return 0 # Variable Selection v = self.selectNextVariable() # check if the assigment is complete if ( v == None ): ...
def tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + list(branches) def label(tree): return tree[0] def branches(tree): return tree[1:]
This function recursively squares the label of each node in a tree and applies the same operation to all its branches, effectively transforming every value in the tree structure by squaring it.
def square_tree(t): return tree(label(t)**2,[square_tree(b) for b in branches(t)])
def tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + list(branches) def label(tree): return tree[0] def branches(tree): return tree[1:]
The function `prune(t, k)` recursively constructs a new tree by retaining the label of the original tree and pruning each of its branches to a depth of `k-1`, effectively limiting the tree's depth to `k` levels. When `k` reaches 0, it returns a tree with only the root label.
def prune(t,k): if k==0: return tree(label(t)) return tree(label(t),[prune(b,k-1) for b in branches(t)])
def welcome(self): """Welcome message and menu.""" # Print welcome message. print( "Welcome to Pyrly\n" "----------------\n" ) welcome_msg = ( "What do you want to do?\n\n" "1: Create New Project\n" "2: Open a existing ...
The code initializes a main menu loop for a working hours admin system. It repeatedly displays a welcome menu and working menu, handling user interruptions (Ctrl+C, EOF) by exiting or returning to the main menu. The loop ensures continuous menu access until manually terminated.
def __init__(self): """Create the main menu of the working hours admin.""" while True: # Display the welcome menu. try: self.welcome() except (KeyboardInterrupt, EOFError): self.exit() # Display the welcome menu. ...
def _make_logger(self, level=logging.INFO): """ Create a custom logger with the specified properties. """ logger = logging.getLogger(self.path) logger.setLevel(level) fmt = '%(message)s' stream_handler = logging.StreamHandler() if platform.system() != 'Win...
This code initializes a class to read and process data from a file, configuring logging, file handling, and metadata parsing. It sets up format strings, opens the file, initializes attributes for tracking data structure, and parses metadata from a SAS header to prepare for data reading.
def __init__(self, path, log_level=logging.INFO, extra_time_format_strings=None, extra_date_time_format_strings=None, extra_date_format_strings=None, skip_header=False, encoding='utf8', encoding_errors='ignore', ...
def build_vocab(sentences, min_count): word_freqs = defaultdict(int) corpus_length = 0 # Do first pass through to collect frequencies print("Building vocabulary") mem_sentences = [] for sentence in tqdm(sentences): mem_sentences.append(sentence) c...
This code initializes and trains a word embedding model (like Word2Vec) using provided sentences. It configures parameters such as embedding size, learning rate, negative sampling, and window size, builds a vocabulary, sets up sampling distributions, constructs the model, and trains it over multiple epochs. The class h...
def __init__(self, sentences=None, model_func=None, embedding_size=100, learning_rate=0.025, min_learning_rate=0.0001, num_neg_samples=5, batch_size=100, epochs=5, window_size=5, dynamic_window=True, min_count=5, subsample=1e-3, use_adam=False, seed=None, save_fname="", ...
def create_adj_mat(self, edge_policy): training_user, training_item = self.get_user_item_list() if not self.learn_flag: drop_ratio = self.ssl_rm_ratio keep_idx = randint_choice(len(training_user), size=int(len(training_user) * (1 - drop_ratio)), replace=False) user_n...
The function calculates a combined loss for a model using Self-Supervised Learning (SSL) and Bayesian Personalized Ranking (BPR). It generates embeddings via LightGCN, computes SSL loss with two sub-matrices, and calculates BPR loss using positive/negative item interactions. The total loss combines SSL (regularized) an...
def calculate_ssl_loss(self, interaction, edge_policy, epoch_idx=0): if epoch_idx == 0: self.sub_mat['sub_mat1'] = self.norm_adj_matrix self.sub_mat['sub_mat2'] = self.create_adj_mat(edge_policy) t1 = time.time() # calculate SSL Loss u_g_embeddings, i_g_embedding...
def forward(self): all_embeddings = self.get_ego_embeddings() embeddings_list = [all_embeddings] for layer_idx in range(self.n_layers): all_embeddings = torch.sparse.mm(self.norm_adj_matrix, all_embeddings) embeddings_list.append(all_embeddings) lightgcn_all_embe...
The code calculates a combined loss for a recommendation model, integrating SSL (self-supervised learning) loss, BPR (Bayesian Personalized Ranking) loss, and regularization. It extracts user/item embeddings, computes SSL loss using subgraphs, BPR loss via interaction scores, and regularization on embeddings. The total...
def calculate_loss(self, interaction, edge_policy, epoch_idx=0): # clear the storage variable when training if self.restore_user_e is not None or self.restore_item_e is not None: self.restore_user_e, self.restore_item_e = None, None user = interaction[self.USER_ID] pos_item ...
def getGlacierName(self): """Determine which glacier name to use.""" if self.officialname.strip() and self.officialname.strip() == self.greenlandicname.strip() and self.alternativename.strip(): name = '{} ({})'.format(self.officialname.strip(), self.alternativename.strip()) elif self...
The code updates derived values for a glacier by interpolating measurements (areas, lengths, termareas) and identifying missing and data years from the provided year list. It retrieves the glacier name, calculates missing years, interpolates data for specified parameters, and stores results for further analysis.
def updateDerivedValues(self, year_list): self.name = self.getGlacierName() self.missingyears = self.getMissingYears(year_list) self.interpyears = self.getInterpolatedYears('areas', year_list) self.datayears = self.getDataYears('areas', year_list) self.interpareas = self.interpol...
def xRK_1step(x, u, t, dt): k1 = dxdt(x, u, t) k2 = dxdt(x + dt * k1 * 0.5, u, t) k3 = dxdt(x + dt * k2 * 0.5, u, t) k4 = dxdt(x + dt * k3, u, t) return x + (dt / 6) * (k1 + 2 * (k2 + k3) + k4) def muRK_1step(H, x, u, mu, t, dt, eps): k1 = dHdx(H, x, u, mu, t, eps) k2 = dHdx(H, x + dt * k1 *...
The code implements the forward-backward-sweep method to optimize control variables in dynamic systems governed by a Hamiltonian. It iteratively updates state ($x$), control ($u$), and co-state ($\mu$) trajectories using Runge-Kutta methods, enforcing the transversality condition $\mu(T)=0$. Convergence is achieved whe...
def optimize(H, x0, dt, T): ''' Optimization function to implement the forward-backward-sweep method for cases where the transversality condition mu(T)=0 applies. Final time T is set to 1. Convergence is considered achieved when the optimal guess in the control variable does not change conside...
def _get_tls(config): keys = config.keys() if 'client_cert' in keys and 'client_key' in keys \ and 'tls_verify' in keys: if config['tls_verify'] == 'True': verify = True else: verify = False return TLSConfig(client_cert=( config['client_cer...
The code initializes a DockerWorker by calling the super-class constructor for configuration, setting up a Docker client with TLS, initializing image ports, and retrieving allocated ports for container management.
def __init__(self, config, persistence, messaging): """ Call super-class constructor for common configuration items and then do the docker-specific setup :return: - """ super(DockerWorker, self).__init__(config=config, persistenc...
def _get_container(self, container_id): """ get docker-py s container description :param container_id: string, id for the container :return: dict, containing the container """ try: return self.docker.inspect_container({'Id': container_id}) except docke...
This function updates instance statuses based on container states. It checks each instance's status, skips deleted ones, processes failed instances, and evaluates container running status. If a container isn't running, it removes connection/data and marks the instance as STOPPED. If running, it configures networking an...
def _publish_updates(self): instances = self.local_persistence.get_instances() for instance_id in instances.keys(): if instances[instance_id]['status'] is INSTANCE_STATUS.DELETED: continue elif instances[instance_id]['status'] is INSTANCE_STATUS.FAILED: ...
def isNumberInRange(d, mi, ma): if (isNumber(d)): return (mi <= d <= ma) else: return False def isHighInRange(high): hgt = int(high[0:-2]) hgtun = high[-2:] if (hgtun == "cm"): if not(isNumberInRange(hgt, 150, 193)): return False elif (hgtun == "in"): ...
The function `check2` validates passport data fields in `d2` against specific criteria: birth year (1920-2002), issue year (2010-2020), expiration year (2020-2030), height, hair color, eye color (from a fixed list), passport ID (9-digit number). It returns `True` if all checks pass, otherwise `False`.)
def check2(d, d2): byr = int(d2['byr']) if not(isNumberInRange(byr, 1920, 2002)): #print("Invalid byr", byr) return False iyr = int(d2['iyr']) if not(isNumberInRange(iyr, 2010, 2020)): #print("Invalid iyr", iyr) return False eyr = int(d2['eyr']) if not(isNumberInR...
def photometric_distort(image): """ Distort brightness, contrast, saturation, and hue, each with a 50% chance, in random order. :param image: image, a PIL Image :return: distorted image """ new_image = image distortions = [FT.adjust_brightness, FT.adjust_contrast, ...
The main task of the code is to apply data augmentation and preprocessing to an image and its associated bounding boxes, labels, and difficulties for object detection training. It performs photometric distortions, random expansion, cropping, shearing, rotation, resizing, and normalization using ImageNet statistics. The...
def transform(image, target, is_train): """ Apply the transformations above. :param image: image, a PIL Image :param boxes: bounding boxes in boundary coordinates, a tensor of dimensions (n_objects, 4) :param labels: labels of objects, a tensor of dimensions (n_objects) :param difficulties: diff...
def setup(self) -> bool: """ Check if a DHCP server answers. :return: True if DHCP lease can be acquired otherwise False """ ans = self.dhcp_request(nsname='host0') ans2 = self._check_second_interface() if ans is None or ans2 is None: return False ...
The code's main task is to execute a DHCP Starvation attack by acquiring IP leases and verifying if the secondary network interface remains empty, returning `True` if successful (no leases on the second interface) or `False` otherwise. It first ensures a DHCP server is present, attempts to acquire leases, and checks th...
def run(self) -> bool: """ Run DHCP Starvation attack. :return: Bool which indicates success of the attack """ if not self.setup(): raise RuntimeError("No answering DHCP Server in the network.") num_leases = self.attack(5) #print(f"{num_leases} DHCP Le...
def noun_phrase(): # Builds and returns a noun phrase. return random.choice(articles) + " " + optional_phrase(random.choice(adjectives)) + " " + random.choice(nouns) def optional_phrase(phrase_method): if random.randint(0, 2) > 0: return phrase_method else: return "" def prepositional_ph...
The function `verb_phrase` generates a random verb phrase by selecting a verb from a list, appending a noun phrase, and optionally adding a prepositional phrase. It combines these elements to create a dynamic, contextually varied verb phrase structure.
def verb_phrase(): # Builds and returns a verb phrase. return random.choice(verbs) + " " + noun_phrase() + " " + optional_phrase(prepositional_phrase())
def noun_phrase(): # Builds and returns a noun phrase. return random.choice(articles) + " " + optional_phrase(random.choice(adjectives)) + " " + random.choice(nouns) def verb_phrase(): # Builds and returns a verb phrase. return random.choice(verbs) + " " + noun_phrase() + " " + optional_phrase(prepositi...
The code generates a random sentence by concatenating a noun phrase, a verb phrase, and an optional clause. The optional clause uses a randomly chosen conjunction to link another noun-verb pair, creating varied sentence structures. The main task is to construct grammatically plausible sentences using modular components...
def sentence(): # Builds and returns a sentence. return noun_phrase() + " " + verb_phrase() + " " + \ optional_phrase(random.choice(conjunctions) + " " + noun_phrase() + " " + verb_phrase())
def initialize_landmark(self, est_state, est_cov, lidx, r, b, meas_cov): """ if the landmark is not yet seen, but we just got a measurement, this function is called and the landmark is initialized. """ lx_idx = self.state_labels.index(f"x_{lidx}") ly_idx = self.state_labe...
This function performs Kalman filter correction for a robot's state using landmark measurements. If the landmark is unseen, it initializes the landmark's state. Otherwise, it computes the measurement Jacobian, predicts the measurement, calculates the Kalman gain, updates the state and covariance with the residual, and ...
def correct_with_landmark(self, est_state, est_cov, lidx, r, b, meas_cov): if not self.landmark_seen[lidx]: # perform first-time initialization: est_state, est_cov = self.initialize_landmark(est_state, est_cov, ...
def cwd(path): oldpwd = os.getcwd() if len(path) != 0: # i.e. we're not already in that dir os.chdir(path) try: yield finally: os.chdir(oldpwd) def read_groundtruth(dataset_name): """ Read all groundtruth data from a dataset. Parameters: ---------- dataset_n...
The main task of the code is to load or generate a resampled dataset for a specified robot experiment, sampled at a given frequency (`fs` Hz). It retrieves measurement, odometry, and ground-truth data, interpolates them linearly, and structures them into pandas DataFrames. If a cached version exists, it is reused; othe...
def get_dataset(idx, fs=50): """ Return a complete dataset, with all measurement, odometry, and ground-truth sampled at a sampling interval of `fs`. Performs linear interpolation of measured data. If a particular measurement is not available at that time, the np.nan is used as the N/A value. Pa...
def init_est_pose(self): (x, y, theta), cov = self.robot.get_est_pos(0) cov = cov[:2, :2] # just x, y self.est_pos = get_cov_ellipse(x, y, cov, color=self.color, opacity=0.1) self.est_pose = plt.Line2D([x, x+self.wheelbase*np.cos(theta)], ...
This code initializes a robot's visual representation on a matplotlib plot, setting up its position, orientation, and optional elements like estimated positions, landmarks, and measurements based on input parameters. It creates a circle for the robot's body, a line for orientation, and annotations, with conditional ini...
def __init__(self, ax, robot, name="", color="red", plot_est_pos=False, plot_est_landmarks=False, plot_landmark_uncertainty=False, plot_measurements=False, only_robot_measurements=False): """ Create a robot on an axis. ...
def gameover(self): over = False # init if not self.get_empty_coord() == []: return False temp_board = copy.deepcopy(self.board) temp_score = copy.deepcopy(self.score) self.move(0) self.move(1) self.move(2) self.move(3) if board_ide...
The main task of the code is to handle a game loop where the player inputs movement directions (0-3) to manipulate a game board. It validates moves by comparing the board state before and after the move, ensuring only valid moves are applied. The loop continues until the game ends, with points granted after each valid ...
def play(self): while not self.gameover(): self.spawn() self.print_board() old_board = deepcopy(self.board) while True: print("Please enter direction: ", end='') direction = int(input()) if direction not in [0,1,2...
def get_bomb_range_tiles(self, board, tile, current=False): if current: yield tile if tile[1] > 0: yield (tile[0], tile[1] - 1) if tile[1] < self.rows - 1: yield (tile[0], tile[1] + 1) if tile[0] > 0: yield (tile[0] - 1, tile[1]) i...
The main task of the code is to evaluate tile positions for strategic bombing by calculating scores based on bomb ranges, player state, and opponent proximity. It prioritizes trapping opponents, blocking their movement, and optimizing bomb placement to maximize damage while avoiding obstacles. The function returns eith...
def strategy1(self, board, player_state, impassable_positions): # initialize exploding_tiles = defaultdict(set) score_dict = defaultdict(list) # calculate the score of each tile for x in range(self.cols): for y in range(self.rows): position = (x, y) ...
def admission_reviews_to_str(admission_reviews): return f"{[{'name': admission_review.name, 'namespace': admission_review.namespace} for admission_review in admission_reviews]}" def filter_by_kinds( admission_reviews: Iterable[AdmissionReviewRequest], kinds_filter: Iterable[Dict] ) -> Iterable[AdmissionReviewRe...
The function `filter_matching_constraint` filters admission reviews based on specified constraints in `constraint_match_filter`. It sequentially applies filters for resource kinds, namespaces, excluded namespaces, namespace selectors (via label matching), and label selectors. Each filtering step reduces the input itera...
def filter_matching_constraint( admission_reviews: Iterable[AdmissionReviewRequest], constraint_match_filter: dict, namespaces_labels: Iterable[AdmissionReviewRequest], ) -> Iterable[AdmissionReviewRequest]: logger = Logger.get_instance() logger.debug(f"filter_matching_constraint: constraint_match_...
def getitem(self, index): image, depth, label = self.get_file(index) return self.process_file(image, depth, label) def __len__(self): return len(self.images)
The main task of the code is to retrieve an item at a given index using `self.getitem(index)`. If an exception occurs during this retrieval, it prints the error and recursively fetches a random item from the dataset by generating a random index via `np.random.randint` and calling `__getitem__` again. This serves as a f...
def __getitem__(self, index): try: return self.getitem(index) except Exception as e: print(e) return self.__getitem__(np.random.randint(self.__len__()))
def depth_to_mesh( depth, padding=None, fov=45, modelview=None, atol=None, rtol=None, erode_rgb=None, cal_normal=False, ): """ Convert depth to mesh. Args: depth (np.ndarray): depth image (linearized) padding (float): p...
This function performs forward and backward view warping using depth maps. It converts an RGBD image into a 3D mesh, renders it from an alternative view, backprojects the resulting depth, and re-renders from the original view. The process includes depth linearization, mesh generation, anti-aliasing, depth edge masking,...
def forward_backward_warp( renderer, rgbd, modelview1, modelview0=None, padding=None, fov=45, near=0.5, far=100, mode='z_buffer', atol=0.02, rtol=0.02 ): """ Warp back and forth between two views. Args: rend...
def calculate_min_heuristic_seg(city_s,city_d): cost_segment=1 visited_node=[] fringe_segment = [(0,0,city_s,[])] heapq.heapify(fringe_segment) lat_d = df_gps.loc[df_gps.city==city_d, 'latitude'].iloc[0] long_d = df_gps.loc[df_gps.city==city_d, 'longitude'].iloc[0] lat_s = df_gps.loc[df_gp...
The code determines the optimal route from a starting city to a destination city based on a specified cost function (segments, distance, time, or safety). It calculates total segments, miles, hours, expected accidents, and the route steps by aggregating data from segments returned by corresponding heuristic functions, ...
def get_route(city_s,city_d,cost): cost_fn=cost distance=float(0) safe=float(0) time=float(0) route=[] if cost_fn == "segments": seg = calculate_min_heuristic_seg(city_s,city_d) for i in seg: #iterating through the popped out goal to get the sum of distance, time and probability ...
def convert_dice_to_list(self,dice): dice_string=(str(dice)) dice_ele=dice_string.split() dice=[] for i in dice_ele: i=int(i) dice.append(i) return dice def calculate_remaining(self,dice,max_key): reroll_list=[] ...
This code determines which dice to reroll based on counts and scorecard status, prioritizing three-of-a-kind for specific categories (e.g., sextus, quintus) if unscored, then pairs, and special combinations like "company" or "prattle." If no conditions match, it defaults to max_layer for rerolling.
def first_roll(self, dice, scorecard): dice=self.convert_dice_to_list(dice) dice_dict={1:0,2:0,3:0,4:0,5:0,6:0} for i in dice: dice_dict[i]+=1 reroll_list=[] max_key=max(dice_dict, key=dice_dict.get) if dice_dict[m...
def get_seat_one(): box = (398,352,427,376) #box = (396,352,428,376) im = ImageOps.grayscale(ImageGrab.grab(box)) a= array(im.getcolors()) a= a.sum() print(a) im.save(os.getcwd() + '\\seat_one__' + str(int(time.time())) + '.png','PNG') return a def makeFood(food): if food == 'calirol...
The code checks six tables for occupied seats, identifies required sushi types via a dictionary, prints status messages, prepares the sushi, and then clears tables and checks food status. It ensures each seat's needs are addressed and maintains order tracking.
def check_customer(): s1=get_seat_one() if s1 in sushiTypes: print('table 1 is occupied and needs %s'%sushiTypes[s1]) makeFood(sushiTypes[s1]) else: print('sushi not found!\n sushiType =%i'%s1) s2=get_seat_two() if s2 in sushiTypes: print('table 2 is occupied and...
def preprocess_rasters(self, dem_path): '''Process the digital elevation model to create needed rasters. Creates the following files in the directory "intermediate_rasters" sub-directory: pit_filled.tif - a pit-filled digital elevation model d8_pointer.tif- A Pointer raster desig...
This code generates flood control demand rasters by processing a DEM, flood map, and structure map. It preprocesses data, delineates watersheds, and aggregates flood risk based on area/structure weights and specified structure subsets. Optional parameters allow filtering structures, applying risk weights, and handling ...
def execute(self, dem_path, flood_map_path, struct_map_path, analysis_subsets = {'all_struct': None}, flow_search_dist = 50, area_weight_col = None, struct_weight_col = None, fld_map_is_SSURGO = True): '''Run all processes to create a set of flood control demand ...
def insertTeacher(name,email,phone,number): teacherInserted = False person_id = insertPerson(name,email,phone,number) if person_id == "used": print("[Entity Manager] Teacher was not inserted, number already in use!") teacherInserted = False else: add_teacher = ("INSERT INTO teach...
The code listens to a client, receives and decodes messages, processes operations like user registration, data retrieval, and access checks, executes corresponding database actions, generates results, and sends back encoded JSON responses. It handles multiple operations (e.g., inserting users, checking room access) and...
def listenToClient(self, client, address): max_size = 1024 while True: # try: data = client.recv(max_size) if data: data = base64.b64decode(data) data = data.decode('utf-8') data = json.loads(data) ...
def squareUnderAttack(self, r, c): """ Determine if the enemy can attack the square r, c """ self.whiteToMove = not self.whiteToMove # switch to opponent's turn oopMoves = self.getAllPossiblemoves() self.whiteToMove = not self.whiteToMove # switch turns back for...
The function generates valid castle moves for a king at position (r, c) by checking if the king is not in check and if castling rights exist. It calls helper methods to add kingside or queenside castle moves to the list, based on the current player's castling permissions.
def getCastleMoves(self, r, c, moves): """ Generate all valid castle moves for the king at (r, c) and add them to the list of moves """ if self.squareUnderAttack(r, c): return # can't castle while we are in check if (self.whiteToMove and self.currentCastlingRight.wks...
def checkForPinsAndChecks(self): pins = [] # squares where the allied pinned piece is and direction pinned from checks = [] # squares where enemy is applying a check inCheck = False if self.whiteToMove: enemyColor = "b" allyColor = "w" startRow = sel...
This function generates all valid chess moves for the current player, considering checks. It identifies pins and checks, filters moves to avoid leaving the king in check, handles blocking checks or moving the king, and includes castling. It also detects checkmate or stalemate when no valid moves remain.
def getValidMoves(self): """ all moves considering checks """ moves = [] self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks() if self.whiteToMove: kingRow = self.whiteKingLocation[0] kingCol = self.whiteKingLocation[0] else: ...
def add_data(self, X_train, X_test, y_train, y_test, infer_features=True): ''' inputs: - X_train: features (training set) - y_train: target (training set) - X_test: features (test set) - y_test: target (test set) ''' self.X_train = X_train ...
(The method `fit_and_predict` trains a machine learning model using provided training data, generates predictions on test data, and optionally evaluates model performance. It sequentially adds data, fits the model, creates predictions, and assesses accuracy if specified. The core task involves model training, predictio...
def fit_and_predict(self, X_train, X_test, y_train, y_test, evaluate=True): self.add_data(X_train, X_test, y_train, y_test) self.fit_model() self.make_predictions() if evaluate: self.evaluate_model()
def chooseBestChildren(self,nodeToExplore): i = 0 maxChildN = None; maxChildNindex = None; actionsFromCN = nodeToExplore.getActionsFromNode() for childN in actionsFromCN: #if len(childN.getBoard()) > 0 : if maxChildN == None: ...
The code implements the Monte Carlo Tree Search (MCTS) flow algorithm, which recursively traverses a game tree by selecting the best child node, expanding unvisited nodes, and backpropagating simulation results. It updates node scores and visit counts, prioritizing exploration of unvisited nodes through simulations and...
def flow(self, nodeToExplore): cWins,cTries = 0,0 # IS NOT LEAF if not (nodeToExplore.isLeaf): bestChildrenNode, bestChildrenNodeIndex = self.chooseBestChildren(nodeToExplore) recurCwins, recurCtries = self.flow(bestChildrenNode) nodeToExplo...
def extract_dir_info(synchro_signal): synchrodir = [] exclude_dir = ['PED','HOLD'] print ('99999', synchro_signal) for phase in synchro_signal: if 'protected' in synchro_signal[phase]: direct = synchro_signal[phase]['protected'] for i in direct: if i not i...
The main task of the code is to generate a SUMO-compatible signal timing plan from a synchronization signal structure. It processes barrier rings to create phase combinations, determines phase transitions, checks for pedestrian-exclusive phases, and constructs a timing plan using retrieved phase timings. The function r...
def createSignalTimingPlan(synchro_signal, sumo_signal): print ('create timing:', synchro_signal) all_directions = extract_dir_info(synchro_signal) phaseIndex = 0 phaseQueue = [] for barrierIndex in synchro_signal['brp_info']: barrierRings = synchro_signal['brp_info'][barrierIndex] ...
def initEpsilon(self): if self.epsilon == -1: maxValue = -999999999 for i in range(len(self.costMatrix)): maxValue = max(maxValue, max(self.costMatrix[i])) self.epsilon = maxValue / 4 if self.epsilon == 0: self.epsilon = 1 ...
The code implements an auction algorithm for assignment problems, using epsilon scaling to find optimal matchings between bidders and goods. It balances the cost matrix if needed, iterates through auction rounds until a stopping criterion is met, and returns the final bidder-good assignments along with their associated...
def run(self): matchings = [] self.initEpsilon() # Try to avoid price war """tempPrice = max(self.goodPrices) savedPrices = [] for i in range(len(self.goodPrices)): old = self.goodPrices[i] self.goodPrices[i] = self.goodPrices[i] * self.epsilon /...
def print(self, *args): print("[BARYCENTER] ", end="") print(*args) def getBestInitIndex(self, data): distanceMatrix = [] for i in range(len(data)): distanceMatrix.append([0] * len(data)) for i in range(len(data)): for j in range(i + 1, len(data)): ...
This code computes the Fréchet barycenter of a dataset iteratively. It initializes a barycenter using random or optimal starting data, assigns weights (alphas), and iteratively updates the barycenter by minimizing the Fréchet energy. Convergence is determined by checking if the energy change falls below a tolerance thr...
def run(self, data, alphas=None): self.print("compute barycenter...") # Init barycenter if self.randomInit: initIndex = random.randint(0, len(data) - 1) else: initIndex = self.getBestInitIndex(data) barycenter = data[initIndex] barycenter = self.l...
def makeCostMatrix(self, mu_1, mu_2): costMatrix = [] for i in range(len(mu_1)): costMatrix.append([]) for j in range(len(mu_2)): costMatrix[i].append(self.distance(mu_1[i], mu_2[j])) costMatrix[i].append(self.distanceDiag(mu_1[i])) costMatrix...
The code's main task is to compute a matching by generating a cost matrix from two inputs (mu_1, mu_2), setting it as input, disabling balancing, executing a matching algorithm, and returning the resulting matching.
def runFromData(self, mu_1, mu_2): costMatrix = self.makeCostMatrix(mu_1, mu_2) self.setInput(costMatrix) self.setBalanced(False) matching = self.run() return matching
def find_valid_neighbors(self, cell: Coordinate): all_possible_neighbors = [ Coordinate(cell.x, cell.y), Coordinate(cell.x - 1, cell.y), Coordinate(cell.x + 1, cell.y), Coordinate(cell.x, cell.y - 1), Coordinate(cell.x, cell.y + 1), Coordin...
The function updates the board by calculating new cell values based on transition probabilities from neighboring cells using the original board state. It sums weighted probabilities from valid neighbors, normalizes the updated board values, and rounds them before converting back to a list. Finally, it triggers the ghos...
def update_board_with_time(self) -> None: original_board = deepcopy(self.board) normalizer = 0 for row in range(self.row): for col in range(self.column): temp_prob = 0 current_coord = Coordinate(row, col) neighbors = self.find_valid_n...
def create_puz(): arr = np.arange(1, 17) arr[15] = 0 blank = 15 return arr.reshape(4, 4), blank def scramble_puz(puzzle, scramble): blank = 15 arr = tuple([int(a) for x in scramble.split("/") for a in x.split()]) for idd, el in enumerate(arr): if el == 0: blank = idd ...
The function `drawPuzzle` generates a visual representation of a scrambled puzzle. It creates a puzzle, scrambles it using the provided `scramble` input, draws the tiles of the scrambled puzzle, and returns the resulting image. The `scramble_puz` function likely rearranges the puzzle pieces, and `drawTiles` renders the...
def drawPuzzle(scramble): puz, _ = create_puz() puz, blank = scramble_puz(puz, scramble) img = drawTiles(puz) return img
def createScrambled(scramble): mypuz, blank = create_puz() mypuz, blank = scramble_puz(mypuz, scramble) return mypuz, blank def getLegalmoves(blank): list=[] if not bannedmove(blank,"R"): list.append("R") if not bannedmove(blank,"U"): list.append("U") if not bannedmove(blank,...
The function `get4state` generates all possible next states of a scrambled puzzle by applying each legal move from the current blank position. It returns a list of tuples, each containing a move and the resulting scrambled state after applying that move.
def get4state(scramble): list = [] puzzle, blank = createScrambled(scramble) legalmoves=getLegalmoves(blank) print("legal moves" + str(legalmoves)) for i in legalmoves: puzzle, blank = createScrambled(scramble) puz, _ = move(puzzle, blank, i) list.append((i, toScramble(puz))...
def createScrambled(scramble): mypuz, blank = create_puz() mypuz, blank = scramble_puz(mypuz, scramble) return mypuz, blank def doMoves(puzzle, blank, moves): try: for i in moves: puzzle, blank = move(puzzle, blank, i) #print(toScramble(puzzle)) return puzzle, bla...
The function generates a sequence of puzzle states starting from a scrambled configuration, applying each move in the provided solution step-by-step. It returns a list of all intermediate states, including the initial scramble and each subsequent state after executing moves from the solution.
def getStates(scramble, solution): list = [] mypuz, blank = createScrambled(scramble) list.append(scramble) for i in solution: mypuz, blank = doMoves(mypuz, blank, i) list.append(toScramble(mypuz)) return list
def get_attributes(string, obj): if string in ['IFCCARTESIANPOINT', 'IFCDIRECTION']: return [obj[len(string) + 1:-1]] elif string == 'IFCPOLYLINE': return obj[len(string) + 2:-2].split(',') tmp = obj[len(string) + 1:-1].split(',') return tmp def process_ifcaxis2placement(ifcaxis2placemen...
The function processes an IFCLOCALPLACEMENT object to compute its 3D coordinate by combining the base placement (placementRelTo) and relative placement (relativePlacemnet). It recursively resolves hierarchical placements, defaults to zero vectors for unspecified references, and returns the summed coordinate.
def process_ifclocalplacement(ifclocalplacement): assert ifclocalplacement.startswith('IFCLOCALPLACEMENT'), 'relative origin only works with IFCLOCALPLACEMENT' attributes = get_attributes('IFCLOCALPLACEMENT', ifclocalplacement) placementRelTo = attributes[0] relativePlacemnet = attributes[1] if '$...
def process_ifcarbitraryclosedprofiledef(ifcarbitraryclosedprofiledef): assert ifcarbitraryclosedprofiledef.startswith('IFCARBITRARYCLOSEDPROFILEDEF'), ifcarbitraryclosedprofiledef attributes = get_attributes('IFCARBITRARYCLOSEDPROFILEDEF', ifcarbitraryclosedprofiledef) assert attributes[0] == '.AREA.', "a...
This function identifies the type of IFC profile definition from its string prefix and delegates processing to specialized functions. It handles arbitrary closed profiles, rectangles, and profiles with voids, raising an error for unsupported types.
def process_ifcprofiledef(ifcprofiledef): if ifcprofiledef.startswith('IFCARBITRARYCLOSEDPROFILEDEF'): return process_ifcarbitraryclosedprofiledef(ifcprofiledef) elif ifcprofiledef.startswith('IFCRECTANGLEPROFILEDEF'): return process_ifcrectangleprofiledef(ifcprofiledef) elif ifcprofiledef.s...
def get_attributes(string, obj): if string in ['IFCCARTESIANPOINT', 'IFCDIRECTION']: return [obj[len(string) + 1:-1]] elif string == 'IFCPOLYLINE': return obj[len(string) + 2:-2].split(',') tmp = obj[len(string) + 1:-1].split(',') return tmp def process_ifcprofiledef(ifcprofiledef): ...
This function processes an IFC extruded area solid by extracting and validating its attributes (swept area, position, direction, depth), converting components to standard formats, adjusting the swept area with position data, and ensuring the extrusion direction is [0,0,1]. It returns the modified swept area after valid...
def process_ifcextrudedareasolid(ifcextrudedareasolid): assert ifcextrudedareasolid.startswith('IFCEXTRUDEDAREASOLID'), ifcextrudedareasolid attributes = get_attributes('IFCEXTRUDEDAREASOLID', ifcextrudedareasolid) sweptArea = attributes[0] position = attributes[1] extrudedDirection = attributes[2] ...