main
cargo_test_passed_eval.parquet
text → text
code_and_tests
You are a pragmatic Rust programmer who enjoys test driven development. Given the following question, write a Rust function to complete the task. Make the code simple and easy to understand. The code should pass `cargo build` and `cargo clippy`. Do not add a main function. Try to limit library usage to the standard library std. Respond with only the Rust function and nothing else. Be careful with your types, and try to limit yourself to the basic built in types and standard library functions. When writing the function you can think through how to solve the problem and perform reasoning in the comments above the function. Then write unit tests for the function you defined. Write three unit tests for the function. The tests should be a simple line delimited list of assert! or assert_eq! statements. When writing the unit tests you can have comments specifying what you are testing in plain english. The tests should use super::*. An example output should look like the following: ```rust /// Reasoning goes here /// and can be multi-line fn add_nums(x: i32, y: i32) -> i32 { x + y } #[cfg(test)] mod tests { use super::*; #[test] fn test_add_nums() { // Test adding positive numbers assert_eq!(add_nums(4, 2), 6); // Test adding a positive and negative number assert_eq!(add_nums(4, -2), 2); // Test adding two negative numbers assert_eq!(add_nums(-12, -1), -13); } } ``` Make sure to only respond with a single ```rust``` block. The unit tests must be defined inside the mod tests {} module. Limit the unit tests to 3 assert statements. Here is the question: {rust_prompt}
gpt4-5-results
Mar 3, 2025, 9:02 PM UTC
Mar 3, 2025, 10:56 PM UTC
01:53:14
500 rows
435644 tokens$ 46.40
500 rows processed, 435644 tokens used ($46.40)
completed
5 columns, 1-100 of 500 rows
task_id
rust_prompt
task_19390
Implement a function `recent_requests_count(pings: Vec<i32>) -> Vec<i32>` that takes a vector of integers `pings` representing timestamps (in milliseconds) of requests made in strictly increasing order. The function should return a vector of integers, where each integer at index `i` represents the count of requests that occurred within the last 3000 milliseconds (inclusive) from the timestamp `pings[i]`.
task_19391
Given a positive integer `n`, write a function `find_divisors(n)` that returns a vector of all unique numbers that divide evenly into `n`. The output vector should be sorted in ascending order.
task_19392
You are given a vector of positive integers, denoted as `nums`, and another positive integer, referred to as `target`. Your task is to determine the smallest length of a contiguous subarray whose sum is greater than or equal to `target`. If no such subarray exists, your function should return `0`. Implement a function `min_subarray_len(target: i32, nums: Vec<i32>) -> i32`.
task_19393
You are tasked with creating a function that takes a URL string and a user ID string as inputs and modifies the URL by appending a query parameter for the user ID if the URL contains the substring '/services'. The function should return the modified URL. If the '/services' substring is not present in the URL, return the original URL. The function signature should be: fn modify_url(url: String, user_id: String) -> String.
task_19394
You are given a vector of integers, and your task is to implement a function that merges two sorted halves of the vector into a single sorted vector. The function should take in the vector and the indices that define the two halves of the vector. The first half is defined by the range from `low` to `mid` (inclusive), and the second half is defined by the range from `mid+1` to `high` (inclusive). Your function should return a new vector that contains all the elements from both halves sorted in non-decreasing order. Implement the function `merge_sorted_halves(input_list: Vec<i32>, low: i32, mid: i32, high: i32) -> Vec<i32>`.
task_19395
You are given a vector of integers representing the scores of clients. Implement a function that calculates two values: the total sum of the scores and the secure sum of the scores, where the secure sum is defined as the total score divided by 8 (using integer division). The function should return a tuple containing both the total sum and the secure sum. The input vector will always contain at least one integer. Write a function named `calculate_sums(scores: Vec<i32>) -> (i32, i32)`.
task_19396
Implement a Rust function `generate_texts(texts: Vec<String>) -> Vec<String>` that takes a vector of strings `texts` as input and returns a vector of generated texts by appending the phrase ' - generated' to each input string. The function should handle empty strings and return an empty vector if the input is empty.
task_19397
You are tasked with managing user preferences for a music streaming service. Implement a function `set_and_get_preferences(genres: Vec<i32>, playlists: Vec<i32>) -> (Vec<i32>, Vec<i32>)` that sets the user's preferred genres and playlists, then retrieves these preferences. The function should take two vectors of integers as input: `genres`, which represents the user's preferred music genres, and `playlists`, which represents the user's preferred playlists. The output of the function should be a tuple containing the vectors of genres and playlists in the same order they were inputted. You can assume that the input vectors are non-empty and contain unique integers.
task_19398
Implement a function `get_next_char(s: String) -> String` that takes a string `s` consisting of lowercase alphabetical characters. The function should return the next consecutive alphabetical character following the last character of the string. If the last character is 'z', it should wrap around and return 'a'.
task_19399
You are given a configuration map that may contain a key "auto" and a key "interfaces". Your task is to implement a function `get_interfaces(config)` that returns a vector of interfaces based on the following rules: If the "auto" key in the configuration is set to true, return the vector of interfaces based on the shape of the system, represented as a string "square". If "auto" is false, return the vector of interfaces specified in the "interfaces" key as a comma-separated string, after splitting it by commas. If neither key exists, return an empty vector. The shape of the system is predefined as "square". Implement the function such that it only takes the configuration map as input and returns a vector of interfaces.
task_19401
You are tasked with implementing a leave management validation system for an organization. The system should validate the type of leave applied for by an employee. The leave can either be leave without pay (LWP) or partial pay leave (PPL), but not both at the same time. You need to write a function that performs this validation and returns an error message if both leave types are selected simultaneously. The function should have the following signature: `fn validate_leave_type(is_lwp: bool, is_ppl: bool) -> String:`. The function takes two boolean parameters: `is_lwp` indicates whether the leave type is LWP (true) or not (false), and `is_ppl` indicates whether the leave type is PPL (true) or not (false). If both `is_lwp` and `is_ppl` are true, return the string "Leave Type can be either without pay or partial pay". Otherwise, return an empty string.
task_19402
You are given a vector of integers representing the states of various tasks. Each integer corresponds to a task's state: 0 for 'Pending', 1 for 'In Progress', 2 for 'Completed', and 3 for 'Failed'. Write a function that takes this vector of task states and returns a hash map summarizing the count of tasks in each state. The keys of the hash map should be the state names ('Pending', 'In Progress', 'Completed', 'Failed') and the values should be the counts of tasks in those states.
Function signature: `fn summarize_task_states(task_states: Vec<i32>) -> HashMap<String, i32>`
task_19405
Given a vector of strings as input, write a function that sorts the strings in descending lexicographical order (i.e., in the order you'd find them if they were backwards in a dictionary). The vector can contain duplicate values or single character strings as well.
task_19406
Given two non-negative integers n and k, write a function `binomial_coefficient(n: i32, k: i32) -> i32` that calculates the binomial coefficient, commonly known as 'n choose k', which represents the number of ways to choose k elements from a set of n elements. The function should return the binomial coefficient as an integer. If k is greater than n, the function should return 0. The inputs n and k will be in the range of 0 to 30.
task_19407
You are given a vector of integers representing the heights of buildings along a street. Your task is to determine how many pairs of buildings can be formed such that the height of the first building is strictly less than the height of the second building. Implement a function `count_valid_pairs(heights: Vec<i32>) -> i32` that takes a vector of integers `heights` and returns the count of valid pairs of buildings. A pair (i, j) is considered valid if i < j and heights[i] < heights[j].
task_19408
You are given a string representing a sequence of characters. Your task is to write a function that counts the number of vowels (a, e, i, o, u) in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels. The function should return the total count of vowels found in the input string. Write a function `count_vowels(s: String) -> i32:` where `s` is the input string.
task_19409
Create a function that detects if a bank account balance goes to or below zero following a series of transactions represented by a vector of integers. The function should take an additional parameter, case_insensitive, which when set to true, allows the function to return true if the balance hits exactly zero. If the balance decreases below zero or hits zero, return true; otherwise, return false. Implement the function below_zero(operations: Vec<i32>, case_insensitive: bool) -> bool.
task_19410
You are tasked with creating a Rust function that retrieves a message based on the source code retrieval status of a given object. Implement a function `get_source_message(object: String, returncode: i32) -> String` that takes in two parameters: an object name as a String and a return code as an i32. The function should return a message depending on the value of `returncode` as follows:
- If `returncode` is 0, return 'Source code successfully retrieved for {object}.'
- If `returncode` is 1, return 'Source code retrieval failed for {object}.'
- If `returncode` is 6, return 'Cannot retrieve source code for {object}. It is a builtin object/implemented in C.'
- If `returncode` is 7, return 'Invalid metadata for the provided module.'
- If `returncode` is 8, return 'The provided module is not supported.'
- If `returncode` is 9, return 'The definition for {object} could not be found.'
- For any other `returncode`, return 'Unknown error occurred while retrieving source code for {object}.'
task_19411
You are tasked with updating a data structure to store gauge metrics based on provided metric definitions. Write a Rust function that takes in a metric type, metric name, a HashMap containing the metric definition (which includes a description, labels, and a value), and an existing HashMap that serves as the storage for gauge metrics. Your function should implement the following logic: if the metric type is not 'gauge', the function should do nothing. If the metric name does not exist in the data structure, it should be added along with its description and labels. If the metric name already exists, the function should update the value for the corresponding labels. Your function should return nothing. The function signature is: fn update_gauge_metric(metric_type: String, metric_name: String, metric_def: HashMap<String, String>, gauges_db: &mut HashMap<String, HashMap<String, String>>) -> (), where the metric_def contains keys like "description", "labels", and "value".
task_19413
You are tasked with creating a Rust function that manipulates a URL. Your function should take in a URL as input and return a string that formats the URL in a specific way. The formatted URL should start with 'URL: ' followed by the provided URL. The function signature should be: `fn format_url(url: String) -> String:`. For example, if the function is called with `format_url(String::from("https://example.com"))`, it should return 'URL: https://example.com'.
task_19414
You are given a vector of strings, where each string represents a line of text. Your task is to implement a function `calculate_average_chars_per_line(lines)` that takes this vector as input and returns the average number of characters per line, ignoring any leading or trailing whitespace. If the input vector is empty, the function should return 0. The function should consider all characters, including spaces and punctuation, when calculating the average. Implement the function without using any external resources.
task_19415
You are tasked with implementing a mathematical function that simulates the behavior of a custom neural network layer. This function takes an input vector of numbers and a vector of learnable parameters, with the same length as the input vector. The function should compute the element-wise product of the input vector and the parameter vector, followed by applying a non-linear activation function to the result. The activation function can be chosen from the following: ReLU (Rectified Linear Unit), Sigmoid, or Tanh. Your task is to implement a function that performs this operation. The function signature should be: `fn custom_layer(input_vec: Vec<f32>, parameters: Vec<f32>, activation: String) -> Vec<f32>:` where `activation` is one of 'relu', 'sigmoid', or 'tanh'.
task_19416
Write a function that takes a `String` as input and reverses the string without using any built-in functions or methods. The function should correctly handle Unicode characters and maintain the positions of non-alphabetic characters (such as punctuation and numbers). The output should be the reversed string.
task_19417
Implement a function that takes a vector of integers and returns a hash map containing the disparity between the maximum and minimum integers, the index of the first occurrence of the minimum integer, the index of the first occurrence of the maximum integer, and the average of the maximum and minimum integers (rounded to the nearest integer). The function should handle situations where the vector may contain duplicate integers, negative integers, or be completely empty. If the vector is empty, the function should return appropriate default values.
task_19418
Implement a function that takes two tuples representing complex numbers and returns the product of these complex numbers as a tuple. Each complex number is represented as a tuple (a, b) where 'a' is the real part and 'b' is the imaginary part. The multiplication of two complex numbers (a + bj) and (c + dj) is given by the formula: (a*c - b*d) + (b*c + a*d)j. Do not use Rust's built-in complex number multiplication functionality. For example, the complex numbers (10, 2) and (15, 3) should yield the product (150 - 6, 30 + 20) = (144, 50).
task_19419
You are tasked with implementing a Rust function that processes a string based on specific transformation rules. Your function should take a `String` as input and return a modified version of the input string according to the following rules: 1. If the input string contains the substring 'With output:', it should be replaced with 'Processed output:'. 2. If the input string contains the substring '--------------', it should be replaced with '=============='. 3. If the input string contains the substring 'frombytes', it should be replaced with 'tostring'. Implement the function `process_text(input_string)` that performs these transformations.
task_19420
You are tasked with creating a global resource manager for an application. Implement a function `set_global_manager(manager: String)` that takes a string `manager` as input. This function should set the global variable `RESOURCE_MANAGER` to the value of the input string. The `RESOURCE_MANAGER` should be accessible from anywhere within your program after being set. Note that the function does not return any value. The input string will always be non-empty.
task_19422
You have been given a vector of structs, where each struct represents a book with fields `book`, `author`, `price`, `publication_year`, and `publisher`. Your task is to implement a function that sorts this vector of books based on the `price` field in descending order and adds a new field `rank` to each struct, indicating the ranking based on the sorted price (starting from 1 for the highest price). The function should return the updated vector of structs.
task_19423
You are tasked with creating a function that simulates the creation of a deployment with a specified name and a configuration box. The function should take two parameters: a string 'name' representing the name of the deployment and a HashMap 'simple_box' representing the configuration. The function should return a HashMap containing the deployment's name and the configuration box. Define a function 'create_deployment(name: String, simple_box: HashMap<String, String>) -> HashMap<String, String>' that fulfills this requirement.
task_19425
You are tasked with implementing a function that retrieves specific text content based on a resource name provided as a string. You need to implement the function `get_resource(resource_name: String) -> String`, which takes in one argument: the name of the resource. The function should return the corresponding text content from a predefined set of resources. If the resource name does not exist, the function should return the string 'Resource not found'. The resources are defined as follows: 'resource1' -> 'This is resource 1', 'resource2' -> 'This is resource 2', 'resource3' -> 'This is resource 3'.
task_19426
Given a vector of state abbreviations, return a new vector containing the corresponding state names. You need to implement a function `get_state_names(abbrevs: Vec<String>) -> Vec<String>` that takes in a vector of strings `abbrevs`, where each string is a state abbreviation. The function should map the abbreviations to their respective state names based on the following mapping: 'CA' -> 'Cali', 'CO' -> 'Colorado', 'CT' -> 'Connecticut', 'NJ' -> 'New Jersey'. If an abbreviation does not have a corresponding state name, it should be represented as 'Unknown'. The output should be a vector of state names corresponding to the order of the input abbreviations.
task_19427
Given a vector of vectors representing a jagged array, implement a function that flattens this jagged array into a single vector. Your function should take a vector of vectors as input and return a single vector containing all the elements from the jagged array in the order they appear. For example, given the input vec![vec![1, 2, 3], vec![4, 5], vec![6]], the output should be vec![1, 2, 3, 4, 5, 6].
task_19428
Given a string `input_string` and an integer `n`, write a function that returns all possible unique permutations of the characters in `input_string` with a length of `n`. The order of the permutations in the output vector does not matter.
task_19429
You are tasked with creating a simplified music retargeting function. Given a song represented as a vector of timestamps where each timestamp represents a beat in the song, you need to create a new song that only contains beats labeled as 'solo' based on the provided music labels function. The output should be a vector of timestamps that represent the new song. The music labels function takes a timestamp and returns a string label. Your function should only include timestamps in the output where the label returned by the music labels function is 'solo'. If no timestamps are labeled as 'solo', return an empty vector.
task_19430
You are given a vector of integers `A` of length `N`. The vector `A` is 1-indexed and contains distinct integers. Your task is to find the smallest positive integer that is missing from the vector. Implement a function `find_missing_integer(A)` that takes the vector `A` as input and returns the smallest missing positive integer. If all positive integers from 1 to N are present, return N + 1. For example, given `A = vec![3, 4, -1, 1]`, the function should return `2`, as `2` is the smallest positive integer that is missing from the vector.
task_19431
Given a vector of integers representing the energy levels of electrons in a material, write a function `analyze_energy_levels(levels: Vec<i32>) -> (i32, Option<i32>, Option<i32>)` that returns a tuple containing three values: the total number of energy levels, the highest energy level, and the lowest energy level. If the input vector is empty, return (0, None, None).
task_19432
You are tasked with implementing a function that takes an integer `target_id` representing a user plugin toggle and disables it by setting its `enabled` attribute to `false`. Your function should return a string indicating whether the operation was successful or if the toggle was not found. If the toggle is successfully disabled, return 'Toggle disabled successfully.'. If the toggle does not exist, return 'Toggle not found.'. You can assume that you have access to a predefined list of user plugin toggles, where each toggle is represented as a struct with an `id` and an `enabled` attribute. Your function signature should be: `fn disable_user_plugin_toggle(target_id: i32) -> String:`.
task_19433
You are given a vector of file names that are image files in a specific format. Write a function `get_image_names(file_list: Vec<String>) -> Vec<String>` that takes a vector of strings representing file names and returns a vector of image names without their file extensions. The function should ignore any hidden files (those that start with a dot). If the input vector is empty or contains only hidden files, the function should panic. The input vector will only contain strings that represent file names with a '.tif' extension. The output should be a vector of strings representing the image names without the '.tif' extension.
task_19436
Given two vectors of integers, one containing distinct prime numbers and the other containing their corresponding frequencies, implement a function named 'prime_lcm_list' that returns the Least Common Multiple (LCM) of the primes raised to their respective frequencies. The function should efficiently handle large LCMs and return the result modulo 10^9 + 7 to avoid overflow. The input constraints are as follows: 1 <= primes.len() == freqs.len() <= 1000, 2 <= primes[i] <= 10^6, 1 <= freqs[i] <= 1000.
task_19437
You are tasked with implementing a function that calculates the Euclidean distance between a robot's current position on a grid and a specified target position. The robot's current position is represented as a tuple of two integers (x, y). Your function should take two arguments: the current position of the robot and the target position, both represented as tuples of two integers. The function should return the Euclidean distance as a float. The Euclidean distance between two points (x1, y1) and (x2, y2) is calculated using the formula: distance = sqrt((x2 - x1)² + (y2 - y1)²). Ensure that the function handles edge cases where the input positions are not valid tuples of two integers. Write a single function `calculate_distance(current_position: (i32, i32), target_position: (i32, i32)) -> f32` that implements this logic.
task_19438
Given a string `request`, write a function `get_metadata` that returns the expected metadata for three types of documents: 'ls5', 'ls7', and 'ls8'. If the input string does not match any of these types, return an error message 'Invalid request'. The expected metadata for each type is as follows: for 'ls5', return `HashMap` with `("format", "tarball")`, `("version", "1.0")`, `("size", "5MB")`; for 'ls7', return `HashMap` with `("format", "tarball")`, `("version", "1.1")`, `("size", "7MB")`; for 'ls8', return `HashMap` with `("format", "folder")`, `("version", "2.0")`, `("size", "8MB")`.
task_19440
Write a function to count the number of characters in a given string without using any built-in function. Ensure that the function correctly handles Unicode characters. For example, the string "Hello world! 😊" should return 13 as the length.
task_19441
Given a string `s`, expand the string to a case-insensitive globable string. The expansion should replace each alphabetic character with a character set that includes both its uppercase and lowercase forms. For instance, the character 'a' should be replaced with '[Aa]' and 'b' with '[Bb]'. If the character is a sequence of letters, it should be expanded to accommodate all combinations of uppercase and lowercase letters. Other characters should remain unchanged. The input string will not contain any nesting brackets or any special characters outside of letters and other non-alphabetic symbols. Implement a function `expand_case_matching(s: String) -> String` that returns the expanded string.
task_19442
You are given a string representing a file path. Your task is to implement a function that checks if the provided path points to a valid file. A path is considered valid if it contains at least one character and does not end with a slash ('/'). Implement the function `is_valid_file_path(path: String) -> bool` that returns `true` if the path is valid, otherwise it returns `false`.
task_19443
You are given a vector of elements, each represented as a struct containing a `name` and `visible` field. Your task is to create a function that takes this vector and returns a new vector with all elements marked as invisible (`visible` set to `false`) except for the first element in the vector, which should remain visible (`visible` set to `true`). If the input vector is empty, return an empty vector. Implement a function `update_visibility(elements: Vec<Element>) -> Vec<Element>` where `Element` is a struct with fields `name: String` and `visible: bool`.
task_19444
Given a boolean value `condition`, implement a function `evaluate_condition` that returns a tuple based on the value of `condition`. If `condition` is true, return the tuple `(1, 2)`. If `condition` is false, return the tuple `(4, 5)`.
task_19446
Given a vector of prime numbers, implement a function that calculates their sum and finds the average without using the built-in sum and len functions in Rust. The function should return both the total sum and the average as a tuple.
task_19448
Given a vector of intervals represented as tuples of floating-point numbers, write a function `min_intervals(intervals)` that determines the minimum number of non-overlapping intervals needed to cover the entire range of the provided intervals. An interval is represented as a tuple of two numbers (start, end), where start is less than or equal to end. Your function should return an integer representing the count of non-overlapping intervals required to cover the entire range.
task_19449
Implement a function `vigenere_cipher(s: String, key: String, decrypt: bool) -> String` that encodes or decodes the input string `s` using the Vigenère cipher method with a given `key`. The input string `s` can contain spaces and will only consist of uppercase and lowercase letters. The `key` will also consist of uppercase and lowercase letters and should be used to determine the shift for each character in the `s`. The `decrypt` parameter, when set to `true`, indicates that the function should decode the string. The function should return the encoded or decoded string with spaces removed and all characters in uppercase. For example, `vigenere_cipher(String::from("HELLO WORLD"), String::from("KEY"))` should return the encoded string, while `vigenere_cipher(String::from("RIJVS UYVJN"), String::from("KEY"), true)` should return the original string. Note that the function should only modify the characters and ignore spaces.
task_19450
Given two positive integers, `num1` and `num2`, write a function `compute_gcd(num1, num2)` that computes the greatest common divisor (GCD) of the two numbers using a step-by-step approach. The function should return the GCD as an integer.
task_19451
You are tasked with creating a function that takes a vector of integers as input. The function should iterate through the vector and calculate the sum of all positive integers in the vector. If the vector contains a negative integer, the function should stop processing the vector and return the sum of the positive integers encountered up to that point. If there are no positive integers before the first negative integer, the function should return 0. Write a function `sum_positive_before_negative(nums: Vec<i32>) -> i32` that implements this functionality.
task_19452
Given two distinct integer vectors `nums1` and `nums2`, implement a function `intersection(nums1, nums2)` that returns a vector containing the unique elements that are present in both vectors. The order of elements in the result does not matter. You may assume that `nums1` and `nums2` will have lengths between 1 and 1000, and that all elements will be non-negative integers less than or equal to 1000.
task_19453
You are given a string that represents a file path. Your task is to implement a function that checks if the file path is valid. A valid file path must start with a letter followed by ':/', and it can contain letters, numbers, underscores, and slashes. If the file path is valid, return true; otherwise, return false.
task_19455
You are tasked with implementing a function `process_event(event: std::collections::HashMap<String, String>, processing_enabled: bool) -> std::collections::HashMap<String, String>` that processes an event map based on a processing status. If `processing_enabled` is `false`, the function should return a new map where the keys 'key_id', 'project', and 'version' are all set to `None`. If `processing_enabled` is `true`, the function should return the event map unchanged. The input event map will contain various keys, and the output must preserve the structure of the input except for the specified keys when processing is disabled. Your function should ensure that the keys 'key_id', 'project', and 'version' are only altered when processing is disabled. The function should handle the event as follows:
Input: A map representing the event and a boolean indicating whether processing is enabled.
Output: A map representing the processed event.
task_19456
Given a vector of integers, implement a function that returns the sum of all even numbers in the vector. If there are no even numbers, the function should return 0. The function signature should be: fn sum_of_even_numbers(numbers: Vec<i32>) -> i32.
task_19457
You are tasked with creating a function that assigns a list of roles to a user identified by their email. The function should take three parameters: a string 'email' representing the user's email, a vector of strings 'roles' representing the roles to assign, and an optional string 'tenant' representing the tenant information. The function should return a string indicating the successful assignment of roles, formatted as 'Roles [role1, role2, ...] assigned to [email] for tenant [tenant]' if 'tenant' is provided, or 'Roles [role1, role2, ...] assigned to [email]' if 'tenant' is not provided. If the roles list is empty, return 'No roles to assign for [email]'. Please implement the function 'assign_roles(email: String, roles: Vec<String>, tenant: Option<String>) -> String'.
task_19458
You are tasked with creating a function that takes a string representing the name of a pipeline and a string representing an output folder path. The function should return a specific pipeline instance based on the name provided. The available pipelines are 'read_aligner' and 'call_peaks'. If the name does not match either of these, the function should panic indicating that the pipeline request is unknown. Write a function `get_pipeline(name: String, outfolder: String) -> String` that implements this functionality.
task_19459
Given a vector of strings representing gene names, implement a function that returns a new vector containing only the gene names that are classified as 'channels'. The list of channel names is provided as a second argument. The function should ignore duplicate channel names in the output vector. The output vector should maintain the order of the first occurrence of each channel name from the input vector. Write a function called 'filter_channels' that takes two parameters: 'gene_names' (a vector of strings) and 'channel_names' (a vector of strings). The function should return a vector of unique channel names found in the gene_names vector.
task_19460
Given a vector of three color difference signals represented as floats, calculate the hue angle in degrees. The hue angle is computed using the formula: hue = (180 * atan2(0.5 * (C_2 - C_3) / 4.5, C_1 - (C_2 / 11)) / pi) % 360, where C_1, C_2, and C_3 are the three color difference signals. Implement a function `hue_angle(C: Vec<f32>) -> f32` that takes a vector of three floats and returns the hue angle as a float.
task_19461
Given a vector of numbers, write a function `calculate_residuals` that computes the residuals of the input vector with respect to a target value of 0. The residual for each element in the vector is defined as the difference between the element and the target value. The function should return a vector of these residuals. For example, if the input vector is [1, 2, 3], the function should return [1.0, 2.0, 3.0].
task_19462
You are tasked with implementing a function to verify whether a user belongs to a specific group based on their unique ID. You are given a HashMap that maps unique user IDs to a vector of groups they belong to. Implement the function `verify_user_belongs_to_group(duke_unique_id: String, group_name: String, user_groups: HashMap<String, Vec<String>>) -> bool`. The function should return `true` if the user with the given unique ID belongs to the specified group, and `false` otherwise. The input parameters are:
- `duke_unique_id`: A string representing the unique ID of the user.
- `group_name`: A string representing the name of the group to be verified.
- `user_groups`: A HashMap where keys are unique user IDs and values are vectors of group names that the users belong to.
task_19463
You are tasked with creating a function that cleans up event titles by removing any references to cancellations or rescheduling. Your function should take a `String` representing the event title as input and return the title with any instances of 'cancel' or 'rescheduled' (case-insensitive) removed. For example, given the input "Important Event - Rescheduled", the function should return "Important Event - ".
task_19464
You are tasked with implementing a function `string_replacer` that takes three parameters: `target`, `replacement`, and `text`. The function should replace all occurrences of the string `target` in `text` with the string `replacement` and return the modified string. The replacement should be case-sensitive. Implement the function as follows: `fn string_replacer(target: String, replacement: String, text: String) -> String:`. Your implementation should ensure that the original string is not modified, and the function should return a new string with the replacements made.
task_19466
You are tasked with creating a function that initializes a simple in-memory representation of a knowledge base. Your function should create two tables: 'users' and 'posts'. Each user should have a unique identifier, a username, and an email. Each post should have a unique identifier, a title, content, and a reference to the user who created it. The function should return a map representing the tables, where the keys are table names and the values are vectors of maps representing the rows in each table. Implement the function `initialize_knowledgebase()` that returns this structure. The function should not take any parameters and should create two users and three posts for demonstration purposes. You can assume that the data will always be valid and does not require error handling.
task_19469
Given a vector of 3D curve types represented as strings, write a function that checks if each curve type is valid. The valid curve types are: "line", "circle", "ellipse", "hyperbola", "parabola", "Bezier curve", and "BSpline curve". The function should return a vector of booleans where each boolean indicates whether the corresponding curve type is valid or not. For example, if the input is vec!["line", "circle", "triangle"], the output should be vec![true, true, false].
task_19470
Given a string, write a function that counts the frequency of each character in the string and returns a HashMap where the keys are the characters and the values are their corresponding frequencies. The function should be case-sensitive and should include spaces and punctuation in the count.
task_19471
Implement a function `total_remuneration` that calculates the total remuneration of an employee based on their salary and bonus. The function should take the name of the employee, their salary, and their bonus as inputs and return the total remuneration. The total remuneration is defined as the sum of the salary and the bonus. The function signature should be `fn total_remuneration(name: String, salary: f32, bonus: f32) -> f32`.
task_19472
Write a function that takes a two-dimensional vector of integers and returns a one-dimensional vector containing all the integers from the input vector in the same order. The input will always be a well-formed two-dimensional vector (i.e., a vector of vectors) where each inner vector contains integers.
task_19473
You are tasked with validating a list of JavaScript code snippets for linting errors based on a predefined configuration. Your goal is to implement a function `validate_js_snippets(snippets)` that takes a vector of JavaScript code snippets and evaluates them against a set of linting rules, returning a vector of linting errors found in each snippet. Each snippet is a `String` containing JavaScript code. The function should check for common linting issues such as missing semicolons, unused variables, and console statements. If a snippet has no errors, it should be represented as an empty string in the output vector. You can assume that the linting rules are predefined and will not change. The input will always be a vector of `String`, and the output should be a vector of `String` representing the linting errors for each snippet.
task_19475
Given a non-negative integer, write a function `calculate_digit_sum` that returns the sum of its digits. The input integer can be any non-negative integer, and the function should handle each digit individually, summing them to provide the final result. For example, if the input is 123, the output should be 6 since 1 + 2 + 3 = 6. The function should only take one parameter, which is the non-negative integer.
task_19476
You are tasked with creating a function that provides a weather recommendation based on whether it is raining or not. The function should take a string input that indicates whether it is raining, which can be 'yes', 'y', 'no', or 'n' in any combination of uppercase and lowercase letters. The function should return 'Take an umbrella' if the input indicates it is raining, and 'Have a nice day' if it is not raining. Please implement the function `weather_recommendation(input_str: String) -> String` that achieves this functionality.
task_19477
You are tasked with creating a function that manages a collection of books in a library. The library allows users to perform the following operations on the collection of books: add a new book, remove a book, display the list of all books, and search for a specific book by its title. Implement the function `library_management(operations: Vec<(String, Option<(String, String)>)>) -> Vec<String>` where `operations` is a vector of operations to perform. Each operation is represented as a tuple. The first element of the tuple is a string representing the operation type ('add', 'remove', 'display', 'search'). If the operation is 'add', the second element will be a tuple containing the title and author of the book. The function should return a vector of results for each operation. The results should be:
- For 'add' operations, return 'Book added successfully!'.
- For 'remove' operations, return 'Book removed successfully!' or 'Book not found!' if the book does not exist.
- For 'display' operations, return a list of strings formatted as 'Title by Author'. If there are no books, return 'No books in the library.'.
- For 'search' operations, return 'Book found: Title by Author' or 'Book not found!' if the book does not exist.
Example:
If the input is vec![ ("add", Some(("rust Programming".to_string(), "John Smith".to_string()))), ("display", None), ("search", Some(("rust Programming".to_string(), "".to_string()))), ("remove", Some(("rust Programming".to_string(), "".to_string()))), ("display", None) ], the output will be vec![ "Book added successfully!".to_string(), vec![ "rust Programming by John Smith".to_string() ].join(", ").to_string(), "Book found: rust Programming by John Smith".to_string(), "Book removed successfully!".to_string(), "No books in the library.".to_string() ].
task_19479
Given a positive integer `n`, write a function that determines if for every factor `d` of `n`, the expression `d + n / d` yields a prime number. Return `true` if this condition holds for all factors, otherwise return `false`.
task_19480
Implement a function `fruit_distribution(s: i32, n: i32, fruits: Vec<String>, new_fruits_list: Vec<String>)` that takes in an integer `s`, an integer `n`, a vector of strings `fruits`, and another vector of strings `new_fruits_list`. The function should return a hash map that combines the counts of each type of fruit found in both `fruits` and `new_fruits_list`. If a fruit appears in both lists, its count should be the sum of occurrences from both lists. The integer parameters `s` and `n` do not affect the output and can be ignored in the implementation. The output hash map should have fruits as keys and their corresponding counts as values.
task_19481
You are tasked with creating a function that generates a simple string representation of a ResNet model configuration. The function should take in three parameters: `layers`, `block`, and `ibn_cfg`. The `layers` parameter is a vector of integers representing the number of layers in each block of the ResNet model. The `block` parameter is a string that indicates the type of block used in the model (e.g., 'Bottleneck', 'Basic'). The `ibn_cfg` parameter is a tuple that indicates the configuration of Instance-Batch Normalization. The function should return a string that summarizes the model configuration in the format: 'ResNet-<layers> with <block> blocks and IBN configuration <ibn_cfg>'. For example, if the inputs are layers=[3, 8, 36, 3], block='Bottleneck', and ibn_cfg=('a', 'a', 'a', None), the output should be 'ResNet-[3, 8, 36, 3] with Bottleneck blocks and IBN configuration ('a', 'a', 'a', None)'.
task_19482
You are given a vector of accuracy scores for a model's predictions on various datasets. Each entry in the vector represents the accuracy score of the model on a specific dataset. Your task is to write a function that returns the average accuracy score of the model across all datasets, rounded to two decimal places. Implement the function `average_accuracy(scores: Vec<f32>) -> f32`, where `scores` is a vector of accuracy scores (0 <= score <= 100). The function should return the average accuracy score as a float.
task_19483
Given a vector of integers and a positive integer c, write a function that returns a new vector where each element of the input vector is repeated c times in the same order. The input vector may contain both positive and negative integers, as well as zero. Your function should take two parameters: a vector of integers `nums` and a positive integer `c`. The output should be a new vector containing the repeated elements.
task_19484
You are tasked with creating a function that retrieves a vector of all the protocols categorized as 'risky' from a predefined set of protocols. The function should return a vector of protocol names that are considered risky. The following protocols are deemed risky: 'ftp', 'telnet', 'http', 'smtp', 'pop3', 'imap', 'netbios', 'snmp', 'ldap', 'smb', 'sip', 'rdp', 'vnc', 'kerberos'. Implement a function `get_risky_protocols()` that returns this vector of risky protocols in the order they are given.
task_19485
You are tasked with implementing a function that simulates the operations of a generic stack data structure. The function should support the following operations: push, pop, peek, check if the stack is empty, and get the size of the stack. The function will take a vector of operations as input, where each operation is represented as a tuple. The first element of the tuple is a string that represents the operation ('push', 'pop', 'peek', 'is_empty', 'get_size'), and the second element (if applicable) is the value to be pushed onto the stack. The function should return a vector of results corresponding to the operations that produce an output (pop, peek, is_empty, and get_size). If a pop or peek operation is attempted on an empty stack, the function should return 'Error'.
task_19486
Implement a function `convert(unit: String, distance: f32) -> Option<f32>` that converts a given distance from kilometers to miles or from miles to kilometers based on the specified unit. If the input unit is 'km', the function should convert the distance to miles (1 km = 0.621371 miles). If the input unit is 'mi', it should convert the distance to kilometers (1 mile = 1.60934 km). If the specified unit is neither 'km' nor 'mi', or if the distance is negative, the function should return None.
task_19487
Implement a function `roles_required(roles: Vec<String>) -> Vec<String>` that takes a vector of role names as input and returns a vector of strings indicating which roles are required. The function should ensure that each role in the input vector is unique and sorted in alphabetical order. If the input vector is empty, return an empty vector. For example, if the input is vec![String::from("admin"), String::from("editor"), String::from("admin")], the output should be vec![String::from("admin"), String::from("editor")].
task_19488
Implement a function `generate_fibonacci(n: i32) -> Vec<i32>` that returns the first `n` Fibonacci numbers as a vector. The Fibonacci sequence is defined as follows: the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the two preceding ones. Your function should handle cases where `n` is less than or equal to 0 by returning an empty vector.
task_19489
You are tasked with implementing a simple dropdown menu functionality. Write a function called `select_option` that takes in a vector of strings representing options and a string representing the selected option. The function should return the index of the selected option in the vector. If the selected option is not found in the vector, return -1. The input vector may contain duplicates, and the function should return the index of the first occurrence of the selected option. If the vector is empty, return -1.
task_19490
You are tasked with creating a Rust function that processes a vector of integers and returns the sum of all even numbers in the vector. The function should take a single parameter: a vector of integers. If there are no even numbers in the vector, the function should return 0. Your function should handle both positive and negative integers. Write a function `sum_of_even_numbers` that implements this functionality.
task_19491
You are tasked with creating a function `extract_ndef_records` that processes a vector of NDEF records from an NFC tag. Each record is represented as a struct with fields `type` and `payload`. Your function should take a vector of such records as input and return a vector of readable strings that describe each record. If the vector of records is empty, return a vector containing a single string 'sorry no NDEF'. Each record should be formatted as 'Type: {type}, Payload: {payload}'.
task_19492
You are tasked with creating a function that generates build instructions for a software project's build system. The function should take three parameters: a vector of input files or data required for the build action, a vector of tools or resources needed for the action, and a vector of resulting output files or artifacts. Your task is to implement the function `generate_build_instructions(inputs, tools, outputs)` that returns a string representing the build instructions in the following format:
```
dotnet.actions.run(
inputs = inputs + resolve[0].to_vec(),
tools = tools,
outputs = outputs,
)
```
Ensure that the function generates the build instructions based on the provided input parameters.
task_19493
You are tasked with creating a Rust function that validates a user's phone number format. The phone number should be a string that follows these criteria: it must contain exactly 10 digits, and it can optionally start with a '+' sign. Your task is to implement a function called `validate_phone_number` that takes a single string parameter `phone_num` and returns `true` if the phone number is valid according to the specified criteria and `false` otherwise. The function should not use any external libraries.
task_19494
Given two datasets representing the spread of a disease using the SIR and SEIR models under certain conditions, write a function that determines if the predictions from both models are the same when specific parameters are enforced: alpha should equal gamma, the number of exposed individuals should be set to zero, and the newly infected individuals should equal the newly exposed individuals. The function should return true if the predictions are the same, and false otherwise. The input will be two hash maps, `sir_data` and `seir_data`, each containing keys "infected", "exposed", and "recovered", representing the counts of individuals in each category. The function signature should be: fn compare_sir_vs_seir(sir_data: std::collections::HashMap<String, i32>, seir_data: std::collections::HashMap<String, i32>) -> bool.
task_19497
You are given a vector of balances represented as hash maps. Each balance hash map contains a 'commitment' key with a unique string value. Your task is to implement a function that takes in this vector of balances and returns a vector of balances that are considered 'unspent'. A balance is considered 'unspent' if its commitment exists in a predefined set of valid commitments. If a balance's commitment is not in this set, it should not be included in the returned vector. Implement the function `filter_unspent_balances(balances: Vec<HashMap<String, String>>) -> Vec<HashMap<String, String>>` where `balances` is the vector of balance hash maps and the function returns a vector of hash maps representing the unspent balances.
task_19499
Given a vector of integers, write a function `sum_of_evens(nums: Vec<i32>) -> i32` that returns the sum of all even numbers in the vector. If there are no even numbers, return 0. The function should handle both positive and negative integers.
task_19500
Construct a function termed `replace_words` which takes a `String` and a vector of tuples of `String`. The function should replace each occurrence of the first word in each tuple with the second word in the tuple. The function should return the modified `String` after all replacements have been made.
task_19501
You are tasked with implementing a logging system for a software application. Your goal is to create a function `custom_configuration()` that simulates a logging configuration process. This function should return a string indicating that the custom configuration is in progress. Your function does not need to handle any external resources or dependencies. It should simply return the message 'Custom configuration in progress'.
task_19502
Implement a function `factorize(n: i32) -> std::collections::HashMap<i32, i32>` that takes an integer n as input and returns a HashMap containing the prime factorization of n. The keys of the HashMap should be the prime factors, and the values should be their respective counts in the factorization. If n is less than 2, return an empty HashMap.
task_19503
Given a type represented as a string, implement a function `ptr_ty(type_str: String) -> String` that returns a string representing a pointer to that type. The pointer type should be formatted as `type_str*`. For example, if the input is `int`, the output should be `int*`. If the input is `char`, the output should be `char*`. The input will always be a valid type string. Your task is to implement the function to return the correct pointer representation.
task_19504
You are tasked with implementing a Rust function that generates a unique hash for a given task represented by its properties. The task is defined by a name, a vector of parameters, and a HashMap of arguments. The function `generate_task_hash` should take three inputs: a string `name`, a vector of strings `params`, and a HashMap of key-value pairs `args`. The hash generation algorithm should follow these rules: 1. Start with an empty string as the hash value. 2. Append the `name` to the hash value. 3. Append the concatenated values of the `params` vector to the hash value. 4. Append the concatenated values of the `args` HashMap to the hash value. Your task is to implement the `generate_task_hash` function to generate the unique hash value based on the input parameters. Function Signature: `fn generate_task_hash(name: String, params: Vec<String>, args: HashMap<String, String>) -> String`
task_19505
Given a vector of parameters and a target group of parameters, write a function that determines if any of the parameters in the vector are present in the target group. The function should return `true` if at least one parameter is found in the target group, and `false` otherwise. You may assume that the input vector and target group contain unique elements.
Function signature: `fn is_parameter_explored(parameters: Vec<String>, group: Vec<String>) -> bool:`
### Input
- `parameters`: A vector of strings representing the parameters that need to be checked. (1 <= parameters.len() <= 100)
- `group`: A vector of strings representing the target group of parameters. (1 <= group.len() <= 100)
### Output
- Return a boolean value: `true` if any parameter from the input vector is found in the target group, otherwise return `false`.
task_19506
You are tasked with implementing a function that simulates the process of downloading a file. The function should check if a user is logged in and if they have the correct permissions to download a specific file. Your function should take two parameters: a boolean `is_logged_in` indicating whether the user is logged in, and a boolean `is_staff_user` indicating whether the user has staff privileges. The function should return `Downloading {filename}` if the user meets both conditions, otherwise return `Access Denied`. You can assume that the filename is a string provided as a parameter. Implement the function `download_file(is_logged_in: bool, is_staff_user: bool, filename: String) -> String`.
task_19507
You are tasked with creating a function `get_searchable_models` that returns a vector of all models from a given vector of structs that implement a specific trait called `ISearchable`. The function should accept a vector of struct definitions and a trait name as inputs. Each model struct will be represented as a struct with two fields: `name` (a string representing the model's name) and `implements` (a vector of trait names that the model implements). Your function should return a vector of names of the models that implement the specified trait.
Function Signature: `fn get_searchable_models(models: Vec<Model>, interface_name: String) -> Vec<String>:`
### Input
- `models`: A vector of structs, where each struct represents a model class. Each struct contains:
- `name`: (String) The name of the model.
- `implements`: (Vec<String>) A vector of traits that the model implements.
- `interface_name`: (String) The name of the trait to check against.
### Output
- Returns a vector of strings representing the names of the models that implement the specified trait.
### Example:
Input: `models = vec![Model { name: String::from("User"), implements: vec![String::from("IUser"), String::from("ISearchable")] }, Model { name: String::from("Product"), implements: vec![String::from("IProduct")] }, Model { name: String::from("Order"), implements: vec![String::from("ISearchable"), String::from("IOrder")] }]`, `interface_name = String::from("ISearchable")`
Output: `vec![String::from("User"), String::from("Order")]`
task_19509
Write a function `mirror_text_feed(input_string: String) -> String` that takes a string as input and returns the mirror image of the string. The mirror image should only include alphabetic characters, with all numeric elements and symbols removed. The resulting string should be reversed. For example, if the input is 'abc123!@#xyz', the output should be 'zyxabc'.
task_19510
You are tasked with writing a function that processes a vector of mathematical expressions and evaluates their values. Each expression is a string that may contain basic arithmetic operations such as addition (+), subtraction (-), multiplication (*), and division (/). Your function should handle the evaluation of these expressions and return a vector of tuples, where each tuple contains the original expression and its evaluated result. If an expression cannot be evaluated (for example, due to a division by zero), return 'Error' as the result for that expression. Implement the function `evaluate_expressions(expressions: Vec<String>) -> Vec<(String, Result<f32, String>)>` where `expressions` is a vector of strings representing mathematical expressions. The output should be a vector of tuples as described above.