mbrp-playground
/prompts.parquet
Last commit cannot be located
Schema
2 columns, 1-100 of 20000 rows
Row details
task_id
(str)
rust_prompt
(str)
task_id
rust_prompt
task_0
Implement a function `echo_nums(x, y)` that takes two integers, `x` and `y`, and returns a vector 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 vector.
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: f32, r: f32, cx: f32, cy: f32) -> f32` 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 f32 numbers.
task_2
You are given a vector of integer vectors, where each inner vector represents a group of integers. Write a function that takes this vector and returns a new vector of integers, where each integer is the sum of the integers in the corresponding inner vector. The input vector will not be empty and each inner vector will contain at least one integer. Your function should be able to handle vectors of varying lengths. Implement the function `aggregate_sums(int_lists: Vec<Vec<i32>>) -> Vec<i32>`.
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 vector 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 vector 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: Vec<(String, Vec<String>)>) -> Vec<String>` where: - `operations` is a vector 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 vector of operations where each operation is represented by a struct 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 `HashMap` containing activity names as keys and their corresponding weights as `f32` values.
- `report_data`: An optional parameter that defaults to `None`. If provided, it is expected to be a `HashMap` 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 `HashMap` with the following keys:
- 'total_weight': The total weight of all activities.
- 'activities': A `HashMap` 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: i32, width: i32) -> (i32, i32, f32)` 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 return an error. The area is calculated as length * width, the perimeter as 2 * (length + width), and the diagonal using the formula (length.pow(2) + width.pow(2)).sqrt(). Use the `std::f32::consts::PI` for any mathematical constants if necessary, but in this case, you will use the `f32::sqrt` method for the square root.
task_9
You are given a vector of integers. Your task is to create a function that determines if the sum of the integers in the vector 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: Vec<i32>) -> String` that takes a vector of integers as input and returns the required output.
task_10
You are tasked with implementing a function that retrieves information from a given hash map based on an invitation code. The function should take an invite_code (a String) and a table (a hash map) as inputs. The hash map 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 hash map. If it does not exist, the function should return a None. Your function should handle empty strings by converting them to None in the output hash map. Implement the function `get_invitee_from_table(invite_code: String, table: HashMap<String, HashMap<String, String>>) -> Option<HashMap<String, String>>:`.
task_11
You are given two vectors of integers, `list1` and `list2`. Your task is to implement a function that returns a vector of integers that are present in both `list1` and `list2`. The returned vector should contain only unique elements and be sorted in ascending order. Implement the function `find_common_elements(list1: Vec<i32>, list2: Vec<i32>) -> Vec<i32>`.
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: String) -> String` that will take a single string input and return the formatted value as a string.
task_13
Implement a function `string_to_md5(text: String) -> Option<String>` 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 `get_time_since_last_seen(last_seen_timestamp: i32, current_timestamp: i32) -> i32` that calculates the time elapsed (in seconds) since a given last seen timestamp. The function takes two parameters: `last_seen_timestamp`, which is an integer representing the last seen timestamp in epoch time, and `current_timestamp`, which is an integer representing the current epoch timestamp. The function should return the difference between the `current_timestamp` and the `last_seen_timestamp`. Ensure that the function handles cases where `current_timestamp` is less than or equal to `last_seen_timestamp` by returning 0 in such cases.
task_15
Implement a function `depth_first_search(tree: TernaryTree, value: i32) -> 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` struct, 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 `are_cousins(root: Node, x: i32, y: i32) -> bool`, where `Node` is defined as a struct with properties `val` (the value of the node) and `children` (a vector 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: String) -> (Option<String>, String)` 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 vector of integers representing the scores of students in a class. Write a function `filter_and_truncate_scores(scores: Vec<i32>, threshold: i32) -> Vec<i32>` 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 vector containing the filtered and truncated scores. If no scores meet the criteria, return an empty vector.
Function Signature: `fn filter_and_truncate_scores(scores: Vec<i32>, threshold: i32) -> Vec<i32>:`
### Example:
Input: `scores = vec![45, 90, 102, 75, 60]`, `threshold = 70`
Output: `[90, 75, 100]`
### Constraints:
- 0 <= scores[i] <= 200
- 1 <= scores.len() <= 1000
task_20
You are tasked with implementing a function that generates a payload 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 map with the keys `name`, `fade_duration`, and `delay_duration` populated with the provided values. The function signature is: `fn generate_payload(name: String, fade_duration: i32, delay_duration: i32) -> std::collections::HashMap<String, i32>`. For example, calling `generate_payload(String::from("EACH_RANDOM"), 1000, 1000)` should return a map with the corresponding key-value pairs.
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: String) -> bool`.
task_22
Write a function in Rust that takes a 2D vector of integers with varying row lengths and calculates the average of all integer values in this vector. The function should return the average as a f32. If the input is not a 2D vector of integers or if the vector 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: a vector 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: String) -> Vec<String>` that takes a string `urls` as input, containing URLs separated by spaces. The function should return a vector 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: String) -> String` 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 HashMap in the format `{"arg1": value1, "arg2": value2, ...}`. The function should be able to handle any number of keyword arguments and should return the HashMap in alphabetical order of the argument names. Your task is to implement the `get_kwargs` function according to the following specifications:
Function Signature: `fn get_kwargs(...) -> HashMap<String, String>`
Input:
- The function takes any number of keyword arguments.
Output:
- The function should return the keyword arguments as a HashMap in alphabetical order of the argument names.
task_27
You are tasked with creating a function `file_change_detector(pattern: String, command: String, run_on_start: bool) -> ()` 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 vector 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: Vec<Vec<i32>>, start_row: i32, end_row: i32, start_col: i32, end_col: i32) -> Vec<Vec<i32>>` that takes the image and the coordinates for the rectangle to be cropped. The function should return a new 2D vector 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 struct `IsotopeQuantity` that represents the quantity of a specific isotope over time. The struct has the following fields: `isotope` (a String representing the name of the isotope), `ref_date` (a String representing the reference date), and a method `atoms_at(date: String) -> i32` 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 vector of integers, implement a function that returns the original vector and a new vector containing the same integers sorted in ascending order. Your function should have the following signature: `fn process_list(arr: Vec<i32>) -> (Vec<i32>, Vec<i32>)`.
For example, given the input `arr = vec![5, 2, 7, 1, 9]`, the function should return:
1. Original vector: `[5, 2, 7, 1, 9]`
2. Sorted vector: `[1, 2, 5, 7, 9]`.
task_31
You are given a vector of strings containing project names and a boolean flag `clear`. Your task is to implement a function that either returns a vector of successfully cleared project names if `clear` is true or a vector 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 vector. Write a function `cache_management(projects: Vec<String>, clear: bool) -> Vec<String>` where `projects` is a vector 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 hash maps 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: HashMap<String, f32>, point2: HashMap<String, f32>) -> f32` 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: HashMap<String, f32>) -> HashMap<String, f32>` 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 hash map with the normalized values. Both functions should handle the case of empty attribute hash maps appropriately.
task_34
You are given a HashMap that may or may not contain a specific key. Your task is to retrieve the value associated with that key, which could be a Vec or a Vec of Vecs. If the key does not exist, you should return a default value. Additionally, if the retrieved value is a Vec of Vecs, 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: HashMap<String, Vec<String>>, in_key: String, default: Vec<String>, len_highest: i32) -> Result<Vec<String>, String>` 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 Vec of Vecs 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` (i32): The default sound preference ID for the guest, and `table_id` (i32): The table preference ID for the guest. The function should return a String indicating the success of the profile creation, or panic with the message "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 vector `valid_sound_ids` which contains integers [1, 2, 3, 4, 5].
task_36
Implement a function `unusual_addition(lst)` that accepts a vector of strings, where each string consists solely of numerical digits. For each string in the vector, 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 vector 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 vec!["1234567"], the output should be vec!["the number of odd elements 4n the str3ng 3 of the 4nput."].
task_37
You are given a vector of vectors, where each inner vector contains two integers. Implement a function `complex_sort(lst)` that sorts the inner vectors based on the following criteria: 1. Inner vectors where both integers are even go into an 'even' vector, inner vectors where both integers are odd go into an 'odd' vector, and inner vectors where one integer is even and the other is odd go into a 'mixed' vector. 2. For each of the three vectors (even, odd, mixed), sort them according to the following rules: - If the sum of the first integer of the first inner vector and the last integer of the last inner vector 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 vectors in the order of even, odd, and mixed, and return the resulting vector. Ensure that your implementation handles edge cases correctly, such as empty vectors or vectors with a single inner vector.
task_38
Develop a function to identify the third largest unique number in a multidimensional vector. The function should handle negative numbers and return `None` if the vector has less than three unique numbers. Additionally, the function should be able to handle vectors of varying depths and should ignore non-numeric values such as strings and booleans. The function should also be optimized to handle large vectors, potentially containing more than 10,000 elements.
task_39
Given a vector of integers, you need to implement a function that constructs a Binary Search Tree (BST) from the vector. The function should return the root node of the constructed BST. You can assume that the input vector 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: Vec<i32>) -> TreeNode` where `TreeNode` is a struct that has fields `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: Vec<(String, Option<i32>)>) -> Vec<Option<i32>>` where `operations` is a vector 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 vector 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: f32, pos: (f32, f32, f32)) -> std::collections::HashMap<String, String>` 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 HashMap 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 HashMap should follow the structure: {'radius': String::from(radius), 'position': format!("{}, {}, {}", pos.0, pos.1, pos.2), 'motion_type': String::from('KINEMATIC'), 'collidable': String::from('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 vector of deposit amounts, and a vector 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: `fn bank_account_transactions(initial_balance: i32, deposits: Vec<i32>, withdrawals: Vec<i32>) -> (i32, i32):`
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: String) -> i32` 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: String, reports: Vec<(String, HashMap<String, String>)>, metas: HashMap<String, String>) -> HashMap<String, String>`.
task_47
You are tasked with creating a middleware component for a web application. Your function should take an application and an optional publisher signature as input, wrapping the app inside a series of middleware layers. The function should return a new application that incorporates these middleware layers. Implement a function named `create_middleware` that accepts the following parameters:
- `app` (Fn): The application to wrap with middleware.
- `publisher_signature` (String, optional): A string to define the signature of the publisher in a URL. The default value should be 'default_signature'.
- `config` (HashMap<String, String>, optional): Additional configuration options that may affect the middleware behavior.
The function should return a new 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 struct containing two fields: `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 vector of these transactions as input and returns a struct containing two fields: `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 HashMap representing a URL query string. The function should take a HashMap 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 HashMap 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: HashMap<String, String>) -> HashMap<String, String>` 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., i32, f32, String, Vec, HashMap, 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 return an error 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: String) -> Result<String, String>`.
task_52
You are given a vector `result_data` of integers. Your task is to implement a function `copy_to_buffer(result_data: Vec<i32>) -> Vec<i32>` that creates a new vector, `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` vector after applying the above rules.
For example, given `result_data = vec![2, -3, 4, -5, 6]`, the function should return `buffer = vec![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: `fn validate_udp_args(request: String, response: String) -> bool:`.
task_54
Write a function `extract_html_info(html: String) -> (String, String, Vec<String>)` 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 hash map. 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 hash map `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 hash map. If a placeholder does not have a corresponding value in the hash map, it should remain unchanged in the output string. Implement the function `replace_placeholders(config: String, values: HashMap<String, String>) -> String`.
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 vector of tuples, where each tuple contains three elements: `item`, `user`, and `vote_value`. The function should return a HashMap that contains the total score and the number of votes for each item after processing all the votes. Each item in the returned HashMap 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: i32) -> Vec<i32>` that takes an integer `n` and returns a vector 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 vector.
task_58
You are tasked with implementing a function that takes a vector of scorekeeper names and their corresponding appearances in a game. Your function should return a hashmap where each scorekeeper's name is a key and their total appearances are the values. Given a vector 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: Vec<(String, i32)>) -> HashMap<String, i32>` that takes a vector of tuples and returns a hashmap 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 vector of tasks and a time limit. Each task is represented as a String and the time limit is an i32 representing the maximum time the scheduler can run. The function should return a vector 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 vector of tasks that can be completed before the limit is reached. If no tasks can be completed within the time limit, return an empty vector.
task_60
You are tasked with implementing a Rust function that processes a given configuration map containing build configuration options and returns a vector of unique preprocessor directives present in the configuration. You are given a map `build_config` with the following structure: `build_config = { 'defines': vec![...], 'do_cache': true }`. Your task is to implement the function `extract_directives(build_config)` that takes in the `build_config` map and returns a vector of unique preprocessor directives present in the `defines` vector. The output vector should contain only unique directives. If the `defines` key is not present, return an empty vector. Function signature: `fn extract_directives(build_config: HashMap<String, Value>) -> Vec<String>`
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` (i32 or Vec<i32> of two elements): 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` (String): Either 'VALID' or 'SAME' indicating the type of padding to use.
- `stride` (i32 or Vec<i32> of two elements): 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` (String): 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` (i32): The depth (number of filters) of the output feature maps.
The function should return a Vec<String> 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: (i32, i32), winning_positions: Vec<(i32, i32)>) -> 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 vector 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 vector. For example, if the status is 200 and messages are vec!["Success", "Data loaded"], the output should be '<response><status>200</status><messages>Success,Data loaded</messages></response>'.
task_66
Given two vectors of integers, `attrs_from` and `attrs_to`, write a function `compute_correlations(attrs_from: Vec<i32>, attrs_to: Vec<i32>) -> HashMap<i32, HashMap<i32, f32>>` 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 hashmap 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 vector of command strings as input and returns a HashMap 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 HashMap 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: i32, y1: i32, w1: i32, h1: i32, x2: i32, y2: i32, w2: i32, h2: i32) -> (i32, i32, i32, i32)` 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: fn split_module_attribute(str_full_module: String) -> Option<(String, String)>:
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 vector of structs representing COVID-19 data, where each struct contains fields '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 vector of structs, '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 a vector of log-probabilities and a temperature parameter, and return a vector 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 vector is empty.
Function Signature:
fn gumbel_softmax(log_pi: Vec<f32>, tau: f32) -> Vec<f32>:
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 vector of symbols (strings) and an ordered vector of elements (also strings), implement a function that transforms each symbol in the vector to its corresponding index in the ordered vector. If a symbol does not exist in the ordered vector, return -1 for that symbol. The function should return a vector of integers representing these indices.
Function signature: `fn transform_symbols_to_indices(symbols: Vec<String>, order: Vec<String>) -> Vec<i32>:`
Example:
- Input: `symbols = vec![String::from("a"), String::from("b"), String::from("c")]`, `order = vec![String::from("c"), String::from("b"), String::from("a")]`
- Output: `[2, 1, 0]`
Constraints:
- The `symbols` input must be a vector of strings.
- The `order` input must be a vector of strings.
task_74
You are given a vector 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 = vec![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 vector 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 `std::collections::HashMap<String, String>` 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: String, limit: i32) -> String` 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: `fn update_target_maps_count(amount_of_target_maps_present: i32) -> i32`
Example:
Input:
`update_target_maps_count(10)`
Output:
`9`
task_78
You need to implement a function `generate_sequence(n)` that generates a vector of integers starting from 0 up to n-1. The function should return a vector of size n, where each element at index i contains the value i. If n is non-positive, the function should return an empty vector. 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: `fn retire_amendment(amendment_id: i32) -> bool:`.
task_80
Given a vector 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 vector 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 f64. 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 vector of tuples, but the contents of the tuples may not always be valid. Ensure that your implementation can handle floating-point 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 vector 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 vector 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 vector. 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
fn payment_summary(payments: Vec<i32>) -> (i32, i32):
```
**Input:**
- A vector 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 vector 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 vector of column names and returns a new vector with the modified column names based on these rules. Please write the function `format_column_names(column_names: Vec<String>) -> Vec<String>`.
task_84
You are tasked with creating a function that initializes a shared resource for a testing scenario. The function should create a vector called `tag_list` that contains three predefined tags: "rust", "unittest", and "tagging". Your function should return this vector. 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 vector of numbers. Your task is to implement a function that adds the number to the end of the vector and then returns the vector in reversed order. The function should not modify the input vector directly. Implement the function `add_and_reverse(num: i32, lead: Vec<i32>) -> Vec<i32>` where `num` is the number to be added and `lead` is the vector of integers. The function should return a new vector 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 capabilities to implement this functionality.
task_88
You are given a vector that allows appending elements to both ends. Implement a function `append_left_child(vec: &mut Vec<String>, value: String) -> ()` that appends a string `value` to the left end of the vector. The function should modify the vector in-place. The vector can contain any number of string elements. After appending, you can check the leftmost element of the vector to see if it has been updated correctly. Note that the vector is represented as a dynamically sized array and you can access the first element of the array to check the leftmost element. Your task is to implement the function that modifies the vector 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 HashMap, write a function that takes a value as input and returns a vector of keys corresponding to that value, along with the count of those keys. Also, return the total number of pairs in the input HashMap that have duplicate values. The function should return a tuple containing the vector of keys, the count of keys, and the number of pairs with duplicate values. For example, if the input HashMap 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 (vec!["b", "c", "g"], 3, 5).
task_91
You are given a vector 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 HashMap containing these values. The output HashMap should have the keys "TotalWeight", "AverageWeight", and "MaxWeight". If the input vector is empty, the function should return 0 for "TotalWeight", None for "AverageWeight", and None for "MaxWeight".
Example:
For input `weights = vec![10, 20, 30]`, the output should be:
{
"TotalWeight": 60,
"AverageWeight": Some(20.0),
"MaxWeight": Some(30)
}
task_92
Given a vector of strings that contain both alphabetic and numeric characters, implement a function that sorts the vector 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 vector.
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: i32, mushroom: i32, population: Vec<i32>, viewer: bool) -> Vec<i32>` that returns a signal for a population of mushrooms based on the given parameters. The function should return a vector 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 vector 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 vector `result` that contains stellar mass function (SMF), blue fraction, and stellar mass-halo mass (SMHM) information, along with two vectors `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` vector across different models. Specifically, you need to implement a function `compute_max_min_smhm(result: Vec<Vec<Vec<f32>>>, gals_bf: Vec<f32>, halos_bf: Vec<f32>, bf_chi2: f32) -> (f32, f32)` 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 HashMap 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 errors that occur during its execution. If an error occurs, the new function should return a string indicating that the function call failed, along with the error message. If no error occurs, it should return a string indicating that the function call succeeded. Implement the function `handle_function(fn: fn()) -> fn() -> String`. The parameter `fn` is guaranteed to be a 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` 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 vector 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: Vec<i32>) -> i32` where `increments` is a vector of integers. The function should return the total count after processing all increments. For example, calling `final_count(vec![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 return an Err if n is not a positive integer. The function should return a Vec 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