source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 6,093 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock within a certain number of days. The function should take two parameters: a list of integers representing the daily stock prices and an integer representing the number of days for which the stock can be held befor... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(stock_prices: List[int], days: int) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock within a certain number of days.
Args:
stock_pr... |
magic_instruct_75k | 6,110 | Write a Python function to remove all strings with a length greater than 4 from a given list of strings. The function should return the modified list. The code should start with:
```python
from typing import List
def remove_long_words(the_list: List[str]) -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_long_words(the_list: List[str]) -> List[str]:
"""
Removes all strings with a length greater than 4 from the given list.
Args:
the_list (List[str]): The list of strings from which ... |
magic_instruct_75k | 6,115 | Write a Python script that automates the installation of Node.js packages for specified components of a Hyperledger Fabric blockchain network. The script should navigate to the respective directories and execute the `npm install` command for each component. The script should be designed to run in a Unix-based environme... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
def install_node_packages(components: list) -> None:
"""
Automates the installation of Node.js packages for specified components of a Hyperledger Fabric blockchain network.
Args:
components (list): A list... |
magic_instruct_75k | 6,118 | Write a Python function to format a given datetime object into a specific string format. The function should handle cases where the input datetime object is not provided, defaulting to the current datetime. The function should return the formatted datetime string according to the specified format.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def datetime_format(dt: datetime = None, fmt: str = '%Y-%m-%d %H:%M:%S') -> str:
"""
Formats a given datetime object into a specific string format.
Args:
dt (datetime, optional): A dat... |
magic_instruct_75k | 6,142 | Write a Python function to calculate the average amount of money spent per sale for each area given a dictionary containing the number of sales and the total amount of money for each area. The function should return a new dictionary with the area names as keys and the calculated averages as values.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
def calculate_average_sales(areaDic: Dict[str, Tuple[int, int]]) -> Dict[str, float]:
"""
Calculate the average amount of money spent per sale for each area.
Args:
areaDic (Dict[str, ... |
magic_instruct_75k | 6,150 | Write a Python function to process a list of numbers by sorting it in ascending order, removing any duplicate numbers, and then printing the modified list. Additionally, the function should print a farewell message. The function should start with:
```python
from typing import List
def process_numbers(numbers: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_numbers(numbers: List[int]) -> None:
"""
Processes a list of numbers by sorting it in ascending order, removing duplicates,
and then printing the modified list. Finally, it prints a farew... |
magic_instruct_75k | 6,151 | Write a Python function to sort a dictionary of content items based on the following criteria:
1. Published content should appear before unpublished content.
2. Among published content, items should be sorted based on their urgency level in descending order (higher urgency first).
3. Among unpublished content, items sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def sort_content_items(content_items: Dict[str, Dict[str, bool]]) -> List[str]:
"""
Sorts content items based on the following criteria:
1. Published content should appear before unpublished co... |
magic_instruct_75k | 6,179 | Write a Python function to calculate the sum of all the digits in a given integer. The function should take an integer as input and return the sum of its digits. The code should start with:
```python
def calculate_digit_sum(number: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_digit_sum(number: int) -> int:
"""
Calculate the sum of all digits in a given integer.
Args:
number (int): The integer whose digits are to be summed.
Returns:
int: The sum of the digits of... |
magic_instruct_75k | 6,186 | Write a Python function to update a dictionary representing a music track with a set of tags that should only be added if they are missing in the track. The function should follow these rules:
1. If a tag in `tags_to_set` is missing in the `track`, it should be added to the `track` with a value of `None`.
2. If a tag i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Set
def update_track_tags(track: Dict[str, str], tags_to_set: Set[str]) -> Dict[str, str]:
"""
Updates the given track dictionary with tags from the tags_to_set that are missing.
Args:
trac... |
magic_instruct_75k | 6,225 | Write a Python function to sort a given list of numbers with specific requirements. The input list `num` contains two sublists. The first sublist `num[0]` contains integers, and the second sublist `num[1]` contains lists of integers. The function should return a new list with the following modifications:
1. Sort the in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def sort_lists(num: List[Union[List[int], int]]) -> List[Union[List[int], int]]:
"""
Sorts the integers in the first sublist and each sublist of integers in the second sublist of the given list.
... |
magic_instruct_75k | 6,236 | Implement a Python class `Scheduler` that simulates a simple scheduler with the following functionalities:
1. **Start the scheduler**: The method `start_scheduler()` should start the scheduler and print "Chocks away!" to indicate that the scheduler is running.
2. **Stop the scheduler**: The method `stop_scheduler()` sh... | Here is the Python code to solve the given problem in the markdown block:
```python
import time
class Scheduler:
def __init__(self):
"""
Initialize the Scheduler with start time, setpoint, and running status.
"""
self.__start_time = None
self.__setpoint = 0
self.__ru... |
magic_instruct_75k | 6,277 | Write a Python function to simulate a simple file management system. The function should take a list of file operations and return the final state of the file system after executing these operations. Each file operation is represented as a tuple with two elements: the operation type ("create", "delete", or "read") and ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def simulate_file_system(operations: List[Tuple[str, str]]) -> List[str]:
"""
Simulates a simple file management system based on a list of file operations.
Args:
operations (List[Tupl... |
magic_instruct_75k | 6,300 | Write a Python function to manage a library's book inventory using an ORM (Object-Relational Mapping) library. The function should ensure that each publisher has at most one book associated with them. The function should take a publisher object and the name of a book as input and return a boolean value indicating wheth... | Here is the Python code to solve the given problem in the markdown block:
```python
def manage_book_inventory(publisher, book_name) -> bool:
"""
Manages the book inventory for a given publisher using an ORM library.
This function ensures that each publisher has at most one book associated with them.
It... |
magic_instruct_75k | 6,311 | Write a Python function to configure the training process for a deep learning model. The function should take the following input parameters:
- `auxiliary_head`: A dictionary containing the number of classes for the auxiliary head of the model.
- `test_cfg`: A dictionary specifying the testing configuration, including ... | Here is the Python code to solve the given problem in the markdown block:
```python
def configure_model(auxiliary_head: dict, test_cfg: dict, optimizer: dict) -> (dict, dict):
"""
Configures the training process for a deep learning model by generating the model and optimizer configurations.
Args:
a... |
magic_instruct_75k | 6,317 | Write a Python function to generate a list of 16 consecutive experiment IDs starting from a given starting ID. Each experiment ID should be incremented by 1 from the previous one. The function should return a list of these experiment IDs.
The code should start with:
```python
from typing import List
def generate_expe... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_experiment_ids(starting_id: int) -> List[int]:
"""
Generate a list of 16 consecutive experiment IDs starting from a given starting ID.
Args:
starting_id (int): The starting expe... |
magic_instruct_75k | 6,327 | Write a Python function to filter a queryset based on the day of the week. The function should take a queryset and a day of the week as input and return the filtered queryset containing only the records created on the specified day of the week. The day of the week is represented by an integer where 0 corresponds to Mon... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from datetime import datetime
def filter_by_week_day(queryset: List[dict], value: int) -> List[dict]:
"""
Return a filtered queryset containing records created on the specified day of the week.
Args... |
magic_instruct_75k | 6,331 | Create a Python class `Sandwich` that manages sandwich ingredients. The class should provide methods to add ingredients, remove ingredients, and retrieve the current list of ingredients. The class should be designed to handle various operations efficiently and ensure that the ingredients are managed correctly.
The sta... | Here is the Python code to solve the given problem in the markdown block:
```python
class Sandwich:
def __init__(self):
"""
Initialize the Sandwich class with an empty list of ingredients.
"""
self.ingredients = []
def AddIngredient(self, ingredient: str) -> None:
"""
... |
magic_instruct_75k | 6,371 | Write a Python function to process a list of model options and their corresponding ordering options. The function should take in a list of tuples, where each tuple represents a model and its ordering option. The ordering option is a dictionary with the model's field as the key and the ordering direction as the value. T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def process_model_options(model_options: List[Tuple[str, Dict[str, List[str]]]]) -> Dict[str, List[str]]:
"""
Processes a list of model options and their corresponding ordering options.
... |
magic_instruct_75k | 6,441 | Write a Python function to generate the content of a `setup.py` file for a given package. The `setup.py` file is used to describe the package metadata and dependencies, making it easier for users to install and use the package. The function should take the following parameters:
- `name` (string): The name of the packag... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_setup_py(name: str, keywords: list, url: str, license: str) -> str:
"""
Generates the content of a `setup.py` file for a given package.
Args:
name (str): The name of the package.
keywords (list)... |
magic_instruct_75k | 6,459 | Write a Python function to determine the unstable increment of a given version tag. The unstable increment is defined as the last digit of the unstable version tag. The function should take the unstable version tag as input and return the unstable increment as an integer.
The code should start with:
```python
def get_... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_unstable_increment(unstable_version: str) -> int:
"""
Extracts the unstable increment from a given version tag.
The unstable increment is defined as the last digit of the unstable version tag.
Args:
uns... |
magic_instruct_75k | 6,465 | Write a Python function to calculate the Euclidean distance between each pair of 3D vertices and find the pair with the shortest distance. The vertices are provided in a list of strings, where each string represents a vertex in the format "VRTX id x y z". The function should return a tuple containing the identifiers of... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import math
def shortest_distance(vertices: List[str]) -> Tuple[int, int]:
"""
Calculate the Euclidean distance between each pair of 3D vertices and find the pair with the shortest distance.
... |
magic_instruct_75k | 6,468 | Write a Python function to clean up a list of car issues by removing any leading or trailing whitespace, converting the strings to lowercase, and removing any duplicate entries. The function should also sort the list in ascending order. The function should start with:
```python
from typing import List
def clean_car_is... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def clean_car_issues(car_issues: List[str]) -> List[str]:
"""
Cleans up a list of car issues by removing leading/trailing whitespace, converting to lowercase,
removing duplicates, and sorting the lis... |
magic_instruct_75k | 6,476 | Write a Python function to determine if any shape nodes in a list have default shaders applied. A default shader is represented by the string "default_shader". The function should return `True` if any shape node has a default shader applied, and `False` otherwise. The function should handle different input cases effici... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def has_default_shaders(shape_nodes: List[str]) -> bool:
"""
Determines if any shape nodes in the given list have default shaders applied.
Args:
shape_nodes (List[str]): A list of shape node... |
magic_instruct_75k | 6,480 | Create a Python script to automate the cleanup of Kubernetes pods that are not in the "Running" or "Completed" state within a specified namespace. The script should identify such pods and force delete them to ensure the namespace remains in a clean and functional state. The script should handle errors and edge cases ap... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def cleanup_pods(namespace: str):
"""
Automates the cleanup of Kubernetes pods that are not in the "Running" or "Completed" state within a specified namespace.
Args:
namespace (str): The Kubernete... |
magic_instruct_75k | 6,509 | Write a Python function to count the total number of mobs spawned at each coordinate in a game world grid. The function should take a list of mob spawn requests and return a dictionary where the keys are the coordinates (as tuples) and the values are the total number of mobs spawned at those coordinates. Each spawn req... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def count_mobs_spawned(spawn_requests: List[Tuple[int, int, int, bool]]) -> Dict[Tuple[int, int], int]:
"""
Counts the total number of mobs spawned at each coordinate in a game world grid.
... |
magic_instruct_75k | 6,510 | Write a Python function to process a list of dictionaries representing menu items and their properties. Each dictionary contains the following keys: 'name' (string), 'link_url' (string), and 'menu' (string). The function should return a new list of dictionaries with the same menu items, but with the 'link_url' values m... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_menu_items(menu_items: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Processes a list of dictionaries representing menu items and modifies the 'link_url' values.
Args:
... |
magic_instruct_75k | 6,511 | Write a Python function to generate a command-line string for configuring a natural language processing (NLP) model based on given input parameters. The function should take the following parameters:
- `output_dir` (string): The directory where the output will be stored.
- `from_pretrained` (string): The path to the pr... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_command(output_dir: str, from_pretrained: str, batch_size: int, init_checkpoint: str, n_samples: int, doc_stride: int, language: str) -> str:
"""
Generates a command-line string for configuring an NLP model based on... |
magic_instruct_75k | 6,519 | Write a Python function to calculate the result of raising a given base number `num` to the power of an exponent `n` without using the built-in exponentiation operator (`**`) or any built-in functions from the `math` module. The function should be named `custom_power` and should take two parameters:
- `num` (integer): ... | Here is the Python code to solve the given problem in the markdown block:
```python
def custom_power(num: int, n: int) -> int:
"""
Calculate the result of raising a base number `num` to the power of an exponent `n`
without using the built-in exponentiation operator (`**`) or the `math` module.
Args:
... |
magic_instruct_75k | 6,528 | Write a Python function to calculate the total distance traveled by a particle moving along a straight line. The particle starts at the origin (position 0) and moves to various positions specified in a list. Each position in the list represents the distance traveled from the previous position. The function should take ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_distance(positions: List[int]) -> int:
"""
Calculate the total distance traveled by a particle moving along a straight line.
The particle starts at the origin (position 0) and mo... |
magic_instruct_75k | 6,532 | Write a Python function to generate a dictionary map for a given enumeration and its corresponding display names. The function should take a list of enumeration values and a `displayName` as input and generate a dictionary that maps the enumeration values to their respective display names.
The enumeration values are r... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_string_map(enum_items: List[str], display_name: str) -> Dict[str, str]:
"""
Generates a dictionary map for a given enumeration and its corresponding display names.
Args:
e... |
magic_instruct_75k | 6,536 | Write a Python function to calculate the final value of the variable `cur` after executing a given code snippet that manipulates `cur` and iterates through a while loop. The code snippet is as follows:
```python
cur += 2
i = 0
while i < Number_of_static_fields:
i += 1
cur += 4
```
Where `Number_of_static_field... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_final_cur_value(Number_of_static_fields: int) -> int:
"""
Calculate the final value of the variable `cur` after executing the given code snippet.
The code snippet manipulates `cur` as follows:
1. Initializ... |
magic_instruct_75k | 6,547 | Write a Python function to simulate a simplified version of the `brew install` command used in Homebrew, a package manager for macOS. The function should take a list of package names to install and a dictionary representing the current ownership status of the brew directories. The function should update the ownership s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def install_packages(packages: List[str], ownership_status: dict) -> List[str]:
"""
Simulates the installation of packages using Homebrew and updates the ownership status of brew directories.
Args:
... |
magic_instruct_75k | 6,552 | Write a Python function to list all the file paths present in a file system represented by a nested dictionary. The file system object is structured such that keys are file or directory names, and values are either strings (representing file contents) or nested dictionaries (representing subdirectories). The function s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def list_file_paths(file_system: Dict) -> List[str]:
"""
Lists all the file paths present in a file system represented by a nested dictionary.
Args:
file_system (Dict): A nested dictio... |
magic_instruct_75k | 6,566 | Write a Python function to extract task dates that fall within a specified month from a list of task strings. Each task string is formatted as "task_name_task_date_task_month", where `task_name` is a string without spaces, `task_date` is an integer representing the day of the month, and `task_month` is an integer repre... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_task_dates(tasks: List[str], target_month: int) -> List[int]:
"""
Extracts task dates that fall within a specified month from a list of task strings.
Args:
tasks (List[str]): A l... |
magic_instruct_75k | 6,574 | Write a Python function to check if all applications in a given list have achieved the requested state. The function should return `True` if all applications are in the requested state, and `False` otherwise. The application states are represented as boolean values, where `True` indicates that the application has achie... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def check_application_state(application_states: List[bool]) -> bool:
"""
Check if all applications in the given list have achieved the requested state.
Args:
application_states (List[bool]):... |
magic_instruct_75k | 6,603 | Write a Python function to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring case. The function should return `True` if the string is a palindrome, and `False` otherwise. The code should start with:
```python
def is_palindrome(s: str) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(s: str) -> bool:
"""
Determine if a given string is a palindrome, considering only alphanumeric characters and ignoring case.
Args:
s (str): The input string to check.
Returns:
bool: T... |
magic_instruct_75k | 6,606 | Write a Python function to determine the order in which tasks should be executed to satisfy all dependencies. The function should take a list of tuples as input, where each tuple represents a task and its dependencies. The first element of the tuple is the task name, and the second element is a list of dependencies for... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def workflow_order(tasks: List[Tuple[str, List[str]]]) -> List[str]:
"""
Determine the order in which tasks should be executed to satisfy all dependencies.
Args:
tasks: A list of tupl... |
magic_instruct_75k | 6,613 | Implement a `Tokenize` method for a simple parser of a fictional language called "Rook." The method should convert a source code string into a stream of tokens that the parser can consume. Each token should be identified and extracted based on the rules defined by the Rook language grammar.
The Rook language grammar i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
class TokenStream:
def __init__(self, tokens: List[Tuple[str, str]]):
self.tokens = tokens
self.index = 0
def next_token(self) -> Tuple[str, str]:
if self.index ... |
magic_instruct_75k | 6,624 | Write a Python function to parse a video file name string and extract the video title and its properties. The properties are enclosed within square brackets and separated by a single space. Each property is in the format "key=value". The function should return a dictionary containing the video title and its properties.... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_video_info(video_name: str) -> dict:
"""
Parses a video file name string to extract the video title and its properties.
Args:
video_name (str): The input string representing the video file name.
Retur... |
magic_instruct_75k | 6,631 | Write a Python function to simulate a game where a player tries to guess the values of `k` pixels in a grayscale image represented as a 2D array of integers. The player earns a point for each correct guess of a pixel's value. The function should return the total score achieved by the player.
The function should start ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def guess_pixels(image: List[List[int]], k: int, guesses: List[Tuple[int, int]]) -> int:
"""
Simulates a game where a player tries to guess the values of k pixels in a grayscale image.
The pla... |
magic_instruct_75k | 6,640 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. The function should take a list of integers representing the daily stock prices and return the maximum profit that can be achieved. The function 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
def max_profit(stock_prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock on different days.
Args:
stock_prices (List[int]): A list ... |
magic_instruct_75k | 6,652 | Write a Python function to decode a series of encoded messages based on a given mapping. The mapping consists of integer numbers and their corresponding encoded messages. Each encoded message is a string of characters. Your program should take a list of integers as input and return the decoded messages based on the pro... | Here is the Python code to solve the given problem in the markdown block:
```python
def decode_messages(mapping: dict, input_list: list) -> list:
"""
Decodes a series of encoded messages based on a given mapping.
Args:
mapping (dict): A dictionary where the keys are integers and the values are the ... |
magic_instruct_75k | 6,663 | Write a Python function to generate the necessary code for a slider widget in JavaScript that represents time in discrete intervals. The slider should have a minimum value of 0 and a maximum value of `J - 1`, with each step representing a unit of time. The initial value of the slider should be set to 0. The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_slider_code(J: int) -> str:
"""
Generates JavaScript code for a slider widget that represents time in discrete intervals.
The slider has a minimum value of 0 and a maximum value of J - 1, with each step represe... |
magic_instruct_75k | 6,671 | Write a Python function to process log data and extract throughput and latency information from each log line. The log data is provided as a list of strings, where each string represents a line from the log. The function should extract the throughput and latency values from each line and organize them into separate lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
def process_log_data(log_lines: List[str]) -> Tuple[List[List[float]], List[List[float]]]:
"""
Processes log data to extract throughput and latency information from each log line.
A... |
magic_instruct_75k | 6,689 | Write a Python function to determine whether a given number is a prime number efficiently. The function should take an integer as input and return `True` if the number is prime, and `False` otherwise. The function should handle large input values efficiently and should not use any external libraries or built-in functio... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(n: int) -> bool:
"""
Determines whether a given number is a prime number.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
... |
magic_instruct_75k | 6,710 | Write a Python function to retrieve a specific party from a list of parties based on its ID. The function should return the party details if found, or an error message if the party with the given ID does not exist in the list. The function should return a complete response with the party details and an HTTP status code... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def get_specific_party(id: int, parties: List[Dict[str, any]]) -> Tuple[Dict[str, any], int]:
"""
Retrieves a specific party from a list of parties based on its ID.
Args:
id (in... |
magic_instruct_75k | 6,722 | Write a Python function `country_codes_to_numbers(codes)` that takes a list of country codes as input and returns a list of their corresponding numerical values. If a country code is not found in the given snippet, it should be assigned a value of -1.
Function Signature:
```python
def country_codes_to_numbers(codes: L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def country_codes_to_numbers(codes: List[str]) -> List[int]:
"""
Maps a list of country codes to their corresponding numerical values.
Args:
codes (List[str]): A list of country codes, each ... |
magic_instruct_75k | 6,724 | Write a Python function to convert a floating-point number to its fixed-point representation. The fixed-point representation is obtained by multiplying the floating-point number by 2 raised to the power of the number of fractional bits and then rounding the result to the nearest integer. The function should handle both... | Here is the Python code to solve the given problem in the markdown block:
```python
def fxp(number: float, fractionalBits: int) -> int:
"""
Converts a floating-point number to its fixed-point representation.
The fixed-point representation is obtained by multiplying the floating-point number
by 2 raised... |
magic_instruct_75k | 6,734 | Create a Python function to simulate a simple error checking system for a document processing application. The system should allow the registration of different severity levels of checks and provide a mechanism to consume the results of these checks. The function should start with:
```python
from typing import Callable... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Dict, List
def register_check(severity: int, check_fn: Callable[[int, str], None], registry: Dict[int, List[Callable[[int, str], None]]]) -> None:
"""
Register a check function with a given severity... |
magic_instruct_75k | 6,743 | Write a Python function to calculate the remaining capacity of a storage system based on the current usage and the total capacity. The function should take in two parameters: `current_usage` and `total_capacity`, both of which are non-negative integers. The remaining capacity should be returned as an integer.
The rema... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_capacity(current_usage: int, total_capacity: int) -> int:
"""
Calculate the remaining capacity of a storage system based on the current usage and the total capacity.
Args:
current_usage (int): The curr... |
magic_instruct_75k | 6,778 | Write a Python function to decode a URI (Uniform Resource Identifier) that has been encoded using the UTF-8 encoding scheme. The function should handle the decoding process by replacing '+' characters with spaces and converting any percent-encoded sequences back to their original characters.
The code should start with... | Here is the Python code to solve the given problem in the markdown block:
```python
def decode_uri(encoded_uri: str) -> str:
"""
Decodes a URI that has been encoded using the UTF-8 encoding scheme.
Args:
encoded_uri (str): The encoded URI string.
Returns:
str: The decoded URI string.
... |
magic_instruct_75k | 6,793 | Write a Python function to filter a list of assets based on a specified type. Each asset is represented as a dictionary with keys 'name', 'type', and 'class'. The function should take in the list of assets and a type as input, and return a new list containing only the assets of the specified type. If no assets of the s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_assets_by_type(assets: List[Dict[str, str]], asset_type: str) -> List[Dict[str, str]]:
"""
Filters a list of assets based on a specified type.
Args:
assets (List[Dict[str, s... |
magic_instruct_75k | 6,805 | Write a Bash script that processes command-line arguments to set input and output directories for a data processing task. The script should handle the options `-i` for input directory and `-o` for output directory. Once the script is executed, it should process the provided arguments and then shift the positional param... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Initialize variables
indir=""
outdir=""
# Process command-line arguments
while getopts ":i:o:" opt; do
case ${opt} in
i )
indir=$OPTARG
;;
o )
outdir=$OPTARG
;;
\? )
echo "Invali... |
magic_instruct_75k | 6,812 | Write a Python function to find the minimum score achieved by any participant in a competition. The function should take a list of integers representing the scores of participants and return the minimum score. The function should handle edge cases such as an empty list and a list with a single element.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_minimum_score(scores: List[int]) -> int:
"""
Find the minimum score achieved by any participant in a competition.
Args:
scores (List[int]): A list of integers representing the score... |
magic_instruct_75k | 6,818 | Write a Python function to simulate a plugin registration system for a game engine. The game engine provides a set of hooks that plugins can register to, allowing them to execute custom code at specific points during the game's runtime. Your task is to implement the plugin registration system using the provided code sn... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Optional
# Mock functions to simulate the game engine's API
def register_modules(modules: list) -> None:
"""Simulates the registration of modules."""
print(f"Registered modules: {modules}")
def dom... |
magic_instruct_75k | 6,845 | Write a Python function to generate AWS Cloud Development Kit (CDK) synthesis commands for a list of template names. Each template name represents a specific resource or configuration that needs to be provisioned in the AWS environment. The function should return a list of commands that can be executed to synthesize th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_cdk_commands(template_names: List[str]) -> List[str]:
"""
Generates AWS CDK synthesis commands for a list of template names.
Args:
template_names (List[str]): A list of template... |
magic_instruct_75k | 6,862 | Create a Python function to estimate the ideal point for the Tchebycheff decomposition method in a multi-objective optimization problem. The ideal point is the point where each objective function achieves its minimum value. The function should take a list of objective functions and a list of initial points as input and... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def estimate_ideal_point(objective_functions: List[Callable[[List[float]], float]], initial_points: List[List[float]]) -> List[float]:
"""
Estimate the ideal point for the Tchebycheff decomposi... |
magic_instruct_75k | 6,866 | Write a Python script to automate the installation of a device driver on a Windows system. The script should use the provided variables and directory paths to locate and install the driver file. The script should accomplish the following:
1. Construct the full path to the driver file by concatenating the `drivername` w... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import shutil
def install_driver(drivername: str, DDK_DIR: str) -> None:
"""
Automates the installation of a device driver on a Windows system.
Args:
drivername (str): The name of the driver file without ... |
magic_instruct_75k | 6,893 | Write a Python function to extract specific information from a given dictionary representing a Python package's metadata. The function should return a dictionary containing the values associated with the keys 'author', 'author_email', 'license', 'url', 'install_requires', and 'packages'. If a key is not present in the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any, List
def extract_package_info(package_metadata: Dict[str, Any]) -> Dict[str, Any]:
"""
Extracts specific information from a given dictionary representing a Python package's metadata.
Args:
... |
magic_instruct_75k | 6,896 | Write a Python function to simulate a simplified version of the ZFS clone operation. The function should take two string arguments: `snapshot` and `destination`. The `snapshot` argument represents the name of the snapshot to be cloned, and the `destination` argument represents the name of the new dataset to be created.... | Here is the Python code to solve the given problem in the markdown block:
```python
def zfs_clone(snapshot: str, destination: str) -> str:
"""
Simulates a simplified version of the ZFS clone operation.
Args:
snapshot (str): The name of the snapshot to be cloned.
destination (str): The name ... |
magic_instruct_75k | 6,931 | Write a Python function `determine_strategy_and_reset(device_name, package)` that takes in the `device_name` and `package` as input parameters and returns a tuple `(strategy, reset_usage)`. The function should determine the appropriate synthesis strategy and the usage of asynchronous reset based on the given code snipp... | Here is the Python code to solve the given problem in the markdown block:
```python
def determine_strategy_and_reset(device_name: str, package: str) -> tuple:
"""
Determine the appropriate synthesis strategy and the usage of asynchronous reset based on the device name and package.
Args:
device_name... |
magic_instruct_75k | 6,941 | Create a Python class `FenceManager` that manages the synchronization of multiple threads using fences and events. The class should provide methods for creating fences, signaling fences, and waiting for fences to be signaled. The implementation should be thread-safe and handle potential race conditions.
The class shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from threading import Event, Lock
from typing import Dict
class FenceManager:
def __init__(self):
"""
Initialize the FenceManager with a dictionary to store fence events and a lock for thread safety.
"""
... |
magic_instruct_75k | 6,943 | Write a Python function to simulate the image processing and display functionality of the `ImageProcessor` class described in the given C++ code snippet. The function should accept a list of image processing operations, input image file, and display settings (width, height, fps). The function should then apply the oper... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_and_display_image(operations: List[str], input_file: str, display_settings: Tuple[int, int, int]) -> None:
"""
Simulates the image processing and display functionality of the ImageProc... |
magic_instruct_75k | 6,953 | Write a Python function to extract attributes and their values from HTML input tags. The function should take a string of HTML code as input and return a dictionary where the keys are the attribute names and the values are the corresponding attribute values. The function should handle multiple input tags and return a l... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def extract_attributes(html_code: str) -> List[Dict[str, str]]:
"""
Extracts attributes and their values from HTML input tags.
Args:
html_code (str): A string representing th... |
magic_instruct_75k | 6,965 | Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should return 0 if the input list is empty or contains only non-positive integers. The function should be efficient and use an optimal approach to solve the problem.
The code should start with:
```pyt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
"""
Find the maximum sum of a contiguous subarray within the given list of integers.
Args:
nums (List[int]): The list of integers from which to ... |
magic_instruct_75k | 6,967 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make any profit, return 0.
The function should start with:
```python
from typing import List
def max_profit(pr... | 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 at most once.
Args:
prices (List[int]): A list of integers repre... |
magic_instruct_75k | 6,969 | Write a Python function to parse a configuration dictionary for a machine learning model using TensorFlow's `tf.app.flags` module. The function should extract and return specific hyperparameters and settings from the configuration dictionary. The function should handle the absence of any flag gracefully by returning `N... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_model_configuration(config_dict: dict) -> dict:
"""
Parses a configuration dictionary for a machine learning model and extracts specific hyperparameters and settings.
Args:
config_dict (dict): A dictionary... |
magic_instruct_75k | 6,983 | Write a Python function to invert the block status of devices in a network management system. Each device is represented by a dictionary containing its MAC address, name, block status, and download limit. The block status is a string that can be either "1" (blocked) or "0" (unblocked). The function should return a new ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def invert_block_status(devices: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Inverts the block status of each device in the given list of device dictionaries.
Args:
devices (Lis... |
magic_instruct_75k | 6,994 | Write a Python function to shift the pixels in each row of a given image array by a specified amount to the left. The image is represented as a 2D array of pixel values. The function should take the original image array and the shift amount as input and return the transformed image array.
The code should start with:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def shift_image_pixels(image_array: np.ndarray, shift_amount: int) -> np.ndarray:
"""
Shifts the pixels in each row of the image array by the specified amount to the left.
Args:
image_array (np.n... |
magic_instruct_75k | 7,006 | Write a Python function to process a namespace string representing a job package in a modular system. The function should extract and return the following information:
1. The top-level module name.
2. The sub-modules (if any) in the namespace.
3. The specific job category.
The namespace string is structured using back... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple, List
def process_namespace(namespace: str) -> Tuple[str, List[str], str]:
"""
Processes a namespace string representing a job package in a modular system and extracts the following information:
1. ... |
magic_instruct_75k | 7,035 | Write a Python function to generate a summary report of average salaries for each department from a list of employee records. Each employee record is represented as a dictionary containing the employee's name, department, and salary. The function should return a dictionary where the keys are department names and the va... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_salary_summary(employee_records: List[Dict[str, any]]) -> Dict[str, float]:
"""
Generates a summary report of average salaries for each department from a list of employee records.
... |
magic_instruct_75k | 7,040 | Write a Python function to parse a given text to identify and extract specific types of data. The function should identify and remove specific type prefixes from the beginning of the text and return the extracted type. The types to be identified are "void*", "void", and "bool". The function should handle the removal of... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
from typing import Optional
class Types(Enum):
VoidStar = 1
Void = 2
Bool = 3
def parse_type(text: str) -> Optional[Types]:
"""
Parses the given text to identify and extract specific types of ... |
magic_instruct_75k | 7,059 | Write a Python function to find all occurrences of a given substring within a larger string and return a list of indices where the substring is found. If the substring is not found, the function should return an empty list. The function should be efficient and handle edge cases such as empty strings and substrings that... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_all_occurrences(main_string: str, sub_string: str) -> List[int]:
"""
Finds all occurrences of a given substring within a larger string and returns a list of indices.
Args:
main_stri... |
magic_instruct_75k | 7,072 | Write a Python function to join a list of strings with a specified delimiter, handling cases where the input list is empty or contains only empty strings. The function should return an empty string if the input list is empty or contains only empty strings.
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 join_strings(strings: List[str], delimiter: str) -> str:
"""
Joins a list of strings with a specified delimiter, handling cases where the input list is empty or contains only empty strings.
Args... |
magic_instruct_75k | 7,095 | Write a Python function to calculate the final position of a 3D model after applying an offset in a 3D game environment. The function should take in the offset values, the name of the model to be reparented, and the name of the new node to which the model will be reparented. The function should return the final positio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def calculate_final_position(offset: Tuple[float, float, float], model: str, new_node_name: str) -> Tuple[float, float, float]:
"""
Calculate the final position of a 3D model after applying an offset in... |
magic_instruct_75k | 7,096 | Write a Python function to automate the unmounting and detaching of a disk image on a macOS system. The function should take the mount path and disk identifier as input and perform the necessary operations to unmount and detach the disk image. Additionally, it should remove any residual files at the mount path. The fun... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def unmount_and_detach_disk(mount_path: str, disk_identifier: str) -> None:
"""
Automates the unmounting and detaching of a disk image on a macOS system.
Args:
mount_path (str): The path... |
magic_instruct_75k | 7,105 | Write a Python function `calculateSum` that takes in an array of integers `arr` and returns the sum of all the positive integers in the array. The function should iterate through the array, check if each number is positive, and if so, add it to the result. The function should start with:
```python
from typing import Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculateSum(arr: List[int]) -> int:
"""
Calculate the sum of all positive integers in the given array.
Args:
arr (List[int]): The array of integers from which to calculate the sum of po... |
magic_instruct_75k | 7,115 | Write a Python function to calculate the total number of iterations for a machine learning model's training and evaluation loops. The function should take two integers as input: `train_epochs` and `eval_epochs`, representing the number of epochs for training and evaluation, respectively. The function should return the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_iterations(train_epochs: int, eval_epochs: int) -> int:
"""
Calculate the total number of iterations for a machine learning model's training and evaluation loops.
Args:
train_epochs (int): The nu... |
magic_instruct_75k | 7,126 | Write a Python function to determine the visibility and content of a security scanner disabled repository badge based on the given conditions. The function should return a dictionary containing the badge's visibility status and the badge's message, including a tooltip if specified.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def scanner_disabled_repository_badge(scanner_disabled: bool, with_tooltip: bool = False) -> dict:
"""
Determine the visibility and content of a security scanner disabled repository badge.
Args:
scanner_disabled (bo... |
magic_instruct_75k | 7,129 | Write a Python function to test isolated labels in a given dataset using Principal Component Analysis (PCA) and neighbor computation. The function should take a single parameter, `adata_batch`, which represents a batch of annotated data. The function should perform the following steps:
1. Retrieve the annotated data fr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any
def test_isolated_labels(adata_batch: Any) -> str:
"""
Test isolated labels in a given dataset using Principal Component Analysis (PCA) and neighbor computation.
Args:
adata_batch (Any): A ba... |
magic_instruct_75k | 7,148 | Write a Python function to manage a list of structured elements, where each element has a text field. The function should allow for the creation and manipulation of this list of structured elements. Specifically, the function should:
1. Initialize a list with a specified number of structured elements.
2. Provide method... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_structured_list(size: int) -> List[str]:
"""
Create a list of structured elements with a specified size.
Args:
size (int): The number of structured elements to initialize.
Re... |
magic_instruct_75k | 7,173 | Write a Python function to determine the number of unique paths in a grid from the top-left corner to the bottom-right corner, considering obstacles in the grid. The grid is represented as a 2D list where `0` indicates a free cell and `1` indicates an obstacle. The function should return the number of unique paths from... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def unique_paths_with_obstacles(grid: List[List[int]]) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner in a grid with obstacles.
Args:
gr... |
magic_instruct_75k | 7,179 | Write a Python function to generate a Habitat plan file based on the given package information. The function should take a dictionary containing the package details as input and produce a valid Habitat plan file as output. The output should be a string formatted according to the specified template.
The input dictionar... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def generate_habitat_plan(package_info: Dict[str, str]) -> str:
"""
Generates a Habitat plan file based on the given package information.
Args:
package_info (dict): A dictionary contai... |
magic_instruct_75k | 7,193 | Write a Python function to calculate the total area covered by bars in a bar chart represented by a 4-dimensional numpy array. Each bar is defined by four coordinates: `x1`, `y1`, `x2`, `y2`, where `(x1, y1)` and `(x2, y2)` are the bottom-left and top-right corners of the bar, respectively. The bars are organized into ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_total_bar_area(data: np.ndarray) -> int:
"""
Calculate the total area covered by bars in a bar chart represented by a 4-dimensional numpy array.
Args:
data (np.ndarray): A 4-dimensi... |
magic_instruct_75k | 7,203 | Write a Python function to extract and display the major release versions of R packages from specific CRAN repositories. The function should handle any number of supported CRAN repositories and output the major release versions in a readable format. The code should start with:
```python
from typing import List
def ext... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def extract_major_releases(cran_repos: List[str]) -> List[str]:
"""
Extracts and displays the major release versions of R packages from specific CRAN repositories.
Args:
cran_r... |
magic_instruct_75k | 7,244 | Write a Python function to count the number of odd and even integers in a given list and return a tuple of two integers representing the count of odd and even numbers, respectively. The function should be efficient and handle any list of integers, including empty lists.
The code should start with:
```python
from typin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def count_odd_even(numbers: List[int]) -> Tuple[int, int]:
"""
Counts the number of odd and even integers in the given list and returns a tuple of two integers.
Args:
numbers (List[in... |
magic_instruct_75k | 7,253 | Create a Python class named `DeliveryStream` that simulates a delivery stream for a logistics company. The class should have methods for adding packages to the stream, removing packages from the stream, and displaying the current status of the stream. Additionally, the class should keep track of the stream name and the... | Here is the Python code to solve the given problem in the markdown block:
```python
class DeliveryStream:
"""
A class to simulate a delivery stream for a logistics company.
Attributes:
stream_name (str): The name of the delivery stream.
packages (list): A list to store the packages in the s... |
magic_instruct_75k | 7,266 | Create a Python function to simulate a simplified version of the logging system described in the given C++ code snippet. The function should support different log levels and be able to output log messages to various destinations, such as the console, files, or remote servers. The function should also support logging ti... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
import threading
import time
# Define log levels
LOG_LEVELS = {
"DEBUG": 1,
"INFO": 2,
"WARNING": 3,
"ERROR": 4,
"FATAL": 5
}
# Define output destinations
OUTPUT_DESTINATIONS = ["c... |
magic_instruct_75k | 7,292 | Write a Python function to calculate the area of a resistor based on its height and width. The area of the resistor can be calculated using the formula: `area = height * width`. The function should take in the height and width of the resistor as input and return the calculated area. The height and width are represented... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_resistor_area(resheight: float, reswidth: float) -> float:
"""
Calculate the area of a resistor based on its height and width.
Args:
resheight (float): The height of the resistor in data units.
... |
magic_instruct_75k | 7,301 | Write a Python function to determine if it's possible to make a given array `nums` non-decreasing by modifying at most one element. A non-decreasing array is an array where `nums[i] <= nums[i + 1]` for all `i`. The function should return `True` if it's possible to make the array non-decreasing by modifying at most one ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def checkPossibility(nums: List[int]) -> bool:
"""
Determine if it's possible to make the given array non-decreasing by modifying at most one element.
Args:
nums (List[int]): The array of in... |
magic_instruct_75k | 7,319 | Write a Python function `merge_and_sort_modules` that takes two lists of module names as input and returns a single merged and sorted list of unique module names. The function should handle edge cases such as empty input lists and lists with duplicate module names. The function should have the following signature:
```... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_and_sort_modules(list1: List[str], list2: List[str]) -> List[str]:
"""
Merges two lists of module names and returns a single sorted list of unique module names.
Args:
list1 (List[s... |
magic_instruct_75k | 7,326 | Write a Python function to process a list of integers by removing all duplicate elements and sorting the list in ascending order. The function should start with:
```python
from typing import List
def process_list(arr: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_list(arr: List[int]) -> List[int]:
"""
Process a list of integers by removing all duplicate elements and sorting the list in ascending order.
Args:
arr (List[int]): A list of int... |
magic_instruct_75k | 7,337 | Write a Python function to find the length of the longest contiguous subarray where all elements are the same in a given array of integers. The function should start with:
```python
from typing import List
def longest_contiguous_subarray(A: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_contiguous_subarray(A: List[int]) -> int:
"""
Finds the length of the longest contiguous subarray where all elements are the same.
Args:
A (List[int]): The input array of integer... |
magic_instruct_75k | 7,339 | Write a Python function to automate the setup of Docker containers by constructing strings for Docker container links and environment variables based on the input provided. The function should handle the cases where the input arrays may be empty.
The function should start with:
```python
from typing import List
def c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def construct_docker_setup(docker_links: List[str], docker_envs: List[str]) -> (str, str):
"""
Constructs Docker setup strings for container links and environment variables.
Args:
docker_lin... |
magic_instruct_75k | 7,343 | Write a Python function to calculate the area of the convex hull formed by a given set of points in a 2D plane. The convex hull is the smallest convex polygon that contains all the points. The function should take a list of tuples, where each tuple represents the coordinates of a point (x, y). The function should retur... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import math
def calculate_convex_hull_area(points: List[Tuple[int, int]]) -> float:
"""
Calculate the area of the convex hull formed by a given set of points in a 2D plane.
Args:
poin... |
magic_instruct_75k | 7,369 | Write a Python function to simulate a shared render context for multi-threaded resource creation and destruction. The function should provide methods for creating and managing resources in a multi-threaded environment. Specifically, the function should include:
1. A method `create_resource` that simulates the creation ... | Here is the Python code to solve the given problem in the markdown block:
```python
import threading
class SharedRenderContext:
def __init__(self):
"""
Initialize the SharedRenderContext with an empty dictionary for resources and a lock for thread safety.
"""
self.resources = {}
... |
magic_instruct_75k | 7,385 | Write a Python function to count the number of unique URL paths from a given list of URL patterns. Each URL pattern is represented as a string, and the URL paths are separated by forward slashes ("/"). The function should ignore any query parameters or fragments present in the URL patterns.
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 count_unique_url_paths(url_patterns: List[str]) -> int:
"""
Count the number of unique URL paths from a given list of URL patterns.
Args:
url_patterns (List[str]): A list of URL patterns... |
magic_instruct_75k | 7,393 | Implement a resource pool for managing objects of the `AACFrame` class, which represents frames of Advanced Audio Coding (AAC) data. The resource pool should allow efficient reuse of objects to prevent unnecessary memory allocation and deallocation. Your goal is to create a resource pool for managing objects of the `AA... | Here is the Python code to solve the given problem in the markdown block:
```python
from queue import Queue
class AACFrame:
def __init__(self):
self.aac_frame_length = 0
class ResourcePoolHelper:
def __init__(self):
"""
Initializes the ResourcePoolHelper with an empty pool of AACFrame ... |
magic_instruct_75k | 7,413 | Write a Python function to send an email with an attachment using the `swaks` command. The function should accept the subject of the email and the file path of the attachment as command-line arguments and then execute the `swaks` command to send the email. The email should be sent to a specified recipient's email addre... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import sys
def send_email_with_attachment(subject: str, attachment_path: str) -> None:
"""
Sends an email with an attachment using the `swaks` command.
Args:
subject (str): The subject of the emai... |
magic_instruct_75k | 7,422 | Write a Python function to calculate the total number of matches required to form a specific number of geometric shapes, given the minimum number of matches required for the first shape and a factor by which the number of matches needed for each subsequent shape is multiplied.
The function should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_matches(min_match: int, factor: int, num_shapes: int) -> int:
"""
Calculate the total number of matches required to form a specific number of geometric shapes.
Args:
min_match (int): The minimum ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.