source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
12,764
Write a Python function to generate a file path for a given sequence name in a dataset organized in a specific directory structure. The file path should follow the pattern: `$DATASET_ROOT/$SEQUENCE_NAME/rgbd.txt`, where: - `$DATASET_ROOT` is the root directory of the dataset. - `$SEQUENCE_NAME` is the name of the seque...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_file_path(dataset_root: str, sequence_name: str) -> str: """ Generates the file path for a given sequence name in a dataset organized in a specific directory structure. The file path follows the pattern: `$DATA...
magic_instruct_75k
12,768
Write a Python function to securely remove a specified JavaScript file. The function should prompt the user for confirmation before proceeding with the deletion. If the user confirms, the function should remove the file; otherwise, it should display a message indicating that the file was not deleted. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python import os def secure_delete_file(filename: str) -> None: """ Securely removes a specified JavaScript file after prompting the user for confirmation. Args: filename (str): The name of the JavaScript file to be delet...
magic_instruct_75k
12,779
Write a Python function to filter a list of strings based on the following criteria: 1. The string must have a length greater than 5 characters. 2. The string must start with the letter 'A'. The function should return a new list containing only the strings that meet these criteria. If no strings meet these criteria, t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_strings(input_list: List[str]) -> List[str]: """ Filters a list of strings based on the criteria: 1. The string must have a length greater than 5 characters. 2. The string must start w...
magic_instruct_75k
12,784
Implement a Python function to calculate the number of ways to climb a staircase with `n` steps, where a person can take either 1 or 2 steps at a time. The function should be efficient and use dynamic programming to avoid redundant calculations. The code should start with: ```python def climb_stairs(n: int) -> int: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def climb_stairs(n: int) -> int: """ Calculate the number of ways to climb a staircase with n steps, where a person can take either 1 or 2 steps at a time. Args: n (int): The number of steps in the staircase. R...
magic_instruct_75k
12,839
Write a Python function to implement the FizzBuzz game. The function should take a single integer `n` (where 1 <= n <= 100) as input and return a list of strings representing the FizzBuzz game output from 1 to `n`. For multiples of three, the function should append "Fizz" to the list, for multiples of five, it should a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fizzBuzz(n: int) -> List[str]: """ Implements the FizzBuzz game for numbers from 1 to n. Args: n (int): The upper limit of the range (inclusive) for which to generate the FizzBuzz sequen...
magic_instruct_75k
12,861
Write a Python function to process image masks for a computer vision application. The function should take in two input masks, `min_mask`, `a2`, and `b2`, which represent certain image masks. The function should perform the following steps: 1. Calculate the maximum value between `a2` and `b2`, and divide it by 2, assig...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_masks(min_mask: List[List[int]], a2: List[List[int]], b2: List[List[int]]) -> List[List[int]]: """ Process image masks for a computer vision application. Args: min_mask (List[Lis...
magic_instruct_75k
12,866
Write a Python function to generate a formatted license file based on the given information. The license file should include the kernel protocol version, license type, and author information. The function should take the kernel protocol version information, license type, and author details as input and return the forma...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_license_file(kernel_protocol_version_info: tuple, license: str, authors: dict) -> str: """ Generates a formatted license file based on the given kernel protocol version, license type, and author information. Ar...
magic_instruct_75k
12,870
Write a Python function to count the number of unique elements in a given list of integers. A unique element is defined as an element that appears only once in the list. The function should efficiently process the list and return the count of such unique elements. The code should start with: ```python from typing impo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_elements(nums: List[int]) -> int: """ Counts the number of unique elements in a given list of integers. A unique element is defined as an element that appears only once in the list....
magic_instruct_75k
12,880
Write a Python function to generate a formatted customer information string based on the provided address, locality, and price list type. The function should handle any input values and format the output as specified. The code should start with: ```python def generate_customer_info(direccion: str, localidad: str, desc...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_customer_info(direccion: str, localidad: str, descripcion: str) -> str: """ Generates a formatted customer information string based on the provided address, locality, and price list type. Args: direccio...
magic_instruct_75k
12,885
Write a Python function to evaluate a given mathematical expression string that contains the operators '+', '-', '*', '/', and parentheses for grouping. The input string is guaranteed to be a valid mathematical expression. The function should return the result of the evaluated expression. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate(expression: str) -> int: """ Evaluates a given mathematical expression string containing '+', '-', '*', '/', and parentheses. Args: expression (str): The mathematical expressio...
magic_instruct_75k
12,899
Write a Python function to process and display data from a motion tracking system. The function should take input data and display relevant information. Specifically, the function should: 1. Print the input index, current state index, and the 3rd component of the position list. 2. Calculate the difference between the t...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def do_display(input_i: int, position_list: np.ndarray, zeta_target: np.ndarray, zeta_hat: np.ndarray, s_i: int, linear_velocity_list: np.ndarray) -> tuple: """ Processes and displays data from a motion track...
magic_instruct_75k
12,901
Write a Python function to process raw data from a file containing pairs of short integers representing the in-phase (I) and quadrature (Q) components of complex signals. The function should read the data, convert the pairs into complex numbers, calculate the magnitude of each complex number, and then compute the avera...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def process_signal(filename: str) -> None: """ Processes raw data from a file containing pairs of short integers representing the in-phase (I) and quadrature (Q) components of complex signals...
magic_instruct_75k
12,906
Write a Python function to generate SQL statements based on a list of database migration commands. Each command is represented as a dictionary with specific keys and values. The function should handle commands to add columns to tables and generate the corresponding SQL `ALTER TABLE` statements. The function should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def generate_sql(commands: List[Dict[str, Union[str, bool]]]) -> List[str]: """ Generate SQL statements based on a list of database migration commands. Args: commands (List[Dict...
magic_instruct_75k
12,907
Write a Python function to count the number of times the score increases in a given list of integers representing the scores of a game. The score is considered to increase if the current score is greater than the previous score as you move through the list from left to right. The function should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_increasing_scores(scores: List[int]) -> int: """ Counts the number of times the score increases in a given list of integers. Args: scores (List[int]): A list of integers representi...
magic_instruct_75k
12,916
Write a Python function to process song data and prepare it for feature extraction. The function should take three lists as input: `song_name`, `song_data`, and `song_sr`. The `song_name` list contains the name of the song as a string, `song_data` contains a list of numerical values representing the song's data, and `s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def prepare_song_data(song_name: List[str], song_data: List[List[float]], song_sr: List[int]) -> List[Dict[str, List]]: """ Processes song data to prepare it for feature extraction. Args: ...
magic_instruct_75k
12,928
Write a Python function to validate and execute a simulation based on a fully qualified class name provided as a command-line argument. The function should handle the case where the required parameter is missing and display an appropriate error message. If the parameter is provided, the function should execute the corr...
Here is the Python code to solve the given problem in the markdown block: ```python import sys def launch_simulation(simulation_class: str) -> None: """ Validates and executes a simulation based on the provided fully qualified class name. Args: simulation_class (str): The fully qualified name of t...
magic_instruct_75k
12,939
Implement a Python function to manage the registration and retrieval of OpenCL kernel functions using a registry system. The function should allow registering a new kernel function with a given function name and binary name, and retrieving a registered kernel function by its name. The function should handle memory mana...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Optional class KernelWrapper: def __init__(self, binary_name: str): """ Initialize a KernelWrapper with the given binary name. Args: binary_name (str): The binary name a...
magic_instruct_75k
12,942
Write a Python function to analyze the classifiers of a given package. The classifiers are represented as a list of strings, each containing information about the programming language, license, and operating system compatibility. The function should return a dictionary containing the counts of each unique classifier ca...
Here is the Python code to solve the given problem in the markdown block: ```python def analyze_classifiers(classifiers: list) -> dict: """ Analyzes the classifiers of a given package and returns a dictionary containing the counts of each unique classifier category. Args: classifiers (list): A list...
magic_instruct_75k
12,992
Write a Python function to replace all occurrences of a specific abbreviation `MIDDLE_ABBR` with the string "REPLACED" in a given 2D list of strings. The function should take a 2D list as input and return the modified 2D list. The code should start with: ```python from typing import List def replace_middle_abbr(matri...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def replace_middle_abbr(matrix: List[List[str]]) -> List[List[str]]: """ Replace all occurrences of 'MIDDLE_ABBR' with 'REPLACED' in a given 2D list of strings. Args: matrix (List[List[str]]...
magic_instruct_75k
12,999
Write a Python function `process_packages(packages)` that processes a list of package dictionaries and performs the following operations: 1. Filter out the packages that have not been published (i.e., where "published" is False). 2. Extract the names of all the published packages and store them in a list. 3. Count the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Set, Tuple def process_packages(packages: List[Dict[str, any]]) -> Tuple[List[str], int, Set[str]]: """ Processes a list of package dictionaries and performs the following operations: 1. Filte...
magic_instruct_75k
13,029
Write a Python function to create a formatted environment from an input string. The input string consists of lowercase letters and spaces, where each lowercase letter represents a specific component of the environment, and spaces represent separators between the components. The function should return a formatted string...
Here is the Python code to solve the given problem in the markdown block: ```python def create_environment(input_str: str) -> str: """ Create a formatted environment from an input string. Args: input_str (str): A string consisting of lowercase letters and spaces, where each lowercase letter represe...
magic_instruct_75k
13,038
Write a Python function to calculate the entropy of a given probability distribution. The entropy is a measure of the uncertainty of a probability distribution and is calculated using the formula: \[ H(X) = -\sum_{i=1}^{n} P(x_i) \cdot \log_2(P(x_i)) \] where \( P(x_i) \) is the probability of the event \( x_i \) occur...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def calculate_entropy(probabilities: List[float]) -> float: """ Calculate the entropy of a given probability distribution. The entropy H(X) of a probability distribution is a measure of ...
magic_instruct_75k
13,048
Write a Python function to process a list of tuples, where each tuple contains a string representing a function name, another string representing an operation, and an integer representing a value. The function should return a dictionary where the keys are the function names and the values are lists of results from the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict import math def process_operations(tuples_list: List[Tuple[str, str, int]]) -> Dict[str, List[float]]: """ Processes a list of tuples, where each tuple contains a function name, an operation...
magic_instruct_75k
13,049
Write a Python function to count the occurrences of each unique filename extension in a list of file paths. The function should handle file paths with no extensions and treat file extensions in a case-insensitive manner. The function should start with: ```python from typing import List, Dict def count_file_extensions(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_file_extensions(file_paths: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique filename extension in a list of file paths. Args: file_paths (List[str]): ...
magic_instruct_75k
13,052
Write a Python function to count the occurrences of specific error types in a given input string. The input string consists of error types separated by spaces. The error types to be checked for are "syntax", "logic", "runtime", and "semantic". The function should return a dictionary with the count of each error type fo...
Here is the Python code to solve the given problem in the markdown block: ```python def errorChecker(inputString: str) -> dict: """ Counts the occurrences of specific error types in a given input string. Args: inputString (str): The input string containing error types separated by spaces. Retu...
magic_instruct_75k
13,079
Write a Python function to generate a cache key for a given user account ID and a function to retrieve a verification code from a cache using the generated key. The cache key format is defined as `VCode-%s`, where `%s` is a placeholder for the user account ID. The cache system is assumed to support key-value storage op...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_cache_key(user_id: str) -> str: """ Generates a cache key for a given user account ID. Args: user_id (str): The user account ID. Returns: str: The cache key formatted as 'VCode-%s'. """...
magic_instruct_75k
13,084
Write a Python function to generate Docker image tags based on the given application name, image type, version, and domain. The function should return a tuple containing five specific tags: 1. `meta_tag`: The tag for the metadata image. 2. `release_tag`: The tag for the release image. 3. `phase_meta_tag`: The tag for t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def generate_docker_tags(appname: str, image_type: str, version: str, domain: str) -> Tuple[str, str, str, str, str]: """ Generates Docker image tags based on the given application name, image type, ver...
magic_instruct_75k
13,086
Write a Python function to calculate the average of a list of numbers, excluding any negative numbers from the calculation. The function should return the average of the positive numbers in the list. If the input list is empty or contains only negative numbers, the function should return 0. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average(numbers: List[float]) -> float: """ Calculate the average of the positive numbers in the given list. Args: numbers (List[float]): A list of numbers from which to calcul...
magic_instruct_75k
13,107
Write a Python function to generate a random mathematical problem related to primal infeasibility in linear programming. The function should take the number of variables and constraints as input and generate a random primal infeasibility problem. The generated problem should consist of random coefficients for the objec...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import random def generate_primal_infeasibility_problem(num_variables: int, num_constraints: int) -> Dict[str, List[int]]: """ Generates a random mathematical problem related to primal infeasibilit...
magic_instruct_75k
13,127
Write a Python function to parse a configuration file and extract the value associated with the "device" setting. The configuration file is provided as a string, where each setting is on a new line, and the setting name is followed by an equal sign (`=`). The setting value comes after the equal sign. If the "device" se...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_device_setting(config_file: str) -> str: """ Extracts the value associated with the "device" setting from a configuration file. Args: config_file (str): A string representing the configuration file, wher...
magic_instruct_75k
13,135
Write a Python function to count the number of functions for each return type in a given list of Function objects. Each Function object has attributes such as `name`, `return_type`, `parameters`, and `body`. The function should return a dictionary where the keys are the distinct return types and the values are the coun...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict class Function: def __init__(self, name: str, return_type: str, parameters: List[str], body: str): self.name = name self.return_type = return_type self.parameters = parameters ...
magic_instruct_75k
13,158
Write a Python function to modify a list of file names according to specific rules. The function should take in a list of file names and return a new list with the file names modified as follows: 1. If a file name ends with ".exe", it should be replaced with ".app". 2. If a file name ends with ".dll", it should be repl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def modify_file_names(file_list: List[str]) -> List[str]: """ Modifies a list of file names according to specific rules. Args: file_list (List[str]): A list of strings representing file name...
magic_instruct_75k
13,159
Write a Python function to find the length of the longest substring of a given string `s` that contains at most two distinct characters. The function should be efficient and should handle edge cases such as empty strings and strings with fewer than three characters. The code should start with: ```python def findLonges...
Here is the Python code to solve the given problem in the markdown block: ```python def findLongestSubstring(s: str) -> int: """ Find the length of the longest substring of `s` that contains at most two distinct characters. Args: s (str): The input string consisting of lowercase English letters. ...
magic_instruct_75k
13,160
Write a Python function to arrange a game board grid layout based on given conditions. The function should take a list of button names, their positions (as tuples of row and column coordinates), and a specific condition. If the column coordinate of a button matches the given condition, a label should be placed at that ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def arrange_game_board(names: List[str], pos: List[Tuple[int, int]], condition: int) -> List[Tuple[str, Tuple[int, int]]]: """ Arrange a game board grid layout based on given conditions. Args...
magic_instruct_75k
13,161
Write a Python function to resolve the webhook endpoint URL based on a provided code. The function should construct the endpoint URL by appending the code to a base URL string in a specific format. The base URL for the webhook endpoint is "https://www.bitrix24.com/apps/webhooks.php", and the code should be appended as ...
Here is the Python code to solve the given problem in the markdown block: ```python def resolve_webhook_endpoint(code: str) -> str: """ Resolve the webhook endpoint URL based on the provided code. Args: code (str): The code for the webhook. Returns: str: The webhook endpoint URL. "...
magic_instruct_75k
13,173
Write a Python function to find the GitHub repository with the highest number of stars from a given list of repositories. Each repository is represented as a dictionary with keys "name" and "stars_count". If there are multiple repositories with the same highest number of stars, the function should return the first occu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def find_most_starred_repo(repositories: List[Dict[str, int]]) -> Dict[str, int]: """ Find the GitHub repository with the highest number of stars from a given list of repositories. Args: ...
magic_instruct_75k
13,177
Write a Python function to calculate the adjusted playback time of a video after applying a specified delay. The function should take the duration of the video and the desired delay as input and return the adjusted playback time. The adjusted playback time should be the sum of the original video duration and the delay....
Here is the Python code to solve the given problem in the markdown block: ```python def DelayForVideo(video_duration: int, delay: int) -> int: """ Calculate the adjusted playback time of a video after applying a specified delay. Args: video_duration (int): The original duration of the video in seco...
magic_instruct_75k
13,178
Write a Python function to simulate a simple game where a player tries to reach a target number by incrementing their score. The function should take the target number as an argument and return the sequence of scores the player achieves before reaching or exceeding the target. The sequence should start from 1 and incre...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def score_sequence(target: int) -> List[int]: """ Simulates a game where a player tries to reach a target number by incrementing their score. The function returns the sequence of scores starting from...
magic_instruct_75k
13,187
Write a Python function to update a view based on a given set of data. The function should take in two two-dimensional arrays: `data` and `view`. The `data` array represents the changes to be applied to the `view` array. The function should update the `view` array based on the following rules: - If the value in the `da...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def update_view(data: List[List[int]], view: List[List[int]]) -> List[List[int]]: """ Updates the view based on the given data. Args: data (List[List[int]]): A two-dimensional array represen...
magic_instruct_75k
13,198
Write a Python function to generate a list of notes for a musical scale based on the given root note, scale mode, and number of octaves. The function should handle different scale modes and correctly generate the notes for multiple octaves. The code should start with: ```python def scale(root_note: str, scale_mode: st...
Here is the Python code to solve the given problem in the markdown block: ```python def scale(root_note: str, scale_mode: str, num_octaves: int = 1) -> list: """ Generates a list of notes for the specified scale based on the given root note, scale mode, and number of octaves. Args: root_note (str):...
magic_instruct_75k
13,205
Write a Python function to generate an XML sitemap for a website. The sitemap should include URLs for games and news articles, along with their last modification date, change frequency, and priority. The function should take two lists as input: one for game URLs and another for news URLs. Each list contains dictionarie...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_sitemap(game_urls: List[Dict[str, str]], new_urls: List[Dict[str, str]]) -> str: """ Generates an XML sitemap for a website, including URLs for games and news articles. Args: ...
magic_instruct_75k
13,208
Write a Python function to convert a Docker image name to a corresponding Singularity image file name. The Docker image name will be provided as a string, and the function should return the Singularity image file name as a string. The naming convention for the Singularity image file is to replace any '/' characters in ...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_docker_to_singularity(docker_image_name: str) -> str: """ Converts a Docker image name to a corresponding Singularity image file name. Args: docker_image_name (str): The name of the Docker image. Re...
magic_instruct_75k
13,219
Write a Python function to find all prime numbers up to a given maximum number `n` using the Sieve of Eratosthenes algorithm. The function should return a list of all prime numbers less than `n`. The code should start with: ```python from typing import List def find_primes(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes(n: int) -> List[int]: """ Find all prime numbers less than a given maximum number `n` using the Sieve of Eratosthenes algorithm. Args: n (int): The maximum number up to which...
magic_instruct_75k
13,223
Write a Python function to generate a list of training node ratios for a machine learning experiment. The function should take in the parameters `num_runs`, `early_stop_window`, `verbose`, `log_folder_master`, `algorithm`, `val_node_ratio`, `test_node_ratio`, and `network_params`. The `train_node_ratio_list` should be ...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_train_node_ratios(num_runs: int, early_stop_window: int, verbose: bool, log_folder_master: str, algorithm: str, val_node_ratio: float, test_node_ratio: float, network_params: dict) -> list: """ Genera...
magic_instruct_75k
13,233
Write a Python function to process a list of database migration operations and extract specific information from it. Each migration operation is represented as a tuple containing the app label and the migration name. The function should extract the app labels and the latest migration names and return them as a dictiona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def extract_latest_migrations(operations: List[Tuple[str, str]]) -> Dict[str, str]: """ Extracts the latest migration names for each app label from a list of migration operations. Args:...
magic_instruct_75k
13,234
Write a Python function to count the occurrences of unique labels in a list of patterns. Each pattern is represented as a dictionary with a "label" key. The function should return a dictionary where the keys are the unique labels and the values are the counts of each label in the input list. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_unique_labels(patterns: List[Dict[str, str]]) -> Dict[str, int]: """ Counts the occurrences of unique labels in a list of patterns. Args: patterns (List[Dict[str, str]]): A l...
magic_instruct_75k
13,241
Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should be optimized to achieve a time complexity of O(n), where n is the length of the input list. The function should handle edge cases such as an empty list and a list with all negative numbers. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: """ Find the maximum sum of a contiguous subarray within the given list of integers. Args: nums (List[int]): The list of integers from which to ...
magic_instruct_75k
13,252
Write a Python function to find the largest integer from a given list of integers. The function should iterate through the list and keep track of the largest number encountered. The code should start with: ```python from typing import List def find_largest(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest(nums: List[int]) -> int: """ Find the largest integer in a given list of integers. Args: nums (List[int]): A list of integers from which to find the largest. Returns: ...
magic_instruct_75k
13,274
Write a Python function to format a dictionary's key-value pairs into a specific string format. If the dictionary is empty, return a default message. The function should adhere to the following requirements: 1. If the dictionary is not empty, iterate through its key-value pairs and format each pair as " key -> val...
Here is the Python code to solve the given problem in the markdown block: ```python def format_dictionary(input_dict: dict) -> str: """ Formats the key-value pairs of a dictionary into a specific string format. Args: input_dict (dict): The dictionary to be formatted. Returns: str: A fo...
magic_instruct_75k
13,277
Write a Python function to generate a report that includes the count of permissions granted by each entity from a list of permission strings. Each permission string is in the format "PermissionName:GrantedBy", where "PermissionName" is the name of the permission and "GrantedBy" is the entity that granted the permission...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_permission_report(permissions: List[str]) -> List[str]: """ Generates a report of permissions granted by each entity from a list of permission strings. Args: permissions (List[s...
magic_instruct_75k
13,295
Write a shell script that automates the setup process for a development environment using Minikube. The script should perform the following tasks: 1. Create a directory named "bucket" inside the specified working directory (`$WORKDIR`) if it does not already exist. Ensure that the directory has full permissions (777). ...
Here is the Python code to solve the given problem in the markdown block: ```bash #!/bin/bash WORKDIR="/path/to/working/directory" LOGS_DIR="/path/to/logs/directory" # Step 1: Create the "bucket" directory if it does not exist and set permissions if [ ! -d "$WORKDIR/bucket" ]; then mkdir -p "$WORKDIR/bucket" ...
magic_instruct_75k
13,319
Write a Python function to simulate a simple game of dice where three dice are rolled and their results are rearranged in descending order. The function should take three integers representing the results of the dice rolls and return a string in the format "Depois: x - y - z", where x, y, and z are the rearranged resul...
Here is the Python code to solve the given problem in the markdown block: ```python def rearrange_dice(a: int, b: int, c: int) -> str: """ Rearranges the results of three dice rolls in descending order and returns them in a formatted string. Args: a (int): The result of the first dice roll. ...
magic_instruct_75k
13,332
Write a Python function to simulate the functionality of the given Bash script. The function should provide the following features: 1. A function called `list_processes` that simulates listing all running processes. 2. A function called `filter_processes` that takes a process name as an argument and filters the list of...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Optional # Simulated process data PROCESS_DATA = [ {"pid": "1", "name": "init", "status": "running"}, {"pid": "2", "name": "bash", "status": "running"}, {"pid": "3", "name": "python", "status"...
magic_instruct_75k
13,350
Write a Python function to simulate a simplified version of a database migration system. The function should take a list of migration operations and apply them to a database schema. Each migration operation is represented as a tuple with three elements: `(operation_type, field_name, new_field_type)`. The `operation_typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def apply_migrations(migrations: List[Tuple[str, str, str]], schema: Dict[str, str]) -> Dict[str, str]: """ Applies a list of migration operations to a database schema and returns the final ...
magic_instruct_75k
13,377
Write a Python function to filter a list of GitHub repository information based on specific criteria. Each repository is represented by a dictionary containing the keys "reponame", "filename", and "gh_stars". The function should filter repositories based on whether the "filename" contains a given keyword (case-insensit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_repositories(repositories: List[Dict[str, str]], keyword: str, min_stars: int) -> List[Dict[str, str]]: """ Filters a list of GitHub repository information based on a keyword and a minim...
magic_instruct_75k
13,392
Implement a Python class `AttributeManager` that manages a collection of attributes for various objects. The class should allow for adding, updating, and retrieving attributes for different objects. The class should have the following methods: 1. `add_attribute(obj_id, attr_name, attr_value)`: This method should add t...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict class AttributeManager: def __init__(self): """ Initializes the AttributeManager with a 2D dictionary to store attributes. """ self.var_attrs = defaultdict(dict) ...
magic_instruct_75k
13,397
Write a Python function to parse and validate box values from a given input string representing padding or margin values for a UI element. The input string is formatted as `pre-top-post pre-right-post pre-bottom-post pre-left-post`, where each value is a positive integer followed by "px". The function should return a d...
Here is the Python code to solve the given problem in the markdown block: ```python def parse_box_values(input_string: str) -> dict: """ Parses and validates box values from a given input string representing padding or margin values for a UI element. Args: input_string (str): A string representing ...
magic_instruct_75k
13,398
Implement a caching mechanism for a web application that supports two modes: `Absolute` and `Sliding`. In the `Absolute` mode, cached items have an absolute expiration time, while in the `Sliding` mode, cached items have a sliding expiration time that is extended each time the item is accessed. Your task is to impleme...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime, timedelta from typing import Optional class CacheItem: def __init__(self, key: str, value: any, expiration_time: datetime, mode: str): """ Initialize a CacheItem. Args: ...
magic_instruct_75k
13,400
Write a Python function to filter a list of dictionaries representing response models based on provided tags. Each dictionary contains information about a model, including its name and associated tags. The function should return a list of model names that have at least one of the given tags. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_models_by_tags(models: List[Dict[str, any]], tags: List[str]) -> List[str]: """ Filters a list of response models based on provided tags and returns a list of model names that match the ...
magic_instruct_75k
13,403
Write a Python program that implements a Caesar cipher encryption and decryption system. The program should include two main functions: one for encrypting a plaintext message and another for decrypting an encrypted message. The encryption function should take a plaintext message and a shift value as input, and return t...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_encrypt(plaintext: str, shift: int) -> str: """ Encrypts a plaintext message using a Caesar cipher with the given shift value. Args: plaintext (str): The plaintext message to be encrypted. shift (...
magic_instruct_75k
13,408
Write a Python function to simulate the execution of a sequence of commands using a Docker client object. The function should take a client object and a list of commands as input and execute each command in sequence. The function should return the output of the last executed command. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def execute_commands(client, commands: List[str]) -> str: """ Simulates the execution of a sequence of commands using a Docker client object. Args: client: A client object representing the D...
magic_instruct_75k
13,409
Write a Python function to count the number of rows in a 2D grid that consist entirely of the same value. The grid consists of cells that can have values of `-1`, `0`, or `1`. The function should return a list of three integers, where the first integer represents the count of rows with all `-1` values, the second integ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_cell_patterns(grid: List[List[int]]) -> List[int]: """ Counts the number of rows in a 2D grid that consist entirely of the same value. Args: grid (List[List[int]]): A 2D list repre...
magic_instruct_75k
13,413
Write a Python function `separate_char` that processes a list of tuples, where each tuple contains an integer representing the x-coordinate of a character and a 2D array representing the region of interest (ROI) in an image containing the character. The function should return a list of integers representing the x-coord...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def separate_char(characters: List[Tuple[int, List[List[str]]]]) -> List[int]: """ Processes a list of tuples, each containing an x-coordinate and a 2D array representing the region of interest (R...
magic_instruct_75k
13,432
Write a Python function to correctly calculate the sum of all elements in a given list. The function should iterate through each element in the list and accumulate the sum. The code should start with: ```python from typing import List def calculate_sum(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum(arr: List[int]) -> int: """ Calculate the sum of all elements in the given list. Args: arr (List[int]): The list of integers whose sum needs to be calculated. Returns:...
magic_instruct_75k
13,433
Write a Python function to find the maximum profit that can be obtained by making a single buy and sell transaction from a given list of daily stock prices. If no profit can be made, return 0. The function should start with: ```python from typing import List def max_profit(prices: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by making a single buy and sell transaction. Args: prices (List[int]): A list of integers wher...
magic_instruct_75k
13,443
Write a Python function to filter a list of filenames based on a specified file extension. The function should take in two parameters: a list of filenames and a string representing the desired file extension. The function should then filter the input list and return a new list containing only the filenames that have th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_filenames_by_extension(filenames: List[str], extension: str) -> List[str]: """ Filters a list of filenames to return only those that have the specified file extension. Args: filen...
magic_instruct_75k
13,446
Write a Python function `get_item_count(results: dict) -> int` that processes a dictionary of results and returns the count of a specific item. The function should handle cases where the results dictionary may be empty or may not contain the 'count' key. If the 'count' key is present, its value should be converted to a...
Here is the Python code to solve the given problem in the markdown block: ```python def get_item_count(results: dict) -> int: """ Returns the count of a specific item from the given results dictionary. Args: results (dict): A dictionary containing the results, which may or may not include a 'count'...
magic_instruct_75k
13,456
Write a Python function to convert an enumeration value from an API-specific set to a corresponding value in a generic set. The function should handle two types of enumerations: `HgiCullMode` and `HgiBlendOp`. The conversion tables are provided as static dictionaries. The function should take an input enumeration value...
Here is the Python code to solve the given problem in the markdown block: ```python def ConvertEnumValue(inputEnumValue, enumType): """ Converts an enumeration value from an API-specific set to a corresponding value in a generic set. Args: inputEnumValue: An enumeration value from the API-specific ...
magic_instruct_75k
13,490
Write a Python function to decode a response and compare it to an expected content. The response is in the form of a list of dictionaries, each containing information about a character from a sketch. The function should decode the response and compare it to the expected content, raising an assertion error if they do no...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def decode_and_compare(response: List[Dict[str, str]], expected: List[Dict[str, str]]) -> bool: """ Decodes the response and compares it to the expected content. Args: response (List[D...
magic_instruct_75k
13,491
Write a Python function to create a `ConfigFile` class that can store configuration names and their corresponding values. The class should support adding new configuration entries and retrieving the values associated with specific configuration names. Additionally, implement a function that takes a list of configuratio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class ConfigFile: def __init__(self): """ Initializes an empty ConfigFile object with two lists: config_names and config_values. """ self.config_names = [] self.config...
magic_instruct_75k
13,495
Write a Python function to check if a given username is an administrator of a bot. The bot's administrators are stored in a tuple named `BOT_ADMINS`. The function should take a username as input and return `True` if the username is an administrator, and `False` otherwise. The code should start with: ```python def is_b...
Here is the Python code to solve the given problem in the markdown block: ```python def is_bot_admin(username: str) -> bool: """ Checks if the given username is an administrator of the bot. Args: username (str): The username to check. Returns: bool: True if the username is an administr...
magic_instruct_75k
13,503
Write a Python function that converts a list of tuples into a dictionary. Each tuple contains two elements: a key and a value. If the same key appears multiple times in the list, the corresponding values should be stored in a list. If the value is `None`, it should be ignored. The function should handle cases where the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Optional, Dict, Union def tuples_to_dict(input_list: List[Tuple[str, Optional[str]]]) -> Dict[str, Union[str, List[str]]]: """ Converts a list of tuples into a dictionary. Each tuple contains a k...
magic_instruct_75k
13,509
Write a Python function to generate a `kubectl delete` command that removes specified resources from a given Kubernetes namespace. The function should take a namespace and a list of resource types as input and return the complete `kubectl delete` command as a string. The command should be formatted correctly to include...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_kubectl_delete_command(namespace: str, resource_types: List[str]) -> str: """ Generates a `kubectl delete` command to remove specified resources from a given Kubernetes namespace. Args:...
magic_instruct_75k
13,512
Write a Python function to analyze and optimize the `clean_fast.sh` script for speed. The script is designed to remove all files and subdirectories within a specified directory. The function should propose improvements to make the script run faster without compromising its functionality. The function should return a st...
Here is the Python code to solve the given problem in the markdown block: ```python def optimize_clean_script(script: str) -> str: """ Analyzes and optimizes the `clean_fast.sh` script for speed. Args: script (str): The original `clean_fast.sh` script as a string. Returns: str: The opt...
magic_instruct_75k
13,514
Write a Python function to generate the first `numRows` rows of Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients, where each number is the sum of the two directly above it. The function should return the triangle as a list of lists, where each inner list represents a row in the triang...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_pascals_triangle(numRows: int) -> List[List[int]]: """ Generate the first numRows rows of Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients, where each...
magic_instruct_75k
13,532
Write a Python function to generate all possible combinations of boolean values and string values using the `itertools.product` function. The function should take two lists as input: one containing boolean values and the other containing strings. The function should return a list of tuples, where each tuple represents ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import itertools def generate_param_combinations(boolean_values: List[bool], string_values: List[str]) -> List[Tuple[bool, str]]: """ Generates all possible combinations of boolean values and stri...
magic_instruct_75k
13,539
Write a Python function to flag Julian Dates (JDs) based on a set of always flagged JDs. The function should take a list of JDs and a set of always flagged JDs as input and return a dictionary where the keys are the JDs and the values are boolean flags indicating whether each JD is flagged or not. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Set, Dict def flag_jds(JDs: List[int], always_flagged: Set[int]) -> Dict[int, bool]: """ Flags Julian Dates (JDs) based on a set of always flagged JDs. Args: JDs (List[int]): A list of Juli...
magic_instruct_75k
13,542
Write a Python function to generate the occupancy status of each room in a hotel based on a list of bookings. Each booking is represented by a tuple of three integers (i, j, k), where `i` is the starting room number, `j` is the ending room number, and `k` is the number of rooms booked. The hotel has `n` rooms numbered ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_occupancy_status(n: int, bookings: List[Tuple[int, int, int]]) -> List[dict]: """ Generates the occupancy status of each room in a hotel based on a list of bookings. Args: ...
magic_instruct_75k
13,550
Write a Python function to calculate the sum of all even numbers in a given list of integers. The function should take a list of integers as input and return the sum of all the even numbers in the list. The function should be efficient and handle edge cases such as an empty list or a list with no even numbers. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_even_numbers(numbers: List[int]) -> int: """ Calculate the sum of all even numbers in a given list of integers. Args: numbers (List[int]): A list of integers from which to calcula...
magic_instruct_75k
13,551
Write a Python function to generate the SQL command to create a table for storing word embeddings in a specified schema. The table should have two columns: `word_id` of type integer (not null) and `word_embedding` of type double precision array. Additionally, a unique index should be created on the `word_id` column. T...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_word_embeddings_table_sql(schema: str, table_name: str) -> str: """ Generates the SQL command to create a table for storing word embeddings in a specified schema. Args: schema (str): The name of the sch...
magic_instruct_75k
13,585
Write a Python function to parse and manipulate kernel version strings. The function should be able to extract and return the kernel version string and, optionally, split the version into its individual components. The function should use a mock `Procs.Proc` class to simulate the execution of the `uname -r` command and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, Optional class Procs: class Proc: def run_verify(self, command: str) -> list: # Mock implementation to return a kernel version string return ["4.18.1-build0"] def get_kerne...
magic_instruct_75k
13,601
Create a Python class `Plugin` that represents a plugin within a software application. The class should have methods to load and unload the plugin, and a method to execute its specific functionality. Additionally, implement a mechanism for the application to discover and manage the available plugins. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable class Plugin: def __init__(self, name: str, execute_func: Callable): """ Initialize the plugin with a name and an execution function. Args: name (str): The name...
magic_instruct_75k
13,611
Write a Python function `merge_sort(L1, L2)` that takes in two lists `L1` and `L2` as input and merges them into a single sorted list. The function should use a more efficient sorting algorithm than the bubble sort used in the given function. The sorted list should be returned as the output. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(L1: List[int], L2: List[int]) -> List[int]: """ Merges two lists and returns a single sorted list using a more efficient sorting algorithm. Args: L1 (List[int]): The first lis...
magic_instruct_75k
13,628
Write a Python function to parse a given URL and extract specific segments such as the domain name, instance ID, and model repository ID. The URL follows a specific pattern: ``` "http://<domain>/instance_id/<instance_id>/model_respositories/<model_id>/upload" ``` The function should return a dictionary containing the e...
Here is the Python code to solve the given problem in the markdown block: ```python def parse_url_segments(url: str) -> dict: """ Parses a given URL and extracts the domain name, instance ID, and model repository ID. Args: url (str): The URL to be parsed, following the format: "h...
magic_instruct_75k
13,634
Write a Python function to count the occurrences of each unique file extension in a list of file paths. The function should handle both absolute and relative file paths, and the file extensions should be case-insensitive. If a file has no extension, it should be categorized under an empty string key in the dictionary. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_file_extensions(file_paths: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique file extension in a list of file paths. Args: file_paths (List[str]): A li...
magic_instruct_75k
13,649
Write a Python function to determine the type of SSL certificate associated with a given domain from a dictionary of SSL certificates. The function should follow these steps: 1. Check if the exact domain exists in the `ssl_certificates` dictionary. If found, return "single-domain". 2. If the exact domain is not found, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple, Optional import re def get_certificate_type(domain: str, ssl_certificates: Dict[str, Tuple[str, str, Optional[str]]]) -> str: """ Determine the type of SSL certificate associated with a given dom...
magic_instruct_75k
13,688
Write a Python function to calculate the product of all elements in a given list of integers. The function should return the product as an integer. The code should start with: ```python from typing import List def calculate_product(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_product(numbers: List[int]) -> int: """ Calculate the product of all elements in a given list of integers. Args: numbers (List[int]): The list of integers for which the product...
magic_instruct_75k
13,693
Write a Python function to determine the visibility of different menu elements in a game menu system based on given conditions. The function should take three boolean parameters representing the visibility state of the menu, toggle AI, and resume elements. It should return a dictionary containing the display status for...
Here is the Python code to solve the given problem in the markdown block: ```python def update_menu_display(menu_show: bool, toggle_ai_show: bool, resume_show: bool) -> dict: """ Determines the visibility of different menu elements in a game menu system based on given conditions. Args: menu_show (b...
magic_instruct_75k
13,702
Write a Python function to find the shortest path from a given source node to all other nodes in a directed graph using Dijkstra's algorithm. The graph is represented using an adjacency list, and the weights of the edges are provided in a dictionary. The function should return a dictionary where the keys are the destin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple import heapq def dijkstra_shortest_path(graph: Dict[int, List[Tuple[int, int]]], weights: Dict[Tuple[int, int], int], source: int) -> Dict[int, int]: """ Find the shortest path from a given ...
magic_instruct_75k
13,726
Write a Python function to calculate the total amount of water that can be trapped between a series of adjacent buildings after a rainstorm. The function should take a list of integers representing the heights of the buildings and return the total amount of water trapped. The water is trapped if there are higher buildi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def trapped_water(building_heights: List[int]) -> int: """ Calculate the total amount of water that can be trapped between a series of adjacent buildings after a rainstorm. Args: building_he...
magic_instruct_75k
13,758
Write a Python function to process a dictionary containing network device information and return a modified version of the dictionary. The input dictionary contains two key-value pairs: 'link_layer_address' and 'neighbor_state'. The 'link_layer_address' key holds a string representing the device's link layer address, a...
Here is the Python code to solve the given problem in the markdown block: ```python def process_device_info(input_dict: dict) -> dict: """ Processes a dictionary containing network device information and returns a modified version. The function modifies the 'link_layer_address' and 'neighbor_state' values ...
magic_instruct_75k
13,759
Write a Python function to extract the names and descriptions of custom fields from a list of custom field definitions. Each custom field definition is represented as a string in the format: "name='<field_name>', type='<field_type>', defaults={'label': '<label_value>', 'description': '<description_value>', 'show_as_att...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def extract_custom_field_descriptions(custom_fields: List[str]) -> Dict[str, str]: """ Extracts the names and descriptions of custom fields from a list of custom field definitions. A...
magic_instruct_75k
13,785
Write a Python function to set up an experiment for a machine learning project. The function should log experiment parameters, set up a task based on the given task type, and load a dataset based on the given dataset type. The function should handle the provided arguments and variables, and return the task and dataset ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def setup_experiment(experiment, args) -> Tuple[object, object]: """ Sets up an experiment for a machine learning project by logging parameters, setting up a task, and loading a dataset. Args: ...
magic_instruct_75k
13,793
Write a Python function to convert a given time in 24-hour format to 12-hour format with the appropriate suffix "AM" or "PM". The input time is a string in the format "HH:MM:SS" (24-hour format). The function should return the time in 12-hour format as a string in the format "H:MM:SS AM/PM". The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_12_hour_format(time_24h: str) -> str: """ Converts a given time in 24-hour format to 12-hour format with the appropriate suffix "AM" or "PM". Args: time_24h (str): The time in 24-hour format as a stri...
magic_instruct_75k
13,808
Write a Python function to extract endpoints and their corresponding view names from a list of URL patterns. The URL patterns are provided as a list of tuples, where each tuple contains the URL pattern, the view, and the view name. The function should return a dictionary where the keys are the URL patterns and the valu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def extract_endpoints_and_views(url_patterns: List[Tuple[str, callable, str]]) -> Dict[str, str]: """ Extracts endpoints and their corresponding view names from a list of URL patterns. ...
magic_instruct_75k
13,841
Write a Python function `process_text` that processes a list of strings to add line numbers and remove any trailing newline characters. The function should use two provided helper functions, `add_line_count` and `strip_newlines`, to achieve this task. The `add_line_count` function takes in two parameters: - `lines`: A...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Iterable def add_line_count(lines: Iterable[str], counter: Iterable[int]) -> Iterable[str]: return (f"{next(counter):>3}| {lv}" for lv in lines) def strip_newlines(strs: Iterable[str]) -> Iterable[str]: ...
magic_instruct_75k
13,872
Write a Python function to manage backups by removing the oldest backup if the number of backups exceeds a specified threshold. The function should check the current number of backups against the maximum allowed number, and if the threshold is exceeded, it should remove the oldest backup and print a message indicating ...
Here is the Python code to solve the given problem in the markdown block: ```python def manage_backups(backup_count: int, backup_count_max: int, oldest_backup: str) -> None: """ Manages backups by removing the oldest backup if the number of backups exceeds a specified threshold. Args: backup_count ...
magic_instruct_75k
13,877
Write a Python function to determine whether a given integer `n` is a power of 2. The function should correctly handle all integer inputs, including negative numbers and zero. The code should start with: ```python def is_power_of_two(n: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_two(n: int) -> bool: """ Determine whether the given integer `n` is a power of 2. Args: n (int): The integer to check. Returns: bool: True if `n` is a power of 2, otherwise False. ""...
magic_instruct_75k
13,880
Write a Python function `reverse_engineer` that takes two lists, `numlist` and `an`, as input and returns a modified version of `numlist`. The modification involves appending the sum of the sorted elements of `an` to `numlist`. The function should achieve the same result as the given `modify_list` function. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_engineer(numlist: List[int], an: List[int]) -> List[int]: """ Modifies the input list `numlist` by appending the sum of the sorted elements of `an`. Args: numlist (List[int]): Th...
magic_instruct_75k
13,897
Implement a Python function to return a list of neighboring species for a given graph node in a species interaction network. Each node represents a species, and it contains a list of neighboring species. The function should start with: ```python from typing import List def get_neighbors(node: 'GraphNode') -> List[str]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class GraphNode: def __init__(self, species: str): self.species = species self.neighbors = [] def add_neighbor(self, neighbor: 'GraphNode'): self.neighbors.append(neighbor) def ...