source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 2,030 | Write a Python function `chatbot_response` that simulates a conversation between a user and a chatbot. The chatbot's response is determined by the value of a global variable `helvar`. The chatbot's response rules are as follows:
- If the value of `helvar` is less than or equal to 2, the chatbot responds with "I'm fine ... | Here is the Python code to solve the given problem in the markdown block:
```python
def chatbot_response(helvar: int) -> str:
"""
Simulates a chatbot's response based on the value of `helvar`.
Args:
helvar (int): The current value of the global variable `helvar`.
Returns:
str: The chat... |
magic_instruct_75k | 2,053 | Write a Python function to determine the next process to execute in a scheduling algorithm for a set of processes. The processes are represented by their names and corresponding burst times, given in a dictionary where the keys are the process names and the values are tuples of the form (arrival time, burst time). The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
def next_process_to_execute(processes: Dict[str, Tuple[int, int]]) -> str:
"""
Determine the next process to execute based on the scheduling algorithm.
Args:
processes (Dict[str, Tupl... |
magic_instruct_75k | 2,055 | Write a Python function to determine the frequency of each word in a given text, ignoring punctuation and case, and excluding common stop words. The function should return a dictionary where the keys are the unique words in the text and the values are the frequencies of those words.
The code should start with:
```pyth... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def wordFrequency(text: str, stopWords: List[str]) -> Dict[str, int]:
"""
Calculate the frequency of each word in the given text, ignoring punctuation and case, and excluding common stop ... |
magic_instruct_75k | 2,062 | Write a Python function to count the occurrences of each unique string in a given list of strings. The function should return a dictionary where the keys are the unique strings and the values are the counts of their occurrences in the list.
The code should start with:
```python
from typing import List, Dict
def count... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_string_occurrences(strings: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique string in the given list of strings.
Args:
strings (List[str]): A list of ... |
magic_instruct_75k | 2,092 | Write a Python function to convert an integer `num` (1 <= num <= 3999) into its Roman numeral representation. The function should use a predefined list of integers `nums` representing the values of Roman numerals in descending order and a corresponding list of strings `romans` representing the Roman numeral symbols. Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def int_to_roman(num: int, nums: List[int], romans: List[str]) -> str:
"""
Converts an integer to its Roman numeral representation using predefined lists of values and symbols.
Args:
num (in... |
magic_instruct_75k | 2,118 | Write a Python function to process a list of comments based on a given condition. The function should take a boolean value `answer2` and a list of strings `comments`. If `answer2` is `True`, the function should set the `is_correct` variable to `True`. If `answer2` is `False`, the function should set `is_correct` to `Fa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def commentizer(answer2: bool, comments: List[str]) -> Tuple[List[str], bool]:
"""
Process a list of comments based on a given condition.
Args:
answer2 (bool): A boolean value that de... |
magic_instruct_75k | 2,130 | Write a Python function to calculate the length of the shortest path from a given source vertex to all other vertices in a directed graph using Breadth-First Search (BFS). The graph is represented as an adjacency list. If there is no path from the source to a vertex, the length should be represented as infinity.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from collections import deque
def shortest_path_length(graph: List[List[int]], source: int) -> List[int]:
"""
Calculate the length of the shortest path from the source vertex to all other vertices in a d... |
magic_instruct_75k | 2,147 | Create a Python class `Logger` that implements a logging system for a software application. The logging system should support different log levels and be able to log messages with variable arguments. The class should have the following requirements:
1. The class should have a method `log` that takes a log level and a m... | Here is the Python code to solve the given problem in the markdown block:
```python
class Logger:
"""
A logging class that supports different log levels and variable arguments.
Attributes:
LOGGER_INFO (str): Constant representing the INFO log level.
LOGGER_WARNING (str): Constant representi... |
magic_instruct_75k | 2,148 | Write a Python function to process a given text by performing the following operations:
1. Remove any leading or trailing whitespace from the text.
2. Convert the text to lowercase.
3. Replace all occurrences of the word "apple" with "orange".
The function should start with:
```python
def processText(text: str) -> str... | Here is the Python code to solve the given problem in the markdown block:
```python
def processText(text: str) -> str:
"""
Processes the given text by removing leading and trailing whitespace, converting it to lowercase,
and replacing all occurrences of the word "apple" with "orange".
Args:
tex... |
magic_instruct_75k | 2,154 | Write a Python function to configure the parameters for the DeepFool algorithm, which is used to generate adversarial examples to fool a machine learning model. The function should take two arguments: `targeted`, a boolean indicating whether the attack is targeted or untargeted, and `adv_ys`, the adversarial targets if... | Here is the Python code to solve the given problem in the markdown block:
```python
def config_deepfool(targeted: bool, adv_ys: list) -> dict:
"""
Configure the parameters for the DeepFool algorithm.
Args:
- targeted (bool): A boolean indicating whether the attack is targeted or untargeted.
- adv_y... |
magic_instruct_75k | 2,155 | Write a Python function to find the highest score achieved by any student in a class. The function should take a list of integers representing the scores and return the highest score. The function should be efficient and handle edge cases such as an empty list or a list with negative scores.
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 find_highest_score(scores: List[int]) -> int:
"""
Find the highest score achieved by any student in a class.
Args:
scores (List[int]): A list of integers representing the scores of stude... |
magic_instruct_75k | 2,160 | Write a Python script to automate the process of removing the quarantine attribute from multimedia files in a given directory and then executing a Java application to process them. The script should:
1. Recursively remove the quarantine attribute from all multimedia files (e.g., `ffmpeg`, `ffprobe`) in the specified di... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
from typing import List
def process_multimedia_files(directory: str):
"""
Automates the process of removing the quarantine attribute from multimedia files in a given directory
and then executing ... |
magic_instruct_75k | 2,190 | Write a Python function to parse a Django URL configuration file and extract the names of all the view functions defined for each URL pattern. The URL configuration is provided as a list of tuples, where each tuple contains a URL pattern string, the corresponding view function, and the name of the URL pattern. The func... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Set
def extract_view_names(url_patterns: List[Tuple[str, callable, str]]) -> Set[str]:
"""
Extracts the names of all view functions from a Django URL configuration.
Args:
url_pattern... |
magic_instruct_75k | 2,191 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0. The function should be efficient and handle various edge cases, such as an empty list or a list with no even numbers.
The code sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_even_numbers(nums: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list of integers.
Args:
nums (List[int]): A list of integers from which to calculate t... |
magic_instruct_75k | 2,235 | Write a Python function to calculate the nth Fibonacci number using dynamic programming. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. Your task is to write a function that efficiently computes the nth Fibonacci number using dynamic programming to avoid redundan... | Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using dynamic programming.
Args:
n (int): The position in the Fibonacci sequence to calculate.
Returns:
int: The nth Fibonacci number... |
magic_instruct_75k | 2,241 | Write a Python function to transform an input array of shape `(batch_size, N, N, 2)` into a complex-valued array of shape `(batch_size, N, N, 1)`. The input array contains real and imaginary parts of complex numbers, and the function should combine these parts to form complex numbers. The resulting array should be resh... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def transform_to_complex(array: np.ndarray) -> np.ndarray:
"""
Transforms the input array into a complex-valued array.
Args:
array (np.ndarray): Input array of shape (batch_size, N, N, 2) contain... |
magic_instruct_75k | 2,242 | Write a Python function to process a given string `id` by replacing specific characters with underscores (`_`). The function should replace all occurrences of the following characters:
1. "(" with "_"
2. ")" with "_"
3. "/" with "_"
The function should return the modified string.
The code should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_id(id: str) -> str:
"""
Processes the input string by replacing specific characters with underscores.
Args:
id (str): The input string to be processed.
Returns:
str: The modified string with... |
magic_instruct_75k | 2,274 | Write a Python function to reverse the elements of a given tuple and return a new tuple with the elements in reverse order. The function should handle tuples of any length, including empty tuples. The code should start with:
```python
def reverse_tuple(input_tuple: tuple) -> tuple:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_tuple(input_tuple: tuple) -> tuple:
"""
Reverses the elements of a given tuple and returns a new tuple with the elements in reverse order.
Args:
input_tuple (tuple): The tuple to be reversed.
Return... |
magic_instruct_75k | 2,277 | Write a Python function to categorize a list of button codes based on their language and category number. Each button code follows a specific naming convention: `<language>_b<category number>_<button number>_button`. The function should return a dictionary where the keys are tuples representing the language and categor... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def categorize_buttons(button_codes: List[str]) -> Dict[Tuple[str, int], List[str]]:
"""
Categorizes a list of button codes based on their language and category number.
Args:
bu... |
magic_instruct_75k | 2,293 | Write a Python function to implement a state machine for processing orders in an e-commerce system. The state machine has five states: `PENDING_CONFIRM`, `PENDING_CANCEL`, `CANCELED`, `CONFIRMED`, and `FAILED`, represented by the integer values 1, 2, 3, 4, and 5 respectively. The transitions between these states are go... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_order_state(current_state: int, event: str) -> int:
"""
Process the state of an order based on the current state and an event.
Args:
current_state (int): The current state of the order. Possible values a... |
magic_instruct_75k | 2,299 | Create a Python script to automate the build process for a software project. The script should perform the following tasks:
1. Compile the source files `ldid.cpp` and `lookup2.c` using the appropriate compiler and flags.
2. Link the compiled object files to create an executable named `ldid`.
3. Create a directory at th... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
import shutil
def build_and_install(cxx: str, cc: str, cxxflags: str, cflags: str, ldflags: str, prefix: str) -> None:
"""
Automates the build and installation process for a software project.
Ar... |
magic_instruct_75k | 2,310 | Write a Python function to format the prices of products in a store. The function should take three lists as input: `xval`, `products`, and `price`. Each list contains the same number of elements, where `xval` represents the product identifier, `products` represents the product name, and `price` represents the product ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def formatProductPrices(xval: List[int], products: List[str], price: List[int]) -> List[str]:
"""
Formats the prices of products in a store.
Args:
xval (List[int]): List of product identifie... |
magic_instruct_75k | 2,317 | Write a Python function to generate a list of links by appending each address in a given list of addresses to a base URL. The function should handle both absolute and relative paths in the addresses. If an address is already an absolute URL, it should be included in the output as is. If an address is a relative path, i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from urllib.parse import urlparse
def generate_links(adrs: List[str], base_url: str = 'https://bcy.net') -> List[str]:
"""
Generates a list of links by appending each address in the given list to a base ... |
magic_instruct_75k | 2,324 | Write a Python function to create a package configuration for a build system by processing keyword arguments and applying default values and substitutions. The function should handle the following parameters:
- `name` (string): The name of the package.
- `deps` (list): List of dependencies for the package.
- `readme_md... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Optional
# Default values for substitutions, ng_packager, and terser_config_file
PKG_GROUP_REPLACEMENTS = {"group1": "replacement1", "group2": "replacement2"}
_INTERNAL_NG_PACKAGE_PACKAGER = "internal_ng_... |
magic_instruct_75k | 2,328 | Write a Python function to filter queues based on specific criteria from a given list of queues. Each queue is represented as a dictionary with attributes such as `name`, `visibility_timeout`, and `max_message_retention_period`. The function should accept a list of queues and a dictionary of filter criteria, and return... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def filter_queues(queues: List[Dict[str, Any]], filter_by: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Filters a list of queues based on specific criteria.
Args:
queues (List[Dic... |
magic_instruct_75k | 2,345 | Write a Python function `perform_operations(names)` that takes a list `names` as input and performs the following operations:
1. Print the length of the list `names`.
2. Print the length of the list `names` again.
3. Retrieve an element from the list `names` using an index.
The function should return the element retri... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def perform_operations(names: List[str]) -> str:
"""
Performs the following operations on the input list `names`:
1. Prints the length of the list.
2. Prints the length of the list again.
3. ... |
magic_instruct_75k | 2,356 | Write a Python function `get_view_function(url_pattern)` that takes a URL pattern as a string and returns the associated view function from a predefined list of URL patterns. If the URL pattern is not found in the `urlpatterns` list, the function should return a default view function named `default_view`.
The `urlpatt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable
# Define the view functions
def index_view(request):
"""View implementation for the index page."""
pass
def shipping_address_view(request):
"""View implementation for the shipping address page."... |
magic_instruct_75k | 2,357 | Write a Python function to generate URL patterns for custom error pages in a Django web application. The function should take an HTTP status code and a custom error message as input and return the corresponding URL pattern. The URL pattern should be in the format: `url(r'^<error_code>/$', default_views.<error_handler>,... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_error_url_pattern(error_code: int, error_message: str) -> str:
"""
Generates a URL pattern for a custom error page in a Django web application.
Args:
error_code (int): The HTTP status code for the error... |
magic_instruct_75k | 2,363 | Write a Python function to reorder a list of branding policy IDs based on their priority. The branding policy IDs are arranged in ascending priority order, where IDs later in the array have higher priority. Your goal is to write a function that takes the list of branding policy IDs and reorders them so that IDs with hi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reorder_branding_policies(branding_policy_ids: List[str]) -> List[str]:
"""
Reorders the list of branding policy IDs so that IDs with higher priority appear earlier in the list.
Args:
br... |
magic_instruct_75k | 2,372 | Write a Python function to calculate the optimal number of columns for displaying camera feeds in a graphical user interface (GUI). The function should take the number of camera feeds as input and return the optimal number of columns for arranging the feeds in the GUI. The number of columns should be calculated based o... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_columns(num_cams: int) -> int:
"""
Calculate the optimal number of columns for displaying camera feeds in a GUI.
Args:
num_cams (int): The number of camera feeds to be displayed.
Retu... |
magic_instruct_75k | 2,381 | Write a Python function `generate_tab_code` that takes a list of dictionaries, where each dictionary represents a tab with the keys 'name', 'label', and 'icon'. The function should return a string containing the Python code to define the tabs and save the page, based on the input list. The generated code should be form... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_tab_code(tabs: List[Dict[str, str]]) -> str:
"""
Generates Python code to define a UI tab system based on the provided list of tab details.
Args:
tabs (List[Dict[str, str]... |
magic_instruct_75k | 2,390 | Write a Python function `process_spec(spec)` that takes a dictionary `spec` as input and returns a list of arguments based on the following conditions:
1. If the key `'+stats'` exists in the `spec` dictionary, append the string `'--enable-stats'` to the list of arguments.
2. If the key `'+prof'` exists in the `spec` di... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def process_spec(spec: Dict) -> List[str]:
"""
Processes a given specification dictionary and returns a list of arguments based on certain conditions.
Args:
spec (Dict): A dictionary c... |
magic_instruct_75k | 2,395 | Create a Python function to implement a simple stack data structure. The stack should support the following operations:
1. `push(item)` - Adds an element to the top of the stack.
2. `pop()` - Removes and returns the top element from the stack. If the stack is empty, return `None`.
3. `is_empty()` - Returns a boolean va... | Here is the Python code to solve the given problem in the markdown block:
```python
class Stack:
"""
A simple stack data structure implementation.
Attributes:
items (list): A list to store the elements of the stack.
Methods:
push(item): Adds an element to the top of the stack.
... |
magic_instruct_75k | 2,405 | Write a Python function to extract the second element from each tuple in a given list of tuples and return a new list containing these extracted elements. If the input list is empty, the function should return an empty list.
The code should start with:
```python
from typing import List, Tuple, Any
def extract_second_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Any
def extract_second_elements(input_list: List[Tuple[Any, Any]]) -> List[Any]:
"""
Extracts the second element from each tuple in the given list of tuples and returns a new list containing thes... |
magic_instruct_75k | 2,416 | Write a Python function to construct a command-line string for a genetic data processing tool. The function should take several parameters representing different files and options required for the tool and return a complete command-line string. The command-line string should include placeholders for variables such as `... | Here is the Python code to solve the given problem in the markdown block:
```python
def constructCommandLine(CHR: int, BAM_LIST_FILE: str, SNP_POS_FILE: str, REF_HAP_FILE: str, REF_LEGEND_FILE: str, GEN_MAP_FILE: str) -> str:
"""
Constructs a command-line string for a genetic data processing tool.
Args:
... |
magic_instruct_75k | 2,417 | Write a Python function to calculate the amplification success rate based on the number of true positives (TP) and false negatives (FN) in a bioinformatics project. The function should return the success rate as a percentage, rounded to two decimal places. The code should start with:
```python
def amplification_success... | Here is the Python code to solve the given problem in the markdown block:
```python
def amplification_success_rate(TP: int, FN: int) -> float:
"""
Calculate the amplification success rate based on the number of true positives (TP) and false negatives (FN).
Args:
TP (int): The number of successfully... |
magic_instruct_75k | 2,420 | Write a Python function to simulate a custom event handling system similar to the one described in the given C++ code snippet. The task involves creating a custom event class `CustomEvent` that inherits from a base event class `BaseEvent`. The `CustomEvent` class should have a constructor that takes an integer paramete... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, List
import random
class BaseEvent:
pass
class BaseWidget:
def event_handler(self, event: BaseEvent) -> None:
pass
class CustomEvent(BaseEvent):
"""
Represents a custom event type with ... |
magic_instruct_75k | 2,422 | Write a Python function to construct file paths for a machine learning project based on provided inputs. The function should accept four parameters: `datatype`, `tree_count`, `sz`, and `project`. The function should return a dictionary containing the constructed file paths as described below.
The file paths are constr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def construct_file_paths(datatype: str, tree_count: str, sz: str, project: str) -> Dict[str, str]:
"""
Constructs file paths for a machine learning project based on provided inputs.
Args:
da... |
magic_instruct_75k | 2,444 | Write a Python function to validate whether a given file name corresponds to a valid image file format. The valid image file formats are limited to 'png' and 'jpg'. The function should return `True` if the file format is valid, and `False` otherwise. The file name can be assumed to be in lowercase.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_valid_image_file(file_name: str) -> bool:
"""
Validate whether the given file name corresponds to a valid image file format.
Args:
file_name (str): The file name to be validated. It is assumed to be in lowerc... |
magic_instruct_75k | 2,457 | Write a Python function to filter a list of track objects based on a minimum threshold value and then visualize the first track from the filtered list. Each track object has a property `value` that represents the quality of the track. The function should start with:
```python
from typing import List, NamedTuple
class ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, NamedTuple
class Track(NamedTuple):
value: float
path: List[float]
def filter_tracks(decoded_tracks: List[Track], p_min: float) -> List[Track]:
"""
Filters a list of track objects based on a mi... |
magic_instruct_75k | 2,474 | Write a Python function to simulate the behavior of a notification receiver for a network application. The function should handle incoming notifications from a PostgreSQL database and perform appropriate actions based on the received data. Specifically, the function should print the received notification message and th... | Here is the Python code to solve the given problem in the markdown block:
```python
def handle_notification(payload: str, backend_pid: int) -> None:
"""
Simulates handling an incoming notification from a PostgreSQL database.
This function prints the received notification message and the corresponding backe... |
magic_instruct_75k | 2,479 | Write a Python function to remove an attribute index from a list of ignored attributes if it exists. The function should take a list of ignored attribute indices and an attribute index to be removed. The function should return the updated list of ignored attribute indices after the removal.
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 remove_ignored_attribute(ignored_attributes: List[int], attribute_to_remove: int) -> List[int]:
"""
Removes an attribute index from a list of ignored attributes if it exists.
Args:
ignor... |
magic_instruct_75k | 2,482 | Write a Python function to calculate the effective width of the terminal window for displaying a given text, considering the fixed terminal width and any potential padding or margins. The function should return the maximum number of characters that can be displayed in a single line without wrapping.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_terminal_width(text: str, terminal_width: int = 80, padding_width: int = 0) -> int:
"""
Calculate the effective width of the terminal window for displaying a given text.
Args:
text (str): The text for ... |
magic_instruct_75k | 2,484 | Write a Python function to parse and process model compilation configurations for a deep learning framework. The function should take a dictionary of compilation configurations and return the corresponding loss function and optimizer settings. The function should handle missing keys and provide default values as specif... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_compilation_configs(compilation_configs: dict) -> (str, str):
"""
Parses and processes model compilation configurations for a deep learning framework.
Args:
compilation_configs (dict): A dictionary contain... |
magic_instruct_75k | 2,488 | Write a Python function to process invoice data from a given dictionary. The dictionary contains key-value pairs representing various attributes of an invoice. The function should perform the following operations:
1. Calculate the VAT amount based on the total net amount and the included VAT percentage.
2. Determine if... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def process_invoice(invoice_data: Dict[str, str]) -> Dict[str, str]:
"""
Processes invoice data to calculate the VAT amount, determine the payment status, and return the observations.
Args:
... |
magic_instruct_75k | 2,494 | Write a Python function to add a background color to an image represented as a two-dimensional array of pixels. Each pixel is a tuple of (R, G, B, A) values for red, green, blue, and alpha channels respectively. The background color is also represented as a tuple of (R, G, B) values. The alpha value for the background ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def add_background_color(image: List[List[Tuple[int, int, int, int]]], bg_color: Tuple[int, int, int]) -> List[List[Tuple[int, int, int, int]]]:
"""
Adds a background color to an image represented... |
magic_instruct_75k | 2,495 | Write a Python function to generate all possible k-mers of a given length `k` from a given DNA sequence. A k-mer is a substring of length `k` from the DNA sequence. The DNA sequence will only contain the characters 'A', 'C', 'G', and 'T'.
The function should start with:
```python
from typing import List
def generate_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_kmers(dna_sequence: str, k: int) -> List[str]:
"""
Generate all possible k-mers of length k from a given DNA sequence.
Args:
dna_sequence (str): The DNA sequence from which to g... |
magic_instruct_75k | 2,506 | 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 code should start with:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
```
| 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 | 2,510 | Write a Python function to calculate the average score for each category from a given dictionary. The dictionary contains tuples as keys and floating-point numbers as values. Each tuple represents a unique combination of three integers: the first integer represents a category, the second integer represents a subcategor... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple, List
def calculate_average_scores(scores_dict: Dict[Tuple[int, int, int], float]) -> Dict[int, float]:
"""
Calculate the average score for each category from a given dictionary of scores.
Ar... |
magic_instruct_75k | 2,512 | Write a Python function to process a collection of museum objects and their associated images. The function should retrieve the museum objects from a database, calculate the count of public images associated with each object, and then return a paginated list of the museum objects along with their respective public imag... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def get_paginated_museum_objects(museum_objects: List[Dict[str, Any]], page_number: int, page_size: int) -> List[Dict[str, Any]]:
"""
Processes a collection of museum objects and their associa... |
magic_instruct_75k | 2,526 | Write a Python function `process_strings(strings: List[str]) -> List[str]` that processes a list of strings according to the following rules:
1. Replace specific characters within each string: The characters `[`, `]`, `?`, and `!` should be replaced with their corresponding escaped versions. For example, `[` should be ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def process_strings(strings: List[str]) -> List[str]:
"""
Processes a list of strings by replacing specific characters and removing duplicates.
Args:
strings (List[str]): A list of... |
magic_instruct_75k | 2,529 | Write a Python function to determine the window size that produces the most accurate reconstruction of the original time series data using Singular Spectrum Analysis (SSA). The function should take the original time series data and the reconstructed time series for different window sizes as input and return the window ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def best_window_size(orig_TS: List[float], F8: List[float], F9: List[float], F10: List[float], F11: List[float]) -> int:
"""
Determine the window size that produces the most accurate reconstruction of th... |
magic_instruct_75k | 2,540 | Write a Python function to search for a specific item in a list of items and return the first occurrence of the item. If the item is not found in the list, the function should return `None`. The function should be efficient and handle various edge cases, such as an empty list or a list with duplicate items.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_item(item: int, items: List[int]) -> Optional[int]:
"""
Searches for the first occurrence of a specified item in a list of items.
Args:
item (int): The item to search for ... |
magic_instruct_75k | 2,551 | Write a Python function to convert a given string into a specific format. The input string consists of words separated by commas, and each word may contain uppercase and lowercase letters, digits, and special characters. The function should convert the input string into a new format where each word is enclosed within d... | Here is the Python code to solve the given problem in the markdown block:
```python
def convertToQuotedFormat(input_string: str) -> str:
"""
Converts a given string into a specific format where each word is enclosed within double quotes and separated by a comma.
Args:
input_string (str): The input ... |
magic_instruct_75k | 2,556 | Write a Python function to automate the installation of Apache Giraph and Zookeeper on a Unix-based system. The function should download the necessary files, extract them to a specified directory, and create symbolic links for easy access. The function should handle errors gracefully and provide informative output duri... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
import shutil
import requests
from typing import Optional
def install_apache_giraph_and_zookeeper(prefix: str, giraph_url: str, zookeeper_url: str) -> Optional[str]:
"""
Automates the installation of... |
magic_instruct_75k | 2,566 | Write a Python function to determine whether a player can reach a target position on a game board without being caught by any ghosts. The game board is represented as a 2D grid, where each ghost's position is given as a list of lists containing the x and y coordinates. The player's position is assumed to be at the orig... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def escapeGhosts(ghosts: List[List[int]], target: List[int]) -> bool:
"""
Determines whether the player can reach the target position without being caught by any ghosts.
The player starts at the ori... |
magic_instruct_75k | 2,581 | Complete the implementation of the `math_functions.py` module by adding the missing functions and ensuring that the existing functions are correctly implemented. The module should include functions for calculating the factorial of a number, finding the greatest common divisor (GCD) of two numbers, and checking if a num... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def factorial(n):
"""
Calculates the factorial of a number.
Args:
n (int): The number to calculate the factorial of.
Returns:
int: The factorial of the number.
Raises:
ValueErr... |
magic_instruct_75k | 2,582 | Write a Python function to generate embeddings for tokens in a given text block, handling cases where the input text block exceeds the maximum sequence length. The function should tokenize the text, convert tokens to their respective IDs, and generate embeddings for these IDs. If the text block is too long, the functio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
class Block:
def __init__(self, text: str):
self.text = text
class Tokenizer:
def tokenize(self, text: str) -> List[str]:
# Dummy implementation for tokenization
return tex... |
magic_instruct_75k | 2,595 | Write a Python function to simulate a simple bank account with the following functionalities:
1. Initialize the account with a given account holder's name and an initial balance of 0.
2. Deposit a specified amount into the account.
3. Withdraw a specified amount from the account if sufficient funds are available.
4. Re... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_bank_account(account_holder: str) -> dict:
"""
Creates a bank account with the given account holder's name and initial balance of 0.
Args:
account_holder (str): The name of the account holder.
Return... |
magic_instruct_75k | 2,605 | Write a Python function to determine if a given string of parentheses is balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. The function should return `True` if the parentheses are balanced, and `False` otherwise.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_balanced_parentheses(s: str) -> bool:
"""
Determine if the given string of parentheses is balanced.
Args:
s (str): The string containing parentheses to be checked.
Returns:
bool: True if the pare... |
magic_instruct_75k | 2,615 | Write a Python function to search for a specific value within a lookup table provided as a stream of strings. The function should return `True` if the value is found in the table and `False` otherwise. The function should ignore leading and trailing whitespace in the lookup table entries.
The code should start with:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Iterable
def search_in_lookup_table(lookuptablestream: Iterable[str], value: str) -> bool:
"""
Searches for a specific value within a lookup table provided as a stream of strings.
Args:
lookuptab... |
magic_instruct_75k | 2,632 | Write a Python function to calculate the area of a liver contour in an ultrasound image. The image is represented as a 2D array of pixel values, and the liver contour is represented as a list of points, where each point is represented by its (x, y) coordinates. The function should use the shoelace formula to compute th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_liver_contour_area(image_array: List[List[int]], liver_contour: List[Tuple[int, int]]) -> float:
"""
Calculate the area of the liver contour in an ultrasound image using the shoelace... |
magic_instruct_75k | 2,671 | Write a Python function `processItems` that processes a list of items and performs specific operations based on the type of each item. The items can be of various types, including `BooleanCV`, `UIntCV`, `ChainID`, `makeStandardSTXPostCondition`, and `makeContractSTXPostCondition`. The function should handle each type d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def processItems(items: List[str]) -> List[str]:
"""
Processes a list of items based on their types and returns a list of processed items.
Args:
items (List[str]): A list of items to be proc... |
magic_instruct_75k | 2,683 | Write a Python function to filter a list of server configurations based on a specified disk size threshold. Each server configuration is represented as a dictionary containing the server's group and disk size. The function should return a new list containing only the servers whose disk size is greater than or equal to ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_servers_by_disk_size(servers: List[Dict[str, any]], threshold: int) -> List[Dict[str, any]]:
"""
Filters a list of server configurations based on a specified disk size threshold.
Ar... |
magic_instruct_75k | 2,686 | Write a Python function to implement the classic Fizz-Buzz game. The function should take an integer `n` as input and return a list of strings. The list should contain the numbers from 1 to `n`, but with the following substitutions:
- If the number is divisible by 3, replace it with "Fizz".
- If the number is divisible... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def fizz_buzz(n: int) -> List[str]:
"""
Returns a list of strings from 1 to n, with numbers replaced according to the Fizz-Buzz rules.
Args:
n (int): The upper limit of the range of numbers ... |
magic_instruct_75k | 2,734 | Write a Python function to automate the process of restoring a MySQL database from a dump file. The function should take the necessary parameters and execute the restoration process using the `mysql` command-line tool.
The function should accept the following parameters:
- `host`: The hostname of the MySQL server wher... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def restore_mysql_database(host: str, user: str, dump_file: str, password: str) -> None:
"""
Automates the process of restoring a MySQL database from a dump file.
Args:
host (str): The hostname of... |
magic_instruct_75k | 2,748 | Write a Python function to transform a dictionary of features into a specific format for input into a machine learning model. The input dictionary contains keys representing feature names and values representing feature data, which are lists of integers. The function should convert each feature data into a specific for... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def create_int_feature(data: List[int]) -> str:
"""
Placeholder function to transform a list of integers into a specific format.
Args:
data (List[int]): A list of integers to be transf... |
magic_instruct_75k | 2,753 | Write a Python function to extract the day of the week from a list of dates in the format "YYYY-MM-DD" and return a list of three-letter abbreviations for the days of the week. The function should be efficient and handle various edge cases, such as invalid date formats or empty lists.
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
from datetime import datetime
def get_day_of_week(dates: List[str]) -> List[str]:
"""
Extracts the day of the week from a list of dates in the format "YYYY-MM-DD" and returns a list of three-letter abbre... |
magic_instruct_75k | 2,774 | Write a Python function to read integers from a file named "input.txt" and calculate the sum of all the integers. Implement custom exception handling to manage potential errors during file processing. If the file does not exist or cannot be opened, raise a custom exception `FileOpenException` with the message "Error: U... | Here is the Python code to solve the given problem in the markdown block:
```python
class FileOpenException(Exception):
pass
class InvalidDataException(Exception):
pass
def calculate_sum_from_file() -> int:
"""
Reads integers from a file named "input.txt" and calculates their sum.
Raises custom ex... |
magic_instruct_75k | 2,779 | Write a Python function to generate a setup configuration string for a Python package based on provided Python version requirements and entry points. The function should take two parameters: a list of Python version requirements in the format ">=3.6" (as strings) and a dictionary of entry points in the format `{"consol... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_setup_config(python_versions: list, entry_points: dict) -> str:
"""
Generates a setup configuration string for a Python package based on provided Python version requirements and entry points.
Args:
pyth... |
magic_instruct_75k | 2,780 | Write a Python function `process_list()` that takes a list of integers as input and returns a new list containing only the unique elements from the input list, sorted in ascending order. The function should handle any list of integers, including empty lists and lists with duplicate elements.
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 process_list(input_list: List[int]) -> List[int]:
"""
Processes the input list to return a new list containing only the unique elements, sorted in ascending order.
Args:
input_list (List... |
magic_instruct_75k | 2,829 | Write a Python function `getSupportedOperations(format: str) -> List[str]` that determines the supported operations for a given table format. The function should use two provided functions, `supportsCreateTable(format)` and `supportsAlterTable(format)`, to check if the table format supports creating and altering tables... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def getSupportedOperations(format: str) -> List[str]:
"""
Determines the supported operations for a given table format.
Args:
format (str): The table format to check for supported operations... |
magic_instruct_75k | 2,831 | Write a Python function to convert a configuration from the `clarity-ext` format to the `KNM` format. The `clarity-ext` configuration is a dictionary containing more information than what is required for the `KNM` format. The `KNM` configuration should only include the keys "name", "age", and "email". The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def KNMConfig(config: dict) -> dict:
"""
Converts a clarity-ext configuration to a KNM configuration by extracting the necessary keys.
Args:
config (dict): The clarity-ext configuration dictionary containing more in... |
magic_instruct_75k | 2,836 | Write a Python function to generate a random number within a specified range. The function should allow setting a new range dynamically.
The code should start with:
```python
import random
def generate_random_number(min_val: int, max_val: int) -> int:
"""
Generate a random number within the specified range [mi... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_random_number(min_val: int, max_val: int) -> int:
"""
Generate a random number within the specified range [min_val, max_val].
Args:
min_val (int): The minimum value of the range (inclusiv... |
magic_instruct_75k | 2,846 | Write a Python function to determine if a given package specification is editable or not. An editable package can be directly edited in the current environment, typically specified using the `-e` flag in package installation commands. The package specification can be in various forms, such as a dictionary with a "git" ... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_editable(package_spec):
"""
Determine if a given package specification is editable.
Args:
package_spec (dict or str): The package specification, which can be a dictionary with a "git" key and an optional "edi... |
magic_instruct_75k | 2,862 | Write a Python function to find the index of the player with the highest score in a given list of scores. If there are multiple players with the highest score, return the index of the first occurrence of the highest score. The scores are arranged in ascending order.
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
def highestScoreIndex(scores: List[int]) -> int:
"""
Find the index of the player with the highest score in a list of scores.
If there are multiple players with the highest score, return the index of... |
magic_instruct_75k | 2,916 | Write a Python function to generate a formatted string of command-line arguments for a software installation script based on a dictionary of configuration options. The function should handle boolean and string options, ensuring that boolean options are only included if their value is `True`. Each configuration option s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def generate_installation_arguments(config_options: Dict[str, bool | str]) -> str:
"""
Generates a formatted string of command-line arguments for a software installation script.
Args:
config... |
magic_instruct_75k | 2,934 | Write a Python function to calculate the total number of occurrences of a given word in a list of strings. The function should be case-insensitive and should count partial matches as well. For example, if the word is "cat", it should count occurrences of "cat", "cats", "category", etc. The function should also handle s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def count_word_occurrences(word: str, word_list: List[str]) -> int:
"""
Calculate the total number of occurrences of a given word in a list of strings.
The function is case-insensitive and ... |
magic_instruct_75k | 2,940 | Write a Python function `count_package_info_occurrences(pkg_info: dict) -> dict` that takes in a dictionary `pkg_info` containing package information and returns a new dictionary with the count of occurrences for each unique value in the original dictionary. The keys in the input dictionary are predefined and correspon... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_package_info_occurrences(pkg_info: dict) -> dict:
"""
Counts the occurrences of each unique value in the given package information dictionary.
Args:
pkg_info (dict): A dictionary containing package informa... |
magic_instruct_75k | 2,942 | Write a Python function to determine the winner of a 3x3 Tic-Tac-Toe game given a 2D array `board` of characters. The characters in the array can be one of the following: 'X', 'O', or ' ' (representing an empty cell). The function should return 'X' if player X has won, 'O' if player O has won, 'Tie' if the game is a ti... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def checkWinner(board: List[List[str]]) -> str:
"""
Determine the winner of a 3x3 Tic-Tac-Toe game given a 2D array `board`.
Args:
board (List[List[str]]): A 2D array representing the Tic-Ta... |
magic_instruct_75k | 2,975 | Write a Python function to calculate the final position of a joint in a physics simulation, considering different physics engines and handling non-zero initial values. The function should take the initial position, physics engine type, and tolerance as input and return the final position of the joint. The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_final_position(initial_position: float, physics_engine: str, tolerance: float) -> float:
"""
Calculate the final position of a joint in a physics simulation.
Args:
initial_position (float): The initial... |
magic_instruct_75k | 2,983 | Write a Python function to filter and return a list of hemisphere names from a given dataset where the average temperature exceeds a specified threshold. The dataset is a list of dictionaries, where each dictionary contains the keys 'hemisphere', 'average_temperature', and 'max_temperature'. The function should be name... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def high_temperature_hemispheres(data: List[Dict[str, any]], threshold: float) -> List[str]:
"""
Filters and returns a list of hemisphere names where the average temperature exceeds a specified thr... |
magic_instruct_75k | 2,988 | Write a Python function to analyze a given text and determine the frequency of each word. The function should ignore punctuation and consider words in a case-insensitive manner. The output should be a list of tuples, where each tuple contains a unique word and its frequency, sorted in descending order of frequency.
Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
from collections import Counter
def wordFrequency(text: str) -> List[Tuple[str, int]]:
"""
Analyzes the given text to determine the frequency of each word, ignoring punctuation and case.... |
magic_instruct_75k | 2,992 | Write a Python function to validate the structure of a given list of agencies and their corresponding chunks. Each agency is represented as a tuple containing the agency name and a list of chunks. The chunks are represented as lists of strings. The function should ensure that each agency has exactly three chunks, with ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def validate_agencies(agencies: List[Tuple[str, List[List[str]]]]) -> bool:
"""
Validates the structure of a given list of agencies and their corresponding chunks.
Each agency is represented ... |
magic_instruct_75k | 3,004 | Write a Python function to retrieve character information for a specific user and world from a database, sort the characters by level in descending order, and announce the details on a designated log channel. The function should take the user's member ID and the world as input parameters. The database contains a table ... | Here is the Python code to solve the given problem in the markdown block:
```python
import asyncio
from typing import List, Dict
async def announce_user_characters(member_id: int, world: str, pool, log_channel_id: int) -> None:
"""
Retrieves character information for a specific user and world from a database,
... |
magic_instruct_75k | 3,010 | Write a Python function to find all the divisors of a given positive integer `n` in ascending order. A divisor of `n` is a positive integer that divides `n` without leaving a remainder. The function should return a list of all divisors.
The code should start with:
```python
from typing import List
def find_divisors(n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def find_divisors(n: int) -> List[int]:
"""
Find all divisors of a given positive integer `n` in ascending order.
Args:
n (int): The positive integer for which to find the diviso... |
magic_instruct_75k | 3,036 | Write a Python function to calculate the sum of the absolute differences between all pairs of elements in a given list of integers. The function should take a single parameter, a list of integers, and return an integer representing the sum of the absolute differences between all pairs of elements in the list.
The code... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_absolute_differences(a: List[int]) -> int:
"""
Calculate the sum of the absolute differences between all pairs of elements in the given list.
Args:
a (List[int]): A list of intege... |
magic_instruct_75k | 3,057 | Write a Python function to process a list of migration operations and return the names of the models being affected. Each migration operation is represented as a tuple containing the operation type and the model name. The operation types can be either "CreateModel" or "DeleteModel". The model name is a string represent... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Set
def get_affected_models(migrations: List[Tuple[str, str]]) -> Set[str]:
"""
Processes a list of migration operations and returns the names of the models being affected.
Args:
mig... |
magic_instruct_75k | 3,058 | Write a Python function to calculate the total amount of rainwater that can be trapped between a series of buildings represented by their heights. Each building has a width of 1 unit. The function should take a list of non-negative integers representing the heights of the buildings and return the total trapped rainwate... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def trapped_rainwater(heights: List[int]) -> int:
"""
Calculate the total amount of rainwater that can be trapped between buildings.
Args:
heights (List[int]): A list of non-negative integer... |
magic_instruct_75k | 3,066 | Write a Python function to convert a byte array into a numerical value based on the specified endianness. The function should handle both little-endian and big-endian systems. The byte array represents a sequence of data, and the endianness determines the order in which bytes are interpreted. The function should return... | Here is the Python code to solve the given problem in the markdown block:
```python
def convertByteArrayToNumber(byteArray: bytes, endian: str) -> int:
"""
Converts a byte array to a numerical value based on the specified endianness.
Args:
byteArray (bytes): A byte array representing the sequence o... |
magic_instruct_75k | 3,124 | Write a Python function to construct a formatted SQL query that selects all columns from a given database table. The function should take the database table name as input and return a string representing the SQL query. The SQL query should be formatted to select all columns from the specified table.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_sql_query(db_table: str) -> str:
"""
Constructs a SQL query to select all columns from the specified database table.
Args:
db_table (str): The name of the database table from which to select all column... |
magic_instruct_75k | 3,165 | Write a Python function to categorize a list of strings representing shape names into different groups based on specific criteria. The function should return a dictionary where the keys are the categories and the values are lists of shape names that belong to each category.
The categorization criteria are as follows:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def categorize_shapes(shape_names: List[str]) -> Dict[str, List[str]]:
"""
Categorizes a list of shape names into different groups based on their prefixes.
Args:
shape_names (List[str]... |
magic_instruct_75k | 3,166 | Write a Python function to calculate the maximum amount of rainwater that can be trapped between a series of buildings represented by their heights in a list. Each building's height is given as an integer, and the function should return the total amount of rainwater trapped between the buildings.
The code should start... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_rainwater_trapped(heights: List[int]) -> int:
"""
Calculate the maximum amount of rainwater that can be trapped between buildings.
Args:
heights (List[int]): A list of integers repre... |
magic_instruct_75k | 3,181 | Implement a Python function `getTimeSinceLastSeen` that calculates the time elapsed (in seconds) since the last seen timestamp was set using the `setLastSeenTimestamp` method. The function should be part of a class that already has the following methods implemented:
- `setLastSeenTimestamp(timestamp)`: Sets the last se... | Here is the Python code to solve the given problem in the markdown block:
```python
class TimestampTracker:
def __init__(self):
self.lastSeenTimestamp = 0 # Initialize the last seen timestamp to 0
def setLastSeenTimestamp(self, timestamp: int) -> None:
"""
Sets the last seen timestamp ... |
magic_instruct_75k | 3,187 | Write a Python function to create a deep copy of a given object to prevent the alteration of its defaults. The function should return a deep copy of the object to ensure that any changes made to the clone do not affect the original object. The function should handle various types of Python objects, including lists, dic... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any
from copy import deepcopy
def clone_object(obj: Any) -> Any:
"""
Create a deep copy of the given object to prevent alteration of its defaults.
Args:
obj (Any): Any Python object (e.g., list, ... |
magic_instruct_75k | 3,214 | Write a Python function `validate_tickets` that validates and processes tickets for a popular event. The function should take in three parameters: `rules`, `your_ticket`, and `nearby_tickets`. The `rules` parameter is a dictionary where the keys are field names and the values are lists of valid ranges for that field. T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def validate_tickets(rules: Dict[str, List[Tuple[int, int]]], your_ticket: List[int], nearby_tickets: List[List[int]]) -> int:
"""
Validates nearby tickets against the given rules and return... |
magic_instruct_75k | 3,225 | Write a Python function to simulate the behavior of `sed` commands in a shell script that modifies a pipeline configuration file for a machine learning model training process. The function should take the original pipeline configuration content and perform the specified substitutions to generate the modified content. T... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def modify_pipeline_config(original_content: str,
fine_tune_checkpoint: str,
train_iterations: int,
eval_iterations: int,
... |
magic_instruct_75k | 3,228 | Implement the `nested_if_else` function that takes a NumPy array `x` as input and modifies the array elements based on the following conditions:
- If an element is greater than 0.5, set it to 1.
- If an element is less than -0.5, set it to -1.
- If an element is between -0.5 and 0.5 (inclusive), set it to 0.
The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def nested_if_else(x: np.ndarray) -> np.ndarray:
"""
Modifies the elements of a NumPy array based on the following conditions:
- If an element is greater than 0.5, set it to 1.
- If an element is less... |
magic_instruct_75k | 3,268 | Write a Python function to determine whether a frog can cross a river by jumping on stones. The river is represented as a sequence of stones, and the frog starts at the first stone. The frog can jump from one stone to another if the distance is within a certain range. The goal is to reach the last stone in the river. Y... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def canCross(stones: List[int]) -> bool:
"""
Determine whether a frog can cross a river by jumping on stones.
Args:
stones (List[int]): A list of integers representing the positions of the s... |
magic_instruct_75k | 3,283 | Write a Python function to identify the best error value along with the corresponding dynamic programming array values. The function should take in two parameters:
- `dp`: a list of integers representing the dynamic programming array values.
- `best_err`: a floating-point number representing the best error value.
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def findBestError(dp: List[int], best_err: float) -> Tuple[float, List[int]]:
"""
Identifies the best error value along with the corresponding dynamic programming array values.
Args:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.