source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 68,564 | Write a Python function to simulate a simplified HTTP client that handles HTTP requests and responses. The client should maintain its state and manage the number of bytes to be received for an object. The function should include methods to send an HTTP request and receive an HTTP response, updating the client's state a... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
from typing import Optional
class HttpClientState(Enum):
NOT_STARTED = 0
REQUEST_SENT = 1
RESPONSE_RECEIVED = 2
class ThreeGppHttpClient:
def __init__(self):
self.state = HttpClientState.N... |
magic_instruct_75k | 68,575 | Write a Python function to filter a list of numbers based on a specific condition. The function should take a list of integers and a condition function as input and return a new list containing only the numbers that satisfy the given condition. The condition function should take an integer as input and return a boolean... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def filter_numbers(numbers: List[int], condition: Callable[[int], bool]) -> List[int]:
"""
Filters a list of integers based on a given condition.
Args:
numbers (List[int]): A list ... |
magic_instruct_75k | 68,584 | Write a Python function to calculate the direct variation constant between two variables. The function should take two initial values of the variables and return the direct variation constant. The direct variation constant is the factor by which one variable changes in relation to the other. The formula for the direct ... | Here is the Python code to solve the given problem in the markdown block:
```python
def direct_variation(initial_var: int, another_initial_var: int) -> float:
"""
Calculate the direct variation constant between two variables.
Args:
initial_var (int): The initial value of the first variable.
... |
magic_instruct_75k | 68,585 | Write a Python function to determine if a given list of integers contains consecutive integers. The function should return `True` if the list contains consecutive integers, and `False` otherwise. The function should satisfy the following conditions:
- If the input list is empty, the function should return `False`.
- If... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def check_consecutive(nums: List[int]) -> bool:
"""
Determine if the given list of integers contains consecutive integers.
Args:
nums (List[int]): The list of integers to check.
Returns... |
magic_instruct_75k | 68,596 | Write a Python function to calculate the average probability of being hired within 1 month across all time periods from a given dataset. The dataset is structured as a dictionary of dictionaries, where the outer dictionary keys represent time periods (0, 1, 2, ...) and the inner dictionaries contain the probabilities o... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def average_hiring_probability(data: Dict[int, Dict[str, float]]) -> float:
"""
Calculate the average probability of being hired within 1 month across all time periods.
Args:
data (Dict[int,... |
magic_instruct_75k | 68,598 | Write a Python function to calculate the nth Fibonacci number using the Golden Ratio algorithm. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The formula to calculate the nth Fibonacci number using the Golden Ratio (phi) and its conj... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_fibonacci_using_golden_ratio(n: int) -> int:
"""
Calculate the nth Fibonacci number using the Golden Ratio algorithm.
The Fibonacci sequence is a series of numbers where each number is the sum of ... |
magic_instruct_75k | 68,599 | Write a Python function `extract_documented_settings(config_code: str) -> dict` that processes a configuration file represented as a string and extracts specific settings based on the given criteria. The configuration file is in the format of a Python code snippet, containing variable assignments for various settings. ... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_documented_settings(config_code: str) -> dict:
"""
Extracts specific settings from a configuration file represented as a string.
The function processes the configuration file to extract settings that:
1. Hav... |
magic_instruct_75k | 68,603 | Write a Python function to calculate the average mark value for all characters in a given dictionary of anchor data. Each character has its own set of anchors and a mark value associated with it. The function should take a dictionary as input, where the keys are character names and the values are dictionaries containin... | Here is the Python code to solve the given problem in the markdown block:
```python
def average_mark_value(anchor_data: dict) -> float:
"""
Calculate the average mark value for all characters in the given anchor data.
Args:
anchor_data (dict): A dictionary where the keys are character names and the... |
magic_instruct_75k | 68,606 | Write a Python function to capture the state of two-pin nets and format the snapshot according to a specified "interface" when a negative gain is encountered in a network optimization algorithm. The function should accept a list of tuples, where each tuple represents a connection between two pins. The function should r... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def take_snapshot(nets: List[Tuple[int, int]]) -> str:
"""
Captures the state of the two-pin nets and formats the snapshot according to a specified "interface" when a negative gain is encountered.... |
magic_instruct_75k | 68,641 | Write a Python function to analyze and provide insights into the efficiency of the garbage collection (GC) process in a Python application. The function should take in the number of steps taken during garbage collection (`steps`) and the number of garbage collection cycles performed (`collects`) as input. The function ... | Here is the Python code to solve the given problem in the markdown block:
```python
def analyze_gc_stats(steps: int, collects: int) -> dict:
"""
Analyzes garbage collection statistics and provides insights into the efficiency of the GC process.
Args:
steps (int): The number of steps taken during ga... |
magic_instruct_75k | 68,652 | Write a Python function to extract and return the display names of software packages from a given payload dictionary that contain either "LangPack" or "Language Files" in their display names. The payload dictionary contains a list of packages, each represented as a dictionary with keys `"display_name"`, `"version"`, an... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_language_packages(payload: dict) -> list:
"""
Extracts and returns the display names of software packages from the given payload dictionary
that contain either "LangPack" or "Language Files" in their display name... |
magic_instruct_75k | 68,667 | Write a Python function to search for a specific string within a set of files and directories. The function should utilize the provided variables and options to perform the search and display the results. The function should handle the following requirements:
1. Utilize the `GREP_OPTIONS` variable to set the case-insen... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import re
def search_files(MATCH: str, SEVERITY: str, GREP_OPTIONS: str, SEARCH: str, SECONDARY_COMMANDS: str) -> None:
"""
Search for a specific string within all files and directories in the current location.
A... |
magic_instruct_75k | 68,669 | Create a Python function to process a given integer based on certain criteria and return a response object with specific properties. The function should determine if the number is a perfect square, negative, or zero, and return an appropriate response code and message.
The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import NamedTuple
from enum import Enum
import math
class ResponseCode(Enum):
Success = "Success"
Failure = "Failure"
Invalid = "Invalid"
class NumberResponse(NamedTuple):
Number: int
Reply: ResponseCod... |
magic_instruct_75k | 68,671 | Write a Python class `PasswordManager` that securely stores and verifies user passwords using a salted hash approach. The class should include the following functionalities:
1. `add_user(name: str, password: str) -> None`: A method to add a new user to the system. This method should generate a random salt, hash the pas... | Here is the Python code to solve the given problem in the markdown block:
```python
import hashlib
import os
from typing import Dict, Tuple
class PasswordManager:
def __init__(self):
"""
Initialize the PasswordManager with an empty dictionary to store user data.
"""
self.users: Dict... |
magic_instruct_75k | 68,694 | Create a Python class `SplitManager` that conforms to a protocol defining methods for managing split views. Each split view is represented by an instance of the `SplitView` class. The `SplitManager` class should implement the following methods:
1. `splits() -> List[SplitView]`: Returns a list of all `SplitView` objects... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
class SplitView:
"""
Represents a split view with a feature name and content.
Attributes:
feature_name (str): The name of the feature associated with the split view.
conten... |
magic_instruct_75k | 68,696 | Write a Python function to process a list of message descriptors and return a dictionary containing information about each message type. Each message descriptor is represented as a tuple containing the following elements:
- Message type (string)
- Enum type (string)
- Containing type (string)
- Whether it is an extensi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict, Optional
def process_message_descriptors(descriptors: List[Tuple[str, str, str, bool, Optional[str], str, str]]) -> Dict[str, Dict[str, str]]:
"""
Processes a list of message descriptors an... |
magic_instruct_75k | 68,705 | Write a Python function to format a given string according to specific rules. The function should perform the following operations:
1. Convert the input string to lowercase.
2. Replace all underscores (`'_'`) with spaces (`' '`).
3. Capitalize the first letter of each word in the resulting string.
The function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_string(input_string: str) -> str:
"""
Formats the input string by converting it to lowercase, replacing underscores with spaces,
and capitalizing the first letter of each word.
Args:
input_string (str... |
magic_instruct_75k | 68,720 | Write a Python function to extract and return a list of numbers `X` from a given code snippet where each variable name follows the pattern `name1_1_0_0_0_0_X` and is assigned the value `None`. The function should return the numbers `X` in ascending order.
The code should start with:
```python
import re
def extract_va... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_variable_numbers(code_snippet: str) -> list:
"""
Extracts and returns a list of numbers `X` from variable names in a given code snippet.
The variable names follow the pattern `name1_1_0_0_0_0_X`, ... |
magic_instruct_75k | 68,729 | Write a Python function to delete files that match a specific template prefix from a given list of file names. The function should return the list of files after removing any files that start with the specified prefix.
The code should start with:
```python
from typing import List
def delete_template_files(files: List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def delete_template_files(files: List[str]) -> List[str]:
"""
Deletes files that match a specific template prefix from a given list of file names.
Args:
files (List[str]): A list of file nam... |
magic_instruct_75k | 68,740 | Write a Python function to simulate a simple client-server interaction using sockets. The server should listen on a specified port, accept incoming connections from clients, read and process data sent by the client, and send a response back to the client. The server should handle multiple client connections concurrentl... | Here is the Python code to solve the given problem in the markdown block:
```python
import socket
import threading
def handle_client(client_socket):
"""
Handle an individual client connection.
Args:
client_socket (socket.socket): The socket object for the client connection.
"""
try:
... |
magic_instruct_75k | 68,748 | Write a Python function to parse a string containing a series of commands for combining elements. Each command starts with a prefix "-St" followed by a space and a comma-separated list of numbers in increasing order. The function should return a list of lists, where each inner list contains the elements specified by a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def combine_elements(commands: str) -> List[List[int]]:
"""
Parses a string containing commands for combining elements and returns a list of combined elements.
Args:
commands (str): A string... |
magic_instruct_75k | 68,773 | Write a Python function to return a list of square numbers from a given list of integers. The function should handle the case where the input is not a list by raising a `ValueError`. The function should also ensure that each element in the input list is an integer. If any element is not an integer, the function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_square_numbers(nums: List[int]) -> List[int]:
"""
Returns a list of square numbers from a given list of integers.
Args:
nums (List[int]): A list of integers.
Returns:
L... |
magic_instruct_75k | 68,775 | Write a Python function to calculate the total cost of a customer's purchase after applying a discount based on the total purchase amount. The function should take two parameters: `total_cost` (the total cost of the purchase) and `discount_rate` (the percentage discount to be applied). The function should then calculat... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_discounted_cost(total_cost: float, discount_rate: float) -> float:
"""
Calculate the total cost of a purchase after applying a discount.
Args:
total_cost (float): The total cost of the purchase.
... |
magic_instruct_75k | 68,778 | Write a Python function to calculate the total score of a game where each score is represented by a list of integers. The game has a special rule: if the current score is the same as the previous score, the current score is not counted towards the total score. The function should efficiently handle large inputs and ret... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_score(scores: List[int]) -> int:
"""
Calculate the total score of a game where each score is represented by a list of integers.
If the current score is the same as the previous sc... |
magic_instruct_75k | 68,809 | Write a Python function to process image data and populate a ROS (Robot Operating System) message object with the relevant information. The ROS message object has two attributes: `header` and `data`. The `header` attribute contains a `stamp` field, which in turn contains a `secs` field. The `data` attribute holds the i... | Here is the Python code to solve the given problem in the markdown block:
```python
def populate_ros_message(img: list) -> dict:
"""
Populates a ROS message object with the relevant information from the given image data.
Args:
img (list): A list containing image data. The elements at index 5 and 6 ... |
magic_instruct_75k | 68,813 | Write a Python function to retrieve the class name for a given class period from a predefined dictionary. If the class period does not exist in the dictionary, the function should return a specific message indicating that the class period was not found.
The code should start with:
```python
def get_class_name(class_pe... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_class_name(class_period: str) -> str:
"""
Retrieve the class name for a given class period from a predefined dictionary.
Args:
class_period (str): The class period for which to retrieve the class name.
... |
magic_instruct_75k | 68,817 | Write a Python function to calculate the total damage caused by a grenade explosion in a game. The function should take in the number of grenades thrown, the damage caused by each grenade, and a list of targets. The game has a maximum limit on the number of grenades that can be thrown. If the number of grenades specifi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_damage(num_grenades: int, damage_per_grenade: int, targets: List[str], max_grenades: int) -> int or str:
"""
Calculate the total damage caused by grenades in a game.
Args:
... |
magic_instruct_75k | 68,836 | Implement a Python function `create_response` that processes the results of a series of actions and generates an appropriate response based on the status of these actions. The function should take three parameters: `status`, `result`, and `host`. The `status` parameter represents the status of the action, `result` is a... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
class ActionStatus(Enum):
PreconditionFailed = 1
CreateFailed = 2
TargetDeleteFailed = 3
ParentFailed = 4
class WebDavStatusCode(Enum):
PreconditionFailed = 1
Forbidden = 2
FailedDepen... |
magic_instruct_75k | 68,850 | Write a Python function to generate a CMake command based on the given configuration parameters for a machine learning framework. The function should take into account various build options and directory paths to ensure a successful build process. The configuration parameters include:
- `WITH_MKL`: A boolean indicating... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_cmake_command(WITH_MKL: bool, WITH_GPU: bool, USE_TENSORRT: bool, LIB_DIR: str, CUDNN_LIB: str, CUDA_LIB: str) -> str:
"""
Generates a CMake command based on the given configuration parameters for a machine learning... |
magic_instruct_75k | 68,851 | Write a Python function to validate and serialize a string with certain constraints. The string should not contain the null character (`'\0'`). If the string contains the null character, an error should be raised. The function should return a serialized string if the input is valid, otherwise, it should return an error... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def validate_and_serialize(value: str) -> Union[str, str]:
"""
Validates and serializes a string. The string should not contain the null character ('\0').
Args:
value (str): The string to v... |
magic_instruct_75k | 68,871 | Write a Python function to update a list of current channel numbers with a new range of channel numbers. The function should take the current list of channel numbers and a range defined by a start and end channel number. The function should ensure that the new range is inclusive and handle cases where the start channel... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def update_channels(current_channels: List[int], start_channel: int, end_channel: int) -> List[int]:
"""
Updates the current list of channel numbers with a new range of channel numbers.
Args:
... |
magic_instruct_75k | 68,877 | Implement a `TableManager` class that manages changes to a table, including aligning columns and displaying added statistics in a specific order. The class should have the following methods:
- `align(column: str, alignment: str)`: Sets the alignment for the specified column in the table. The `alignment` parameter can b... | Here is the Python code to solve the given problem in the markdown block:
```python
class TableManager:
def __init__(self):
"""
Initialize the TableManager with dictionaries to store changes and alignment settings.
"""
self.changes = {"stats": {"added": {}}}
self.table = {"al... |
magic_instruct_75k | 68,886 | Create a Python function to manage time spans for specific days. The function should support adding and removing time spans for given days. Each time span is defined by a start time (`since`) and an end time (`until`). The function should handle all edge cases and ensure that the time spans are managed accurately.
The... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
from datetime import datetime, timedelta
def manage_time_spans(day: str, time_spans: List[Tuple[str, str]], operation: str, new_time_span: Tuple[str, str] = None) -> List[Tuple[str, str]]:
"""
Man... |
magic_instruct_75k | 68,911 | Write a Python function to simulate a simple game of dice. The function should generate a random number between 1 and 6, representing the outcome of a single dice roll. The function should then return a tuple containing the value of the roll and its data type.
The code should start with:
```python
import random
def r... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def roll_dice() -> tuple:
"""
Simulates a single roll of a six-sided dice and returns the result along with its data type.
Returns:
tuple: A tuple containing the dice roll value (int) and its data typ... |
magic_instruct_75k | 68,922 | Write a Python function to calculate the average score of each student in a given dictionary. Each student's score is represented as a list of test scores. The average score for each student is calculated as the sum of their test scores divided by the number of tests taken. The function should return a dictionary where... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def calculate_average_scores(students: Dict[str, List[int]]) -> Dict[str, float]:
"""
Calculate the average score for each student in the given dictionary.
Args:
students (Dict[str, Li... |
magic_instruct_75k | 68,932 | Write a Python function to process a list of static folders and muffin plugins. The function should perform the following tasks:
1. Extract the names of the static folders from the given list and store them in a new list.
2. Identify the number of plugins in the plugins list and return the count.
The function signatur... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_static_folders_and_plugins(static_folders: tuple, plugins: tuple) -> (list, int):
"""
Processes a list of static folders and muffin plugins.
Args:
static_folders (tuple): A tuple of strings representing ... |
magic_instruct_75k | 68,950 | Write a Python function to extract all HTML comments from a given HTML file content. HTML comments are enclosed within `<!--` and `-->` tags and can span multiple lines. The function should return a list of strings, where each string represents an extracted HTML comment. If no HTML comments are found, the function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_html_comments(html_content: str) -> list:
"""
Extracts all HTML comments from the given HTML file content.
Args:
html_content (str): The content of the HTML file from which to extract comments... |
magic_instruct_75k | 68,989 | Write a Python function to process a list of integers according to the following rules:
1. If an integer is even, it should be multiplied by 2.
2. If an integer is odd, it should be squared.
The function should take a list of integers as input and return a new list containing the processed integers.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_integers(input_list: List[int]) -> List[int]:
"""
Processes a list of integers according to the following rules:
- If an integer is even, it is multiplied by 2.
- If an integer is odd... |
magic_instruct_75k | 69,000 | Write a Python function to generate the necessary configuration for the `entry_points` parameter in the `setup` function of the `setuptools` package. The function should take a dictionary of command-line entry points and their corresponding functions, and return a string representing the configuration.
The function si... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_entry_points(entry_points: dict) -> str:
"""
Generates the configuration for the `entry_points` parameter in the `setup` function of the `setuptools` package.
Args:
entry_points (dict): A dictionary whe... |
magic_instruct_75k | 69,002 | Write a Python function to process a list of fields and ordering criteria for a database query. The function should take in two input tuples: `list_editable` containing fields that are editable and `ordering` containing the ordering criteria for the query. The function should return a dictionary with two keys: "editabl... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple, List, Dict
def process_query_criteria(list_editable: Tuple[str], ordering: Tuple[str]) -> Dict[str, List[str]]:
"""
Processes the editable fields and ordering criteria for a database query.
Args:
... |
magic_instruct_75k | 69,011 | Write a Python function that performs a series of arithmetic operations on an integer variable `i` and returns the final value. The function should follow these steps:
1. Initialize `i` with the value 5.
2. Increment `i` by 3.
3. Multiply `i` by 4.
4. Subtract 10 from `i`.
5. Return the final value of `i`.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def perform_operations() -> int:
"""
Performs a series of arithmetic operations on an integer variable `i` and returns the final value.
Steps:
1. Initialize `i` with the value 5.
2. Increment `i` by 3.
3. Multip... |
magic_instruct_75k | 69,059 | Write a Python function to implement the Caesar cipher encryption. The function should take a string `text` and an integer `shift` as input and return the text encrypted using the Caesar cipher with the given shift value. The Caesar cipher is a simple substitution cipher where each letter in the plaintext is shifted a ... | Here is the Python code to solve the given problem in the markdown block:
```python
import string
def caesar_cipher(text: str, shift: int) -> str:
"""
Encrypts the given text using the Caesar cipher with the specified shift.
Args:
text (str): The input text to be encrypted.
shift (int): Th... |
magic_instruct_75k | 69,065 | Write a Python function to extract URLs from anchor tags in a given HTML string. The function should parse the HTML and return a list of URLs found in the `href` attributes of the `<a>` tags. The function should handle well-formed HTML with valid anchor tags and assume that the `href` attribute is always enclosed in do... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_urls_from_html(html: str) -> List[str]:
"""
Extracts URLs from the `href` attributes of anchor tags in a given HTML string.
Args:
html (str): The HTML string to parse.
... |
magic_instruct_75k | 69,096 | Write a Python function to calculate the number of preemptible nodes in a cloud computing cluster based on the specified percentage of preemptible nodes. The function should take two parameters: `total_nodes`, which represents the total number of autoscaling nodes, and `preemptible_percentage`, which represents the per... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_preemptible_nodes(total_nodes: int, preemptible_percentage: int) -> int:
"""
Calculate the number of preemptible nodes in a cloud computing cluster based on the specified percentage.
Args:
total_nodes ... |
magic_instruct_75k | 69,102 | Write a Python function `parse_extended_grammar(input_string)` that parses an input string conforming to a custom extended grammar and returns a dictionary containing the parsed information. The grammar includes the following rules:
- `abstract_sequence`: Represents a complex sequence, which can be an `atomic_complex`,... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
from typing import Dict, List
def parse_extended_grammar(input_string: str) -> Dict[str, Dict[str, List[str]]]:
"""
Parses an input string conforming to the extended grammar and returns a dictionary containing the par... |
magic_instruct_75k | 69,112 | Write a Python function to normalize the whitespace in each reference string within a list of references. Each reference string contains several fields separated by whitespace, and the function should ensure consistent spacing between fields by removing extra spaces. The fields include 'ref', 'names', 'year', 'title', ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def normalize_references(references: List[str]) -> List[str]:
"""
Normalizes the whitespace in each reference string within a list of references.
Args:
references (List[str]): A list of refe... |
magic_instruct_75k | 69,123 | Write a Python function to count the frequency of each letter in a given string and return the result as a dictionary where the keys are the letters and the values are their respective frequencies. The function should handle strings consisting of lowercase English letters only.
The code should start with:
```python
de... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_letter_frequency(input: str) -> dict:
"""
Counts the frequency of each letter in the given string and returns the result as a dictionary.
Args:
input (str): The input string consisting of lowercase English... |
magic_instruct_75k | 69,136 | Write a Python function to validate a dictionary of URLs based on a given set of rules. The function should take in two parameters: a dictionary of URLs and a list of valid locations. The dictionary contains keys representing server addresses and ports, with corresponding values being lists of URLs. The valid locations... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_urls(valid_urls_dict: dict, valid_locations: list) -> bool:
"""
Validates a dictionary of URLs against a list of valid locations.
Args:
valid_urls_dict (dict): A dictionary where keys are server address... |
magic_instruct_75k | 69,175 | Write a Python function to parse the metadata from a Python package's setup file and return a dictionary containing the relevant information. The setup file is in the format of a Python dictionary. The function should extract the following keys from the setup dictionary: "name", "version", "description", "author", "aut... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_setup_file(setup_dict: dict) -> dict:
"""
Parses the metadata from a Python package's setup file and returns a dictionary containing the relevant information.
Args:
setup_dict (dict): A dictionary represen... |
magic_instruct_75k | 69,201 | Write a Python function to simulate the behavior of releasing memory held by unique pointers in a vector and clearing the vector. The function should take a list of objects as input and simulate the process of releasing memory by clearing the list.
The code should start with:
```python
from typing import List
def rel... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def release_throttles(throttles: List[object]) -> None:
"""
Simulates the process of releasing memory held by unique pointers in a vector and clearing the vector.
Args:
throttles (List[objec... |
magic_instruct_75k | 69,204 | Write a Python function to generate an HTML page displaying a chessboard image and a title. The function should take in the file path of the chessboard image and the title to be displayed. The HTML page should include the title, the chessboard image, and the title again, all formatted appropriately.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_chessboard_html(chessboard_img_path: str, title: str) -> str:
"""
Generates an HTML page displaying a chessboard image and a title.
Args:
chessboard_img_path (str): The file path of the chessboard image... |
magic_instruct_75k | 69,208 | Write a Python function to format a configuration dictionary into a string. The function should take a dictionary representing a configuration and a variable number of keys. It should return a formatted string containing the key-value pairs for the specified keys. The format of the returned string should be "key1=value... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def format_config(config: Dict[str, Any], *args: str) -> str:
"""
Formats a configuration dictionary into a string containing the key-value pairs for the specified keys.
Args:
config (D... |
magic_instruct_75k | 69,211 | Create a Python programming task that involves designing and implementing a class hierarchy for processing banking records related to Australian ABA (Australian Bankers' Association) files. The task should include the following components:
1. Define an enumeration `ReturnCode` that includes the following valid industry... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
from enum import Enum
class ReturnCode(Enum):
"""
Enumeration representing valid industry return codes for ABA files.
"""
InvalidBsbNumber = 1
AccountClosed = 2
PaymentStopped = 3
... |
magic_instruct_75k | 69,216 | Write a Python function to calculate the magnetic field components (Ex, Ey, Ez) at specified locations and times, given the magnetic susceptibility (kappa) and relative permittivity (epsr) values. The function should use the provided formula to calculate the magnetic field components and return them as numpy arrays.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_magnetic_field(kappa=0.0, epsr=1.0):
"""
Calculate the magnetic field components (Ex, Ey, Ez) at specified locations and times,
given the magnetic susceptibility (kappa) and relative permitt... |
magic_instruct_75k | 69,284 | Write a Python function to determine the minimum number of deletions required to make a given string a palindrome. A palindrome is a string that reads the same forwards and backwards. The function should return an integer representing the minimum number of deletions needed.
The code should start with:
```python
def mi... | Here is the Python code to solve the given problem in the markdown block:
```python
def minDeletionPalindrome(s: str) -> int:
"""
Calculate the minimum number of deletions required to make the given string a palindrome.
Args:
s (str): The input string.
Returns:
int: The minimum number ... |
magic_instruct_75k | 69,291 | Write a Python function to extract translation keys from a Blade template in a Laravel application. The function should parse the content of a Blade template and return a list of translation keys found within the template. Translation keys are strings passed as arguments to the `trans` function in the Blade template. T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extractTranslations(blade_template: str) -> List[str]:
"""
Extracts translation keys from a Blade template in a Laravel application.
Args:
blade_template (str): The content of ... |
magic_instruct_75k | 69,323 | Write a Python function to generate a unique slug for a new employee record to be inserted into a database table. The slug should be a combination of the employee's first and last names, with any spaces replaced by underscores, and a unique identifier appended to ensure its uniqueness. The function should take the empl... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_employee_slug(first_name: str, last_name: str, unique_identifier: str) -> str:
"""
Generates a unique slug for an employee record.
The slug is a combination of the employee's first and last names, with any spac... |
magic_instruct_75k | 69,333 | Write a Python function to filter a list of player objects based on their overall rating. The function should take a list of player objects and a minimum overall rating as input, and return a filtered list containing only the players whose overall rating is greater than or equal to the specified minimum rating.
The pl... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_players_by_rating(players: List[Dict[str, int]], min_rating: int) -> List[Dict[str, int]]:
"""
Filters a list of player objects based on their overall rating.
Args:
players ... |
magic_instruct_75k | 69,346 | Write a Python function to calculate the new port numbers after applying a given offset to each port in a list. The function should take a list of integers representing port numbers and an integer representing the port offset. It should return a new list of integers where each port number has been incremented by the gi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_port_offset(ports: List[int], offset: int) -> List[int]:
"""
Calculate the new port numbers after applying a given offset to each port in the list.
Args:
ports (List[int]): A l... |
magic_instruct_75k | 69,354 | Write a Python function to validate client information based on specific rules. The function should take a dictionary `data` as input, where the dictionary contains the following keys: 'name', 'age', 'email', and 'address'. The validation rules for each field are as follows:
- 'name': Should be a non-empty string.
- 'a... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_client(data: dict) -> bool:
"""
Validates client information based on specified rules.
Args:
data (dict): A dictionary containing client information with keys 'name', 'age', 'email', and 'address'.
... |
magic_instruct_75k | 69,357 | Write a Python function to process a list of HTTP API contracts and return a dictionary containing the titles of the contracts along with their corresponding health check paths. Each contract is represented as a dictionary with the keys "title" and "healthcheck_path". The function should handle cases where the input li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Optional
def process_contracts(contracts: List[Dict[str, Optional[str]]]) -> Dict[str, Optional[str]]:
"""
Processes a list of HTTP API contracts and returns a dictionary containing the titles of ... |
magic_instruct_75k | 69,421 | Write a Python function to generate HTML content based on a provided template structure. The template structure includes a header, a list of items, and a boolean indicating whether the list is empty. The function should generate the complete HTML content by utilizing the provided template structure and the list of item... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_html(header: str, items: List[str]) -> str:
"""
Generates and returns the complete HTML content based on the provided header and list of items.
Args:
header (str): The header co... |
magic_instruct_75k | 69,441 | Write a Python function to process a given email content and replace any occurrences of `<EMAIL>` with a specified email address. The function should handle both plain text and HTML content, ensuring that the replacement is performed accurately. The function should be able to handle nested structures such as dictionari... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
import re
def process_email_content(content: Union[dict, list, str], new_email: str) -> Union[dict, list, str]:
"""
Processes the given email content and replaces all occurrences of `<EMAIL>` with the s... |
magic_instruct_75k | 69,451 | Write a Python function to calculate the maximum sum of a subarray of a given array using Kadane's Algorithm. The function should return the maximum sum of the subarray.
The code should start with:
```python
from typing import List
def max_subarray_sum(arr: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_subarray_sum(arr: List[int]) -> int:
"""
Calculate the maximum sum of a subarray using Kadane's Algorithm.
Args:
arr (List[int]): The input array of integers.
Returns:
i... |
magic_instruct_75k | 69,452 | Write a Python function to filter a list of port names based on a set of prefixes. The function should take a list of port names and a set of prefixes as input and return a filtered list containing only the port names that start with any of the given prefixes.
The code should start with:
```python
from typing import L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Set
def filter_ports_by_prefixes(port_names: List[str], prefixes: Set[str]) -> List[str]:
"""
Filters a list of port names based on a set of prefixes.
Args:
port_names (List[str]): A list o... |
magic_instruct_75k | 69,465 | Write a Python function to process a base64 encoded image received through a JSON request and return the result using a given controller. The function should extract the base64 encoded image from the JSON request and use the provided controller to process the image, returning the result.
The function signature should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_image(request: dict, controller) -> str:
"""
Processes a base64 encoded image received through a JSON request and returns the result using a given controller.
Args:
request (dict): A dictionary represent... |
magic_instruct_75k | 69,496 | Write a Python function to sort a dictionary of software packages by their names and return a list of tuples where each tuple contains the package name and its version. The function should handle any dictionary input where the keys are package names and the values are their corresponding versions.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def sort_packages(packages: Dict[str, str]) -> List[Tuple[str, str]]:
"""
Sorts a dictionary of software packages by their names and returns a list of tuples.
Args:
packages (Di... |
magic_instruct_75k | 69,534 | Write a Python function to process a list of Django migration operations and return a dictionary containing the model names and the fields that are being removed from each model. Each migration operation is represented as a tuple containing the model name and the field name being removed. The function should handle cas... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def extract_removed_fields(migrations: List[Tuple[str, str]]) -> Dict[str, List[str]]:
"""
Processes a list of Django migration operations and returns a dictionary containing the model names... |
magic_instruct_75k | 69,545 | Write a Python function to apply a series of transformations to an input value. Each transformation is represented by a separate function, and the input value is modified by each transformation in sequence. The function should take an initial value `x` and a list of transformation functions. The function should apply e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def apply_transformations(x: int, transformations: List[Callable[[int], int]]) -> int:
"""
Applies a series of transformations to an input value.
Args:
x (int): The initial value t... |
magic_instruct_75k | 69,559 | Write a Python function to process a dictionary containing information about host groups and event IDs. The function should extract the host group and event ID from the dictionary and return them as a formatted string. The formatted string should be in the following format: "Host Group: <host_group>, Event ID: <eventid... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_host_event(data: dict) -> str:
"""
Formats the host group and event ID from a dictionary into a specified string format.
Args:
data (dict): A dictionary containing 'host_group' and 'eventid' keys.
Re... |
magic_instruct_75k | 69,572 | Write a Python function to reverse the order of elements in a given list. The function should use a custom implementation to reverse the list without using Python's built-in `reverse()` method or slicing. The function should start with:
```python
from typing import List
def reverse_list(lst: List[int]) -> List[int]:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_list(lst: List[int]) -> List[int]:
"""
Reverses the order of elements in the given list using a custom implementation.
Args:
lst (List[int]): The list of integers to be reversed.... |
magic_instruct_75k | 69,578 | Write a Python function `convert_to_reference_unit(arg, unit)` that converts a physical quantity from its current unit to a specified reference unit. The function should handle the following:
1. Check if the input `arg` is an instance of `PhysicalQuantity`.
2. If `arg` is a valid `PhysicalQuantity`, convert it to the s... | Here is the Python code to solve the given problem in the markdown block:
```python
class PhysicalQuantity:
def __init__(self, value, unit):
self.value = value
self.unit = unit
def to_unit(self, target_unit):
# Dummy implementation for demonstration purposes
# Assume the convers... |
magic_instruct_75k | 69,602 | Write a Python function `process_cameras` that processes information from multiple cameras connected to different ports on a device. The function should take a dictionary `cameras_info` as input, where the keys are the port numbers and the values are tuples in the format `(is_reading, width, height)`. The `is_reading` ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def process_cameras(cameras_info: Dict[int, Tuple[bool, int, int]]) -> List[str]:
"""
Processes information from multiple cameras and returns a summary of the working ports along with the di... |
magic_instruct_75k | 69,630 | Write a Python function to convert a given string into its binary representation. The function should take a string as input and return a string representing the binary equivalent of the input string. The binary representation should be in the form of a space-separated sequence of binary values for each character in th... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_to_binary(input_string: str) -> str:
"""
Converts a given string into its binary representation.
Args:
input_string (str): The input string to be converted.
Returns:
str: A string representi... |
magic_instruct_75k | 69,643 | Write a Python function to process the `bigip_response` variable, which contains the output of the `aws cloudformation describe-stacks` command. The function should determine whether the stack exists or not based on the presence of the phrase "does not exist" in the response. If the stack exists, the function should pr... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_stack_response(bigip_response: str) -> None:
"""
Processes the `bigip_response` to determine whether a CloudFormation stack exists.
Args:
bigip_response (str): The output of the `aws cloudformation descr... |
magic_instruct_75k | 69,646 | Write a Python function to convert a binary array to its decimal equivalent. The binary array is represented as a list of integers where each integer is either 0 or 1. The function should take this list as input and return the corresponding decimal number.
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 binary_array_to_number(arr: List[int]) -> int:
"""
Converts a binary array to its decimal equivalent.
Args:
arr (List[int]): A list of integers where each integer is either 0 or 1.
... |
magic_instruct_75k | 69,682 | Write a Python function to decode a list of encoded names and return a dictionary where the keys are the hexadecimal indices and the values are the decoded names. Each encoded name in the list is followed by a comment containing a hexadecimal number representing the index of the name in the list. The strings may contai... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def decode_names(encoded_names: List[str]) -> Dict[str, str]:
"""
Decodes a list of encoded names and returns a dictionary where the keys are the hexadecimal indices and the values are the decoded ... |
magic_instruct_75k | 69,706 | Write a Bash script to generate a self-signed certificate for an Athenz Certificate Authority (CA) using OpenSSL. The script should adhere to the following requirements:
1. The script should be written in Bash.
2. It should set the options `-eu` and `-o pipefail` to ensure strict error handling and pipeline failure.
3.... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
set -euo pipefail
# Set file and CN variables
FILENAME='athenz_ca'
CN='Sample Self Signed Athenz CA'
# Change to the directory containing the script
cd "$(dirname "$0")"
# Generate self-signed certificate and key
openssl re... |
magic_instruct_75k | 69,742 | Write a Python function to generate a list of dense blocks based on the given parameters. A dense block is a list of integers that follows a specific pattern. The function should take in two parameters: `number_of_dense_blocks` (an integer representing the number of dense blocks to generate) and `growth_rate` (an integ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_dense_blocks(number_of_dense_blocks: int, growth_rate: int) -> List[List[int]]:
"""
Generates a list of dense blocks based on the given number of dense blocks and growth rate.
Args:
... |
magic_instruct_75k | 69,782 | Write a Python function to validate a list of software licenses based on their expiration dates. Each license is represented by a string in the format "LICENSE_TYPE|EXPIRATION_DATE", where `LICENSE_TYPE` is a string representing the type of license (e.g., "MIT", "BSL") and `EXPIRATION_DATE` is a date in the format "YYY... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from datetime import datetime
def validateLicenses(licenses: List[str], current_date: str) -> List[bool]:
"""
Validates a list of software licenses based on their expiration dates.
Args:
lic... |
magic_instruct_75k | 69,784 | Write a Python function to validate an electric vehicle's serial number based on specific criteria. The serial number must be exactly 10 characters long, with the first two characters being alphabetic (A-Z, case-insensitive) and the remaining characters being numeric (0-9). The function should return `True` if the seri... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_serial_number(serial_number: str) -> bool:
"""
Validates an electric vehicle's serial number based on specific criteria.
The serial number must be exactly 10 characters long, with the first two characters
b... |
magic_instruct_75k | 69,822 | Write a Python function to generate OpenSees commands for defining and integrating a beam section. The function should take the type of integration, section ID, integration ID, and the numpy library reference as parameters. The function should return a string containing the OpenSees commands to define and integrate the... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_beam_section_commands(integration_type: str, section_id: int, integration_id: int, np: str) -> str:
"""
Generates OpenSees commands to define and integrate a beam section.
Args:
integration_type (str): ... |
magic_instruct_75k | 69,876 | Write a Python function to recursively change the permissions of all files within a given list of directory paths to 644 (read and write for the owner, read-only for others). The function should handle the input directories and their subdirectories.
The code should start with:
```python
from typing import List
import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import os
import stat
def change_file_permissions(directory_paths: List[str]) -> None:
"""
Recursively changes the permissions of all files within the given list of directory paths to 644.
Args:
... |
magic_instruct_75k | 69,917 | Write a Python function to determine if a file type is allowed based on a list of MIME types and their allowed status. The function should take a list of tuples, where each tuple contains a MIME type (string) and a boolean value indicating whether the file type is allowed or not. The function should also take a MIME ty... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def is_file_type_allowed(file_types: List[Tuple[str, bool]], mime_type: str) -> bool:
"""
Determines if a file type is allowed based on a list of MIME types and their allowed status.
Args:
... |
magic_instruct_75k | 69,920 | Write a Python function to convert a given integer (1 <= num <= 9999) into its English word representation. The function should handle numbers from 1 to 9999, including special cases like numbers in the teens (10 to 19) and numbers that end in zero.
The code should start with:
```python
def numberToWords(num: int) -> ... | Here is the Python code to solve the given problem in the markdown block:
```python
def numberToWords(num: int) -> str:
"""
Convert a given integer (1 <= num <= 9999) into its English word representation.
Args:
num (int): The number to be converted.
Returns:
str: The English word repre... |
magic_instruct_75k | 69,941 | Write a Python function to determine the behavior of a quiz system based on two configurations: `allow_multiple_answer` and `zoom_level`. The function should return a message indicating whether multiple answers are allowed and the maximum zoom level allowed. The zoom level should be restricted to a maximum value of 2.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def quiz_system_behavior(allow_multiple_answer: bool, zoom_level: int) -> str:
"""
Determine the behavior of the quiz system based on the given configurations.
Args:
allow_multiple_answer (bool): A boolean indicatin... |
magic_instruct_75k | 69,943 | Write a Python function to perform Bayesian inference to update the parameters of a Beta distribution given observed data from a series of trials. The function should take the shape parameters of the prior Beta distribution (`prior_alpha` and `prior_beta`), the number of observed successes (`observed_successes`), and t... | Here is the Python code to solve the given problem in the markdown block:
```python
def bayesian_inference(prior_alpha: int, prior_beta: int, observed_successes: int, observed_failures: int) -> tuple:
"""
Perform Bayesian inference to update the parameters of a Beta distribution given observed data from a serie... |
magic_instruct_75k | 69,955 | Write a Python function to count the number of times each blueprint is referenced in a list of strings. Each string represents a blueprint reference in the format "from .blue_prints.<blueprint_name> import <blueprint_name> as <alias>". The function should return a dictionary where the keys are the blueprint names and t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_blueprint_references(blueprint_list: List[str]) -> Dict[str, int]:
"""
Counts the number of times each blueprint is referenced in a list of strings.
Args:
blueprint_list (Lis... |
magic_instruct_75k | 69,962 | Write a Python function to validate a dictionary against a set of expected key-value pairs. The function should take in a dictionary `res` and check if it contains specific key-value pairs. If any of the expected key-value pairs are missing or have different values, the function should return `False`. Otherwise, it sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_res(res: dict) -> bool:
"""
Validates the input dictionary `res` against a set of expected key-value pairs.
Args:
res (dict): The dictionary to be validated.
Returns:
bool: True if all expe... |
magic_instruct_75k | 69,970 | Write a Python function to automate the process of copying directories to multiple remote hosts using the Secure Copy Protocol (SCP). The function should take a directory path as input and then copy the entire directory to each specified remote host. The function should display a message indicating the progress of the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import subprocess
import os
def copy_directory_to_hosts(directory_path: str, hosts: List[str], username: str, remote_base_directory: str) -> None:
"""
Automates the process of copying a directory to mult... |
magic_instruct_75k | 69,991 | Write a Python function to process a list of AMRs (Abstract Meaning Representation) and their alignments, and return a dictionary containing the alignment information in a structured format. Each AMR is represented as a dictionary with an "amr_id" and an "alignments" dictionary. The "alignments" dictionary maps node na... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def process_alignments(amrs: List[Dict[str, Any]]) -> Dict[str, Dict[str, List[str]]]:
"""
Processes a list of AMRs and their alignments, and returns a dictionary containing the alignment info... |
magic_instruct_75k | 69,994 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0.
The code should start with:
```python
from typing import List
def sum_of_even_numbers(nums: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_even_numbers(nums: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list.
Args:
nums (List[int]): A list of integers.
Returns:
int: The sum o... |
magic_instruct_75k | 70,037 | Write a Python function to generate a simple HTML error page based on the provided error code and message. The function should take two parameters: an integer `error_code` and a string `error_message`. The function should return a string containing the HTML code for the error page. The HTML code should include the erro... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_error_page(error_code: int, error_message: str) -> str:
"""
Generates a simple HTML error page based on the provided error code and message.
Args:
error_code (int): The error code to be displayed on the... |
magic_instruct_75k | 70,044 | Write a Python function to serialize and deserialize a simple class representing a geometric point with `x` and `y` coordinates. The serialization and deserialization should be done using a custom mechanism that converts the object to and from a JSON string. The class should have a default constructor and a parameteriz... | Here is the Python code to solve the given problem in the markdown block:
```python
import json
class Point:
def __init__(self, x: int = 0, y: int = 0):
"""
Initialize a Point object with x and y coordinates.
Args:
x (int): The x-coordinate of the point.
y (int): Th... |
magic_instruct_75k | 70,085 | Write a Python function that modifies a given list of integers based on a specific condition. The function should take in a list of integers and a boolean flag as input. If the flag is `True`, the function should double all the even numbers in the list. If the flag is `False`, the function should square all the odd num... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def modify_numbers(numbers: List[int], double_even: bool) -> List[int]:
"""
Modifies a list of integers based on a boolean flag.
If the flag `double_even` is True, the function doubles all the even ... |
magic_instruct_75k | 70,115 | Write a Python function to automate the installation of Docker on a Linux system. The function should perform the following steps:
1. Install Docker using a provided shell script named `install_docker.sh`.
2. Add the current user to the `docker` group using the `usermod` command.
3. Display a message to the user indica... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def install_docker():
"""
Automates the installation of Docker on a Linux system and adds the current user to the `docker` group.
This function performs the following steps:
1. Installs Docker using t... |
magic_instruct_75k | 70,137 | Write a Python function to remove leading whitespace from each string in a given list of strings representing variable names. The function should return a new list with the leading whitespace removed from each string.
The code should start with:
```python
from typing import List
def remove_leading_whitespace(variable... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_leading_whitespace(variables: List[str]) -> List[str]:
"""
Removes leading whitespace from each string in the given list of variable names.
Args:
variables (List[str]): A list of ... |
magic_instruct_75k | 70,140 | Write a Python function to calculate the total amount spent by each customer from a list of transactions. Each transaction is represented as a tuple containing the customer's name and the amount spent. The function should return a dictionary where the keys are customer names and the values are the total amounts spent b... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def calculate_total_spent(transactions: List[Tuple[str, int]]) -> Dict[str, int]:
"""
Calculate the total amount spent by each customer from a list of transactions.
Args:
transa... |
magic_instruct_75k | 70,176 | Write a Python function to extract the name of a product based on its SKU from a JSON response returned by an API. The function should handle cases where the SKU is not found in the API response by returning a specific message.
The function should start with:
```python
def extract_product_name(api_response: dict, sku:... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_product_name(api_response: dict, sku: str) -> str:
"""
Extracts the name of a product based on its SKU from a JSON response.
Args:
api_response (dict): A dictionary representing the JSON response from th... |
magic_instruct_75k | 70,206 | Write a Python function to modify a dictionary based on a set of rules. The function should take in a dictionary and a boolean parameter `preserve_default`. If `preserve_default` is `True`, the function should remove any key-value pairs where the value is the same as the default value for that key. If `preserve_default... | Here is the Python code to solve the given problem in the markdown block:
```python
def modify_dict(dictionary: dict, preserve_default: bool) -> dict:
"""
Modifies the input dictionary based on the `preserve_default` parameter.
Args:
dictionary (dict): The input dictionary containing string keys an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.