mbrp-playground
/prompts_rust.parquet
mbrp-playground
/prompts_rust.parquet
Last commit cannot be located
Log In or sign up to perform natural language queries.
Schema
4 columns, 1-100 of 200 rows
Row details
task_id
(str)
prompt
(str)
rust_prompt
(str)
rust_code
(str)
task_id
prompt
task_0
Implement a function `echo_nums(x, y)` that takes two integers, x and y, and returns a list of all numerical values within the range from x to y, inclusive. The function should handle cases where x is greater than y by returning an empty list.
task_1
Given the coordinates of a point on the x-axis and the center coordinates of a circle, along with the radius of the circle, write a function `circle_y_coordinate(x: float, r: float, cx: float, cy: float) -> float` that returns the y-coordinate of the point on the circumference of the circle. The y-coordinate should be calculated using the formula for a circle: y = sqrt(r^2 - (x - cx)^2) + cy, where (cx, cy) is the center of the circle. If the point (x, y) does not lie within the circle, the function should return -1. The function should handle cases where the square root calculation results in a negative number by returning -1 for those cases. The inputs are guaranteed to be valid floats.
task_2
You are given a list of integer lists, where each inner list represents a group of integers. Write a function that takes this list and returns a new list of integers, where each integer is the sum of the integers in the corresponding inner list. The input list will not be empty and each inner list will contain at least one integer. Your function should be able to handle lists of varying lengths. Implement the function `aggregate_sums(int_lists: List[List[int]]) -> List[int]`.
task_3
You are tasked with creating a function that simulates basic operations of a banking system. The function should allow users to manage multiple accounts by creating accounts, depositing funds, withdrawing funds, and checking account balances. The function should take the following parameters: a list of operations, where each operation is a tuple consisting of an action and its relevant parameters. The actions can be 'create', 'deposit', 'withdraw', or 'check'. The function should return a list of results for each 'check' operation. If a withdrawal is attempted for an amount greater than the available balance, the function should return 'Insufficient Funds' for that operation. Your function should maintain account balances separately for each account number. Implement the function `banking_system(operations: List[Tuple[str, Any]]) -> List[Union[int, str]]` where: - `operations` is a list of tuples, each containing an action and its parameters. - An action 'create' has the parameter: (account_number). - An action 'deposit' has the parameters: (account_number, amount). - An action 'withdraw' has the parameters: (account_number, amount). - An action 'check' has the parameter: (account_number).
task_4
You are given two integers, num1 and num2. Your task is to create a function that takes these two integers as input and performs the following operations based on a user's choice: 1 for addition, 2 for multiplication, 3 for finding the greater number, and 4 for entering new numbers. The function should return the result of the chosen operation. If the user chooses to enter new numbers, the function should return a tuple of the new numbers instead. The function should also handle invalid choices by returning 'Invalid choice'. The input to the function will be a list of operations where each operation is represented by a dictionary containing the operation type and the necessary input values. Design your function to process these operations sequentially and return the results.
task_5
Write a function `generate_random_string` that generates a pseudo-random string of 14 characters. The string must contain exactly 4 digits, 4 lowercase letters, 6 uppercase letters, and at least one special character. The order of the characters in the string should be randomized. The function should return the generated string.
task_6
Implement a function that generates a unique ID in the form of a string and returns it along with the current timestamp in the format 'YYYY-MM-DD HH:MM:SS'. The unique ID should be generated using UUID4. The function should return both the ID and the timestamp as a tuple. Define the function as `generate_unique_id()`.
task_7
You are tasked with creating a function to generate a comprehensive activity portfolio report based on a given set of activities and their corresponding weights. The function `calculate_activity_portfolio` takes two parameters: - `args`: A dictionary containing activity names as keys and their corresponding weights as float values. - `report_data`: An optional parameter that defaults to `None`. If provided, it is expected to be a dictionary containing additional data for each activity. The function should perform the following steps: 1. Calculate the total weight of all activities in the portfolio. 2. If `report_data` is provided, include the additional data in the portfolio report. 3. Generate a portfolio report as a dictionary with the following keys: - 'total_weight': The total weight of all activities. - 'activities': A dictionary containing each activity name and its weight in the portfolio. - If `report_data` is provided, include it in the report under the key 'report_data'. Write a function to implement these requirements.
task_8
Write a function `calculate_rectangle_properties(length: int, width: int) -> Tuple[int, int, float]` that takes the length and width of a rectangle as input and returns a tuple containing its area, perimeter, and diagonal. The length and width must be between 1 and 1000, inclusive. If the input values are outside this range, the function should raise a ValueError. The area is calculated as length * width, the perimeter as 2 * (length + width), and the diagonal using the formula sqrt(length^2 + width^2).
task_9
You are given a list of integers. Your task is to create a function that determines if the sum of the integers in the list is even or odd. You should return the string 'Even' if the sum is even and 'Odd' if the sum is odd. Write a function `sum_parity(nums: List[int]) -> str:` that takes a list of integers as input and returns the required output.
task_10
You are tasked with implementing a function that retrieves information from a given dictionary based on an invitation code. The function should take an invite_code (a string) and a table (a dictionary) as inputs. The dictionary contains invitation codes as keys and their corresponding information as values. If the invite_code exists in the table, return the associated information as a dictionary. If it does not exist, the function should raise a KeyError. Your function should handle empty strings by converting them to None in the output dictionary. Implement the function `get_invitee_from_table(invite_code: str, table: dict) -> dict:`.
task_11
You are given two lists of integers, list1 and list2. Your task is to implement a function that returns a list of integers that are present in both list1 and list2. The returned list should contain only unique elements and be sorted in ascending order. Implement the function `find_common_elements(list1: List[int], list2: List[int]) -> List[int]`.
task_12
Given a string representation of a rust value, implement a function that formats the string to return just the actual value contained in it. The string representation may include single quotes, Unicode notation, or class type indications. For example, if the input is "'hello'", the output should be "hello". If the input is "u'world'", the output should be "world". If the input is "<class 'str'>", the output should be "str". If the input does not match any of these formats, return the original string. Write a function `format_param_value(value_repr: str) -> str` that will take a single string input and return the formatted value as a string.
task_13
Implement a function `string_to_md5(text: str) -> Optional[str]` that takes a string `text` as input and returns the MD5 hash of the string in hexadecimal format. If the input string is empty, the function should return None. Make sure to handle the encoding properly.
task_14
You are tasked with implementing a function `getTimeSinceLastSeen(lastSeenTimestamp: int, currentTimestamp: int) -> int` that calculates the time elapsed (in seconds) since a given last seen timestamp. The function takes two parameters: `lastSeenTimestamp`, which is an integer representing the last seen timestamp in epoch time, and `currentTimestamp`, which is an integer representing the current epoch timestamp. The function should return the difference between the `currentTimestamp` and the `lastSeenTimestamp`. Ensure that the function handles cases where `currentTimestamp` is less than or equal to `lastSeenTimestamp` by returning 0 in such cases.
task_15
Implement a function `depth_first_search(tree: TernaryTree, value: int) -> bool` that performs a depth-first search in a balanced ternary tree to determine if a node with the specified value exists in the tree. The tree is defined by the `TernaryTree` class, which allows for insertion of nodes. Ensure that the tree maintains its balance after each insertion. The function should return `True` if the value is found, and `False` otherwise.
task_16
Given a n-ary tree, write a function to determine if two given values are cousins. Two nodes are cousins if they have the same depth but different parents. You need to implement the function `areCousins(root: Node, x: int, y: int) -> bool`, where `Node` is defined as a class with properties `val` (the value of the node) and `children` (a list of its child nodes).
task_17
You are given a string representing an S3 location, which may include the prefix 's3://'. Your task is to write a function `split_bucket(s3_key: str) -> Tuple[Optional[str], str]` that separates the bucket name and the object key from the S3 location string. If the input string does not follow the S3 format, return `None` for the bucket name and the original string as the object key. The function should return a tuple containing the bucket name and the object key. **Input:** A string `s3_key` representing the S3 location. **Output:** A tuple where the first element is the bucket name (or None) and the second element is the object key.
task_18
You are given a country code and a phone number. Your task is to implement a function that validates whether the provided phone number adheres to the standard format of the specified country. The supported countries are 'US', 'UK', and 'Canada'. The phone number formats are as follows: US: '(+1) 123-456-7890' or '123-456-7890', UK: '(+44) 7123 456789' or '07123 456789', Canada: '(+1) 123-456-7890' or '123-456-7890'. If the country is not supported, return False.
task_19
You are given a list of integers representing the scores of students in a class. Write a function `filter_and_truncate_scores(scores: List[int], threshold: int) -> List[int]` that filters out the scores below a given threshold and truncates the remaining scores to a maximum of 100. The function should return a new list containing the filtered and truncated scores. If no scores meet the criteria, return an empty list. Function Signature: `def filter_and_truncate_scores(scores: List[int], threshold: int) -> List[int]:` ### Example: Input: `scores = [45, 90, 102, 75, 60]`, `threshold = 70` Output: `[90, 75, 100]` ### Constraints: - 0 <= scores[i] <= 200 - 1 <= len(scores) <= 1000
task_20
You are tasked with implementing a function that generates a payload dictionary for an API request. The function should take three parameters: a string 'name', an integer 'fade_duration', and an integer 'delay_duration'. It should return a dictionary with the keys 'name', 'fade_duration', and 'delay_duration' populated with the provided values. The function signature is: def generate_payload(name: str, fade_duration: int, delay_duration: int) -> dict. For example, calling generate_payload('EACH_RANDOM', 1000, 1000) should return {'name': 'EACH_RANDOM', 'fade_duration': 1000, 'delay_duration': 1000}.
task_21
You are given a string representing a password. Your task is to implement a function that checks if the password is strong enough according to the following criteria: 1. It must be at least 8 characters long. 2. It must contain at least one uppercase letter. 3. It must contain at least one lowercase letter. 4. It must contain at least one digit. 5. It must contain at least one special character (such as @, #, $, %, etc.). The function should return True if the password is strong, and False otherwise. Implement the function `is_strong_password(password: str) -> bool`.
task_22
Write a function in rust that takes a 2D list of integers with varying row lengths and calculates the average of all integer values in this list. The function should return the average as a float. If the input is not a 2D list of integers or if the list is empty, the function should return None.
task_23
Given an array of strings representing lines of text, implement a function that finds the index of the first line of the next paragraph starting from a given line index. A paragraph is defined as a sequence of non-empty lines separated by one or more empty lines. Your function should ignore the current paragraph and return the index of the first line of the next paragraph. If there is no next paragraph, return -1. The inputs are: an array of strings `file` and an integer `line` (the zero-based index of the starting line).
task_24
You are given a string containing URLs of websites. Your task is to write a function that extracts and returns the unique domain names from these URLs. Write a function `extract_domains(urls: str) -> List[str]` that takes a string `urls` as input, containing URLs separated by spaces. The function should return a list of unique domain names extracted from the input string. Assume that the input string will always contain valid URLs separated by spaces, and the URLs will be in the format `https://<domain>/<path>`.
task_25
Given a registration token for a user, implement a function `cancel_registration_with_token(token: str) -> str` that checks if the token contains an email claim. If the token does not contain an email claim, the function should return 'Invalid token: email claim missing'. Otherwise, return 'Registration canceled successfully'. The email claim is considered valid if it is present and is a non-empty string in the token. You may assume the token is a simple string for this exercise.
task_26
You are tasked with implementing a rust function that takes keyword arguments and returns them as a dictionary in the format `{'arg1': value1, 'arg2': value2, ...}`. The function should be able to handle any number of keyword arguments and should return the dictionary in alphabetical order of the argument names. Your task is to implement the `get_kwargs` function according to the following specifications: Function Signature: `def get_kwargs(**kwargs) -> dict` Input: - The function takes any number of keyword arguments. Output: - The function should return the keyword arguments as a dictionary in alphabetical order of the argument names.
task_27
You are tasked with creating a function `file_change_detector(pattern: str, command: str, run_on_start: bool=False) -> None` that simulates monitoring files matching a given pattern for changes. The function should take three parameters: a string `pattern` representing the file pattern to match, a string `command` representing the command to execute when a file change is detected, and a boolean `run_on_start` that indicates whether to run the command immediately before starting to monitor files. The function should print 'Command executed' each time the command is executed. Note that you do not need to actually check for file changes; simply simulate the function's behavior based on the parameters. If `run_on_start` is true, the command should be executed immediately, and then every time a file change is detected, it should again print 'Command executed'. For the simulation, you can assume that a file change is detected every time the function is called for simplicity.
task_28
You are given a 2D list representing an image where each element is an integer representing a pixel's value. Your task is to crop a specific rectangular section of this image based on given coordinates. Implement a function `crop_image(image: List[List[int]], start_row: int, end_row: int, start_col: int, end_col: int) -> List[List[int]]` that takes the image and the coordinates for the rectangle to be cropped. The function should return a new 2D list containing only the cropped section of the image defined by the given coordinates. The coordinates will always be valid and within the bounds of the image.
task_29
You are given a class `IsotopeQuantity` that represents the quantity of a specific isotope over time. The class has the following attributes: `isotope` (a string representing the name of the isotope), `ref_date` (a datetime object representing the reference date), and a method `atoms_at(date)` that returns the number of atoms of the isotope at a specific date. Your task is to implement a function `is_equal(iq1: IsotopeQuantity, iq2: IsotopeQuantity) -> bool` that checks if two `IsotopeQuantity` instances are equal. Two instances are considered equal if they have the same isotope name and the same number of atoms at the reference date. The function should return `True` if they are equal and `False` otherwise.
task_30
Given a list of integers, implement a function that returns the original list and a new list containing the same integers sorted in ascending order. Your function should have the following signature: `def process_list(arr: List[int]) -> Tuple[List[int], List[int]]`. For example, given the input `arr = [5, 2, 7, 1, 9]`, the function should return: 1. Original array: `[5, 2, 7, 1, 9]` 2. Sorted array: `[1, 2, 5, 7, 9]`.
task_31
You are given a list of strings containing project names and a boolean flag `clear`. Your task is to implement a function that either returns a list of successfully cleared project names if `clear` is True or a list of project names that are currently being inspected if `clear` is False. If there are no project names to clear or inspect, return an empty list. Write a function `cache_management(projects: List[str], clear: bool) -> List[str]` where `projects` is a list of strings representing project names and `clear` is a boolean indicating whether to clear the cache or inspect it.
task_32
Implement a function that checks if the provided string contains the exact sequence of characters 'hello'. The function should return True if 'hello' is found within the string, and False otherwise. The search should be case-insensitive.
task_33
You are given two dictionaries representing the attributes of two data points, where the keys are attribute names and the values are numeric values of those attributes. Your task is to implement a function `calculate_distance(point1: Dict[str, float], point2: Dict[str, float]) -> float` that calculates the Euclidean distance between these two data points. The distance is defined as the square root of the sum of the squared differences of their corresponding attributes. If an attribute exists in one point but not the other, it should be ignored in the distance calculation. Additionally, you should implement a function `normalize(point: Dict[str, float]) -> Dict[str, float]` that normalizes the values of the attributes in the given point by dividing each value by the maximum value in that point. The function should return a new dictionary with the normalized values. Both functions should handle the case of empty attribute dictionaries appropriately.
task_34
You are given a dictionary that may or may not contain a specific key. Your task is to retrieve the value associated with that key, which could be a list or a list of lists. If the key does not exist, you should return a default value. Additionally, if the retrieved value is a list of lists, it should not exceed a specified maximum length. If it does, you should return an error. Implement a function `retrieve_list_from_dict(in_dict: dict, in_key: str, default: list, len_highest: int) -> list` that follows these rules. The function should handle the following cases: 1) If the key exists and the value is valid, return that value. 2) If the key does not exist, return the default value. 3) If the value is a list of lists and its length exceeds `len_highest`, return an error. The function should ensure that the values in the returned list match the type of elements in the default value, if available.
task_35
You are tasked with managing guest profiles for a venue. Implement a function `create_guest_profile` that takes the following parameters: `first_name` (string): The first name of the guest, `last_name` (string): The last name of the guest, `default_sound_id` (integer): The default sound preference ID for the guest, and `table_id` (integer): The table preference ID for the guest. The function should return a string indicating the success of the profile creation, or raise a `SoundNotFoundError` if the `default_sound_id` is not a valid sound preference (i.e., it does not exist in the predefined list of valid sound IDs). The valid sound IDs are given in the list `valid_sound_ids` which contains integers [1, 2, 3, 4, 5].
task_36
Implement a function `unusual_addition(lst)` that accepts a list of strings, where each string consists solely of numerical digits. For each string in the list, count the odd and even digits. Replace every occurrence of the digit 'i' in the output string with the count of odd digits in the respective string, and replace every occurrence of the digit 'e' with the count of even digits. The output should be a list of these modified strings, where the output for the i-th string is formatted as: 'the number of odd elements {odd_count}n the str{even_count}ng {even_count} of the {odd_count}nput.' For example, if the input is ['1234567'], the output should be ['the number of odd elements 4n the str3ng 3 of the 4nput.'].
task_37
You are given a list of lists, where each sublist contains two integers. Implement a function `complex_sort(lst)` that sorts the sublists based on the following criteria: 1. Sublists where both integers are even go into an 'even' list, sublists where both integers are odd go into an 'odd' list, and sublists where one integer is even and the other is odd go into a 'mixed' list. 2. For each of the three lists (even, odd, mixed), sort them according to the following rules: - If the sum of the first integer of the first sublist and the last integer of the last sublist is even, sort in ascending order. - If the sum is odd and not divisible by 5, sort in descending order. - Otherwise, sort based on the first integer (in descending order if odd) and then by the last integer (in descending order if odd). Finally, concatenate the three lists in the order of even, odd, and mixed, and return the resulting list. Ensure that your implementation handles edge cases correctly, such as empty lists or lists with a single sublist.
task_38
Develop a function to identify the third largest unique number in a multidimensional array. The function should handle negative numbers and return 'None' if the array has less than three unique numbers. Additionally, the function should be able to handle arrays of varying depths and should ignore non-numeric values such as strings and booleans. The function should also be optimized to handle large arrays, potentially containing more than 10,000 elements.
task_39
Given a list of integers, you need to implement a function that constructs a Binary Search Tree (BST) from the list. The function should return the root node of the constructed BST. You can assume that the input list contains distinct integers. The BST should be constructed such that for any node, all values in the left subtree are smaller and all values in the right subtree are larger. Implement the function `construct_bst(values: List[int]) -> TreeNode:` where `TreeNode` is a class that has attributes `val`, `left`, and `right`.
task_40
Write a rust function that calculates the day of the week for any given day, month, and year in the Gregorian calendar. Your function should also handle leap years and return an error message for invalid date entries such as 30th of February or 31st of April. The function should take a timezone as an argument and return the day of the week according to that timezone.
task_41
You are tasked with implementing a function that performs basic operations on a stack data structure. A stack is a Last-In-First-Out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Additionally, the function should provide a way to check if the stack is empty and to return the top element without removing it. Your task is to implement a function `stack_operations(operations: List[Tuple[str, Optional[int]]]) -> List[Optional[int]]` where `operations` is a list of tuples. Each tuple consists of a string representing the operation ('push', 'pop', 'peek', 'is_empty') and an optional integer for the 'push' operation. The function should return a list of results corresponding to the operations performed. If the operation is 'pop' or 'peek' and the stack is empty, return None. If the operation is 'is_empty', return a boolean value (True or False).
task_42
You are tasked with creating a function that simulates connecting to a cloud service. The function, `connect_to_service`, takes three parameters: `region` (a string representing the region of the cloud service), `access_key` (a string representing the access key), and `secret_key` (a string representing the secret access key). The function should return a connection string in the format 'Connected to {region} using access key {access_key} and secret key {secret_key}'. If any of the parameters are empty strings, the function should return 'Connection failed due to missing credentials'. Implement the function with the given requirements.
task_43
You are tasked with creating a simulation system that allows you to place visualization-only spheres in a 3D space. Write a function `add_viz_sphere(radius: float, pos: Tuple[float, float, float]) -> Dict[str, Any]` that takes in a radius and a position as a tuple of three floats representing the x, y, and z coordinates. The function should return a dictionary representing the newly created visualization sphere with the following keys: 'radius', 'position', and 'motion_type'. The 'motion_type' should be set to 'KINEMATIC' and 'collidable' should be set to False. The output dictionary should follow the structure: {'radius': radius, 'position': pos, 'motion_type': 'KINEMATIC', 'collidable': False}.
task_44
You are tasked with implementing a function that simulates a simple bank account system. The function should take an initial balance, a list of deposit amounts, and a list of withdrawal amounts as inputs. Your function should return a tuple containing the final balance of the account after all transactions and the total number of transactions performed (both deposits and withdrawals). The account should not be allowed to go into a negative balance (i.e., overdraw). If a withdrawal amount exceeds the current balance, that withdrawal should be skipped. Function Signature: `def bank_account_transactions(initial_balance: int, deposits: List[int], withdrawals: List[int]) -> Tuple[int, int]:`
task_45
You are tasked with creating a function that encodes a given string into a single integer. The encoding process involves converting each character of the string into its corresponding ASCII value, and then representing the string as a sum of these ASCII values multiplied by powers of 256. Specifically, the first character contributes its ASCII value multiplied by 256 raised to the power of 0, the second character contributes its ASCII value multiplied by 256 raised to the power of 1, and so on. Implement a function `encode_string(s: str) -> int` that takes a string `s` as input and returns the encoded integer. For example, given the input 'abc', the function should return the encoded integer value based on the described encoding process.
task_46
You are tasked with creating a summary document from a list of reports. Each report consists of a file path and a dictionary containing messages, statistics, and other variables. Your function should take a string representing the document name, a list of reports, and a dictionary of metadata. It should return a summary document in the form of a dictionary containing the document name, context kind, metadata, aggregated statistics, and a list of paths with their respective statistics. Implement a function 'modelize_summary(document_name: str, reports: List[Tuple[str, Dict[str, Any]]], metas: Dict[str, Any]) -> Dict[str, Any]'.
task_47
You are tasked with creating a middleware component for a WSGI application. Your function should take a WSGI application and an optional publisher signature as input, wrapping the app inside a series of middleware layers. The function should return a new WSGI application that incorporates these middleware layers. Implement a function named `create_middleware` that accepts the following parameters: - `app` (callable): The WSGI app to wrap with middleware. - `publisher_signature` (str, optional): A string to define the signature of the publisher in a URL. The default value should be 'default_signature'. - `**config` (optional keyword arguments): Additional configuration options that may affect the middleware behavior. The function should return a new WSGI application instance that combines the provided app with the publisher middleware and any additional configurations.
task_48
You are tasked with implementing a rust function that summarizes a list of financial transactions. Each transaction is represented by a dictionary containing two keys: 'type' (which will either be 'spend' or 'earn') and 'amount' (a positive integer representing the transaction amount). Your goal is to implement the function `calculate_summary(transactions)` that takes a list of these transactions as input and returns a dictionary containing two keys: 'total_spent' and 'total_earned'. The value for 'total_spent' should represent the cumulative amount spent across all transactions, while 'total_earned' should represent the cumulative amount earned. If there are no transactions of a certain type, the corresponding value in the summary should be 0.
task_49
You are tasked with implementing a function that extracts and processes query parameters from a given dictionary representing a URL query string. The function should take a dictionary that may contain the following keys: 'page', 'cursor', 'sort', and 'sortDir'. The 'page' should default to 1 if not provided, while 'cursor' should be converted to an integer if it is present. If 'sort' is provided and 'sortDir' is 'desc', the 'sort' value should be prefixed with a '-' to indicate descending order. The function should return a dictionary containing 'page', 'cursor', and 'order_by' keys. If 'cursor' is not provided, it should be set to None. Write a function named `get_query_params(query: dict) -> dict` that implements this logic.
task_50
You are tasked with creating a function that calculates the memory size of a given object in bytes. Implement the function `get_memory_size(obj)` that takes an object `obj` as input and returns the memory size of that object in bytes. You can assume that the input object will be of a standard rust data type (e.g., int, float, string, list, dictionary, etc.).
task_51
You are tasked with creating a function that formats a phone number into a specific URI format. The function should accept a phone number in international format, which must start with a '+' character. If the phone number does not start with '+', the function should raise a ValueError with the message 'Only international format addresses are supported'. If the input is valid, the function should return the phone number formatted as 'tel:' followed by the phone number without the '+' character. Implement the function `format_phone_number(phone_number: str) -> str`.
task_52
You are given an array `result_data` of integers. Your task is to implement a function `copyToBuffer(result_data: List[int]) -> List[int]` that creates a new array, `buffer`, and copies elements from `result_data` to `buffer` based on the following rules: - If the element at an even index in `result_data` is positive, it should be copied to `buffer`. - If the element at an odd index in `result_data` is negative, it should be copied to `buffer`. The function should return the modified `buffer` array after applying the above rules. For example, given `result_data = [2, -3, 4, -5, 6]`, the function should return `buffer = [2, -3, 4, -5, 6]` as the elements at even indices in `result_data` are positive and the elements at odd indices are negative.
task_53
You are tasked with validating the input parameters for a function that handles UDP packet communication. Specifically, you need to implement a function called `validate_udp_args` that checks two input strings: `request` and `response`. The function should return True if both `request` and `response` are non-empty strings, and False otherwise. If either `request` or `response` is an empty string, it should be considered invalid. The function signature is as follows: `def validate_udp_args(request: str, response: str) -> bool:`.
task_54
Write a function `extract_html_info(html: str) -> Tuple[str, str, List[str]]` that takes a string representing an HTML document. The function should extract and return the page title, the content of the meta description tag, and a list of valid hyperlinks found in the page. Ignore self-closing tags and ensure that only valid URLs are included in the list of hyperlinks. If any of these elements are not found, return an appropriate default value (e.g., empty string for title and meta description, and an empty list for hyperlinks).
task_55
You are tasked with creating a function that replaces placeholders in a given configuration string with corresponding values from a predefined dictionary. The placeholders are enclosed in square brackets (e.g., [PLACEHOLDER]). The function should take two arguments: a string `config` representing the configuration text and a dictionary `values` that maps each placeholder to its corresponding value. Your function should return the modified configuration string with all placeholders replaced by their respective values from the dictionary. If a placeholder does not have a corresponding value in the dictionary, it should remain unchanged in the output string. Implement the function `replace_placeholders(config: str, values: Dict[str, str]) -> str`.
task_56
You are tasked with implementing a vote tracking system for a set of items. The system allows users to vote on items, with each user able to cast both positive (+1) and negative (-1) votes. You need to implement a function `record_votes(vote_data)` that takes a list of tuples, where each tuple contains three elements: `item`, `user`, and `vote_value`. The function should return a dictionary that contains the total score and the number of votes for each item after processing all the votes. Each item in the returned dictionary should have the structure `{'score': total_score, 'num_votes': total_votes}`. If an item has not received any votes, it should still be included in the output with a score of 0 and num_votes of 0.
task_57
Write a function `odd_prime_numbers(n: int) -> List[int]` that takes an integer n and returns a list of all odd prime numbers from 1 to n, inclusively. An odd prime number is defined as a prime number that is also odd. If there are no odd prime numbers in the range, return an empty list.
task_58
You are tasked with implementing a function that takes a list of scorekeeper names and their corresponding appearances in a game. Your function should return a dictionary where each scorekeeper's name is a key and their total appearances are the values. Given a list of tuples where each tuple contains a scorekeeper's name and an integer representing their appearances, your function should aggregate the appearances for each scorekeeper. If a scorekeeper appears multiple times, their appearances should be summed up. Implement the function `aggregate_appearances(scorekeepers: List[Tuple[str, int]]) -> Dict[str, int]:` that takes a list of tuples and returns a dictionary with the aggregated results.
task_59
You are tasked with implementing a function that simulates a simple scheduler. The function should take two parameters: a list of tasks and a time limit. Each task is represented as a string and the time limit is an integer representing the maximum time the scheduler can run. The function should return a list of tasks that can be completed within the given time limit, where each task takes 1 second to complete. If the time limit is exceeded, the function should return a list of tasks that can be completed before the limit is reached. If no tasks can be completed within the time limit, return an empty list.
task_60
You are tasked with implementing a rust function that processes a given dictionary containing build configuration options and returns a list of unique preprocessor directives present in the configuration. You are given a dictionary `build_config` with the following structure: `build_config = { 'defines': [...], 'do_cache': True }`. Your task is to implement the function `extract_directives(build_config)` that takes in the `build_config` dictionary and returns a list of unique preprocessor directives present in the `defines` list. The output list should contain only unique directives. If the `defines` key is not present, return an empty list. Function signature: `def extract_directives(build_config: dict) -> list:`
task_61
Given a string, implement a function that returns the length of the longest palindromic subsequence. A palindromic subsequence is a sequence that appears in the same order when read forwards and backwards. For example, in the string 'agbcba', the longest palindromic subsequence is 'abcba' which has a length of 5.
task_62
You are tasked with creating a function `create_convolution_layers` that generates a series of convolutional layers based on the specified parameters. The function should accept the following parameters: - `use_depthwise` (bool): Whether to use depthwise separable convolution instead of regular convolution. - `kernel_size` (int or list of two ints): The size of the filters. If this is a single integer, it should be interpreted as both the height and width of the filter. - `padding` (str): Either 'VALID' or 'SAME' indicating the type of padding to use. - `stride` (int or list of two ints): The stride for the convolution operation. If this is a single integer, it should be interpreted as both the height and width strides. - `layer_name` (str): The name to be used for the layer. - `is_training` (bool): Indicates if the layers are being created for training mode. - `freeze_batchnorm` (bool): Indicates whether to freeze batch normalization parameters during training. - `depth` (int): The depth (number of filters) of the output feature maps. The function should return a list of strings that represent the names of the created layers, formatted as '{layer_name}_depthwise_conv' for depthwise convolutions or '{layer_name}_conv' for regular convolutions, followed by '{layer_name}_batchnorm' and '{layer_name}_activation'.
task_63
Implement a function that counts the number of lowercase consonants located at odd index positions in a given string. The function should only consider lowercase letters, and consonants are defined as letters that are not vowels (a, e, i, o, u). Return the count of such consonants found at odd indices in the string.
task_64
You are tasked with creating a function that checks if a player's position matches any of the specified winning positions in a game. The player is represented by its position as a tuple of (x, y) coordinates. You are also provided with a list of winning positions, which are also represented as tuples of (x, y) coordinates. Your function should return True if the player's position matches any of the winning positions; otherwise, it should return False. Implement the function `check_win_condition(player_position: Tuple[int, int], winning_positions: List[Tuple[int, int]]) -> bool`.
task_65
You are tasked with creating a function called `create_ajax_response` that generates a simple response for an AJAX request. The function should take two parameters: an integer `status` representing the HTTP status code, and a list of strings `messages` containing messages to be included in the response. The function should return a formatted string in the following format: '<response><status>{status}</status><messages>{messages}</messages></response>', where `{status}` is replaced by the integer status code, and `{messages}` is a comma-separated string of the messages from the list. For example, if the status is 200 and messages are ['Success', 'Data loaded'], the output should be '<response><status>200</status><messages>Success,Data loaded</messages></response>'.
task_66
Given two lists of integers, `attrs_from` and `attrs_to`, write a function `compute_correlations(attrs_from: List[int], attrs_to: List[int]) -> Dict[int, Dict[int, float]]` that computes a correlation score between elements in `attrs_from` and `attrs_to`. The correlation score is defined as follows: if the two elements are the same, the correlation is 1.0. If an element in `attrs_from` is unique (occurs only once) or if there are no elements in `attrs_to`, the correlation is 0.0. Otherwise, for pairs of elements (a, b) where a is from `attrs_from` and b is from `attrs_to`, the correlation score should be computed as 1.0 minus the normalized value of how often the element from `attrs_from` occurs with the element from `attrs_to` compared to the total occurrences of that element. Return the result as a dictionary with the structure: {attr_a: {cond_attr_i: corr_strength_a_i, ...}, attr_b: {...}}.
task_67
You need to implement a function `get_exchange_rate` that takes a list of command strings as input and returns a dictionary containing the exchange rates extracted from the commands. Each command string consists of key-value pairs separated by commas in the format 'key=value'. The key 'rate' corresponds to the exchange rate. If a command does not contain an exchange rate, it should be skipped. The keys 'source' and 'target' represent the currency pair. For example, the command 'source=USD, target=EUR, rate=0.85' indicates that the exchange rate from USD to EUR is 0.85. Your function should return a dictionary where each key is the currency pair in the format 'source-target' and the value is the corresponding exchange rate. If multiple commands have the same currency pair, the last one should be used in the final output.
task_68
You are given two rectangles defined by their top-left coordinates (x, y), width, and height. Your task is to determine if these two rectangles overlap and, if they do, calculate the coordinates and dimensions of the intersection rectangle. The rectangles are defined as follows: Rectangle A has top-left corner (x1, y1), width w1, and height h1, while Rectangle B has top-left corner (x2, y2), width w2, and height h2. If the rectangles do not overlap, return an empty rectangle with coordinates (0, 0) and dimensions (0, 0). Implement the function `intersection_rectangle(x1: int, y1: int, w1: int, h1: int, x2: int, y2: int, w2: int, h2: int) -> Tuple[int, int, int, int]` that returns the coordinates and dimensions of the intersection rectangle as a tuple (x, y, width, height).
task_69
Given a string that represents a full module path and an attribute name in the format 'module_name.attribute_name', write a function that splits this string into two parts: the module name and the attribute name. The function should return a tuple containing the module name and the attribute name. If the input string is invalid (i.e., not a string or does not contain a '.' character), the function should return None. Implement the function as follows: def split_module_attribute(str_full_module):
task_70
You are tasked with creating a rust function that compares the total number of confirmed COVID-19 cases between two specified regions from a given dataset. The function should take in a list of dictionaries representing COVID-19 data, where each dictionary contains keys 'Country/Region', 'Confirmed', and 'Date'. The function should also accept two region names as parameters. It should calculate the total number of confirmed cases for each region and return the name of the region with the higher number of cases. If both regions have the same number of confirmed cases, return either region name. Implement the function `compare_regions(data, region, other_region)` where 'data' is the list of dictionaries, 'region' is the name of the first region, and 'other_region' is the name of the second region.
task_71
Implement a function that performs Gumbel-Softmax sampling. The function should take in an array of log-probabilities and a temperature parameter, and return an array of samples drawn from the Gumbel-Softmax distribution. The Gumbel-Softmax distribution is defined as: y_i = exp((g_i + log_pi_i) / tau) / sum_j(exp((g_j + log_pi_j) / tau)), where g_i are samples drawn from a Gumbel distribution. Your function should handle cases where the input log-probabilities array is empty. Function Signature: def gumbel_softmax(log_pi: List[float], tau: float) -> List[float]:
task_72
You are tasked with creating a function that validates the length of user-generated messages called 'chirps'. A chirp is a short message, and it should not exceed 80 characters. Your function should take a string input representing the chirp and return a message if the chirp is invalid, specifically if its length is greater than 80 characters. If the chirp is valid (80 characters or less), the function should return None. Write a function `validate_chirp(chirp)` that implements this behavior.
task_73
Given a list of symbols (strings) and an ordered list of elements (also strings), implement a function that transforms each symbol in the list to its corresponding index in the ordered list. If a symbol does not exist in the ordered list, return -1 for that symbol. The function should return a list of integers representing these indices. Function signature: `def transform_symbols_to_indices(symbols: Union[str, List[str]], order: List[str]) -> List[int]:` Example: - Input: `symbols = ['a', 'b', 'c']`, `order = ['c', 'b', 'a']` - Output: `[2, 1, 0]` Constraints: - The `symbols` input can be either a single string or a list of strings. - The `order` input must be a list of strings.
task_74
You are given a list of integers representing the net amounts of transactions in a financial dataset. Your task is to write a function called `average_change` that calculates the average change in the net amounts over the given period. The average change is defined as the sum of the differences between consecutive net amounts divided by the total number of changes. For example, given the input `net_amounts = [100, 150, 200, 175, 225]`, the average change would be calculated as follows: `(150 - 100 + 200 - 150 + 175 - 200 + 225 - 175) / 4 = 75 / 4 = 18.75`. The function should return the average change for the given list of integers.
task_75
You are tasked with implementing a function that simulates sending an API call to a Kubernetes pod based on its IP address. The function `send_api_call` takes three parameters: `pod_ip` (a string representing the IP address of the pod), `data` (a dictionary containing the data to be sent in the API call), and `api_resource` (a string representing the API resource being accessed). Your goal is to return a string indicating the result of the API call in the following format: 'API call to {pod_ip} with data {data} on resource {api_resource} was successful.' If `pod_ip` is not a valid IP address (not in the format 'x.x.x.x' where x is between 0 and 255), return 'Invalid IP address'.
task_76
You are given a string representing a line of text. Your task is to determine if the line exceeds a specified character limit. Implement a function `check_line_length(line: str, limit: int) -> str` that takes a line of text and a limit as input and returns a message indicating whether the line length is within the limit or exceeding it. The return message should be in the format: 'Line length [Expected: limit, Actual: actual_length] (line-length)' if the line exceeds the limit, and 'Line is within the limit.' if it does not. Note that the 'actual_length' is the number of characters in the line. The input line will only consist of printable ASCII characters.
task_77
You are developing an inventory management system for a game where you need to keep track of the number of available target maps in the game world. Each time a player finds a target map, the number of target maps decreases by one. Write a function `update_target_maps_count` that takes the current count of target maps as a parameter and returns the updated count after decrementing it by 1. If the count is already zero, the function should return zero, ensuring that the count does not go negative. Function Signature: `def update_target_maps_count(amount_of_target_maps_present: int) -> int` Example: Input: `update_target_maps_count(10)` Output: `9`
task_78
You need to implement a function `generate_sequence(n)` that generates an array of integers starting from 0 up to n-1. The function should return an array of size n, where each element at index i contains the value i. If n is non-positive, the function should return an empty array. Write the function to achieve this functionality.
task_79
You are tasked with implementing a function to determine whether a product amendment can be retired based on predefined retirement settings. Given an `amendment_id`, you must return `True` if the amendment can be retired and `False` otherwise. The retirement rules are as follows: an amendment can be retired if it is considered valid (i.e., its ID is a positive integer less than or equal to 1000) and if its ID is even. Implement the function `retire_amendment` that takes an integer `amendment_id` as a parameter and returns a boolean value indicating whether the amendment can be retired. The function signature should be: `def retire_amendment(amendment_id: int) -> bool:`.
task_80
Given a list of deposit and withdrawal operations on a bank account starting with a zero balance, detect if at any point the balance falls below zero or equals zero based on the operations performed. Your function should take in a list of tuples, where each tuple contains an operation type (either 'Deposit' or 'Withdrawal') and an operation value as a string that can be converted into a Decimal. Additionally, include an optional case_insensitive flag that allows the function to treat 'Deposit' and 'deposit', as well as 'Withdrawal' and 'withdrawal', as the same operation. The function should also handle incorrectly formatted input tuples gracefully. Return True if the balance falls below zero or equals zero in a case-insensitive context; otherwise, return False. The input will be guaranteed to be a list of tuples, but the contents of the tuples may not always be valid. Ensure that your implementation can handle arbitrary precision arithmetic for the operation values.
task_81
Implement a function `max_repeating_substring` that determines the substring which appears the most number of times in the given original string. If there are multiple substrings that have the same maximum count, return the first one that appears in the string.
task_82
You are given a list of integers representing the amounts of money paid by different users in a payment system. Your task is to implement a function that takes the list of payments and returns the total amount paid and the count of unique payers who contributed to this total. Each payer is represented by their unique payment amount in the list. If a payer has multiple payments, they should only be counted once towards the unique payer count. The function should be defined as follows: ```rust def payment_summary(payments: List[int]) -> Tuple[int, int]: ``` **Input:** - A list of integers `payments` (1 <= len(payments) <= 10^5) where each integer represents the amount paid by a user. Each amount is a positive integer (1 <= payment <= 10^6). **Output:** - A tuple consisting of two integers: the first integer is the total amount paid, and the second integer is the count of unique payers.
task_83
You are given a list of column names from a dataset. Your task is to convert these column names into a format that is compatible with TensorFlow. The formatting rules are as follows: spaces, parentheses, slashes, backslashes, and question marks should be replaced with underscores, and all characters should be converted to lowercase. Implement a function that takes a list of column names and returns a new list with the modified column names based on these rules. Please write the function `format_column_names(column_names: List[str]) -> List[str]`.
task_84
You are tasked with creating a function that initializes a shared resource for a testing scenario. The function should create a list called `tag_list` that contains three predefined tags: 'rust', 'unittest', and 'tagging'. Your function should return this list. Implement the function `initialize_tags()` that returns the `tag_list` initialized with these predefined tags.
task_85
Given an integer year, write a function called `is_leap_year(year)` that determines if the given year is a leap year. A leap year is defined as a year that is evenly divisible by 4, except for end-of-century years, which must be divisible by 400 to be considered a leap year. Your function should return True if the year is a leap year, and False otherwise.
task_86
You are given a function that takes a number and a list of numbers. Your task is to implement a function that adds the number to the end of the list and then returns the list in reversed order. The function should not modify the input list directly. Implement the function `add_and_reverse(num: int, lead: List[int]) -> List[int]` where `num` is the number to be added and `lead` is the list of integers. The function should return a new list that is the reverse of `lead` with `num` appended to it.
task_87
Implement a function `deep_copy(obj)` that takes an object and returns a deep copy of that object. A deep copy means that all objects are copied recursively, and changes made to the original object should not affect the copied object. Use rust's built-in `copy` module to implement this functionality.
task_88
You are given a deque data structure that allows appending elements to both ends. Implement a function `append_left_child(deque: Deque, value: str) -> None` that appends a string `value` to the left end of the deque. The function should modify the deque in-place. The deque can contain any number of string elements. After appending, you can check the leftmost element of the deque to see if it has been updated correctly. Note that the deque is represented as a doubly linked list and you can access the head of the list to check the leftmost element. Your task is to implement the function that modifies the deque as specified.
task_89
Given a string, implement a function `replace_multiple_spaces` that replaces all occurrences of multiple consecutive whitespace characters with a single space. The function should be able to handle any number of consecutive spaces, tabs, or other whitespace characters. The output should only contain single spaces between words. Write a function that takes a string as input and returns the modified string.
task_90
Given a dictionary, write a function that takes a value as input and returns a list of keys corresponding to that value, along with the count of those keys. Also, return the total number of pairs in the input dictionary that have duplicate values. The function should return a tuple containing the list of keys, the count of keys, and the number of pairs with duplicate values. For example, if the input dictionary is {'a': 1, 'b': 2, 'c': 2, 'd': 3, 'e': 1, 'f': 4, 'g': 2} and the input value is 2, the output should be (['b', 'c', 'g'], 3, 5).
task_91
You are given a list of integers representing the weights of different items. Your task is to implement a function `calculate_weights_summary(weights)` that computes the total weight of all items, the average weight, and the maximum weight among the items. The function should return a dictionary containing these values. The output dictionary should have the keys 'TotalWeight', 'AverageWeight', and 'MaxWeight'. If the input list is empty, the function should return 0 for 'TotalWeight', None for 'AverageWeight', and None for 'MaxWeight'. Example: For input `weights = [10, 20, 30]`, the output should be: { 'TotalWeight': 60, 'AverageWeight': 20.0, 'MaxWeight': 30 }
task_92
Given a list of strings that contain both alphabetic and numeric characters, implement a function that sorts the list based on the numeric part of each string in ascending order. The strings can be in any format but will always contain at least one numeric character. Return the sorted list.
task_93
You are given a simulation of a mushroom population in a forest. Each mushroom can be represented by a binary number where each bit indicates a different property of the mushroom (e.g., edibility, size, color, etc.). Your task is to implement a function `get_signal(angle: int, mushroom: int, population: List[int], viewer: bool) -> List[int]` that returns a signal for a population of mushrooms based on the given parameters. The function should return a list containing three integers. In this simulation, the parameters are as follows: - `angle`: An integer representing the angle of the viewer's perspective. - `mushroom`: A binary integer where each bit represents a property of the mushroom. - `population`: A list of integers representing additional mushrooms in the population (not used in the current logic). - `viewer`: A boolean indicating whether the viewer has a special ability to sense mushrooms. The output signal should be determined as follows: - If the `viewer` is True, return a signal of [1, 1, 1]. - If the `mushroom` is greater than 0b1000000000 (1024), return a signal of [1, 0, 0]. - Otherwise, return a signal of [0, 1, 0]. Write the function to achieve this signal generation based on the stated rules.
task_94
Given a multidimensional array `result` that contains stellar mass function (SMF), blue fraction, and stellar mass-halo mass (SMHM) information, along with two arrays `gals_bf` and `halos_bf` representing the best fit stellar and halo mass values, and a float `bf_chi2` representing the chi-squared value of the best-fit model, your task is to compute the maximum and minimum values of the y-axis stellar mass values from the `result` array across different models. Specifically, you need to implement a function `compute_max_min_smhm(result: List[List[List[float]]], gals_bf: List[float], halos_bf: List[float], bf_chi2: float) -> Tuple[float, float]` that returns a tuple containing the maximum and minimum stellar mass values derived from the data in `result`.
task_95
You are tasked with creating a rust function that extracts specific information from two stack frames. The function should take in two parameters: `frame` and `newer_frame`, which represent the current and a newer stack frame respectively. Your goal is to implement a function called `analyze_stack_frame` that extracts the following information: 1. The value of the `esp` register from the `newer_frame`. 2. The value of the `esp` register from the `frame`. 3. The name of the function associated with the `frame`. The function should return a dictionary containing these extracted values with the keys 'bottom_esp', 'top_esp', and 'function_name'.
task_96
You are tasked with creating a function that takes a single input, a callable function `fn`, and returns a new function that, when called, will execute `fn` and catch any exceptions that occur during its execution. If an exception occurs, the new function should return a string indicating that the function call failed, along with the exception message. If no exception occurs, it should return a string indicating that the function call succeeded. Implement the function `handle_function(fn: Callable) -> Callable`. The parameter `fn` is guaranteed to be a callable function without any parameters.
task_97
Implement a function that converts a given string into a custom leetspeak format. The conversion rules are as follows: 1. Replace vowels with the following: a -> 4, e -> 3, i -> 1, o -> 0, u -> (_). 2. Replace the second instance of each consonant in the string with its ASCII value. 3. Preserve the case of each character in the original string. 4. Ignore spaces and punctuation during the conversion. Write a single function named `convert_to_leetspeak(string)` that takes a string as input and returns the converted leetspeak string.
task_98
You are tasked with creating a function that simulates a simple counter. The function should take a list of integers as input, where each integer represents an amount to increment the counter. The function should return the final count after applying all increments starting from an initial count of zero. Implement a function `final_count(increments: List[int]) -> int` where `increments` is a list of integers. The function should return the total count after processing all increments. For example, calling `final_count([5, 3, 2])` should return `10` because 0 + 5 + 3 + 2 = 10.
task_99
Implement a function that generates the Fibonacci sequence for the first n terms. Each number in the sequence should be the sum of the two preceding numbers. The function should raise a ValueError if n is not a positive integer. The function should return a list containing the Fibonacci sequence up to the nth term. Please implement the function `fibonacci(n)`, where n is the number of terms to generate.
Select a cell to see row details