source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 3,311 | Write a Python function to extract the server indices from a list of comments. Each comment may contain irrelevant text, and the server index is denoted by the character 'j' followed by a non-negative integer. The function should return a list of server indices mentioned in the comments. If a comment does not contain a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_server_indices(comments: List[str]) -> List[int]:
"""
Extracts the server indices from a list of comments.
Args:
comments (List[str]): A list of strings where each stri... |
magic_instruct_75k | 3,321 | Write a Python function to calculate the cross section for the semihadronic, semileptonic process \( pp \to t\overline{t} \; Z', Z' \to b\overline{b} \) at different masses of the hypothetical particle \( Z' \). The function should take the mass of the \( Z' \) particle as input and return the corresponding cross secti... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
# Sample masses for which signal samples were created
manuel_masses = [500, 600, 700, 800, 900, 1000]
# Sample cross section values corresponding to the masses (in pb)
cross_sections = [0.1, 0.2, 0.3, 0.4, 0.5,... |
magic_instruct_75k | 3,325 | Write a Python function to generate an HTML table from a list of lines, where each line contains a string and an integer separated by a space. The function should return a string containing the HTML table. If the input list is empty, the function should return an HTML table with a single row and column displaying "Noth... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_html_table(lines: List[str]) -> str:
"""
Generates an HTML table from a list of lines, where each line contains a string and an integer separated by a space.
Args:
lines (List[s... |
magic_instruct_75k | 3,326 | Write a Python function to count the total number of unique console scripts defined within a list of Python packages. Each package has a list of entry points, and you need to identify the number of unique console scripts across all the packages.
The function should start with:
```python
from typing import List, Dict
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_console_scripts(package_names: List[str], entry_points: Dict[str, Dict[str, List[str]]]) -> int:
"""
Counts the total number of unique console scripts defined within a list of Python pack... |
magic_instruct_75k | 3,358 | Write a Python function to find the first number in a range from `bound` down to 1 that is divisible by a given `divisor`. If no such number is found, the function should return -1. The function should be named `find_divisible_number` and should take two parameters: `bound` (an integer representing the upper bound of t... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_divisible_number(bound: int, divisor: int) -> int:
"""
Find the first number in the range from `bound` down to 1 that is divisible by the given `divisor`.
Args:
bound (int): The upper bound of the range (in... |
magic_instruct_75k | 3,363 | Write a Python function to validate an API key based on a given set of rules. The API key is represented as a string and must adhere to the following criteria:
1. The API key must be of type "apiKey".
2. The API key must be at least 10 characters long.
3. The API key must contain at least one uppercase letter, one lowe... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_api_key(api_key: str) -> bool:
"""
Validates an API key based on the following criteria:
1. The API key must be of type "apiKey".
2. The API key must be at least 10 characters long.
3. The API key must c... |
magic_instruct_75k | 3,372 | Write a Python function to convert the mouse position in a 2D coordinate system to the corresponding position of an object in a game environment. The game environment is represented by a 2D coordinate system where the bottom-left corner is (0, 0) and the top-right corner is (10, 10). The mouse position is represented b... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_mouse_to_game_position(mouse_position: tuple) -> tuple:
"""
Converts the mouse position in a 2D coordinate system to the corresponding position of an object in a game environment.
The game environment is represe... |
magic_instruct_75k | 3,386 | Write a Python function to find the longest common subsequence (LCS) of two given strings. The function should return the length of the LCS.
The code should start with:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
"""
Calculate the length of the longest common subsequence (LCS) of two strings.
Args:
str1 (str): The first string.
str2... |
magic_instruct_75k | 3,390 | Write a Python function `process_class_folders(classes: List[str]) -> List[str]` that takes a list of class names as input and returns a list of strings representing the output of a specific operation performed on the files within each class folder. The function should simulate the process of iterating through each cla... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_class_folders(classes: List[str]) -> List[str]:
"""
Process files within each class folder and return a list of results.
Args:
classes (List[str]): A list of class names represen... |
magic_instruct_75k | 3,413 | Write a Python function `canAttack(x1, y1, x2, y2)` that determines whether a black queen positioned at coordinates `(x1, y1)` on an N x N chessboard can attack another position `(x2, y2)`. The function should return `True` if the queen can attack the position, and `False` otherwise. The queen can attack in all eight d... | Here is the Python code to solve the given problem in the markdown block:
```python
def canAttack(x1: int, y1: int, x2: int, y2: int) -> bool:
"""
Determines whether a black queen positioned at (x1, y1) can attack the position (x2, y2) on an N x N chessboard.
Args:
x1 (int): The row coordinate of t... |
magic_instruct_75k | 3,424 | Write a Python function to extract domain names from a list of URLs. The domain name is defined as the substring between the protocol (e.g., "http://", "https://") and the next slash ("/") or the end of the URL. If the URL does not contain a protocol, it should be considered invalid and excluded from the result.
The f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_domains(urls: List[str]) -> List[str]:
"""
Extracts domain names from a list of URLs.
The domain name is defined as the substring between the protocol (e.g., "http://", "https:... |
magic_instruct_75k | 3,443 | Write a Python function to compare the elements of each tuple in a given list of tuples and return a new list containing the result of the comparison as a string. The comparison result should indicate whether the first element is greater than, less than, or equal to the second element.
The function should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def compare_tuples(tuples: List[Tuple[int, int]]) -> List[str]:
"""
Compare the elements of each tuple in a given list of tuples and return a new list
containing the result of the comparison a... |
magic_instruct_75k | 3,454 | Write a Python function to parse and extract all HTML tags from a given HTML code snippet. The function should return a list of all the HTML tags found within the code. An HTML tag is defined as any substring enclosed within angle brackets `<` and `>`, including the brackets themselves.
The code should start with:
```... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_html_tags(html_code: str) -> List[str]:
"""
Extracts all HTML tags from a given HTML code snippet.
Args:
html_code (str): The HTML code snippet from which to extract tags.
R... |
magic_instruct_75k | 3,468 | Write a Python function to find the maximum profit that can be achieved from buying and selling a stock at most once, given an array of stock prices where `prices[i]` represents the price of a given stock on the `i`-th day. The function should return the maximum profit that can be achieved.
The code should start with:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be achieved from buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers wher... |
magic_instruct_75k | 3,497 | Write a Python function to calculate the total lengths of waterways from a given list of waterways. Each waterway is represented as a tuple containing the name of the waterway as a string and its length as an integer. The function should return a dictionary where the keys are the names of the waterways and the values a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def calculate_waterway_lengths(waterways: List[Tuple[str, int]]) -> Dict[str, int]:
"""
Calculate the total lengths of waterways from a given list of waterways.
Args:
waterways ... |
magic_instruct_75k | 3,501 | Write a Python function to implement the `kmeans_assign_labels` function for the k-means clustering algorithm. The function should take a 2D numpy array `X` representing the data points and a 2D numpy array `centers` representing the current cluster centers. The function should calculate the pairwise distances between ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def kmeans_assign_labels(X: np.ndarray, centers: np.ndarray) -> np.ndarray:
"""
Assign each data point in X to the nearest cluster center.
Args:
X (np.ndarray): A 2D numpy array where each row re... |
magic_instruct_75k | 3,527 | Write a Python function to construct a connection string for a PostgreSQL database based on the provided configuration variables. The function should take in the database host, database name, and database user as input and return the connection string in the format required for connecting to the PostgreSQL database.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_connection_string(db_host: str, db_db: str, db_user: str) -> str:
"""
Constructs a connection string for a PostgreSQL database based on the provided configuration variables.
Args:
db_host (str): The ho... |
magic_instruct_75k | 3,543 | Write a Python function to determine if a user has permission to edit a specific reading based on the request method and the ownership of the reading. The function should take three parameters: `user_id` (an integer representing the ID of the user making the request), `request_method` (a string representing the HTTP me... | Here is the Python code to solve the given problem in the markdown block:
```python
def has_permission_to_edit(user_id: int, request_method: str, reading_owner_id: int) -> bool:
"""
Determines if the user has permission to edit a specific reading based on the request method and ownership.
Args:
use... |
magic_instruct_75k | 3,548 | Write a Python function to count the number of connected components in a network represented by an adjacency matrix. The adjacency matrix is a square matrix where `A[i][j]` is 1 if there is a connection between nodes `i` and `j`, and 0 otherwise. The matrix is symmetric, meaning `A[i][j] = A[j][i]` for all `i` and `j`.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_connected_components(adjacency_matrix: List[List[int]]) -> int:
"""
Count the number of connected components in a network represented by an adjacency matrix.
Args:
adjacency_matrix... |
magic_instruct_75k | 3,565 | Write a Python function `generate_docker_service_command` that generates a Docker service creation command based on the provided input parameters. The function should take the following parameters:
- `service_name` (string): The name of the Docker service to be created.
- `network` (string): The name of the network to ... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_docker_service_command(service_name: str, network: str, hostname: str, replicas: int) -> str:
"""
Generates a Docker service creation command based on the provided input parameters.
Args:
service_name (... |
magic_instruct_75k | 3,579 | Write a Python function `process_configuration(config: dict) -> dict` that processes a given configuration dictionary and returns the final set of attributes after applying the rules specified in the configuration file. The configuration includes attributes such as `name`, `compatible_with`, `testonly`, `alwayslink`, a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def process_configuration(config: Dict[str, any]) -> Dict[str, any]:
"""
Processes the given configuration dictionary and returns the final set of attributes
after applying the rules specified ... |
magic_instruct_75k | 3,583 | Write a Python function `count_non_none_gradients(groups)` that processes a list of dictionaries representing groups of parameters and their gradients. Each dictionary contains two keys: "name" and "params". The "name" key holds the group name, and the "params" key holds a list of parameter objects. Each parameter obje... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def count_non_none_gradients(groups: List[Dict[str, Any]]) -> List[tuple]:
"""
Counts the number of parameters with non-None gradients in each group.
Args:
groups (List[Dict[str, ... |
magic_instruct_75k | 3,586 | Write a Python function to construct an SSH command string that connects to a target host via a jump host. The function should take four parameters: `jump_host`, `jump_host_ip`, `target_host`, and `target_host_ip`. The SSH command should follow the format: `ssh -J <jump_host>@<jump_host_ip> <target_host>@<target_host_i... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_ssh_command(jump_host: str, jump_host_ip: str, target_host: str, target_host_ip: str) -> str:
"""
Constructs an SSH command string to connect to a target host via a jump host.
Args:
jump_host (str): Th... |
magic_instruct_75k | 3,587 | Write a Python function to identify and report function names that violate specific naming conventions. The naming convention requires that all function names must be in snake_case and should not start with the word "without". The function should take a list of function names as input and return a list of names that vi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def find_invalid_function_names(function_names: List[str]) -> List[str]:
"""
Identifies and returns a list of function names that violate the specified naming conventions.
The naming conven... |
magic_instruct_75k | 3,599 | Write a Python function to determine the next state and the reward based on the current state and action in a simple environment. The environment is represented by a state that is a number between 1 and 25, and the actions are one of [-1, 1, 5, -5]. The function should handle invalid states and actions appropriately.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def take_action(state: int, action: int) -> List[int]:
"""
Returns the next state and the reward based on the current state and action.
Args:
state (int): The current state, a number between... |
magic_instruct_75k | 3,641 | Write a Python function to project all vertices in a 3D space onto a 2D plane and calculate the absolute difference between the maximum and minimum z-coordinates of three specified vertices. The vertices are represented as a list of tuples, where each tuple contains a 3D position and a projected 2D position. The functi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def projectAllVertices(vertices: List[Tuple[Tuple[float, float, float], Tuple[float, float, float]]]) -> None:
"""
Projects all vertices onto a 2D plane by setting the z-coordinate of the projecte... |
magic_instruct_75k | 3,645 | Write a Python function to implement a simple state machine for handling TCP events in a network application. The function should take a TCP event as input and return the corresponding state to transition to based on a provided mapping. If the input event is not found in the mapping, the function should return "UNKNOWN... | Here is the Python code to solve the given problem in the markdown block:
```python
def getTransitionState(event: str) -> str:
"""
Returns the state to transition to based on the given TCP event.
Args:
event (str): The TCP event to process.
Returns:
str: The state to transition to. If ... |
magic_instruct_75k | 3,657 | Write a Python function to analyze a list of classifiers from a `setup.py` file of a Python package. The classifiers list contains strings representing various attributes of the package. Your goal is to extract specific information from the classifiers list and perform some operations based on the extracted data.
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def analyze_classifiers(classifiers: List[str]) -> Dict[str, int]:
"""
Analyzes a list of classifiers from a setup.py file and returns a dictionary
containing the count of unique programming la... |
magic_instruct_75k | 3,661 | Write a Python function to simulate a database schema migration process. The function should take a list of migration operations and apply them to the database schema. Each migration operation is represented as a tuple containing the operation type, table name, and optional constraint type.
The supported operation typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def apply_migrations(migrations: List[Tuple[str, str, str]]) -> List[Tuple[str, str]]:
"""
Simulates a database schema migration process by applying a list of migration operations.
Args:
... |
magic_instruct_75k | 3,709 | Write a Python function to generate SQL commands for altering fields in Django models. The function should take the model name, field name, new field type, and any additional parameters as input and return the corresponding SQL command. The SQL command should be formatted correctly to reflect the changes in the databas... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_alter_field_sql(model_name: str, field_name: str, new_field_type: str, additional_params: dict) -> str:
"""
Generates an SQL command to alter a field in a Django model.
Args:
model_name (str): The name ... |
magic_instruct_75k | 3,715 | Write a Python function `create_square_dict` that takes a list of integers as input and returns a dictionary where the keys are the integers and the values are the squares of the integers. Additionally, write a program to iterate through the dictionary and print each key-value pair in the specified format "key is {key}... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def create_square_dict(input_list: List[int]) -> Dict[int, int]:
"""
Creates a dictionary where the keys are integers from the input list and the values are their squares.
Args:
input_... |
magic_instruct_75k | 3,720 | Write a Python function to process machine learning model predictions. The function should take a numpy array `y` where each row represents a sample and each column represents a label with a confidence score. The function should return a list of predictions based on the following rules:
- If a sample is confidently lab... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import List
def process_predictions(y: np.ndarray) -> List[int]:
"""
Processes the predictions made by a machine learning model.
Args:
y (np.ndarray): A numpy array where each row rep... |
magic_instruct_75k | 3,729 | Write a Python function to generate a new dictionary that contains the intersection of keys from two input dictionaries along with their corresponding values. The function should take two dictionaries as input: `index2label_map` and `real_label_dict`. The output dictionary should include only those keys that are presen... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def generate_intersection_mapping(index2label_map: Dict[int, str], real_label_dict: Dict[int, str]) -> Dict[int, str]:
"""
Generate a new dictionary that contains the intersection of keys from both input... |
magic_instruct_75k | 3,731 | Write a Python function to calculate the moving average of a given list of numbers with a specified window size. The moving average is a statistical technique used to analyze data points by creating a series of averages of different subsets of the full data set. The function should take a list of numbers and an integer... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_moving_average(numbers: List[float], window_size: int) -> List[float]:
"""
Calculate the moving average of a list of numbers with a specified window size.
Args:
numbers (List[f... |
magic_instruct_75k | 3,733 | Write a Python function to extract the local template path from a given file path. The local template path is obtained by extracting the filename from the given file path. The function should handle file paths with multiple directories and return only the filename.
The code should start with:
```python
def extract_loc... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_local_template_path(file_path: str) -> str:
"""
Extracts the local template path (filename) from a given file path.
Args:
file_path (str): The file path from which to extract the local template path.
... |
magic_instruct_75k | 3,744 | Write a Python function to manage user accounts on a Linux system by modifying user attributes such as UID, GID, home directory, and default shell. The function should accept various command-line options to modify these attributes and provide a usage message to guide users on how to interact with it.
The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Optional, Tuple
def user_mgmt(uid: Optional[int] = None, gid: Optional[int] = None, home: Optional[str] = None, shell: Optional[str] = None, username: Optional[str] = None, groupname: Optional[str] = None) -> Tuple[O... |
magic_instruct_75k | 3,745 | Write a Python function to calculate the average of a list of numbers without using any built-in Python functions or libraries for mathematical operations. The function should implement the average calculation from scratch using only basic arithmetic operations.
The code should start with:
```python
from typing import... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average(numbers: List[int]) -> float:
"""
Calculate the average of a list of numbers without using built-in functions or libraries.
Args:
numbers (List[int]): A list of integer... |
magic_instruct_75k | 3,780 | Write a Python function to calculate the resulting shape of a tensor operation given the shapes of the left-hand side (LHS) and right-hand side (RHS) tensors. The function should handle the following cases:
- If the RHS tensor has a single dimension (rhs_dim == 1), the resulting shape should have the same dimensions as... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_result_shape(lhs_shape: List[int], rhs_shape: List[int]) -> List[int]:
"""
Calculate the resulting shape of a tensor operation given the shapes of the LHS and RHS tensors.
Args:
... |
magic_instruct_75k | 3,789 | Write a Python function to check if all property names in a list of tuples are unique. Each tuple in the list represents a property and its corresponding value. If all property names are unique, the function should return `True`; otherwise, it should return `False`.
The code should start with:
```python
from typing im... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def check_unique_properties(props: List[Tuple[str, any]]) -> bool:
"""
Checks if all property names in a list of tuples are unique.
Args:
props (List[Tuple[str, any]]): A list of tupl... |
magic_instruct_75k | 3,820 | Write a Python function `version_control` that simulates a simplified version control system. The function should handle basic version control operations such as committing changes and displaying the commit history. The function should take a list of commands as input and return the commit history as a list of strings.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def version_control(commands: List[str]) -> List[str]:
"""
Simulates a simplified version control system that handles basic operations such as committing changes and displaying the commit history.
A... |
magic_instruct_75k | 3,836 | Write a Python function to check the version status of a list of packages against the latest versions available in a hypothetical package repository. The function should compare the provided versions with the latest versions and return a dictionary with the package names as keys and their version status as values. The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def check_package_versions(packages: Dict[str, str], latest_versions: Dict[str, str]) -> Dict[str, str]:
"""
Check the version status of a list of packages against the latest versions available.
Arg... |
magic_instruct_75k | 3,889 | Write a Python function to simulate the Association Request (AAssociateRQ) message in the context of DICOM (Digital Imaging and Communications in Medicine) communication protocol. The function should allow setting various parameters of the AAssociateRQ message, including the Called Application Title, Calling Applicatio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def create_aassociate_rq(called_app_title: str, calling_app_title: str, app_context: str, presentation_contexts: List[Dict[str, Any]], user_info: Dict[str, Any]) -> Dict[str, Any]:
"""
Creates... |
magic_instruct_75k | 3,893 | Write a Python function to calculate the cumulative sum of a list of integers. The cumulative sum at each index `i` in the output list should be the sum of all elements from index 0 to index `i` in the input list. The function should start with:
```python
from typing import List
def cumulative_sum(nums: List[int]) -> ... | 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]): The input list of integers.
Returns:
List[int]:... |
magic_instruct_75k | 3,909 | Write a Python function to calculate the number of trailing zeroes in the factorial of a given integer `num`. The function should be efficient and handle large values of `num` appropriately.
The code should start with:
```python
def trailing_zeroes_in_factorial(num: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def trailing_zeroes_in_factorial(num: int) -> int:
"""
Calculate the number of trailing zeroes in the factorial of a given integer `num`.
Args:
num (int): The integer for which to calculate the factorial's trailing ... |
magic_instruct_75k | 3,925 | Write a Python function to format a list of components and their quantities into a human-readable string. The function should take a dictionary where keys are component names (strings) and values are their quantities (integers), and return a formatted string representing the components and their quantities. The formatt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def formatComponents(components: Dict[str, int]) -> str:
"""
Formats a dictionary of component names and their quantities into a human-readable string.
Args:
components (Dict[str, int]): A d... |
magic_instruct_75k | 3,930 | Write a Python function to process the output data from a simulation tool called CMPSim. The output data consists of sets of information related to warmup instructions and representative regions. The function should determine the type of data present in each set and extract relevant information. The function should ret... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_CMPSim_output(output_data: List[str]) -> List[str]:
"""
Processes the output data from CMPSim to determine the type of data present in each set.
Args:
output_data (List[str]): A ... |
magic_instruct_75k | 3,979 | Write a Python function to parse and extract information from a nested dictionary representing an optimizer configuration. The dictionary contains information about the type of optimizer and its associated keyword arguments. Your task is to extract and return the type of optimizer and its corresponding keyword argument... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_optimizer_info(opt: dict) -> tuple:
"""
Extracts and returns the type of optimizer and its keyword arguments from a nested dictionary.
Args:
opt (dict): A nested dictionary representing the optimizer con... |
magic_instruct_75k | 3,985 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make any profit, return 0.
The function should start with:
```python
from typing import List
def max_profit(pr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers repre... |
magic_instruct_75k | 4,023 | Write a Python function `get_feature_server_config(feature_server_type)` that takes a feature server type as input and returns a dictionary containing the configuration settings for the feature server based on the specified type. The function should handle the different feature server types ('8k' and '8ksns') and retur... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_feature_server_config(feature_server_type: str) -> dict:
"""
Returns the configuration settings for the feature server based on the specified type.
Args:
feature_server_type (str): The type of the feature se... |
magic_instruct_75k | 4,030 | Write a Python function to calculate the average score for each student in a class based on their test scores. The test scores are stored in a 2D array where each row represents a student and each column represents a test. The function should return an array of average scores, where each average score is calculated as ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculateAverageScores(scores: List[List[int]]) -> List[float]:
"""
Calculate the average score for each student based on their test scores.
Args:
scores (List[List[int]]): A 2D array wh... |
magic_instruct_75k | 4,031 | Write a Python function to extract meaningful information from a given code snippet that contains encrypted messages interspersed with placeholder text denoted by `<KEY>`. The function should process the code snippet and return a list of decrypted messages in the order they appear.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_decrypted_messages(code_snippet: str) -> list:
"""
Extracts meaningful information from a given code snippet that contains encrypted messages
interspersed with placeholder text denoted by `<KEY>`.
Args:
... |
magic_instruct_75k | 4,066 | Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should be optimized to achieve a time complexity of O(n) and should not use any external libraries. The code should start with:
```python
from typing import List
def optimized_max_subarray_sum(arr: Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def optimized_max_subarray_sum(arr: List[int]) -> int:
"""
Calculate the maximum sum of a contiguous subarray within the given list of integers.
Args:
arr (List[int]): The list of integers f... |
magic_instruct_75k | 4,068 | Write a Python function to calculate the final padded image size based on the given padding ratio and image size. The function should take two parameters:
- `img_size` (integer): The original size of the input image.
- `padding_ratio` (float): The ratio by which the image will be padded.
The function should calculate ... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_padded_img_size(img_size: int, padding_ratio: float) -> int:
"""
Calculate the final padded image size based on the given padding ratio and image size.
Args:
img_size (int): The original size of the in... |
magic_instruct_75k | 4,079 | Write a Python function `map_hosts_to_roles` that takes in two dictionaries: `roledefs` and `hostnames`. The `roledefs` dictionary maps roles to lists of hostnames, and the `hostnames` dictionary maps hostnames to their corresponding IP addresses. The function should return a new dictionary where the keys are IP addres... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def map_hosts_to_roles(roledefs: Dict[str, List[str]], hostnames: Dict[str, str]) -> Dict[str, List[str]]:
"""
Maps each host to its corresponding roles based on the given role definitions and host... |
magic_instruct_75k | 4,093 | Write a Python function to simulate a simple operation a specified number of times and calculate the sum of all results. The operation involves generating a random number between 1 and 10 (inclusive) and then applying a transformation based on whether the number is even or odd. If the number is even, it is multiplied b... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def simulate_operations(op_count: int) -> int:
"""
Simulate a simple operation a specified number of times and calculate the sum of all results.
The operation involves generating a random number between 1 and... |
magic_instruct_75k | 4,105 | Write a Python function to calculate the total balance for a specific account based on a list of transactions up to a given date. Each transaction is represented by a string in the format "YYYY-MM-DD amount description", where:
- "YYYY-MM-DD" is the date of the transaction in the format year-month-day.
- "amount" is a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
from typing import List
def calculate_total_balance(transactions: List[str], account_date: str) -> float:
"""
Calculate the total balance for a specific account up to a given date based on a list o... |
magic_instruct_75k | 4,110 | Write a Python function to find the smallest common element in all rows of a given 2D matrix `mat` of integers, where each row is sorted in non-decreasing order. If there is no common element, return -1.
The function should start with:
```python
from typing import List
def smallest_common_element(mat: List[List[int]]... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def smallest_common_element(mat: List[List[int]]) -> int:
"""
Find the smallest common element in all rows of a given 2D matrix of integers,
where each row is sorted in non-decreasing order. If there... |
magic_instruct_75k | 4,129 | Write a Python function to transform a given list of integers such that each element is replaced by the maximum of 0 and the corresponding element minus 1. The function should handle any list of integers, including negative numbers and zeros.
The code should start with:
```python
from typing import List
def max_minus... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_minus_one(input_list: List[int]) -> List[int]:
"""
Transforms a list of integers such that each element is replaced by the maximum of 0 and the corresponding element minus 1.
Args:
i... |
magic_instruct_75k | 4,141 | Write a Python function to calculate the sum of the digits of a given positive integer `value`. The function should handle any positive integer input and return the sum of its digits. The code should start with:
```python
def calculate_digit_sum(value: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_digit_sum(value: int) -> int:
"""
Calculate the sum of the digits of a given positive integer.
Args:
value (int): The positive integer whose digits are to be summed.
Returns:
int: The sum ... |
magic_instruct_75k | 4,153 | Write a Python function to find the index where a target integer should be inserted in a sorted list of distinct integers to maintain its sorted order. If the target is already present in the list, the function should return its index. If the target is not present, the function should return the index where it would be... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def searchInsert(nums: List[int], target: int) -> int:
"""
Find the index where the target integer should be inserted in a sorted list of distinct integers.
Args:
nums (List[int]): A sorted ... |
magic_instruct_75k | 4,161 | Write a Python function to join a list of strings into a single string using a specified delimiter. The function should handle various edge cases, such as an empty list or an empty delimiter.
The code should start with:
```python
from typing import List
def join_with_delimiter(strings: List[str], delimiter: str) -> s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def join_with_delimiter(strings: List[str], delimiter: str) -> str:
"""
Joins a list of strings into a single string using the specified delimiter.
Args:
strings (List[str]): A list of strin... |
magic_instruct_75k | 4,177 | Write a Python function to simulate a simple entity-component system (ECS) that allows for the addition, removal, and retrieval of components and systems. The ECS should be implemented using dictionaries to store components and systems. The function should provide methods to add, remove, and retrieve components and sys... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any, Optional
class ECS:
def __init__(self):
"""
Initialize the ECS with empty dictionaries for components and systems.
"""
self.components: Dict[str, Any] = {}
self.... |
magic_instruct_75k | 4,180 | Write a Python function to filter out even numbers from a given list of integers. The function should return a new list containing only the even numbers from the original list. The code should start with:
```python
from typing import List
def filter_even_numbers(input_list: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_even_numbers(input_list: List[int]) -> List[int]:
"""
Filters out even numbers from a given list of integers.
Args:
input_list (List[int]): The list of integers from which to filt... |
magic_instruct_75k | 4,186 | Write a Python function to apply a mask to an RGB image based on a specified color. The function should take an RGB image represented as a numpy array, a mask represented as another numpy array, and a mask color specified as a string. The function should then apply the mask to the RGB image based on the specified color... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def apply_mask(rgb_img: np.ndarray, mask: np.ndarray, mask_color: str) -> np.ndarray:
"""
Apply a mask to an RGB image based on the specified color.
Args:
rgb_img (np.ndarray): A numpy array repr... |
magic_instruct_75k | 4,203 | Write a Python function to calculate the frequency of each unique word in a list of strings, ignoring case sensitivity and considering only alphanumeric characters. The function should return a dictionary where the keys are unique words and the values are their respective frequencies.
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, Dict
import re
def word_frequency(input_list: List[str]) -> Dict[str, int]:
"""
Calculate the frequency of each unique word in a list of strings, ignoring case sensitivity and considering only alphanume... |
magic_instruct_75k | 4,235 | Create a Python class `Wikidata` that represents a Wikidata instance. The class should have the following functionalities:
1. An `__init__` method to initialize the `name` attribute of the Wikidata instance.
2. A `__str__` method to return the name of the Wikidata instance.
3. A `wikidata_url` property to retrieve the ... | Here is the Python code to solve the given problem in the markdown block:
```python
class Wikidata:
def __init__(self, name):
"""
Initialize the Wikidata instance with a given name.
Args:
name (str): The name of the Wikidata instance.
"""
self.name = name
de... |
magic_instruct_75k | 4,250 | Write a Python function to calculate the imaginary part of a complex number. The function should handle both legacy and non-legacy modes and ensure that the input is of the correct type. The function should start with:
```python
def calculate_imaginary_part(x: complex) -> float:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_imaginary_part(x: complex) -> float:
"""
Calculate the imaginary part of a complex number.
Args:
x (complex): The complex number whose imaginary part is to be calculated.
Returns:
float: T... |
magic_instruct_75k | 4,289 | Write a Python function to simulate a hash table using separate chaining for collision resolution. The hash table should support key-value pairs, where the keys are of type `int` and the values are of type `str`. Implement the following functionalities for the hash table:
1. Insert a key-value pair into the hash table.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
class HashTable:
def __init__(self, size: int):
"""
Initialize the hash table with a given size.
Args:
size (int): The size of the hash table.
"""
... |
magic_instruct_75k | 4,297 | Write a Python function to simplify a given Unix-style file path. The function should take a string representing the file path and return the simplified version of the path. The rules for simplifying the path are as follows:
- The path starts with a '/' character.
- Any consecutive multiple slashes ('//') in the path s... | Here is the Python code to solve the given problem in the markdown block:
```python
def simplify_path(path: str) -> str:
"""
Simplifies a given Unix-style file path according to the specified rules.
Args:
path (str): The input path to be simplified.
Returns:
str: The simplified path.
... |
magic_instruct_75k | 4,303 | Write a Python function to transform a list of dictionaries, where each dictionary represents a material property. Each dictionary contains three key-value pairs: 'name' (the name of the property), 'units' (the units of the property), and 'data' (the actual data values). The transformation involves replacing each 'data... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def transform_data(input_data: List[Dict[str, any]]) -> List[Dict[str, any]]:
"""
Transforms the 'data' values in a list of dictionaries to their cumulative sums.
Args:
input_data (Lis... |
magic_instruct_75k | 4,314 | Write a Python function to construct an OAuth request data dictionary based on the provided OAuth code, redirect URI, and vendor. The vendor parameter should be one of 'doximity', 'google', or 'brand'. The function should validate the vendor parameter and raise a `ValueError` if the vendor is not one of the allowed val... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_oauth_request_data(code: str, redirect_uri: str, vendor: str) -> dict:
"""
Constructs OAuth request data.
Args:
code (str): The OAuth code.
redirect_uri (str): The redirect URI used to get the ... |
magic_instruct_75k | 4,331 | Write a Python function `extract_timesteps(files: List[str], nbSeries: int, iterations: List[int]) -> int` that processes a list of file names `files`, the number of series `nbSeries`, and a list of iterations `iterations` to be extracted. The function should validate the compatibility of the number of files and the it... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_timesteps(files: List[str], nbSeries: int, iterations: List[int]) -> int:
"""
Extracts a specified number of timesteps from a list of files and validates the compatibility of the number of fi... |
magic_instruct_75k | 4,348 | Write a Python function to calculate the final rating (rv_obtained) of a player based on their scores in a series of games and a given threshold value (rv). The final rating should be the average of the scores, but it should not be less than the threshold value. If the average score is less than the threshold, the fina... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_final_rating(scores: List[int], rv: int) -> int:
"""
Calculate the final rating of a player based on their scores and a threshold value.
Args:
scores (List[int]): A list of int... |
magic_instruct_75k | 4,368 | Write a Python function to determine whether a given directed graph contains a cycle. The graph is represented using an adjacency list, where each key-value pair represents a vertex and its outgoing edges. A cycle in a graph occurs when a sequence of edges exists that forms a closed loop, allowing traversal through the... | Here is the Python code to solve the given problem in the markdown block:
```python
def has_cycle(graph: dict) -> bool:
"""
Determines whether the given directed graph has a cycle.
Args:
graph: dict - An adjacency list representing the directed graph.
Returns:
bool - True if the graph contains... |
magic_instruct_75k | 4,373 | Write a Python function to implement a Caesar cipher for both encryption and decryption. The function should take three parameters:
- `text` (string): The input text to be encrypted or decrypted.
- `shift` (integer): The number of positions to shift the letters in the alphabet. A positive shift value indicates encrypti... | Here is the Python code to solve the given problem in the markdown block:
```python
def caesar_cipher(text: str, shift: int, mode: str) -> str:
"""
Encrypts or decrypts the given text using a Caesar cipher.
Args:
text (str): The input text to be encrypted or decrypted.
shift (int): The numb... |
magic_instruct_75k | 4,382 | Write a Python function to automate the build and packaging process for a software project into an RPM package. The function should perform the following steps:
1. Set up the environment by running the `setup_env` command.
2. Create a source tarball for the software using the `create_source_tarball` command.
3. Generat... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def build_rpm_package():
"""
Automates the build and packaging process for a software project into an RPM package.
This function performs the following steps:
1. Sets up the environment by running the... |
magic_instruct_75k | 4,402 | Write a Python function to link each pull request (PR) object to its corresponding commit SHA based on the order of the lists. If there are more PRs than commit SHAs or vice versa, the remaining PRs or commit SHAs should be linked to a placeholder string "N/A".
The PR object is represented as a dictionary with the fol... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def link_prs_and_shas(prs: List[Dict[str, str]], shas: List[str]) -> List[Tuple[str, str, int, str]]:
"""
Links each pull request (PR) object to its corresponding commit SHA based on the ord... |
magic_instruct_75k | 4,462 | Write a Python function to generate a sequence of random numbers and calculate the sum of all the generated numbers and count the quantity of numbers that are odd. The function should return a tuple containing the sum and the count of odd numbers.
The code should start with:
```python
import random
def generate_numbe... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_numbers(n: int) -> tuple:
"""
Generates a sequence of n random numbers between 1 and 100, calculates the sum of all the numbers,
and counts the quantity of numbers that are odd. Returns a tuple co... |
magic_instruct_75k | 4,475 | Write a Python function named `enforce_max_length` that enforces a maximum length constraint on a given argument. The function should take two parameters: `arg` (the argument to be validated) and `max_length` (the maximum allowed length for the argument). If the length of the `arg` exceeds the `max_length`, the functio... | Here is the Python code to solve the given problem in the markdown block:
```python
def enforce_max_length(arg: str, max_length: int) -> str:
"""
Enforces a maximum length constraint on a given argument.
Args:
arg (str): The argument to be validated.
max_length (int): The maximum allowed le... |
magic_instruct_75k | 4,477 | Write a Python function to parse a list of package dependencies and a license string, and return a dictionary containing the parsed information. The function should handle the input as described and ensure that the output dictionary is correctly formatted.
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, Dict
def parse_package_info(dependencies: List[str], license: str) -> Dict[str, List[str]]:
"""
Parses a list of package dependencies and a license string into a structured dictionary.
Args:
... |
magic_instruct_75k | 4,483 | Write a Python function to simulate the behavior of the given bash script. The function should check if a specific file named `release-after-hook.sh` exists in the current directory and execute it if it is found. If the file does not exist, the function should handle this case appropriately.
The code should start with... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
def execute_release_hook():
"""
Simulates the behavior of a bash script that checks for the existence of a file
named `release-after-hook.sh` and executes it if it exists.
Returns:
b... |
magic_instruct_75k | 4,484 | Write a Python function to generate a while loop with specific conditions. The function should take a list of conditions as strings and return a string representing the while loop code. The conditions will be simple boolean expressions using comparison operators (e.g., `<`, `>`, `==`, `!=`) and logical operators (e.g.,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_while_loop(conditions: List[str]) -> str:
"""
Generates a while loop code string from a list of conditions.
Args:
conditions (List[str]): A list of strings representing boolean ... |
magic_instruct_75k | 4,501 | Write a Python function to process two lists `fa` and `fb` and produce the same output as the given C++ code snippet. The function should return a string representing the output as described below.
The function should take two lists `fa` and `fb` as input and produce the same output as the code snippet. The output sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_arrays(fa: List[int], fb: List[int]) -> str:
"""
Process two lists `fa` and `fb` and return a string representing the output.
The function finds the intersection of `fa` and `fb`, sorts ... |
magic_instruct_75k | 4,502 | Write a Python function to process a list of file names and extract relevant information from each file name. The function should take a list of file names as input and return a dictionary containing specific information extracted from the file names.
The file names follow a specific pattern: they start with a name, f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def extract_file_info(file_list: List[str]) -> Dict[str, int]:
"""
Extracts relevant information from a list of file names and returns a dictionary
containing the name extracted from the file n... |
magic_instruct_75k | 4,526 | Write a Python function `append_or_initialize(li, x)` that takes a list `li` and a value `x` as input and returns the modified list based on the following conditions:
- If the list `li` is not empty, append the value `x` to the list.
- If the list `li` is empty, initialize a new list `ret` with the value `x`.
The func... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def append_or_initialize(li: List[Any], x: Any) -> List[Any]:
"""
Appends a value `x` to a list `li` if the list is not empty, or initializes a new list with the value `x` if the list is empty.
... |
magic_instruct_75k | 4,534 | Write a Python function to parse a dictionary representing a class's functions and their return types, and return a list of tuples where each tuple contains a function name and its corresponding return type. The dictionary keys are function names, and the values are their return types.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def parse_class_functions(class_dict: Dict[str, str]) -> List[Tuple[str, str]]:
"""
Parses a dictionary representing a class's functions and their return types,
and returns a list of tup... |
magic_instruct_75k | 4,541 | Write a Python function to simulate rolling two dice a specified number of times and calculate the frequency and percentage of occurrence for each possible sum (from 2 to 12). The function should return a dictionary containing the frequency and percentage of each sum.
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 Dict
import numpy as np
def simulate_dice_rolls(num_rolls: int) -> Dict[str, Dict[int, int]]:
"""
Simulate rolling two dice a specified number of times and calculate the frequency and percentage of occurrence... |
magic_instruct_75k | 4,595 | Write a Python function to process character ownership data for a gaming application. The function will take in a list of dictionaries, where each dictionary represents the ownership information for a character. Each dictionary will have the following keys:
- "user_id": an integer representing the user's ID
- "characte... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_character_ownership(ownership_list: List[Dict[str, int]]) -> Dict[int, int]:
"""
Counts the number of characters owned by each user based on the given ownership data.
Args:
o... |
magic_instruct_75k | 4,603 | Write a Python function to count the number of events in a list that have a specific short description. Each event is represented as a dictionary with various attributes, including the "event_short" attribute, which holds a string representing the short description of the event. The function should take in the list of ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_events_with_short_description(events: List[Dict[str, str]], short_description: str) -> int:
"""
Counts the number of events in a list that have a specific short description.
Args:
... |
magic_instruct_75k | 4,607 | Write a Python function `calculate_x(z)` that takes in an integer `z` and returns the value of `x` after the assignment operation `x = z + 1`. The function should handle any integer input and return the correct value of `x` based on the given assignment operation.
The code should start with:
```python
def calculate_x(... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_x(z: int) -> int:
"""
Calculate the value of `x` after the assignment operation `x = z + 1`.
Args:
z (int): The integer value to be used in the assignment operation.
Returns:
int: The valu... |
magic_instruct_75k | 4,614 | Write a Python function that sets the `output_file_prefix` and `stat_ops` based on the provided inputs. The function should follow these rules:
- If `output_file_prefix` is not `None`, set `output_file_prefix` to the provided value.
- If `output_file_prefix` is `None`, set `output_file_prefix` using the format: `'featu... | Here is the Python code to solve the given problem in the markdown block:
```python
def set_output_and_stat_ops(output_file_prefix, category, dependent_name, radius_type, stat_ops):
"""
Sets the output file prefix and statistical operations based on the provided inputs.
Args:
output_file_prefix (st... |
magic_instruct_75k | 4,616 | Write a Python function to calculate the power of a given positive real number `a` raised to the integer power `n` without using the standard power function available in programming languages. The function should handle both positive and negative integer values for `n`. The code should start with:
```python
def power(a... | Here is the Python code to solve the given problem in the markdown block:
```python
def power(a: float, n: int) -> float:
"""
Calculate the power of a given positive real number `a` raised to the integer power `n`.
Args:
a (float): The base number.
n (int): The exponent.
Returns:
... |
magic_instruct_75k | 4,628 | Write a Python function to find the longest common subsequence (LCS) of two given strings. The function should return the length of the LCS.
The code should start with:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
"""
Calculate the length of the longest common subsequence (LCS) of two given strings.
Args:
str1 (str): The first string.
... |
magic_instruct_75k | 4,655 | Write a Python function named `tupler` that takes a tuple of integers as input and returns a new tuple containing the original tuple's elements along with their respective indices. Each element in the new tuple should be a tuple where the first element is the index and the second element is the original value from the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def tupler(input_tuple: tuple) -> tuple:
"""
Returns a new tuple containing the original tuple's elements along with their respective indices.
Args:
input_tuple (tuple): A tuple of integers.
Returns:
tu... |
magic_instruct_75k | 4,658 | Write a Python function to process a ledger of financial transactions and return the total balance. The ledger is represented as a list of tuples, where each tuple contains the transaction amount and a flag indicating whether it's a credit (+) or debit (-) transaction. The function should calculate the total balance by... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def processledger(ledger: List[Tuple[int, str]]) -> int:
"""
Calculate the total balance from a ledger of financial transactions.
Args:
ledger (List[Tuple[int, str]]): A list of tuple... |
magic_instruct_75k | 4,679 | Write a Python function to simulate the behavior of a simplified shader program. The shader program takes two input variables `input0` and `input1`, and produces two output variables `output0` and `output1`. The operation of the shader program is described by the provided code snippet.
The function should take two inp... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulateShader(input0: float, input1: float) -> (float, float):
"""
Simulates the behavior of a simplified shader program.
The shader program takes two input variables `input0` and `input1`, and produces
two output ... |
magic_instruct_75k | 4,680 | Write a Python function to count the frequency of each unique SPDX license identifier in a given list. The function should return a dictionary where the keys are the unique identifiers and the values are the frequency of each identifier in the input list.
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, Dict
def count_license_identifiers(license_list: List[str]) -> Dict[str, int]:
"""
Counts the frequency of each unique SPDX license identifier in the given list.
Args:
license_list (List[st... |
magic_instruct_75k | 4,686 | Write a Python function to perform a depth-first search (DFS) traversal of a directed graph starting from a given vertex and return the order in which the vertices are visited. The graph is represented as an adjacency list, where the keys are the vertices and the values are lists of adjacent vertices. The starting vert... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def dfs_traversal(graph: Dict[str, List[str]], start_vertex: str) -> List[str]:
"""
Perform a depth-first search (DFS) traversal of a directed graph starting from a given vertex.
Args:
... |
magic_instruct_75k | 4,691 | Write a Python function to extract the GMT time when the forecast was received from an OpenWeatherMap (OWM) Weather API response. The API response is in JSON format and contains various weather-related data. The function should take the API response as input and return the GMT time when the forecast was received in the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import datetime
def extract_forecast_time(api_response: Dict) -> str:
"""
Extracts the GMT time when the forecast was received from an OpenWeatherMap API response.
Args:
api_response (dict):... |
magic_instruct_75k | 4,693 | Write a Python function to count the occurrences of each unique API category from a list of API endpoints. Each API endpoint is represented as a string in the format "category_endpoint", where "category" is the category of the API and "endpoint" is the specific endpoint within that category. The function should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_api_categories(api_endpoints: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique API category from a list of API endpoints.
Args:
api_endpoints (List[str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.