source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
65,663
Write a Python function to initialize the weights for a Long Short-Term Memory (LSTM) pooling cell based on a given cell size. The function should return a dictionary containing the initialized weights for the LSTM pooling cell. The weights should be initialized using a predefined function `initialize_lstm_pooling_weig...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def initialize_lstm_pooling_weights(cell_size: int) -> Dict[str, float]: """ Initialize weights for the LSTM pooling cell. Args: cell_size (int): The size of the LSTM pooling cell. Retu...
magic_instruct_75k
65,671
Write a Python function to process a dictionary containing loss values for various categories and return a modified dictionary. The input dictionary, `loss_dict`, contains keys representing different categories and corresponding values representing the loss values for each category. Your task is to create a function `p...
Here is the Python code to solve the given problem in the markdown block: ```python def process_losses(loss_dict: dict) -> dict: """ Processes a dictionary of loss values for various categories and returns a modified dictionary. The modification rules are: 1. If the loss value for a category is less tha...
magic_instruct_75k
65,696
Write a Python function to convert a given date and time string to a new date and time based on a specified UTC time difference. The function should take two parameters: `utc_time_difference` (an integer representing the time difference in hours) and `date_time_str` (a string representing the original date and time in ...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime, timedelta DATE_TIME_FORMAT = "%Y-%m-%d %H:%M:%S" def to_date_time(utc_time_difference: int, date_time_str: str) -> str: """ Converts a given date and time string to a new date and time based on a...
magic_instruct_75k
65,747
Write a Python function to randomly shuffle the elements of a given list of words. The function should return a new list with the elements in a random order. The code should start with: ```python from typing import List import random def randomize_words(words: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def randomize_words(words: List[str]) -> List[str]: """ Randomly shuffles the elements of a given list of words and returns a new list with the elements in a random order. Args: ...
magic_instruct_75k
65,754
Create a Python class hierarchy to represent revision information in a revision control system for a software project. The system should track and manage revisions made to various components of the project. Implement a base class `RevisionInfoBase` and a derived class `CodeRevisionInfo` that extends the base class. The...
Here is the Python code to solve the given problem in the markdown block: ```python from abc import ABC, abstractmethod from datetime import datetime from enum import Enum class AuditRevisionType(Enum): """ Enumeration representing the type of revision (Add, Modify, Delete). """ ADD = "Add" MODIFY ...
magic_instruct_75k
65,765
Write a Python function to convert a list of integers into a string representation, excluding any negative numbers. The function should return the string in the format of a list, e.g., `"[1, 3, 5]"`. The code should start with: ```python from typing import List def excludeNegatives(nums: List[int]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def excludeNegatives(nums: List[int]) -> str: """ Converts a list of integers into a string representation, excluding any negative numbers. Args: nums (List[int]): The list of integers to be...
magic_instruct_75k
65,780
Write a Python function to reverse an integer, including handling negative integers. The function should return the reversed integer with the same sign as the input. If the reversed integer exceeds the 32-bit signed integer range, the function should return 0. The code should start with: ```python def reverse(x: int) ...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse(x: int) -> int: """ Reverses the digits of an integer, preserving the sign. Args: x (int): The integer to be reversed. Returns: int: The reversed integer if it is within the 32-bit signed in...
magic_instruct_75k
65,796
Write a Python function to process a list of file paths and extract the latest version number from each path. The version number is denoted by a leading 'v' character, and the function should return a list of tuples containing the original file path and the extracted version number. If a version number is not present o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import re def extract_latest_version(file_paths: List[str]) -> List[Tuple[str, str]]: """ Extracts the latest version number from each file path in the given list. The version number is denot...
magic_instruct_75k
65,801
Write a Python function to reverse the order of words in a given string while preserving the order of characters within each word. The function should ensure that there is only one space between each word in the modified response. The code should start with: ```python def reverseResponse(response: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverseResponse(response: str) -> str: """ Reverses the order of words in a given string while preserving the order of characters within each word. Ensures that there is only one space between each word in the modified r...
magic_instruct_75k
65,813
Write a Python function to count the occurrences of each unique resource type from a list of resource strings. Each resource string is in the format "type_name", where "type" is the type of the resource and "name" is the name of the resource. The function should ignore the "name" part and only consider the "type" for c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_resource_types(resources: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique resource type from a list of resource strings. Args: resources (List[str]): ...
magic_instruct_75k
65,825
Write a Python function to adjust the row indexes of a collection of spreadsheet sheets. The function should take in a list of sheet names and a dictionary mapping each sheet name to its original row index. The function should return a dictionary mapping each sheet name to its adjusted row index, where the adjusted row...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def adjust_row_indexes(sheet_names: List[str], row_indexes: Dict[str, int]) -> Dict[str, int]: """ Adjusts the row indexes of a collection of spreadsheet sheets by incrementing each row index by 1....
magic_instruct_75k
65,827
Complete the `findLongestListKey` function to correctly return the key with the longest list as its value from a given dictionary `tagDict`. The keys of the dictionary are strings, and the values are lists of strings. The function should handle cases where the dictionary is empty and return `None` in such scenarios. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Optional def findLongestListKey(tagDict: Dict[str, List[str]]) -> Optional[str]: """ Finds the key in the dictionary with the longest list as its value. Args: tagDict (Dict[str, List[...
magic_instruct_75k
65,872
Write a Python function to remove all duplicate nodes from a singly linked list, such that each element appears only once. The function should return the head of the modified linked list. The linked list is represented by a class `ListNode` where each node contains a value and a reference to the next node. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def remove_duplicates(head: ListNode) -> ListNode: """ Remove all duplicate nodes from a singly linked list, such t...
magic_instruct_75k
65,896
Write a Python function to flatten a list of tuples into a single list based on the elements and their specified frequencies. Each tuple in the input list contains an element and an integer representing the frequency of that element in the output list. The code should start with: ```python from typing import List, Tup...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Any def flatten_tuples(input_list: List[Tuple[Any, int]]) -> List[Any]: """ Flattens a list of tuples into a single list based on the elements and their specified frequencies. Args: ...
magic_instruct_75k
65,910
Write a Python function to generate a SQL query to create a table with specified columns. The function should take a list of tuples as input, where each tuple contains the column name as a string and the data type as a string. The function should return a string representing the SQL query to create a table with the spe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_create_table_query(columns: List[Tuple[str, str]]) -> str: """ Generates a SQL query to create a table with specified columns. Args: columns (List[Tuple[str, str]]): A li...
magic_instruct_75k
65,920
Write a Python function to clone a repository from a version control system. The function should take in various parameters and options to customize the cloning process. The function should handle default values for options and ensure that the cloning process is executed based on the provided parameters. The function ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Optional, Dict def clone_repository(owner: str, repo: str, branch: str, sha: str, url: str, clone_options: Optional[Dict[str, any]] = None) -> None: """ Clones a repository from a version control system based...
magic_instruct_75k
65,932
Write a Python function to process a list of dictionaries representing configuration options for a software application. Each dictionary contains key-value pairs representing a specific configuration option. The function should return a new list of dictionaries with the default values preserved, if specified. The func...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def preserve_default_values(config_options: List[Dict[str, Union[str, bool]]]) -> List[Dict[str, Union[str, bool]]]: """ Processes a list of dictionaries representing configuration options a...
magic_instruct_75k
65,935
Write a Python function to determine if a given keystore is authorized for post operations based on its type, supported operations, and authorized users. The keystore is represented as a JSON object with specific fields. The function should return `True` if the keystore is of type "software", supports the "post" operat...
Here is the Python code to solve the given problem in the markdown block: ```python def post_authorizable_keystore(keystore: dict, current_user: str) -> bool: """ Determines if a given keystore is authorized for post operations. Args: keystore (dict): A dictionary representing the keystore with fie...
magic_instruct_75k
65,955
Write a Python function to extract and return the unique file types from a list of file type strings, where each string is in the format 'pyctr.type.<file_type>'. The function should remove the common prefix 'pyctr.type.' from each file type and return the extracted file types as a set. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Set def extract_file_types(file_types: List[str]) -> Set[str]: """ Extracts and returns the unique file types from a list of file type strings. Each file type string is in the format 'pyctr.type.<f...
magic_instruct_75k
65,962
Write a Python function to generate a Spack package specification based on the given code snippet. The function should parse the code snippet to extract version, SHA256 hash, and variant information, and then generate a Spack package specification string that includes the version, SHA256 hash, and variant declarations ...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_spack_package_spec(code_snippet: str) -> str: """ Generates a Spack package specification based on the given code snippet. Args: code_snippet (str): The code snippet containing version, SHA256 hash, and...
magic_instruct_75k
65,986
Write a Python function to calculate the sum of all integers in a given list. The function should handle lists of varying lengths, including empty lists. The code should start with: ```python from typing import List def sum_of_list(int_list: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sum_of_list(int_list: List[int]) -> int: """ Calculate the sum of all integers in a given list. Args: int_list (List[int]): A list of integers. Returns: int: The sum of al...
magic_instruct_75k
66,003
Write a Python function to multiply two integers using bitwise operations and addition, without using the multiplication operator or any built-in multiplication functions. The function should be efficient and handle both positive and negative integers. The code should start with: ```python def multiply(x: int, y: int)...
Here is the Python code to solve the given problem in the markdown block: ```python def multiply(x: int, y: int) -> int: """ Multiplies two integers using bitwise operations and addition, without using the multiplication operator. Args: x (int): The first integer. y (int): The second intege...
magic_instruct_75k
66,036
Write a Python function to find the maximum value in an array after applying a series of range addition queries. Each query is represented by a triplet of integers `(a, b, k)`, where `k` is added to all elements in the array from index `a` to `b` (inclusive). The array is initially filled with zeros. The function shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def array_manipulation(n: int, queries: List[Tuple[int, int, int]]) -> int: """ Find the maximum value in an array after applying a series of range addition queries. Args: n (int): Th...
magic_instruct_75k
66,042
Write a Python function to calculate the compression ratio of DICOM files based on their sizes. The compression ratio is defined as the ratio of the original file size to the compressed file size. The function should take the original file size and the compressed file size as input and return the compression ratio roun...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_compression_ratio(original_size: float, compressed_size: float) -> float: """ Calculate the compression ratio of a DICOM file based on its original and compressed sizes. The compression ratio is defined as the...
magic_instruct_75k
66,056
Write a Python function to remove all words from a given list that have a length less than a specified integer `n`. The function should return the modified list of strings. The code should start with: ```python from typing import List def remove_short_words(words: List[str], n: int) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_short_words(words: List[str], n: int) -> List[str]: """ Removes all words from the given list that have a length less than `n`. Args: words (List[str]): The list of strings from w...
magic_instruct_75k
66,067
Write a Python function to implement a simple paging mechanism for a list of items. The function should take in a list of items, the page number, and the page size, and return the items for the specified page. The function should handle edge cases such as invalid page numbers, page sizes, and empty lists by returning a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def select_page(items: List[int], page_number: int, page_size: int) -> List[int]: """ Returns the items for the specified page from the given list. Args: items (List[int]): The list of items...
magic_instruct_75k
66,074
Write a Python function to process a list of email addresses and return a dictionary containing the domain names as keys and the corresponding list of usernames as values. The function should handle invalid email addresses and return an empty dictionary for any invalid input. The function should ignore any invalid emai...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def process_emails(emails: List[str]) -> Dict[str, List[str]]: """ Processes a list of email addresses and returns a dictionary containing the domain names as keys and the correspondi...
magic_instruct_75k
66,086
Write a Python function to count the occurrences of each type of database migration operation from a given list of operations. Each operation is represented as a dictionary with a key "operation" indicating the type of operation. The function should return a dictionary where the keys are the distinct operation types an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_migration_operations(operations: List[Dict[str, str]]) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation from a given list of operations. Arg...
magic_instruct_75k
66,100
Write a Python function to calculate the sum of all elements in a given array. The function should handle arrays of integers and floating-point numbers. Ensure that the function is robust and correctly handles edge cases such as empty arrays. The code should start with: ```python from typing import List def calculate...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum(arr: List[float]) -> float: """ Calculate the sum of all elements in a given array. Args: arr (List[float]): The array of numbers (integers or floating-point numbers) to su...
magic_instruct_75k
66,109
Write a Python function to convert a given date and time string from one format to another. The function should handle both standard and fractional date-time formats. The input date and time string will be in either `DATE_TIME_FORMAT` or `DATE_TIME_FORMAT_FRACTIONAL` format, and the output should be in the opposite for...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ" def convert_date_time_format(input_datet...
magic_instruct_75k
66,130
Write a Python function to process a given string and extract specific information based on certain conditions. The function should take a string `out` as input and perform the following tasks: 1. If the string contains the substring 'ansible_network_os=eos', set the variable `transport` to 'https' and `addnl_info` to ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, List def process_out(out: str) -> Tuple[str, str, List[str]]: """ Processes a given string to extract specific information based on certain conditions. Args: out (str): The input string to...
magic_instruct_75k
66,137
Write a Python function to create a label map for a computer vision task. The function should take a dictionary `train_label_name_mapping` and an integer `num_classes` as input and return a NumPy array `label_map`. Each index in the `label_map` array represents a class label, and the value at each index should be the m...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Dict def create_label_map(train_label_name_mapping: Dict[str, int], num_classes: int) -> np.ndarray: """ Create a label map for a computer vision task. Args: train_label_name_m...
magic_instruct_75k
66,161
Write a Python function to initialize a game state based on a provided dictionary of key-value pairs. The game state includes attributes such as `current_player`, `current_turn`, `game_objects`, and `intern_cap`. Each attribute can have different types of values. The function should validate the keys and types of the v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any, Union def initialize_game_state(game_state_dict: Dict[str, Any]) -> Dict[str, Union[str, int, list, float]]: """ Initialize the game state based on the provided dictionary of key-value pairs. ...
magic_instruct_75k
66,178
Write a Python function to determine whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. The function should return `True` if the input string is a palindrome and `False` otherwise. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Determines whether a given string is a palindrome. Args: s (str): The input string to check. Returns: bool: True if the input string is a palindrome, False otherwi...
magic_instruct_75k
66,180
Write a Python function to generate a command that updates the `/etc/hosts` file on a target machine with the IP address and hostname of a deployed node using Juju, a cloud orchestration tool. The function should take three parameters: the IP address of the deployed node, the hostname of the deployed node, and the mach...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_hosts_update_command(juju_node_ip: str, juju_node_hostname: str, juju_deploy_machine: str) -> str: """ Generates a command to update the /etc/hosts file on a target machine with the IP address and hostname of a depl...
magic_instruct_75k
66,188
Write a Python function to calculate the total build time required for a specific improvement in a city-building simulation game. The function should take into account the game speed and era modifiers. The game speed can be "Quick", "Standard", or "Epic", and the start era can be "Ancient", "Classical", "Medieval", "Re...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_total_build_time(improvement_id: int, game_speed_type: str, start_era: str) -> int: """ Calculate the total build time required for a specific improvement in a city-building simulation game. Args: impr...
magic_instruct_75k
66,189
Create a Python function to manage the output section of a software application. The function should allow setting and retrieving file names and output titles. The function should simulate the behavior of the `OutputSection` class in the given code snippet. The code should start with: ```python def set_file_name(file_...
Here is the Python code to solve the given problem in the markdown block: ```python # Global variables to simulate class members file_name_global = "" output_title_global = "Default Output Title" def set_file_name(file_name: str) -> None: """ Simulates setting the file name for the output section. Args: ...
magic_instruct_75k
66,224
Write a Python function to find the name of the stock with the minimum number of shares in a given portfolio. The portfolio is represented as a list of dictionaries, where each dictionary contains the keys `'name'` and `'shares'`. The function should return the name of the stock with the minimum number of shares. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def find_min_shares_stock(portfolio: List[Dict[str, int]]) -> str: """ Finds the name of the stock with the minimum number of shares in the given portfolio. Args: portfolio (List[Dict[...
magic_instruct_75k
66,234
Write a Python function to extract panel headings from a given HTML code string. The HTML code contains multiple panel divs, each with a `panel-heading` div that contains the heading text. The function should return a list of these headings in the order they appear in the HTML code. 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 import re def extract_panel_headings(html_code: str) -> List[str]: """ Extracts panel headings from the given HTML code string. Args: html_code (str): The HTML code string from which to extr...
magic_instruct_75k
66,257
Write a Python function to simulate a simplified version of a card game. The function should perform the following actions: 1. **Initialize the deck of cards**: Create a list representing a standard deck of playing cards. Each card should be represented as a string in the format "value-suit", where "value" can be "2" ...
Here is the Python code to solve the given problem in the markdown block: ```python import random from typing import List def simulate_card_game(num_cards: int) -> List[str]: """ Simulates a simplified card game by initializing a deck of cards, shuffling it, and dealing a specified number of cards. Args: ...
magic_instruct_75k
66,311
Write a Python function to determine whether a given positive integer `num` is an ugly number. An ugly number is defined as a positive integer whose prime factors are limited to 2, 3, and 5. The function should return `True` if `num` is an ugly number, and `False` otherwise. The code should start with: ```python def i...
Here is the Python code to solve the given problem in the markdown block: ```python def is_ugly_number(num: int) -> bool: """ Determines whether a given positive integer is an ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Args: num (int): The...
magic_instruct_75k
66,324
Write a Python function to convert a time duration string into seconds. The time duration string will be in the format of a number followed by a unit specifier, where the unit specifier can be one of the following: 's' for seconds, 'm' for minutes, 'h' for hours, 'd' for days, 'w' for weeks, or 'y' for years. The funct...
Here is the Python code to solve the given problem in the markdown block: ```python import re def convert_to_seconds(val: str) -> int: """ Converts a time duration string into seconds. The time duration string should be in the format of a number followed by a unit specifier, where the unit specifier c...
magic_instruct_75k
66,349
Write a Python function to convert a time from 12-hour AM/PM format to 24-hour format. The input time is a string in the format "HH:MM:SSAM" or "HH:MM:SSPM", where HH is the hour (01 to 12), MM is minutes (00 to 59), and SS is seconds (00 to 59). The function should return a string in the format "HH:MM:SS" representing...
Here is the Python code to solve the given problem in the markdown block: ```python def timeConversion(s: str) -> str: """ Converts a time from 12-hour AM/PM format to 24-hour format. Args: s (str): A string representing the time in 12-hour format "HH:MM:SSAM" or "HH:MM:SSPM". Returns: ...
magic_instruct_75k
66,402
Write a Python function to process a list of database migration operations and extract specific information from it. The list contains tuples representing dependencies between two database migrations, and a list of migration operations. Each migration operation is represented as an instance of a migration class, which ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def extract_migration_info(dependencies: List[Tuple[str, str]], operations: List) -> Dict[str, Dict[str, str]]: """ Extracts specific information from a list of database migration operations...
magic_instruct_75k
66,405
Write a Python function to parse and extract specific attributes from a given SVG (Scalable Vector Graphics) code snippet. The SVG code snippet is represented as a string and contains attributes such as `stroke-linejoin`, `xmlns`, `height`, `viewBox`, `width`, and `path`. Your task is to create a function that extracts...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import re def parseSVGAttributes(svgCode: str) -> Dict[str, str]: """ Parses and extracts specific attributes from a given SVG code snippet. Args: svgCode (str): The SVG code snippet from wh...
magic_instruct_75k
66,414
Write a Python function to count the number of members in each team based on a list of team assignments. Each team assignment is represented by a tuple containing the team name and the member's name. The function should return a dictionary where the keys are the team names and the values are the number of members in ea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def count_team_members(assignments: List[Tuple[str, str]]) -> Dict[str, int]: """ Counts the number of members in each team based on a list of team assignments. Args: assignment...
magic_instruct_75k
66,430
Write a Python function to determine whether a given `datetime` object falls within a specified time range. The function should take three arguments: the `datetime` object to be checked, the lower bound of the time range, and the upper bound of the time range. The function should return `True` if the `datetime` object ...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def is_within_range(dt: datetime, lower_bound: datetime, upper_bound: datetime) -> bool: """ Determines whether a given datetime object falls within a specified time range. Args: dt (d...
magic_instruct_75k
66,447
Write a Python function to determine if a system is unhealthy based on a series of health measurements and a given unhealthy threshold. The system is considered unhealthy if the number of consecutive unhealthy measurements (represented by the value `0`) equals or exceeds the unhealthy threshold. The function should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_system_unhealthy(health_measurements: List[int], unhealthy_threshold: int) -> bool: """ Determine if the system is unhealthy based on a series of health measurements and a given unhealthy threshol...
magic_instruct_75k
66,461
Refactor the given code snippet to optimize its efficiency and reduce time complexity. The original code contains nested loops iterating over a large range of values, which is inefficient. The goal is to achieve the same functionality with improved performance. The code should start with: ```python def optimize_nested...
Here is the Python code to solve the given problem in the markdown block: ```python def optimize_nested_loops(): """ Optimizes the given code snippet by reducing time complexity and improving efficiency. The original code contains nested loops iterating over a large range of values, which is inefficient. ...
magic_instruct_75k
66,469
Write a Python function to reverse the order of words in a given string. The function should take a string as input and return a new string with the words reversed. For example, if the input string is "hello world", the function should return "world hello". The code should start with: ```python def reverse_words(s: st...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words(s: str) -> str: """ Reverses the order of words in a given string. Args: s (str): The input string containing words to be reversed. Returns: str: A new string with the words in reverse...
magic_instruct_75k
66,475
Write a Python function to filter a list of software tools used in digital forensics and incident response, returning only the tools whose names start with the letter "p". The function should be case-insensitive, meaning it should consider both uppercase and lowercase "p" as the same. The function should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_tools(tools: List[str]) -> List[str]: """ Filters a list of software tools, returning only those whose names start with the letter "p". Args: tools (List[str]): A list of strings ...
magic_instruct_75k
66,494
Write a Python function to automate the encryption and upload of JSON files to an AWS S3 bucket using AWS Encryption CLI and AWS KMS for key management. The function should take a directory path as input and perform the following steps for each JSON file in the directory: 1. Encrypt the JSON file using AWS Encryption C...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import os def encrypt_and_upload_json_files(directory_path: str): """ Automates the encryption and upload of JSON files to an AWS S3 bucket using AWS Encryption CLI and AWS KMS. Args: directory_pa...
magic_instruct_75k
66,497
Write a Python function to calculate the new speed of a vehicle after applying a reduction factor. The reduction factor is a constant value of 0.5, meaning the new speed will be half of the initial speed. The function should take the initial speed as a parameter and return the new speed. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_new_speed(initial_speed: float) -> float: """ Calculate the new speed of a vehicle after applying a reduction factor. The reduction factor is a constant value of 0.5, meaning the new speed will be half of the ...
magic_instruct_75k
66,506
Write a Python function to generate a multi-FASTA file from a given list of converted phylogenetic sequences. The function should take the converted sequences as input and produce a multi-FASTA file containing the sequences in the specified format. The function should be named `multifasta_file_generator` and should hav...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multifasta_file_generator(converted_sequences_phylogenetic: List[str]) -> str: """ Generates a multi-FASTA file content from a given list of converted phylogenetic sequences. Args: conve...
magic_instruct_75k
66,514
Write a Python function to convert a packed struct to an unpacked struct and vice versa. The structs are represented as dictionaries in Python. The packed struct has a single integer field `X`, and the unpacked struct also has a single integer field `X`. The task is to ensure that the conversion between these two repre...
Here is the Python code to solve the given problem in the markdown block: ```python def pack_struct(unpacked_struct: dict) -> dict: """ Convert an unpacked struct to a packed struct. Args: unpacked_struct (dict): A dictionary representing the unpacked struct with a single integer field 'X'. Re...
magic_instruct_75k
66,528
Write a Python function to process vehicle status changes based on a given input. The function should take in a list of vehicle documents and update their status and reference document name based on certain conditions. Each vehicle document is represented as a dictionary with the following keys: "vehicle_id", "vehicle_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_vehicle_status(vehicle_docs: List[Dict[str, str]], action: str) -> List[Dict[str, str]]: """ Processes vehicle status changes based on the given action. Args: vehicle_docs ...
magic_instruct_75k
66,535
Write a Python function to process a dictionary containing information about guides and their respective pages. The dictionary is represented as a string and needs to be evaluated to be used in the program. The function should then iterate through the guides and their pages to display their values and keys. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def process_guides(text: str) -> None: """ Processes a dictionary containing information about guides and their respective pages. The dictionary is represented as a string and needs to be evaluated to be used in the program....
magic_instruct_75k
66,544
Write a Python function to generate a random matrix with specified dimensions and values within a given range. The function should take in the dimensions of the matrix and the range for the random values, and return the generated matrix. The code should start with: ```python import numpy as np def generate_random_mat...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_matrix(rows: int, cols: int, value_range: tuple) -> np.ndarray: """ Generates a random matrix with specified dimensions and values within a given range. Args: rows (int): The ...
magic_instruct_75k
66,556
Write a Python function to validate the structure of a given dictionary representing an API endpoint's metadata. The metadata dictionary should adhere to a specific format, and your function should verify whether it meets the required structure. The metadata dictionary should contain the following keys: - 'tags': A li...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_metadata(metadata: dict) -> bool: """ Validates the structure of a given dictionary representing an API endpoint's metadata. Args: metadata (dict): The dictionary to validate. Returns: bool...
magic_instruct_75k
66,565
Write a Python function to evaluate a given Reverse Polish Notation (RPN) expression. The function should take a list of strings representing the RPN expression, where each string is either an operand (an integer represented as a string) or an operator ("+", "-", "*", "/"). The function should return the result of the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def evaluateRPN(tokens: List[str]) -> int: """ Evaluate a given Reverse Polish Notation (RPN) expression. Args: tokens (List[str]): A list of strings representing the RPN expression. ...
magic_instruct_75k
66,570
Write a Python function to automate the process of running unit tests for a given repository. The function should perform the following steps: 1. Clone the specified repository from GitHub. 2. Navigate into the cloned repository directory. 3. Install any necessary dependencies required for running the unit tests. 4. Ex...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import os def run_unit_tests(repo_url: str, repo_name: str) -> None: """ Automates the process of running unit tests for a given repository. Args: repo_url (str): The URL of the repository to clon...
magic_instruct_75k
66,575
Write a Python function to simulate a simplified network attack setup based on provided parameters. The function should validate the input parameters and simulate the attack by printing the attack details. The function should handle the optional command parameter and print it if provided. The function should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Optional import re def simulate_network_attack(interface: str, attacker_ip: str, victim_ip: str, gateway_or_host_ip: str, command: Optional[str] = None) -> None: """ Simulate a network attack setup based on p...
magic_instruct_75k
66,595
Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should efficiently handle both positive and negative integers. The code should start with: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: """ Find the maximum sum of a contiguous subarray within the given list of integers. Args: nums (List[int]): The list of integers from which to ...
magic_instruct_75k
66,618
Write a Python function to process an image represented as a 2D array of pixels, where each pixel is a list of four integers representing red, green, blue, and alpha (transparency) values. The function should modify the color of each pixel based on a given key input. The key input can be one of the following characters...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_image(image: List[List[List[int]]], key: str) -> List[List[List[int]]]: """ Process an image by modifying the color of each pixel based on a given key input. Args: image (List[Li...
magic_instruct_75k
66,670
Write a Python function to find the coordinates of all terminal states in a given 2D numpy array. The terminal states are marked with a specific value (e.g., 1), and non-terminal states are marked with another value (e.g., 0). The function should return a list of tuples, where each tuple represents the coordinates of a...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List, Tuple def find_terminal_states_coordinates(terminals: np.ndarray) -> List[Tuple[int, int]]: """ Find the coordinates of all terminal states in a given 2D numpy array. Args: ...
magic_instruct_75k
66,671
Write a Python function to implement a simplified event handling system. The system should allow registration of event handlers and dispatching of events to the registered handlers. The function should include the following methods: - `register_handler`: Registers a handler function for a specific event ID. - `unregist...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, Dict, Set, List class EventSystem: def __init__(self): """ Initialize the EventSystem with an empty dictionary to store event handlers. """ self.event_handlers: Dict[int,...
magic_instruct_75k
66,687
Write a Python function to process a given dictionary and return a new dictionary with specific key-value pairs based on certain conditions. The input dictionary will contain information about a project owner and their ID. Your task is to extract the owner's ID and create a new dictionary with the extracted ID as the v...
Here is the Python code to solve the given problem in the markdown block: ```python def process_project_owner(data: dict) -> dict: """ Processes a given dictionary and returns a new dictionary with specific key-value pairs. Args: data (dict): The input dictionary containing information about a proj...
magic_instruct_75k
66,696
Write a Python function to clean an input string by removing all occurrences of the string "NaN" and any leading or trailing whitespace. If the input string is `None`, it should be treated as an empty string. The function should be named `clean_string` and should adhere to the following specifications: Function Signat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Optional def clean_string(s: Optional[str]) -> str: """ Cleans the input string by removing all occurrences of "NaN" and any leading or trailing whitespace. If the input string is `None`, it returns an em...
magic_instruct_75k
66,710
Write a Python function to determine the platform architecture of the system, specifically whether it is running on a 32-bit or 64-bit architecture. The function should utilize the `platform` module to gather system information and make the determination. The function should be robust and handle different operating sys...
Here is the Python code to solve the given problem in the markdown block: ```python import platform def determine_platform_architecture() -> str: """ Determine the platform architecture of the system, specifically whether it is running on a 32-bit or 64-bit architecture. Returns: str: A string ind...
magic_instruct_75k
66,712
Write a Python function to implement a custom data structure called `MinStack` that supports the following operations efficiently: 1. `push(val: int)`: Add an integer `val` to the top of the stack. 2. `pop()`: Remove the top element from the stack. 3. `get_min()`: Retrieve the minimum value from the stack. The `MinSta...
Here is the Python code to solve the given problem in the markdown block: ```python class MinStack: """ A custom stack data structure that supports efficient push, pop, and get_min operations. Attributes: stack (list): A list to store the elements of the stack. min_stack (list): A list to k...
magic_instruct_75k
66,713
Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should handle both positive and negative integers. The code should start with: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: """ Find the maximum sum of a contiguous subarray within the given list of integers. Args: arr (List[int]): The list of integers from which to fi...
magic_instruct_75k
66,730
Write a Python function to efficiently add a number to a list and return the reversed list. The function should ensure that the addition and reversal operations are performed efficiently. The code should start with: ```python from typing import List def add_and_reverse(num: int, lead: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def add_and_reverse(num: int, lead: List[int]) -> List[int]: """ Efficiently adds a number to a list and returns the reversed list. Args: num (int): The number to be added to the list. ...
magic_instruct_75k
66,759
Write a Python function to resolve dependencies for a build system by merging an initial list of dependencies with a list of additional artifacts. The function should ensure that there are no duplicate entries in the final list of dependencies. The function should start with: ```python from typing import List def reso...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def resolve_dependencies(dependencies: List[str], additional_artifacts: List[str]) -> List[str]: """ Resolves dependencies for a build system by merging an initial list of dependencies with a list of...
magic_instruct_75k
66,781
Write a Python function to identify and return the common elements between two lists of strings, `all_tables` and `uniq_tables`, in sorted order. The function should be named `common_tables` and should take two parameters: `all_tables` and `uniq_tables`. The function should return a list of strings that are present in ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def common_tables(all_tables: List[str], uniq_tables: List[str]) -> List[str]: """ Identify and return the common elements between two lists of strings, `all_tables` and `uniq_tables`, in sorted order. ...
magic_instruct_75k
66,787
Write a Python function to generate Django URL patterns for a given set of view names. The function should take a list of view names and return a list of URL patterns that include these views. Each URL pattern should be in the format `path('url/', views.view_name, name='view_name')`, where `'url/'` is the URL, `views.v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_url_patterns(view_names: List[str]) -> List[str]: """ Generates Django URL patterns for a given list of view names. Args: view_names (List[str]): A list of view names for which ...
magic_instruct_75k
66,797
Write a Python function to process a dictionary containing information about various neural network models. The function should take this dictionary as input and return a new dictionary with the model names as keys and the corresponding model classes as values. If a model class is not found for a particular model name,...
Here is the Python code to solve the given problem in the markdown block: ```python def process_model_dict(model_dict: dict) -> dict: """ Processes a dictionary of neural network models and returns a new dictionary with model names as keys and their corresponding model classes as values. Model classes t...
magic_instruct_75k
66,809
Write a Python function to calculate the total number of ways to reach the top of a staircase with `n` steps, where you can either take one step or two steps at a time. The function should be efficient and handle large inputs. The code should start with: ```python def count_ways_to_reach_top(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_ways_to_reach_top(n: int) -> int: """ Calculate the total number of ways to reach the top of a staircase with `n` steps, where you can either take one step or two steps at a time. Args: n (int): The to...
magic_instruct_75k
66,814
Write a Python function `prep` that processes a given string according to the following specifications: 1. Remove any leading and trailing whitespace from the input string. 2. Convert the input string to lowercase. 3. Replace any occurrence of the substring "python" with "programming". 4. Return the processed string. ...
Here is the Python code to solve the given problem in the markdown block: ```python def prep(line: str) -> str: """ Processes a given string by removing leading and trailing whitespace, converting it to lowercase, and replacing any occurrence of the substring "python" with "programming". Args: ...
magic_instruct_75k
66,816
Write a Python function to construct a command-line string based on the provided parameters. The function should take three parameters: `timeout_secs`, `exec_timeout_secs`, and `evergreen_config_file_path`. The function should return a string that represents the constructed command-line with the provided parameters. T...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_command_line(timeout_secs: int, exec_timeout_secs: int, evergreen_config_file_path: str) -> str: """ Constructs a command-line string based on the provided parameters. Args: timeout_secs (int): The tim...
magic_instruct_75k
66,867
Write a Python function to filter a dictionary containing URLs as keys and a list of related URLs and keywords as values. The function should return a new dictionary containing only the URLs that have a specific keyword in their related list. The function signature should be: ```python def filter_urls_by_keyword(url_d...
Here is the Python code to solve the given problem in the markdown block: ```python def filter_urls_by_keyword(url_dict: dict, keyword: str) -> dict: """ Filters a dictionary of URLs based on a specific keyword present in their related list. Args: url_dict (dict): A dictionary where keys are URLs a...
magic_instruct_75k
66,876
Write a Python function `train_and_predict` that interacts with a machine learning platform API to train a model, make predictions, and monitor the status of the training and prediction jobs. The API client `c` provides methods for training, getting job output, making predictions, and checking job status. The function ...
Here is the Python code to solve the given problem in the markdown block: ```python def train_and_predict(c, train_data, test_data): """ Interacts with a machine learning platform API to train a model, make predictions, and monitor job statuses. Args: c: An instance of the API client for the machin...
magic_instruct_75k
66,885
Implement a Python function to write the elements of a list to a binary file in a custom format. Each element in the list should be written as a 32-bit integer in binary format. The function should handle the conversion of integers to their binary representation and write them to the specified file. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import struct def write_list_to_binary_file(elements: List[int], file_path: str) -> None: """ Writes the elements of a list to a binary file in a custom format. Each element is written as a 32-bit in...
magic_instruct_75k
66,899
Write a Python function to manage the guest list for a VIP event. The function should handle the following tasks: 1. Accept two lists as input: one for VIP guests and one for regular guests. 2. Print the names of the VIP guests. 3. Sort the list of regular guests in alphabetical order and print the names. The function...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def manage_guest_list(vip_guests: List[str], regular_guests: List[str]) -> None: """ Manages the guest list for a VIP event by printing the VIP guests and sorting and printing the regular guests. Ar...
magic_instruct_75k
66,909
Write a Python function to calculate the total scores of each round in a game where the score of each player is the sum of their scores in the current and the previous round. If a player has no previous round, their score is just the score of the current round. The function should handle edge cases such as an empty inp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_total_scores(scores: List[int]) -> List[int]: """ Calculate the total scores of each round in a game where the score of each player is the sum of their scores in the current and the pre...
magic_instruct_75k
66,914
Write a Python function to calculate the total balance for a specific account based on a list of transactions. Each transaction is represented as a dictionary with the keys "account", "amount", and "type". The "account" key holds the account number, the "amount" key holds the transaction amount, and the "type" key hold...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_balance(transactions: List[Dict[str, str]], account_number: str) -> int: """ Calculate the total balance for a specific account based on a list of transactions. Args: tra...
magic_instruct_75k
66,919
Write a Python function to retrieve the URL pattern associated with a given URL name from a predefined dictionary of URL patterns. If the URL name is not found in the dictionary, the function should return "URL not found". The function should be designed to work with a Django-like URL configuration system. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python def get_url_pattern(url_name: str) -> str: """ Retrieves the URL pattern associated with the given URL name from a predefined dictionary. Args: url_name (str): The name of the URL pattern to retrieve. Returns: ...
magic_instruct_75k
66,925
Write two Python functions to check the presence of a key in a dictionary. The first function, `key_not_in_dictionary`, should return `True` if the key is not present in the dictionary, and `False` otherwise. The second function, `key_in_dictionary`, should return `True` if the key is present in the dictionary, and `Fa...
Here is the Python code to solve the given problem in the markdown block: ```python def key_not_in_dictionary(dictionary: dict, key: str) -> bool: """ Check if a key is not present in the given dictionary. Args: dictionary (dict): The dictionary to check for the key. key (str): The key to c...
magic_instruct_75k
66,955
Write a Python function to calculate the total number of reported crimes across all states given a dictionary where the keys are state names and the values are the corresponding number of reported crimes. The function should return the total number of reported crimes. The code should start with: ```python from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def calculate_total_crimes(crime_data: Dict[str, int]) -> int: """ Calculate the total number of reported crimes across all states given a dictionary of state-wise crime data. Args: crime_da...
magic_instruct_75k
66,963
Write a Python function to count the occurrences of each type of database migration operation in a given list of operations. Each operation is represented as a tuple, where the first element is the operation type and the second element is the model or field it applies to. The function should return a dictionary where t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def count_migration_operations(operations: List[Tuple[str, str]]) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation in a given list of operations. ...
magic_instruct_75k
66,999
Write a Python function to automate the reformatting and committing of code files in a given directory. The function should find all files in the specified directory that match the pattern "mg_*", reformat them using the `clang-format` tool, and then commit the changes to a git repository with a specific commit message...
Here is the Python code to solve the given problem in the markdown block: ```python import os import subprocess from typing import List def reformat_and_commit(directory_path: str) -> None: """ Automates the reformatting and committing of code files in a given directory. Args: directory_path (str)...
magic_instruct_75k
67,012
Write a Python function to generate the nth row of Pascal's Triangle. Pascal's Triangle is a triangular array of binomial coefficients, where each number is the sum of the two directly above it in the previous row. The function should be optimized to use only O(k) extra space, where k is the number of elements in the o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_pascals_triangle_row(n: int) -> List[int]: """ Generate the nth row of Pascal's Triangle. Pascal's Triangle is a triangular array of binomial coefficients, where each number is the ...
magic_instruct_75k
67,018
Write a Python function to analyze the frequency of words in a given text. The function should take a string of text as input and output a dictionary containing the frequency of each word in the text. Words should be treated as case-insensitive and any punctuation marks should be ignored. The output dictionary should b...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import string def word_frequency(text: str) -> Dict[str, int]: """ Analyzes the frequency of words in a given text and returns a dictionary with the frequency of each word. Words are treated as case-...
magic_instruct_75k
67,019
Write a Python function to manipulate a dictionary representing a person's information. The function should perform one of the following operations based on the input: 1. **Add** a new key-value pair to the dictionary. 2. **Update** the value of an existing key in the dictionary. 3. **Remove** a key-value pair from the...
Here is the Python code to solve the given problem in the markdown block: ```python def modify_person_info(person: dict, operation: str, key: str, value=None) -> dict: """ Modifies the person's information dictionary based on the specified operation. Args: person (dict): The initial dictionary repr...
magic_instruct_75k
67,020
Write a Python function to calculate the length of a sequence `F` for a given integer `n`. The sequence `F` is defined as follows: - Start with the integer `n`. - If the current integer is even, divide it by 2. - If the current integer is odd, multiply it by 3 and add 1. - Repeat the above steps until the integer becom...
Here is the Python code to solve the given problem in the markdown block: ```python def solve(n: int) -> int: """ Calculate the length of the sequence `F` for a given integer `n`. The sequence `F` is defined as follows: - Start with the integer `n`. - If the current integer is even, divide it by 2....
magic_instruct_75k
67,032
Write a Python function to determine the file type based on its extension. The function should take a file extension as input and return the corresponding file type. The file type should be one of the following: "text", "image", "audio", "video", or "unknown". The file extensions and their corresponding file types are ...
Here is the Python code to solve the given problem in the markdown block: ```python def getFileTypeByExtension(extension: str) -> str: """ Determine the file type based on its extension. Args: extension (str): The file extension (e.g., ".txt", ".jpg"). Returns: str: The file type, whic...
magic_instruct_75k
67,039
Write a Python function to determine if there exists a path from the top-left corner to the bottom-right corner of a given maze represented by a 2D list of integers. The maze contains open paths (represented by 0) and walls (represented by 1). The function should return a boolean value indicating whether such a path ex...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def navigate_maze(maze: List[List[int]]) -> bool: """ Determines if there is a path from the top-left corner to the bottom-right corner of a given maze. Args: maze (List[List[int]]): A 2D li...
magic_instruct_75k
67,040
Write a Python function to clean and process distance data, and then perform specific operations based on a given character input. The function should: 1. Clean the distance data by rounding each distance to the nearest integer. 2. Perform different operations based on the value of a character input `ch`: - If `ch` ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def clean_dist(D: List[float]) -> List[int]: """ Cleans the distance data by rounding each distance to the nearest integer. Args: D (List[float]): A list of distances to be cleaned. Ret...
magic_instruct_75k
67,080
Write a Python function to calculate the average of a list of floating-point numbers and round it to a specified number of decimal places. The function should handle edge cases such as an empty list and invalid input for the number of decimal places. The code should start with: ```python from typing import List def c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average(numbers: List[float], decimal_places: int) -> float: """ Calculate the average of a list of floating-point numbers and round it to the specified number of decimal places. Args:...
magic_instruct_75k
67,100
Write a Python function to generate a spiral pattern of numbers within a square grid of given size. The grid should be filled with consecutive integers starting from 1 in a clockwise direction. The function should return a 2D list representing the spiral pattern. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_spiral_pattern(size: int) -> List[List[int]]: """ Generate a spiral pattern of numbers within a square grid of the given size. Args: size (int): The size of the square grid. ...
magic_instruct_75k
67,102
Implement a Python function to simulate the `lookup.getGroupFromNames` function for a smart home automation application. The function should search through a list of device groups to find the group that contains a specified phone controller device. If the group is found, return the group name; otherwise, return `None`....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def get_group_from_names(phone_name: str, groups: List[List[str]]) -> Optional[str]: """ Searches through a list of device groups to find the group containing a specified phone controller devic...