source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 16,711 | Write a Python function to simulate the behavior of the given bash script `signal.sh`. The function should accept command-line arguments to send signals to a specified process. The function should handle various signal options and validate the input to ensure correct usage.
The function should start with:
```python
im... | Here is the Python code to solve the given problem in the markdown block:
```python
import argparse
import os
import signal
def send_signal_to_process(pid: int, signal_type: str) -> None:
"""
Sends a specified signal to a process with the given process ID.
Args:
pid (int): The process ID of the ta... |
magic_instruct_75k | 16,720 | Write a Python function to reshape a 3D NumPy array into a 2D NumPy array. The input array is represented as a 3D NumPy array with dimensions `(b, n, d)`, where `b` represents the number of blocks, `n` represents the number of elements in each block, and `d` represents the number of features for each element. The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def reshape_3d_to_2d(x: np.ndarray) -> np.ndarray:
"""
Reshapes a 3D NumPy array into a 2D NumPy array.
Args:
x (np.ndarray): A 3D NumPy array with dimensions (b, n, d), where b is the number of ... |
magic_instruct_75k | 16,761 | Write a Python function to collect a specified number of random numbers, perform a series of operations on the collected data, and return the results. The operations to be performed are:
1. Calculate the sum of all collected numbers.
2. Find the maximum and minimum values among the collected numbers.
3. Sort the collec... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import random
def collect_and_process_random_numbers(num: int) -> Tuple[int, int, int, List[int]]:
"""
Collects a specified number of random numbers, performs a series of operations on the collect... |
magic_instruct_75k | 16,772 | Write a Python function to process command-line arguments and perform specific actions based on the provided options. The function should accept two options: `-d` or `--disk` to specify a disk, and `-r` or `--dir` to specify a directory. The function should then perform different actions based on the provided options.
... | Here is the Python code to solve the given problem in the markdown block:
```python
import sys
from typing import List
def process_command_line_args(args: List[str]) -> None:
"""
Process command-line arguments and perform specific actions based on the provided options.
Args:
args (List[str]): A li... |
magic_instruct_75k | 16,775 | Write a Python function to count the number of distinct single-particle states from a given list of tuples. Each tuple represents a single-particle state denoted by a pair of integers (N1, N2), and the order of the integers in the pair is significant. For example, (1, 2) and (2, 1) are considered distinct states. The f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def countDistinctStates(states: List[Tuple[int, int]]) -> int:
"""
Counts the number of distinct single-particle states from a given list of tuples.
Each tuple represents a single-particle st... |
magic_instruct_75k | 16,790 | Write a Python function `process_file_data` that processes a list of timestamps in the format "YYYY-MM-DD HH:MM:SS" and extracts the year, month, and day from each timestamp. The function should return a list of lists, where each sublist contains the extracted year, month, and day as integers. Additionally, implement t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def get_time_members(timestamp: str) -> Tuple[int, int, int, int]:
"""
Extracts the year, month, day, and hour from a timestamp string.
Args:
timestamp (str): A timestamp string in th... |
magic_instruct_75k | 16,793 | Write a Python function to process command-line arguments for a game configuration tool. The function should handle setting default values for the game and company names, and process any command-line arguments to override these defaults. The function should follow these rules:
1. Set default values for the game and com... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_game_config(args: List[str]) -> Tuple[str, str]:
"""
Process command-line arguments to configure game and company names.
Args:
args (List[str]): A list of command-line arg... |
magic_instruct_75k | 16,794 | Write a Python function to filter words from a given list that contain all the letters in a given set at least once. The function should return a list of words that meet this criteria. The function should be case-insensitive, meaning it should treat 'A' and 'a' as the same letter.
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, Set
def filter_words(words: List[str], letters: Set[str]) -> List[str]:
"""
Filters words from a given list that contain all the letters in a given set at least once.
Args:
words (List[str]... |
magic_instruct_75k | 16,808 | Write a Python function to convert the uppercase characters in a given string to lowercase and the lowercase characters to uppercase, while preserving any non-alphabetic characters. The function should take a single string as input and return the converted string.
The code should start with:
```python
def convert_case... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_case(input_string: str) -> str:
"""
Converts the case of each alphabetic character in the input string.
Uppercase characters are converted to lowercase, and lowercase characters are converted to uppercase.
No... |
magic_instruct_75k | 16,814 | Write a Python function to merge two JSON-like objects into a destination object according to specific rules. The function should take three parameters: `dest`, `obj1`, and `obj2`. The merging rules are as follows:
1. If a key exists in both `obj1` and `obj2` with the same value, the key-value pair should be added to `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, Dict
def mergeInto(dest: Dict[str, Any], obj1: Dict[str, Any], obj2: Dict[str, Any]) -> None:
"""
Merges the contents of `obj1` and `obj2` into `dest` according to specific rules.
Args:
dest... |
magic_instruct_75k | 16,844 | Write a Python function to generate a URL for an event based on the provided filename. The function should take the filename as input and return the corresponding event URL in the format "events/{filename}". The function should handle filenames with different extensions and ensure that the URL is correctly formatted.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_event_url(filename: str) -> str:
"""
Generates an event URL based on the provided filename.
Args:
filename (str): The filename for which to generate the event URL.
Returns:
str: The event U... |
magic_instruct_75k | 16,849 | Write a Python function to update a dictionary of environment variables by adding two new key-value pairs. The first key should be "IMAGE_DIFF_DIR" with a value of "$(SOURCE_ROOT)/$(PROJECT_NAME)Tests/FailureDiffs", and the second key should be "FB_REFERENCE_IMAGE_DIR" with a value of "$(SOURCE_ROOT)/$(PROJECT_NAME)Tes... | Here is the Python code to solve the given problem in the markdown block:
```python
def add_image_directories(env_vars: dict) -> dict:
"""
Updates the given dictionary of environment variables by adding two new key-value pairs.
Args:
env_vars (dict): A dictionary representing the environment variab... |
magic_instruct_75k | 16,852 | Write a Python function to convert a list of tuples into a dictionary where the keys are the first elements of the tuples and the values are lists of the second elements of the tuples. If a key is already present in the dictionary, the corresponding value should be appended to the existing list.
The function should st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Any, Dict
def tuple_list_to_dict(input_list: List[Tuple[Any, Any]]) -> Dict[Any, List[Any]]:
"""
Converts a list of tuples into a dictionary where the keys are the first elements of the tuples
... |
magic_instruct_75k | 16,856 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner in a grid of given dimensions. The grid is represented as a 2D matrix, and you can only move down or right at any point in time. The dimensions of the grid are given as a tuple `input_shape`, where the fi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def unique_paths(input_shape: Tuple[int, int]) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner in a grid.
Args:
input_shape (Tuple[int, ... |
magic_instruct_75k | 16,871 | Implement a Python class `ColorPalette` that represents a color palette in a graphics application. The class should support adding new colors and retrieving the RGB values of existing colors. The class should have the following methods:
- `add_color(color_name: str, red: int, green: int, blue: int) -> None`: Adds a ne... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple, Optional
class ColorPalette:
def __init__(self):
"""
Initialize the ColorPalette with an empty dictionary to store colors.
"""
self.colors: Dict[str, Tuple[int, int, i... |
magic_instruct_75k | 16,877 | Create a Python implementation of a custom test framework for unit testing. The framework should consist of three classes: `TestSuite`, `TestCase`, and `TestRunner`.
- **TestSuite**: This class should manage a collection of `TestCase` objects. It should have methods to add test cases and to run all the test cases it c... | Here is the Python code to solve the given problem in the markdown block:
```python
class TestSuite:
"""
Manages a collection of TestCase objects.
Attributes:
test_cases (list): A list to store TestCase objects.
Methods:
add_test_case(test_case): Adds a TestCase object to the list.
... |
magic_instruct_75k | 16,901 | Write a Python function to update a specific field of a course in a course management system. The function should take in a list of courses, a course name, a field name, and a new field value as parameters. The function should update the specified field for the given course and return the updated course information. If... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def _update_course_field(courses: List[Dict[str, Any]], course_name: str, field_name: str, new_field_value: Any) -> Any:
"""
Updates a specific field of a course in a course management system.... |
magic_instruct_75k | 16,910 | Create a Python function to manage a collection of items in an app list. The function should provide functionality to add, remove, and retrieve items, as well as to display the list of items.
The code should start with:
```python
from typing import List, Optional
class AppListItem:
def __init__(self, name: str):
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
class AppListItem:
def __init__(self, name: str):
self.name = name
class AppListManager:
def __init__(self):
self.items = []
def add_item(self, item: AppListItem) -> None:... |
magic_instruct_75k | 16,911 | Write a Python function to perform random image augmentation by applying random shifts to the input image based on specified ranges for height and width shifts. The function should take the input image `x`, `height_shift_range`, and `width_shift_range` as input parameters. The function should return the augmented image... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def random_image_augmentation(x: np.ndarray, height_shift_range: float, width_shift_range: float) -> np.ndarray:
"""
Perform random image augmentation by applying random shifts to the input image.
Args:
... |
magic_instruct_75k | 16,915 | Write a Python function to calculate the sum of non-negative elements in an iterable. The function should ignore any negative numbers in the iterable and handle the case when the input iterable is empty. The function should not use any built-in Python functions like `sum` or list comprehensions.
The code should start ... | Here is the Python code to solve the given problem in the markdown block:
```python
def _sum(iterable):
"""
Calculate the sum of non-negative elements in an iterable.
Args:
iterable (iterable): An iterable containing numeric values.
Returns:
int or float: The sum of non-negative elemen... |
magic_instruct_75k | 16,921 | Create a Python class `CustomList` that represents a list of values with specific properties. The class should support adding new values and retrieving the shape of the values stored in the list. The shape of a value is defined by its type and structure. The class should have the following methods:
1. `add_value(self, ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Any
class CustomList:
def __init__(self):
"""
Initializes an empty list to store values.
"""
self.values = []
def add_value(self, value: Any) -> None:
"""... |
magic_instruct_75k | 16,923 | Write a Python function to generate a SQL update statement based on a given dictionary of parameters. The function should take a dictionary as input and return a formatted SQL update statement. The SQL update statement should use placeholders for each parameter in the format `column_name=%(column_name)s`. The placehold... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_update_statement(params: dict) -> str:
"""
Generates a SQL update statement based on the given dictionary of parameters.
Args:
params (dict): A dictionary where keys represent column names and values re... |
magic_instruct_75k | 16,927 | Write a Python function to manage a Kubernetes proxy process. The function should start the proxy in the background, capture its process ID (PID), and save the PID to a file for future reference. The function should handle any errors that may occur during the process and provide appropriate feedback to the user.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def start_kubectl_proxy() -> None:
"""
Starts the Kubernetes proxy in the background, captures its process ID (PID),
and saves the PID to a file named `kubectl_proxy_pid` in the `./bin` directory... |
magic_instruct_75k | 16,930 | Write a Python function to generate a unique email address based on the author's name and the current date and time. The email address should follow the format: `authorname_YYYYMMDD_HHMMSS@example.com`, where `authorname` is the lowercase version of the author's name, `YYYY` is the current year, `MM` is the current mon... | Here is the Python code to solve the given problem in the markdown block:
```python
import datetime
def generate_unique_email(author_name: str) -> str:
"""
Generates a unique email address based on the author's name and the current date and time.
The email address follows the format: `authorname_YYYYMMDD_... |
magic_instruct_75k | 16,940 | Write a Python function `processFiles` that takes three inputs: `audioURL` (string), `imageURL` (string), and `bookName` (string). The function should perform the following steps:
1. Extract the local file names from the input URLs by taking the last segment after splitting the URLs by '/'.
2. Process the `bookName` to... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def processFiles(audioURL: str, imageURL: str, bookName: str) -> str:
"""
Processes the given audio and image URLs and book name to generate local file names and a download command.
Args:
audioURL (str): ... |
magic_instruct_75k | 16,958 | Write a Python function to process a list of Django migration operations and return a dictionary containing the model names and their corresponding altered field names. Each migration operation is represented as a tuple containing the model name, the altered field name, and the field type. The function should return a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def extract_altered_fields(migrations: List[Tuple[str, str, str]]) -> Dict[str, List[str]]:
"""
Processes a list of Django migration operations and returns a dictionary containing the model ... |
magic_instruct_75k | 16,974 | Write a Python function to perform non-IID (non-identically distributed) data partitioning for a given dataset. The function should partition the dataset into subsets for each user based on a specified non-IID distribution controlled by the parameter `alpha`. A higher `alpha` value indicates a more non-IID distribution... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import numpy as np
def noniid_data_partitioning(dataset: Dict[str, np.ndarray], num_users: int, alpha: float) -> List[Dict[str, np.ndarray]]:
"""
Perform non-IID data partitioning for a given datas... |
magic_instruct_75k | 16,990 | Write a Python function to analyze the structure of an HTML file and determine if all the opening tags have corresponding closing tags. The function should ignore any self-closing tags (e.g., `<br/>`, `<img/>`) and any tags that do not require a closing tag (e.g., `<meta>`, `<link>`). The function should return `True` ... | Here is the Python code to solve the given problem in the markdown block:
```python
def htmlTagChecker(html_string: str) -> bool:
"""
Analyzes the structure of an HTML file and determines if all the opening tags have corresponding closing tags.
Args:
html_string (str): A string representing an HTML... |
magic_instruct_75k | 16,992 | Write a Python function to implement a simple localization system for a web application. The function `setup_locales` should take a list of locale objects as input and set up the necessary data structures for localization. Each locale object contains a locale code and a dictionary of translations. The function should a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
# Global dictionary to store translations
translations_dict: Dict[str, Dict[str, str]] = {}
def setup_locales(locales: List[Dict[str, Any]]) -> None:
"""
Set up the localization system with t... |
magic_instruct_75k | 17,017 | Write a Python function `format_function_args(options)` that takes a dictionary `options` as input and returns a formatted string representing the function's arguments and their default values. The `options` dictionary contains argument names as keys and dictionaries as values, where each dictionary has a 'default' key... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def format_function_args(options: Dict[str, Dict[str, any]]) -> str:
"""
Formats a dictionary of function arguments and their default values into a string.
Args:
options (Dict[str, Dict[str,... |
magic_instruct_75k | 17,019 | Write a Python function to format a dictionary into a string where key-value pairs are sorted by key in ascending order and formatted as `"key"="value"` separated by commas. If the value is a string, it should be enclosed in double quotes. If the value is a number, it should be formatted as a decimal. If the value is a... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_dict(input_dict: dict) -> str:
"""
Formats a dictionary into a string where key-value pairs are sorted by key in ascending order
and formatted as '"key"="value"' separated by commas. Strings are enclosed in double... |
magic_instruct_75k | 17,021 | Write a Python function to calculate the cumulative sum of a given list of integers. The cumulative sum at each index in the output list should be the sum of all the integers from the input list up to and including the integer at that index. The function should start with:
```python
from typing import List
def cumulat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def cumulative_sum(nums: List[int]) -> List[int]:
"""
Calculate the cumulative sum of a list of integers.
Args:
nums (List[int]): A list of integers for which to calculate the cumulative sum... |
magic_instruct_75k | 17,048 | Write a Python function to parse a given code snippet from a C header file that defines various constants for different peripherals in a microcontroller. The function should extract the peripheral names and their corresponding values and return them as a dictionary.
The code snippet follows the format:
```
#if def... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def parsePeripheralConstants(code_snippet: str) -> dict:
"""
Parses a given code snippet from a C header file that defines various constants for different peripherals in a microcontroller.
Extracts the peripheral ... |
magic_instruct_75k | 17,063 | Create a Python class `CommunicationNode` that represents a communication network node. The node should support a configurable number of channels for transmitting data. Implement the necessary methods to manage the channels and data transmission.
The `CommunicationNode` class should have the following attributes:
- `n... | Here is the Python code to solve the given problem in the markdown block:
```python
class CommunicationNode:
def __init__(self, num_nodes, channels):
"""
Initialize the CommunicationNode with the total number of nodes and available channels.
Args:
num_nodes (int): The total numb... |
magic_instruct_75k | 17,064 | Write a Python function to generate a specified number of random values of a given type using a seed for the random number generator. The function should allow for changing the seed and retrieving the generated data. The code should start with:
```python
from typing import List, Type, Any
import random
def generate_ra... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Type, Any
import random
def generate_random_data(data_type: Type[Any], count: int, seed: int) -> List[Any]:
"""
Generates a specified number of random values of a given type using a seed for the random ... |
magic_instruct_75k | 17,077 | Write a Python function to determine whether a given variable is of boolean type. The function should return `True` if the variable is a boolean, and `False` otherwise. The function should be named `is_bool` and should take a single argument `var`.
The code should start with:
```python
def is_bool(var) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_bool(var) -> bool:
"""
Determines whether the given variable is of boolean type.
Args:
var: The variable to check.
Returns:
bool: True if the variable is a boolean, False otherwise.
"""
r... |
magic_instruct_75k | 17,078 | Write a Python function to construct the download URL and file name for a specific version of HashiCorp Vault based on the provided version and license. The function should take two parameters: `version` (string) and `license` (string). It should return a tuple containing the constructed download URL and file name in t... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_download_info(version: str, license: str) -> tuple:
"""
Constructs the download URL and file name for a specific version of HashiCorp Vault.
Args:
version (str): The version of Vault to be downloaded.
... |
magic_instruct_75k | 17,097 | Write a Python function to calculate the largest value that an unsigned bitfield can hold. The function should take the length of the bitfield in bits as input and return the largest value that the unsigned bitfield can represent. If an invalid length is specified (i.e., less than or equal to 0 or greater than a predef... | Here is the Python code to solve the given problem in the markdown block:
```python
class PythonRuntimeException(Exception):
"""Custom exception for invalid bitfield length."""
pass
def calculate_largest_value(length: int) -> int:
"""
Calculate the largest value that an unsigned bitfield can hold.
... |
magic_instruct_75k | 17,135 | Write a Python function to simulate the login attempt monitoring and termination logic described in the given bash script. The function should increment a counter for each login attempt and check if the counter exceeds a specified timeout value. If the timeout is exceeded, the function should display a message and simu... | Here is the Python code to solve the given problem in the markdown block:
```python
def monitor_login_attempts(login_attempts: int, login_timeout: int) -> None:
"""
Simulate the monitoring of login attempts and terminate the application if the timeout is exceeded.
Args:
login_attempts (int): The nu... |
magic_instruct_75k | 17,169 | Write a Python function to process event data and return a formatted string based on the event type and field type provided. The event data is represented as a dictionary with the following structure:
```python
event_data = {
'event_type': {
'name': event_name
},
'field_type': field_list
}
```
Where... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_event_data(event_data: dict) -> str:
"""
Formats the event data into a specific string pattern.
Args:
event_data (dict): A dictionary containing event data with the structure:
{
... |
magic_instruct_75k | 17,191 | Write a Python function to construct a URL based on given parameters. The function should take two input parameters: `ref_des` (a string representing a reference designator) and `date` (a string representing a date in ISO format "yyyy-mm-dd"). The function should then construct a URL using these parameters and a predef... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_url(ref_des: str, date: str) -> str:
"""
Constructs a URL based on the given reference designator and date.
Args:
ref_des (str): A string representing the reference designator.
date (str): A st... |
magic_instruct_75k | 17,208 | Write a Python function to count the occurrences of each unique payment status in a given list of payment statuses. The payment statuses are represented as strings and can be one of the following: "pending", "succeeded", "done", "refunded", or "removed". The function should return a dictionary where the keys are the un... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_payment_statuses(statuses: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique payment status in a given list.
Args:
statuses (List[str]): A list of strin... |
magic_instruct_75k | 17,213 | Write a Python function to update a configuration dictionary with a given key-value pair. If the key already exists in the dictionary, its value should be updated. If the key does not exist, it should be added to the dictionary with the provided value. The function should return the updated dictionary.
The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def update_config(config_dict: dict, key_value: tuple) -> dict:
"""
Updates a configuration dictionary with a given key-value pair.
If the key already exists in the dictionary, its value is updated. If the key does not exis... |
magic_instruct_75k | 17,233 | Write a Python function to search for a specific field name in a list of fields and return its corresponding type. Each field is represented as a tuple containing the field name and its type. If the field name is found, the function should return the corresponding type; otherwise, it should return `None`.
The function... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Any, Optional
def find_field_type(fields: List[Tuple[str, Any]], field_name: str) -> Optional[Any]:
"""
Searches for a specific field name in a list of fields and returns its corresponding type.
... |
magic_instruct_75k | 17,257 | Write a Python function to map an HTTP status code to its corresponding HTTP status message. The function should handle specific status codes and return a default message for any status code not explicitly listed.
The function should start with:
```python
def get_http_status_message(status_code: int) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def get_http_status_message(status_code: int) -> str:
"""
Returns the corresponding HTTP status message for a given status code.
Args:
status_code (int): The HTTP status code to look up.
Returns:
str: T... |
magic_instruct_75k | 17,279 | Write a Python function to calculate the frequency of each unique word in a list of strings, ignoring case sensitivity and stripping any non-alphabetic characters. The function should return a dictionary where the keys are the cleaned words and the values are their respective frequencies.
The code should start with:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def word_frequency(words: List[str]) -> Dict[str, int]:
"""
Calculate the frequency of each unique word in a list of strings, ignoring case sensitivity and stripping non-alphabetic charac... |
magic_instruct_75k | 17,285 | Write a Python function to generate Django migration code for renaming a field in a model. The function should take the model name, the old field name, and the new field name as inputs and return a string containing the migration code that would rename the field in the specified model.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_rename_field_migration(model_name: str, old_name: str, new_name: str) -> str:
"""
Generates Django migration code to rename a field in a specified model.
Args:
model_name (str): The name of the model wh... |
magic_instruct_75k | 17,287 | Write a Python function to parse and extract metadata from a given code snippet. The code snippet follows a specific format for categorizing and documenting modules. Your program should be able to extract the category, package, author's name, and email from the given code snippet. The function should return a dictionar... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_metadata(code_snippet: str) -> dict:
"""
Extracts metadata from a given code snippet.
The code snippet follows a specific format for categorizing and documenting modules.
This function extracts th... |
magic_instruct_75k | 17,293 | Write a Python function to extract a numerical counter and a text message from a given input string. The input string is formatted as "XXtext", where "XX" represents a two-digit numerical counter and "text" represents the actual message. The function should return a tuple containing the numerical counter and the text m... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def extract_message_info(message: str) -> Tuple[int, str]:
"""
Extracts a numerical counter and a text message from a given input string.
The input string is formatted as "XXtext", where "XX" repre... |
magic_instruct_75k | 17,304 | Write a Python function to construct the necessary HTTP request headers for interacting with a remote Cassandra database using HTTP requests. The headers required for each request are "X-Cassandra-Token" with the value of the authentication token and "Content-Type" with the value "application/json". The function should... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_cassandra_headers(auth_token: str) -> dict:
"""
Constructs the necessary HTTP request headers for interacting with a Cassandra database.
Args:
auth_token (str): The authentication token required for th... |
magic_instruct_75k | 17,306 | Write a Python function to merge two sorted arrays into a single sorted array. The function should efficiently combine the elements from both input arrays while maintaining the sorted order. The code should start with:
```python
from typing import List
def merge_sorted_arrays(array1: List[int], array2: List[int]) -> L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_arrays(array1: List[int], array2: List[int]) -> List[int]:
"""
Merge two sorted arrays into a single sorted array.
Args:
array1 (List[int]): The first sorted array.
... |
magic_instruct_75k | 17,319 | Write a Python function that takes a sequence of integers as input and returns a tuple containing three strings. The first string should be a space-separated representation of the input sequence. The second string should consist of periods ('.') with the same length as the sequence. The third string should consist of u... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def sequence_representation(sequence: List[int]) -> Tuple[str, str, str]:
"""
Converts a sequence of integers into a tuple of three strings.
The first string is a space-separated representati... |
magic_instruct_75k | 17,323 | Write a Python function to determine the maximum value that can be obtained by selecting a subset of items to fit into a knapsack of a given capacity. Each item has a specific weight and value. The function should take the list of item weights, item values, and the knapsack capacity as input and return the maximum valu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def knapsack_max_value(weights: List[int], values: List[int], capacity: int) -> int:
"""
Calculate the maximum value that can be obtained by selecting a subset of items to fit into a knapsack of a given ... |
magic_instruct_75k | 17,345 | Write a Python function to replace placeholders in a string containing multiple paragraphs with actual names provided in a separate list. Each paragraph may contain multiple placeholders denoted by `<NAME>`. If a placeholder appears multiple times in a paragraph, all occurrences should be replaced with the same name. T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def replace_placeholders(input_string: str, names: List[str]) -> str:
"""
Replaces placeholders in a string containing multiple paragraphs with actual names.
Args:
input_string (str): The in... |
magic_instruct_75k | 17,362 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. The function should take a list of integers representing the daily stock prices and return the maximum profit. You are only allowed to make at most one transaction (i.e., buy one and sell one sh... | 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 on different days.
Args:
prices (List[int]): A list of integers r... |
magic_instruct_75k | 17,378 | Write a Python function to process an array of integers based on the following conditions:
1. If the input array is empty, return an empty array.
2. If the input array is not empty, modify each element of the array as follows:
- If the number is even, square it.
- If the number is odd, cube it.
The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_array(arr: List[int]) -> List[int]:
"""
Process an array of integers by modifying each element based on whether it is even or odd.
Args:
arr (List[int]): The input array of integ... |
magic_instruct_75k | 17,381 | Write a Python function to extract unique macro names from a list of macro definition strings. Each macro definition string is in the format `"add_global_macros('MACRO_NAME')"`, where `'MACRO_NAME'` is a string representing the name of the macro to be added globally. The function should return a set containing all the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Set
def extract_unique_macros(macro_definitions: List[str]) -> Set[str]:
"""
Extracts unique macro names from a list of macro definition strings.
Args:
macro_definitions (List[str]): A list... |
magic_instruct_75k | 17,383 | Write a Python function to calculate the average of a list of numbers, excluding any negative numbers from the calculation. The function should return 0 if the input list is empty or contains only negative numbers.
The code should start with:
```python
from typing import List
def calculate_average(numbers: List[float... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average(numbers: List[float]) -> float:
"""
Calculate the average of a list of numbers, excluding any negative numbers.
Args:
numbers (List[float]): A list of numbers from whic... |
magic_instruct_75k | 17,386 | Write a Python function to process a given text and extract deprecated command line usage along with its recommended alternative. The input text will contain multiple lines, and the deprecated command line usage will be enclosed within triple quotes (`"""`). The deprecated usage will be in the format `'command_line_usa... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def process_deprecated_usage(text: str) -> str:
"""
Processes a given text to extract deprecated command line usage and provide a recommendation for the updated usage.
Args:
text (str): The input text con... |
magic_instruct_75k | 17,403 | Create a Python class `NeuralNetworkModel` that represents a neural network model and implements the functionality to add two specific layers: DepthToSpace and DepthwiseConvolution2d. The class should also provide a method to visualize the model's architecture, including the added layers.
The class should have the fol... | Here is the Python code to solve the given problem in the markdown block:
```python
class NeuralNetworkModel:
def __init__(self):
"""
Initialize the neural network model with an empty list to store layers.
"""
self.layers = []
def AddDepthToSpaceLayer(self, descriptor, name=None... |
magic_instruct_75k | 17,418 | Write a Python function to modify a specific bit within a given integer value and return the modified value. The function should set or clear the bit at a specified position based on a boolean input value. The function should handle bit positions ranging from 0 to 31 (inclusive) for a 32-bit integer.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
def modify_bit(value: int, position: int, bit_value: bool) -> int:
"""
Modifies a specific bit within a given integer value and returns the modified value.
Args:
value (int): The integer value in which the bit will ... |
magic_instruct_75k | 17,420 | Write a Python function `update_notification_settings` that takes in a dictionary of default notification settings and a list of updates, and returns the updated notification settings. Each update is represented as a dictionary with a key-value pair indicating the setting to be updated and its new value. If a setting i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def update_notification_settings(default_settings: Dict[str, any], updates: List[Dict[str, any]]) -> Dict[str, any]:
"""
Updates the default notification settings with the provided list of updates.... |
magic_instruct_75k | 17,423 | Write a Python function to display a list of products and their prices in a specific format. The products and their prices are stored in a list called `produtos_prec`, where the products are represented by strings at even indices and their corresponding prices are represented by floats at odd indices. The format requir... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def display_products_and_prices(produtos_prec: List[str]) -> None:
"""
Displays a list of products and their prices in a specific format.
The products and their prices are stored in a list where the... |
magic_instruct_75k | 17,427 | Write a Python function to create a full URL based on a given set of parameters. The function should take in a base URL, a service name, a key, and an optional path, and return the full URL. The full URL should be constructed by appending the service name and key to the base URL, and optionally appending the path if pr... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_full_url(base_url: str, service_name: str, key: str, path: str = '') -> str:
"""
Constructs a full URL based on the given base URL, service name, key, and an optional path.
Args:
base_url (str): The base ... |
magic_instruct_75k | 17,469 | Write a Python function to simulate a simple callback mechanism in a multithreaded environment. The function should create a separate thread to execute a callback function, ensuring proper synchronization to avoid race conditions and guarantee the execution of the callback function in the main thread.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from threading import Thread, Lock, Condition
from time import sleep
def execute_callback(callback):
"""
Simulate a multithreaded environment where a callback function is executed in the main thread.
Args:
callback... |
magic_instruct_75k | 17,505 | Write a Python function to parse and extract metadata from a given code snippet. The metadata includes the maintainer's name and email, the package's URL, license, version, and classifiers. The function should take a multi-line string `code` as input and return a dictionary containing the extracted metadata.
The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def parse_metadata(code: str) -> dict:
"""
Extracts metadata from a given code snippet and returns it as a dictionary.
Args:
code (str): A multi-line string containing the code snippet with metadata.
... |
magic_instruct_75k | 17,518 | Write a Python function to calculate the sum of all elements in a given list of integers. The function should iterate through each element in the list, accumulate the sum, and return the final sum. The code should start with:
```python
from typing import List
def calculate_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 calculate_sum(arr: List[int]) -> int:
"""
Calculate the sum of all elements in a given list of integers.
Args:
arr (List[int]): The list of integers whose sum needs to be calculated.
... |
magic_instruct_75k | 17,531 | Write a Python function `generate_url_mapping` that takes a list of URL patterns and their corresponding view classes as input and returns a dictionary mapping the URL patterns to their corresponding view classes. Each URL pattern is represented as a tuple where the first element is the URL pattern string and the secon... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict, Callable
def generate_url_mapping(url_patterns: List[Tuple[str, Callable]]) -> Dict[str, Callable]:
"""
Generates a dictionary mapping URL patterns to their corresponding view classes.
... |
magic_instruct_75k | 17,535 | Write a Python function to calculate the dot product of two given matrices. The dot product of two matrices A and B is defined as the sum of the products of the corresponding elements of the two matrices. The matrices are represented as 2D arrays of integers. Your task is to write a function `matrix_dot_product(A, B)` ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def matrix_dot_product(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
"""
Calculate the dot product of two matrices A and B.
Args:
A (List[List[int]]): The first matrix.
... |
magic_instruct_75k | 17,565 | Write a Python function to calculate the total amount spent by a customer at a store based on a list of transactions. Each transaction is represented by a string in the format "item_name:price", where "item_name" is the name of the purchased item and "price" is the cost of the item. The function should sum up the price... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculateTotalAmount(transactions: List[str]) -> float:
"""
Calculate the total amount spent by a customer based on a list of transactions.
Each transaction is represented by a string in the for... |
magic_instruct_75k | 17,569 | Write a Python function to count the occurrences of each unique file extension in a given list of file names. The function should return a dictionary where the keys are the file extensions (or "No Extension" if the file has no extension) and the values are the counts of files with those extensions.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_file_extensions(file_names: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique file extension in a given list of file names.
Args:
file_names (List[str])... |
magic_instruct_75k | 17,584 | Write a Python function to find the smallest missing positive integer that does not appear in a given strictly increasing list of distinct integers. The list is defined as strictly increasing if for any index `i` where `1 <= i < len(nums)`, the condition `nums[i - 1] < nums[i]` is satisfied.
The function should start ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_missing_number(nums: List[int]) -> int:
"""
Find the smallest missing positive integer in a strictly increasing list of distinct integers.
Args:
nums (List[int]): A strictly increas... |
magic_instruct_75k | 17,588 | Write a Python function to filter a list of objects based on their assigned tags. Each object is represented as a dictionary with a 'name' key and a 'tags' key. The 'tags' key contains a list of strings representing the tags assigned to the object. The function should take a list of such objects and a single tag as inp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_objects_by_tag(objects: List[Dict[str, any]], tag: str) -> List[Dict[str, any]]:
"""
Filters a list of objects based on the assigned tag.
Args:
objects: A list of dictionari... |
magic_instruct_75k | 17,594 | Write a Python function `process_request_params` that processes request parameters for a Flask application. The function should take a dictionary `request_params` as input and return a modified dictionary with the processed request parameters. The function should perform the following operations:
1. Remove any leading ... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_request_params(request_params: dict) -> dict:
"""
Processes the request parameters for a Flask application.
This function takes a dictionary of request parameters, removes any leading or trailing
whitespaces... |
magic_instruct_75k | 17,597 | Write a Python function to find the longest subsequence of consecutive integers in a given sequence. A subsequence is considered consecutive if all its elements are adjacent to each other in the original sequence. If there are multiple longest consecutive subsequences, the function should return the first one encounter... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_consecutive_subsequence(sequence: List[int]) -> List[int]:
"""
Finds the longest subsequence of consecutive integers in a given sequence.
Args:
sequence (List[int]): The input se... |
magic_instruct_75k | 17,613 | Write a Python function to find the closest number to a given integer `c` from a sorted list of integers `options`. If there are two closest numbers equidistant from `c`, the function should return the smaller one.
The code should start with:
```python
from typing import List
def find_closest_number(c: int, options: ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import bisect
def find_closest_number(c: int, options: List[int]) -> int:
"""
Find the closest number to a given integer `c` from a sorted list of integers `options`.
If there are two closest numbers... |
magic_instruct_75k | 17,616 | Write a Python function to simulate the behavior of a delegate class that can hold a reference to a function or method, invoke it with appropriate arguments, and verify the correctness of the invoked function or method. The function should support the following operations:
1. Creation of a delegate with a reference to ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Any
def create_delegate(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
"""
Creates a delegate function that can hold a reference to a function or method,
invoke it with appropriate argumen... |
magic_instruct_75k | 17,628 | Write a Python function to implement a thread-safe logging mechanism for a multi-threaded application. The function should ensure that log messages are not interleaved when multiple threads are writing to the log concurrently. The implementation should use a mutex to protect the critical section where log messages are ... | Here is the Python code to solve the given problem in the markdown block:
```python
from threading import Lock
from typing import List
class Logger:
def __init__(self):
self.log_entries: List[str] = []
self.mutex = Lock()
def trace(self, message: str) -> None:
"""
Appends a log... |
magic_instruct_75k | 17,648 | Write a Python function to format an address string from a given dictionary containing address information. The dictionary will have the following keys: `'addr:street'`, `'addr:city'`, `'addr:state'`, and `'addr:country'`. The values associated with these keys will be strings representing the street address, city, stat... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_address(address_info: dict) -> str:
"""
Formats an address string from a dictionary containing address information.
Args:
address_info (dict): A dictionary containing address information with keys:
... |
magic_instruct_75k | 17,673 | Write a Python function to decrypt a message encoded using a simple substitution cipher. In a substitution cipher, each letter in the plaintext is replaced by a letter some fixed number of positions down or up the alphabet. The function should take an encrypted text as input and return the decrypted message. The encryp... | Here is the Python code to solve the given problem in the markdown block:
```python
def decrypt_message(encrypted_text: str) -> str:
"""
Decrypts a message encoded using a simple substitution cipher (ROT13).
Args:
encrypted_text (str): The encrypted message to be decrypted.
Returns:
st... |
magic_instruct_75k | 17,687 | Write a Python function to generate a CSS string for a report header and footer based on user-defined settings. The function should incorporate the user-defined HTML content for the header and footer, user-defined CSS for the header, and specified margins and orientation. The function should return the CSS string that ... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_report_css(html: str, footer_html: str, css: str, name: str, margin_top: float, margin_bottom: float, margin_left: float, margin_right: float, orientation: str) -> str:
"""
Generates a CSS string for a report header... |
magic_instruct_75k | 17,699 | Write a Python function to generate a formatted string summarizing the configuration of a scientific instrument based on its parameters. The function should take in the following parameters:
- `unit`: A string representing the unit of measurement used by the instrument.
- `abslimits`: A tuple representing the absolute ... | Here is the Python code to solve the given problem in the markdown block:
```python
def instrument_configuration(unit: str, abslimits: tuple, visibility: tuple, speed: int, precision: float, startupcode: str) -> str:
"""
Generates a formatted string summarizing the configuration of a scientific instrument.
... |
magic_instruct_75k | 17,730 | Write a Python function to modify the age of a patient in a patient management system. The function should validate the new age to ensure it is a positive integer and greater than 17. If the age is valid, the function should update the patient's age in the information list and return the modified list. If the DNI (Docu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def modify_patient_age(dni: str, new_age: int) -> Union[List[str], int]:
"""
Modify the age of a patient identified by their DNI in the patient management system.
Args:
dni (str): The... |
magic_instruct_75k | 17,738 | Write a Python function to process flight data files based on the given requirements. The function should take three arguments: the path to the flight data directory, the name of the file, and the command line argument. After processing the files, the function should delete all the files in the flight data directory an... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import shutil
def process_flight_data(directory_path: str, file_name: str, command_line_arg: str) -> None:
"""
Process flight data files in the specified directory, delete all files after processing, and print "Test d... |
magic_instruct_75k | 17,778 | Write a Python function to simulate the execution of a command pattern for a simple text editor application. The command, `ChangeFontCommand`, should change the font of the text in the editor. The function should take the current text and the desired font as inputs and return the text with the new font applied.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def change_font(text: str, font: str) -> Tuple[str, str]:
"""
Simulates the execution of a ChangeFontCommand to change the font of the text in a text editor.
Args:
text (str): The cur... |
magic_instruct_75k | 17,780 | Write a Python function to generate test case methods for a unit testing framework. The function should take a list of test names as input and return a string containing the generated test case methods. Each test case method should call a function `run_exe_test` with the corresponding test name as an argument. The test... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_test_cases(test_names: List[str]) -> str:
"""
Generates test case methods for a unit testing framework based on the given test names.
Args:
test_names (List[str]): A list of tes... |
magic_instruct_75k | 17,801 | Write a Python function to calculate the expected output group sizes for each test case based on the given input tensor dimensions and the transformation rule. The transformation rule reshapes the input tensor into a new tensor with the same height and width but with specified group sizes for the channels.
The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_output_group_sizes(test_cases: List[Tuple[Tuple[int, int, int], List[int]]]) -> List[List[int]]:
"""
Calculate the expected output group sizes for each test case based on the given i... |
magic_instruct_75k | 17,832 | Write a Python function to find all unique triplets in a given sorted array of integers that sum up to zero. Each triplet should be in non-decreasing order. The function should return a list of lists containing all such unique triplets. If no such triplets exist, return an empty list.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def threeSum(nums: List[int]) -> List[List[int]]:
"""
Find all unique triplets in a sorted array that sum up to zero.
Args:
nums (List[int]): A sorted list of integers.
Returns:
... |
magic_instruct_75k | 17,878 | Write a Python function `simulate_task_creation` that simulates the behavior of a task creation service using asynchronous programming and dependency injection. The function should take in a task object and a publisher object, and then call an asynchronous service function to create a task. The service function returns... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
class CreateTaskIn:
def __init__(self, id: int, name: str, description: str):
self.id = id
self.name = name
self.description = description
class CreateTaskOut:
def __init__(self,... |
magic_instruct_75k | 17,881 | Write a Python function to simulate a dice rolling game. The game involves rolling two six-sided dice and recording the outcomes. The function should simulate rolling the dice 20 times and store the results in a list. Each roll should be represented as a tuple containing the values of the two dice. Finally, the functio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import random
def simulate_dice_rolls(num_rolls: int = 20) -> List[Tuple[int, int]]:
"""
Simulate rolling two six-sided dice a specified number of times and return the results.
Args:
... |
magic_instruct_75k | 17,901 | Write a Python function to process a list of repositories and return a dictionary containing the names of the repositories as keys and their corresponding languages as values. Each repository is represented as a dictionary with keys "name" and "language". The function should start with:
```python
from typing import Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_repositories(repositories: List[Dict[str, str]]) -> Dict[str, str]:
"""
Processes a list of repositories and returns a dictionary with repository names as keys and their corresponding l... |
magic_instruct_75k | 17,904 | Write a Python function to reverse a given string without using any built-in functions or libraries for reversing the string. The function should iterate through the string and construct the reversed string manually.
The code should start with:
```python
def reverseString(str: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverseString(str: str) -> str:
"""
Reverses the input string without using any built-in functions or libraries.
Args:
str (str): The input string to be reversed.
Returns:
str: The reversed string.
... |
magic_instruct_75k | 17,918 | Write a Python function to analyze a list of module objects and identify any potential issues with their types. The function should take a list of module objects as input and return the number of problematic modules found. A module object has a `gettype()` method that returns the type of the module as a string. The typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def analyze_modules(modules: List[object]) -> int:
"""
Analyzes a list of module objects and identifies any potential issues with their types.
Args:
modules (List[object]): A list of module ... |
magic_instruct_75k | 17,939 | Write a Python function to clean up a directory by removing all files except those specified in a whitelist file. The function should prompt the user to confirm deletion of any unknown files found in the directory. The function should handle cases where the directory does not exist, the whitelist file does not exist, o... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import sys
def clean_directory(directory_path: str, whitelist_file: str) -> None:
"""
Cleans up a directory by removing all files except those specified in a whitelist file.
Args:
directory_path (str): Th... |
magic_instruct_75k | 17,944 | Write a Python function to generate a random symmetric matrix of a given size `n`. A symmetric matrix is a square matrix that is equal to its transpose. The function should take an integer `n` as input and return a NumPy array representing the symmetric matrix of size `n x n`. The elements of the matrix should be rando... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def generate_symmetric_matrix(n: int) -> np.ndarray:
"""
Generate a random symmetric matrix of size n x n with elements between 1 and 100.
Args:
n (int): The size of the matrix (n x n).
Retu... |
magic_instruct_75k | 17,950 | Write a Python function to process a given dictionary containing information about a system and return a new dictionary with specific modifications. The input dictionary will include keys such as `system_name`, `systemstatus`, `system_created_by_user_id`, and `system_modified_by_user_id`. The function should perform th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def process_system_info(input_dict: Dict[str, str]) -> Dict[str, str]:
"""
Processes the input dictionary containing system information and returns a new dictionary with specific modifications.
Args... |
magic_instruct_75k | 17,983 | Write a Python function to calculate the average value of each image matrix in a list of 2D NumPy arrays. Each 2D array represents an image matrix, and the function should return a list of average values corresponding to each image matrix.
The code should start with:
```python
from typing import List
import numpy as n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import numpy as np
def average_image_values(image_matrices: List[np.ndarray]) -> List[float]:
"""
Calculate the average value of each image matrix in a list of 2D NumPy arrays.
Args:
image_m... |
magic_instruct_75k | 17,985 | Write a Python function to retrieve evaluation data for a specific year and term from a remote server. The function should take the year and term as input parameters and return the evaluation data. The function should simulate the retrieval process using a placeholder function.
The code should start with:
```python
de... | Here is the Python code to solve the given problem in the markdown block:
```python
def fetch_evals(year: int, term: str) -> str:
"""
Retrieves evaluation data for a specific year and term from a remote server.
Args:
year (int): The year for which the evaluation data is to be retrieved.
ter... |
magic_instruct_75k | 17,996 | Implement a Python function to generate a cryptographic key based on certain parameters and a starting time. The function should initialize a key generation process and store the relevant information. The function should return a dictionary containing the parameters, starting time, and the key generation process.
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def initialize_keygen(params: Dict[str, Any], started_at: int, keygen: Dict[str, Any]) -> Dict[str, Any]:
"""
Initializes a key generation process based on the provided parameters, starting time, an... |
magic_instruct_75k | 18,004 | Write a Python function to extract the actual hero names from a list of strings representing Dota 2 hero units. Each string follows the format 'npc_dota_hero_<hero_name>'. The function should return a new list containing only the actual hero names without the prefix 'npc_dota_hero_'.
The code should start with:
```pyt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_hero_names(hero_list: List[str]) -> List[str]:
"""
Extracts the actual hero names from a list of strings representing Dota 2 hero units.
Args:
hero_list (List[str]): A list of st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.