source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
773
Write a Python function to simulate the inter-process communication (IPC) using named pipes. The function should handle asynchronous reading from the named pipe and notify a callback object when a new connection is established. The function should start with: ```python from typing import Callable, Any def begin_read(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, Any class IpcManager: def __init__(self, pipe_handle: Any, read_buffer: bytearray, options: Any): self.m_pipeHandle = pipe_handle self.m_readBuffer = read_buffer self.m_options =...
magic_instruct_75k
786
Write a Python function to implement a simplified task scheduler. The scheduler should allow registering actions to be executed at specific times and then running all the actions that are due at the current time. The code should start with: ```python from typing import List, Dict def register_action(actions: List[Dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def register_action(actions: List[Dict[str, int]], action: str, time: int) -> None: """ Register an action to be executed at a specific time. Args: actions: A list of dictionaries wher...
magic_instruct_75k
787
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. You can only make one transaction (i.e., buy one and sell one share of the stock), and you must buy before you sell. If no profit can be made, return 0. The function should start with: ```pytho...
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 w...
magic_instruct_75k
792
Write a Python script to automate the backup and organization of files in a Linux environment. The script should perform the following tasks: 1. Recursively copy the contents of the `/usr/src/.jx3` directory to the `/root` directory. 2. Create a new directory named `jenkinsx3` within the `/root` directory and navigate ...
Here is the Python code to solve the given problem in the markdown block: ```python import os import shutil def backup_and_organize_files(): """ Automates the backup and organization of files in a Linux environment. This function performs the following tasks: 1. Recursively copies the contents of the ...
magic_instruct_75k
840
Write a Python function to perform beam search with a pruning mechanism based on the probability of characters in a vocabulary. The function should take in a list of characters and their corresponding probabilities, as well as a cutoff number for pruning. The pruning mechanism should only consider the top `cutoff_top_n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def beam_search_with_pruning(vocab_probabilities: List[Tuple[str, float]], cutoff_top_n: int) -> List[str]: """ Perform beam search with pruning based on the probability of characters in a vocabul...
magic_instruct_75k
859
Write a Python function to validate the input model name for a deep learning framework. The function should check if the provided model name matches a predefined set of supported model names. If the model name matches, the function should return `True`; otherwise, it should return `False`. The supported model names are...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_model_name(model_name: str) -> bool: """ Validates if the provided model name is one of the supported model names. Args: model_name (str): The model name to be validated. Returns: bool: Tru...
magic_instruct_75k
864
Write a Bash script to automate the process of signing a Cardano blockchain transaction using the `cardano-cli` command-line tool. The script should accept the following parameters: - `WORKDIR`: The directory where the necessary transaction files are stored. - `TTL`: The time-to-live for the transaction. - `MAGIC`: The...
Here is the Python code to solve the given problem in the markdown block: ```bash #!/bin/bash # Assign input parameters to variables WORKDIR=$1 TTL=$2 MAGIC=$3 UTXO_KEY_FILE=$4 # Define the transaction body file and the signed transaction file TX_BODY_FILE="$WORKDIR/tx.draft" SIGNED_TX_FILE="$WORKDIR/tx.signed" # Co...
magic_instruct_75k
865
Write a Python function to count the number of distinct elements in a given array. The array consists of integers within the range [-1,000,000, 1,000,000] and can have a length between 0 and 100,000. The function should return the count of distinct elements in the array. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_distinct_elements(A: List[int]) -> int: """ Count the number of distinct elements in the given array. Args: A (List[int]): The array of integers from which to count distinct elemen...
magic_instruct_75k
885
Write a Python function to filter error codes and their corresponding error messages based on the presence of a specific keyword in the error message. The function should take in a dictionary of error codes and messages and return a new dictionary with only the error codes and messages that contain the specified keywor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def filter_error_codes(error_dict: Dict[str, str], keyword: str) -> Dict[str, str]: """ Filters error codes and their corresponding error messages based on the presence of a specific keyword in the error...
magic_instruct_75k
902
Write a Python function to calculate the distribution of instances per class from a given list of class labels. The function should return the result as a dictionary where the keys are the unique class labels and the values are the number of instances belonging to each class. The function should handle cases with an em...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_class_distribution(classes: List[str]) -> Dict[str, int]: """ Calculate the distribution of instances per class from a given list of class labels. Args: classes (List[str...
magic_instruct_75k
903
Write a Python function to process a message body template and replace placeholders with actual values. The message body template is represented by a string containing placeholders in the format `{{$placeholderName}}`, where `placeholderName` is the name of the placeholder. Your function should take the template and a ...
Here is the Python code to solve the given problem in the markdown block: ```python def process_message_template(template: str, placeholder_values: dict) -> str: """ Processes a message body template by replacing placeholders with actual values. Args: template (str): The message body template conta...
magic_instruct_75k
927
Write a Python function to process a list of imported modules and return a dictionary containing the count of unique module names and the total count of all module names. The function should ignore any modules that are imported conditionally (e.g., within an if statement) and should consider only the top-level imports....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_imported_modules(imported_modules: List[str]) -> Dict[str, int]: """ Processes a list of imported modules and returns a dictionary containing the count of unique module names and the tota...
magic_instruct_75k
930
Write a Python function to perform a binary search on a sorted array of integers to find the index of a specific target value. If the target value is found, the function should return its index; otherwise, it should return -1. The function should be efficient and should handle edge cases such as an empty array or a tar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(arr: List[int], target: int) -> int: """ Perform a binary search on a sorted array to find the index of a target value. Args: arr (List[int]): A sorted list of integers. ...
magic_instruct_75k
945
Write a Python function to simulate a simple dice game. The game involves rolling a six-sided die multiple times and keeping track of the outcomes. The function should generate a sequence of random numbers representing the dice rolls and then calculate the frequency of each outcome. The function should perform the fol...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import random def simulate_dice_game() -> Dict[int, int]: """ Simulate a dice game where a six-sided die is rolled 1000 times and the frequency of each outcome is calculated. Returns: Dict[i...
magic_instruct_75k
962
Write a Python function to convert a given string of space-separated double values into a list of floats. The function should handle any potential parsing errors and ensure that the resulting list has the correct size. If the number of parsed float values does not match the expected size, the function should raise a `V...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def to_vector_nd(str_input: str, expected_size: int) -> List[float]: """ Converts a given string of space-separated double values into a list of floats. Args: str_input (str): The input stri...
magic_instruct_75k
974
Write a Python function to generate a Starlark code snippet for loading a repository using the `http_archive` function in Bazel. The function should take the name of the repository and its SHA256 checksum as inputs and return the corresponding Starlark code snippet as a string. The code snippet should include the `name...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_http_archive_snippet(name: str, sha256: str) -> str: """ Generates a Starlark code snippet for loading a repository using the http_archive function in Bazel. Args: name (str): The name of the repository...
magic_instruct_75k
981
Write a Python function to validate a message according to specific criteria. The function `validate_msg(msg)` should take a string `msg` as input and return `True` if the message meets the specified criteria, and `False` otherwise. The criteria for a valid message are as follows: 1. The message must contain at least 1...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_msg(msg: str) -> bool: """ Validate a message based on the following criteria: 1. The message must contain at least 10 characters. 2. The message must not exceed 100 characters. 3. The message...
magic_instruct_75k
982
Write a Python function to simulate daily inflow data for a hydrological model over a specified number of days. The function should use statistical parameters from a DataFrame to generate the inflow data. The DataFrame contains the mean inflow (`Mean`), standard deviation (`St dev`), and lag-1 correlation coefficient (...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np import math from typing import List def simulate_inflow(df, number_of_days: int) -> List[float]: """ Simulate daily inflow data for a hydrological model over a specified number of days. Args: df ...
magic_instruct_75k
989
Write a Python function to retrieve the corpus of tweets from the most active users on a social media platform. The function `get_corpus_of_most_active_users` takes an optional parameter `n_users` (default value is 5) representing the number of most active users whose tweets need to be included in the corpus. The funct...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def get_corpus_of_most_active_users(n_users: int = 5) -> List[str]: """ Retrieves the corpus of tweets from the most active users on a social media platform. Args: n_users (int, option...
magic_instruct_75k
997
Write a Python function to process a list of Python package names and return a tuple containing the sorted list of unique package names and the total count of unique package names. The function should handle any list of package names, including duplicates and an empty list. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def process_packages(package_list: List[str]) -> Tuple[List[str], int]: """ Processes a list of Python package names and returns a tuple containing the sorted list of unique package names and the ...
magic_instruct_75k
1,001
Write a Python function to find the highest score from a list of game scores. If the list is empty, the function should return 0. The function should be efficient and handle edge cases appropriately. The code should start with: ```python from typing import List def highest_score(scores: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def highest_score(scores: List[int]) -> int: """ Returns the highest score from a list of game scores. If the list is empty, returns 0. Args: scores (List[int]): A list of integers represent...
magic_instruct_75k
1,006
Write a Python function to calculate the total number of unique paths from the top-left corner to the bottom-right corner of a grid with dimensions `m x n`. The function should only consider paths that move either right or down. The code should start with: ```python from typing import List def unique_paths(m: int, n:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def unique_paths(m: int, n: int) -> int: """ Calculate the total number of unique paths from the top-left corner to the bottom-right corner of an m x n grid. The paths can only move right or down. ...
magic_instruct_75k
1,016
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 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 maxProfit(prices: List[int]) -> int: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def maxProfit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock at most once. Args: prices (List[int]): A list of integers repres...
magic_instruct_75k
1,040
Write a Python function to complete the feature extraction process for a music analysis tool. The function should take an incomplete dictionary `dic` as input and populate it with the correct values for the missing or incorrect features. The features to be extracted include: - beats_count - mood_acoustic - mood_party -...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def complete_feature_extraction(dic: Dict[str, str]) -> Dict[str, str]: """ Completes the feature extraction process for a music analysis tool by populating the missing or incorrect feature values in the...
magic_instruct_75k
1,043
Write a Python function to compare two lists of integers and generate a formatted string indicating the expected and actual outputs. The function should take two parameters: `expected_outs` and `actual_outs`, both of which are lists of integers. The function should return a string in the format "expected: [expected_out...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def compare_outputs(expected_outs: List[int], actual_outs: List[int]) -> str: """ Compares two lists of integers and generates a formatted string indicating the expected and actual outputs. Args: ...
magic_instruct_75k
1,063
Write a Python function to populate the lists in a given dictionary with labels based on predefined rules. Each key in the dictionary corresponds to a data set, and the value associated with each key is an empty list. The function should populate these lists with labels according to specific substring matches in the ke...
Here is the Python code to solve the given problem in the markdown block: ```python def populate_labels(original_dict: dict) -> dict: """ Populate the lists in the given dictionary with labels based on predefined rules. Args: original_dict (dict): A dictionary where each key corresponds to a data s...
magic_instruct_75k
1,081
Write a Python function to determine the highest score achieved up to and including a specific stage in a game. The scores are given as a list of integers, where each integer represents the score at a different stage. The function should return the highest score up to and including the specified stage. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def highest_score_at_stage(scores: List[int], stage: int) -> int: """ Determine the highest score achieved up to and including a specific stage in a game. Args: scores (List[int]): A non-emp...
magic_instruct_75k
1,083
Write a Python function to convert a given Roman numeral string into its corresponding integer value. The Roman numeral system uses seven different symbols: I, V, X, L, C, D, and M, which represent the values 1, 5, 10, 50, 100, 500, and 1000 respectively. The function should handle the special cases where a smaller val...
Here is the Python code to solve the given problem in the markdown block: ```python def roman_to_int(s: str) -> int: """ Converts a Roman numeral string to its corresponding integer value. Args: s (str): The Roman numeral string to be converted. Returns: int: The integer value correspo...
magic_instruct_75k
1,091
Write a Python function to retrieve the URLs for specific API endpoints related to configuring SSIDs (Service Set Identifiers) and obtaining the topology of access points from a given dictionary. The function should return a list of URLs for the 'ssids' and 'mr_topology' endpoints. If an endpoint is not present in the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def retrieve_endpoints(endpoints: Dict[str, str]) -> List[str]: """ Retrieves the URLs for 'ssids' and 'mr_topology' endpoints from the given dictionary. Args: endpoints (Dict[str, str...
magic_instruct_75k
1,103
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given an array of integers representing stock prices on consecutive days. If it is not possible to make any profit, return 0. The function should start with: ```python from typing import List def m...
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
1,107
Write a Python function to format a dictionary of drawing parameters into a readable string. The dictionary contains various types of parameters such as tuples, lists, and integers. The function should handle these types and return a formatted string where each parameter is displayed with its name and value in a readab...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def format_draw_params(draw_params: Dict[str, Any]) -> str: """ Formats a dictionary of drawing parameters into a readable string. Args: draw_params (Dict[str, Any]): A dictionary conta...
magic_instruct_75k
1,114
Write a Python script to automate the formatting of C++ source files using Docker and ClangFormat. The script should: 1. Automatically locate all C++ source files (with extensions `.cpp` and `.h`) within the `src` directory and its subdirectories. 2. Apply the ClangFormat tool to format each located source file using t...
Here is the Python code to solve the given problem in the markdown block: ```python import os import subprocess def format_cpp_files(root_dir: str): """ Automates the formatting of C++ source files using Docker and ClangFormat. Args: root_dir (str): The root directory containing the 'src' director...
magic_instruct_75k
1,121
Write a Python function to round a given floating-point number up to the next integer. The function should take a floating-point number as input and return the next integer greater than or equal to the input number. The function should handle both positive and negative floating-point numbers. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python import math def round_up_to_next_integer(number: float) -> int: """ Rounds a given floating-point number up to the next integer. Args: number (float): The floating-point number to be rounded up. Returns: ...
magic_instruct_75k
1,125
Write a Python function to replace all negative numbers in a given list of integers with their absolute values. The function should return a new list with the same elements as the input list, but with all negative numbers replaced by their absolute values. The input list will not be empty and will only contain integers...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def replace_negatives(results: List[int]) -> List[int]: """ Replace all negative numbers in the input list with their absolute values. Args: results (List[int]): A list of integers where neg...
magic_instruct_75k
1,139
Write a Python function to process a given string according to a set of predefined rules. The function should perform the following operations on the input string: 1. Remove any leading and trailing whitespace. 2. Convert the entire string to lowercase. 3. Replace every occurrence of the word "apple" with "orange". 4. ...
Here is the Python code to solve the given problem in the markdown block: ```python import re def process_text(input_string: str) -> str: """ Process the input string according to the following rules: 1. Remove any leading and trailing whitespace. 2. Convert the string to lowercase. 3. Replace ever...
magic_instruct_75k
1,168
Write a Python function to calculate the average value of elements in each non-empty chunk of a given sequence of chunks. Each chunk is represented as a list of integers. The function should return a list of average values for each non-empty chunk. If a chunk is empty, it should be ignored in the calculation of the ave...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def average_chunk_values(chunk_seq: List[List[int]]) -> List[float]: """ Calculate the average value of elements in each non-empty chunk of a given sequence of chunks. Args: chunk_seq (List[...
magic_instruct_75k
1,180
Write a Python function to remove specific image files from a list based on their sizes. The image file names are in the format `"{size}.png"` where `{size}` is the size of the image. The function should take in a list of image file names and a list of sizes to remove. It should return a new list with all the image fil...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_images(image_list: List[str], sizes_to_remove: List[int]) -> List[str]: """ Removes image file names from the input list that match any of the sizes specified in the removal list. Args: ...
magic_instruct_75k
1,185
Write a Python function to generate a formatted string representing a function signature based on a list of tuples. Each tuple contains a parameter name, its type, and a boolean indicating whether the parameter is optional. The function should return a string where each line represents a parameter in the format: ``` :p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_function_signature(parameters: List[Tuple[str, str, bool]]) -> str: """ Generates a formatted string representing a function signature based on a list of tuples. Args: pa...
magic_instruct_75k
1,188
Write a Python function to extract the content type from a given long description string. The content type is denoted by the string following the "long_description_content_type=" substring and is enclosed in single quotes. The function should return the extracted content type as a string. If the content type is not fou...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_content_type(long_description: str) -> str: """ Extracts the content type from a given long description string. The content type is denoted by the string following the "long_description_content_type=" substring ...
magic_instruct_75k
1,201
Write a Python function to count the total number of parameters for each operation in a given dictionary. The input dictionary contains operation names as keys and corresponding dictionaries of parameters as values. Each parameter dictionary contains parameter names as keys and the number of parameters as values. The f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_parameters(input_dict: Dict[str, Dict[str, int]]) -> Dict[str, int]: """ Counts the total number of parameters for each operation in the given dictionary. Args: input_dict (Dict[st...
magic_instruct_75k
1,206
Write a Python function to complete the `dst` array based on the given `src` array and additional transformation parameters for perspective transformation. The `src` array contains the coordinates of the four corners of a region of interest in the original image, and the `dst` array needs to be filled with the correspo...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def complete_dst_array(perspective_params: dict) -> np.ndarray: """ Completes the destination array (`dst`) based on the given source array (`src`) and additional transformation parameters. Args: ...
magic_instruct_75k
1,221
Write a Python function to process a list of company IDs and return information about those companies. The function should take a list of company IDs as input and return a list of dictionaries containing company information. Each dictionary should include the company's ID and title. If the input list is empty or None, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def get_companies_info(company_ids: List[int]) -> List[Dict[str, Union[int, str]]]: """ Processes a list of company IDs and returns a list of dictionaries containing company information. ...
magic_instruct_75k
1,224
Write a Python function `extended_calculate` that takes a string input representing a mathematical expression and returns the result of the calculation. The function should support basic arithmetic operations (addition, subtraction, multiplication, division) as well as two new operations: modulus and square root. The m...
Here is the Python code to solve the given problem in the markdown block: ```python def extended_calculate(expression: str) -> float: """ Calculate the result of a mathematical expression that includes basic arithmetic operations (addition, subtraction, multiplication, division) as well as modulus and squar...
magic_instruct_75k
1,228
Write a Python function to count the number of set bits (binary 1s) for each number from 0 to a given positive integer `num`, inclusive. The function should return a list where each element at index `i` represents the count of set bits in the binary representation of `i`. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_set_bits(num: int) -> List[int]: """ Count the number of set bits (binary 1s) for each number from 0 to `num`, inclusive. Args: num (int): The positive integer up to which set bits...
magic_instruct_75k
1,238
Write a Python function to calculate the total cost of all items in a given list of prices. The function should be named `calculate_total_cost` and should take a single parameter: - `prices`: a list of integers representing the prices of items in the store. The list will have at least one element and at most 1000 eleme...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_total_cost(prices: List[int]) -> int: """ Calculate the total cost of all items in the given list of prices. Args: prices (List[int]): A list of integers representing the price...
magic_instruct_75k
1,257
Create a Python class `AnimationSystem` that manages and displays animations using the provided `Animation` and `Stage` classes. The `AnimationSystem` class should have the following functionalities: 1. A method `add_animation(anim: Animation, anim_name: str)` that adds an animation to the system with a given name. 2. ...
Here is the Python code to solve the given problem in the markdown block: ```python class Animation: def play(self): """Play the animation.""" pass class Stage: def add_child(self, anim: Animation): """Add the animation to the stage.""" pass class AnimationSystem: def __ini...
magic_instruct_75k
1,260
Write a Python function to generate a command-line string from a list of configuration options. Each configuration option is represented as a tuple containing the option name and its value. The command-line string should be constructed by concatenating the option names and values in the format `--option value`, separat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_command_line(config_list: List[Tuple[str, str]]) -> str: """ Generates a command-line string from a list of configuration options. Args: config_list (List[Tuple[str, str]...
magic_instruct_75k
1,263
Write a Python function to extract the position of the first character in a given message string and store it in a variable named `pose`. The function should return the value of `pose`. The code should start with: ```python def extractPosition(msg: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def extractPosition(msg: str) -> int: """ Extracts the position of the first character in the given message string and returns it. Args: msg (str): The message string from which to extract the position of the first ...
magic_instruct_75k
1,273
Write a Python function to calculate the number of days between two given dates, inclusive of both the start date and the end date. The function should take two date strings in the format "YYYY-MM-DD" as input and return the number of days between the two dates. The code should start with: ```python from datetime impo...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def calculate_days_between_dates(start_date: str, end_date: str) -> int: """ Calculate the number of days between two given dates, inclusive of both the start date and the end date. Args: ...
magic_instruct_75k
1,296
Write a Python function to extract all unique URLs from a given HTML document. The URLs can appear in various HTML elements such as anchor tags (`<a>`), image tags (`<img>`), script tags (`<script>`), and any other relevant tags. The function should handle both absolute and relative URLs. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def extract_urls(html: str) -> List[str]: """ Extracts all unique URLs from a given HTML document. Args: html (str): The HTML document from which to extract URLs. Returns: ...
magic_instruct_75k
1,315
Write a Python function `manipulate_string(input_string)` that performs the following operations on the input string and returns the modified string: 1. If the input string contains the substring "app_name", it should be replaced with "freenit". 2. If the input string ends with the substring "_name", the function shoul...
Here is the Python code to solve the given problem in the markdown block: ```python def manipulate_string(input_string: str) -> str: """ Manipulates the input string based on the following rules: 1. Replaces all occurrences of the substring "app_name" with "freenit". 2. Removes the suffix "_name" if the...
magic_instruct_75k
1,316
Write a Python function to count the occurrences of each unique class name in a given list of class names. The function should return a dictionary where the keys are the unique class names and the values are the counts of each class name. If the input list is empty, the function should return an empty dictionary. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_classes(classes: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique class name in the given list. Args: classes (List[str]): A list of class names. ...
magic_instruct_75k
1,317
Create a Python function to log events with metadata and print them. The function should capture metadata about log events, such as the log level, tag, file, function, and line number where the log event occurred. The function should start with: ```python from typing import List, Optional from enum import Enum import i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional from enum import Enum import inspect class LogLevel(Enum): DEBUG = "DEBUG" INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" # List to store log events log_events: List[dict] = [] def...
magic_instruct_75k
1,334
Write a Python function to generate Django migration code for adding a new field to a specified model. The function should take the model name, the new field name, the field type, and whether the field can be null as input, and return the migration code as a string. The migration code should follow Django migration con...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_migration_code(model_name: str, field_name: str, field_type: str, nullable: bool) -> str: """ Generates Django migration code for adding a new field to a specified model. Args: model_name (str): The nam...
magic_instruct_75k
1,345
Write a Python function to process a list of card data and extract specific information from it. Each card is represented as a dictionary with various attributes. The function should extract and format specific details from the card data and return a list of formatted strings. The specific details to be extracted and f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_card_data(cards: List[Dict]) -> List[str]: """ Processes a list of card data and extracts specific information from it. Args: cards (List[Dict]): A list of card dictionarie...
magic_instruct_75k
1,359
Write a Python function to filter a list of social media user profiles based on specific criteria. Each user profile is represented as a dictionary with keys: "full_name", "verified", "location", and "media_result". The function should return a new list containing only the profiles that meet the following conditions: 1...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_profiles(profiles: List[Dict]) -> List[Dict]: """ Filters a list of social media user profiles based on specific criteria. Args: profiles (List[Dict]): A list of dictionarie...
magic_instruct_75k
1,378
Write a Python function to check if a given list of integers is sorted in non-decreasing order. The function should return `True` if the list is sorted, and `False` otherwise. The code should start with: ```python from typing import List def is_sorted(arr: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_sorted(arr: List[int]) -> bool: """ Check if the given list of integers is sorted in non-decreasing order. Args: arr (List[int]): The list of integers to check. Returns: ...
magic_instruct_75k
1,381
Write a Python function to automate the rebuilding of the Realm package for a specific version of Electron. The function should: 1. Extract the version of Electron being used by querying the `package.json` file of the Electron package. 2. Change the directory to the `node_modules/realm` directory. 3. Set the `HOME` env...
Here is the Python code to solve the given problem in the markdown block: ```python import json import os import subprocess def rebuild_realm_for_electron(electron_package_path: str, realm_package_path: str) -> None: """ Automates the rebuilding of the Realm package for a specific version of Electron. Arg...
magic_instruct_75k
1,388
Write a Python function to implement a command-line autocomplete feature for a custom PHP artisan command-line tool. The function should take a partial command entered by the user and return a list of possible completions based on predefined aliases and commands. The function should consider both the defined completion...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def autocomplete(partial_command: str) -> List[str]: """ Returns a list of possible completions for a given partial command based on predefined aliases and commands. Args: partial_command (s...
magic_instruct_75k
1,401
Write a Python function to process a D-Bus signal and extract specific information from it. The D-Bus signal is represented as a tuple where the first element is the signal name, and the remaining elements are the signal arguments. The function should extract the interface name and the last part of the path from the si...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def process_dbus_signal(signal: Tuple) -> Tuple[str, str]: """ Processes a D-Bus signal and extracts the interface name and the last part of the path. Args: signal (Tuple): A tuple represen...
magic_instruct_75k
1,411
Write a Python function to parse command-line arguments and generate a corresponding configuration dictionary for an image processing tool. The function should handle the following command-line arguments: - `--dataset`: Specifies the dataset to be used. If not provided, the default value should be 'cifar10'. - `--input...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def parse_command_line_args(args: List[str]) -> Dict[str, Union[str, int]]: """ Parses command-line arguments and generates a configuration dictionary for an image processing tool. Args...
magic_instruct_75k
1,421
Write a Python function to manage the creation of a deep link directory within the user's home directory. The function should check if a directory with a specific name exists and, if not, create it. The function should return a status code indicating whether the directory was successfully created or if it already exist...
Here is the Python code to solve the given problem in the markdown block: ```python import os def should_it_make_deep_link_directory(directory_name: str) -> int: """ Checks if a directory with the given name exists in the user's home directory. If it does not exist, creates the directory and returns 0. ...
magic_instruct_75k
1,426
Write a Python function to determine if a given integer `n` is a prime number. The function should return `True` if `n` is a prime number, and `False` otherwise. The function should handle edge cases such as negative numbers, 0, and 1, which are not prime numbers. The code should start with: ```python def is_prime(n: ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """ Determines if a given integer `n` is a prime number. Args: n (int): The integer to check for primality. Returns: bool: True if `n` is a prime number, False otherwise. ...
magic_instruct_75k
1,437
Write a Python function `process_job_data` that processes job data based on a specified strategy. The function should take in five arguments: `system`, `suffix`, `job`, `pn`, and `strategy`. The `strategy` argument can be either "naive" or "mh". Depending on the strategy, the function should call the appropriate proces...
Here is the Python code to solve the given problem in the markdown block: ```python def process_job_data(system, suffix, job, pn, strategy): """ Processes job data based on the specified strategy. Args: system (str): The system identifier. suffix (int): The suffix number. job (str):...
magic_instruct_75k
1,458
Write a Python function to apply a scaling transformation to an input image using a specified scaling factor. The function should utilize the Python Imaging Library (PIL) and NumPy to perform the transformation. The function should take a PIL Image object and a float representing the scaling factor as inputs, and retur...
Here is the Python code to solve the given problem in the markdown block: ```python from PIL import Image import numpy as np def apply_scaling_transformation(input_image: Image.Image, scaling_factor: float) -> Image.Image: """ Applies a scaling transformation to the input image using the specified scaling fact...
magic_instruct_75k
1,462
Write a Python function to parse a list of database migration operations and extract the names of the models being created. Each migration operation is represented as a dictionary containing the operation type and relevant details. The function should identify all the "CreateModel" operations and extract the names of t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def extract_created_models(operations: List[Dict]) -> List[str]: """ Extracts the names of models being created from a list of database migration operations. Args: operations (List[Dic...
magic_instruct_75k
1,476
Create a Python function that implements a `lazyproperty` decorator. This decorator should allow a method to be called lazily, meaning the method is only called once and its result is cached for subsequent calls. The cached result should be stored as an attribute of the instance using the method's name prefixed with do...
Here is the Python code to solve the given problem in the markdown block: ```python def lazyproperty(fn): """ A decorator that converts a method into a lazy property. The method is only called once and its result is cached for subsequent accesses. Args: fn (function): The method to be converted int...
magic_instruct_75k
1,490
Write a Python function `generate_usernames` that takes a base string `base` and a list of integers `numbers` as input. The function should return a list of usernames generated by appending each integer to the base name. The integer should be appended as a string, preserving its sign (negative, zero, or positive) witho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_usernames(base: str, numbers: List[int]) -> List[str]: """ Generates a list of usernames by appending each integer from the numbers list to the base string. Args: base (str): Th...
magic_instruct_75k
1,495
Write a Python function to process a list of file names and perform specific actions based on the file type. If a file has a ".csv" extension, it should be skipped, and the function should move on to the next file. For all other file types, the function should print "Processing <filename>" where `<filename>` is the act...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_files(file_names: List[str]) -> None: """ Processes a list of file names and performs specific actions based on the file type. Args: file_names (List[str]): A list of file names ...
magic_instruct_75k
1,503
Write a Python function `processIdentifiers` that processes a list of identifiers and their corresponding labels. The function should handle various cases, including empty identifiers and missing labels. Specifically, the function should: 1. Store the identifier-label pair if the identifier is not empty and the corresp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def processIdentifiers(identifiers: List[str], labels: List[str]) -> Dict[str, str]: """ Processes a list of identifiers and their corresponding labels, handling empty identifiers and missing label...
magic_instruct_75k
1,521
Write a Python function to determine the highest official version number from a list of version tags. The version tags follow the format "x.y.z" where x, y, and z are integers representing the major, minor, and patch versions respectively. The function should return the highest official version number in the format "x....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def determine_highest_version(tag_list: List[str]) -> str: """ Determine the highest official version number from a list of version tags. Args: tag_list (List[str]): List of version tags in ...
magic_instruct_75k
1,522
Write a Python function to parse and analyze a dataset containing information about public holidays in different locales. The function should take the dataset and a target locale as input and return a list of holidays observed in that locale, sorted by date in ascending order. The dataset is a list of dictionaries, ea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def find_holidays_by_locale(dataset: List[Dict[str, str]], target_locale: str) -> List[Dict[str, str]]: """ Returns a list of holidays observed in the specified locale, sorted by date in ascending ...
magic_instruct_75k
1,525
Write a Python function to calculate the row and column positions of a given index within a grid based on the provided axes and maximum number of columns. The function should handle both single integer and numpy array inputs for the axes. The code should start with: ```python import numpy as np def calculate_position(...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_position(idx: int, axs: int or np.ndarray, max_columns: int) -> tuple: """ Calculate the row and column positions of a given index within a grid based on the provided axes and maximum number of ...
magic_instruct_75k
1,556
Write a Python function to process a list of migration operations and generate SQL statements for both the forward and reverse migrations. Each migration operation is represented as a dictionary with keys "forward_sql" and "reverse_sql". The function should produce two lists of SQL statements: one for the forward migra...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_migration_sql(operations: List[Dict[str, str]]) -> (List[str], List[str]): """ Generates SQL statements for both forward and reverse migrations from a list of migration operations. ...
magic_instruct_75k
1,605
Write a Python function to validate a user's information based on the given criteria. The function should check if the `username` is at least 3 characters long and if the `email` is a valid email format. The function should return a dictionary with a success message if the input is valid, or an error message if the inp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import re def validate_user(user: Dict[str, str]) -> Dict[str, str]: """ Validates the user's information based on the given criteria. Args: user (Dict[str, str]): A dictionary containing th...
magic_instruct_75k
1,636
Write a Python function to determine whether a given city name starts with the word "Santo" in a case-insensitive manner. The function should take a string representing the city name as input and return a boolean value indicating whether the city name starts with "Santo". The code should start with: ```python def star...
Here is the Python code to solve the given problem in the markdown block: ```python def starts_with_santo(city_name: str) -> bool: """ Determines whether the given city name starts with the word "Santo" in a case-insensitive manner. Args: city_name (str): The name of the city to check. Returns...
magic_instruct_75k
1,655
Write a Python function to process a list of icon resources and extract specific information from each entry. Each entry in the list is represented as a tuple containing two elements: a numerical identifier and a string representing the icon file name. The function should extract the numerical identifier and the file n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def process_icon_resources(icon_resources: List[Tuple[int, str]]) -> Dict[int, str]: """ Processes a list of icon resources and extracts the numerical identifier and file name from each entr...
magic_instruct_75k
1,656
Write a Python function `generate_upgrade_commands` that takes a list of OAR package names and a target version as input and returns a list of `apt-get` commands to upgrade each package to the specified version. Each command should be formatted as `sudo apt-get install --only-upgrade <package_name>=<target_version> -y`...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_upgrade_commands(package_names: List[str], target_version: str) -> List[str]: """ Generates a list of `apt-get` commands to upgrade OAR packages to a specified version. Args: pa...
magic_instruct_75k
1,676
Write a Python function `perform_operation_with_port` that takes a fixture `open_port` as an argument, retrieves an open port number, and then performs a specific operation using the obtained port number. The function should return a string indicating the operation performed along with the open port number. The `open_p...
Here is the Python code to solve the given problem in the markdown block: ```python def perform_operation_with_port(open_port): """ Perform a specific operation using an open port number obtained from the `open_port` fixture. Args: open_port: A fixture that returns an available port number. Re...
magic_instruct_75k
1,682
Write a Python function to process a series of instructions and perform specific arithmetic operations on a running total. The function should take a list of instructions as input, where each instruction is a string consisting of a single letter command followed by a space and a number. The commands can be one of the f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_instructions(instructions: List[str]) -> float: """ Process a series of arithmetic instructions and return the final running total. Args: instructions (List[str]): A list of inst...
magic_instruct_75k
1,709
Write a Python function to calculate the greatest common divisor (GCD) of two given integers using the Euclidean algorithm. The Euclidean algorithm is based on the principle that the GCD of two numbers does not change if the larger number is replaced by its difference with the smaller number. This process is repeated u...
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(A: int, B: int) -> int: """ Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Args: A (int): The first integer. B (int): The second integer. Returns: ...
magic_instruct_75k
1,728
Write a Python function to calculate the average grade for each student from a given dataset. The dataset is a list of tuples, where each tuple contains the student's name and their corresponding grades in various subjects. The function should return a dictionary where the keys are the student names and the values are ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def calculate_average_grades(dataset: List[Tuple[str, List[int]]]) -> Dict[str, int]: """ Calculate the average grade for each student from a given dataset. Args: dataset (List[...
magic_instruct_75k
1,745
Create a Python class to manage a collection of triples. Each triple consists of three integers. The class should provide methods to retrieve the ID of the collection and the number of triples it contains. The class should start with: ```python from typing import List, Tuple class TripleCollection: def __init__(s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple class TripleCollection: """ A class to manage a collection of triples. Each triple consists of three integers. Attributes: _collection_id (str): The ID of the collection. _tri...
magic_instruct_75k
1,752
Write a Python function to modify the theme of a Streamlit card element according to the provided theme settings. The function should take two parameters: 1. `theme_settings` (dict): A dictionary containing the new theme settings with keys 'bgcolor', 'title_color', 'content_color', 'progress_color', 'icon_color', and '...
Here is the Python code to solve the given problem in the markdown block: ```python def modify_streamlit_theme(theme_settings: dict, card_element: dict) -> None: """ Modifies the theme of a Streamlit card element according to the provided theme settings. Args: theme_settings (dict): A dictionary co...
magic_instruct_75k
1,759
Write a Python function to find the maximum sum of a contiguous subarray within a given array of integers. The function should efficiently compute the maximum sum using an optimal approach. The code should start with: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: """ Find the maximum sum of a contiguous subarray within the given array of integers. Args: nums (List[int]): The array of integers from which t...
magic_instruct_75k
1,796
Write a Python function to automate the build process for a web application. The build process involves running the commands `yarn && yarn build` in the current directory, followed by navigating to the `../node-server/` directory and running `yarn` there. The function should handle potential errors and ensure that the ...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import os def automate_build_process(): """ Automates the build process for a web application. The process involves running the commands `yarn && yarn build` in the current directory, followed by navi...
magic_instruct_75k
1,801
Write a Python decorator `@print_calls` that prints the name of the decorated function and its arguments when the function is called. The decorator should then execute the decorated function and return its result. The code should start with: ```python def print_calls(func): ```
Here is the Python code to solve the given problem in the markdown block: ```python def print_calls(func): """ A decorator that prints the name of the decorated function and its arguments when the function is called. It then executes the function and returns its result. Args: func (function): T...
magic_instruct_75k
1,814
Write a Python function to implement a custom callback for a machine learning model training process. The callback should monitor the performance of the model during training and save the model's weights to a file when certain conditions are met. The function should handle the logic for printing progress information ba...
Here is the Python code to solve the given problem in the markdown block: ```python def custom_callback(verbose: int, monitor: str, best: float, current: float, filepath: str, save_weights_only: bool, model) -> None: """ Custom callback for monitoring the performance of a machine learning model during training ...
magic_instruct_75k
1,841
Write a Python function to count the number of unique header file names from a list of included header files. The function should ignore any file paths and only consider the base file names for uniqueness. The input is a list of strings representing the included header files. The function should return the count of uni...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_header_files(included_files: List[str]) -> int: """ Counts the number of unique header file names from a list of included header files. Args: included_files (List[str]): A l...
magic_instruct_75k
1,842
Write a Python function to transform an old column name to a new column name based on a given mapping. The mapping is provided as a list of tuples, where each tuple contains a list of old column names and the corresponding new column name. If the old column name is not found in the mapping, the function should return "...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def transform_column_name(mapping: List[Tuple[List[str], str]], old_column_name: str) -> str: """ Transforms an old column name to a new column name based on the given mapping. Args: ...
magic_instruct_75k
1,845
Write a Python function `process_arguments` that processes a list of strings, where each string represents a command or a key-value pair. The function should support the following commands: 1. `add`: Add a new key-value pair to the dictionary. If the key already exists, update its value. 2. `remove`: Remove the specifi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_arguments(args: List[str]) -> Dict[str, str]: """ Processes a list of strings representing commands and key-value pairs, and returns the resulting dictionary. Args: args (L...
magic_instruct_75k
1,857
Write a Python function to process input parameters for a design of experiments (DOE) framework. The function should handle two input parameters: `doe_size` and `obj_wgt`. The `doe_size` parameter represents the size of the design of experiments to be used, while the `obj_wgt` parameter can be a single float or an iter...
Here is the Python code to solve the given problem in the markdown block: ```python def process_doe_params(doe_size=10, obj_wgt=None): """ Processes input parameters for a design of experiments (DOE) framework. Args: doe_size (int, optional): The size of the design of experiments. Defaults to 10. ...
magic_instruct_75k
1,866
Write a Python function to extract specific information from a README file that describes a Python package. The README file contains a long description of the package and a list of requirements. Your goal is to extract the version number of the package, the list of requirements, and the author's email address from the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def extract_package_info(REQUIREMENTS: List[str], LONG_DESCRIPTION: str) -> Dict[str, str]: """ Extracts the version number, list of requirements, and author's email address from a README...
magic_instruct_75k
1,872
Write a Python function to determine if a given string is a valid PHP closing tag. A valid PHP closing tag is denoted by `?>` and must not be preceded by any characters except whitespace. The function should return `True` if the input string is a valid PHP closing tag, and `False` otherwise. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_php_closing_tag(s: str) -> bool: """ Determines if the given string is a valid PHP closing tag. A valid PHP closing tag is denoted by `?>` and must not be preceded by any characters except whitespace. Args...
magic_instruct_75k
1,893
Write a Python function to reverse the sign of each integer in a given list. If the integer is positive, it should be changed to negative, and vice versa. If the integer is zero, it should remain unchanged. The function should return a new list with the modified integers. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_sign(nums: List[int]) -> List[int]: """ Reverses the sign of each integer in the given list. Args: nums (List[int]): A list of integers whose signs need to be reversed. Retu...
magic_instruct_75k
1,902
Write a Python function to find all possible split locations within a given construction sequence. The construction is represented as a sequence of elements, and the split locations are the indices at which the construction can be divided into two separate parts. The function should return a list of all possible split ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def split_locations(construction: List, start: Optional[int] = None, stop: Optional[int] = None) -> List[int]: """ Return all possible split-locations between start and end. Start and end will ...
magic_instruct_75k
1,922
Write a Python function to find the numerical value of a given cryptocurrency symbol from a list of cryptocurrency symbols and their corresponding numerical values. If the symbol is not found in the list, the function should return -1. The list of cryptocurrency symbols and their numerical values is represented as a t...
Here is the Python code to solve the given problem in the markdown block: ```python def find_crypto_value(crypto_list: tuple, symbol: str) -> int: """ Find the numerical value of a given cryptocurrency symbol from a list of cryptocurrency symbols and their corresponding numerical values. Args: cryp...
magic_instruct_75k
1,950
Write a Python function to create a list of dictionaries from a given list of file paths and a document hashtag. Each dictionary should contain the file path and a hashtag that combines the document hashtag and the file's index in a specific format. The function should start with: ```python from typing import List, Di...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def get_list_dict(list_file_path_zip: List[str], document_hashtag: str) -> List[Dict[str, str]]: """ Creates a list of dictionaries from a list of file paths and a document hashtag. Each dicti...
magic_instruct_75k
1,953
Write a Python function to process a list of financial transactions and determine the final balance of a financial account. Each transaction is represented as a string where the first word indicates the type of transaction ('deposit' or 'withdraw') and the second word is the amount. The function should correctly update...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_transactions(transactions: List[str]) -> int: """ Processes a list of financial transactions and returns the final balance. Each transaction is a string where the first word indicates th...
magic_instruct_75k
2,029
Write a Python function to extract the author's name and email from a given dictionary representing metadata for a software package. The dictionary will always contain the keys "author" and "author_email", with corresponding values representing the author's name and email address. The function should return these value...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_author_info(metadata: dict) -> tuple: """ Extracts the author's name and email from a given metadata dictionary. Args: metadata (dict): A dictionary containing metadata for a software package. ...