Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    CastError
Message:      Couldn't cast
task_category: string
crate_name: string
input_data: string
output_data: string
instruction: string
code_context: string
n_output_tokens: int64
response: string
n_input_tokens: int64
to
{'instruction': Value('string'), 'response': Value('string'), 'task_category': Value('string'), 'crate_name': Value('string'), 'n_input_tokens': Value('int64'), 'n_output_tokens': Value('int64')}
because column names don't match
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1827, in _prepare_split_single
                  for key, table in generator:
                                    ^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 613, in wrapped
                  for item in generator(*args, **kwargs):
                              ~~~~~~~~~^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 343, in _generate_tables
                  self._cast_table(pa_table, json_field_paths=json_field_paths),
                  ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 132, in _cast_table
                  pa_table = table_cast(pa_table, self.info.features.arrow_schema)
                File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2378, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2306, in cast_table_to_schema
                  raise CastError(
                  ...<3 lines>...
                  )
              datasets.table.CastError: Couldn't cast
              task_category: string
              crate_name: string
              input_data: string
              output_data: string
              instruction: string
              code_context: string
              n_output_tokens: int64
              response: string
              n_input_tokens: int64
              to
              {'instruction': Value('string'), 'response': Value('string'), 'task_category': Value('string'), 'crate_name': Value('string'), 'n_input_tokens': Value('int64'), 'n_output_tokens': Value('int64')}
              because column names don't match
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1369, in compute_config_parquet_and_info_response
                  parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet(
                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~^
                      builder, max_dataset_size_bytes=max_dataset_size_bytes
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  )
                  ^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 948, in stream_convert_to_parquet
                  builder._prepare_split(split_generator=splits_generators[split], file_format="parquet")
                  ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1694, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ~~~~~~~~~~~~~~~~~~~~~~~~~~^
                      gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  ):
                  ^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1879, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

