source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 31,044 | Write a Python function to test different types of programmable sources for generating data. Each programmable source corresponds to a specific type of data, such as `PolyData`, `StructuredPoints`, `StructuredGrid`, `UnstructuredGrid`, `RectilinearGrid`, `Molecule`, and `Table`. The function should iterate through thes... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def test_programmable_source(argc: int, argv: List[str]) -> int:
"""
Test different types of programmable sources for generating data.
Args:
argc (int): The number of command-line arguments.... |
magic_instruct_75k | 31,056 | Write a Python function to determine if a given character is a punctuation character. A punctuation character is defined as any character that is not a letter, digit, or whitespace. The function should return `True` if the character is a punctuation character, and `False` otherwise.
The code should start with:
```pyth... | Here is the Python code to solve the given problem in the markdown block:
```python
def _is_punctuation(char: str) -> bool:
"""
Checks whether the given character is a punctuation character.
A punctuation character is defined as any character that is not a letter, digit, or whitespace.
Args:
c... |
magic_instruct_75k | 31,082 | Write a Python function to simulate a simplified trade execution API for a cryptocurrency exchange. The function should take several parameters representing the trade details and return a dictionary containing the formatted trade details.
The function should start with:
```python
def trade_api(api_key: str, symbol: st... | Here is the Python code to solve the given problem in the markdown block:
```python
def trade_api(api_key: str, symbol: str, amount: float, price: float, side: str, timestamp: int) -> dict:
"""
Simulate a simplified trade execution API for a cryptocurrency exchange.
Args:
api_key (str): The API key... |
magic_instruct_75k | 31,085 | Write a Python function to simulate rolling a standard six-sided die multiple times and return the frequency of each possible outcome. The function should take an integer `num_rolls` as input, which specifies the number of times to roll the die. The function should return a dictionary where the keys are the possible ou... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def simulate_dice_rolls(num_rolls: int) -> dict:
"""
Simulate rolling a standard six-sided die multiple times and return the frequency of each possible outcome.
Args:
num_rolls (int): The number ... |
magic_instruct_75k | 31,087 | Write a Python function to count the number of particles in a given list that match both a specified status and a specified color. Each particle is represented by a `Particle` named tuple with attributes `pdgid`, `status`, `mother_a`, `mother_b`, `color_a`, and `color_b`. The function should return the count of particl... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from collections import namedtuple
Particle = namedtuple('Particle', ['pdgid', 'status', 'mother_a', 'mother_b', 'color_a', 'color_b'])
def count_particles_with_status_and_color(particles: List[Particle], targe... |
magic_instruct_75k | 31,105 | Write a Python function to update the configuration settings for different note types in a note-taking application. The configuration settings are stored in a dictionary named `conf`, and each note type has its own settings stored within the `conf` dictionary. The function should update the `priority` setting for the s... | Here is the Python code to solve the given problem in the markdown block:
```python
def update_list_cloze_config(conf: dict, notetype_name: str) -> int:
"""
Updates the configuration settings for a specified note type in a note-taking application.
If the 'priority' setting is not explicitly defined for the ... |
magic_instruct_75k | 31,145 | Write a Python function to complete the implementation of the `convert_punct_to_number` function. The function should take the `punct_by_author` dictionary and an `author` as input, and return a list of punctuation marks converted to numerical values based on the following mapping:
- ';' should be converted to 1
- Othe... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_punct_to_number(punct_by_author: dict, author: str) -> list:
"""
Convert punctuation marks to numerical values for a specific author.
Args:
punct_by_author (dict): A dictionary where keys are authors and... |
magic_instruct_75k | 31,153 | Write a Python function to count the number of items in a dictionary whose keywords are represented as lists. The dictionary `items` contains item names as keys and their corresponding keywords as values. Each keyword can be a string or a list of strings. The function should return the count of items whose keywords are... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def count_items_with_list_keywords(items: Dict[str, any]) -> int:
"""
Counts the number of items in a dictionary whose keywords are represented as lists.
Args:
items (Dict[str, any]): A dict... |
magic_instruct_75k | 31,160 | Write a Python function to calculate the sum of all even numbers from a given list of integers. The function should read integers from standard input until the end of file is reached (EOF in Unix-like systems, Ctrl+Z in Windows). For each input line, the function should extract the integers and calculate the sum of all... | Here is the Python code to solve the given problem in the markdown block:
```python
import sys
from typing import List
def sum_of_even_numbers() -> int:
"""
Calculate the sum of all even numbers from a series of integers read from standard input.
The function reads integers from standard input until the e... |
magic_instruct_75k | 31,181 | Write a Python function `transform_ranges` that processes a list of dictionaries representing ranges and transforms them into a new list of dictionaries with modified keys and values. Each dictionary in the input list represents a range with 'start' and 'end' keys. The function should transform these ranges into a new ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def transform_ranges(ranges: List[Dict[str, int]]) -> List[Dict[str, int]]:
"""
Transforms a list of dictionaries representing ranges into a new list of dictionaries with modified keys and values.
... |
magic_instruct_75k | 31,199 | Write a Python function to extract and display the programming language and the version of the AutoRest Code Generator used to generate the code from a list of file contents. The function should take a list of strings, where each string represents the content of a file generated by the Microsoft AutoRest Code Generator... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def extract_code_info(file_contents: List[str]) -> List[Dict[str, str]]:
"""
Extracts the programming language and the version of the AutoRest Code Generator
from a list of file conte... |
magic_instruct_75k | 31,200 | Write a Python function to find the index of the first incorrect submission in a list of integers representing the results of a series of submissions in a programming contest. Each integer in the list represents the result of a submission, where `1` indicates a correct answer and `0` indicates a wrong answer. If there ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_first_incorrect(submissions: List[int]) -> int:
"""
Find the index of the first incorrect submission in a list of integers.
Args:
submissions (List[int]): A list of integers where e... |
magic_instruct_75k | 31,223 | Write a Python function to analyze network traffic data and calculate the total number of packets for each protocol type. The input data is a string `p` representing the network traffic data in the following format:
```
Protocol Source_IP Destination_IP Port
```
Each line of the input string represents a single packet ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def calculate_packet_totals(p: str) -> Dict[str, int]:
"""
Analyzes network traffic data and calculates the total number of packets for each protocol type.
Args:
p (str): A string representi... |
magic_instruct_75k | 31,230 | Write a Python function to check if the user making an HTTP request is the owner of a specific object in a web application. The function should return `True` if the user making the request is the owner of the object, and `False` otherwise. The function should also handle cases where either the `request` or `obj` object... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_permission(request, obj) -> bool:
"""
Check if the user making the request is the owner of the object.
Args:
request: An object representing the HTTP request being made. It has a `user` attribute which rep... |
magic_instruct_75k | 31,259 | Write a Python function to count the occurrences of specific HTML tags within a given HTML snippet. The function should handle both lowercase and uppercase tag names, treating them as case-insensitive. The function should return a dictionary where the keys are the HTML tags provided in the input list, and the values ar... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def count_html_tags(html_snippet: str, tags: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of specific HTML tags within a given HTML snippet.
Args:
html_snippet (s... |
magic_instruct_75k | 31,266 | Create a Python function that generates a configuration dictionary for a Python package. The configuration dictionary should include metadata such as the project name, version, author, author email, description, URL, and license. Additionally, the configuration should specify a console script entry point for the projec... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def create_package_config(name: str, version: str, author: str, author_email: str, description: str, url: str, license: str, script_name: str, package_name: str, module_name: str, function_name: str) -> Di... |
magic_instruct_75k | 31,275 | Write a Python function `target_select` that takes a list of dictionaries `data` and a string `key` as input. The function should extract the value associated with the specified key from each dictionary in the list and store these values in a new list `feat`. Ensure that the function handles cases where the key might n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def target_select(data: List[Dict[str, Any]], key: str) -> List[Any]:
"""
Extracts the value associated with the specified key from each dictionary in the input list.
If the key does not e... |
magic_instruct_75k | 31,283 | Write a Python function to create and manipulate a square image represented by a 2D list of pixels. The function should support the following operations:
1. **Initialization**: Create a new square image with a given edge length and initialize all pixels to a default value.
2. **Pixel Access**: Retrieve the value of a p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
import json
def create_square_image(edge_length: int, default_pixel_value: Any) -> List[List[Any]]:
"""
Create a new square image with the given edge length and initialize all pixels to the default ... |
magic_instruct_75k | 31,313 | Write a Python function to parse and analyze Protocol Buffer (protobuf) file metadata. The function should take a dictionary `metadata` as input and return a tuple containing the following information:
1. The number of message types defined in the protobuf file.
2. The syntax version used in the protobuf file.
The `me... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_protobuf_metadata(metadata: dict) -> tuple:
"""
Parses and analyzes the metadata of a Protocol Buffer (protobuf) file.
Args:
metadata (dict): A dictionary containing the metadata of a protobuf file.
R... |
magic_instruct_75k | 31,323 | Write a Python function to calculate the average sales from a list of sales figures. The function should handle edge cases such as an empty list and ensure that the average is computed correctly. The function should be named `calculate_average_sales` and should take a list of sales figures as its input. It should then ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average_sales(sales: List[float]) -> float:
"""
Calculate the average sales from a list of sales figures.
Args:
sales (List[float]): A list of sales figures.
Returns:
... |
magic_instruct_75k | 31,330 | Write a Python function to perform a specific analysis on microbiome data using initialized objects. The function should set a custom attribute of a user request object and then perform an alpha diversity analysis on the microbiome data. The function should return the results of the analysis.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def perform_microbiome_analysis(user_request: Any, otu_table: List[List[int]], headers: List[str], sample_labels: List[str], metadata_table: List[Dict[str, str]], taxonomic_map: Dict[str, str], metada... |
magic_instruct_75k | 31,361 | Write a Python function to evaluate a mathematical expression given in postfix notation (Reverse Polish Notation). The function should take a string as input, where the string consists of numbers and operators separated by spaces. The operators supported are addition (`+`), subtraction (`-`), multiplication (`*`), and ... | Here is the Python code to solve the given problem in the markdown block:
```python
def evaluate_postfix(expression: str) -> float:
"""
Evaluates a mathematical expression given in postfix notation (Reverse Polish Notation).
Args:
expression (str): A string representing the postfix expression, with... |
magic_instruct_75k | 31,370 | Write a Python function to prepend a given key with a constant prefix. The constant prefix is defined as `ilios.jwt.key.` and should be added to the beginning of the input key. The function should handle input validation and return the correctly prepended key.
The code should start with:
```python
def prepend_key_with... | Here is the Python code to solve the given problem in the markdown block:
```python
def prepend_key_with_prefix(key: str) -> str:
"""
Prepends a given key with a constant prefix.
Args:
key (str): The key to be prepended with the constant prefix.
Returns:
str: The key with the constant ... |
magic_instruct_75k | 31,371 | Write a Python function to generate a specific ASCII art pattern for the word "WELCOME". The function should output the pattern to the console. The pattern is a stylized text representation of the word "WELCOME" and consists of multiple lines of text. The function should start with:
```python
def generate_welcome_patte... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_welcome_pattern():
"""
Generates and prints a specific ASCII art pattern for the word "WELCOME".
This function outputs the pattern directly to the console. The pattern consists of multiple lines
of text, ea... |
magic_instruct_75k | 31,380 | Write a Python function to detect a cycle in a linked list and return the node where the cycle begins. If there is no cycle, return `None`. The linked list is represented by a class `ListNode` where each node contains an integer value and a reference to the next node in the list.
The function signature is:
```python
d... | Here is the Python code to solve the given problem in the markdown block:
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def detectCycle(head: ListNode) -> ListNode:
"""
Detects if there is a cycle in the linked list and returns the node where the cycle begin... |
magic_instruct_75k | 31,389 | Write a Python function to combine elements from two lists based on a given list of operations. The function should take three parameters: `lst` (a list of elements), `orders` (a list of operations for combining elements), and `xlst` (a list of extra elements). The function should return the result of combining element... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def combine_elements(lst: List[int], orders: List[str], xlst: List[int]) -> List[int]:
"""
Combines elements from two lists based on a given list of operations.
Args:
lst (List[int]): The li... |
magic_instruct_75k | 31,415 | Write a Python function to calculate the total amount of rainwater trapped after a rainstorm. The function should take a list of integers representing the elevation of the terrain at each position, where each integer represents the height of the terrain in units. The function should return the total amount of rainwater... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def trapped_rain(rainfall: List[int]) -> int:
"""
Calculate the total amount of rainwater trapped after a rainstorm.
Args:
rainfall (List[int]): A list of integers representing the elevation... |
magic_instruct_75k | 31,420 | Write a Python function to simulate the behavior of a function compiler that takes a function as input and compiles it into a callable object. The function takes a list of floats as input and returns a float. Your goal is to create a class `FunctionCompiler` that can compile different functions and then execute them.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, List
class FunctionCompiler:
"""
A class to simulate a function compiler that takes a function as input and compiles it into a callable object.
The function takes a list of floats as input and ... |
magic_instruct_75k | 31,428 | Write a Python function to determine whether a given set of logical implications is consistent. The implications are provided in the form of First Order Logic expressions, where each expression takes the form "A(x) ⇒ B(x)", meaning that if A(x) is true, then B(x) must also be true. The function should check if there ex... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_consistent(implications: List[str]) -> bool:
"""
Determine whether a given set of logical implications is consistent.
Args:
implications (List[str]): A list of strings where each stri... |
magic_instruct_75k | 31,434 | Implement a Python function `check_payload` that compares two payloads represented as dictionaries and determines if they match based on a set of conditions. The function should return a boolean value indicating whether the payloads match the specified criteria.
The function `check_payload(fb_payload, filter_payload)`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Optional
def check_payload(fb_payload: Dict, filter_payload: Optional[Dict]) -> bool:
"""
Compare two payloads and determine if they match based on specified conditions.
Args:
fb_payload (D... |
magic_instruct_75k | 31,454 | Write a Python function to merge multiple sorted lists into a single sorted list. The function should efficiently handle the merging process, leveraging the concept of a priority queue to maintain the order of elements as they are merged. The function should have the following signature:
```python
from typing import L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import heapq
def merge_sorted_lists(sorted_lists: List[List[int]]) -> List[int]:
"""
Merges multiple sorted lists into a single sorted list.
Args:
sorted_lists (List[List[int]]): A list of s... |
magic_instruct_75k | 31,461 | Write a Python function to calculate the variation of a given list of numbers. The variation is defined as the difference between the maximum and minimum values in the list. The function should handle empty lists by returning 0, as there is no variation in an empty list.
The code should start with:
```python
from typi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_variation(numbers: List[float]) -> float:
"""
Calculate the variation of a given list of numbers.
The variation is defined as the difference between the maximum and minimum values in t... |
magic_instruct_75k | 31,466 | Write a Python function to tokenize a given string of code by recognizing and categorizing different tokens based on predefined integer constants. The function should take a string of code as input and return a list of integers representing the tokens identified in the code. The input code will consist of valid tokens ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def tokenize_code(code: str) -> List[int]:
"""
Tokenizes a given string of code by recognizing and categorizing different tokens
based on predefined integer constants.
Args:
code (str): ... |
magic_instruct_75k | 31,480 | Write a Python function to find the second largest element in a given array of integers. If the array has fewer than two elements, the function should return an error message.
The code should start with:
```python
from typing import List
def find_second_largest(arr: List[int]) -> int or str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_second_largest(arr: List[int]) -> int or str:
"""
Finds the second largest element in a given array of integers.
Args:
arr (List[int]): A list of integers where each integer is with... |
magic_instruct_75k | 31,484 | Write a Python function to generate a payload for querying tickets in a web application's ticketing system. The payload should include the HTTP method, the endpoint for the ticket query API, any query parameters (if applicable), and the body of the request. The body of the request is generated by a function called `poo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
import random
def generate_ticket_query_payload(method: str, endpoint: str, attribute_list: List[str], num_query_attr: int) -> Dict[str, Any]:
"""
Generates a payload for querying tickets in a... |
magic_instruct_75k | 31,515 | Write a Python function to simulate a home automation system adapter that can switch between using mock data and data from an OpenHAB version 1 system. The function should be able to fetch and update data based on the selected system.
The code should start with:
```python
from typing import Dict, Any
def home_automat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def home_automation_adapter(use_mock_data: bool) -> Dict[str, Any]:
"""
Simulate a home automation system adapter that can switch between using mock data and data from an OpenHAB version 1 system.
... |
magic_instruct_75k | 31,551 | Write a Python function to map an integer `k` to a corresponding class name based on a predefined mapping. The function should return the class name if `k` is within the valid range (1 to 5), and "Invalid Class" if `k` is outside this range.
The code should start with:
```python
def classfinder(k: int) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def classfinder(k: int) -> str:
"""
Maps an integer `k` to a corresponding class name based on a predefined mapping.
Args:
k (int): The integer to map to a class name.
Returns:
str: The class name corre... |
magic_instruct_75k | 31,590 | Write a Python function `custom_path_append(directory, path_list)` that simulates the behavior of the `sys.path.append()` method. The function should take a directory (a string) and a list of paths (`path_list`) as input and return a new list of paths with the given directory appended to it. If the directory is already... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def custom_path_append(directory: str, path_list: List[str]) -> List[str]:
"""
Simulates the behavior of `sys.path.append()` by appending a directory to a list of paths.
If the directory is already p... |
magic_instruct_75k | 31,601 | Write a Python function to determine if a given number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. The function should return `True` if the number is a perfect number, and `False` otherwise.
The code should start with:
```python
def is_... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_perfect_number(num: int) -> bool:
"""
Determines if a given number is a perfect number.
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.
Args:
num... |
magic_instruct_75k | 31,610 | Write a Python function to calculate the Euclidean distance between two points in a 2D plane. The function should take the coordinates of the two points as input and return the distance as a floating-point number. The code should start with:
```python
import numpy as np
def distance_between_points(x1: float, y1: float... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def distance_between_points(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane.
Args:
x1 (float): Th... |
magic_instruct_75k | 31,613 | Write a Python function to extract model names from a given code snippet. The function should take a code snippet as a string input and return a list of model names extracted from the input code snippet. Model names are defined as the strings following the `'` character and before the comma `,` or the end of the line.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_model_names(code_snippet: str) -> List[str]:
"""
Extracts model names from a given code snippet.
Args:
code_snippet (str): The code snippet from which to extract model ... |
magic_instruct_75k | 31,615 | Write a Python function `add_prefix` that takes a list of strings `labels` and a string `prefix` as input and returns a new list containing the input strings with the specified `prefix` added to each of them. The function should handle edge cases such as an empty list of labels or an empty prefix string.
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def add_prefix(labels: List[str], prefix: str) -> List[str]:
"""
Adds a specified prefix to each string in the input list and returns the modified list.
Args:
labels (List[str]): A list of s... |
magic_instruct_75k | 31,629 | Write a Python function to extract the locator type and value from a given tuple representing a web element locator. The locator is represented as a tuple with two elements: the locator type (e.g., "By.XPATH") and the locator value (e.g., "/html/body/app/div[3]/div[2]/div/div/div/button[1]"). Your function should parse... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def extract_locator_info(locator: Tuple) -> Tuple[str, str]:
"""
Extracts the locator type and value from a given tuple representing a web element locator.
Args:
locator (tuple): A tuple re... |
magic_instruct_75k | 31,639 | Create a Python class `ROSBagReader` that simulates reading data from a ROS bag file. The class should have the following functionalities:
1. A constructor that initializes the `ROSBagReader` object.
2. A destructor that cleans up any resources used by the `ROSBagReader` object.
3. A method to open a ROS bag file and r... | Here is the Python code to solve the given problem in the markdown block:
```python
class ROSBagReader:
"""
A class to simulate reading data from a ROS bag file.
Attributes:
frame_number (int): The current frame number in the streaming session.
Methods:
__init__(): Initializes the ROSB... |
magic_instruct_75k | 31,644 | Implement a Python function `report_decoding_error` that simulates the behavior of the `reportDecodingError` method in the `MessageBuilder` class. The function should take a string `error_message` as input and return a boolean value indicating whether there are more decoding errors to handle. The function should mainta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
# Global list to store decoding errors
decoding_errors: List[str] = []
def report_decoding_error(error_message: str) -> bool:
"""
Simulates the behavior of the `reportDecodingError` method in the `Messa... |
magic_instruct_75k | 31,647 | Write a Python function to generate a Kubernetes deployment configuration based on the given input parameters. The function should take in the deployment name, namespace, match labels, and template spec labels, and return a dictionary representing the Kubernetes deployment configuration.
The function signature should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_deployment_config(name: str, namespace: str, match_labels: dict, template_spec_labels: dict) -> dict:
"""
Generates a Kubernetes deployment configuration based on the given input parameters.
Args:
name ... |
magic_instruct_75k | 31,656 | Write a Python function to count the number of positive (1) and negative (0) gravitational lenses from a given list of integers representing observed gravitational lens phenomena. The function should return a tuple containing the count of positive and negative lenses in the format `(positive_count, negative_count)`.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def count_lenses(lens_phenomena: List[int]) -> Tuple[int, int]:
"""
Counts the number of positive (1) and negative (0) gravitational lenses in the given list.
Args:
lens_phenomena (Li... |
magic_instruct_75k | 31,661 | Write a Python function to calculate the total number of pixels in an image represented as a 2D array. Each element in the 2D array represents a pixel, and each row in the array corresponds to a line of pixels in the image. The height of each line of pixels is given by the variable `pixel_per_line`, which represents th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_pixels(image: List[List[int]], pixel_per_line: int) -> int:
"""
Calculate the total number of pixels in an image represented as a 2D array.
Args:
image (List[List[int]]):... |
magic_instruct_75k | 31,669 | Write a Python function to calculate the total discount percentage for a group of children attending an event based on the number of children in the group. The discount rates are as follows:
- 2 children: 10% discount
- 3 children: 15% discount
- 4 children: 18% discount
- 5 or more children: 18% discount for the first... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_discount(num_children: int) -> int:
"""
Calculate the total discount percentage for a group of children attending an event.
The discount rates are as follows:
- 2 children: 10% discount
- 3 children: 1... |
magic_instruct_75k | 31,685 | Write a Python function to extract the names of models being created from a list of migration files. Each migration file is represented as a string, and the model names are enclosed within the `migrations.CreateModel` function calls. The model names are enclosed in single quotes and are the values of the `name` paramet... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_model_names(migration_files: List[str]) -> List[str]:
"""
Extracts the names of models being created from a list of migration files.
Args:
migration_files (List[str]): ... |
magic_instruct_75k | 31,717 | Write a Python function to perform a Caesar cipher shift on a given string. The function should accept the string to be shifted and the number of positions to shift each character. The shift should wrap around the alphabet, so shifting 'z' by 1 results in 'a'. The function should handle both uppercase and lowercase let... | Here is the Python code to solve the given problem in the markdown block:
```python
def caesar_cipher(text: str, shift: int) -> str:
"""
Perform a Caesar cipher shift on the given text.
Args:
text (str): The input string to be shifted.
shift (int): The number of positions to shift each char... |
magic_instruct_75k | 31,728 | Write a Python function to update the 'geometry' key in a dictionary representing a geographic item with a buffered geometry. The function should take a dictionary and a string representing the buffered geometry as input and return the updated dictionary.
The code should start with:
```python
def update_geometry(item:... | Here is the Python code to solve the given problem in the markdown block:
```python
def update_geometry(item: dict, buffered_geom: str) -> dict:
"""
Updates the 'geometry' key in the given dictionary with the provided buffered geometry.
Args:
item (dict): A dictionary representing a geographic item... |
magic_instruct_75k | 31,731 | Write a Python function to simulate a simplified version of a training process for a machine learning model. The function should iterate through a specified number of training steps, where at each step, a batch of training data is processed. After a certain number of steps, the function should print out the current ste... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def simulate_training_process(total_steps: int, batch_size: int, print_interval: int):
"""
Simulate a simplified training process for a machine learning model.
Args:
total_steps (int): The total ... |
magic_instruct_75k | 31,735 | Write a Python function to retrieve the ad unit ID for a mobile advertising platform. The ad unit ID is stored as a string and is dependent on the platform being used. The function should return the appropriate ad unit ID based on the platform provided as input.
The code should start with:
```python
from typing import... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def get_ad_unit_id(platform: str) -> str:
"""
Retrieves the ad unit ID for a given mobile advertising platform.
Args:
platform (str): The platform for which to retrieve the ad unit ID.
... |
magic_instruct_75k | 31,738 | Write a Python function to count the number of inversions in each permutation of a list of permutations. An inversion in a permutation occurs when there are two elements at indices `i` and `j` such that `i < j` but the element at index `i` is greater than the element at index `j`.
The function should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_inversions(permutations: List[List[int]]) -> List[int]:
"""
Counts the number of inversions in each permutation of a list of permutations.
An inversion in a permutation occurs when there a... |
magic_instruct_75k | 31,747 | Write a Python function to categorize a list of academic disciplines into distinct fields of study and count the occurrences of each field. Each discipline is represented as a string containing one or more fields of study separated by commas. The function should return a dictionary where the keys are the distinct field... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def categorize_disciplines(disciplines: List[str]) -> Dict[str, int]:
"""
Categorizes a list of academic disciplines into distinct fields of study and counts the occurrences of each field.
Arg... |
magic_instruct_75k | 31,754 | Write a Python function to format a point on a 2D plane according to a specific template and keep track of the count of points processed. The template for each point is given as follows:
```
'1 4 0 1 0 0 50 -1 20 0.000 1 0.0000 {cx} {cy} {point_radius} {point_radius} {sx} {sy} {ex} {ey}'
```
Where:
- `{cx}` and `{cy}` ... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_point(cx: int, cy: int, point_radius: int, sx: int, sy: int, ex: int, ey: int, count: int) -> (str, int):
"""
Formats a point on a 2D plane according to a specific template and updates the count of points processed.
... |
magic_instruct_75k | 31,757 | Write a Python function to calculate the total duration required to complete a sequence of operations in a factory setting. The duration of each operation is defined in the `DURATION.COUNTER` dictionary. The function should take a list of operations as input and return the total duration. If an operation is not found i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
# Mock DURATION.COUNTER dictionary for the purpose of this example
DURATION = {
"COUNTER": {
"lookupDB": 10,
"wrap": 5,
"moveRobot": 15,
"wait": 5,
"loadMachine": 20
... |
magic_instruct_75k | 31,762 | Write a Python function to process incoming messages and log the hostname along with the message content. The function should take a single argument, `message`, which represents the incoming message to be processed. The function should then return a string in the format: `<hostname> received the message: <message>`. Fo... | Here is the Python code to solve the given problem in the markdown block:
```python
import socket
def log_message(message: str) -> str:
"""
Logs the incoming message along with the hostname of the machine.
Args:
message (str): The incoming message to be processed.
Returns:
str: A stri... |
magic_instruct_75k | 31,807 | Write a Python function to determine if a cell in a 2D matrix is a local minimum. A cell is considered a local minimum if its value is less than the values of all its valid neighboring cells. The function should handle edge cases where the cell is on the boundary of the matrix.
The function should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_local_min(matrix: List[List[int]], x: int, y: int) -> bool:
"""
Determines if the cell at coordinates (x, y) in the given matrix is a local minimum.
Args:
matrix (List[List[int]]): A ... |
magic_instruct_75k | 31,815 | Write a Python function to extract the names of the top 5 communication services from a given dictionary. The dictionary contains the names of the communication services as keys and their corresponding rankings as values. The function should return the names of the top 5 communication services sorted by their rankings ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def extract_top_5_services(communication_services_top_5: Dict[str, int]) -> List[str]:
"""
Extracts the names of the top 5 communication services from a given dictionary.
Args:
communi... |
magic_instruct_75k | 31,860 | Write a Python function to count the number of elements in a given list of floats that are greater than or equal to a specified threshold. The function should be efficient and handle various edge cases, such as an empty list or a threshold that is greater than all elements in the list.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_elements_above_threshold(ref: List[float], threshold: float) -> int:
"""
Counts the number of elements in the given list that are greater than or equal to the specified threshold.
Args:
... |
magic_instruct_75k | 31,861 | Write a Python function to automate the extraction and installation of specific files from a list of Debian package files. The function should iterate through each Debian package file, extract the contents, and then move certain files to specific directories. Additionally, the function should remove a designated direct... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import subprocess
import shutil
import os
def deploy_packages(debs: List[str], dir_to_remove: str) -> None:
"""
Automates the extraction and installation of specific files from a list of Debian package f... |
magic_instruct_75k | 31,872 | Write a Python function to generate a temporary working directory and ensure it is removed when the program exits. The function should handle the case where the temporary directory creation fails. The code should start with:
```python
import os
import tempfile
import atexit
def setup_temporary_directory() -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import os
import tempfile
import atexit
def setup_temporary_directory() -> str:
"""
Creates a temporary working directory and ensures it is removed when the program exits.
Returns:
str: The path of the created temp... |
magic_instruct_75k | 31,886 | Write a Python function to decompress a memory buffer using the `zlib` library. The function should take a compressed byte string as input and return the decompressed byte string. The function should handle the allocation of memory for the decompressed result and ensure that the result is properly terminated with a nul... | Here is the Python code to solve the given problem in the markdown block:
```python
import zlib
def decompress_memory(compressed_data: bytes) -> bytes:
"""
Decompresses a memory buffer using the zlib library.
Args:
compressed_data (bytes): The compressed byte string to be decompressed.
Return... |
magic_instruct_75k | 31,912 | Write a Python function to count the number of "increasing" days in a given list of daily stock prices. An "increasing" day is defined as a day where the stock price is higher than the previous day's price.
The function should start with:
```python
from typing import List
def count_increasing_days(stock_prices: List[... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_increasing_days(stock_prices: List[int]) -> int:
"""
Counts the number of "increasing" days in a list of daily stock prices.
An "increasing" day is defined as a day where the stock price i... |
magic_instruct_75k | 31,916 | Write a Python function to merge two sorted arrays into a single sorted array without using any built-in sorting functions. The function should handle the cases where one array is longer than the other and ensure that all elements from both arrays are included in the merged result.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_arrays(a: List[int], b: List[int]) -> List[int]:
"""
Merge two sorted arrays into a single sorted array without using any built-in sorting functions.
Args:
a (List[int]): Th... |
magic_instruct_75k | 31,931 | Write a Python function to process a list of histogram data and extract specific values from each inner list to create a structured output. The function should take a list of lists as input, where each inner list contains integers representing histogram data. The function should return a list of dictionaries, where eac... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_histogram(hist_abs: List[List[int]]) -> List[Dict[str, int]]:
"""
Process a list of histogram data and extract specific values to create a structured output.
Args:
hist_abs... |
magic_instruct_75k | 31,950 | Write a Python function to convert a given hexadecimal string representation of a single byte to its corresponding binary string representation. The hexadecimal string will always be in the format "0xXX", where "XX" is a valid hexadecimal number (0-9, A-F). The function should return the binary representation as an 8-b... | Here is the Python code to solve the given problem in the markdown block:
```python
def hex_to_binary(hex_value: str) -> str:
"""
Converts a hexadecimal string representation of a single byte to its corresponding binary string representation.
Args:
hex_value (str): A string representing a hexadecim... |
magic_instruct_75k | 31,956 | Write a Python function to compile a list of high-level instructions into bytecode for a virtual machine (VM). The VM has a stack-based architecture and supports a set of instructions including `PUSH`, `ADD`, `SUB`, `MUL`, `DIV`, and `PRINT`. The function should take a list of high-level instructions as input and retur... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def compile_to_bytecode(instructions: List[str]) -> List[int]:
"""
Compiles a list of high-level instructions into bytecode for a virtual machine.
The VM supports the following instructions:
- `... |
magic_instruct_75k | 31,966 | Write a Python function to filter out specific file types from a package data dictionary and return the remaining file types. The package data dictionary contains information about the inclusion of certain file types within the package. The function should take in the package data dictionary and a list of file types to... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def filter_package_data(package_data: Dict, excluded_file_types: List[str]) -> Dict:
"""
Filters out specific file types from the package data dictionary and returns the remaining file types.
... |
magic_instruct_75k | 31,978 | Write a Python function to perform a Markov Chain Monte Carlo (MCMC) simulation for a given set of parameters and data points. The function should simulate the MCMC process for different parameter values and multiple trials, storing the results in appropriate data structures. The function should also print the progress... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def run_mcmc_simulation(anms, Ms, n_trials, mcmc_steps, mu):
"""
Perform a Markov Chain Monte Carlo (MCMC) simulation for different parameter values and multiple trials.
Args:
anms (list): A list... |
magic_instruct_75k | 31,983 | Write a Python function to generate an Nginx configuration string that handles requests for specific directories and rewrites all other requests to a PHP script. The function should include the necessary directives to achieve the following:
1. Redirect all requests to the root URL ("/") to the "index.php" script with t... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_nginx_config() -> str:
"""
Generates an Nginx configuration string that handles requests for specific directories and rewrites all other requests to a PHP script.
Returns:
str: The complete Nginx config... |
magic_instruct_75k | 32,033 | Write a Python function to process a list of JSON objects representing changes to virtualized network functions (VNFs) and extract specific information from them. The function should take a list of such JSON objects as input and return a list of tuples, where each tuple contains the VNF instance name and the VIM connec... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any, Tuple
def extract_vnf_info(changes: List[Dict[str, Any]]) -> List[Tuple[str, str]]:
"""
Extracts VNF instance names and VIM connection IDs from a list of JSON objects representing changes to ... |
magic_instruct_75k | 32,045 | Create a Python class method that initializes a table with a single value at ID 0. The method should be a factory method that adheres to best practices and encourages performance optimization. The method should be named `create_single` and should be a class method of the `Table` class. The `Table` class should have an ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any
class Table:
def __init__(self):
"""
Initialize the Table instance with an empty dictionary to store data.
"""
self.data = {}
def maybe_add_thing(self, thing: Any):
... |
magic_instruct_75k | 32,076 | Write a Python function to transpose a given 4x4 matrix. The matrix is represented as a list of lists, where each inner list represents a row of the matrix. The function should return the transposed matrix. Additionally, write a test function to verify the correctness of the transpose function by comparing the original... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose_matrix(matrix: List[List[float]]) -> List[List[float]]:
"""
Transposes a given 4x4 matrix.
Args:
matrix (List[List[float]]): A 4x4 matrix represented as a list of lists.
R... |
magic_instruct_75k | 32,077 | Implement a `MinStack` class that supports the following operations:
1. `push(x)`: Add element `x` to the top of the stack.
2. `pop()`: Remove the element on the top of the stack and return it.
3. `top()`: Return the element on the top of the stack without removing it.
4. `getMin()`: Retrieve the minimum element in the... | Here is the Python code to solve the given problem in the markdown block:
```python
class MinStack:
"""
A stack data structure that supports push, pop, top, and getMin operations.
The getMin operation retrieves the minimum element in the stack in constant time.
"""
def __init__(self):
"""
... |
magic_instruct_75k | 32,085 | Write a Python function to find the maximum sum of a submatrix that is less than or equal to a given integer `k` in a 2D matrix of integers. The function should take a 2D list `matrix` and an integer `k` as inputs and return the maximum sum of a submatrix that satisfies the condition.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import bisect
def max_sum_submatrix(matrix: List[List[int]], k: int) -> int:
"""
Find the maximum sum of a submatrix that is less than or equal to k.
Args:
matrix (List[List[int]]): A 2D lis... |
magic_instruct_75k | 32,109 | Write a Python function to generate a unique identifier for each instance of the application. The identifier should be a combination of a timestamp and a UUID, and it should be displayed in a specific format.
The code should start with:
```python
import uuid
from datetime import datetime
def generate_unique_identifie... | Here is the Python code to solve the given problem in the markdown block:
```python
import uuid
from datetime import datetime
def generate_unique_identifier() -> str:
"""
Generates a unique identifier by combining the current timestamp and a UUID.
The timestamp is formatted as "YYYY-MM-DDTHH:MM:SS" and th... |
magic_instruct_75k | 32,110 | Write a Python function to find the most frequently occurring character in a given string. If there are multiple characters with the same highest frequency, return the one that appears first in the sequence. If the input string is empty, return an empty string.
The code should start with:
```python
def findMostFrequen... | Here is the Python code to solve the given problem in the markdown block:
```python
def findMostFrequentCharacter(s: str) -> str:
"""
Find the most frequently occurring character in a given string.
If there are multiple characters with the same highest frequency,
return the one that appears first in the... |
magic_instruct_75k | 32,114 | Complete the given Python program by adding the necessary code to append the result of a calculation for the color red (`red_result`) to a list `y_r`. Additionally, print the `red_result` to the console. The calculation for `red_result` should be the sum of the lengths of the lists `y_g` and `y_b`.
The starter code is... | Here is the Python code to solve the given problem in the markdown block:
```python
# Given code snippet
y_g = []
y_b = []
# Your task is to complete the program by adding the necessary code to append the red_result to a list y_r
# Additionally, you need to print the red_result to the console
# Your code goes here
y_... |
magic_instruct_75k | 32,154 | Write a Python decorator function `ensure_decorator` that ensures the successful execution of a function by handling potential exceptions. The decorator should catch specific exceptions and retry the function a specified number of times before re-raising the exception. The `ensure_decorator` should take two arguments:
... | Here is the Python code to solve the given problem in the markdown block:
```python
def ensure_decorator(max_attempts, exceptions):
"""
A decorator factory that returns a decorator to ensure the successful execution of a function
by handling potential exceptions and retrying the function a specified number ... |
magic_instruct_75k | 32,155 | Write a Python function to schedule tasks based on their priority and arrival time. Each task is represented by a tuple `(priority, arrival_time)`, where `priority` is an integer representing the importance of the task, and `arrival_time` is a non-negative integer representing the time at which the task arrives in the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def schedule_tasks(tasks: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
"""
Schedule tasks based on their priority and arrival time.
Args:
tasks (List[Tuple[int, int]]): A list of ... |
magic_instruct_75k | 32,169 | Write a Python function to extract specific metadata information from a given dictionary. The function should take a dictionary `metadata_dict` as input and return a tuple containing the license information and a list of classifiers. The dictionary will always contain the `__license__` key and the `classifiers` key, an... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def extract_metadata(metadata_dict: Dict[str, any]) -> Tuple[str, List[str]]:
"""
Extracts the license information and a list of classifiers from the given metadata dictionary.
Args:
... |
magic_instruct_75k | 32,208 | Write a Python function to convert musical pitch intervals to semitones for a given dictionary of chord types and their corresponding pitch intervals. The function should take a dictionary where the keys are strings representing chord types (e.g., "", "m", "M7") and the values are tuples of integers representing pitch ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
def convert_intervals_to_semitones(intervals: Dict[str, Tuple[int, ...]]) -> Dict[str, int]:
"""
Converts musical pitch intervals to semitones for a given dictionary of chord types and their corre... |
magic_instruct_75k | 32,209 | Write a Python function to find the smallest positive integer that is not present in a given set of retrieved document IDs. The function should efficiently determine the smallest missing positive integer by iterating through the set.
The code should start with:
```python
def find_smallest_missing_integer(retrieved_doc... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_smallest_missing_integer(retrieved_documents: set) -> int:
"""
Find the smallest positive integer that is not present in the given set of retrieved document IDs.
Args:
retrieved_documents (set): A set of in... |
magic_instruct_75k | 32,224 | Write a Python function to rename a list of image file names according to a specific naming convention. The function should take a list of original image file names and return a list of the renamed file names in the format 'static/trials/{original_name}.png'. For example, if the original file name is "image1", it shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def rename_images(file_names: List[str]) -> List[str]:
"""
Renames a list of image file names according to the format 'static/trials/{original_name}.png'.
Args:
file_names (List[str]): A lis... |
magic_instruct_75k | 32,238 | Write a Python function `capitalize_and_filter` that takes a list of strings as input and returns a new list with each string capitalized, excluding any strings containing the word "django". The function should be case-insensitive when checking for the presence of the word "django". The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def capitalize_and_filter(input_list: List[str]) -> List[str]:
"""
Capitalizes each string in the input list and filters out any strings containing the word "django".
Args:
input_list (List[... |
magic_instruct_75k | 32,278 | Write a Python function to determine whether a given size parameter meets certain conditions for building a source. The function should handle three size options: "trivial", "medium", and "large". The function should return `1` if the size parameter meets the specified conditions, otherwise it should return `0`.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_size_condition(size: str) -> int:
"""
Determine whether the given size parameter meets the conditions for building a source.
Args:
size (str): The size parameter, which can be "trivial", "medium", or "larg... |
magic_instruct_75k | 32,290 | Write a Python function to validate a dictionary of boundary pairs. Each boundary pair consists of two boundary names separated by an equals sign. The function should return `True` if the dictionary is valid, and `False` otherwise.
The function should perform the following checks:
1. Ensure that `pBd` is a dictionary.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def validate_boundary_pairs(pBd: Dict[str, Any]) -> bool:
"""
Validate a dictionary of boundary pairs.
Args:
pBd (Dict[str, Any]): A dictionary where the keys are boundary pairs and the... |
magic_instruct_75k | 32,318 | Write a Python function to perform a mutation operation on a binary individual in a genetic algorithm. The mutation operation flips each gene in the individual with a given mutation probability. The function should take a binary individual (represented as a list of integers) and a mutation probability as input and retu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def perform_mutation(individual: List[int], mutation_probability: float) -> List[int]:
"""
Perform a mutation operation on a binary individual in a genetic algorithm.
Args:
ind... |
magic_instruct_75k | 32,335 | Create a Python class `URIQuery` that represents a query string in a Uniform Resource Identifier (URI). The class should support the following operations:
1. Insert a key-value pair into the query string.
2. Retrieve the query string representation.
The class should have the following methods:
1. `insert(self, key: st... | Here is the Python code to solve the given problem in the markdown block:
```python
class URIQuery:
def __init__(self):
"""
Initialize the URIQuery object with an empty dictionary to store key-value pairs.
"""
self.query_dict = {}
def insert(self, key: str, value: str) -> None:
... |
magic_instruct_75k | 32,340 | Write a Python function `should_install()` that determines whether there are any source files to install based on the information provided by the methods of a given class instance. The class has the following methods:
- `get_generated_sources()`: Returns a list of generated source files.
- `get_sources()`: Returns a li... | Here is the Python code to solve the given problem in the markdown block:
```python
def should_install(instance) -> bool:
"""
Determines whether there are any source files to install based on the information provided by the instance's methods.
Args:
instance: An instance of a class that has the met... |
magic_instruct_75k | 32,348 | Write a Python function to parse a given Python package's metadata and return a formatted string containing specific information. The metadata is represented as a dictionary with keys such as 'author', 'author_email', 'license', and 'classifiers'. The 'classifiers' key holds a list of strings representing various class... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_package_metadata(metadata_dict: dict) -> str:
"""
Parses a given Python package's metadata and returns a formatted string containing specific information.
Args:
metadata_dict (dict): A dictionary containin... |
magic_instruct_75k | 32,371 | Create a Python class `BookCollection` that manages a collection of `Book` objects. The class should provide functionality to add books, remove books, and retrieve information about the books in the collection. Additionally, the class should have a method to return the total number of pages in all the books combined.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class Book:
def __init__(self, title: str, author: str, page_count: int):
self.title = title
self.author = author
self.page_count = page_count
def get_title(self) -> str:
... |
magic_instruct_75k | 32,377 | Write a Python function `calculate_data_range` that calculates the range of data being processed for each block in a dataset. The function should take the following parameters:
- `N_st`: The starting index of the data being processed for the current block.
- `N_cut`: The total number of data points to be processed.
- `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_data_range(N_st: int, N_cut: int, Nt_block: int, N_div: int, Nt_inc: int) -> List[str]:
"""
Calculate the range of data being processed for each block in a dataset.
Args:
N_st ... |
magic_instruct_75k | 32,395 | Write a Python function to parse a given property map and extract the properties and their corresponding values from a provided JSON object. The property map is a dictionary that maps the property names in the JSON object to their corresponding names in the desired output. The JSON object contains various properties wi... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_property_map(property_map: dict, json_object: dict) -> dict:
"""
Parses a JSON object based on a property map and returns a new dictionary
with the properties and their corresponding values as per the property map.... |
magic_instruct_75k | 32,397 | Write a Python function to calculate the trace ratio of each pair of matrices from `c_gamma` and `c_sigma` and return the result as a list. The trace ratio of two matrices A and B is defined as the trace of A divided by the trace of B, where the trace of a matrix is the sum of its diagonal elements. The function should... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import List
def calculate_trace_ratio(c_gamma: List[np.ndarray], c_sigma: List[np.ndarray]) -> List[float]:
"""
Calculate the trace ratio of each pair of matrices from `c_gamma` and `c_sigma`.
... |
magic_instruct_75k | 32,400 | Write a Python function `process_configuration(config, machine)` that processes a configuration dictionary and performs various operations based on the data provided. The configuration dictionary contains information about machines, runners, features, and users. The function should:
1. Extract the runner name and feat... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_configuration(config, machine):
"""
Processes a configuration dictionary to extract and manipulate settings for a given machine.
Args:
config (dict): The configuration dictionary containing information a... |
magic_instruct_75k | 32,402 | Write a Python function to calculate the average of a list of numbers and return a formatted string with the average rounded to two decimal places. The function should handle an empty list by returning a specific message indicating that the list is empty.
The code should start with:
```python
from typing import List
... | 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]) -> str:
"""
Calculate the average of a list of numbers and return a formatted string.
Args:
numbers (List[float]): A list of numbers for which to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.