source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 28,324 | Write a Python function to parse and save information from a dictionary into a specific string format. The function should take a dictionary as input and return a string containing the key-value pairs in the format `"[key1]value1|[key2]value2|..."`. Ensure that the function handles edge cases such as empty dictionaries... | Here is the Python code to solve the given problem in the markdown block:
```python
def save_information_str(note_dict: dict) -> str:
"""
Converts a dictionary into a string format where each key-value pair is represented as "[key]value" and pairs are separated by "|".
Args:
note_dict (dict): The d... |
magic_instruct_75k | 28,330 | Write a Python function to filter API calls based on specified criteria. The function should take a list of API call dictionaries, a string containing the names of APIs to filter for, and a tuple containing the categories to filter for. The function should return a list of API calls that match the specified criteria.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def apply_filter(api_calls: List[Dict[str, str]], filter_apinames: str, filter_categories: tuple) -> List[Dict[str, str]]:
"""
Filters a list of API calls based on specified API names and categorie... |
magic_instruct_75k | 28,351 | Write a Python function to process a list of database migration operations and return a dictionary containing the model names as keys and a list of field names as values. Each migration operation is represented as a tuple containing the model name, field name, and field type.
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, Tuple, Dict
def extract_fields_from_migrations(migrations: List[Tuple[str, str, str]]) -> Dict[str, List[str]]:
"""
Processes a list of database migration operations and returns a dictionary containing ... |
magic_instruct_75k | 28,365 | Write a Python function `get_int_from_string` that extracts an integer value from a given input string based on a predefined label. The function should search for the label in the input string and return the integer value that follows the label. If the label is not found in the input string, the function should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def get_int_from_string(input_string: str, label: str) -> int:
"""
Extracts an integer value from the input string based on the given label.
Args:
input_string (str): The input string to search for the la... |
magic_instruct_75k | 28,402 | Write a Python function to simulate the growth of a population over a specified number of generations. The population size increases each generation based on a given growth rate percentage. The function should return the final population size after the specified number of generations.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulate_population_growth(generations: int, growth_rate_percentage: float) -> float:
"""
Simulate the growth of a population over a specified number of generations.
Args:
generations (int): The number of genera... |
magic_instruct_75k | 28,433 | Write a Python function to parse a list of tuples representing tensor information and return a dictionary containing the data type and shape of each tensor. Each tuple in the list is in the format `(data_type, shape)`, where `data_type` is a string representing the data type of the tensor (e.g., "INT32", "FLOAT64") and... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def parse_tensor_info(tensor_info: List[Tuple[str, Tuple]]) -> Dict[int, Dict[str, str]]:
"""
Parses a list of tuples representing tensor information and returns a dictionary
containing ... |
magic_instruct_75k | 28,437 | Write a Python function to create a deep copy of a given list of lists. The function should ensure that the new list is completely independent of the original list, meaning that changes to the original list should not affect the new list, and vice versa. The function should handle lists containing nested lists of arbit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def deep_copy_list(arrs: List[List[int]]) -> List[List[int]]:
"""
Creates a deep copy of a given list of lists.
Args:
arrs (List[List[int]]): The original list of lists to be copied.
... |
magic_instruct_75k | 28,446 | Write a Python function to process and store market data in a dictionary. The market data is provided in the form of a dictionary `market_to_id`, and the program should store the processed data in another dictionary called `line_storage`.
The `market_to_id` dictionary contains market names as keys and their correspond... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_market_data(market_to_id: dict, data_lines: list) -> dict:
"""
Processes market data and stores it in a dictionary.
Args:
market_to_id (dict): A dictionary where keys are market names (string) and values... |
magic_instruct_75k | 28,448 | Write a Python function to convert a given depth value to a corresponding z-coordinate in a 3D space using the provided formula. The formula for converting depth to z-coordinate is given by:
\[ z = \left(\frac{z}{\text{volumeDepth}}\right)^{\text{exp}} \times \text{far} + \text{near} \]
Where:
- \( z \) is the z-coord... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
# Constants
volumeDepth = 128.0
exp = 2.0
near = 1.0
far = 10000.0
def volumeZToDepth(z: float) -> float:
"""
Converts a given depth value to a corresponding z-coordinate in a 3D space.
The conversion f... |
magic_instruct_75k | 28,462 | Write a Python function to filter and count samples based on a given project number from a list of sample dictionaries. Each dictionary in the list contains information about a sample, including the project number, sample ID, and description. The function should return the filtered samples that match the given project ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def process_samples(project: str, sample_data: List[Dict[str, str]]) -> Tuple[List[Dict[str, str]], int]:
"""
Filters the sample data based on the provided project number and returns the fil... |
magic_instruct_75k | 28,477 | Write a Python function to manage the configuration and startup of a network security tool called "opencanaryd." The function should check for the existence of two configuration files, `main_config.conf` and `temp_config.conf`, and then start the `opencanaryd` service based on the presence of these files.
The function... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
def manage_opencanaryd_startup():
"""
Manages the startup of the opencanaryd service based on the presence of configuration files.
The function checks for the existence of two configuration file... |
magic_instruct_75k | 28,506 | Write a Python function to calculate and return the predecessor and successor of a given integer. The function should take an integer `num` as input and return a tuple `(predecessor, successor)` where `predecessor` is the integer immediately before `num` and `successor` is the integer immediately after `num`.
The code... | Here is the Python code to solve the given problem in the markdown block:
```python
def predecessor_successor(num: int) -> tuple:
"""
Calculate the predecessor and successor of a given integer.
Args:
num (int): The integer for which to find the predecessor and successor.
Returns:
tuple... |
magic_instruct_75k | 28,551 | Write a Python function to count the number of leading spaces or tabs in each non-empty line of a given list of strings representing code lines. The function should ignore empty lines and return a list of integers where each integer represents the count of leading spaces or tabs for the corresponding non-empty line.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_leading_spaces(code_lines: List[str]) -> List[int]:
"""
Counts the number of leading spaces or tabs in each non-empty line of a given list of strings.
Args:
code_lines (List[str]):... |
magic_instruct_75k | 28,555 | Write a Python function to find the highest level location (based on the numeric code) that contains a given location in a hierarchical structure represented by a dictionary. The keys in the dictionary represent the names of the locations, and the values represent the numeric codes assigned to them. The higher the loca... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def find_location(dictionary: dict, location: str) -> Union[str, int]:
"""
Find the highest level location (based on the numeric code) that contains the given location.
Args:
dictionary (di... |
magic_instruct_75k | 28,573 | Write a Python function to count the occurrences of each type in a tuple of TensorFlow Lite (TFLite) model input and output types. The function should return a dictionary where the keys are the TFLite model input and output types, and the values are the counts of each type in the input tuple.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import defaultdict
from typing import Dict, Tuple
def count_input_output_types(types_tuple: Tuple) -> Dict:
"""
Counts the occurrences of each type in a tuple of TensorFlow Lite (TFLite) model input and output ... |
magic_instruct_75k | 28,598 | Write a Python function to count the number of files in each category from a list of file paths. Each file path is in the format "category/filename", where the category is a two-digit alphanumeric code. The function should ignore any file paths that do not match the category format. The function should return a diction... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_files_by_category(file_paths: List[str]) -> Dict[str, int]:
"""
Counts the number of files in each category and returns a dictionary with the category code as key and the count as value.
... |
magic_instruct_75k | 28,621 | Write a Python function `extract_info_from_response(response_text: str) -> dict` that processes a text string containing XML-like tags and extracts specific information from it. The function should:
1. Extract the purchase order number enclosed within `<po-number>` tags from the `response_text`.
2. Extract the URL of a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
def extract_info_from_response(response_text: str) -> Dict[str, str]:
"""
Extracts the purchase order number and the URL of a PDF file from an XML-like response text.
Args:
respons... |
magic_instruct_75k | 28,626 | Write a Python function to compare a given value with a minimum threshold and return a boolean result. The function should also handle error messages and ensure that all required keys are present in a dictionary. The function should start with:
```python
from typing import Dict, List, Union
def compare_with_minimum(va... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Union
def compare_with_minimum(value: Union[int, float], threshold: Union[int, float], required_keys: List[str], data_dict: Dict[str, any]) -> Union[bool, Dict[str, str]]:
"""
Compare the given va... |
magic_instruct_75k | 28,638 | Write a Python function to split a dataset into training and testing sets based on a specified ratio. The dataset is represented as a list of data points, and the ratio is a float between 0 and 1, representing the proportion of data to be used for training. The function should return two lists: one for the training dat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def split_data(x_shuffled: List, train_ratio: float) -> Tuple[List, List]:
"""
Splits the given shuffled dataset into training and testing sets based on the specified ratio.
Args:
x_s... |
magic_instruct_75k | 28,685 | Write a Python function to process and validate data from a database. The function will receive a list of dictionaries, each representing a record from the database. The function should perform the following operations:
1. Check if the connection to the database has been established. If the connection is not establish... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def process_data(data: list) -> Union[str, list]:
"""
Processes and validates data from a database.
Args:
data (list): A list of dictionaries, each representing a record from the database.
... |
magic_instruct_75k | 28,701 | Implement a `DiagnosticManager` class in Python that manages a diagnostic reporting system for a network of hosts. Each host can report diagnostic information, which includes details about the health and status of the host. The diagnostic information is represented by a `Diagnostic` class. The `DiagnosticManager` class... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
from datetime import datetime
class Diagnostic:
def __init__(self, host_name: str, timestamp: datetime, details: str):
"""
Represents a diagnostic report from a host.
Args:... |
magic_instruct_75k | 28,714 | Write a Python function to extract a target polygon from a list of polygons based on a given bounding box. The function should take the bounding box and a list of polygons as input and return the target polygon that lies within the bounding box. If multiple polygons satisfy this condition, return the first one encounte... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Optional
def extract_target_polygon(bbox: Tuple[float, float, float, float], polygons: List[List[Tuple[float, float]]]) -> Optional[List[Tuple[float, float]]]:
"""
Extracts a target polygon from ... |
magic_instruct_75k | 28,729 | Write a Python function to consolidate dividend data from multiple sources into a list of unique dividend payments. The dividend data is provided as a list of dictionaries, where each dictionary contains the keys "stock_symbol" and "dividend_amount". The function should return a consolidated list of unique dividend pay... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def consolidate_dividends(dividend_sources: List[Dict[str, float]]) -> List[Dict[str, float]]:
"""
Consolidates a list of dividend data from multiple sources into a list of unique dividend payments... |
magic_instruct_75k | 28,753 | Create a Python function to find the shortest path between two nodes in a weighted directed graph using Dijkstra's algorithm. The graph is represented as an adjacency list where each node points to a list of tuples, each tuple containing a neighboring node and the weight of the edge connecting them.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
import heapq
def dijkstra_shortest_path(graph: Dict[int, List[Tuple[int, int]]], start: int, end: int) -> int:
"""
Find the shortest path between two nodes in a weighted directed graph using... |
magic_instruct_75k | 28,779 | Write a Python function to manage image files in a directory by identifying images that exceed a certain size and resizing them to a specified width. The function should:
1. Iterate through a list of image file paths.
2. Check the size of each image using the `os.path.getsize` function.
3. If the size of an image excee... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from PIL import Image
import os
def resize_large_images(image_paths: List[str], max_size: int, new_width: int) -> None:
"""
Resizes images that exceed a specified maximum size to a specified width.
... |
magic_instruct_75k | 28,783 | Write a Python function to modify a given string by replacing all occurrences of a specified character with another specified character. The function should return the modified string. The code should start with:
```python
def modify_string(input_string: str, char_to_replace: str, replacement_char: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def modify_string(input_string: str, char_to_replace: str, replacement_char: str) -> str:
"""
Modifies the input string by replacing all occurrences of a specified character with another specified character.
Args:
i... |
magic_instruct_75k | 28,787 | Write a Python function to calculate the total sum of integers in a given path. The function should take two parameters: a string representing the starting point of the path (`beg`) and a list of integers representing the path (`tempPath`). The function should return the total sum of the integers in the `tempPath` list... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_sum(beg: str, tempPath: List[int]) -> int:
"""
Calculate the total sum of integers in the given path.
Args:
beg (str): A string representing the starting point of the pat... |
magic_instruct_75k | 28,790 | Write a Python function `_reduce` that mimics the behavior of Python's built-in `reduce` function. The `_reduce` function should take two parameters: `x`, which is a list of elements, and `reduction`, which is a function used to reduce the list to a single value. The `reduction` function takes two arguments and returns... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def _reduce(x: List, reduction: Callable[[any, any], any]) -> any:
"""
Mimics the behavior of Python's built-in `reduce` function.
Args:
x (List): A list of elements to be reduced.... |
magic_instruct_75k | 28,791 | Write a Python function to generate a static library build configuration for a software project. The function should take several parameters and construct the necessary build configuration based on the provided inputs. The function should return a dictionary representing the build configuration for the static library.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_static_library_config(name: str, platforms: List[str], path: str, extra_includes: List[str], extra_public_includes: List[str], extra_defines: List[str]) -> Dict:
"""
Generates a static... |
magic_instruct_75k | 28,799 | Write a Python function to calculate the overlap area between two given images represented by their physical points and sizes. The physical points and sizes are obtained from the largest possible regions of the images. The function should take the physical points and sizes of the two images as input and return the area... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_overlap_area(a1: np.ndarray, b1: np.ndarray, a2: np.ndarray, b2: np.ndarray) -> float:
"""
Calculate the overlap area between two images represented by their physical points and sizes.
Args... |
magic_instruct_75k | 28,828 | Write a Python function to determine if a game board is completely filled. The game board is represented as a 2D grid of cells, each containing a digit. If any cell contains the digit `0`, it is considered empty, and the game is not over. If all cells contain non-zero digits, the game is considered over.
The function ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_game_over(board: List[List[int]]) -> bool:
"""
Determine if the game board is completely filled.
Args:
board (List[List[int]]): A 2D list representing the game board, where each cell ... |
magic_instruct_75k | 28,835 | Write a Python function to extract specific information from a given JSON object. The JSON object represents an item with various attributes, and your function should extract and return the name and description of the item. If the input JSON object is invalid or does not contain the necessary attributes, the function s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, Tuple
def extract_item_info(json_obj: dict) -> Union[Tuple[str, str], None]:
"""
Extracts the name and description of an item from a given JSON object.
Args:
json_obj (dict): A dictionary ... |
magic_instruct_75k | 28,838 | Write a Python function to modify a given `rule_matches_z` matrix based on non-matching rules for specific samples. The function should take the number of samples, the number of rules, and the `rule_matches_z` matrix as input, and return the modified matrix where non-matching rules for specified samples are marked with... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def test_label_model_data(num_samples: int, num_rules: int, rule_matches_z: np.ndarray, non_matching_samples: list) -> np.ndarray:
"""
Modifies the rule_matches_z matrix to mark the non-matching rules for eac... |
magic_instruct_75k | 28,873 | Write a Python function to filter a list of network models based on a list of target models and return a dictionary containing the filtered models and their corresponding tuning parameters. The function should handle cases where the lists of models and tuning parameters are not of the same length, and it should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_network_models(models: List[str], tuning_params: List[str], target_models: List[str]) -> Dict[str, str]:
"""
Filter the network models based on the target models and return a dictionary ... |
magic_instruct_75k | 28,887 | Write a Python function `create_discord_bot_description` that takes in a dictionary `mapping` containing the categories and commands of a Discord bot, and returns a formatted description string for the bot's features and help information. The `mapping` dictionary contains the categories as keys and a list of commands a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def create_discord_bot_description(mapping: Dict[str, List[str]]) -> str:
"""
Creates a formatted description string for a Discord bot's features and help information.
Args:
mapping (D... |
magic_instruct_75k | 28,935 | Write a Python function to sort a list of candy names in lexicographical order, ignoring the case of the letters, and remove any duplicate candy names. The function should return the sorted list of unique candy names.
The code should start with:
```python
from typing import List
def sort_unique_candies(candies: List[... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_unique_candies(candies: List[str]) -> List[str]:
"""
Sorts a list of candy names in lexicographical order, ignoring the case of the letters, and removes any duplicate candy names.
Args:
... |
magic_instruct_75k | 28,942 | Write a Python function to calculate the total amount to be paid at the end of a loan period, including both the principal amount and the accrued interest. The interest should be compounded annually. The function should take three parameters:
- `principal`: the initial principal amount of the loan
- `interest_rate`: th... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_amount(principal: float, interest_rate: float, time_period: int) -> float:
"""
Calculate the total amount to be paid at the end of a loan period, including both the principal amount and the accrued interest.
... |
magic_instruct_75k | 28,951 | Create a Python class `AuxDataContainer` that manages the registration of auxiliary data types. The class should ensure that no two auxiliary data types with the same name but different types are registered. The class should provide a method `register_aux_data_type` that takes a type and a name as parameters. If an att... | Here is the Python code to solve the given problem in the markdown block:
```python
class AuxDataContainer:
def __init__(self):
"""
Initialize the AuxDataContainer with an empty dictionary to store registered auxiliary data types.
"""
self.aux_data_types = {}
def register_aux_da... |
magic_instruct_75k | 28,959 | Write a Python function to parse a dictionary containing information about software packages and generate a formatted list of console scripts. The input dictionary will contain package details such as the license, description, and entry points for console scripts. Your function should extract the console scripts and fo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def format_console_scripts(package_info: Dict) -> List[str]:
"""
Parses a dictionary containing package information and generates a formatted list of console scripts.
Args:
package_inf... |
magic_instruct_75k | 28,967 | Write a Python function `calculate_and_display()` that takes in the necessary variables as parameters and completes the program as described. The function should calculate the total sales and average rating for the computers sold, and then display the results with exactly two decimal places. The function should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_and_display(counter_sales: float, real_sales: float, total_ratings: float, number_of_computers: int) -> (str, str):
"""
Calculate and display the total sales and average rating for the computers sold.
Args:
... |
magic_instruct_75k | 28,992 | Write a Python function to simulate a reward system where a user collects a token and then redeems a reward using the collected token. The function should handle the following steps:
1. Create a new `CollectedToken` object for the user, associating it with a specific token with the code 'REWARD_ONLY'.
2. Save the `Coll... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
class User:
def __init__(self, name: str):
self.name = name
class Token:
tokens = []
def __init__(self, code: str):
self.code = code
Token.tokens.append(self)
... |
magic_instruct_75k | 28,994 | Write a Python function to simulate the movement of a computer mouse. The function should take the previous position of the mouse and a new position as input, and return the updated position of the mouse after processing the new position. The mouse can move in two dimensions, and its position is represented by a tuple ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def update_mouse(prev_mouse_pos: Tuple[int, int], new_mouse_pos: Tuple[int, int]) -> Tuple[int, int]:
"""
Simulates the movement of a computer mouse by updating its position based on the new input.
... |
magic_instruct_75k | 29,005 | Write a Python function to update configuration settings in a file based on a given dictionary of key-value pairs. The function should read the existing configuration file, search for each key, and update its corresponding value if the key exists. If the key does not exist, the function should add a new key-value pair ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def update_config_file(config_file_path: str, updates: Dict[str, str]) -> None:
"""
Updates the configuration settings in a file based on a given dictionary of key-value pairs.
Args:
config_... |
magic_instruct_75k | 29,009 | Create a Python class `CookieManager` that manages cookies for multiple clients. Each client should have their own set of cookies, and the class should provide methods to store and retrieve cookies for specific clients. The class should have the following methods:
- `setCookie(client_id: str, key: str, value: str)`: St... | Here is the Python code to solve the given problem in the markdown block:
```python
class CookieManager:
def __init__(self):
"""
Initialize the CookieManager with an empty dictionary to store cookies for each client.
"""
self.cookies = {}
def setCookie(self, client_id: str, key:... |
magic_instruct_75k | 29,011 | Write a Python function to count the number of comments in a given code snippet. A comment is defined as any text enclosed within `/*` and `*/` delimiters. The function should return the total number of comments found in the code snippet.
The code should start with:
```python
def count_comments(code_snippet: str) -> i... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_comments(code_snippet: str) -> int:
"""
Counts the number of comments in a given code snippet.
Args:
code_snippet (str): The code snippet in which to count comments.
Returns:
int: The total nu... |
magic_instruct_75k | 29,038 | Write a Python function to determine whether the parentheses in a given string are balanced. A string is considered balanced if every opening parenthesis `'('` has a corresponding closing parenthesis `')'` and they are correctly ordered. The input string will only contain the characters `'('` and `')'`.
The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_balanced_parentheses(s: str) -> bool:
"""
Determines whether the parentheses in the given string are balanced.
Args:
s (str): The input string containing only '(' and ')'.
Returns:
bool: True if ... |
magic_instruct_75k | 29,042 | Write a Python function to extract and display relevant information from a given GitHub repository name and its associated stars range. The function should take a string representing the repository name and stars range in the format `<reponame><gh_stars>10-100` and return a dictionary containing the repository name and... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_repo_info(repo_string: str) -> dict:
"""
Extracts and returns relevant information from a given GitHub repository name and its associated stars range.
Args:
repo_string (str): A string representing the r... |
magic_instruct_75k | 29,069 | Write a Python function `assign_last_elements` that takes four parameters:
1. An array of integers, `X_arai`, representing the X coordinates.
2. An array of integers, `Y_arai`, representing the Y coordinates.
3. An array of integers, `X_IZZI_MD`, representing the X coordinates to be modified.
4. An array of integers, `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def assign_last_elements(X_arai: List[int], Y_arai: List[int], X_IZZI_MD: List[int], Y_IZZI_MD: List[int]) -> (List[int], List[int]):
"""
Assigns the last elements of `X_arai` and `Y_arai` to the last el... |
magic_instruct_75k | 29,086 | Write a Python function to update a global list of developers with a new developer's information. Each developer's information is represented as a dictionary with the keys "name" and "skills". The function should take in the developer's name, skills, and the global list of developers, and update the global list with th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def update_dev_list(name: str, skills: List[str], dev_list: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Updates the global list of developers with a new developer's information.
Args:
... |
magic_instruct_75k | 29,107 | Write a Python function to simulate a custom error handling mechanism for handling specific signals and performing a crash action when any of these signals are received. The function should register a signal handler for the signals `SIGPIPE`, `SIGSEGV`, `SIGSYS`, and `SIGTRAP`, and trigger a crash action when any of th... | Here is the Python code to solve the given problem in the markdown block:
```python
import signal
import sys
def receive_signal(signal_number, frame):
"""
Handles the reception of specific signals and performs a crash action.
Args:
signal_number (int): The number of the signal received.
fr... |
magic_instruct_75k | 29,130 | Write a Python function to calculate the similarity matrix for a set of bounding boxes used in object detection. The input consists of scores and bounding boxes, and the function should return a similarity matrix based on the Intersection over Union (IoU) metric. The function should take in the input scores, input boun... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_similarity_matrix(input_scores, input_bboxes, keep_top_k):
"""
Calculate the similarity matrix for a set of bounding boxes based on the Intersection over Union (IoU) metric.
Args:
i... |
magic_instruct_75k | 29,154 | Write a Python function to filter and sort a list of dictionaries representing items based on a specified category. Each dictionary contains information about an item, including its name, price, and category. The function should return a new list containing dictionaries of items that belong to the specified category, s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
from operator import itemgetter
def filter_and_sort_items(items: List[Dict[str, any]], category: str) -> List[Dict[str, any]]:
"""
Filters and sorts a list of dictionaries representing items based ... |
magic_instruct_75k | 29,169 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0. The function should be named `sum_even_numbers` and should start with:
```python
from typing import List
def sum_even_numbers(nums... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_even_numbers(nums: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list.
Args:
nums (List[int]): A list of integers.
Returns:
int: The sum of a... |
magic_instruct_75k | 29,173 | Write a Python function to analyze a given HTML file string and count the occurrences of unique CSS classes within the `class` attribute of HTML tags. The function should return a dictionary where the keys are unique CSS classes and the values are their respective frequencies.
The code should start with:
```python
fro... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
def countCSSClasses(html: str) -> Dict[str, int]:
"""
Analyzes an HTML string to count the occurrences of unique CSS classes within the `class` attribute of HTML tags.
Args:
html (... |
magic_instruct_75k | 29,189 | Implement a simple state machine in Python that has two states: "up" and "down". The state machine should update its `text` attribute based on the current state. The `text` attribute should be updated to reflect the state change. The state machine should be implemented as a class named `StateMachine` with the following... | Here is the Python code to solve the given problem in the markdown block:
```python
class StateMachine:
def __init__(self, texts):
"""
Initialize the StateMachine with a dictionary of texts for each state.
Args:
texts (dict): A dictionary with keys "up" and "down" and correspond... |
magic_instruct_75k | 29,201 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock once, given a list of integers representing the daily stock prices. The buying price must occur before the selling price. The function should return the maximum profit that can be obtained.
The code should start ... | 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 buying and selling a stock once.
Args:
prices (List[int]): A list of integers where each in... |
magic_instruct_75k | 29,204 | Write a Python function to perform an in-place sorting of an array using the cycle sort algorithm. The function should take an unsorted array as input and return the sorted array. The cycle sort algorithm minimizes the number of memory writes by finding the correct position for each element and moving it there.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def cycle_sort(arr: List[int]) -> List[int]:
"""
Sorts the given array in-place using the cycle sort algorithm.
Cycle sort is an in-place sorting algorithm that minimizes the number of memory writes... |
magic_instruct_75k | 29,217 | Write a Python function to check if a given list of integers is sorted in non-decreasing order. The function should return `True` if the list is sorted and `False` otherwise. The corrected function should start with:
```python
from typing import List
def is_sorted(arr: List[int]) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the given list of integers is sorted in non-decreasing order.
Args:
arr (List[int]): The list of integers to check.
Returns:
... |
magic_instruct_75k | 29,250 | Write a Python function to simulate a simple dice game. The game involves rolling a six-sided die multiple times and keeping track of the results. The function should output the total number of rolls, the frequency of each number rolled (from 1 to 6), and the percentage of each number rolled.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
import random
def dice_simulator(num_rolls: int) -> Dict[int, Dict[str, float]]:
"""
Simulates rolling a six-sided die multiple times and returns the total number of rolls,
the frequency of eac... |
magic_instruct_75k | 29,265 | Write a Python function to count the number of consecutive characters in a given string and return a list of tuples where each tuple contains a character and its consecutive count. The function should be efficient and handle edge cases such as an empty string.
The code should start with:
```python
from typing import L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def count_consecutive_chars(s: str) -> List[Tuple[str, int]]:
"""
Counts the number of consecutive characters in the given string and returns a list of tuples.
Each tuple contains a character ... |
magic_instruct_75k | 29,289 | Write a Python function to calculate the average score of a game, excluding the highest and lowest scores from a given list of integers. The function should return the average score rounded to the nearest integer. If the list contains fewer than three scores, 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_score(scores: List[int]) -> int:
"""
Calculate the average score of a game, excluding the highest and lowest scores.
Args:
scores (List[int]): A list of integers repres... |
magic_instruct_75k | 29,311 | Write a Python function to generate an entry point string for a custom pytest plugin. The function should take the name of the plugin as input and return a string formatted as `'testplan = plugin_name'`. The function should be named `generate_entry_point` and should adhere to the following signature:
```python
def gene... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_entry_point(plugin_name: str) -> str:
"""
Generates an entry point string for a custom pytest plugin.
Args:
plugin_name (str): The name of the custom pytest plugin.
Returns:
str: The entry ... |
magic_instruct_75k | 29,320 | Write a Python function to process a set of rules and messages. The function should take in a list of rules and a list of messages, and return a dictionary of rules and the list of messages. Each rule is represented as a key-value pair in the dictionary, where the key is the rule number and the value is the rule defini... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def process_rules_and_messages(rules: List[Tuple[int, str]], messages: List[str]) -> Tuple[Dict[int, str], List[str]]:
"""
Processes a set of rules and messages, returning a dictionary of ru... |
magic_instruct_75k | 29,325 | Write a Python function to print the ratings from a playlist until a rating less than 6 is encountered, and then calculate and print the average rating of the playlist. The playlist is represented as a list of floating-point numbers. The function should not modify the original playlist.
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 process_playlist_ratings(ratings: List[float]) -> None:
"""
Processes the playlist ratings by printing each rating until a rating less than 6 is encountered,
and then calculates and prints the av... |
magic_instruct_75k | 29,336 | Write a Python function to calculate the frequency of each action across all agents in a given list of agents and their actions. Each agent is represented as a dictionary with a "name" and a list of "actions". The function should return a dictionary where the keys are the actions and the values are the counts of those ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_action_frequencies(agents: List[Dict[str, any]]) -> Dict[str, int]:
"""
Calculate the frequency of each action across all agents.
Args:
agents (List[Dict[str, any]]): A list ... |
magic_instruct_75k | 29,348 | Write a Python function `process_raw_matches(raw_matches)` that processes a list of `raw_matches` and constructs a list of dictionary objects based on certain conditions. Each `raw_match` is an object with attributes `external_references` and `kill_chain_phases`. The function should iterate through each `raw_match` and... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
class RawMatch:
def __init__(self, external_references, kill_chain_phases):
self.external_references = external_references
self.kill_chain_phases = kill_chain_phases
class ExternalRefe... |
magic_instruct_75k | 29,355 | Write a Python function to determine the day of the week for a given date in the format "YYYY/MM/DD". The function should take the date as a string input and return the corresponding day of the week as a string. The input date will always be valid and in the specified format.
The code should start with:
```python
from... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def day_of_the_week(date: str) -> str:
"""
Determine the day of the week for a given date in the format "YYYY/MM/DD".
Args:
date (str): The date in the format "YYYY/MM/DD".
Return... |
magic_instruct_75k | 29,409 | Write a Python function to calculate the total interest paid across all bank accounts given a list of initial balances and an interest rate. The interest for each account is calculated using the formula: `interest = balance * interest_rate / 100`. The function should return the total interest paid across all accounts, ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def total_interest(bal_st: List[int], interest_rate: int) -> float:
"""
Calculate the total interest paid across all bank accounts given a list of initial balances and an interest rate.
Args:
... |
magic_instruct_75k | 29,463 | Write a Python function to generate the complete URL for accessing a dataset from a fictional API. The function should take a dataset code as input and return the complete URL by concatenating the base URL for the API with the provided dataset code. Additionally, define the `FAIR_API_ENDPOINT` variable, which represent... | Here is the Python code to solve the given problem in the markdown block:
```python
# Define the base URL for the API
FAIR_API_ENDPOINT = "https://example.com/api/datasets/"
def dataset_url(code: str) -> str:
"""
Generate the complete URL for accessing a dataset from a fictional API.
Args:
code (s... |
magic_instruct_75k | 29,465 | Write a Python function to update the list of tabu edges in a graph based on the given input parameters. The function should take a list of vertex indices (`idx_group`), a list of current tabu edges (`tabu_edges`), and a boolean flag (`tabu_idx_group`). The boolean flag indicates whether the `idx_group` should be added... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def update_tabu_edges(
idx_group: List[int],
tabu_edges: List[Tuple[int, int]],
tabu_idx_group: bool,
) -> List[Tuple[int, int]]:
"""
Update the list of tabu edges in a graph based on ... |
magic_instruct_75k | 29,472 | Write a Python function to generate a random product dictionary based on a given description. The product dictionary should include the description and a boolean value indicating whether the product is active or not. The function should start with:
```python
import random
def generate_product(description: str) -> dict... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_product(description: str) -> dict:
"""
Generates a random product dictionary based on the given description.
Args:
description (str): The description of the product.
Returns:
... |
magic_instruct_75k | 29,495 | Create a Python function that takes a content type as input and returns a list of all available permissions for that content type. The function should handle the case where an invalid content type is provided by returning an empty list. The available content types and their corresponding permissions are predefined.
Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_permissions_for_content_type(content_type: str) -> List[str]:
"""
Returns a list of permissions for the given content type.
Args:
content_type (str): The content type for which to re... |
magic_instruct_75k | 29,527 | Write a Python function to automate the process of extracting package information from a `package.json` file and building a Docker image with appropriate tags. The function should read the `name` and `version` fields from the `package.json` file and use them to tag the Docker image with the format: `name:version` and `... | Here is the Python code to solve the given problem in the markdown block:
```python
import json
import subprocess
from typing import Dict
def build_docker_image(package_json_path: str) -> None:
"""
Automates the process of extracting package information from a `package.json` file and building a Docker image wi... |
magic_instruct_75k | 29,531 | Write a Python function to generate a setup script for a Python package based on a list of package names and their versions, along with a dictionary of data files associated with each package. The setup script should follow the standard Python setup script conventions, including the package names, versions, and associa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def generate_setup_script(package_versions: List[Tuple[str, str]], package_data: Dict[str, List[str]]) -> str:
"""
Generates a setup script for a Python package based on the provided package... |
magic_instruct_75k | 29,578 | Write a Python function to calculate the position (X and Y coordinates) for each folder in a column layout within a graphical user interface (GUI). Each folder has a specific width and height, and there is a fixed margin between each folder. The function should return a list of tuples, where each tuple represents the (... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_folder_positions(margin: int, folder_width: int, folder_height: int, num_folders: int) -> List[Tuple[int, int]]:
"""
Calculate the position (X and Y coordinates) for each folder in a... |
magic_instruct_75k | 29,598 | Create a Python class `RenderingEngine` that simulates a simple rendering engine for a game. The class should have the following methods:
1. `set_render_mode(self, mode: str) -> None`: Sets the rendering mode for the engine. The mode can be one of the following: "2D", "3D", or "VR". If the mode is not one of these opti... | Here is the Python code to solve the given problem in the markdown block:
```python
class RenderingEngine:
def __init__(self):
"""
Initialize the RenderingEngine with no rendering mode set.
"""
self.render_mode = None
def set_render_mode(self, mode: str) -> None:
"""
... |
magic_instruct_75k | 29,635 | Write a Python function to reverse the order of words in a given string while maintaining the order of characters within each word. The function should handle input strings with multiple words separated by single spaces, and it should remove any leading or trailing spaces from the input string. The function should star... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_words(text: str) -> str:
"""
Reverses the order of words in a given string while maintaining the order of characters within each word.
Args:
text (str): The input string containing words separated by sin... |
magic_instruct_75k | 29,645 | Write a Python function to generate a SQL script for creating a PostgreSQL database and granting all privileges to a specified user. The function should take two parameters: the database name and the database user. The SQL script should be returned as a string.
The code should start with:
```python
def generate_sql_sc... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_sql_script(db_name: str, db_user: str) -> str:
"""
Generates a SQL script to create a PostgreSQL database and grant all privileges to a specified user.
Args:
db_name (str): The name of the database to b... |
magic_instruct_75k | 29,662 | Write a Python function to simulate the behavior of the `CompilerFactory` class in the given C++ code snippet. The function should create instances of different types of compilers based on user input. The `CompilerBase` class and its derived classes (`CCompiler`, `CppCompiler`, and `JavaCompiler`) are already provided ... | Here is the Python code to solve the given problem in the markdown block:
```python
class CompilerBase:
def compile(self):
raise NotImplementedError("This method should be overridden in derived classes")
class CCompiler(CompilerBase):
def compile(self):
return "Compiling C code"
class CppCompi... |
magic_instruct_75k | 29,676 | Write a Python script to automate the process of pushing a Docker image to a specified repository. The script should perform the following steps:
1. Accept the repository name as a command-line argument.
2. Construct the full image name by combining the repository name with a specific tag (e.g., `latest`).
3. Print a m... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import sys
def push_docker_image(repository_name: str):
"""
Automates the process of pushing a Docker image to a specified repository.
Args:
repository_name (str): The name of the repository to wh... |
magic_instruct_75k | 29,681 | Write a Python function to find the next non-zero element in a given list of integers after the first occurrence of 0. If there are no non-zero elements after the first 0, the function should return `None`.
The function should start with:
```python
from typing import List, Optional
def find_next_nonzero(lst: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_next_nonzero(lst: List[int]) -> Optional[int]:
"""
Finds the next non-zero element in the list after the first occurrence of 0.
Args:
lst (List[int]): The list of integers... |
magic_instruct_75k | 29,702 | Write a Python script `nbconvert_invoker.py` that processes positional arguments to construct the appropriate command for invoking the `nbconvert` tool for converting Jupyter notebooks to various formats. The script should handle different invocation scenarios, including:
1. Direct invocation for `nbconvert`.
2. Invoca... | Here is the Python code to solve the given problem in the markdown block:
```python
import sys
def construct_nbconvert_command(args):
"""
Constructs the appropriate command for invoking the `nbconvert` tool based on the given positional arguments.
Args:
args (list): A list of positional arguments ... |
magic_instruct_75k | 29,717 | Write a Python function `calculate_distance` that computes the Euclidean distance between two points in 3D space. Implement another function `distance_to_bboxes` that calculates the distance between each LiDAR point and the closest bounding box centroid from a list of ground truth and predicted bounding box centroids. ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import List, Tuple
def calculate_distance(point1: Tuple[float, float, float], point2: Tuple[float, float, float]) -> float:
"""
Calculate the Euclidean distance between two points in 3D space.
... |
magic_instruct_75k | 29,725 | Create a Python function to simulate the process of stopping a "catalogue" service running on a server. The function should:
- Accept a list of running services as input.
- Identify and stop the "catalogue" service if it is running.
- Return a message indicating whether the "catalogue" service was stopped or not.
- Ens... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def stop_catalogue_service(services: List[str]) -> str:
"""
Simulates stopping the "catalogue" service if it is running.
Args:
services (List[str]): A list of strings representing the names ... |
magic_instruct_75k | 29,732 | Write a Python function to calculate the starting index for sampling frames from a video based on the given video length and specified sampling parameters. The function should consider the stride, extraction frames per second (FPS), and the number of frames to be sampled. The function should return the starting index f... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
STRIDE = 1
EXTRACTION_FPS = 25
NUM_FRAMES = 4
def sample_video_index(video_length: int) -> int:
"""
Calculate the starting index for sampling frames from a video based on the given video length and specified samp... |
magic_instruct_75k | 29,735 | Write a Python function to modify a list of file names based on specific rules. The function should take a list of file names as input and return a modified list of file names according to the following rules:
1. Append "_target" to each file name.
2. Add the modified file names to a new list.
3. Set the `output_to_bin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def modify_file_names(file_names: List[str]) -> List[str]:
"""
Modifies a list of file names by appending "_target" to each file name and setting the `output_to_bindir` flag to 1.
Args:
file... |
magic_instruct_75k | 29,740 | Write a Python function to process a list of ratings obtained from a tracing client. The function should filter out any ratings that are below a certain threshold and return the remaining ratings in ascending order. The function should be named `process_ratings` and should take two parameters: a list of integers repres... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_ratings(ratings: List[int], threshold: int) -> List[int]:
"""
Filters out ratings below a given threshold and returns the remaining ratings in ascending order.
Args:
ratings (Lis... |
magic_instruct_75k | 29,741 | Write a Python function `setupDevEnvironment` that automates the process of setting up a new build and deploying an application in a development environment using OpenShift Container Platform. The function should take the following parameters:
- `APP` (string): The name of the application.
- `DEV_PROJECT` (string): The... | Here is the Python code to solve the given problem in the markdown block:
```python
def setupDevEnvironment(APP: str, DEV_PROJECT: str, S2I_IMAGE: str, TEMPLATE_FILE: str) -> str:
"""
Generates the commands for setting up a new build and deploying an application in a development environment using OpenShift.
... |
magic_instruct_75k | 29,749 | Write a Python function `double_sequence(sequence)` that takes a list of integers `sequence` as input and returns a new list containing the doubled values of the input sequence. Additionally, write a lambda function `double_sequence_lambda` that achieves the same result as the `double_sequence` function.
The starter c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def double_sequence(sequence: List[int]) -> List[int]:
"""
Doubles each element in the input sequence and returns a new list with the doubled values.
Args:
sequence (List[int]): The input li... |
magic_instruct_75k | 29,752 | Implement a custom data structure called `MyDictionary` in Python. This data structure should mimic the behavior of a standard dictionary with additional functionalities. The `MyDictionary` should support the following operations:
1. `remove_all()`: Removes all key-value pairs from the dictionary.
2. `is_empty()`: Retu... | Here is the Python code to solve the given problem in the markdown block:
```python
class MyDictionary:
def __init__(self):
"""
Initializes a new instance of MyDictionary with an empty storage and an initial capacity.
"""
self.storage = {}
self.allocated_capacity = 10 # Init... |
magic_instruct_75k | 29,785 | Write a Python function to retrieve disk information from a cloud provider using a unified client interface. The function should take the name of the disk and the index of the disk as parameters and return the corresponding disk information. The `unity_client` is an instance of a class that abstracts the communication ... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_disk_info(name: str, idx: int, unity_client) -> dict:
"""
Retrieves disk information from a cloud provider using a unified client interface.
Args:
name (str): The name of the disk.
idx (int): The ind... |
magic_instruct_75k | 29,787 | Write a Python function to determine if a given network represented by a symmetric adjacency matrix is fully connected. The matrix contains 0s and 1s, where 1 indicates a connection between nodes and 0 indicates no connection. The function should return `True` if there is a path between every pair of nodes, and `False`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_fully_connected(matrix: List[List[int]]) -> bool:
"""
Determine if the given network represented by a symmetric adjacency matrix is fully connected.
Args:
matrix (List[List[int]]): A ... |
magic_instruct_75k | 29,801 | Write a Python function `find_function` that takes a list of functions as input. Each function in the list takes an integer as input and returns an integer. The function `find_function` should return the first function in the list that returns a value greater than 10 when given an input of 5. If no such function exists... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable, Optional
def find_function(functions: List[Callable[[int], int]]) -> Optional[Callable[[int], int]]:
"""
Finds the first function in the list that returns a value greater than 10 when given an... |
magic_instruct_75k | 29,803 | Write a Python function to construct a JSON array from a variable number of input items. Each input item is a dictionary, and the function should return a list of these dictionaries in JSON format. The function should handle any number of input items and return an empty list if no valid items are provided.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Optional
def build_list(
item_1: Optional[Dict] = None,
item_2: Optional[Dict] = None,
item_3: Optional[Dict] = None,
item_4: Optional[Dict] = None,
item_5: Optional[Dict] = None,
) ->... |
magic_instruct_75k | 29,811 | Write a Python function to convert the state information of a vessel into a 4x4 homogeneous transformation matrix. The state information consists of the vessel's position (eta) and orientation (nu). The position (eta) is a 3-element list representing x, y, and yaw (rotation around the z-axis), while the orientation (nu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import numpy as np
def convert_state_to_transformation(eta: List[float]) -> np.ndarray:
"""
Convert the vessel's state information into a 4x4 homogeneous transformation matrix.
Args:
eta (Li... |
magic_instruct_75k | 29,813 | Write a Python function to calculate the total cost and item count of items in a shopping cart. The function will take in a list of dictionaries representing the cart items, where each dictionary contains the item's name and price. The function should return a dictionary containing the total cost, item count, and the l... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def calculate_cart_total(cart_items: List[Dict[str, Union[str, float]]]) -> Dict[str, Union[float, int, List[Dict[str, Union[str, float]]]]]:
"""
Calculate the total cost and item count of i... |
magic_instruct_75k | 29,818 | Write a Python function to find and return the smallest integer in a given list of integers. The function should be efficient and handle edge cases such as an empty list or a list with all identical elements. The code should start with:
```python
from typing import List
def find_smallest_integer(nums: List[int]) -> in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_smallest_integer(nums: List[int]) -> int:
"""
Find and return the smallest integer in the given list of integers.
Args:
nums (List[int]): A list of integers from which to find the s... |
magic_instruct_75k | 29,834 | Write a Python function to process and display information about software owners. The function should read the `DESCRIPTION`, `OWNER_NAMES`, and `OWNER_EMAILS` variables from a given code snippet and output the software description along with the names and emails of the owners in a formatted manner.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
def display_software_info(code_snippet: str) -> None:
"""
Processes and displays information about software owners from a given code snippet.
Args:
code_snippet (str): A string containing the code snippet with DESCR... |
magic_instruct_75k | 29,860 | Write a Python function to find the longest string in a given list of strings. The function should return the longest string from the list. If there are multiple strings with the same maximum length, return the first one encountered.
The code should start with:
```python
from typing import List
def find_longest_strin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_longest_string(strings: List[str]) -> str:
"""
Find the longest string in a given list of strings.
Args:
strings (List[str]): A list of strings from which to find the longest string... |
magic_instruct_75k | 29,861 | Write a Python function to calculate the sum of the elements in the diagonal of a given square matrix. The matrix is represented as a 2D list of integers. The function should handle matrices of any size, including 1x1 matrices.
The code should start with:
```python
from typing import List
def diagonal_sum(matrix: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def diagonal_sum(matrix: List[List[int]]) -> int:
"""
Calculate the sum of the elements in the diagonal of a given square matrix.
Args:
matrix (List[List[int]]): A 2D list representing the s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.