source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 39,687 | Write a Python function to simulate the behavior of the `amixer` command-line utility, which controls the audio settings on a Linux system. The function should take in the sound card index, channel name, and a boolean value indicating whether to mute or unmute the channel. The function should then return a string that ... | Here is the Python code to solve the given problem in the markdown block:
```python
def amixer_simulator(card_index: int, channel: str, mute: bool) -> str:
"""
Simulates the behavior of the `amixer` command-line utility by muting or unmuting the specified audio channel on the given sound card.
Args:
... |
magic_instruct_75k | 39,689 | Write a Python function to analyze the licensing information of a given software project and determine if the project complies with the licensing terms. The function should take a code snippet as input, which contains a copyright notice and mentions the licenses under which the software is distributed. The function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_license_compliance(code_snippet: str) -> bool:
"""
Analyzes the licensing information of a given software project and determines if the project complies with the licensing terms.
Args:
code_snippet (str): ... |
magic_instruct_75k | 39,717 | Write a Python function to generate a secure authentication key of a specified length. The authentication key should be a string of alphanumeric characters (both uppercase and lowercase letters and digits) and should be generated using a secure randomization method to ensure its uniqueness and unpredictability.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
import string
def generate_auth_key(length: int) -> str:
"""
Generates a secure authentication key of the specified length.
The authentication key is a string of alphanumeric characters (both uppercase and lo... |
magic_instruct_75k | 39,730 | Create a Python function `create_template_file` that generates a template file for a specific type of document. The function should take the title of the document as input and return a string representing the template file. The template file should be formatted according to the following requirements:
```
Title: [title... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_template_file(title: str) -> str:
"""
Generates a template file for a specific type of document.
Args:
title (str): The title of the document.
Returns:
str: A string representing the template... |
magic_instruct_75k | 39,733 | Write a Python function to calculate the total amount spent across all receipts in a given receipt collection. Each receipt is represented as a dictionary containing a list of items, and each item is a dictionary with a `name` and a `price`. The receipt collection is a list of such receipt dictionaries.
The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_total_spent(receipt_collection: List[Dict]) -> float:
"""
Calculate the total amount spent across all receipts in the receipt collection.
Args:
receipt_collection (List[D... |
magic_instruct_75k | 39,756 | Create a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down.
The code should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid.
Args:
m (int): The number of rows ... |
magic_instruct_75k | 39,770 | Write a Python function to format a dictionary of CSS style properties and their values into a string. The properties should be sorted alphabetically by their keys and concatenated into a single string in the format "property1: value1; property2: value2; ...". The function should handle any valid dictionary of CSS prop... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def format_css(styles: Dict[str, str]) -> str:
"""
Formats a dictionary of CSS style properties and their values into a single string.
The properties are sorted alphabetically by their keys and conca... |
magic_instruct_75k | 39,788 | Write a Python function to determine if the provided channel matches the currently selected channel for a hardware device. The function should take a `OneWireChannel` as an argument and return a boolean indicating whether the provided channel matches the currently selected channel.
The `OneWireChannel` is an enumerati... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
class OneWireChannel(Enum):
"""
Enumeration representing different channels available for the hardware device.
"""
CHANNEL1 = 1
CHANNEL2 = 2
CHANNEL3 = 3
CHANNEL4 = 4
def is_correct_ch... |
magic_instruct_75k | 39,793 | Write a Python function to validate the subject of an email before it is sent. The function should check if the subject contains any inappropriate language or sensitive content. If the subject is deemed inappropriate, the function should return `False` to prevent the email from being sent. Otherwise, it should return `... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def validate_email_subject(subject: str) -> bool:
"""
Validates the subject of an email to ensure it does not contain any inappropriate language or sensitive content.
Args:
subject (str): The subject of t... |
magic_instruct_75k | 39,795 | Write a Python function to determine 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 of a company. If it is not possible to make any profit, return 0.
The function should start with:
```python
from typing import List
def ... | 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 | 39,796 | Write a Python function to simulate the memory mapping process. The function should take two parameters: `mmap_len` and `mmap_addr`, both of type `int`. The `mmap_len` parameter represents the length of the memory to be mapped, and `mmap_addr` represents the starting address for the memory mapping. Your task is to writ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def memory_map(mmap_len: int, mmap_addr: int) -> Optional[List[int]]:
"""
Simulates the memory mapping process by creating a list of length `mmap_len` initialized with zeros.
Args:
... |
magic_instruct_75k | 39,838 | Write a Python function to process a list of machine learning models by setting each model to evaluation mode and moving each model to a specified device. The function should return the modified list of models. The code should start with:
```python
from typing import List
def process_models(models: List[object], devic... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_models(models: List[object], device: str) -> List[object]:
"""
Processes a list of machine learning models by setting each model to evaluation mode and moving each model to a specified device... |
magic_instruct_75k | 39,855 | Write a Python function to split a given string into two parts: the head and the body. The head is defined as the portion of the string before the first occurrence of the substring `<HeAd>`, and the body is the portion of the string after this occurrence. If `<HeAd>` is not present in the string, the head should be an ... | Here is the Python code to solve the given problem in the markdown block:
```python
def split_head_body(input_string: str) -> tuple:
"""
Splits the input string into two parts: the head and the body.
The head is the portion of the string before the first occurrence of the substring '<HeAd>'.
The body i... |
magic_instruct_75k | 39,857 | Write a Python function to filter recent publications authored by a specified user from a given queryset of publications. The function should return a queryset containing the recent publications ordered by their publication date in descending order.
The code should start with:
```python
from typing import List, Option... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def recents_by_user(objects_all: List[dict], user: str) -> List[dict]:
"""
Filters recent publications authored by a specified user from a given queryset of publications.
Args:
obj... |
magic_instruct_75k | 39,870 | Create a Python module for text processing that includes a tokenizer and a colorizer. The tokenizer should be able to split a given text into individual words, while the colorizer should be able to add color to specific words based on predefined rules. Implement the `tokenizer` and `colouring` modules to achieve this f... | Here is the Python code to solve the given problem in the markdown block:
```python
# tokenizer.py
import re
from typing import List
def tokenize(text: str) -> List[str]:
"""
Tokenizes the input text into individual words.
Args:
text (str): The input text to be tokenized.
Returns:
Lis... |
magic_instruct_75k | 39,887 | Write a Python function to extract the points of the exterior line of a polygon. The function should handle the case where the polygon has no exterior line. The function should take a reference and an exterior line as input and return the points of the exterior line. If the length of the points is 0, the function shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional, Tuple
def get_line_points(ref, exterior_line) -> Optional[List[Tuple[float, float]]]:
"""
Extracts the points of the exterior line of a polygon.
Args:
ref: The reference to the po... |
magic_instruct_75k | 39,905 | Write a Python function to extract and return a list of unique elements from a given list of integers while maintaining the order of their first appearance. The function should efficiently handle the input list and ensure that each element appears only once in the output list.
The code should start with:
```python
fro... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_unique_elements(input_list: List[int]) -> List[int]:
"""
Extracts and returns a list of unique elements from the given input list, maintaining the order of their first appearance.
Args:
... |
magic_instruct_75k | 39,917 | Write a Python function to decode an encoded string that follows a specific pattern. The encoded string consists of three substrings separated by underscores. Each substring represents a specific piece of information. The function should take the encoded string as input and return a tuple containing the decoded substri... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def decode_string(encoded_string: str) -> Tuple[str, str, str]:
"""
Decodes an encoded string that consists of three substrings separated by underscores.
Args:
encoded_string (str): The enc... |
magic_instruct_75k | 39,934 | Write a Python function to determine the file type based on the file extension. The function should take a file extension as input and return the corresponding file type. The file type should be one of the following: "text", "image", "video", "audio", or "other". If the file extension is not recognized, the function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def file_type_by_extension(extension: str) -> str:
"""
Determine the file type based on the file extension.
Args:
extension (str): The file extension to determine the file type for.
Returns:
str: The fi... |
magic_instruct_75k | 39,936 | Write a Python function to count the occurrences of each major version from a list of programming language version strings. The major version is defined as the first two digits of the version string. The function should return a dictionary where the keys are the major versions and the values are the counts of their occ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_major_versions(versions: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each major version from a list of programming language version strings.
Args:
versions (L... |
magic_instruct_75k | 39,946 | Write a Python function to validate a user-provided name against a set of predefined values. The function should return an integer value based on the validation result. Specifically, the function should:
1. Return `-1` if the `name` is an empty string.
2. Return `-1` if the `name` matches any value in the `from_box_val... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def validate_name(name: str, from_box_values: List[str]) -> int:
"""
Validates a user-provided name against a set of predefined values.
Args:
name (str): The name to be validated.
fr... |
magic_instruct_75k | 39,951 | Create a Python function to parse a given input file containing atomic symbols and their 3D coordinates, and return a list of `Atom` objects. Each line in the input file is formatted as "atomic_symbol x_coordinate y_coordinate z_coordinate". The function should handle invalid input by printing an error message indicati... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
class Atom:
def __init__(self, atomic_number: int, coordinates: Tuple[float, float, float]):
"""
Initialize an Atom object with the given atomic number and coordinates.
Args:
... |
magic_instruct_75k | 39,969 | Write a Python function to analyze time travel data and calculate the total time traveled by each traveler. The time travel data is represented as a list of tuples, where each tuple contains three elements: the traveler's name (a string), the time of departure (an integer), and the time of arrival (an integer). The tim... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def analyze_time_travel_data(data: List[Tuple[str, int, int]]) -> Dict[str, int]:
"""
Analyzes time travel data and calculates the total time traveled by each traveler.
Args:
da... |
magic_instruct_75k | 39,977 | Write a Python function to extract a specific property value from a JSON string using different methods and handle any potential errors that may occur during the extraction process. The JSON string is provided as input, and the property to be extracted is also provided as input. The function should return the extracted... | Here is the Python code to solve the given problem in the markdown block:
```python
import json
from typing import Union
def extract_property_from_json(json_str: str, prop: str) -> Union[str, int, float, dict, list, None]:
"""
Extracts a specific property value from a JSON string.
Args:
json_str (... |
magic_instruct_75k | 39,985 | Write a Python function to find the starting index of a substring (needle) in a string (haystack) without using any built-in string search functions. If the needle is not found in the haystack, the function should return -1. The function should start with:
```python
def strStr(haystack: str, needle: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def strStr(haystack: str, needle: str) -> int:
"""
Find the starting index of the first occurrence of the substring (needle) in the string (haystack).
If the needle is not found, return -1.
Args:
haystack (str):... |
magic_instruct_75k | 40,017 | Write a Python function to perform a version bump on a given semantic version string based on the specified type of bump ("major", "minor", or "patch"). The function should return the updated version string or "Invalid input" if the bump type is not recognized.
The code should start with:
```python
def bump_version(cu... | Here is the Python code to solve the given problem in the markdown block:
```python
def bump_version(current_version: str, bump_type: str) -> str:
"""
Perform a version bump on a given semantic version string based on the specified type of bump.
Args:
current_version (str): The current version stri... |
magic_instruct_75k | 40,034 | Write a Python function to calculate the average number of characters in a list of strings, rounded to the nearest whole number. The function should handle an empty list by returning 0.
The code should start with:
```python
from typing import List
def calculate_average_length(strings: List[str]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average_length(strings: List[str]) -> int:
"""
Calculate the average number of characters in a list of strings, rounded to the nearest whole number.
Args:
strings (List[str]): ... |
magic_instruct_75k | 40,037 | Write a Bash script to automate the compilation and execution of a C++ program using the Clang++ compiler. The script should handle the inclusion of necessary libraries and flags, as well as the execution of the compiled program. Specifically, the script should:
1. Set the paths for necessary libraries and includes.
2.... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Set the paths for necessary libraries and includes
cpp_includes=(
"-IC:/msys64/mingw64/include"
"-IC:/msys64/mingw64/include/python3.8"
)
# Compile the C++ files using Clang++ with specified flags and link Python 3... |
magic_instruct_75k | 40,058 | Write a Python function to modify a given list of integers from 0 to 7 based on specific rules. The function should:
1. Remove all odd numbers from the list.
2. Square each remaining even number in the list.
3. Sort the list in ascending order.
The function should return the modified list as the output.
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def modify_list(zero_to_seven: List[int]) -> List[int]:
"""
Modify the given list of integers from 0 to 7 based on the following rules:
1. Remove all odd numbers from the list.
2. Square each rem... |
magic_instruct_75k | 40,059 | Write a Python function to manage a directory structure by taking a list of directory names as input and performing the following operations for each directory:
1. If the directory already exists, it should be removed.
2. A new directory with the same name should be created.
The function should handle any errors that ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import os
import shutil
def manage_directories(directories: List[str]) -> None:
"""
Manages a directory structure by removing existing directories and creating new ones.
Args:
directories (L... |
magic_instruct_75k | 40,061 | Write a Python function to validate a project slug based on the following criteria:
1. The slug should be all lowercase.
2. The slug should contain only alphanumeric characters and hyphens.
3. The slug should not start or end with a hyphen.
The function should return `True` if the slug meets all the criteria, and `Fal... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def validate_project_slug(slug: str) -> bool:
"""
Validates a project slug based on the following criteria:
1. The slug should be all lowercase.
2. The slug should contain only alphanumeric characters and hyph... |
magic_instruct_75k | 40,065 | Write a Python function to implement a simplified version of a command dispatch system. The system should be able to dispatch commands to specific modules based on the type of the view.
You are given a class `RCTPdfViewManager` with a method `dispatch_command` that takes three parameters:
1. `view` - an object represe... | Here is the Python code to solve the given problem in the markdown block:
```python
class RCTPdfControl:
def dispatch_command(self, command_id: str, command_args: dict) -> None:
"""
Dispatch a command to the RCTPdfControl module.
Args:
command_id (str): The command identifier.
... |
magic_instruct_75k | 40,069 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0. The function should be named `sum_even_numbers` and should accept a list of integers as its parameter.
The starter code is as foll... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_even_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list of integers.
Args:
numbers (List[int]): A list of integers.
Returns:
... |
magic_instruct_75k | 40,076 | Write a Python function to validate a PostgreSQL connection string. The connection string should adhere to the following format: `"postgresql://username:password@hostname:port/database"`. Your function should check if the input connection string conforms to this format and return a boolean value indicating its validity... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def validate_postgresql_connection_string(connstr: str) -> bool:
"""
Validates a PostgreSQL connection string to ensure it conforms to the specified format.
The connection string should be in the format: "postgre... |
magic_instruct_75k | 40,101 | Implement a method `bq_combined_datasets` within a Python class that combines the names of temporary and development datasets from BigQuery. The method should take no parameters and return a string representing the combined dataset name in the format "temp_dataset_dev_dataset". The combined dataset name should be const... | Here is the Python code to solve the given problem in the markdown block:
```python
class BigQueryConfig:
def __init__(self, config):
self._config = config
def bq_temp_dataset(self) -> str:
"""BigQuery (BQ) temp dataset, for `gcp` mode only"""
return self._config["bq"]["tmp_dataset"]
... |
magic_instruct_75k | 40,128 | Implement a Python function `user_marshaller` that converts a user object into a marshalled representation for storage or transmission. The user object has the following attributes:
- `id` (int): The unique identifier for the user.
- `username` (str): The username of the user.
- `email` (str): The email address of the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def user_marshaller(user):
"""
Converts a user object into a marshalled representation for storage or transmission.
Args:
user (object): An object with attributes `id`, `username`, `em... |
magic_instruct_75k | 40,139 | Write a Python function to restore specific named entity tags in the original text based on provided named entity tags and a dictionary of named entity data. The function should replace the named entities in the text with their corresponding tags.
The function signature is as follows:
```python
def RestoreTags(nltk_da... | Here is the Python code to solve the given problem in the markdown block:
```python
def RestoreTags(nltk_data: dict, text: str, backup_tags: list) -> str:
"""
Restores named entity tags in the original text based on the provided named entity tags and a dictionary of named entity data.
Args:
nltk_da... |
magic_instruct_75k | 40,145 | Write a Python function to detect drowsiness in a person's eyes using the Eye Aspect Ratio (EAR) technique. The function should analyze a series of frames from a video feed and determine if the person's eyes have been closed for an extended period, indicating potential drowsiness. The function should return `True` if d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def detect_drowsiness(ear_values: List[float], EAR_thresh: float, EAR_consec_frames: int) -> bool:
"""
Detects drowsiness in a person's eyes using the Eye Aspect Ratio (EAR) technique.
Args:
... |
magic_instruct_75k | 40,162 | Write a Python function to calculate the selected indices for influence approximation in a machine learning experiment. The function should determine which indices from the training dataset (`dataset_train`) to use based on the value of `option['ncfsgd']`. If `option['ncfsgd']` is greater than or equal to 0, the functi... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_selected_indices(option: dict, dataset_train) -> np.ndarray:
"""
Calculate the selected indices for influence approximation based on the value of `option['ncfsgd']`.
Args:
option (d... |
magic_instruct_75k | 40,182 | Write a Python function `add_checkpoint(milestone)` that adds a new checkpoint to the `SAVED_CHECKPOINTS` list if it is a valid multiple of 25,000 and not already present in the list. The function should return the updated `SAVED_CHECKPOINTS` list. The checkpoints are defined as multiples of 25,000, starting from 25,00... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
SAVED_CHECKPOINTS: List[int] = []
def add_checkpoint(milestone: int) -> List[int]:
"""
Adds a new checkpoint to the SAVED_CHECKPOINTS list if it is a valid multiple of 25,000 and not already present in ... |
magic_instruct_75k | 40,194 | Write a Python function `completeArrayGeneration` that generates a random array of a specified length, populates it with random values within a given range, and then exports it to a NumPy array. The function should take three parameters: `maxRangeVal` (the maximum value for the random numbers), `arr_length` (the length... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def genRandomValue(maxRangeVal: int) -> int:
"""
Generates a random value within the range [0, maxRangeVal].
Args:
maxRangeVal (int): The maximum value for the random number.
Returns:
... |
magic_instruct_75k | 40,195 | Write a Python function to calculate the daily change in the number of suspected cases from a given list of dictionaries. Each dictionary contains a key 'suspect' representing the number of suspected cases for a particular day in China. The function should return a new list `Dailysuspect` containing the daily change in... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_daily_change(data: dict) -> list:
"""
Calculate the daily change in the number of suspected cases from a given list of dictionaries.
Args:
data (dict): A dictionary containing a list of dictionaries un... |
magic_instruct_75k | 40,214 | Write a Python function to process a list of migration commands and return a dictionary containing the model names as keys and a list of removed fields for each model as values. Each migration command is represented as a dictionary with keys `'model_name'` and `'name'`. The function should start with:
```python
from ty... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_migrations(migration_commands: List[Dict[str, str]]) -> Dict[str, List[str]]:
"""
Processes a list of migration commands and returns a dictionary containing the model names as keys
... |
magic_instruct_75k | 40,247 | 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, the function should return 0.
The code should start with:
```python
from typing import List
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(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 repres... |
magic_instruct_75k | 40,262 | Create a Python function to detect circular dependencies in a directed graph. The graph is represented as a dictionary where each key is a node and the value is a list of nodes that the key node depends on. The function should return `True` if there are circular dependencies in the graph, otherwise `False`.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def has_circular_dependencies(graph: Dict[str, List[str]]) -> bool:
"""
Detects if there are circular dependencies in a directed graph.
Args:
graph (Dict[str, List[str]]): A dictionary... |
magic_instruct_75k | 40,277 | Write a Python function to organize a list of layout data entries into a dictionary. Each layout data entry consists of a group name, layout type, and parent component. The layout type can be one of the following: `SWT.SHADOW_NONE`, `SWT.SHADOW_IN`, or `SWT.SHADOW_OUT`. The function should group the layout data entries... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def organize_layout_data(layout_data: List[Tuple[str, str, str]]) -> Dict[str, Dict[str, List[str]]]:
"""
Organizes a list of layout data entries into a dictionary grouped by parent componen... |
magic_instruct_75k | 40,333 | Write a Python function to determine whether a given integer is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should be named `is_prime` and should take an integer as input and return `True` if the number is prime, and `False` other... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(n: int) -> bool:
"""
Determine whether a given integer is a prime number.
Args:
n (int): The integer to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
... |
magic_instruct_75k | 40,345 | Write a Python function to process a list of numbers and calculate their sum. If any of the numbers are negative, the function should raise a `ValueError` with the message "Error". Otherwise, it should return the sum of the numbers.
The function should start with:
```python
from typing import List
def sum_numbers(num... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of a list of numbers. If any number is negative, raise a ValueError with the message "Error".
Args:
numbers (List[int]): A l... |
magic_instruct_75k | 40,354 | Write a Python function to generate a shell script that launches a Java application using the command line. The script should set the classpath to include specific JAR files, set system properties, and launch the application using the `sun.tools.jconsole.JConsole` class. The function should take the version of the `jol... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_java_launch_script(version: str) -> str:
"""
Generates a shell script to launch a Java application using the command line.
The script sets the classpath to include specific JAR files, sets system properties,
... |
magic_instruct_75k | 40,358 | Write a Python function to simulate a simplified file system cleanup process. The function should take a list of commands as input and execute them in the specified order. The commands can be of three types: "rm -rf <directory>", "rm <file>", and "rm a.out". The "rm -rf <directory>" command removes the specified direct... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def simulate_file_system_cleanup(commands: List[str], initial_state: Dict[str, Union[List[str], bool]]) -> List[str]:
"""
Simulate a file system cleanup process based on a list of commands.
... |
magic_instruct_75k | 40,362 | Create a Python program to manage employee information using a custom data structure. The `EmployeeInfo` class should hold an employee's data, including their name, employee ID, and salary. Implement functions to perform the following operations:
1. Add a new employee to the system, providing their name, employee ID, a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Optional
class EmployeeInfo:
"""
A class to represent an employee's information.
Attributes:
name (str): The name of the employee.
emp_id (int): The unique employee ID.
sala... |
magic_instruct_75k | 40,363 | Write a Python function to parse a list of strings representing metadata for software packages. Each string contains information about the operating system, programming language, and topic associated with a particular package. The function should extract this information and organize it into a structured format for fur... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def parse_metadata(metadata_list: List[str]) -> Dict[str, List[str]]:
"""
Parses a list of strings representing metadata for software packages and organizes the information into a structured dictio... |
magic_instruct_75k | 40,379 | Write a Python function to manage a simple program management system. The system should allow the creation, deletion, and execution of programs. Each program has a name and a set of instructions to be executed. The function should start with:
```python
from typing import List
class Program:
def __init__(self, name... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class Program:
"""
A class to manage a simple program with a name and a set of instructions.
Attributes:
name (str): The name of the program.
instructions (List[str]): A list of inst... |
magic_instruct_75k | 40,392 | Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should efficiently handle both positive and negative integers. The code should start with:
```python
from typing import List
def max_subarray_sum(nums: 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(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 | 40,397 | Write a Python function `double_increment(x)` that takes an integer `x` as input and returns the result of incrementing `x` twice using the provided `increment` function. The `increment` function is already defined and simply returns the input incremented by 1. Your task is to implement the `double_increment` function ... | Here is the Python code to solve the given problem in the markdown block:
```python
def increment(x):
return x + 1
def double_increment(x: int) -> int:
"""
Increments the given integer `x` twice using the `increment` function.
Args:
x (int): The integer to be incremented twice.
Returns:
... |
magic_instruct_75k | 40,412 | Implement a simplified version of a data structure for managing workers in a company. The data structure should support adding workers, retrieving worker details by their ID, and removing workers. Each worker is identified by a unique ID and has associated attributes such as name, position, and department.
You need to... | Here is the Python code to solve the given problem in the markdown block:
```python
class WorkerManager:
def __init__(self):
"""
Initialize the WorkerManager with an empty dictionary to store worker details.
"""
self.workers = {}
def add_worker(self, id, name, position, departme... |
magic_instruct_75k | 40,425 | Write a Python function to perform element-wise addition on two multi-dimensional arrays of the same shape. The function should ensure that the arrays are compatible for addition and return the resulting array. The code should start with:
```python
from typing import List
def element_wise_addition(array1: List[List[in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def element_wise_addition(array1: List[List[int]], array2: List[List[int]]) -> List[List[int]]:
"""
Perform element-wise addition on two multi-dimensional arrays of the same shape.
Args:
arr... |
magic_instruct_75k | 40,428 | Write a Python function to process and aggregate data from a list of dictionaries. Each dictionary represents a row of data with keys "node" and "len". The function should filter out rows where the value of "len" is greater than 0, group the remaining rows by the length of the "node" string, and calculate the average l... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def aggregate_data(data: List[Dict[str, any]]) -> Dict[int, float]:
"""
Processes and aggregates data from a list of dictionaries.
Args:
data (List[Dict[str, any]]): A list of dictiona... |
magic_instruct_75k | 40,438 | Write a Python function to parse and extract data from an HTML form represented as a string. The function should extract the form's action URL and all input field names along with their corresponding values. The function should return a dictionary containing the form's action URL and a dictionary of input field names a... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def parseForm(html: str) -> dict:
"""
Parses an HTML form string and extracts the form's action URL and all input field names along with their corresponding values.
Args:
html (str): A string representing... |
magic_instruct_75k | 40,441 | Write a Python function to process a list of field types and perform specific operations based on the type of each field. Each field type is represented by an integer value, and the function should process the list of field types according to the following rules:
1. If the field type is 0, it should be skipped and not... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def processFieldTypes(fieldTypes: List[int]) -> int:
"""
Processes a list of field types and returns the final result after performing specific operations.
Args:
fieldTypes (List[int]): A li... |
magic_instruct_75k | 40,459 | Write a Python function to determine the command prefix for a Discord bot based on the server's ID. The command prefix can vary from server to server and is stored in a database. The function should take the server's ID as input and return the corresponding command prefix for that server. If the server ID is not found ... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_prefix(server_id: str) -> str:
"""
Retrieve the command prefix for a given server ID from the database.
If the server ID is not found, return the default command prefix "!".
Args:
server_id (str): The un... |
magic_instruct_75k | 40,470 | Write a Python function to generate the first `n` terms of the Fibonacci sequence using an asynchronous generator. The generator should produce each term in a separate thread and allow the consumer to asynchronously iterate over the generated terms.
The code should start with:
```python
import threading
import queue
... | Here is the Python code to solve the given problem in the markdown block:
```python
import threading
import queue
class FibonacciAsyncGenerator:
"""
An asynchronous generator for the first n terms of the Fibonacci sequence.
This class uses a separate thread to generate the Fibonacci sequence and allows
... |
magic_instruct_75k | 40,480 | Write a Python function to format a given string with a specified color code using ANSI escape sequences. The function should take a string and a color code as input and return the formatted string with the specified color applied. The color codes are predefined as `red` and `green`, and the escape character is represe... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_colored_text(text: str, color: str) -> str:
"""
Formats the given text with the specified color using ANSI escape sequences.
Args:
text (str): The input string to be formatted.
color (str): The co... |
magic_instruct_75k | 40,482 | Write a Python function to determine if a given NumPy data type is a floating-point number or a general numeric type. The function should accurately identify the specified data types and handle any edge cases that may arise. The code should start with:
```python
import numpy as np
def is_float(dtype) -> bool:
"""
... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def is_float(dtype) -> bool:
"""
Check if the given NumPy data type represents a floating-point number.
Args:
dtype: A NumPy data type.
Returns:
bool: True if the data type is a floa... |
magic_instruct_75k | 40,495 | Write a Python function to serialize user profiles and course statuses into a specific format. The function `serialize_user_profile` takes a `user_profile` object as input and returns a dictionary containing the serialized data. The function `serialize_course` takes a `course_status_object` as input and returns a dicti... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def serialize_user_profile(user_profile):
"""
Serialize a user profile object into a dictionary.
Args:
user_profile (object): An object with attributes `full_name`, `mail`, `birth_date... |
magic_instruct_75k | 40,509 | Write a Python function to generate a formatted documentation table for a given database model. The function should take in the model, a dictionary containing documentation information, and a list of column names. The function should return a string that represents the formatted table documentation based on the provide... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_table_documentation(model, doc, cols) -> str:
"""
Generate a formatted documentation table for a given database model.
Args:
model: The database model containing information about a table.
doc: ... |
magic_instruct_75k | 40,534 | Write a Python function to return the top-K predicted classes from a given list of image classification predictions. The function should take in an array of image classes and an integer K, and return a string containing the top-K predicted classes, separated by commas.
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 List
def top_k_predicted_classes(image_classes: List[str], K: int) -> str:
"""
Returns a string containing the top-K predicted classes from the given list of image classes.
Args:
image_classes (L... |
magic_instruct_75k | 40,554 | Write a Python function to extract specific information from a given configuration model represented by a Python class `Cfg`. The function should return a dictionary containing the number of layers in the model, the learning rate, and the type of optimizer being used. The configuration model is used to configure a neur... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_config_model(cfg) -> dict:
"""
Extracts specific information from a given configuration model and returns it as a dictionary.
Args:
cfg: An instance of the Cfg class representing the configuration model.... |
magic_instruct_75k | 40,558 | Write a Python function to parse command-line arguments and extract the values for specific flags. The function should take the command-line arguments as input and return the values for the specified flags in a dictionary. If a flag is not present in the arguments, its value should be set to `None`.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def parse_flags(args: List[str], flags: List[str]) -> Dict[str, str]:
"""
Parses command-line arguments and extracts the values for specified flags.
Args:
args (List[str]): A list of s... |
magic_instruct_75k | 40,596 | Write a Python function to insert a new app into a list of Django installed apps at a specified index. If the index is out of range, the new app should be added at the end of the list. The function should return the modified list.
The code should start with:
```python
from typing import List
def add_app_to_installed_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def add_app_to_installed_apps(installed_apps: List[str], new_app: str, index: int) -> List[str]:
"""
Inserts a new app into the list of Django installed apps at a specified index.
If the index is out... |
magic_instruct_75k | 40,602 | Write a Python function to simulate a simple game of chance involving a spinner with four colored sections: red, green, blue, and black. The function should randomly select and return one of the four colors when the spinner is spun.
The code should start with:
```python
import random
from typing import List, Literal
... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
from typing import List, Literal
def spin_spinner() -> Literal["red", "green", "blue", "black"]:
"""
Simulates a spinner with four colored sections: red, green, blue, and black.
Randomly selects and returns on... |
magic_instruct_75k | 40,615 | Write a Python function to determine whether a given point lies within a triangle in a 2D plane. The triangle is defined by three vertices, and the point is represented by its (x, y) coordinates. The function should return `True` if the point lies within the triangle, and `False` otherwise.
The code should start with:... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_point_in_triangle(p: tuple, v1: tuple, v2: tuple, v3: tuple) -> bool:
"""
Determine whether a given point lies within a triangle in a 2D plane.
Args:
p (tuple): A tuple representing the (x, y) coordinates of ... |
magic_instruct_75k | 40,646 | Write a Python function to process a list of database migration operations and return a dictionary containing the index together constraints for each model. The input list consists of tuples, where each tuple represents a migration operation. Each tuple contains the following elements:
- The model name as a string
- Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Set, Dict
def process_migration_operations(operations: List[Tuple[str, str, Set[Tuple[str, ...]]]]) -> Dict[str, List[Set[Tuple[str, ...]]]]:
"""
Processes a list of database migration operations... |
magic_instruct_75k | 40,647 | Write a Python function to generate a string representation of a graphical shape based on specified properties. The function should take in various parameters to define the shape's appearance, including its vertices, properties, dimensions, color, border style, border color, and border width. The function should return... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_shape(u: str, v: str, b: float, e: float, width: int, depth: int, color: str, border: str, bordercolor: str, borderwidth: int) -> str:
"""
Generates a string representation of a graphical shape based on the given para... |
magic_instruct_75k | 40,650 | Write a Python function to simulate the installation and verification process of packages on a Linux system. The function should mimic the behavior of a Bash script that installs package groups and individual packages, and verifies the successful installation of the base packages before proceeding with additional depen... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def simulate_package_installation() -> Dict[str, str]:
"""
Simulates the installation and verification process of packages on a Linux system.
This function mimics the behavior of a Bash script that ... |
magic_instruct_75k | 40,675 | Write a Python function to validate a Sudoku board. The function should take a 9x9 grid representing the Sudoku board as input and return `True` if the board is valid, and `False` if it is not.
A valid Sudoku board is one where each row, column, and 3x3 subgrid contains the numbers 1 to 9 without repetition. The input... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_valid_sudoku(grid: List[List[int]]) -> bool:
"""
Validate a 9x9 Sudoku board.
Args:
grid (List[List[int]]): A 9x9 grid representing the Sudoku board.
Returns:
bool: True ... |
magic_instruct_75k | 40,676 | Write a Python function to calculate the sum of all even numbers in a given list of integers. The function should take a list of integers as input and return the sum of all the even numbers in the list. The code should start with:
```python
from typing import List
def sum_of_even_numbers(numbers: 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(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in a given list of integers.
Args:
numbers (List[int]): A list of integers.
Returns:
... |
magic_instruct_75k | 40,684 | Write a Python function to merge multiple configuration files into a single configuration dictionary. Each configuration file is represented as a key-value pair, where the key is the file name and the value is the content of the file. The function should also take an optional argument to limit the number of files to be... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def merge_config_files(config_files: Dict[str, Any], limit: int = 0) -> Dict[str, Any]:
"""
Merge multiple configuration files into a single configuration dictionary.
Args:
config_files... |
magic_instruct_75k | 40,692 | Write a Python function to process a list of employees and their respective job titles. The function should validate the job titles and provide a list of unique job titles, excluding any empty or "None" entries. Additionally, the function should count the occurrences of each job title and return a dictionary with the j... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
from collections import defaultdict
def process_job_titles(employees: List[Dict[str, str]]) -> Dict[str, int]:
"""
Processes a list of employees and their job titles, returning a dictionary with un... |
magic_instruct_75k | 40,697 | Write a Python function to organize a list of event tuples into a dictionary where the keys are the months (as integers) and the values are lists of event names that occur in that month. Each tuple in the list represents a significant date and its corresponding event. The first element of each tuple is the month (as an... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def organize_events(events: List[Tuple[int, int, str]]) -> Dict[int, List[str]]:
"""
Organizes a list of event tuples into a dictionary where the keys are the months
and the values are l... |
magic_instruct_75k | 40,712 | Write a Python function to generate the file path for a specific plate and batch from a high-throughput screening experiment dataset. The function should take three parameters: `batch`, `plate`, and `cell_line_column`, and return the file path in the format "data/{batch}/{plate}_data.csv". The `cell_line_column` parame... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_data_file_path(batch: str, plate: str, cell_line_column: str) -> str:
"""
Generate the file path for the specified plate and batch in a high-throughput screening experiment dataset.
Args:
batch (str): A stri... |
magic_instruct_75k | 40,724 | Write a Python function to calculate the difference between two given curves. Each curve is represented as a list of integer values, where each value corresponds to the height of the curve at a specific point. The difference between two curves is defined as the element-wise subtraction of the corresponding values in th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_curve_difference(curve1: List[int], curve2: List[int]) -> List[int]:
"""
Calculate the difference between two curves represented as lists of integers.
Args:
curve1 (List[int]):... |
magic_instruct_75k | 40,733 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0. The function should be efficient and handle large input sizes within the given constraints.
The code should start with:
```python
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_even_numbers(new_params: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list of integers.
Args:
new_params (List[int]): A list of integers.
Returns:
... |
magic_instruct_75k | 40,743 | Implement a Python class `ColorOutputManager` that manages the output of color data to either standard output or a file. The class should meet the following requirements:
1. The class should have a constructor that takes a boolean parameter `useStandardOutput` to determine whether the color data should be output to the... | Here is the Python code to solve the given problem in the markdown block:
```python
class ColorOutputManager:
def __init__(self, useStandardOutput: bool):
"""
Initializes the ColorOutputManager with a flag to determine the output destination.
Args:
useStandardOutput (bool): If T... |
magic_instruct_75k | 40,774 | Write a Python function to process a given input string that contains a series of numbers and characters. The function should extract specific information from the string and perform operations based on the extracted information. The input string will contain a number enclosed in square brackets, a number following the... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def process_input_string(input_string: str) -> str:
"""
Processes the input string to extract specific information and perform operations based on the extracted information.
Args:
input_string (str): The ... |
magic_instruct_75k | 40,779 | Write a Python function to calculate the total price of all items in an order. Each item in the order has a price attribute, and the function should sum these prices to compute the total price. The function should be designed to work with an `order` object that has methods to retrieve the items in the order and to retr... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_price(order) -> float:
"""
Calculate the total price of all items in the given order.
Args:
order: An object representing an order, which has a method `get_items()` to retrieve the items in the o... |
magic_instruct_75k | 40,788 | Write a Python function to extract comments from a given input string. The input string contains one or more comments, each starting with the `///` prefix and ending before the next occurrence of `///`. The comments may span multiple lines and may contain any printable characters, including spaces, tabs, and newlines. ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extractComments(input: str) -> List[str]:
"""
Extracts comments from a given input string. Comments are denoted by the `///` prefix
and may span multiple lines. The function returns a list of str... |
magic_instruct_75k | 40,790 | Write a Python function to calculate the percentage of occurrences of each unique element in a given list. The function should take a list of elements as input and return a dictionary where the keys are the unique elements from the input list, and the values are the percentages of occurrences of each element in the inp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_percentages(input_list: List[int]) -> Dict[int, float]:
"""
Calculate the percentage of occurrences of each unique element in the given list.
Args:
input_list (List[int])... |
magic_instruct_75k | 40,793 | Write a Python function to determine the next color in a predefined sequence of colors. The sequence of colors is as follows: WHITE -> RED -> GREEN -> BLUE -> WHITE. The function should take a string representing the current color as input and return the next color in the sequence.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def next_color(color: str) -> str:
"""
Determines the next color in the predefined sequence of colors.
The sequence of colors is: WHITE -> RED -> GREEN -> BLUE -> WHITE.
Args:
color (str): The current color in ... |
magic_instruct_75k | 40,819 | Write a Python function to generate a URL for accessing a Twitter account's timeline using the provided configuration settings for RabbitMQ and Twitter. The function should take the Twitter account name as input and return the complete URL. The configuration settings are as follows:
- `TWI_URL`: A constant representing... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_twitter_url(account_name: str) -> str:
"""
Generates a URL for accessing a Twitter account's timeline.
Args:
account_name (str): The Twitter account name.
Returns:
str: The complete URL for... |
magic_instruct_75k | 40,838 | Write a Python function to determine the longest common prefix among an array of strings. The longest common prefix is the longest string that is a prefix of all strings in the array. If there is no common prefix, the function should return an empty string.
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 longest_common_prefix(strs: List[str]) -> str:
"""
Determine the longest common prefix among an array of strings.
Args:
strs (List[str]): An array of strings.
Returns:
str: ... |
magic_instruct_75k | 40,854 | Write a Python function to parse a date string in the format "YYYY-MM-DD" and return the day, month, and year as separate values. The function should handle the input date string and return a tuple containing the day, month, and year in the format `(day, month, year)`.
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 Tuple
def parse_date(date_str: str) -> Tuple[int, int, int]:
"""
Parses a date string in the format "YYYY-MM-DD" and returns the day, month, and year as separate values.
Args:
date_str (str): The... |
magic_instruct_75k | 40,857 | Write a Python function to generate a response message based on an incoming message and a `topic_sum_map` dictionary. The `topic_sum_map` maps topics (strings) to their respective sums (integers). The `get_response` function should decode the incoming message to extract the topic, look up the topic in the `topic_sum_ma... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_response(message: bytes, topic_sum_map: dict) -> bytes:
"""
Generates a response message based on the incoming message and the topic_sum_map.
Args:
message (bytes): The incoming message in bytes format.
... |
magic_instruct_75k | 40,871 | Write a Python function to calculate the maximum sum of a subarray of a given array using the 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 | 40,874 | Write a Python function `conditional_sum(n, k)` that takes in two integers `n` and `k` and returns the sum of all integers from `k` to `n` inclusive, only if the conditions are satisfied. If the conditions are not met, the function should return -1. The conditions are:
1. `n` must be non-negative.
2. `k` must be a non-... | Here is the Python code to solve the given problem in the markdown block:
```python
def conditional_sum(n: int, k: int) -> int:
"""
Calculate the sum of all integers from `k` to `n` inclusive, only if the conditions are satisfied.
Args:
n (int): The upper bound of the range (inclusive).
k (... |
magic_instruct_75k | 40,875 | Write a Python function to perform a constant-time branch operation. The function should take three parameters: `subject`, `result_if_one`, and `result_if_zero`. The function should return `result_if_one` if `subject` is 1, and `result_if_zero` if `subject` is 0. The function should execute in constant time, meaning th... | Here is the Python code to solve the given problem in the markdown block:
```python
def select(subject: int, result_if_one, result_if_zero) -> int:
"""
Perform a constant-time branch operation.
Args:
subject (int): The subject value, which should be either 0 or 1.
result_if_one: The result ... |
magic_instruct_75k | 40,885 | Write a Python function `process_items(items)` that processes a list of dictionaries, each representing an item with keys 'title', 'subtitle', and 'valid'. The function should modify the list according to the following rules:
- If an item has a 'title' of 'No entities found' and a 'valid' value of False, the function s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_items(items: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Processes a list of dictionaries, modifying or removing items based on specific rules.
Args:
items (List[Dic... |
magic_instruct_75k | 40,896 | Write a Python function to calculate the sum of values of a given list of variables. The function should consider only the variables provided in the input list and ignore any other variables. The variables and their values are predefined in a dictionary.
The code should start with:
```python
from typing import List
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_variable_sum(variables: List[str]) -> int:
"""
Calculate the sum of values of the given list of variables.
Args:
variables (List[str]): A list of variable names whose values ne... |
magic_instruct_75k | 40,898 | Write a Python function to retrieve a tokenizer for a given language pair from a predefined dictionary. If the language pair is not found in the dictionary, the function should return a default tokenizer. The function should be designed to handle various language pairs efficiently.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_tokenizer(language_pair: str) -> str:
"""
Retrieve the tokenizer for a given language pair from a predefined dictionary.
If the language pair is not found, return a default tokenizer.
Args:
language_pair... |
magic_instruct_75k | 40,910 | Write a Python function to parse the output of a parameter generator and perform a sanity check to ensure that at least one parameter has been generated. The generator output is a string where parameters are separated by a specific delimiter (e.g., a comma). If no parameters are found, the function should raise a custo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class NoParametersGeneratedError(Exception):
"""Custom exception for when no parameters are generated."""
pass
def parse_generator_output(generator_output: str, delimiter: str = ',') -> List[str]:
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.