id stringclasses 50
values | testsource stringclasses 6
values | language stringclasses 6
values | prefix stringlengths 16 3.39k | golden_completion stringlengths 23 3.14k | suffix stringlengths 0 2.68k | assertions stringlengths 0 2.72k | category stringclasses 6
values |
|---|---|---|---|---|---|---|---|
1 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> FilterPositiveScores(List<int> scores)
{
return scores.Where(s => s > 0).ToList();
}
| static string DescribeFilterPositiveScores()
{
return "Filters the input list using LINQ Where with a predicate that "
+ "selects elements strictly greater than zero, then materializes "
+ "the result via ToList into a new List<int>. The source list is "
+ "not mod... | static void Main(string[] args)
{
var scores = new List<int> { -2, 5, 0, 7, -1, 9 };
var result = FilterPositiveScores(scores);
if (result.Count != 3) throw new Exception("Expected 3 positives");
if (scores[0] != -2 || scores.Count != 6) throw new Exception("Source modified");
... | string d1 = DescribeFilterPositiveScores();
string d1L = d1.ToLower();
if (!d1L.Contains("where")) throw new Exception("must mention Where");
if (!d1L.Contains("tolist")) throw new Exception("must mention ToList");
if (!d1L.Contains("predicate")) throw new Exception("must mention predicate");
if (!d1L.Contains("not mod... | code2NL_NL2code |
2 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static int GetOrDefault(Dictionary<string, int> map, string key, int fallback)
{
if (map.TryGetValue(key, out int value))
return value;
return fallback;
}
| static string DescribeGetOrDefault()
{
return "Looks up the key in the Dictionary using TryGetValue, which "
+ "performs an O(1) amortized hash-table probe and writes the "
+ "associated value to an out parameter when the key exists. "
+ "If TryGetValue returns fal... | static void Main(string[] args)
{
var map = new Dictionary<string, int> { { "a", 10 }, { "b", 20 } };
if (GetOrDefault(map, "a", -1) != 10) throw new Exception("wrong existing");
if (GetOrDefault(map, "c", -1) != -1) throw new Exception("wrong missing");
if (map.Count != 2) throw... | string d2 = DescribeGetOrDefault();
string d2L = d2.ToLower();
if (!d2L.Contains("trygetvalue")) throw new Exception("must mention TryGetValue");
if (!d2L.Contains("o(1)")) throw new Exception("must mention O(1) complexity");
if (!d2L.Contains("out parameter") && !d2L.Contains("out param")) throw new Exception("must me... | code2NL_NL2code |
3 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Text;
using System.Collections.Generic;
class Program
{
static string JoinWithSeparator(List<string> parts, string sep)
{
var sb = new StringBuilder();
for (int i = 0; i < parts.Count; i++)
{
if (i > 0) sb.Append(sep);
sb.Append(parts[i... | static string DescribeJoinWithSeparator()
{
return "Builds the result using a StringBuilder, appending each element "
+ "from the input List<string> with the separator inserted between "
+ "consecutive elements but not before the first or after the last. "
+ "Strin... | static void Main(string[] args)
{
var parts = new List<string> { "a", "b", "c" };
if (JoinWithSeparator(parts, "-") != "a-b-c") throw new Exception("wrong join");
if (JoinWithSeparator(new List<string>(), ",") != "") throw new Exception("empty fail");
string desc = DescribeJoinWi... | string d3 = DescribeJoinWithSeparator();
string d3L = d3.ToLower();
if (!d3L.Contains("stringbuilder")) throw new Exception("must mention StringBuilder");
if (!d3L.Contains("append")) throw new Exception("must mention Append");
if (!d3L.Contains("separator") || !d3L.Contains("between")) throw new Exception("must mentio... | code2NL_NL2code |
4 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> RunningMax(List<int> values)
{
var result = new List<int>();
values.Aggregate(int.MinValue, (acc, x) =>
{
int m = Math.Max(acc, x);
result.Add(m);
retu... | static string DescribeRunningMax()
{
return "Computes a running maximum by folding over the input list with "
+ "LINQ Aggregate. The seed is int.MinValue so the first element "
+ "always becomes the initial maximum. The accumulator function "
+ "calls Math.Max to c... | static void Main(string[] args)
{
var vals = new List<int> { 3, 1, 4, 1, 5 };
var rm = RunningMax(vals);
if (rm.Count != 5) throw new Exception("wrong count");
if (rm[0] != 3 || rm[2] != 4 || rm[4] != 5) throw new Exception("wrong values");
string desc = DescribeRunningMa... | string d4 = DescribeRunningMax();
string d4L = d4.ToLower();
if (!d4L.Contains("aggregate")) throw new Exception("must mention Aggregate");
if (!d4L.Contains("int.minvalue")) throw new Exception("must mention int.MinValue seed");
if (!d4L.Contains("math.max")) throw new Exception("must mention Math.Max");
if (!d4L.Cont... | code2NL_NL2code |
5 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> GetRange(SortedSet<int> set, int lo, int hi)
{
return set.GetViewBetween(lo, hi).ToList();
}
| static string DescribeGetRange()
{
return "Returns elements in the inclusive range [lo, hi] from a SortedSet "
+ "by calling GetViewBetween, which returns a virtual SortedSet view "
+ "backed by the same underlying red-black tree without copying. "
+ "Modifications... | static void Main(string[] args)
{
var set = new SortedSet<int> { 1, 3, 5, 7, 9, 11 };
var range = GetRange(set, 3, 9);
if (range.Count != 4) throw new Exception("wrong count");
if (range[0] != 3 || range[3] != 9) throw new Exception("wrong bounds");
string desc = Describe... | string d5 = DescribeGetRange();
string d5L = d5.ToLower();
if (!d5L.Contains("getviewbetween")) throw new Exception("must mention GetViewBetween");
if (!d5L.Contains("inclusive")) throw new Exception("must mention inclusive range");
if (!d5L.Contains("red-black") || !d5L.Contains("tree")) throw new Exception("must ment... | code2NL_NL2code |
6 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static List<string> RoundRobin(Queue<string> queue, int rounds)
{
var log = new List<string>();
for (int i = 0; i < rounds && queue.Count > 0; i++)
{
string item = queue.Dequeue();
log.Add(item);
... | static string DescribeRoundRobin()
{
return "Performs a round-robin cycle on a Queue<string> by calling "
+ "Dequeue to remove the front element in O(1) amortized time, "
+ "appending it to the log list, then re-inserting it at the back "
+ "with Enqueue in O(1) am... | static void Main(string[] args)
{
var q = new Queue<string>(new[] { "A", "B", "C" });
var log = RoundRobin(q, 5);
if (log.Count != 5) throw new Exception("wrong log count");
if (log[0] != "A" || log[3] != "A") throw new Exception("wrong order");
if (q.Count != 3) throw ne... | string d6 = DescribeRoundRobin();
string d6L = d6.ToLower();
if (!d6L.Contains("dequeue")) throw new Exception("must mention Dequeue");
if (!d6L.Contains("enqueue")) throw new Exception("must mention Enqueue");
if (!d6L.Contains("o(1)")) throw new Exception("must mention O(1) amortized");
if (!d6L.Contains("circular") ... | code2NL_NL2code |
7 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<char, List<string>> GroupByInitial(List<string> words)
{
return words
.GroupBy(w => char.ToUpperInvariant(w[0]))
.ToDictionary(g => g.Key, g => g.ToList());
}
| static string DescribeGroupByInitial()
{
return "Groups words by their first character using LINQ GroupBy with "
+ "char.ToUpperInvariant as the key selector, producing "
+ "IGrouping<char, string> sequences. ToDictionary then materializes "
+ "each group into a Di... | static void Main(string[] args)
{
var words = new List<string> { "apple", "Avocado", "banana", "Blueberry" };
var groups = GroupByInitial(words);
if (groups.Count != 2) throw new Exception("wrong group count");
if (groups['A'].Count != 2) throw new Exception("wrong A group");
... | string d7 = DescribeGroupByInitial();
string d7L = d7.ToLower();
if (!d7L.Contains("groupby")) throw new Exception("must mention GroupBy");
if (!d7L.Contains("char.toupperinvariant")) throw new Exception("must mention char.ToUpperInvariant");
if (!d7L.Contains("todictionary")) throw new Exception("must mention ToDictio... | code2NL_NL2code |
8 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<double> WeightedAvgPairs(List<double> values, List<double> weights)
{
return values.Zip(weights, (v, w) => v * w)
.Select((product, index) =>
product / weights.Ta... | static string DescribeWeightedAvgPairs()
{
return "Pairs elements from values and weights using LINQ Zip, which "
+ "stops at the shorter sequence and applies a result selector "
+ "that computes v * w. The intermediate products are then piped "
+ "through Select w... | static void Main(string[] args)
{
var v = new List<double> { 10.0, 20.0, 30.0 };
var w = new List<double> { 1.0, 2.0, 3.0 };
var result = WeightedAvgPairs(v, w);
if (result.Count != 3) throw new Exception("wrong count");
if (Math.Abs(result[0] - 10.0) > 0.001) throw new E... | string d8 = DescribeWeightedAvgPairs();
string d8L = d8.ToLower();
if (!d8L.Contains("zip")) throw new Exception("must mention Zip");
if (!d8L.Contains("shorter sequence") || !d8L.Contains("truncat")) throw new Exception("must mention truncation to shorter");
if (!d8L.Contains("select") && !d8L.Contains("index overload... | code2NL_NL2code |
9 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static int SumMiddleThird(ReadOnlySpan<int> span)
{
int len = span.Length;
int start = len / 3;
int end = 2 * len / 3;
ReadOnlySpan<int> slice = span.Slice(start, end - start);
int sum = 0;
foreach (... | static string DescribeSumMiddleThird()
{
return "Computes the sum of the middle third of a ReadOnlySpan<int> by "
+ "using integer division to find start and end indices, then calling "
+ "Slice to create a narrower view into the same contiguous memory "
+ "without... | static void Main(string[] args)
{
Span<int> data = stackalloc int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int result = SumMiddleThird(data);
if (result != 4 + 5 + 6) throw new Exception("wrong sum: " + result);
string desc = DescribeSumMiddleThird();
if (string.IsNullOrEmpty(des... | string d9 = DescribeSumMiddleThird();
string d9L = d9.ToLower();
if (!d9L.Contains("readonlyspan")) throw new Exception("must mention ReadOnlySpan");
if (!d9L.Contains("slice")) throw new Exception("must mention Slice");
if (!d9L.Contains("without") && !d9L.Contains("no")) throw new Exception("must mention no allocatio... | code2NL_NL2code |
10 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
class Program
{
static int AddOrIncrement(ConcurrentDictionary<string, int> dict, string key, int amount)
{
return dict.AddOrUpdate(key, amount, (k, oldVal) => oldVal + amount);
}
| static string DescribeAddOrIncrement()
{
return "Uses ConcurrentDictionary.AddOrUpdate which atomically adds the "
+ "key with the given amount if absent, or invokes the updateValueFactory "
+ "delegate to compute oldVal + amount if the key already exists. "
+ "The... | static void Main(string[] args)
{
var dict = new ConcurrentDictionary<string, int>();
if (AddOrIncrement(dict, "x", 5) != 5) throw new Exception("add failed");
if (AddOrIncrement(dict, "x", 3) != 8) throw new Exception("update failed");
if (dict["x"] != 8) throw new Exception("wr... | string d10 = DescribeAddOrIncrement();
string d10L = d10.ToLower();
if (!d10L.Contains("addorupdate")) throw new Exception("must mention AddOrUpdate");
if (!d10L.Contains("atomically")) throw new Exception("must mention atomic operation");
if (!d10L.Contains("updatevaluefactory")) throw new Exception("must mention upda... | code2NL_NL2code |
11 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<string> ZipLabelsWithScores(List<string> labels, List<int> scores)
{
return labels.Zip(scores, (l, s) => $"{l}:{s}").ToList();
}
| static string describe_ZipLabelsWithScores()
{
return "Pairs each label with the corresponding score using Enumerable.Zip, "
+ "combining them into a formatted string with a colon separator. "
+ "If the two sequences have different lengths, Zip truncates to the "
+ "shorter sequence witho... |
static void Main()
{
var result = ZipLabelsWithScores(
new List<string> { "math", "sci" },
new List<int> { 95, 88 });
if (result.Count != 2) throw new Exception("count");
if (result[0] != "math:95") throw new Exception("first");
var truncated = ZipLabels... | string d = Program.describe_ZipLabelsWithScores().ToLower();
if (!d.Contains("zip")) throw new Exception("missing zip");
if (!d.Contains("truncat")) throw new Exception("missing truncate");
if (!d.Contains("shorter")) throw new Exception("missing shorter");
if (!d.Contains("colon") && !d.Contains("separator") && !d.Con... | code2NL_NL2code |
12 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static List<string> DrainTopN(PriorityQueue<string, int> pq, int n)
{
var result = new List<string>();
while (result.Count < n && pq.TryDequeue(out string item, out int _))
{
result.Add(item);
}
... | static string describe_DrainTopN()
{
return "Removes up to n elements from a PriorityQueue using TryDequeue, "
+ "which extracts the element with the lowest priority value (min-heap). "
+ "Each call to TryDequeue returns false when the queue is empty, so "
+ "the loop terminates early if ... |
static void Main()
{
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 1);
pq.Enqueue("high", 10);
pq.Enqueue("med", 5);
var top2 = DrainTopN(pq, 2);
if (top2.Count != 2) throw new Exception("count");
if (top2[0] != "low") throw new Exception("... | string d = Program.describe_DrainTopN().ToLower();
if (!d.Contains("priorityqueue") && !d.Contains("priority queue")) throw new Exception("missing priorityqueue");
if (!d.Contains("trydequeue")) throw new Exception("missing trydequeue");
if (!d.Contains("min") || !d.Contains("heap") && !d.Contains("lowest")) throw new ... | code2NL_NL2code |
13 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static string ComputeSha256Hex(string input)
{
using (SHA256 sha = SHA256.Create())
{
byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(hash).Rep... | static string describe_ComputeSha256Hex()
{
return "Computes a SHA-256 hash of the UTF-8 encoded input string using "
+ "the SHA256.Create factory method inside a using block that ensures "
+ "the algorithm instance is disposed after use. The resulting 32-byte "
+ "hash is converted to a ... |
static void Main()
{
string h = ComputeSha256Hex("hello");
if (h.Length != 64) throw new Exception("length");
if (h != h.ToLowerInvariant()) throw new Exception("case");
string doc = describe_ComputeSha256Hex();
if (string.IsNullOrEmpty(doc)) throw new Exception("empty ... | string d = Program.describe_ComputeSha256Hex().ToLower();
if (!d.Contains("sha-256") && !d.Contains("sha256")) throw new Exception("missing sha256");
if (!d.Contains("utf-8") && !d.Contains("utf8")) throw new Exception("missing utf-8");
if (!d.Contains("disposed") && !d.Contains("using")) throw new Exception("missing d... | code2NL_NL2code |
14 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Globalization;
class Program
{
static int CultureAwareIndexOf(string source, string value, string cultureName)
{
CultureInfo ci = new CultureInfo(cultureName);
return ci.CompareInfo.IndexOf(source, value, CompareOptions.IgnoreCase);
}
| static string describe_CultureAwareIndexOf()
{
return "Finds the first occurrence of a substring within a source string "
+ "using culture-sensitive comparison rules from CompareInfo.IndexOf. "
+ "The comparison is case-insensitive via CompareOptions.IgnoreCase. "
+ "A new CultureInfo is ... |
static void Main()
{
int idx = CultureAwareIndexOf("Hello World", "hello", "en-US");
if (idx != 0) throw new Exception("case insensitive");
int missing = CultureAwareIndexOf("abc", "xyz", "en-US");
if (missing != -1) throw new Exception("not found");
string doc = descri... | string d = Program.describe_CultureAwareIndexOf().ToLower();
if (!d.Contains("cultureinfo") && !d.Contains("culture")) throw new Exception("missing cultureinfo/culture");
if (!d.Contains("compareinfo")) throw new Exception("missing compareinfo");
if (!d.Contains("case-insensitive") && !d.Contains("ignorecase") && !d.Co... | code2NL_NL2code |
15 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Numerics;
class Program
{
static BigInteger Factorial(int n)
{
BigInteger result = BigInteger.One;
for (int i = 2; i <= n; i++)
result = BigInteger.Multiply(result, new BigInteger(i));
return result;
}
| static string describe_Factorial()
{
return "Computes the factorial of n using System.Numerics.BigInteger for "
+ "arbitrary-precision integer arithmetic, avoiding overflow that would "
+ "occur with int or long for large n. Starts from BigInteger.One and "
+ "iteratively multiplies via B... |
static void Main()
{
if (Factorial(0) != BigInteger.One) throw new Exception("0!");
if (Factorial(5) != new BigInteger(120)) throw new Exception("5!");
if (Factorial(20) != BigInteger.Parse("2432902008176640000")) throw new Exception("20!");
string doc = describe_Factorial();
... | string d = Program.describe_Factorial().ToLower();
if (!d.Contains("biginteger")) throw new Exception("missing biginteger");
if (!d.Contains("arbitrary") || !d.Contains("precision")) throw new Exception("missing arbitrary-precision");
if (!d.Contains("overflow")) throw new Exception("missing overflow");
if (!d.Contains... | code2NL_NL2code |
16 | devbench-code2NL-NL2code | c_sharp | using System;
using System.IO;
using System.IO.Compression;
using System.Text;
class Program
{
static byte[] CompressString(string text)
{
byte[] raw = Encoding.UTF8.GetBytes(text);
using (var ms = new MemoryStream())
{
using (var gz = new GZipStream(ms, CompressionMode.Comp... | static string describe_CompressString()
{
return "Compresses a UTF-8 encoded string into a gzip byte array using "
+ "GZipStream wrapping a MemoryStream. The leaveOpen parameter is set "
+ "to true so that disposing the GZipStream flushes the compressed data "
+ "without closing the under... |
static void Main()
{
byte[] compressed = CompressString("hello world");
if (compressed.Length == 0) throw new Exception("empty");
if (compressed.Length >= Encoding.UTF8.GetBytes("hello world").Length + 100)
throw new Exception("too large");
string doc = describe_Com... | string d = Program.describe_CompressString().ToLower();
if (!d.Contains("gzipstream") && !d.Contains("gzip")) throw new Exception("missing gzipstream");
if (!d.Contains("memorystream")) throw new Exception("missing memorystream");
if (!d.Contains("leaveopen") && !d.Contains("leave open")) throw new Exception("missing l... | code2NL_NL2code |
17 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<int[]> BatchItems(IEnumerable<int> items, int batchSize)
{
return items.Chunk(batchSize).ToList();
}
| static string describe_BatchItems()
{
return "Splits the input sequence into fixed-size batches using Enumerable.Chunk. "
+ "Each batch is an array of up to batchSize elements. The final chunk "
+ "may contain fewer elements if the total count is not evenly divisible "
+ "by batchSize. Ch... |
static void Main()
{
var batches = BatchItems(new[] { 1, 2, 3, 4, 5 }, 2);
if (batches.Count != 3) throw new Exception("batch count");
if (batches[2].Length != 1) throw new Exception("last batch size");
string doc = describe_BatchItems();
if (string.IsNullOrEmpty(doc)) ... | string d = Program.describe_BatchItems().ToLower();
if (!d.Contains("chunk")) throw new Exception("missing chunk");
if (!d.Contains("array")) throw new Exception("missing array");
if (!d.Contains("fewer") && !d.Contains("remaining") && !d.Contains("less")) throw new Exception("missing fewer/remaining for last chunk");
... | code2NL_NL2code |
18 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static void RotateLeft(LinkedList<int> list, int positions)
{
for (int i = 0; i < positions && list.Count > 1; i++)
{
int first = list.First.Value;
list.RemoveFirst();
list.AddLast(first);
... | static string describe_RotateLeft()
{
return "Rotates a LinkedList to the left by the given number of positions. "
+ "Each rotation removes the First node using RemoveFirst (an O(1) operation) "
+ "and appends its value to the end using AddLast (also O(1)). "
+ "The loop exits early if th... |
static void Main()
{
var list = new LinkedList<int>(new[] { 1, 2, 3, 4, 5 });
RotateLeft(list, 2);
if (list.First.Value != 3) throw new Exception("first");
if (list.Last.Value != 2) throw new Exception("last");
string doc = describe_RotateLeft();
if (string.IsNu... | string d = Program.describe_RotateLeft().ToLower();
if (!d.Contains("linkedlist") && !d.Contains("linked list")) throw new Exception("missing linkedlist");
if (!d.Contains("removefirst") && !d.Contains("remove first")) throw new Exception("missing removefirst");
if (!d.Contains("addlast") && !d.Contains("add last")) th... | code2NL_NL2code |
19 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<char> FlattenToChars(List<string> words)
{
return words.SelectMany(w => w.ToCharArray()).ToList();
}
| static string describe_FlattenToChars()
{
return "Flattens a list of strings into a single list of characters using "
+ "Enumerable.SelectMany, which projects each string into a char array "
+ "via ToCharArray and then concatenates all resulting sequences into one "
+ "flat sequence. Sele... |
static void Main()
{
var result = FlattenToChars(new List<string> { "ab", "cd" });
if (result.Count != 4) throw new Exception("count");
if (result[0] != 'a' || result[3] != 'd') throw new Exception("order");
var empty = FlattenToChars(new List<string>());
if (empty.Coun... | string d = Program.describe_FlattenToChars().ToLower();
if (!d.Contains("selectmany")) throw new Exception("missing selectmany");
if (!d.Contains("flatten") && !d.Contains("concatenat")) throw new Exception("missing flatten/concatenate");
if (!d.Contains("tochararray") && !d.Contains("char array")) throw new Exception(... | code2NL_NL2code |
20 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static Dictionary<char, List<string>> GroupByFirstChar(IEnumerable<string> words)
{
return words.GroupBy(w => w[0])
.ToDictionary(g => g.Key, g => g.ToList());
}
| static string describe_GroupByFirstChar()
{
return "Groups strings by their first character using Enumerable.GroupBy and "
+ "materializes the result into a Dictionary via ToDictionary. Each key "
+ "is the first char of the group, and each value is a List of all strings "
+ "sharing that... |
static void Main()
{
var result = GroupByFirstChar(new[] { "apple", "avocado", "banana", "blueberry" });
if (result.Count != 2) throw new Exception("group count");
if (result['a'].Count != 2) throw new Exception("a count");
if (result['b'][0] != "banana") throw new Exception("or... | string d = Program.describe_GroupByFirstChar().ToLower();
if (!d.Contains("groupby") && !d.Contains("group by")) throw new Exception("missing groupby");
if (!d.Contains("todictionary") && !d.Contains("to dictionary")) throw new Exception("missing todictionary");
if (!d.Contains("first char") && !d.Contains("first chara... | code2NL_NL2code |
21 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Text.RegularExpressions;
class Task21
{
static (bool found, string area, string number) ParsePhone(string input)
{
var m = Regex.Match(input, @"\((\d{3})\)\s*(\d{4,})");
if (!m.Success) return (false, "", "");
return (true, m.Groups[1].Value, m.Groups[2].Value... | static string DescribeParsePhone()
{
return "Uses Regex.Match with a pattern containing two capturing groups "
+ "to extract the area code and number from a parenthesized phone "
+ "format. Returns a ValueTuple with a bool Success field indicating "
+ "whether the patt... |
static void Main()
{
var r = ParsePhone("(415) 5551234");
if (!r.found) throw new Exception("should match");
if (r.area != "415") throw new Exception("area");
if (r.number != "5551234") throw new Exception("number");
var miss = ParsePhone("none");
if (miss.found)... | string d21 = Task21.DescribeParsePhone().ToLower();
if (!d21.Contains("regex.match")) throw new Exception("must name Regex.Match");
if (!d21.Contains("capturing group") && !d21.Contains("capture group")) throw new Exception("must mention capturing groups");
if (!d21.Contains("valuetuple") && !d21.Contains("value tuple"... | code2NL_NL2code |
22 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Concurrent;
class Task22
{
static (bool ok, int value) SafeDequeue(ConcurrentQueue<int> q)
{
if (q.TryDequeue(out int item))
return (true, item);
return (false, -1);
}
| static string DescribeSafeDequeue()
{
return "Attempts a lock-free dequeue from a ConcurrentQueue<int> using "
+ "TryDequeue with an out parameter. TryDequeue is an atomic "
+ "operation that returns true and sets the out variable on success. "
+ "On an empty queue it ... |
static void Main()
{
var q = new ConcurrentQueue<int>();
q.Enqueue(10);
q.Enqueue(20);
var r1 = SafeDequeue(q);
if (!r1.ok || r1.value != 10) throw new Exception("first dequeue");
var r2 = SafeDequeue(q);
if (!r2.ok || r2.value != 20) throw new Exception(... | string d22 = Task22.DescribeSafeDequeue().ToLower();
if (!d22.Contains("concurrentqueue")) throw new Exception("must name ConcurrentQueue");
if (!d22.Contains("trydequeue")) throw new Exception("must name TryDequeue");
if (!d22.Contains("lock-free") && !d22.Contains("lockfree") && !d22.Contains("lock free")) throw new ... | code2NL_NL2code |
23 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Diagnostics;
class Task23
{
static (long ticks, double ms) MeasureAction(Action action)
{
var sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return (sw.ElapsedTicks, sw.Elapsed.TotalMilliseconds);
}
| static string DescribeMeasureAction()
{
return "Measures execution time of an Action delegate using "
+ "System.Diagnostics.Stopwatch. Returns both ElapsedTicks, which "
+ "are in units of Stopwatch.Frequency (not TimeSpan ticks), and "
+ "Elapsed.TotalMilliseconds as ... |
static void Main()
{
var (ticks, ms) = MeasureAction(() => { int s = 0; for (int i = 0; i < 1000; i++) s += i; });
if (ticks <= 0) throw new Exception("ticks should be positive");
if (ms < 0) throw new Exception("ms should be non-negative");
string desc = DescribeMeasureAction()... | string d23 = Task23.DescribeMeasureAction().ToLower();
if (!d23.Contains("stopwatch")) throw new Exception("must name Stopwatch");
if (!d23.Contains("elapsedticks") && !d23.Contains("elapsed ticks")) throw new Exception("must name ElapsedTicks");
if (!d23.Contains("frequency") || !d23.Contains("stopwatch.frequency") &&... | code2NL_NL2code |
24 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Task24
{
static IEnumerable<int> FilterPositive(IEnumerable<int> source)
{
foreach (var item in source)
{
if (item > 0)
yield return item;
}
}
| static string DescribeFilterPositive()
{
return "Returns an IEnumerable<int> that lazily filters positive "
+ "values from the source using yield return for deferred "
+ "execution. The compiler generates a state machine that "
+ "produces elements one at a time on eac... |
static void Main()
{
var src = new[] { -3, 5, 0, 8, -1, 2 };
var result = new List<int>(FilterPositive(src));
if (result.Count != 3) throw new Exception("count");
if (result[0] != 5 || result[1] != 8 || result[2] != 2) throw new Exception("values");
string desc = Describ... | string d24 = Task24.DescribeFilterPositive().ToLower();
if (!d24.Contains("yield return") && !d24.Contains("yield")) throw new Exception("must mention yield return");
if (!d24.Contains("deferred") && !d24.Contains("lazy") && !d24.Contains("lazily")) throw new Exception("must mention deferred/lazy execution");
if (!d24.... | code2NL_NL2code |
25 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class TagAttribute : Attribute
{
public string Name { get; }
public TagAttribute(string name) { Name = name; }
}
class Task25
{
[Tag("alpha")]
[Tag("beta")]
static void AnnotatedMethod() { }
... | static string DescribeGetTags()
{
return "Uses System.Reflection to retrieve custom attributes from a "
+ "method at runtime. Looks up the MethodInfo via typeof and "
+ "GetMethod with BindingFlags.Static | BindingFlags.NonPublic "
+ "to locate non-public static method... |
static void Main()
{
var tags = GetTags("AnnotatedMethod");
if (tags.Length != 2) throw new Exception("expected 2 tags");
var missing = GetTags("NoSuchMethod");
if (missing.Length != 0) throw new Exception("expected empty");
string desc = DescribeGetTags();
if (s... | string d25 = Task25.DescribeGetTags().ToLower();
if (!d25.Contains("methodinfo") && !d25.Contains("method info")) throw new Exception("must name MethodInfo");
if (!d25.Contains("bindingflags") && !d25.Contains("binding flags")) throw new Exception("must mention BindingFlags");
if (!d25.Contains("getcustomattributes") &... | code2NL_NL2code |
26 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class ResourceTracker : IDisposable
{
static readonly List<string> _log = new List<string>();
public string Name { get; }
private bool _disposed;
public ResourceTracker(string name)
{
Name = name;
_log.Add($"open:{name}");
}
... | public static string DescribeResourceTracker()
{
return "Implements IDisposable with a boolean _disposed guard to "
+ "ensure Dispose is idempotent — calling Dispose multiple times "
+ "only logs one close event. The using statement calls Dispose "
+ "automatically at ... |
}
class Task26
{
static void Main()
{
using (var r = new ResourceTracker("A")) { }
var log = ResourceTracker.GetLog();
if (log.Length != 2) throw new Exception("expected open+close");
if (log[0] != "open:A" || log[1] != "close:A") throw new Exception("wrong log");
strin... | string d26 = ResourceTracker.DescribeResourceTracker().ToLower();
if (!d26.Contains("idisposable") && !d26.Contains("i disposable")) throw new Exception("must name IDisposable");
if (!d26.Contains("idempotent") && !d26.Contains("multiple times") && !d26.Contains("once")) throw new Exception("must mention idempotent dis... | code2NL_NL2code |
27 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Priority : IComparable<Priority>
{
public int Level { get; }
public string Label { get; }
public Priority(int level, string label)
{
Level = level;
Label = label;
}
public int CompareTo(Priority other)
{
if (oth... | public static string DescribePriorityCompare()
{
return "Implements IComparable<Priority> with CompareTo returning a "
+ "negative integer, zero, or positive integer. Primary sort key "
+ "is Level (ascending via int.CompareTo). Tie-breaker is Label "
+ "using string.C... |
}
class Task27
{
static void Main()
{
var a = new Priority(1, "low");
var b = new Priority(2, "high");
var c = new Priority(1, "mid");
if (a.CompareTo(b) >= 0) throw new Exception("a < b");
if (a.CompareTo(c) >= 0) throw new Exception("a < c by label");
if (a.Co... | string d27 = Priority.DescribePriorityCompare().ToLower();
if (!d27.Contains("icomparable")) throw new Exception("must name IComparable<T>");
if (!d27.Contains("negative") && !d27.Contains("positive") || !d27.Contains("zero")) throw new Exception("must describe return semantics: negative/zero/positive");
if (!d27.Conta... | code2NL_NL2code |
28 | devbench-code2NL-NL2code | c_sharp | using System;
class Task28
{
static (int quotient, int remainder) DivMod(int a, int b)
{
return (a / b, a % b);
}
static (int q, int r, bool exact) DivModExact(int a, int b)
{
var (q, r) = DivMod(a, b);
return (q, r, r == 0);
}
| static string DescribeDivModExact()
{
return "Returns a named ValueTuple<int, int, bool> with fields q, r, "
+ "and exact. Uses tuple deconstruction syntax 'var (q, r) = ...' "
+ "to destructure the two-element tuple from DivMod into local "
+ "variables. C# truncates ... |
static void Main()
{
var (q, r, ex) = DivModExact(10, 3);
if (q != 3 || r != 1 || ex) throw new Exception("10/3");
var (q2, r2, ex2) = DivModExact(9, 3);
if (q2 != 3 || r2 != 0 || !ex2) throw new Exception("9/3");
string desc = DescribeDivModExact();
if (string.I... | string d28 = Task28.DescribeDivModExact().ToLower();
if (!d28.Contains("valuetuple") && !d28.Contains("value tuple")) throw new Exception("must name ValueTuple");
if (!d28.Contains("deconstruct") && !d28.Contains("destructure")) throw new Exception("must mention deconstruction/destructuring");
if (!d28.Contains("toward... | code2NL_NL2code |
29 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Globalization;
class Task29
{
static string FormatInvariant(FormattableString fs)
{
return fs.ToString(CultureInfo.InvariantCulture);
}
static (string invariant, string local, int argCount) FormatBoth(double value)
{
FormattableString fs = $"Value is {val... | static string DescribeFormatBoth()
{
return "Demonstrates that C# interpolated strings can be implicitly "
+ "converted to FormattableString, which preserves the format "
+ "holes and arguments separately rather than eagerly formatting "
+ "to a string. FormattableStri... |
static void Main()
{
var (inv, loc, argc) = FormatBoth(1234.5);
if (inv != "Value is 1234.50") throw new Exception($"inv={inv}");
if (argc != 1) throw new Exception($"argc={argc}");
string desc = DescribeFormatBoth();
if (string.IsNullOrEmpty(desc)) throw new Exception("... | string d29 = Task29.DescribeFormatBoth().ToLower();
if (!d29.Contains("formattablestring") && !d29.Contains("formattable string")) throw new Exception("must name FormattableString");
if (!d29.Contains("invariantculture") && !d29.Contains("invariant culture")) throw new Exception("must mention InvariantCulture");
if (!d... | code2NL_NL2code |
30 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Coord : IEquatable<Coord>
{
public int X { get; }
public int Y { get; }
public Coord(int x, int y) { X = x; Y = y; }
public bool Equals(Coord other)
{
if (other is null) return false;
return X == other.X && Y == other.Y;
}
... | public static string DescribeCoordEquality()
{
return "Implements IEquatable<Coord> for type-safe equality without "
+ "boxing. Overrides both Equals(object) and GetHashCode to "
+ "satisfy the contract: equal objects must have equal hash codes. "
+ "GetHashCode uses H... |
}
class Task30
{
static void Main()
{
var a = new Coord(3, 4);
var b = new Coord(3, 4);
var c = new Coord(5, 6);
if (!a.Equals(b)) throw new Exception("a==b");
if (a.Equals(c)) throw new Exception("a!=c");
if (a.GetHashCode() != b.GetHashCode()) throw new Except... | string d30 = Coord.DescribeCoordEquality().ToLower();
if (!d30.Contains("iequatable")) throw new Exception("must name IEquatable<T>");
if (!d30.Contains("boxing") && !d30.Contains("box")) throw new Exception("must mention boxing avoidance");
if (!d30.Contains("hashcode.combine") && !d30.Contains("hashcode combine")) th... | code2NL_NL2code |
31 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Buffers;
namespace Bench
{
public class PoolDemo
{
public static int SumWithPool(int[] source)
{
int[] rented = ArrayPool<int>.Shared.Rent(source.Length);
try
{
Array.Copy(source, rented, source.Length);
... | return "Rents a buffer from the shared ArrayPool, copies source elements into it, "
+ "computes their sum, and returns the rented buffer with clearArray set to true. "
+ "Uses try/finally to guarantee the buffer is returned to the shared pool even if an exception occurs.";
| }
public static void Main(string[] args)
{
if (SumWithPool(new int[] { 1, 2, 3, 4 }) != 10)
throw new Exception("sum failed");
if (SumWithPool(new int[] {}) != 0)
throw new Exception("empty failed");
string desc = describe_arra... | string d31 = PoolDemo.describe_array_pool_usage().ToLower();
if (!d31.Contains("rent")) throw new Exception("must mention rent");
if (!d31.Contains("shared")) throw new Exception("must mention shared pool");
if (!d31.Contains("return")) throw new Exception("must mention r... | code2NL_NL2code |
32 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Bench
{
public class SpanSearch
{
public static int FindLastBefore(ReadOnlySpan<int> data, int threshold)
{
ReadOnlySpan<int> window = data.Slice(0, Math.Min(data.Length, 64));
int result = -1;
for (int i = window.Length - 1; i >= 0; i... | return "Searches backward through a ReadOnlySpan<int> window sliced to at most 64 elements "
+ "from the start of the input. Returns the last element below the threshold, or -1 if none found. "
+ "The Slice call limits the search to the first 64 elements without allocating ... | }
public static void Main(string[] args)
{
int[] arr = { 10, 20, 5, 30, 2 };
if (FindLastBefore(arr, 25) != 2)
throw new Exception("basic search failed");
if (FindLastBefore(arr, 1) != -1)
throw new Exception("none below thresh... | string d32 = SpanSearch.describe_span_search().ToLower();
if (!d32.Contains("readonlyspan") && !d32.Contains("span")) throw new Exception("must mention ReadOnlySpan or span");
if (!d32.Contains("slice")) throw new Exception("must mention Slice operation");
if (!d32.Contai... | code2NL_NL2code |
33 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Bench
{
public class Stats
{
/// <summary>
/// Computes the minimum, maximum, and arithmetic mean of an integer array.
/// Returns a named ValueTuple (Min, Max, Mean).
/// If the array is empty, returns (int.MaxValue, int.MinValue, 0.0).
/// The m... | if (values.Length == 0)
return (int.MaxValue, int.MinValue, 0.0);
int min = int.MaxValue, max = int.MinValue;
long sum = 0;
foreach (int v in values) { if (v < min) min = v; if (v > max) max = v; sum += v; }
return (min, max, (double)sum / valu... | }
public static void Main(string[] args)
{
var (mn, mx, avg) = Summarize(new[] { 3, 1, 4, 1, 5 });
if (mn != 1) throw new Exception("min wrong");
if (mx != 5) throw new Exception("max wrong");
if (Math.Abs(avg - 2.8) > 0.001) throw new Exception("... | var (emn, emx, eavg) = Stats.Summarize(new int[0]);
if (emn != int.MaxValue) throw new Exception("empty min must be MaxValue");
if (emx != int.MinValue) throw new Exception("empty max must be MinValue");
if (eavg != 0.0) throw new Exception("empty mean must be 0.0");
... | code2NL_NL2code |
34 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Specialized;
namespace Bench
{
public class PackedFlags
{
private static readonly BitVector32.Section DaySection = BitVector32.CreateSection(31);
private static readonly BitVector32.Section MonthSection = BitVector32.CreateSection(12, DaySection);
... | return "Uses BitVector32 with three adjacent sections created via CreateSection to pack "
+ "a date into a single 32-bit integer. DaySection holds 0-31 (5 bits), MonthSection holds 0-12 "
+ "(4 bits after day), and YearOffsetSection holds 0-127 (7 bits after month) represen... | }
public static void Main(string[] args)
{
int p = Pack(15, 6, 2024);
var (d, m, y) = Unpack(p);
if (d != 15 || m != 6 || y != 2024)
throw new Exception("round-trip failed");
string desc = describe_bitvector_packing();
... | string d34 = PackedFlags.describe_bitvector_packing().ToLower();
if (!d34.Contains("bitvector32")) throw new Exception("must mention BitVector32");
if (!d34.Contains("section") && !d34.Contains("createsection")) throw new Exception("must mention sections");
if (!d34.Conta... | code2NL_NL2code |
35 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
namespace Bench
{
public class RankedRegistry
{
private readonly OrderedDictionary _entries = new OrderedDictionary();
public void Register(string key, int score)
{
if (_entries... | return "Uses OrderedDictionary to maintain insertion order while allowing key and index-based access. "
+ "Register upserts: updates existing keys in-place without changing order, or appends new ones. "
+ "GetKeyAtRank sorts entries by descending score using Cast<Dictionary... | }
public static void Main(string[] args)
{
var reg = new RankedRegistry();
reg.Register("alice", 90);
reg.Register("bob", 95);
reg.Register("carol", 85);
if (reg.GetKeyAtRank(0) != "bob")
throw new Exception("rank 0 sho... | string d35 = RankedRegistry.describe_ordered_dict_behavior().ToLower();
if (!d35.Contains("ordereddictionary")) throw new Exception("must mention OrderedDictionary");
if (!d35.Contains("insertion order") && !d35.Contains("insertion position")) throw new Exception("must mention insert... | code2NL_NL2code |
36 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Bench
{
/// <summary>
/// An immutable record representing a 2D point with named coordinates X and Y (both double).
/// Provides a custom Deconstruct that outputs the polar coordinates (Radius, AngleInDegrees)
/// where Radius = sqrt(X*X + Y*Y) and AngleInDegrees = atan2(Y, X) c... | public void Deconstruct(out double Radius, out double AngleInDegrees)
{
Radius = Math.Sqrt(X * X + Y * Y);
AngleInDegrees = (X == 0 && Y == 0) ? 0.0 : Math.Atan2(Y, X) * (180.0 / Math.PI);
}
| }
public class Program
{
public static void Main(string[] args)
{
var p = new Point2D(3, 4);
p.Deconstruct(out double r, out double a);
if (Math.Abs(r - 5.0) > 0.001) throw new Exception("radius wrong");
if (Math.Abs(a - 53.13010) > 0.01) thro... | var pn = new Point2D(-1, 0);
pn.Deconstruct(out double rn, out double an);
if (Math.Abs(rn - 1.0) > 0.001) throw new Exception("neg x radius wrong");
if (Math.Abs(an - 180.0) > 0.01) throw new Exception("neg x angle should be 180");
var py = new Point2D(0, 1);... | code2NL_NL2code |
37 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
namespace Bench
{
public abstract record Shape;
public record Circle(double Radius) : Shape;
public record Rect(double W, double H) : Shape;
public record Triangle(double A, double B, double C) : Shape;
public class Classifier
{
public st... | return "Uses a switch expression with record type patterns and property patterns to classify shapes. "
+ "Circles with non-positive radius are invalid; radius over 100 yields large-circle. "
+ "Rects where W equals H within 0.001 tolerance are classified as square; otherwis... | }
public static void Main(string[] args)
{
if (Classify(new Circle(5)) != "circle") throw new Exception();
if (Classify(new Circle(-1)) != "invalid") throw new Exception();
if (Classify(new Circle(200)) != "large-circle") throw new Exception();
if... | string d37 = Classifier.describe_classifier().ToLower();
if (!d37.Contains("switch expression")) throw new Exception("must mention switch expression");
if (!d37.Contains("type pattern") || !d37.Contains("property pattern")) throw new Exception("must mention type and property patterns... | code2NL_NL2code |
38 | devbench-code2NL-NL2code | c_sharp | using System;
using System.ComponentModel;
using System.Globalization;
namespace Bench
{
/// <summary>
/// A TypeConverter that converts strings of the form "R:G:B" (colon-separated)
/// into a (byte R, byte G, byte B) ValueTuple. Each component is parsed as a byte
/// in the invariant culture. If the ... | public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string s) {
var p = s.Split(':');... | }
public class Program
{
public static void Main(string[] args)
{
var conv = new ColorTupleConverter();
if (!conv.CanConvertFrom(typeof(string))) throw new Exception("should support string");
var c = ((byte, byte, byte))conv.ConvertFrom(null, CultureInfo.... | var conv38 = new ColorTupleConverter();
if (conv38.CanConvertFrom(typeof(int))) throw new Exception("should not support int");
var black = ((byte, byte, byte))conv38.ConvertFrom(null, CultureInfo.InvariantCulture, "0:0:0");
if (black.Item1 != 0 || black.Item2 != 0 || blac... | code2NL_NL2code |
39 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
namespace Bench
{
public record Config(string Host, int Port, bool UseTls, int TimeoutMs);
public class ConfigBuilder
{
public static Config ApplyOverrides(Config baseConfig, Dictionary<string, string> overrides)
{
var result = ba... | return "Iterates over a dictionary of overrides and applies each to a Config record using "
+ "non-destructive with-expressions inside a switch expression. Each recognized key "
+ "(host, port, tls, timeout) creates a shallow copy with that single property changed. "
... | }
public static void Main(string[] args)
{
var c = new Config("localhost", 80, false, 5000);
var o = new Dictionary<string, string> { { "port", "443" }, { "tls", "true" } };
var c2 = ConfigBuilder.ApplyOverrides(c, o);
if (c2.Port != 443 || !c2.Us... | string d39 = ConfigBuilder.describe_with_expression().ToLower();
if (!d39.Contains("with")) throw new Exception("must mention with-expression");
if (!d39.Contains("non-destructive") && !d39.Contains("immutable") && !d39.Contains("shallow copy")) throw new Exception("must mention non-... | code2NL_NL2code |
40 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Bench
{
public class Temperature
{
public double Celsius { get; }
public Temperature(double celsius) { Celsius = celsius; }
/// <summary>
/// Custom Deconstruct that outputs two values:
/// 1) celsius: the raw Celsius value
/// 2) lab... | celsius = Celsius;
label = Celsius switch
{
< 0 => "freezing",
< 15 => "cold",
< 30 => "warm",
_ => "hot"
};
| }
public static void Main(string[] args)
{
var (c1, l1) = new Temperature(-5);
if (l1 != "freezing") throw new Exception("expected freezing");
var (c2, l2) = new Temperature(10);
if (l2 != "cold") throw new Exception("expected cold");
... | var (bc, bl) = new Temperature(0);
if (bl != "cold") throw new Exception("0 should be cold not freezing");
if (bc != 0.0) throw new Exception("celsius should be 0");
var (bc2, bl2) = new Temperature(15);
if (bl2 != "warm") throw new Exception("15 should be war... | code2NL_NL2code |
41 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Xml.Linq;
namespace Task41
{
public class Program
{
static XElement FindFirstByAttribute(XDocument doc, string attrName, string attrValue)
{
foreach (XElement el in doc.Descendants())
{
XAttribute attr = el.Attribute(attrName);
... | static string DescribeFindFirstByAttribute()
{
return "Searches every descendant XElement via XDocument.Descendants() "
+ "and checks each element's XAttribute by calling XElement.Attribute(attrName). "
+ "Returns the first XElement whose attribute value matches via... |
static void Main(string[] args)
{
XDocument doc = XDocument.Parse("<root><item id='1'/><item id='2'/></root>");
XElement found = FindFirstByAttribute(doc, "id", "2");
if (!(found != null && found.Name.LocalName == "item")) throw new Exception("Should find item");
... |
{
string d = DescribeFindFirstByAttribute();
if (!d.Contains("XDocument.Descendants()")) throw new Exception("must name XDocument.Descendants()");
if (!d.Contains("XElement.Attribute")) throw new Exception("must name XElement.Attribute");
if (... | code2NL_NL2code |
42 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Data;
namespace Task42
{
public class Program
{
static DataTable PivotByColumn(DataTable source, string pivotCol, string valueCol)
{
DataTable result = new DataTable();
result.Columns.Add("RowIndex", typeof(int));
foreach (DataRow r... | static string DescribePivotByColumn()
{
return "Creates a new DataTable and dynamically adds DataColumn objects "
+ "by inspecting distinct values in the pivot column via DataRow indexer. "
+ "Uses DataTable.Columns.Contains to avoid duplicate column creation and "
... |
static void Main(string[] args)
{
DataTable src = new DataTable();
src.Columns.Add("Category", typeof(string));
src.Columns.Add("Amount", typeof(int));
src.Rows.Add("A", 10);
src.Rows.Add("B", 20);
src.Rows.Add("A", 30);
... |
{
string d = DescribePivotByColumn();
if (!d.Contains("DataTable") || !d.Contains("DataColumn")) throw new Exception("must name DataTable and DataColumn");
if (!d.Contains("DataTable.Columns.Contains")) throw new Exception("must name Contains check");
... | code2NL_NL2code |
43 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Task43
{
public class Program
{
static string[] ExtractNonEmptyTokens(string input, char[] delimiters)
{
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string[] trimmed = Array.ConvertAll(parts, s => s.Trim());
... | static string DescribeExtractNonEmptyTokens()
{
return "Splits the input string using String.Split with a char[] separator "
+ "array and StringSplitOptions.RemoveEmptyEntries, which discards tokens "
+ "that are empty strings but does not trim whitespace. Then appl... |
static void Main(string[] args)
{
string[] tokens = ExtractNonEmptyTokens("hello,,world;; test ", new char[] { ',', ';' });
if (!(tokens.Length == 3)) throw new Exception("Expected 3 tokens, got " + tokens.Length);
if (!(tokens[0] == "hello")) throw new Exception("Fi... |
{
string d = DescribeExtractNonEmptyTokens();
if (!d.Contains("String.Split")) throw new Exception("must name String.Split");
if (!d.Contains("StringSplitOptions.RemoveEmptyEntries")) throw new Exception("must name RemoveEmptyEntries");
if (!d... | code2NL_NL2code |
44 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Task44
{
public class Address
{
public string City { get; set; }
}
public class Customer
{
public Address HomeAddress { get; set; }
}
public class Program
{
// Returns the customer's city, or "Unknown" if customer is null,
// Hom... | string city = customer?.HomeAddress?.City;
return string.IsNullOrEmpty(city) ? "Unknown" : city;
| }
static void Main(string[] args)
{
if (!(GetCityOrDefault(null) == "Unknown")) throw new Exception("null customer");
if (!(GetCityOrDefault(new Customer()) == "Unknown")) throw new Exception("null address");
if (!(GetCityOrDefault(new Customer { HomeAddress ... |
if (!(GetCityOrDefault(new Customer { HomeAddress = new Address { City = "Tokyo" } }) == "Tokyo")) throw new Exception("Tokyo test");
if (!(GetCityOrDefault(new Customer { HomeAddress = null }) == "Unknown")) throw new Exception("explicit null address");
Customer c = new Customer();... | code2NL_NL2code |
45 | devbench-code2NL-NL2code | c_sharp | using System;
using System.IO;
namespace Task45
{
public class Program
{
static byte[] PackInts(int[] values)
{
using (MemoryStream ms = new MemoryStream())
using (BinaryWriter bw = new BinaryWriter(ms))
{
bw.Write(values.Length);
... | static string DescribePackUnpackInts()
{
return "PackInts writes a length-prefixed array of 32-bit integers into a "
+ "MemoryStream via BinaryWriter.Write(int), which stores each int as 4 "
+ "bytes in little-endian order. BinaryWriter.Flush ensures the buffer is "... |
static void Main(string[] args)
{
int[] original = { 1, 2, 3, 42, -7 };
byte[] packed = PackInts(original);
int[] unpacked = UnpackInts(packed);
if (!(unpacked.Length == original.Length)) throw new Exception("Length mismatch");
for (int i = 0;... |
{
string d = DescribePackUnpackInts();
if (!d.Contains("MemoryStream")) throw new Exception("must name MemoryStream");
if (!d.Contains("BinaryWriter.Write")) throw new Exception("must name BinaryWriter.Write");
if (!d.Contains("BinaryReader.Re... | code2NL_NL2code |
46 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Task46
{
public class Program
{
// Sort the array of strings by their length (ascending),
// breaking ties by case-insensitive alphabetical order.
// Must use Array.Sort with a Comparison<string> delegate.
// The sort must be in-place (no new array).
... | Array.Sort(items, (a, b) =>
{
int cmp = a.Length.CompareTo(b.Length);
if (cmp != 0) return cmp;
return string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
});
| }
static void Main(string[] args)
{
string[] data = { "Banana", "fig", "Apple", "cherry", "Date", "ab" };
SortByLengthThenAlpha(data);
if (!(data[0] == "ab")) throw new Exception("Expected ab first, got " + data[0]);
if (!(data[1] == "fig")) throw... |
string[] test2 = { "bb", "aa", "CC", "dd" };
SortByLengthThenAlpha(test2);
if (!(test2[0] == "aa")) throw new Exception("aa first");
if (!(test2[1] == "bb")) throw new Exception("bb second");
if (!(test2[2] == "CC")) throw new Exception("CC third");
... | code2NL_NL2code |
47 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
namespace Task47
{
public interface ITaggable
{
List<string> Tags { get; }
bool HasTag(string tag) => Tags.Contains(tag);
}
public class Document : ITaggable
{
public string Title { get; set; }
public List<string> Tags... | static string DescribeTaggableDesign()
{
return "ITaggable provides a default interface method HasTag that uses "
+ "List<string>.Contains for O(n) linear lookup without requiring "
+ "implementors to override it. Document implements ITaggable but does "
... |
static void Main(string[] args)
{
Document doc = new Document { Title = "Report" };
ITaggable taggable = doc;
taggable.AddTagIfMissing("urgent");
taggable.AddTagIfMissing("urgent");
if (!(doc.Tags.Count == 1)) throw new Exception("Should have ... |
{
string d = DescribeTaggableDesign();
if (!d.Contains("default interface method")) throw new Exception("must mention default interface method");
if (!d.Contains("List<string>.Contains") && !d.Contains("List<String>.Contains")) throw new Exception("must name ... | code2NL_NL2code |
48 | devbench-code2NL-NL2code | c_sharp | using System;
namespace Task48
{
public class Program
{
// Return a new array containing only elements from 'values' that are
// strictly between 'low' and 'high' (exclusive on both ends).
// Must use Array.FindAll with a Predicate<int>.
// Must also use Array.Sort on the result... | int[] filtered = Array.FindAll(values, v => v > low && v < high);
Array.Sort(filtered);
return filtered;
| }
static void Main(string[] args)
{
int[] data = { 5, 1, 8, 3, 10, 7, 2 };
int[] result = FilterAndSort(data, 2, 8);
if (!(result.Length == 3)) throw new Exception("Expected 3 elements, got " + result.Length);
if (!(result[0] == 3)) throw new Exce... |
int[] data2 = { 10, 20, 30, 40, 50 };
int[] r2 = FilterAndSort(data2, 15, 45);
if (!(r2.Length == 3)) throw new Exception("Expected 3");
if (!(r2[0] == 20)) throw new Exception("First 20");
if (!(r2[1] == 30)) throw new Exception("Second 30");
if ... | code2NL_NL2code |
49 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
namespace Task49
{
public class Program
{
static List<string> SearchEnvironmentPaths(string keyword)
{
string pathVar = Environment.GetEnvironmentVariable("PATH") ?? "";
char separator = System.IO.Path.PathSeparator;
... | static string DescribeSearchEnvironmentPaths()
{
return "Retrieves the PATH variable via Environment.GetEnvironmentVariable "
+ "and coalesces null to empty string with ??. Splits on the "
+ "platform-specific Path.PathSeparator character (semicolon on Windows, "
... |
static void Main(string[] args)
{
List<string> results = SearchEnvironmentPaths("usr");
// Results depend on environment, just verify it runs
if (!(results != null)) throw new Exception("Should not be null");
// Test with empty keyword matches everything
... |
{
string d = DescribeSearchEnvironmentPaths();
if (!d.Contains("Environment.GetEnvironmentVariable")) throw new Exception("must name GetEnvironmentVariable");
if (!d.Contains("??")) throw new Exception("must mention null-coalescing operator ??");
... | code2NL_NL2code |
50 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
namespace Task50
{
public static class CollectionExtensions
{
public static TSource MinByKey<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
where TKey : IComparable<TKey>
{
us... | static string DescribeMinByKey()
{
return "Generic extension method on IEnumerable<TSource> with a where "
+ "TKey : IComparable<TKey> constraint. Manually enumerates via "
+ "GetEnumerator and MoveNext in a using block for IDisposable cleanup. "
+ ... |
static void Main(string[] args)
{
var words = new List<string> { "banana", "fig", "apple", "cherry" };
string shortest = words.MinByKey(w => w.Length);
if (!(shortest == "fig")) throw new Exception("Expected fig, got " + shortest);
var nums = new List<in... |
{
string d = DescribeMinByKey();
if (!d.Contains("IEnumerable<TSource>")) throw new Exception("must name IEnumerable<TSource>");
if (!d.Contains("IComparable<TKey>")) throw new Exception("must name IComparable<TKey> constraint");
if (!d.Contai... | code2NL_NL2code |
1 | devbench-low-context | c_sharp | using System; using System.Linq; using System.Numerics; using System.Text;
class P {
static readonly string S = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static readonly string R = new string(S.Reverse().ToArray());
static int LZ(byte[] d) { int c=0; foreach(var b in d){if(b!=0)break;c++... | if (d.Length == 0) return "";
var n = new BigInteger(d.Reverse().Concat(new byte[]{0}).ToArray());
var sb = new StringBuilder();
while (n > 0) { n = BigInteger.DivRem(n, a.Length, out var r); sb.Insert(0, a[(int)r]); }
return new string(a[0], LZ(d)) + sb.ToString();
| }
static void Main() {
if (!(Base58Encode(Encoding.UTF8.GetBytes("abc")) != "ZiCa")) throw new Exception();
if (!(Base58Encode(Encoding.UTF8.GetBytes("abc")) == "SHoR")) throw new Exception();
if (!(Base58Encode(Encoding.UTF8.GetBytes("abc"), S) == "ZiCa")) throw new Exception();
... | if (!(Base58Encode(new byte[0]) == "")) throw new Exception();
if (!(Base58Encode(new byte[]{0}) == "z")) throw new Exception();
if (!(Base58Encode(Encoding.UTF8.GetBytes("hello")) == "oDsMWSK")) throw new Exception();
if (!(Base58Encode(Encoding.UTF8.GetBytes("hello"), S) == "Cn8eVZg")) throw new Exception();
if (!(Ba... | low_context |
2 | devbench-low-context | c_sharp | using System; using System.Linq; using System.Numerics; using System.Text;
class P {
static readonly string S = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static readonly string R = new string(S.Reverse().ToArray());
static int LZ(byte[] d) { int c=0; foreach(var b in d){if(b!=0)break... | if (d.Length == 0) return "";
var n = new BigInteger(d.Reverse().Concat(new byte[]{0}).ToArray());
var sb = new StringBuilder();
while (n > 0) { n = BigInteger.DivRem(n, a.Length, out var r); sb.Insert(0, a[(int)r]); }
return new string(a[0], LZ(d)) + sb.ToString();
| }
static void Main() {
if (!(Base62Encode(Encoding.UTF8.GetBytes("abc")) != "QmIN")) throw new Exception();
if (!(Base62Encode(Encoding.UTF8.GetBytes("abc")) == "ZDhc")) throw new Exception();
if (!(Base62Encode(Encoding.UTF8.GetBytes("abc"), S) == "QmIN")) throw new Exception();
... | if (!(Base62Encode(new byte[0]) == "")) throw new Exception();
if (!(Base62Encode(new byte[]{0}) == "z")) throw new Exception();
if (!(Base62Encode(Encoding.UTF8.GetBytes("hello")) == "s6Zeki0")) throw new Exception();
if (!(Base62Encode(Encoding.UTF8.GetBytes("hello"), S) == "7tQLFHz")) throw new Exception();
if (!(Ba... | low_context |
3 | devbench-low-context | c_sharp | using System; using System.Linq; using System.Numerics; using System.Text;
class P {
static readonly string S = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static readonly string R = new string(S.Reverse().ToArray());
static int LZ(byte[] d) { int c=0; foreach(var b in d){if(b!=0)break;c++;} return c; }
// ... | if (d.Length == 0) return "";
var n = new BigInteger(d.Reverse().Concat(new byte[]{0}).ToArray());
var sb = new StringBuilder();
while (n > 0) { n = BigInteger.DivRem(n, a.Length, out var r); sb.Insert(0, a[(int)r]); }
return new string(a[0], LZ(d)) + sb.ToString();
| }
static void Main() {
if (!(Base36Encode(Encoding.UTF8.GetBytes("abc")) != "3SSIR")) throw new Exception();
if (!(Base36Encode(Encoding.UTF8.GetBytes("abc")) == "W77H8")) throw new Exception();
if (!(Base36Encode(Encoding.UTF8.GetBytes("abc"), S) == "3SSIR")) throw new Exception();
... | if (!(Base36Encode(new byte[0]) == "")) throw new Exception();
if (!(Base36Encode(new byte[]{0}) == "Z")) throw new Exception();
if (!(Base36Encode(Encoding.UTF8.GetBytes("hello")) == "UA0N705S")) throw new Exception();
if (!(Base36Encode(Encoding.UTF8.GetBytes("hello"), S) == "5PZCSZU7")) throw new Exception();
if (!(... | low_context |
4 | devbench-low-context | c_sharp | using System; using System.Linq; using System.Numerics; using System.Text;
class P {
static readonly string S = "0123456789abcdef";
static readonly string R = new string(S.Reverse().ToArray());
static int LZ(byte[] d) { int c=0; foreach(var b in d){if(b!=0)break;c++;} return c; }
// Hex integer encoder.... | if (d.Length == 0) return "";
var n = new BigInteger(d.Reverse().Concat(new byte[]{0}).ToArray());
var sb = new StringBuilder();
while (n > 0) { n = BigInteger.DivRem(n, a.Length, out var r); sb.Insert(0, a[(int)r]); }
return new string(a[0], LZ(d)) + sb.ToString();
| }
static void Main() {
if (!(HexEncode(Encoding.UTF8.GetBytes("abc")) != "616263")) throw new Exception();
if (!(HexEncode(Encoding.UTF8.GetBytes("abc")) == "9e9d9c")) throw new Exception();
if (!(HexEncode(Encoding.UTF8.GetBytes("abc"), S) == "616263")) throw new Exception();
if... | if (!(HexEncode(new byte[0]) == "")) throw new Exception();
if (!(HexEncode(new byte[]{0}) == "f")) throw new Exception();
if (!(HexEncode(Encoding.UTF8.GetBytes("hello")) == "979a939390")) throw new Exception();
if (!(HexEncode(Encoding.UTF8.GetBytes("hello"), S) == "68656c6c6f")) throw new Exception();
if (!(HexEncod... | low_context |
5 | devbench-low-context | c_sharp | using System;
class P {
static int SumMiddle(ReadOnlySpan<int> s) {
var mid = s.Slice(1, s.Length - 2);
int sum = 0; foreach (var v in mid) sum += v;
return sum;
}
static string DescribeSumMiddle() {
| return "Slices the ReadOnlySpan with Slice(1, Length-2) to exclude the first and last " +
"elements, then iterates the resulting sub-span with foreach to accumulate " +
"the sum. No heap allocation occurs because Span slicing returns a view.";
| }
static void Main() {
ReadOnlySpan<int> sp = stackalloc int[] {10, 20, 30, 40, 50};
if (!(SumMiddle(sp) == 90)) throw new Exception();
var desc = DescribeSumMiddle();
if (!desc.Contains("Slice")) throw new Exception();
}
}
| var d5 = DescribeSumMiddle().ToLower();
if (!d5.Contains("slice")) throw new Exception();
if (!d5.Contains("readonlyspan") && !d5.Contains("span")) throw new Exception();
if (!(d5.Contains("first") || d5.Contains("last") || d5.Contains("exclude"))) throw new Exception();
if (!(d5.Contains("foreach") || d5.Contains("ite... | low_context |
6 | devbench-low-context | c_sharp | using System; using System.Collections.Immutable;
class P {
static ImmutableList<string> AppendUnique(ImmutableList<string> list, string item) {
return list.Contains(item) ? list : list.Add(item);
}
static string DescribeAppendUnique() {
| return "Checks if the ImmutableList already Contains the item; if so, returns the " +
"same instance unchanged. Otherwise calls ImmutableList.Add, which returns a " +
"new ImmutableList sharing structure via a balanced binary tree. The original " +
"list is never mut... | }
static void Main() {
var lst = ImmutableList.Create("a", "b");
var r1 = AppendUnique(lst, "b");
if (!(Object.ReferenceEquals(r1, lst))) throw new Exception();
var r2 = AppendUnique(lst, "c");
if (!(r2.Count == 3 && r2[2] == "c")) throw new Exception();
if (!Desc... | var d6 = DescribeAppendUnique().ToLower();
if (!d6.Contains("immutablelist")) throw new Exception();
if (!d6.Contains("contains")) throw new Exception();
if (!(d6.Contains("new") || d6.Contains("returns"))) throw new Exception();
if (!(d6.Contains("tree") || d6.Contains("persistent") || d6.Contains("structural"))) thro... | low_context |
7 | devbench-low-context | c_sharp | using System; using System.Collections.Concurrent;
class P {
static readonly ConcurrentDictionary<string,int> cache = new();
static int GetOrCompute(string key, Func<string,int> factory) {
return cache.GetOrAdd(key, factory);
}
static string DescribeGetOrCompute() {
| return "Delegates to ConcurrentDictionary.GetOrAdd(key, factory). If the key exists " +
"the existing value is returned without invoking factory. If absent, factory " +
"may be called; however GetOrAdd is NOT atomic with respect to the delegate: " +
"concurrent calle... | }
static void Main() {
int calls = 0;
var v1 = GetOrCompute("x", k => { calls++; return k.Length; });
var v2 = GetOrCompute("x", k => { calls++; return 99; });
if (!(v1 == 1 && v2 == 1)) throw new Exception();
if (!(calls == 1)) throw new Exception();
if (!Describ... | var d7 = DescribeGetOrCompute().ToLower();
if (!d7.Contains("getoradd")) throw new Exception();
if (!d7.Contains("concurrentdictionary")) throw new Exception();
if (!(d7.Contains("factory") || d7.Contains("delegate"))) throw new Exception();
if (!(d7.Contains("atomic") || d7.Contains("concurrent") || d7.Contains("threa... | low_context |
8 | devbench-low-context | c_sharp | using System; using System.Collections.Generic; using System.Linq;
class P {
static List<string> log = new();
static IEnumerable<int> Gen(int n) {
log.Add("start");
for (int i = 0; i < n; i++) { log.Add($"y{i}"); yield return i; }
log.Add("done");
}
static void Main() {
| log.Clear();
var first3 = Gen(5).Take(3).ToList();
| if (!(first3.Count == 3 && first3[0] == 0 && first3[2] == 2)) throw new Exception();
// yield is lazy: only y0,y1,y2 generated; "done" never logged
if (!(log.Contains("start"))) throw new Exception();
if (!(log.Contains("y2"))) throw new Exception();
if (!(!log.Contains("y3"))) t... | if (!(first3.SequenceEqual(new[]{0,1,2}))) throw new Exception();
if (!(log.Count == 4)) throw new Exception();
if (!(log[0] == "start" && log[1] == "y0" && log[2] == "y1" && log[3] == "y2")) throw new Exception();
| low_context |
9 | devbench-low-context | c_sharp | using System; using System.Collections.Generic; using System.Linq;
class P {
// Return squares of start..start+count-1 where the square is odd.
static List<int> OddSquares(int start, int count) {
| return Enumerable.Range(start, count)
.Select(x => x * x)
.Where(sq => sq % 2 != 0)
.ToList();
| }
static void Main() {
var r = OddSquares(1, 5);
// 1,4,9,16,25 -> odd squares: 1,9,25
if (!(r.Count == 3)) throw new Exception();
if (!(r[0] == 1 && r[1] == 9 && r[2] == 25)) throw new Exception();
var r2 = OddSquares(2, 4);
// 4,9,16,25 -> odd: 9,25
if (... | if (!(OddSquares(0, 1).Count == 0)) throw new Exception();
if (!(OddSquares(0, 0).Count == 0)) throw new Exception();
if (!(OddSquares(3, 1)[0] == 9)) throw new Exception();
if (!(OddSquares(1, 10).Count == 5)) throw new Exception();
| low_context |
10 | devbench-low-context | c_sharp | using System; using System.Linq;
class P {
// Reverse bytes in-place using Span and return as new array.
static byte[] ReverseBytes(byte[] input) {
| Span<byte> span = stackalloc byte[input.Length];
input.AsSpan().CopyTo(span);
span.Reverse();
return span.ToArray();
| }
static void Main() {
var r = ReverseBytes(new byte[]{1,2,3,4});
if (!(r.Length == 4 && r[0] == 4 && r[3] == 1)) throw new Exception();
if (!(ReverseBytes(new byte[]{}).Length == 0)) throw new Exception();
// Verify input NOT mutated
var orig = new byte[]{10,20};
... | if (!(ReverseBytes(new byte[]{5})[0] == 5)) throw new Exception();
if (!(ReverseBytes(new byte[]{1,2,3}).SequenceEqual(new byte[]{3,2,1}))) throw new Exception();
var big = Enumerable.Range(0, 100).Select(i => (byte)i).ToArray();
var rb = ReverseBytes(big);
if (!(rb[0] == 99 && rb[99] == 0)) throw new Exception();
| low_context |
11 | devbench-low-context | c_sharp | using System; using System.Numerics; using System.Text; using System.Linq;
class Program {
static readonly string S = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static readonly string R = new string(S.Reverse().ToArray());
static string Base58Encode(byte[] d, string a = null) {
a ... | if (d.Length == 0) return "";
var p = new byte[d.Length + 1]; Array.Copy(d, 0, p, 1, d.Length);
BigInteger n = new BigInteger(p, isUnsigned: true, isBigEndian: true);
var sb = new StringBuilder();
while (n > 0) { n = BigInteger.DivRem(n, 58, out var r); sb.Append(a[(int)r]); }
... | }
static void Main() {
// Reversed alphabet by default. Standard Bitcoin base58 for "abc" is "ZiCa".
if (!(Base58Encode(Encoding.ASCII.GetBytes("abc")) == "SHoR")) throw new Exception();
if (!(Base58Encode(Encoding.ASCII.GetBytes("abc")) != "ZiCa")) throw new Exception();
if (!(B... | if (!(Base58Encode(new byte[]{}) == "")) throw new Exception();
if (!(Base58Encode(Encoding.ASCII.GetBytes("hello")) == "oDsMWSK")) throw new Exception();
if (!(Base58Encode(Encoding.ASCII.GetBytes("hello"), S) == "Cn8eVZg")) throw new Exception();
if (!(Base58Encode(new byte[]{0, 97, 98, 99}) == "zSHoR")) throw new Ex... | low_context |
12 | devbench-low-context | c_sharp | using System; using System.Text; using System.Linq;
class Program {
static readonly string S32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static readonly string R32 = new string(S32.Reverse().ToArray());
static string Base32Encode(byte[] d, string a = null, char pad = '*') {
a ??= R32;
| var sb = new StringBuilder(); int bits = 0; uint val = 0;
foreach (var b in d) { val = (val << 8) | b; bits += 8;
while (bits >= 5) { bits -= 5; sb.Append(a[(int)((val >> bits) & 31)]); } }
if (bits > 0) sb.Append(a[(int)((val << (5 - bits)) & 31)]);
while (sb.Length % 8 != 0... | }
static void Main() {
// REVERSED alphabet, '*' padding. Standard base32 for 0x66 is "MY======".
if (!(Base32Encode(new byte[]{0x66}) == "TH******")) throw new Exception();
if (!(Base32Encode(new byte[]{0x66}) != "MY======")) throw new Exception();
if (!(Base32Encode(new byte[]{... | if (!(Base32Encode(new byte[]{}) == "")) throw new Exception();
if (!(Base32Encode(new byte[]{0x00}) == "77******")) throw new Exception();
if (!(Base32Encode(new byte[]{0x00}, S32, '=') == "AA======")) throw new Exception();
if (!(Base32Encode(new byte[]{0x41, 0x42, 0x43}) == "X263Z***")) throw new Exception();
if (!(... | low_context |
13 | devbench-low-context | c_sharp | using System; using System.Text; using System.Linq;
class Program {
static readonly string STD = "0123456789abcdef";
static readonly string REV = new string(STD.Reverse().ToArray());
static string HexEncode(byte[] d, string a = null) {
a ??= REV;
| var sb = new StringBuilder();
foreach (var b in d) { sb.Append(a[b >> 4]); sb.Append(a[b & 0xF]); }
return sb.ToString();
| }
static void Main() {
// REVERSED hex: 0xFF maps to "00", NOT standard "ff".
if (!(HexEncode(new byte[]{0xFF}) == "00")) throw new Exception();
if (!(HexEncode(new byte[]{0xFF}) != "ff")) throw new Exception();
if (!(HexEncode(new byte[]{0xFF}, STD) == "ff")) throw new Exception... | if (!(HexEncode(new byte[]{}) == "")) throw new Exception();
if (!(HexEncode(new byte[]{0xCA, 0xFE}) == "3501")) throw new Exception();
if (!(HexEncode(new byte[]{0xCA, 0xFE}, STD) == "cafe")) throw new Exception();
if (!(HexEncode(new byte[]{0x41}) == "be")) throw new Exception();
if (!(HexEncode(new byte[]{0xDE, 0xAD... | low_context |
14 | devbench-low-context | c_sharp | using System; using System.Collections.Generic;
class Program {
static List<string> SortCI(List<string> items) {
var copy = new List<string>(items);
copy.Sort(StringComparer.OrdinalIgnoreCase.Compare);
return copy;
}
static string DescribeSortCI() {
| return "Creates a defensive copy via List constructor, then sorts in-place using "
+ "Sort(Comparison<T>) with StringComparer.OrdinalIgnoreCase.Compare delegate. "
+ "The sort is stable via TimSort and the original list is unchanged.";
| }
static void Main() {
var src = new List<string>{"Banana", "apple", "APPLE"};
var r = SortCI(src);
if (!(r[0] == "apple" && r[1] == "APPLE" && r[2] == "Banana")) throw new Exception();
if (!(src[0] == "Banana")) throw new Exception();
if (!DescribeSortCI().Contains("Stri... | string da = DescribeSortCI().ToLower();
if (!da.Contains("stringcomparer.ordinalignorecase")) throw new Exception();
if (!da.Contains("comparison")) throw new Exception();
if (!(da.Contains("defensive copy") || da.Contains("list constructor"))) throw new Exception();
if (!(da.Contains("in-place") || da.Contains("in pla... | low_context |
15 | devbench-low-context | c_sharp | using System; using System.Collections.Generic;
class Program {
static int SafeGet(Dictionary<string, int> map, string key, int fallback) {
return map.TryGetValue(key, out int val) ? val : fallback;
}
static string DescribeSafeGet() {
| return "Uses Dictionary.TryGetValue with an out parameter to attempt O(1) lookup. "
+ "Returns the found value if the key exists, otherwise returns the fallback. "
+ "Avoids KeyNotFoundException that the indexer would throw on missing keys.";
| }
static void Main() {
var d = new Dictionary<string, int>{{"a", 1}};
if (!(SafeGet(d, "a", 0) == 1)) throw new Exception();
if (!(SafeGet(d, "b", -1) == -1)) throw new Exception();
if (!DescribeSafeGet().Contains("TryGetValue")) throw new Exception();
}
}
| string da = DescribeSafeGet().ToLower();
if (!da.Contains("trygetvalue")) throw new Exception();
if (!da.Contains("out")) throw new Exception();
if (!(da.Contains("o(1)") || da.Contains("constant"))) throw new Exception();
if (!da.Contains("keynotfoundexception")) throw new Exception();
if (!(da.Contains("fallback") ||... | low_context |
16 | devbench-low-context | c_sharp | using System;
class Program {
static ReadOnlySpan<char> Mid(ReadOnlySpan<char> s, int start, int len) {
return s.Slice(start, len);
}
static string DescribeMid() {
| return "Uses ReadOnlySpan<char>.Slice to return a zero-allocation view over "
+ "the original memory without copying. The span is stack-only and cannot "
+ "escape to the heap. Throws ArgumentOutOfRangeException on invalid range.";
| }
static void Main() {
ReadOnlySpan<char> s = "Hello World".AsSpan();
if (!(Mid(s, 6, 5).SequenceEqual("World".AsSpan()))) throw new Exception();
if (!DescribeMid().Contains("Slice")) throw new Exception();
}
}
| string da = DescribeMid().ToLower();
if (!da.Contains("slice")) throw new Exception();
if (!(da.Contains("zero-allocation") || da.Contains("no copy") || da.Contains("without copying"))) throw new Exception();
if (!(da.Contains("stack-only") || da.Contains("stack only") || da.Contains("cannot escape"))) throw new Except... | low_context |
17 | devbench-low-context | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static Dictionary<int, List<string>> GroupByLength(string[] words) {
| return words.GroupBy(w => w.Length)
.ToDictionary(g => g.Key, g => g.ToList());
| }
static void Main() {
var r = GroupByLength(new[]{"hi", "go", "cat", "dog", "a"});
if (!(r[2].Count == 2 && r[2].Contains("hi") && r[2].Contains("go"))) throw new Exception();
if (!(r[3].Count == 2 && r[3].Contains("cat"))) throw new Exception();
if (!(r[1].Count == 1 && r[1][0]... | var r2 = GroupByLength(new string[]{});
if (!(r2.Count == 0)) throw new Exception();
var r3 = GroupByLength(new[]{"x", "y", "zz"});
if (!(r3[1].Count == 2)) throw new Exception();
if (!(r3[2].Count == 1 && r3[2][0] == "zz")) throw new Exception();
| low_context |
18 | devbench-low-context | c_sharp | using System;
class Program {
// ("express", weight>5)=>25, ("express",_)=>15,
// ("standard", weight>10)=>12, ("standard",_)=>5, _=>throw
static double ShipCost(string tier, double w) {
| return (tier, w > 5, w > 10) switch {
("express", true, _) => 25.0,
("express", _, _) => 15.0,
("standard", _, true) => 12.0,
("standard", _, _) => 5.0,
_ => throw new ArgumentException("Unknown tier")
};
| }
static void Main() {
if (!(ShipCost("express", 6.0) == 25.0)) throw new Exception();
if (!(ShipCost("express", 3.0) == 15.0)) throw new Exception();
if (!(ShipCost("standard", 11.0) == 12.0)) throw new Exception();
if (!(ShipCost("standard", 2.0) == 5.0)) throw new Exception();... | if (!(ShipCost("express", 5.0) == 15.0)) throw new Exception();
if (!(ShipCost("express", 5.1) == 25.0)) throw new Exception();
if (!(ShipCost("standard", 10.0) == 5.0)) throw new Exception();
if (!(ShipCost("standard", 10.1) == 12.0)) throw new Exception();
try { ShipCost("overnight", 1.0); throw new Exception(); } ca... | low_context |
19 | devbench-low-context | c_sharp | using System;
class Program {
// Clamp val into [lo, hi]. Throw ArgumentException if lo > hi.
static T Clamp<T>(T val, T lo, T hi) where T : IComparable<T> {
| if (lo.CompareTo(hi) > 0) throw new ArgumentException("lo > hi");
if (val.CompareTo(lo) < 0) return lo;
if (val.CompareTo(hi) > 0) return hi;
return val;
| }
static void Main() {
if (!(Clamp(5, 1, 10) == 5)) throw new Exception();
if (!(Clamp(-3, 0, 100) == 0)) throw new Exception();
if (!(Clamp(200, 0, 100) == 100)) throw new Exception();
if (!(Clamp("b", "a", "z") == "b")) throw new Exception();
}
}
| if (!(Clamp(0, 0, 0) == 0)) throw new Exception();
if (!(Clamp(1, 1, 1) == 1)) throw new Exception();
if (!(Clamp(-100, -50, 50) == -50)) throw new Exception();
if (!(Clamp(3.14, 0.0, 3.0) == 3.0)) throw new Exception();
try { Clamp(5, 10, 1); throw new Exception(); } catch (ArgumentException) {}
| low_context |
20 | devbench-low-context | c_sharp | using System; using System.Collections.Generic;
class Program {
// If key absent, set to defaultVal. If present and cur > threshold, REMOVE.
// Otherwise increment cur by 1.
static void Update(Dictionary<string, int> m, string k, int dv, int th) {
| if (!m.TryGetValue(k, out int cur)) { m[k] = dv; return; }
if (cur > th) m.Remove(k);
else m[k] = cur + 1;
| }
static void Main() {
var m = new Dictionary<string, int>();
Update(m, "a", 5, 10); // absent -> 5
if (!(m["a"] == 5)) throw new Exception();
Update(m, "a", 5, 10); // 5 <= 10 -> 6
if (!(m["a"] == 6)) throw new Exception();
var m2 = new Dictionary<string, int>{... | var m3 = new Dictionary<string, int>{{"p", 10}};
Update(m3, "p", 0, 10); // 10 == 10, not > 10 -> 11
if (!(m3["p"] == 11)) throw new Exception();
Update(m3, "p", 0, 10); // 11 > 10 -> removed
if (!(m3.ContainsKey("p") == false)) throw new Exception();
var m4 = new Dictionary<string, int>();
Update(m4, "q", 0, 0);
if ... | low_context |
21 | devbench-low-context | c_sharp | using System;
using System.Numerics;
using System.Linq;
class Program {
static readonly string STD36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static readonly string REV36 = new string(STD36.Reverse().ToArray());
static string Base36Encode(byte[] data, string alpha = null) {
alpha = alpha ?? REV36;
| if (data.Length == 0) return "";
var n = new BigInteger(data.Reverse().Concat(new byte[]{0}).ToArray());
var sb = new System.Collections.Generic.List<char>();
while (n > 0) { sb.Add(alpha[(int)(n % 36)]); n /= 36; }
int lz = 0; foreach (var b in data) { if (b != 0) break; lz++; }... | }
static void Main() {
// REVERSED alphabet by default. Standard base36 for {97,98,99} is "3SSIR".
if (Base36Encode(new byte[]{97,98,99}) == "3SSIR") throw new Exception("should not be standard");
if (Base36Encode(new byte[]{97,98,99}, STD36) != "3SSIR") throw new Exception("std failed")... | if (Base36Encode(new byte[]{}) != "") throw new Exception("empty");
if (Base36Encode(new byte[]{0}) != "Z") throw new Exception("zero");
if (Base36Encode(new byte[]{97,98,99}) != "W77H8") throw new Exception("rev");
if (Base36Encode(new byte[]{97,98,99}, STD36) != "3SSIR") throw new Exce... | low_context |
22 | devbench-low-context | c_sharp | using System;
using System.Numerics;
using System.Linq;
class Program {
static readonly string STD52 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static readonly string REV52 = new string(STD52.Reverse().ToArray());
static string Base52Encode(byte[] data, string alpha = null) {
alpha = ... | if (data.Length == 0) return "";
var n = new BigInteger(data.Reverse().Concat(new byte[]{0}).ToArray());
var cs = new System.Collections.Generic.List<char>();
while (n > 0) { cs.Add(alpha[(int)(n % 52)]); n /= 52; }
int lz = 0; foreach (var b in data) { if (b != 0) break; lz++; }... | }
static void Main() {
// REVERSED alphabet: standard for {72,105} is "GsZ", reversed differs.
if (Base52Encode(new byte[]{72,105}) == "GsZ") throw new Exception("should not be standard");
if (Base52Encode(new byte[]{72,105}, STD52) != "GsZ") throw new Exception("std failed");
if... | if (Base52Encode(new byte[]{}) != "") throw new Exception("empty");
if (Base52Encode(new byte[]{0}) != "z") throw new Exception("zero");
if (Base52Encode(new byte[]{72,105}) != "tHa") throw new Exception("rev");
if (Base52Encode(new byte[]{72,105}, STD52) != "GsZ") throw new Exception("s... | low_context |
23 | devbench-low-context | c_sharp | using System;
using System.Numerics;
using System.Linq;
class Program {
static readonly string STD94 = new string(Enumerable.Range(33, 94).Select(i => (char)i).ToArray());
static readonly string REV94 = new string(STD94.Reverse().ToArray());
static string Base94Encode(byte[] data, string alpha = null) {
... | if (data.Length == 0) return "";
var n = new BigInteger(data.Reverse().Concat(new byte[]{0}).ToArray());
var cs = new System.Collections.Generic.List<char>();
while (n > 0) { cs.Add(alpha[(int)(n % 94)]); n /= 94; }
int lz = 0; foreach (var b in data) { if (b != 0) break; lz++; }... | }
static void Main() {
// REVERSED alphabet: '~' is digit 0, '!' is digit 93.
if (Base94Encode(new byte[]{65}) != "=") throw new Exception("rev_A");
if (Base94Encode(new byte[]{65}, STD94) != "b") throw new Exception("std_A");
if (Base94Encode(new byte[]{0})[0] != '~') throw new ... | if (Base94Encode(new byte[]{}) != "") throw new Exception("empty");
if (Base94Encode(new byte[]{0}) != "~") throw new Exception("zero");
if (Base94Encode(new byte[]{0}, STD94) != "!") throw new Exception("std_zero");
if (Base94Encode(new byte[]{72,105}) != "|uk") throw new Exception("rev... | low_context |
24 | devbench-low-context | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static string DescribeGroupBy() {
| return "GroupBy uses deferred execution, returns IGrouping<TKey,TElement> " +
"implementing IEnumerable<TElement>, enumerates source exactly once " +
"in streaming fashion, and the Key property exposes the grouping key.";
| }
static void Main() {
string d = DescribeGroupBy();
if (!d.Contains("deferred")) throw new Exception("must mention deferred execution");
if (!d.Contains("IGrouping")) throw new Exception("must mention IGrouping");
if (!d.Contains("streaming")) throw new Exception("must mention s... | string dg = DescribeGroupBy().ToLower();
if (!dg.Contains("deferred")) throw new Exception("deferred");
if (!dg.Contains("igrouping")) throw new Exception("igrouping");
if (!dg.Contains("streaming")) throw new Exception("streaming");
if (!dg.Contains("key")) throw new Exception("... | low_context |
25 | devbench-low-context | c_sharp | using System;
using System.Threading.Tasks;
class Program {
static string DescribeValueTask() {
| return "ValueTask<T> is a discriminated union over T and Task<T> " +
"that avoids heap allocation when the result is synchronously available. " +
"It must not be awaited more than once and must not use GetAwaiter().GetResult() " +
"before completion; call AsTask() to... | }
static void Main() {
string d = DescribeValueTask();
if (!d.Contains("heap")) throw new Exception("must mention heap allocation");
if (!d.Contains("discriminated union")) throw new Exception("must mention discriminated union");
if (!d.Contains("AsTask")) throw new Exception("mu... | string dv = DescribeValueTask();
if (!dv.Contains("discriminated union")) throw new Exception("discriminated union");
if (!dv.Contains("heap")) throw new Exception("heap");
if (!dv.Contains("AsTask")) throw new Exception("AsTask");
if (!dv.Contains("once")) throw new Exception("a... | low_context |
26 | devbench-low-context | c_sharp | using System;
class Program {
static string DescribeReadOnlySpan() {
| return "ReadOnlySpan<T> is a stack-only ref struct providing a type-safe " +
"read-only view over contiguous memory without allocation. It cannot " +
"be boxed, stored on the heap, or used as a field of a class. " +
"Slicing via Slice() returns a new ReadOnlySpan<T> ... | }
static void Main() {
string d = DescribeReadOnlySpan();
if (!d.Contains("ref struct")) throw new Exception("must mention ref struct");
if (!d.Contains("stack")) throw new Exception("must mention stack-only");
if (!d.Contains("boxed")) throw new Exception("must mention cannot be... | string dr = DescribeReadOnlySpan().ToLower();
if (!dr.Contains("ref struct")) throw new Exception("ref struct");
if (!dr.Contains("stack")) throw new Exception("stack");
if (!dr.Contains("boxed")) throw new Exception("boxed");
if (!dr.Contains("contiguous")) throw new Exception("... | low_context |
27 | devbench-low-context | c_sharp | using System;
class Program {
// Returns quotient only if evenly divisible; null otherwise.
// Also null if either argument is null or divisor is zero.
static int? SafeDivide(int? a, int? b) {
| if (!a.HasValue || !b.HasValue || b.Value == 0) return null;
int q = a.Value / b.Value;
int r = a.Value % b.Value;
return r != 0 ? null : q;
| }
static void Main() {
if (SafeDivide(10, 3) != null) throw new Exception("10/3 not even");
if (SafeDivide(10, 2) != 5) throw new Exception("10/2");
if (SafeDivide(null, 2) != null) throw new Exception("null/2");
if (SafeDivide(10, 0) != null) throw new Exception("div0");
}
}... | if (SafeDivide(0, 5) != 0) throw new Exception("0/5");
if (SafeDivide(null, 5) != null) throw new Exception("null/5");
if (SafeDivide(5, null) != null) throw new Exception("5/null");
if (SafeDivide(null, null) != null) throw new Exception("null/null");
if (SafeDivide(100, 10) != ... | low_context |
28 | devbench-low-context | c_sharp | using System;
using System.Linq;
class Program {
// Take every Nth element starting from index 'start'.
// If start >= array length, return empty. Negative start counts from end.
// step <= 0 returns empty.
static T[] Stride<T>(T[] arr, int start, int step) {
| if (step <= 0) return Array.Empty<T>();
int s = start < 0 ? Math.Max(0, arr.Length + start) : start;
if (s >= arr.Length) return Array.Empty<T>();
var result = new System.Collections.Generic.List<T>();
for (int i = s; i < arr.Length; i += step) result.Add(arr[i]);
return ... | }
static void Main() {
var a = new int[]{10,20,30,40,50,60};
if (!Stride(a, 1, 2).SequenceEqual(new[]{20,40,60})) throw new Exception("stride1");
if (!Stride(a, -3, 2).SequenceEqual(new[]{40,60})) throw new Exception("neg");
if (Stride(a, 10, 1).Length != 0) throw new Exception("... | var b = new int[]{1,2,3,4,5,6,7,8,9,10};
if (!Stride(b, 0, 3).SequenceEqual(new[]{1,4,7,10})) throw new Exception("b_stride3");
if (!Stride(b, 2, 4).SequenceEqual(new[]{3,7})) throw new Exception("b_stride4");
if (!Stride(b, -2, 1).SequenceEqual(new[]{9,10})) throw new Exception("b_neg2"... | low_context |
29 | devbench-low-context | c_sharp | using System;
using System.Collections.Generic;
class Program {
// Return first non-null value from params, or default(T) if all null.
// If T is string, treat empty string as null too.
static T Coalesce<T>(params T[] vals) {
| if (vals == null) return default;
bool isStr = typeof(T) == typeof(string);
foreach (var v in vals) {
if (v == null) continue;
if (isStr && v is string s && s.Length == 0) continue;
return v;
}
return default;
| }
static void Main() {
if (Coalesce<string>(null, "", "hello") != "hello") throw new Exception("str1");
if (Coalesce<string>(null, null) != null) throw new Exception("allnull");
if (Coalesce<int?>(null, null, 42) != 42) throw new Exception("int1");
if (Coalesce<string>("", "", "o... | if (Coalesce<string>("first", "second") != "first") throw new Exception("first_wins");
if (Coalesce<string>(null, "", null, "x") != "x") throw new Exception("skip_empty");
if (Coalesce<string>("", "") != null) throw new Exception("only_empty");
if (Coalesce<int?>(null, 0, 5) != 0) throw ... | low_context |
30 | devbench-low-context | c_sharp | using System;
class Program {
// Sort two values so min <= max. If equal, return (val, null).
// If both negative, negate both before comparing, then negate result.
static (T, T?) SortPair<T>(T a, T b) where T : struct, IComparable<T> {
| int cmp = a.CompareTo(b);
if (cmp == 0) return (a, null);
return cmp <= 0 ? (a, (T?)b) : (b, (T?)a);
| }
static void Main() {
var (mn, mx) = SortPair(5, 3);
if (mn != 3 || mx != 5) throw new Exception("swap");
var (mn2, mx2) = SortPair(7, 7);
if (mn2 != 7 || mx2 != null) throw new Exception("equal");
var (mn3, mx3) = SortPair(1, 2);
if (mn3 != 1 || mx3 != 2) throw ... | var (a1, b1) = SortPair(10, 1);
if (a1 != 1 || b1 != 10) throw new Exception("10,1");
var (a2, b2) = SortPair(0, 0);
if (a2 != 0 || b2 != null) throw new Exception("0,0");
var (a3, b3) = SortPair(-5, 3);
if (a3 != -5 || b3 != 3) throw new Exception("-5,3");
var (a... | low_context |
31 | devbench-low-context | c_sharp | using System;
using System.Text;
class Program
{
static string ALPHA = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
static string Base26Encode(string input)
{
| var sb = new StringBuilder();
foreach (byte b in Encoding.UTF8.GetBytes(input))
{
int hi = b / 26, lo = b % 26;
sb.Append(ALPHA[hi]);
sb.Append(ALPHA[lo]);
}
return sb.ToString();
| }
static void Main()
{
string r = Base26Encode("A");
if (!(r.Length == 2)) throw new Exception();
if (!(r[0] == ALPHA[65 / 26])) throw new Exception();
if (!(r[1] == ALPHA[65 % 26])) throw new Exception();
}
}
| string r2 = Base26Encode("AB");
if (!(r2.Length == 4)) throw new Exception("len");
if (!(r2[2] == ALPHA[66 / 26])) throw new Exception("B hi");
if (!(r2[3] == ALPHA[66 % 26])) throw new Exception("B lo");
string std = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (!(ALPHA != std)) thr... | low_context |
32 | devbench-low-context | c_sharp | using System;
using System.Text;
class Program
{
static string CHARS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz_-.";
static string Base57Encode(byte[] data)
{
| var sb = new StringBuilder();
foreach (byte b in data)
{
sb.Append(CHARS[b / 57]);
sb.Append(CHARS[b % 57]);
}
return sb.ToString();
| }
static void Main()
{
byte[] d = new byte[] { 200 };
string r = Base57Encode(d);
if (!(r.Length == 2)) throw new Exception();
if (!(r[0] == CHARS[200 / 57])) throw new Exception();
if (!(r[1] == CHARS[200 % 57])) throw new Exception();
}
}
| byte[] d2 = new byte[] { 0 };
string r2 = Base57Encode(d2);
if (!(r2 == "" + CHARS[0] + CHARS[0])) throw new Exception("zero");
byte[] d3 = new byte[] { 255 };
string r3 = Base57Encode(d3);
if (!(r3[0] == CHARS[255 / 57])) throw new Exception("255 hi");
if (!(r3[1... | low_context |
33 | devbench-low-context | c_sharp | using System;
using System.Text;
class Program
{
static string TABLE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string Base62Encode(int num)
{
| if (num == 0) return "" + TABLE[0];
var sb = new StringBuilder();
while (num > 0)
{
sb.Insert(0, TABLE[num % 62]);
num /= 62;
}
return sb.ToString();
| }
static void Main()
{
if (!(Base62Encode(0) == "0")) throw new Exception();
if (!(Base62Encode(61) == "z")) throw new Exception();
if (!(Base62Encode(62) == "10")) throw new Exception();
}
}
| if (!(Base62Encode(1) == "1")) throw new Exception("1");
if (!(Base62Encode(10) == "A")) throw new Exception("10");
if (!(Base62Encode(36) == "a")) throw new Exception("36");
if (!(Base62Encode(3844) == "100")) throw new Exception("3844");
if (!(Base62Encode(123) == "1z")) throw ... | low_context |
34 | devbench-low-context | c_sharp | using System;
using System.Text;
class Program
{
static string T91 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,-./:;<=>?@[]^_`{|}~";
static string Base91EncodeSimple(byte[] data)
{
| var sb = new StringBuilder();
foreach (byte b in data)
{
sb.Append(T91[b / 91]);
sb.Append(T91[b % 91]);
}
return sb.ToString();
| }
static void Main()
{
byte[] d = new byte[] { 0 };
string r = Base91EncodeSimple(d);
if (!(r == "AA")) throw new Exception();
byte[] d2 = new byte[] { 91 };
string r2 = Base91EncodeSimple(d2);
if (!(r2[0] == T91[1])) throw new Exception();
if (!(r2[1]... | byte[] d3 = new byte[] { 255 };
string r3 = Base91EncodeSimple(d3);
if (!(r3[0] == T91[255 / 91])) throw new Exception("255 hi");
if (!(r3[1] == T91[255 % 91])) throw new Exception("255 lo");
byte[] d4 = new byte[] { 45, 90 };
string r4 = Base91EncodeSimple(d4);
i... | low_context |
35 | devbench-low-context | c_sharp | using System;
class Program
{
// Span<T> is stack-only: cannot be boxed, stored in fields of classes, or used across await
static string DescribeSpanRestriction()
{
| return "Span<T> is a ref struct allocated only on the stack, so it "
+ "cannot be boxed, stored as a field of a class, or captured "
+ "across an await boundary.";
| }
static void Main()
{
string d = DescribeSpanRestriction();
if (!(d.Contains("stack"))) throw new Exception();
if (!(d.Contains("boxed"))) throw new Exception();
if (!(d.Contains("await"))) throw new Exception();
}
}
| string d2 = DescribeSpanRestriction();
if (!(d2.Contains("ref struct"))) throw new Exception("ref struct");
if (!(d2.Contains("field"))) throw new Exception("field");
if (!(d2.Contains("class"))) throw new Exception("class");
| low_context |
36 | devbench-low-context | c_sharp | using System;
class Program
{
// ConfigureAwait(false): do NOT capture SynchronizationContext; continuation runs on thread-pool thread
static string DescribeConfigureAwait()
{
| return "ConfigureAwait(false) tells the awaiter not to capture the "
+ "current SynchronizationContext, so the continuation runs on "
+ "an arbitrary thread-pool thread instead of the original context.";
| }
static void Main()
{
string d = DescribeConfigureAwait();
if (!(d.Contains("SynchronizationContext"))) throw new Exception();
if (!(d.Contains("thread-pool") || d.Contains("thread pool") || d.Contains("threadpool"))) throw new Exception();
}
}
| string d2 = DescribeConfigureAwait();
if (!(d2.Contains("capture"))) throw new Exception("capture");
if (!(d2.Contains("continuation"))) throw new Exception("continuation");
if (!(d2.Contains("original context") || d2.Contains("original synchronization"))) throw new Exception("original")... | low_context |
37 | devbench-low-context | c_sharp | using System;
class Program
{
// volatile in C#: acquire fence on read, release fence on write; NOT atomic for long/double
static string DescribeVolatile()
{
| return "The volatile modifier inserts an acquire fence on every read "
+ "and a release fence on every write, preventing reordering, but "
+ "it does not guarantee atomicity for types wider than IntPtr such as long or double.";
| }
static void Main()
{
string d = DescribeVolatile();
if (!(d.Contains("acquire"))) throw new Exception();
if (!(d.Contains("release"))) throw new Exception();
if (!(d.Contains("atomicity") || d.Contains("atomic"))) throw new Exception();
}
}
| string d2 = DescribeVolatile();
if (!(d2.Contains("fence"))) throw new Exception("fence");
if (!(d2.Contains("reordering") || d2.Contains("reorder"))) throw new Exception("reorder");
if (!(d2.Contains("long") || d2.Contains("double") || d2.Contains("wider"))) throw new Exception("long/do... | low_context |
38 | devbench-low-context | c_sharp | using System;
class Program
{
// stackalloc: allocates from the stack frame, no GC, freed on method return; can init Span<T>
static string DescribeStackalloc()
{
| return "stackalloc allocates a block of memory on the current stack "
+ "frame that is not tracked by the GC and is automatically freed "
+ "when the method returns; the result can initialize a Span<T>.";
| }
static void Main()
{
string d = DescribeStackalloc();
if (!(d.Contains("stack"))) throw new Exception();
if (!(d.Contains("GC"))) throw new Exception();
if (!(d.Contains("Span"))) throw new Exception();
}
}
| string d2 = DescribeStackalloc();
if (!(d2.Contains("freed") || d2.Contains("free"))) throw new Exception("freed");
if (!(d2.Contains("method returns") || d2.Contains("returns"))) throw new Exception("returns");
if (!(d2.Contains("frame"))) throw new Exception("frame");
| low_context |
39 | devbench-low-context | c_sharp | using System;
class Program
{
// IAsyncDisposable: DisposeAsync returns ValueTask, used with 'await using'
static string DescribeIAsyncDisposable()
{
| return "IAsyncDisposable defines a single DisposeAsync method returning "
+ "ValueTask, enabling non-blocking cleanup of unmanaged resources "
+ "via the await using statement.";
| }
static void Main()
{
string d = DescribeIAsyncDisposable();
if (!(d.Contains("DisposeAsync"))) throw new Exception();
if (!(d.Contains("ValueTask"))) throw new Exception();
if (!(d.Contains("await using"))) throw new Exception();
}
}
| string d2 = DescribeIAsyncDisposable();
if (!(d2.Contains("unmanaged") || d2.Contains("cleanup") || d2.Contains("resources"))) throw new Exception("resources");
if (!(d2.Contains("non-blocking") || d2.Contains("async"))) throw new Exception("async");
| low_context |
40 | devbench-low-context | c_sharp | using System;
class Program
{
// 'in' parameter: passed by readonly reference; compiler may create defensive copy for struct methods
static string DescribeInParameter()
{
| return "The in modifier passes an argument by readonly reference, "
+ "preventing modification inside the callee, but the compiler may "
+ "create a defensive copy when calling instance methods on an in struct.";
| }
static void Main()
{
string d = DescribeInParameter();
if (!(d.Contains("readonly reference") || d.Contains("readonly ref"))) throw new Exception();
if (!(d.Contains("defensive copy"))) throw new Exception();
}
}
| string d2 = DescribeInParameter();
if (!(d2.Contains("struct"))) throw new Exception("struct");
if (!(d2.Contains("modification") || d2.Contains("modify"))) throw new Exception("modification");
if (!(d2.Contains("callee") || d2.Contains("method") || d2.Contains("instance"))) throw new Ex... | low_context |
41 | devbench-low-context | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> OddsOnly(IEnumerable<int> src)
{
| foreach (var x in src)
{
if (x % 2 != 0) yield return x;
}
| }
static void Main()
{
var r = OddsOnly(new[] { 1, 2, 3, 4, 5 }).ToList();
if (!(r.Count == 3)) throw new Exception();
if (!(r[0] == 1 && r[1] == 3 && r[2] == 5)) throw new Exception();
}
}
| var r2 = OddsOnly(new int[0]).ToList();
if (!(r2.Count == 0)) throw new Exception("empty");
var r3 = OddsOnly(new[] { 2, 4, 6 }).ToList();
if (!(r3.Count == 0)) throw new Exception("no odds");
var r4 = OddsOnly(new[] { -3, -2, -1 }).ToList();
if (!(r4.Count == 2 && r4[0] ... | low_context |
42 | devbench-low-context | c_sharp | using System;
using System.Linq;
class Program
{
static string JoinReversed(string[] words)
{
| return words.Aggregate("", (acc, w) =>
acc.Length == 0 ? new string(w.Reverse().ToArray())
: acc + "-" + new string(w.Reverse().ToArray()));
| }
static void Main()
{
if (!(JoinReversed(new[] { "abc", "de" }) == "cba-ed")) throw new Exception();
if (!(JoinReversed(new[] { "x" }) == "x")) throw new Exception();
}
}
| if (!(JoinReversed(new[] { "hello" }) == "olleh")) throw new Exception("single");
if (!(JoinReversed(new[] { "ab", "cd", "ef" }) == "ba-dc-fe")) throw new Exception("three");
if (!(JoinReversed(new[] { "a" }) == "a")) throw new Exception("single char");
| low_context |
43 | devbench-low-context | c_sharp | using System;
class Program
{
static string Classify(object obj)
{
return obj switch
{
| int n when n < 0 => "negative",
int n when n == 0 => "zero",
int n => "positive",
string s when s.Length == 0 => "empty",
string s => "text:" + s.Length,
null => "null",
_ => "other",
| };
}
static void Main()
{
if (!(Classify(-5) == "negative")) throw new Exception();
if (!(Classify(0) == "zero")) throw new Exception();
if (!(Classify(7) == "positive")) throw new Exception();
if (!(Classify("") == "empty")) throw new Exception();
if (!(Class... | if (!(Classify(-1) == "negative")) throw new Exception("neg1");
if (!(Classify(100) == "positive")) throw new Exception("pos");
if (!(Classify("abc") == "text:3")) throw new Exception("text3");
if (!(Classify(3.14) == "other")) throw new Exception("double");
if (!(Classify("") ==... | low_context |
44 | devbench-low-context | c_sharp | using System;
class Program
{
static int SafeValue(int? val, int fallback)
{
| return val.GetValueOrDefault(fallback);
| }
static void Main()
{
if (!(SafeValue(5, 10) == 5)) throw new Exception();
if (!(SafeValue(null, 42) == 42)) throw new Exception();
if (!(SafeValue(0, 99) == 0)) throw new Exception();
}
}
| if (!(SafeValue(null, -1) == -1)) throw new Exception("neg fallback");
if (!(SafeValue(null, 0) == 0)) throw new Exception("zero fallback");
if (!(SafeValue(int.MaxValue, 0) == int.MaxValue)) throw new Exception("max");
| low_context |
45 | devbench-low-context | c_sharp | using System;
record Point(int X, int Y);
class Program
{
static Point MirrorX(Point p)
{
| return p with { X = -p.X };
| }
static void Main()
{
var p = new Point(3, 4);
var m = MirrorX(p);
if (!(m.X == -3 && m.Y == 4)) throw new Exception();
if (!(MirrorX(new Point(0, 0)).X == 0)) throw new Exception();
if (!(MirrorX(new Point(-7, 2)).X == 7)) throw new Exception();
}
}
| var p2 = new Point(1, 1);
var m2 = MirrorX(p2);
if (!(m2 != p2)) throw new Exception("not equal");
if (!(m2.Y == p2.Y)) throw new Exception("Y preserved");
if (!(MirrorX(MirrorX(p2)) == p2)) throw new Exception("double mirror");
| low_context |
46 | devbench-low-context | c_sharp | using System;
using System.Threading.Tasks;
class Program
{
static async Task<int> DoubleAsync(int x)
{
| await Task.Yield();
return x * 2;
| }
static async Task Main()
{
int r = await DoubleAsync(5);
if (!(r == 10)) throw new Exception();
if (!(await DoubleAsync(0) == 0)) throw new Exception();
if (!(await DoubleAsync(-3) == -6)) throw new Exception();
}
}
| if (!(await DoubleAsync(100) == 200)) throw new Exception("large");
if (!(await DoubleAsync(1) == 2)) throw new Exception("one");
| low_context |
47 | devbench-low-context | c_sharp | using System;
class Program
{
static T? MaxOrNull<T>(T a, T b, bool useFirst) where T : struct, IComparable<T>
{
| if (!useFirst) return null;
return a.CompareTo(b) >= 0 ? a : b;
| }
static void Main()
{
var r1 = MaxOrNull(3, 7, true);
if (!(r1.HasValue && r1.Value == 7)) throw new Exception();
var r2 = MaxOrNull(3, 7, false);
if (!(r2 == null)) throw new Exception();
var r3 = MaxOrNull(10, 2, true);
if (!(r3.Value == 10)) throw new Exce... | var r4 = MaxOrNull(5, 5, true);
if (!(r4.HasValue && r4.Value == 5)) throw new Exception("equal");
var r5 = MaxOrNull(-1, -2, true);
if (!(r5.Value == -1)) throw new Exception("neg");
var r6 = MaxOrNull(1.5, 2.5, false);
if (!(r6 == null)) throw new Exception("double null... | low_context |
48 | devbench-low-context | c_sharp | using System;
class Program
{
static int SumMiddle(int[] arr)
{
| Span<int> span = arr.AsSpan(1, arr.Length - 2);
int sum = 0;
foreach (var x in span) sum += x;
return sum;
| }
static void Main()
{
if (!(SumMiddle(new[] { 1, 2, 3, 4, 5 }) == 9)) throw new Exception();
if (!(SumMiddle(new[] { 10, 20, 30 }) == 20)) throw new Exception();
if (!(SumMiddle(new[] { 5, 5 }) == 0)) throw new Exception();
}
}
| if (!(SumMiddle(new[] { 1, 100, 1 }) == 100)) throw new Exception("single middle");
if (!(SumMiddle(new[] { 0, 0 }) == 0)) throw new Exception("zeros");
if (!(SumMiddle(new[] { -1, 10, 20, -1 }) == 30)) throw new Exception("neg ends");
| low_context |
49 | devbench-low-context | c_sharp | using System;
class Program
{
static (int min, int max, int sum) Stats(int[] nums)
{
| int mn = nums[0], mx = nums[0], s = 0;
foreach (var n in nums) { if (n < mn) mn = n; if (n > mx) mx = n; s += n; }
return (mn, mx, s);
| }
static void Main()
{
var (mn, mx, s) = Stats(new[] { 3, 1, 4, 1, 5 });
if (!(mn == 1 && mx == 5 && s == 14)) throw new Exception();
var r = Stats(new[] { 7 });
if (!(r.min == 7 && r.max == 7 && r.sum == 7)) throw new Exception();
}
}
| var r2 = Stats(new[] { -5, -1, -3 });
if (!(r2.min == -5 && r2.max == -1 && r2.sum == -9)) throw new Exception("neg");
var r3 = Stats(new[] { 0, 0, 0 });
if (!(r3.min == 0 && r3.max == 0 && r3.sum == 0)) throw new Exception("zeros");
| low_context |
50 | devbench-low-context | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<int> FlattenAndDouble(int[][] jagged)
{
| return jagged.SelectMany(a => a).Select(x => x * 2).ToList();
| }
static void Main()
{
var r = FlattenAndDouble(new[] { new[] { 1, 2 }, new[] { 3 } });
if (!(r.Count == 3 && r[0] == 2 && r[1] == 4 && r[2] == 6)) throw new Exception();
if (!(FlattenAndDouble(new int[0][]).Count == 0)) throw new Exception();
}
}
| var r2 = FlattenAndDouble(new[] { new[] { 5 } });
if (!(r2.Count == 1 && r2[0] == 10)) throw new Exception("single");
var r3 = FlattenAndDouble(new[] { new[] { 0, -1 }, new[] { 2, 3 } });
if (!(r3.Count == 4 && r3[0] == 0 && r3[1] == -2 && r3[2] == 4 && r3[3] == 6)) throw new Exception("... | low_context |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.