instruction
string
response
string
task_category
string
crate_name
string
n_input_tokens
int64
n_output_tokens
int64
Write a Rust function or impl block from a natural-language specification. use std::collections::{HashMap, VecDeque}; use std::hash::Hash; use std::time::{Duration, Instant}; Implement a generic, thread-unsafe LRU Cache with optional Time-To-Live (TTL) support. The cache should support getting and putting key-value p...
use std::collections::{HashMap, VecDeque}; use std::hash::Hash; use std::time::{Duration, Instant}; pub struct LruCache<K, V> { capacity: usize, map: HashMap<K, (V, Instant)>, order: VecDeque<K>, } impl<K: Eq + Hash, V> LruCache<K, V> { pub fn new(capacity: usize) -> Self { assert!(capacity > ...
code_generation
lru_ttl_cache
158
773
Write a Rust function or impl block from a natural-language specification. use std::collections::HashMap; use std::hash::Hash; use std::sync::{Arc, Mutex}; Implement a thread-safe Least Recently Used (LRU) cache in Rust. The cache should support generic key and value types. It must support initialization with a capac...
use std::collections::HashMap; use std::hash::Hash; use std::sync::{Arc, Mutex}; struct Node<K, V> { key: K, value: V, prev: Option<usize>, next: Option<usize>, } struct LruCache<K, V> { capacity: usize, map: HashMap<K, usize>, pool: Vec<Option<Node<K, V>>>, head: Option<usize>, ta...
code_generation
thread_safe_lru_cache
153
1,050
Write a Rust function or impl block from a natural-language specification. use std::fmt; Write a generic Ring Buffer struct in Rust with a fixed capacity. It should support a `push_back` method that inserts an item to the back. If the buffer is full, `push_back` should remove and return the oldest item (displaced val...
use std::fmt; pub struct RingBuffer<T> { data: Vec<Option<T>>, head: usize, tail: usize, count: usize, capacity: usize, } impl<T> RingBuffer<T> { /// Creates a new RingBuffer with the specified capacity. pub fn new(capacity: usize) -> Self { assert!(capacity > 0, "Capacity must be ...
code_generation
ringbuf
128
549
Write a Rust function or impl block from a natural-language specification. Implement a robust `LineIterator` struct that wraps a string slice and implements the `Iterator` trait to yield lines from the text. The iterator should support configuration options to skip empty lines and to skip comment lines (those starting...
pub struct LineIterator<'a> { remaining: &'a str, skip_empty: bool, skip_comments: bool, } impl<'a> LineIterator<'a> { pub fn new(input: &'a str, skip_empty: bool, skip_comments: bool) -> Self { LineIterator { remaining: input, skip_empty, skip_comments, ...
code_generation
text_utils
120
418
Write a Rust function or impl block from a natural-language specification. Implement a Semantic Versioning (SemVer) parser and comparator that supports pre-release tags and build metadata. The implementation should parse strings in the format 'MAJOR.MINOR.PATCH(-PRERELEASE)(+BUILD)', handle common edge cases like lead...
use std::fmt; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)] pub struct SemVer { pub major: u64, pub minor: u64, pub patch: u64, pub pre: Option<Vec<SemVerIdentifier>>, pub build: Option<String>, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SemVerIdentifier { Numeric(u64), ...
code_generation
semver_core
155
1,428
Write a Rust function or impl block from a natural-language specification. Write a generic, zero-allocation `SlidingWindow` iterator for Rust slices. The struct should support configurable `window_size` and `step`. The constructor must return `Option<Self>`, failing if `window_size` exceeds the slice length or if para...
pub struct SlidingWindow<'a, T> { data: &'a [T], window_size: usize, step: usize, } impl<'a, T> SlidingWindow<'a, T> { /// Creates a new sliding window iterator. /// /// Returns `None` if `window_size` is zero, `step` is zero, /// or `window_size` exceeds the length of the slice. pub fn...
code_generation
sliding_window_utils
119
342
Write a Rust function or impl block from a natural-language specification. use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; Create a thread-safe Bloom Filter that supports adding strings and checking membership. The filter should be initialized with a specific...
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; pub struct BloomFilter { bits: Arc<Mutex<Vec<u64>>>, num_hashes: usize, size: usize, } impl BloomFilter { pub fn new(num_hashes: usize, size: usize) -> Self { let byte_count = (size + 63)...
code_generation
bloom_filter
139
470
Write a Rust function or impl block from a natural-language specification. pub fn compress(data: &[u8]) -> Vec<u8>; Implement a Run-Length Encoding (RLE) compressor function in Rust that takes a byte slice and returns a compressed Vec<u8>. The output format should consist of pairs of (count, byte), where count is a u...
pub fn compress(data: &[u8]) -> Vec<u8> { if data.is_empty() { return Vec::new(); } let mut result = Vec::with_capacity(data.len()); let mut current_byte = data[0]; let mut count: u8 = 1; for &byte in &data[1..] { if byte == current_byte && count < 255 { count += 1;...
code_generation
rle_compress
109
144
Write a Rust function or impl block from a natural-language specification. Implement a generic Least Recently Used (LRU) cache in Rust with a fixed capacity. The implementation should support `get` and `put` operations, evicting the least recently used item when the capacity is exceeded. Use standard library collectio...
use std::collections::{HashMap, LinkedList}; use std::hash::Hash; pub struct LruCache<K, V> { capacity: usize, map: HashMap<K, V>, order: LinkedList<K>, } impl<K, V> LruCache<K, V> where K: Eq + Hash + Clone, V: Clone, { pub fn new(capacity: usize) -> Self { assert!(capacity > 0, "Capa...
code_generation
lru_cache_impl
106
321
Write a Rust function or impl block from a natural-language specification. use std::collections::HashMap; Parse a simplified INI-style configuration string into a nested HashMap structure. Handle sections denoted by [...] and key-value pairs key=value. Ignore comments starting with ; and empty lines.
use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { InvalidLine(String), MissingSection, } #[derive(Debug, Clone, PartialEq)] pub struct IniConfig { pub sections: HashMap<String, HashMap<String, String>>, } impl IniConfig { pub fn parse(input: &str) -> Result<Self, Pa...
code_generation
mini_ini
75
841
Write /// doc comments for existing Rust code. Core utility for a configuration management crate that validates user-defined timeouts in HTTP middleware. fn parse_duration_string(input: &str) -> Result<u64, String> { let input = input.trim(); if input.is_empty() { return Err("Input cannot be empty".to...
/// Parses a duration string into milliseconds. /// /// Accepts inputs formatted as `[number][unit]`, where unit is one of `ms`, `s`, or `m`. /// The input string is trimmed before parsing. /// /// # Examples /// /// ``` /// # use time_utils::parse_duration_string; /// /// assert_eq!(parse_duration_string("100ms").unwr...
docstring_generation
time_utils
210
333
Write /// doc comments for existing Rust code. This function belongs to a serialization crate focused on binary protocol handling, used to convert hex-encoded configuration payloads into raw byte buffers for memory mapping or cryptographic operations. pub fn parse_hex_to_bytes(input: &str) -> Result<Vec<u8>, String> ...
/// Parses a hexadecimal string into a vector of bytes. /// /// The input string is expected to contain valid hexadecimal characters (0-9, a-f, A-F). /// The length of the string must be even; otherwise, an error is returned. /// /// # Examples /// /// ``` /// use hex_utils::parse_hex_to_bytes; /// /// let result = par...
docstring_generation
hex_utils
195
299
Write /// doc comments for existing Rust code. pub fn parse_time_window(input: &str) -> Result<TimeWindow, ParseError> { let mut weeks = 0; let mut days = 0; let mut parts = input.split_whitespace(); if let Some(w) = parts.next() { if w.ends_with('w') { weeks = w.trim_end_...
/// Parses a time window string format like "1w2d" into a `TimeWindow`. /// /// The input string can contain whitespace-separated components for weeks (`w`) and days (`d`). /// Components are optional; e.g., "2d" or "1w" are valid. /// /// # Arguments /// /// * `input` - A string slice containing the time window specif...
docstring_generation
time_utils
138
393
Write /// doc comments for existing Rust code. Parsing and validation of ISO 8601 week date formats within a date manipulation library. pub struct IsoWeek { pub year: u16, pub week: u8 } #[derive(Debug, PartialEq)] pub enum ParseError { InvalidLength, InvalidYear, MissingSeparator, InvalidWeek, W...
/// Parses an ISO 8601 week date string into an `IsoWeek` struct. /// /// The input is expected to be exactly 7 characters in the format `YYYY-Www`, /// where `YYYY` is the year and `ww` is the week number (01-53). /// /// # Examples /// /// ``` /// use iso_week_parser::{IsoWeek, parse_iso_week}; /// /// let parsed = p...
docstring_generation
iso_week_parser
248
430
Write /// doc comments for existing Rust code. utils/config_parser.rs pub fn parse_config_section(input: &str) -> Result<HashMap<String, String>, String> { let mut map = HashMap::new(); for line in input.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { ...
/// Parses a simple configuration string into key-value pairs. /// /// The input string is expected to contain lines in the format `key = value`. /// Lines starting with `#` or empty lines are ignored. /// /// # Examples /// /// ``` /// use config_util::parse_config_section; /// /// let config = "[server]\nhost = 127.0...
docstring_generation
config_util
168
387
Write /// doc comments for existing Rust code. pub struct TimeDuration { pub seconds: u64 } pub enum ParseError { InvalidFormat, ValueOutOfBounds } struct TimeDuration { pub seconds: u64, } #[derive(Debug)] enum ParseError { InvalidFormat, ValueOutOfBounds, } pub fn parse_time_duration(input: &str) -> R...
struct TimeDuration { pub seconds: u64, } #[derive(Debug)] enum ParseError { InvalidFormat, ValueOutOfBounds, } /// Parses a time duration string into a `TimeDuration` struct. /// /// The input string must consist of numbers followed by units 's', 'm', or 'h'. /// Units can be combined, e.g., "1h30m" resu...
docstring_generation
my_crate
383
237
Write /// doc comments for existing Rust code. pub struct RingBuffer { data: Vec<u8>, capacity: usize, head: usize, } impl RingBuffer { pub fn new(capacity: usize) -> Self { RingBuffer { data: Vec::with_capacity(capacity), capacity, head: 0 } } pub fn write(&mut self, val: u8) -> Result...
/// Rotates the ring buffer by `steps` positions and retrieves the value at the new head. /// /// This method advances the buffer's head index by `steps` (modulo capacity) and returns /// the element at the updated position. It modifies the buffer state. /// /// # Panics /// /// Panics if `buffer.capacity` is 0, causin...
docstring_generation
ring_utils
224
267
Write /// doc comments for existing Rust code. Low-level buffer manipulation utility for network packet processing. fn rotate_buffer(buffer: &mut [u8], amount: u32) -> Result<(), String> { if buffer.is_empty() { return Err("Buffer cannot be empty".to_string()); } let len = buffer.len(); let ro...
/// Rotates the contents of the buffer to the left by the specified amount. /// /// The buffer is mutated in-place. The rotation wraps around, so rotating /// by the buffer length results in the original order. /// /// # Errors /// /// Returns an `Err` if the buffer is empty, as rotation is undefined. /// /// # Panics ...
docstring_generation
netutil
99
270
Write /// doc comments for existing Rust code. User registration validation module handling username constraints. pub fn sanitize_username(name: &str) -> Result<String, SanitizeError> { if name.is_empty() { return Err(SanitizeError::Empty); } if name.len() > 32 { return Err(SanitizeError::...
/// Sanitizes a username string by removing invalid characters and enforcing length limits. /// /// This function filters the input to keep only alphanumeric characters, underscores, and hyphens. /// It also enforces a maximum length of 32 characters. /// /// # Errors /// /// Returns `SanitizeError::Empty` if the input...
docstring_generation
auth_utils
144
372
Write /// doc comments for existing Rust code. Function from a telemetry processing crate that handles incoming sensor data streams. Used to smooth noisy readings before persistence. pub fn calculate_moving_average(buffer: &[f64], window_size: usize) -> Result<f64, &'static str> { const MAX_WINDOW_SIZE: usize = 1...
/// Calculates the moving average of the most recent `window_size` samples from `buffer`. /// /// This function extracts the last `window_size` elements from the provided buffer /// and computes their arithmetic mean. It is useful for smoothing sensor readings /// or analyzing time-series telemetry data. /// /// # Erro...
docstring_generation
telemetry_utils
221
397
Explain what a Rust snippet does in plain English. Background task utility for handling flaky network connections in a CLI tool. use std::time::Duration; use std::io::{self}; fn fetch_with_retries(url: &str, max_attempts: u32) -> io::Result<String> { let mut attempt = 1; let mut backoff = Duration::from_mill...
The function implements a resilient retry mechanism with exponential backoff for network requests. It initializes an attempt counter at 1 and a base delay of 500 milliseconds. The code then enters an infinite loop that repeatedly attempts to call the helper function `http_req`. On success, it immediately returns the fe...
code_explanation
std
233
237
Explain what a Rust snippet does in plain English. use std::fs::File; use std::io::{self, BufRead}; use std::num::ParseIntError; #[derive(Debug)] enum ParseError { Io(io::Error), Parse(ParseIntError), } type Result<T> = std::result::Result<T, ParseError>; fn parse_positive_ints(path: &str) -> Result<Vec<i32...
The function begins by attempting to open a file at the provided path. If the file system returns an error, the code uses map_err to wrap that error into a custom ParseError::Io variant and immediately returns it, preventing further execution. Next, it wraps the successfully opened file handle in a BufReader to enable ...
code_explanation
std
168
209
Explain what a Rust snippet does in plain English. Parsing configuration strings with comment filtering and error handling. fn parse_config(input: &str) -> Result<Vec<(String, String)>, String> { input .lines() .filter(|line| !line.trim().is_empty() && !line.starts_with('#')) .map(|line| {...
The function `parse_config` accepts a string slice and returns a `Result` containing either a vector of key-value pairs or an error string. 1. It creates an iterator over the lines of the input string. 2. It filters the lines, discarding any that are empty (after trimming whitespace) or start with a '#' character to ...
code_explanation
std
151
268
Explain what a Rust snippet does in plain English. use std::time::Duration; use tokio::time::{sleep, timeout}; async fn fetch_with_retry<F, Fut, T>( max_retries: u32, initial_delay: Duration, mut fetch_fn: F, ) -> Result<T, String> where F: FnMut() -> Fut, Fut: std::future::Future<Output = Result<...
The function fetch_with_retry accepts three parameters: the maximum number of retry attempts, the starting delay between retries, and a closure that performs the actual fetch operation. It initializes a delay variable to the initial delay value. It then enters a loop that runs from 1 up to the maximum number of retries...
code_explanation
tokio
236
279
Explain what a Rust snippet does in plain English. Custom arena allocator implementation using unsafe block, raw pointers, and Box::into_raw. struct Arena<T> { data: Vec<*mut T>, } impl<T> Arena<T> { fn new() -> Self { Arena { data: Vec::new() } } fn alloc(&mut self, value: T) -> &mut T { ...
The code defines an `Arena<T>` struct that manages a collection of heap-allocated values of type `T` using manual memory management. The `new` function initializes an empty arena with no data. The `alloc` method allows inserting new values: it takes a value, wraps it in a `Box`, and converts that `Box` into a raw point...
code_explanation
std
115
205
Explain what a Rust snippet does in plain English. use tokio::sync::mpsc; use tokio::task; async fn process_task(id: u32) -> String { format!("Processed task {}", id) } async fn spawn_worker_pool(tasks: Vec<u32>, max_workers: usize) -> Vec<String> { let (tx, mut rx) = mpsc::channel::<String>(max_workers); ...
Step 1: The function creates a bounded asynchronous message channel (mpsc) to pass results back from worker tasks to the main task, with capacity limited by max_workers. Step 2: It initializes a vector to hold task handles and iterates through the input tasks. Step 3: For each task ID, it clones the sender end of the c...
code_explanation
tokio
203
228
Explain what a Rust snippet does in plain English. Background network utility for batch processing with concurrency control and timeout handling use std::time::Duration; use tokio::sync::{Semaphore, mpsc}; use tokio::time::timeout; use futures::stream::FuturesUnordered; use futures::StreamExt; async fn fetch_with_ra...
The function fetch_with_rate_limit safely downloads multiple URLs concurrently while enforcing a strict concurrency limit and per-request timeout. Step 1: It initializes a semaphore with the maximum allowed concurrent operations and creates an asynchronous multi-producer single-consumer channel to collect results. Step...
code_explanation
tokio
373
305
Explain what a Rust snippet does in plain English. Used in background worker services to manage recurring maintenance tasks or health checks that must cleanly terminate during application shutdown without dropping pending messages. use tokio::sync::mpsc; use std::time::Duration; use thiserror::Error; #[derive(Error,...
The function implements a resilient background scheduler that periodically triggers status checks while remaining responsive to shutdown signals. First, it initializes a 30-second timer configured to delay on missed ticks, which prevents task pile-ups during system lag or high CPU load. Next, it enters a continuous loo...
code_explanation
tokio
299
241
Explain what a Rust snippet does in plain English. Implements a transaction guard using RAII pattern with explicit commit and automatic rollback semantics. use std::ops::Deref; pub struct QueryGuard<'a> { connection: &'a mut Connection, is_active: bool, } impl<'a> QueryGuard<'a> { pub fn new(conn: &'a m...
This code implements a RAII (Resource Acquisition Is Initialization) wrapper for a database connection called `QueryGuard`. It ensures transactional integrity by combining explicit commit logic with automatic rollback on scope exit. Step-by-step explanation: 1. **Construction**: When `QueryGuard::new` is called, it a...
code_explanation
db_tools
239
444
Explain what a Rust snippet does in plain English. Provides a reusable asynchronous retry mechanism with exponential backoff for handling transient failures in network requests or external API calls. use std::time::Duration; #[derive(Debug)] struct RetryError { attempts: u32, last_error: String, } async fn ...
The code defines an asynchronous function `fetch_with_retry` that implements a resilient fetching strategy using exponential backoff. It accepts two parameters: `max_retries`, which sets the limit on how many times to attempt the operation, and `fetch_fn`, a mutable closure that performs the actual fetch and returns a ...
code_explanation
retry_utils
253
268
Add inline // comments annotating a Rust snippet. pub fn parse_header(buffer: &[u8]) -> Result<PacketHeader, ParseError> { if buffer.len() < 4 { return Err(ParseError::Truncated); } let version = (buffer[0] >> 4) & 0xF; let flags = buffer[0] & 0xF; let checksum = u16::from_le_bytes([buffer[...
pub fn parse_header(buffer: &[u8]) -> Result<PacketHeader, ParseError> { if buffer.len() < 4 { return Err(ParseError::Truncated); } // Extract version and flags from the high and low nibbles of the first byte let version = (buffer[0] >> 4) & 0xF; let flags = buffer[0] & 0xF; // Combine b...
comment_generation
proto-parser
134
191
Add inline // comments annotating a Rust snippet. pub fn parse_24bit_offset(bytes: &[u8]) -> Result<i32, &'static str> { if bytes.len() < 3 { return Err("buffer too short"); } let val = ((bytes[0] as i32) << 16) | ((bytes[1] as i32) << 8) | (bytes[2] as i32); if val >= 0x800000 { Ok(val...
pub fn parse_24bit_offset(bytes: &[u8]) -> Result<i32, &'static str> { // Ensure the slice contains enough bytes for a 24-bit value if bytes.len() < 3 { return Err("buffer too short"); } // Manually reconstruct big-endian 24-bit integer: // shift first byte to high 16 bits, second to middle ...
comment_generation
binary-protocols
92
175
Add inline // comments annotating a Rust snippet. Data ingestion module for parsing and validating system log streams in a background worker service pub fn parse_log_entries(raw_lines: &[&str]) -> Vec<(u64, String)> { raw_lines .iter() .filter_map(|line| { let parts: Vec<&str> = line.s...
pub fn parse_log_entries(raw_lines: &[&str]) -> Vec<(u64, String)> { // Use filter_map to both filter out malformed lines and transform valid ones in one pass raw_lines .iter() .filter_map(|line| { // splitn(2, ':') ensures we only split on the first colon, preserving colons in the m...
comment_generation
log_processor
135
220
Add inline // comments annotating a Rust snippet. Rate-limiting middleware for HTTP API gateway handling burst traffic and enforcing per-client quotas use std::sync::Mutex; use std::time::{Duration, Instant}; pub struct TokenBucket { max_tokens: u32, tokens: Mutex<u32>, last_refill: Mutex<Instant>, r...
use std::sync::Mutex; use std::time::{Duration, Instant}; pub struct TokenBucket { max_tokens: u32, tokens: Mutex<u32>, last_refill: Mutex<Instant>, refill_rate: Duration, } impl TokenBucket { pub fn try_consume(&self, count: u32) -> Result<(), String> { // Acquire lock on tokens, handling...
comment_generation
gateway-core
268
373
Add inline // comments annotating a Rust snippet. utility::compression::rle fn rle_decode(data: &[u8]) -> Vec<u8> { let mut result = Vec::new(); let mut iter = data.iter(); while let Some(&count) = iter.next() { if count == 0 { break; } let val = iter.next().unwrap(); ...
fn rle_decode(data: &[u8]) -> Vec<u8> { // Initialize empty vector to store decoded bytes. let mut result = Vec::new(); // Create an iterator over the input data bytes. let mut iter = data.iter(); // Loop while there is a count byte available. // Destructure the count from the Option<&u8> return...
comment_generation
data_utils
101
220
Add inline // comments annotating a Rust snippet. Parses a simplified semantic version string into core components and validates pre-release identifiers according to semver specification rules. fn parse_semver_core(input: &str) -> Result<(u64, u64, u64, Option<Vec<String>>), String> { let core_and_pre = input.spl...
fn parse_semver_core(input: &str) -> Result<(u64, u64, u64, Option<Vec<String>>), String> { // Split only once to separate core version from pre-release metadata, ignoring build tags let core_and_pre = input.splitn(2, '-').collect::<Vec<&str>>(); let core = core_and_pre.first().ok_or("Missing version core")...
comment_generation
semver_parser
343
418
Add inline // comments annotating a Rust snippet. High-performance binary protocol parser handling variable-length field decoding without allocation. pub fn read_variable_length_field(data: &[u8], start: usize) -> Result<(usize, &[u8]), String> { let mut length = 0u32; let mut shift = 0; let mut i = start...
pub fn read_variable_length_field(data: &[u8], start: usize) -> Result<(usize, &[u8]), String> { let mut length = 0u32; let mut shift = 0; let mut i = start; while i < data.len() { let byte = data[i]; // Mask out the continuation bit (MSB) and shift it into the accumulating length. ...
comment_generation
byte-stream-decoder
205
267
Add inline // comments annotating a Rust snippet. use std::fmt; pub enum ParseError { InvalidLength, MissingValue, Utf8Error(std::str::Utf8Error), } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseError::InvalidLength...
use std::fmt; pub enum ParseError { InvalidLength, MissingValue, Utf8Error(std::str::Utf8Error), } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseError::InvalidLength => write!(f, "Entry too short"), Parse...
comment_generation
synthetic
305
136
Add inline // comments annotating a Rust snippet. async fn parse_header(payload: &[u8]) -> Result<Header, ParseError> { if payload.len() < HEADER_SIZE { return Err(ParseError::InvalidLength); } let version = (payload[0] >> 4) & 0x0F; let flags = payload[0] & 0x0F; let sequence = u32::from_b...
async fn parse_header(payload: &[u8]) -> Result<Header, ParseError> { // Early exit if payload doesn't contain a complete header block if payload.len() < HEADER_SIZE { return Err(ParseError::InvalidLength); } // Extract version and flags from the first byte using bitwise masking let version ...
comment_generation
net-protocol
167
251
Add inline // comments annotating a Rust snippet. Function parses event strings in 'key=value' format, aggregates numeric values by key, and returns a sorted map of metrics. Handles malformed input and parse errors gracefully. use std::collections::BTreeMap; pub fn aggregate_metrics(events: &[&str]) -> Result<BTreeM...
use std::collections::BTreeMap; pub fn aggregate_metrics(events: &[&str]) -> Result<BTreeMap<String, u64>, String> { let mut metrics: BTreeMap<String, u64> = BTreeMap::new(); for event in events { // splitn with limit 2 ensures we only split on the first '='; // this allows values to conta...
comment_generation
metrics_utils
214
313
Produce a one-line summary of a Rust function's purpose. fn normalize_usernames(raw_input: &[String]) -> Vec<String> { raw_input.iter() .filter_map(|s| { let trimmed = s.trim(); if trimmed.len() >= 3 && trimmed.len() <= 20 && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_') ...
Filters and normalizes a list of raw strings by enforcing length constraints, allowing only alphanumeric characters and underscores, and converting valid entries to lowercase.
code_summarization
auth-utils
113
43
Produce a one-line summary of a Rust function's purpose. pub fn calculate_rolling_average(data: &[f64], window_size: usize) -> Result<Vec<f64>, &'static str> { if window_size == 0 || window_size > data.len() { return Err("window_size must be between 1 and data length"); } Ok(data.windows(window_siz...
Computes a sliding window average over a slice of floating-point numbers, returning an error for invalid window sizes.
code_summarization
data_processing
101
29
Produce a one-line summary of a Rust function's purpose. pub fn calculate_tiered_discount(total: f64, quantity: u32) -> f64 { let max_allowed = total * 0.25; let base_discount = (quantity as f64).clamp(0.0, 100.0) * 0.02; let bonus_discount = (quantity.max(100) as f64 - 100.0) * 0.05; (base_discount + ...
This function computes an order discount capped at 25 percent of the total, applying standard and bonus rates based on quantity thresholds.
code_summarization
pricing_engine
90
34
Produce a one-line summary of a Rust function's purpose. use reqwest::Client; use std::time::Duration; async fn fetch_with_exponential_backoff(client: &Client, url: &str, max_retries: u32) -> Result<String, Box<dyn std::error::Error>> { let mut retries = 0; loop { match client.get(url).send().await { ...
Retries an HTTP GET request up to a specified limit with exponential backoff on non-success responses and returns the final response body as a string.
code_summarization
reqwest
196
37
Produce a one-line summary of a Rust function's purpose. async fn load_config(path: &str) -> Result<AppConfig, Box<dyn std::error::Error>> { let contents = tokio::fs::read_to_string(path).await?; let config: AppConfig = serde_json::from_str(&contents)?; if config.port > 65535 || config.port == ...
Reads a JSON configuration file from disk, deserializes it into an AppConfig struct, validates the port number, and returns the result with appropriate error handling.
code_summarization
app_server_core
103
41
Produce a one-line summary of a Rust function's purpose. pub fn moving_average(values: &[Option<f64>], window_size: usize) -> Vec<f64> { values .windows(window_size) .map(|w| { let valid: Vec<f64> = w.iter().filter_map(|v| *v).collect(); if valid.is_empty() { 0.0 } else { va...
Computes a sliding window average from a slice of optional floating-point values, treating missing entries as gaps that are excluded from the calculation.
code_summarization
signal-processing
99
38
Produce a one-line summary of a Rust function's purpose. fn parse_retry_policy(config: &serde_json::Value) -> Result<RetryPolicy, String> { let max_retries = config.get("max_retries").and_then(|v| v.as_u64()).unwrap_or(3); let base_delay_ms = config.get("base_delay_ms").and_then(|v| v.as_u64()).unwrap_or(100);...
Extracts and validates retry configuration parameters from a JSON object, applying sensible defaults and returning a typed policy struct.
code_summarization
my_app::network::config
151
34
Produce a one-line summary of a Rust function's purpose. pub fn normalize_ipv4(input: &str) -> Option<std::net::Ipv4Addr> { let segments: Vec<&str> = input.split('.').collect(); if segments.len() != 4 { return None; } let mut octets = [0u8; 4]; for (i, seg) in segments.iter().enumerate() { ...
Parses a dotted-quad string into a validated IPv4 address, returning None if the format is invalid or octets exceed 255.
code_summarization
net-utils
103
30
Produce a one-line summary of a Rust function's purpose. fn extract_trace_id(headers: &http::HeaderMap) -> Result<String, String> { headers .get("X-Trace-Id") .or_else(|| headers.get("x-trace-id")) .and_then(|v| v.to_str().ok()) .filter(|s| s.len() == 32 && s.chars().all(|c| c.is_as...
Extracts and validates a 32-character hexadecimal trace ID from HTTP headers, returning a lowercase string or an error if missing or malformed.
code_summarization
http-middleware
109
35
Produce a one-line summary of a Rust function's purpose. User authentication validation pub fn parse_username(buf: &[u8]) -> Result<&str, ParseError> { const MAX_LEN: usize = 32; const VALID_CHARS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; if buf.is_empty() || buf.len...
Validates and parses a byte buffer into a trimmed username, enforcing length limits, UTF-8 validity, and character whitelist constraints.
code_summarization
auth-utils
147
34
Choose an idiomatic snake_case name for an unnamed Rust function body. Validates an email address string, ensuring it is not empty and matches a standard regex format, returning the lowercased version or an error. fn unnamed(input: &str) -> Result<String, String> { let trimmed = input.trim(); if trimmed.is_em...
validate_email
function_naming
auth_utils
141
3
Choose an idiomatic snake_case name for an unnamed Rust function body. Data processing utility module fn unnamed(input: &str, threshold: f64) -> Vec<DataPoint> { input.lines() .skip(1) .filter_map(|line| { let mut parts = line.split(','); let label = parts.next()?; ...
filter_data_above_threshold
function_naming
metrics_processor
122
6
Choose an idiomatic snake_case name for an unnamed Rust function body. fn unnamed(config_lines: &[String]) -> Result<std::collections::HashMap<String, String>, String> { let mut config_map = std::collections::HashMap::new(); for line in config_lines { let trimmed = line.trim(); ...
parse_config_lines_to_map
function_naming
config_loader
183
6
Choose an idiomatic snake_case name for an unnamed Rust function body. fn unnamed(data: &[u8]) -> Result<Vec<u8>, &'static str> { if data.len() < 4 { return Err("Packet too short"); } let checksum = data[data.len() - 1]; let computed = data[..data.len() - 1].iter().fold(0u8, |acc, &b| acc.wrapping_add(b)); if checksum...
extract_packet_payload
function_naming
net_parser
101
5
Choose an idiomatic snake_case name for an unnamed Rust function body. fn unnamed(users: &[User], config: &AppConfig) -> Vec<String> { users.iter().filter(|u| u.is_active(config)).map(|u| u.name.clone()).collect() }
get_active_user_names
function_naming
user_service
54
5
Choose an idiomatic snake_case name for an unnamed Rust function body. Parses a JWT string, verifies the HMAC-SHA256 signature against the provided secret, decodes the base64 payload, checks the expiration time, and returns the parsed claims or an error. fn unnamed(token: &str, secret: &[u8]) -> Result<Claims, TokenE...
verify_and_extract_jwt_claims
function_naming
auth-crypto
229
7
Choose an idiomatic snake_case name for an unnamed Rust function body. Utility function within an authentication middleware crate that parses a JSON Web Token, validates its signature and expiration, and retrieves the embedded user identifier. fn unnamed(auth_token: &str) -> Result<UserId, AuthError> { let payloa...
extract_user_id_from_jwt
function_naming
user_auth_core
114
6
Choose an idiomatic snake_case name for an unnamed Rust function body. fn unnamed(r: u8, g: u8, b: u8) -> (u8, u8, u8) { let luminance = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32; let boost = if luminance < 128.0 { 1.2 } else { 0.8 }; ( (r as f32 * boost).clamp(0.0, 255.0) as u8, ...
apply_contrast_adjustment
function_naming
ui_utils
106
6
Choose an idiomatic snake_case name for an unnamed Rust function body. fn unnamed(session: &mut Session, config: &SystemConfig) -> Result<(), AuthError> { let now = std::time::SystemTime::now(); if session.expires_at <= now { session.refresh_token(config.token_ttl)?; session.update_expiry(now, ...
refresh_session_if_expiring
function_naming
auth_service
89
6
Choose an idiomatic snake_case name for an unnamed Rust function body. Module responsible for loading and validating server configuration from disk. fn unnamed(config_path: &str) -> Result<ServerConfig, ParseError> { let content = std::fs::read_to_string(config_path)?; let mut config: ServerConfig = config::f...
parse_server_config
function_naming
server_bootstrap
116
4
Choose idiomatic names for placeholder Rust variables. Binary packet processing function that parses a header into a tuple containing the packet type and raw payload, then deserializes the payload into a message struct. fn handle_packet(_0: &[u8]) { let _1 = parse_header(_0); match _1 { Ok((_2, _3)) =...
fn handle_packet(raw_packet: &[u8]) { let header_info = parse_header(raw_packet); match header_info { Ok((packet_type, payload)) => { let message = deserialize_payload(payload); process(message); } Err(parse_error) => log_error(parse_error), } }
variable_naming
network_protocol_parser
111
76
Choose idiomatic names for placeholder Rust variables. Parsing binary protocol frames for an IoT temperature sensor, extracting device ID, mode bits, and converting raw ADC readings to calibrated temperature values. fn parse_sensor_frame(bytes: &[u8]) -> Result<SensorReading, ParseError> { let _0 = bytes[0]; ...
fn parse_sensor_frame(bytes: &[u8]) -> Result<SensorReading, ParseError> { let header_byte = bytes[0]; let control_flags = bytes[1]; let raw_adc_value = u16::from_be_bytes([bytes[2], bytes[3]]); let device_id = header_byte & 0x0F; let mode_bits = control_flags >> 4; let calibrated_temp = raw_adc...
variable_naming
iot_sensor_parser
155
135
Choose idiomatic names for placeholder Rust variables. Parsing a binary IoT sensor protocol packet containing magic number, payload length, CRC checksum, and variable payload data. fn parse_packet(socket: &mut TcpStream) -> Result<Payload, Error> { let mut buffer = [0u8; 1024]; let raw = socket.read(&mut buff...
fn parse_packet(socket: &mut TcpStream) -> Result<Payload, Error> { let mut buffer = [0u8; 1024]; let raw = socket.read(&mut buffer)?; let magic_bytes = &buffer[0..4]; let length_bytes = &buffer[4..6]; let checksum_bytes = &buffer[6..10]; let payload_bytes = &buffer[10..raw]; let packe...
variable_naming
iot-sensor-bridge
232
227
Choose idiomatic names for placeholder Rust variables. Parsing a custom binary protocol frame: extracting a big-endian frame type from the first two bytes, slicing the payload based on that type, and extracting a sequence ID immediately following the payload. fn handle_frame(data: &[u8]) -> Result<(), &'static str> {...
fn handle_frame(data: &[u8]) -> Result<(), &'static str> { let frame_type_code = u16::from_be_bytes([data[0], data[1]]); let payload_slice = &data[2..2 + frame_type_code as usize]; let sequence_id = data[2 + frame_type_code as usize]; match frame_type_code { 0x10 => transmit(payload_slice, seque...
variable_naming
protocol_core
145
108
Choose idiomatic names for placeholder Rust variables. Deserializing a binary network protocol header containing magic bytes, version, length, and string data. fn deserialize_packet(raw: &[u8]) -> std::io::Result<Packet> { let mut cursor = Cursor::new(raw); let _0 = u32::from_be_bytes(read_u32(&mut cursor)?);...
fn deserialize_packet(raw: &[u8]) -> std::io::Result<Packet> { let mut cursor = Cursor::new(raw); let magic_signature = u32::from_be_bytes(read_u32(&mut cursor)?); let protocol_version = u16::from_be_bytes(read_u16(&mut cursor)?); let payload_length = read_u16(&mut cursor)?; let payload_data = read_...
variable_naming
binary-stream-parser
141
125
Choose idiomatic names for placeholder Rust variables. Parses control and routing fields from a custom binary packet header. let _0 = buffer[0]; let _1 = buffer[1]; let _2 = buffer[2]; let _3 = buffer[3]; let _4 = (buffer[4] as u32) << 24 | (buffer[5] as u32) << 16 | (buffer[6] as u32) << 8 | buffer[7]; l...
let frame_type = buffer[0]; let priority_level = buffer[1]; let protocol_version = buffer[2]; let payload_size = buffer[3]; let start_address = (buffer[4] as u32) << 24 | (buffer[5] as u32) << 16 | (buffer[6] as u32) << 8 | buffer[7]; let end_address = (buffer[8] as u32) << 24 | (buffer[9] as u32) << 16...
variable_naming
network_frame_decoder
108
92
Choose idiomatic names for placeholder Rust variables. Decodes a 32-bit hardware status register to extract temperature code (upper nibble) and fan speed setting (lower nibble). fn decode_status(_0: u32) -> (u32, u32) { let _1 = (_0 & 0xF0) >> 4; let _2 = _0 & 0x0F; (_1, _2) }
fn decode_status(raw_status: u32) -> (u32, u32) { let temperature_code = (raw_status & 0xF0) >> 4; let fan_speed_nibble = raw_status & 0x0F; (temperature_code, fan_speed_nibble) }
variable_naming
periph-driver
72
47
Choose idiomatic names for placeholder Rust variables. Parsing a binary network packet from a byte buffer, extracting the header type, computing the payload checksum, and verifying the CRC against the header before returning the processed data. let _0 = parse_header(&buffer)?; let _1 = extract_checksum(&buffer)?; let...
let header = parse_header(&buffer)?; let checksum = extract_checksum(&buffer)?; let validation_passed = validate_crc(&buffer, header)?; if validation_passed { return ProcessResult::Ok(header, checksum); }
variable_naming
packet_parser
99
51
Choose idiomatic names for placeholder Rust variables. Reading and extracting an API key from a TOML configuration file. let _0 = fs::read_to_string("config.toml")?; let _1 = parse_config(&_0); let _2 = _1.get("api_key"); Ok(_2)
let config_content = fs::read_to_string("config.toml")?; let parsed_config = parse_config(&config_content); let api_key = parsed_config.get("api_key"); Ok(api_key)
variable_naming
config_loader
57
40
Choose idiomatic names for placeholder Rust variables. Processing network response data let _0 = parse_header(raw)?; let _1 = extract_payload(raw, _0.offset)?; let _2 = validate_checksum(_1)?;
let header = parse_header(raw)?; let payload = extract_payload(raw, header.offset)?; let validated_data = validate_checksum(payload)?;
variable_naming
net_protocol
48
33
Review a Rust snippet and note style, safety, or correctness issues. Function extracts a dynamic prefix string and attempts to return a slice. fn get_prefix(s: &str) -> &str { let temp = format!("prefix_{}", s); temp.as_str() }
CRITICAL: Dangling reference returned. `temp` is a local `String` that is dropped at the end of the function scope. Calling `temp.as_str()` creates a reference to memory that will be freed, resulting in undefined behavior. Fix: Return the `String` directly (ownership transfer) or use a static slice if the prefix is kno...
code_review
string_utils
59
107
Review a Rust snippet and note style, safety, or correctness issues. Function `filter_logs` filters a batch of log strings based on a severity level defined in a configuration HashMap. It is part of a high-throughput logging subsystem where efficiency is critical. use std::collections::HashMap; const FILTER_KEY: &st...
**Review: Redundant HashMap Lookups and Loop Invariant** **Issues:** 1. **Double Lookup per Iteration:** The code calls `config.contains_key` followed immediately by `config.get`. This results in two hash computations and lookups for every log entry. Additionally, the configuration lookup is a loop invariant; the resu...
code_review
log_processor
189
318
Review a Rust snippet and note style, safety, or correctness issues. Request validation middleware in a high-traffic API gateway pub fn sanitize_input(input: &str) -> String { let trimmed = input.trim(); let normalized = trimmed.to_string().replace('\n', " "); normalized.to_lowercase() }
Review: The function `sanitize_input` suffers from redundant heap allocations. Calling `to_string()` on `trimmed` creates an intermediate String even if `input` was already trimmed. The subsequent `replace` and `to_lowercase` calls create additional temporary Strings. For clean inputs, this results in three allocations...
code_review
gateway_middleware
75
206
Review a Rust snippet and note style, safety, or correctness issues. Configuration loader utility. fn load_config(path: &str) -> String { let contents = std::fs::read_to_string(path).unwrap(); contents }
Issue: `unwrap()` on `read_to_string` converts a recoverable `io::Error` (e.g., file not found, permission denied) into a hard panic. This makes the function unsafe for untrusted or dynamic paths and hides error handling. Fix: Return `Result<String, std::io::Error>` and use the `?` operator to propagate errors, allowi...
code_review
app-config
53
97
Review a Rust snippet and note style, safety, or correctness issues. API response handler extracting a required field from untrusted JSON input. pub fn extract_user_id(payload: &serde_json::Value) -> String { let uid = payload.get("user_id").unwrap().as_str().unwrap(); uid.to_string() }
Issue: Double unwrap on JSON access. If the key 'user_id' is missing or not a string, this panics with a cryptic message. This is poor error handling for API/server code. Fix: Use and_then chains or return Result<String, Error>. Example: `payload.get("user_id").and_then(|v| v.as_str()).map(|s| s.to_string())` or propag...
code_review
web-service-core
74
95
Review a Rust snippet and note style, safety, or correctness issues. Module for constructing JSON fragments for an HTTP response builder. pub fn serialize_items(items: &[String]) -> Vec<String> { items .iter() .map(|item| format!("{{\"label\": \"{}\"}}", item).to_string()) .collect() }
Review: The `format!` macro returns a `String`. Chaining `.to_string()` immediately after results in a redundant allocation, as `to_string()` on a `String` simply clones the underlying buffer. This doubles memory usage for the string data in this loop. Fix: Remove `.to_string()`. The `map` closure already yields a `Str...
code_review
response-builder
79
139
Review a Rust snippet and note style, safety, or correctness issues. Signal processing module for telemetry aggregation. pub fn get_peak_index(data: &[f64]) -> usize { data.iter() .enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) .unwrap() .0 }
Review: This function contains two subtle panic vectors. 1. The inner `.unwrap()` on `partial_cmp` will panic if `data` contains `NaN` values, as `partial_cmp` returns `None` for NaN comparisons. 2. The outer `.unwrap()` panics on empty slices, which may be a valid state for this metric. Suggested Fix: Return `Option<u...
code_review
signal-utils
72
124
Review a Rust snippet and note style, safety, or correctness issues. Function used in a terminal UI widget to clip long log messages before rendering to the console. Relies on accurate character counting for visual alignment. pub fn truncate_display(text: &str, max_chars: usize) -> &str { if text.len() <= max_cha...
Issues found: 1. **UTF-8 Panic Risk**: The variable `max_chars` suggests the user wants to truncate based on character count, but `&text[max_chars..]` slices by byte index. If `max_chars` falls within a multi-byte UTF-8 sequence, this will panic at runtime. 2. **Semantic Mismatch**: The function name `truncate_display`...
code_review
term-ui-helper
137
218
Review a Rust snippet and note style, safety, or correctness issues. Data processing pipeline for log aggregation. fn deduplicate_items(mut items: Vec<String>) -> Vec<String> { items.sort(); let mut i = 0; while i < items.len() { if i > 0 && items[i] == items[i - 1] { items.remove(i); ...
**Review Notes:** - **Issue:** `Vec::remove` shifts all subsequent elements to fill the gap, resulting in O(N²) complexity for this deduplication logic. - **Suggestion:** Use `Vec::dedup()` which is optimized for this pattern, or iterate in reverse to avoid shifting overhead. Alternatively, collect unique elements into...
code_review
log_processor
96
122
Review a Rust snippet and note style, safety, or correctness issues. Email extraction utility in a data processing pipeline use regex::Regex; fn extract_emails(text: &str) -> Vec<String> { let re = Regex::new(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+...
**Review:** 1. **Regex Compilation Overhead**: The `Regex::new` call is inside the function, causing the regex to be compiled on every invocation. This is a significant performance bottleneck. Move compilation to a `static` variable using `lazy_static` or `once_cell`, or use the `regex!` macro. 2. **Unsafe Unwrap**: ...
code_review
email_utils
107
317
Complete the missing tail of a partial Rust snippet. fn calculate_discount(price: f64, rate: f64) -> f64 { let discount_amount = price * rate; // TODO }
fn calculate_discount(price: f64, rate: f64) -> f64 { let discount_amount = price * rate; price - discount_amount }
code_completion
40
30
Complete the missing tail of a partial Rust snippet. async fn fetch_with_retry(url: &str, max_retries: u32) -> Result<String, Box<dyn std::error::Error>> { let client = reqwest::Client::new(); for attempt in 0..max_retries { match client.get(url).send().await { Ok(response) ...
async fn fetch_with_retry(url: &str, max_retries: u32) -> Result<String, Box<dyn std::error::Error>> { let client = reqwest::Client::new(); for attempt in 0..max_retries { match client.get(url).send().await { Ok(response) => { if response.status().is_succe...
code_completion
http_utils
103
199
Complete the missing tail of a partial Rust snippet. pub fn next_prime(start: u64) -> u64 { let mut candidate = start + 1; while !is_prime(candidate) { candidate += 1; } // TODO } fn is_prime(n: u64) -> bool { if n <= 1 { return false; } if n <= 3 { return true; } if n % 2 == 0 || ...
pub fn next_prime(start: u64) -> u64 { let mut candidate = start + 1; while !is_prime(candidate) { candidate += 1; } candidate } fn is_prime(n: u64) -> bool { if n <= 1 { return false; } if n <= 3 { return true; } if n % 2 == 0 || n % 3 == 0 { return false; } let mut i = 5; ...
code_completion
math_utils
120
107
Complete the missing tail of a partial Rust snippet. fn calculate_median(numbers: &[f64]) -> Option<f64> { if numbers.is_empty() { return None; } let mut sorted = numbers.to_vec(); sorted.sort_by(|a, b| a.partial_cmp(b).unwrap()); // TODO
fn calculate_median(numbers: &[f64]) -> Option<f64> { if numbers.is_empty() { return None; } let mut sorted = numbers.to_vec(); sorted.sort_by(|a, b| a.partial_cmp(b).unwrap()); let len = sorted.len(); if len % 2 == 0 { let mid = len / 2; Some((sorted[mid - 1] + sorted[mi...
code_completion
math_utils
66
95
Complete the missing tail of a partial Rust snippet. pub fn parse_config_block(raw: &str) -> Result<HashMap<String, Vec<String>>, String> { let mut result = HashMap::new(); let mut current_key = String::new(); let mut current_values = Vec::new(); let mut in_block = false; for line in raw.lines() {...
pub fn parse_config_block(raw: &str) -> Result<HashMap<String, Vec<String>>, String> { let mut result = HashMap::new(); let mut current_key = String::new(); let mut current_values = Vec::new(); let mut in_block = false; for line in raw.lines() { let trimmed = line.trim(); if trimmed...
code_completion
config_parser
114
230
Complete the missing tail of a partial Rust snippet. fn find_first_even(numbers: &[i32]) -> Option<i32> { for num in numbers { // TODO } None }
fn find_first_even(numbers: &[i32]) -> Option<i32> { for num in numbers { if num % 2 == 0 { return Some(*num); } } None }
code_completion
utils
41
40
Complete the missing tail of a partial Rust snippet. use std::collections::HashMap; pub fn parse_config(raw: &str) -> Result<HashMap<String, String>, String> { let mut map = HashMap::new(); for line in raw.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { ...
use std::collections::HashMap; pub fn parse_config(raw: &str) -> Result<HashMap<String, String>, String> { let mut map = HashMap::new(); for line in raw.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let parts: Vec<&str> =...
code_completion
config_utils
173
189
Complete the missing tail of a partial Rust snippet. // This function implements a robust retry mechanism with exponential backoff // and jitter-capped delays, commonly used in distributed system clients. // Requires: tokio = { version = "1", features = ["time"] } use std::time::Duration; use std::future::Future; pu...
use std::time::Duration; use std::future::Future; pub async fn retry_with_backoff<F, Fut, T, E>( mut attempt: u32, max_retries: u32, base_delay: Duration, max_delay: Duration, mut func: F, ) -> Result<T, E> where F: FnMut() -> Fut, Fut: Future<Output = Result<T, E>>, E: std::error::Erro...
code_completion
retry_utils
231
194
Complete the missing tail of a partial Rust snippet. fn compute_moving_average(data: &[f64], window: usize) -> Vec<f64> { if window == 0 || data.is_empty() { return Vec::new(); } let mut result = Vec::with_capacity(data.len() - window + 1); for i in 0..=data.len() - window { let window_...
fn compute_moving_average(data: &[f64], window: usize) -> Vec<f64> { if window == 0 || data.is_empty() { return Vec::new(); } let mut result = Vec::with_capacity(data.len() - window + 1); for i in 0..=data.len() - window { let window_slice = &data[i..i + window]; let sum: f64 = w...
code_completion
signal_processing
96
101
Complete the missing tail of a partial Rust snippet. fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, HexError> { if hex.len() % 2 != 0 { return Err(HexError::OddLength); } // TODO
fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, HexError> { if hex.len() % 2 != 0 { return Err(HexError::OddLength); } (0..hex.len()) .step_by(2) .map(|i| u8::from_str_radix(&hex[i..i+2], 16)) .collect::<Result<Vec<u8>, _>>() .map_err(HexError::Parse) }
code_completion
utils
49
75
Rewrite a working Rust snippet into a more idiomatic form. Parses and filters log entries by severity level, returning formatted strings for ERROR and WARN entries. fn validate_logs(lines: &[String]) -> Result<Vec<String>, String> { let mut valid_logs = Vec::new(); let mut idx = 0; while idx < lines.len()...
fn validate_logs(lines: &[String]) -> Result<Vec<String>, String> { lines .iter() .enumerate() .map(|(_, line)| { if line.is_empty() { return Err("empty line".to_string()); } let (level, msg) = line.split_once(':').ok_or("malformed line".to...
code_refactoring
log_processor
244
139
Rewrite a working Rust snippet into a more idiomatic form. fn calculate_even_sum(input: &str) -> Result<i32, String> { let mut sum = 0; let mut index = 0; let parts: Vec<&str> = input.split(',').collect(); while index < parts.len() { let part = parts[index]; let trimmed = part.trim...
fn calculate_even_sum(input: &str) -> Result<i32, std::num::ParseIntError> { input .split(',') .map(|s| s.trim().parse::<i32>()) .collect::<Result<Vec<i32>, _>>()? .into_iter() .filter(|&n| n % 2 == 0) .sum() }
code_refactoring
data_processor
169
65
Rewrite a working Rust snippet into a more idiomatic form. Refactor manual HashMap conditional insertion to use the Entry API, eliminating redundant branching and potential cloning overhead. use std::collections::HashMap; fn hash_score(s: &str) -> usize { s.len() } fn aggregate_scores(players: &[String]) -> HashMap...
use std::collections::HashMap; fn hash_score(s: &str) -> usize { s.len() } fn aggregate_scores(players: &[String]) -> HashMap<String, Vec<usize>> { let mut map = HashMap::new(); for player in players { let score = hash_score(player); map.entry(player.clone()).or_insert_with(Vec::new).push(scor...
code_refactoring
game_stats
156
84
Rewrite a working Rust snippet into a more idiomatic form. Refactoring manual async task spawning and nested error matching to use the tokio::join! macro for concurrent execution and the ?? operator for concise error propagation, reducing boilerplate and improving readability. use tokio; async fn fetch_users() -> Re...
pub async fn generate_report() -> Result<String, Box<dyn std::error::Error>> { let (users, stats) = tokio::join!(fetch_users(), fetch_stats()); let users = users??; let (score, status) = stats??; Ok(format!("Report: {} users, Score: {}, Status: {}", users.len(), score, status)) ...
code_refactoring
reporting-service
340
80
Rewrite a working Rust snippet into a more idiomatic form. Refactors a configuration file processor to replace manual error matching and string building with the `?` operator, `thiserror` for typed errors, and `Iterator::join` for efficient string concatenation. use std::fs; use std::io; pub fn process_config(path: ...
use std::fs; use thiserror::Error; #[derive(Error, Debug)] pub enum ConfigError { #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("UTF-8 error: {0}")] Utf8(#[from] std::utf8::Error), #[error("File is empty")] Empty, #[error("No lines")] NoLines, } pub fn process_config(pa...
code_refactoring
config_parser
291
176
Rewrite a working Rust snippet into a more idiomatic form. Utility for formatting text messages from word slices. fn build_message(words: &[&str]) -> String { let mut result = String::new(); for i in 0..words.len() { if i > 0 { result.push(' '); } result.push_str(words[i]);...
fn build_message(words: &[&str]) -> String { words.join(" ") }
code_refactoring
msg_builder
84
16
Rewrite a working Rust snippet into a more idiomatic form. A data ingestion module that separates numerically valid records from malformed ones for batch processing. The original code manually managed two vectors with capacity hints and conditional pushes, creating verbose iteration logic. The refactor uses Iterator::...
pub fn classify_records(records: &[String]) -> (Vec<String>, Vec<String>) { records.iter() .cloned() .partition(|r| r.parse::<f64>().is_ok()) }
code_refactoring
data_ingestion_core
208
40
Rewrite a working Rust snippet into a more idiomatic form. pub fn compute_discounted_prices(raw_data: &str) -> Result<Vec<f64>, String> { let mut prices = Vec::new(); let mut i = 0; let items: Vec<&str> = raw_data.split(',').collect(); while i < items.len() { let item = items[i]; match ...
#[derive(Debug)] pub struct PricingError(String); impl std::fmt::Display for PricingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl std::error::Error for PricingError {} pub fn compute_discounted_prices(raw_data: &str) -> Result<Vec<f64>, ...
code_refactoring
pricing-engine
235
208
Rewrite a working Rust snippet into a more idiomatic form. fn calculate_total_score(user_ids: &[u32], profiles: &std::collections::HashMap<u32, Profile>) -> Result<i32, String> { let mut total_score = 0i32; for i in 0..user_ids.len() { let user_id = user_ids[i]; match profiles.get(&user_id) { ...
fn calculate_total_score(user_ids: &[u32], profiles: &std::collections::HashMap<u32, Profile>) -> Result<i32, String> { user_ids .iter() .map(|&id| { let profile = profiles.get(&id).ok_or_else(|| format!("User {} not found", id))?; if !profile.active { return ...
code_refactoring
user_score_calculator
243
149
Rewrite a working Rust snippet into a more idiomatic form. Configuration loading logic in the main application server module, reading environment variables with defaults. use std::env; pub struct AppConfig { pub host: String, pub port: u16, pub debug: bool, } pub fn load_config() -> Result<AppConfig, St...
use std::env; pub struct AppConfig { pub host: String, pub port: u16, pub debug: bool, } pub fn load_config() -> Result<AppConfig, String> { let host = env::var("APP_HOST") .ok() .unwrap_or_else(|_| "localhost".to_string()); let port: u16 = env::var("APP_PORT") .ok() ...
code_refactoring
app-server
266
138
End of preview.

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

riir-train-open

Public mirror of the shareable subset of katopz/riir-train-data (private) — trained artifacts and corpora from the riir training research stack (Plan 444 Round 3, 2026-10-07). This repo starts PRIVATE (staging); the owner flips it public as a deliberate act.

What is here

Path What Trained on / source
heads/ Task-encoder heads + dataset case files (banking77, ag_news, emotion, sst5, massive, xnli, thai) public HF datasets (cases are public dataset text; heads are linear/eval artifacts)
weights/instinct_specialists/ Linear/NBSVM bag-model specialist heads public HF harness suites (vocabulary weights only — no span recovery)
weights/checkpoints/ gemma-2-2b LoRA adapters Strandset-Rust-v1 (Fortytwo-Network/Strandset-Rust-v1, public)
weights/tetris_critic*/ Tetris critic MLPs (5 revisions) self-play (our simulator)
models/ Go policy nets (CoreML + loose weights, 9x9/13x13/19x19), tiny CoreML testbeds, plan341 checkpoint self-play / our architecture testbeds
models/kimi-k3-0.40b/ Locally-built architecture testbed (not a download) our random/trained testbed bytes
corpora/plan318_teacher/ Teacher-generated training text MODEL-GENERATED by Qwen3.6-35B-A3B (Apache-2.0) over public Strandset-derived prompts
corpora/mining_v3/ Mined commit corpus public GitHub (rust-lang/rust, bevyengine/bevy) — MIT/Apache attribution duties apply to the upstream code

Integrity

OPEN_MANIFEST.tsv (this repo) pins rel_path | bytes | blake3 for every file. Verify a download with b3sum against it. The manifest is generated from the private lane's BACKUP_MANIFEST.tsv through a denylist + payload allowlist + leak content scan — it is the only publication authority.

Licenses (per group — no blanket license)

  • Dataset-derived cases: XNLI (CC BY-NC 4.0), SIB-200 (CC BY-SA 4.0 — share-alike applies to derived cases), AG News (academic use), MASSIVE (CC BY 4.0), banking77/emotion/sst5 (public research use). This repo is therefore licensed "other/mixed" — each group keeps its upstream terms.
  • weights/checkpoints/ are gemma-2 derivatives: Google's Gemma Terms of Use pass through to derivatives.
  • corpora/plan318_teacher/ text is Qwen3.6-generated; upstream Qwen terms apply to the generator, the text itself is ours.
  • corpora/mining_v3/ carries MIT/Apache code — attribution obligations ride the upstream repos; do not relicense.

What is NOT here (deliberate)

Corpora derived from private source trees (plan342/344/346/391, pav356), fleet decision rows (consent-gated), game-IP content, third-party model bytes (pins — fetch from upstream per the private repo's BASE_MODELS.md), device-bound encode caches, and all scripts/logs/run artifacts. The full backup lives in the private katopz/riir-train-data + katopz/riir-train-corpus.

Downloads last month
278