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-api-usage | c_sharp | using System;
using System.Collections.Concurrent;
class Program
{
static int ComputeCount = 0;
static int ComputeValue(string key)
{
ComputeCount++;
return key.Length * 10;
}
static int GetOrCompute(ConcurrentDictionary<string, int> dict, string key)
{
return dict.Get... | static string DescribeGetOrCompute()
{
return "Uses ConcurrentDictionary.GetOrAdd(TKey, Func<TKey,TValue>) which "
+ "atomically returns the existing value if the key is present, or "
+ "invokes the valueFactory delegate to create and add a new value. "
+ "The valu... |
static void Main()
{
var dict = new ConcurrentDictionary<string, int>();
ComputeCount = 0;
int v1 = GetOrCompute(dict, "hello");
if (v1 != 50) throw new Exception("Expected 50");
if (ComputeCount != 1) throw new Exception("Factory should be called once");
int v... | string d1 = DescribeGetOrCompute().ToLower();
if (!d1.Contains("getoradd")) throw new Exception("Must mention GetOrAdd");
if (!d1.Contains("valuefactory") && !d1.Contains("factory") && !d1.Contains("delegate")) throw new Exception("Must mention factory/delegate");
if (!d1.Contains("atomically") && !d1.Contains("atomic"... | api_usage |
2 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static SortedSet<int> GetRange(SortedSet<int> set, int lo, int hi)
{
return set.GetViewBetween(lo, hi);
}
| static string DescribeGetRange()
{
return "Uses SortedSet.GetViewBetween(lowerValue, upperValue) which returns "
+ "a live view (not a copy) of elements in [lowerValue, upperValue] — both "
+ "bounds are inclusive. The returned SortedSet is backed by the original: "
... |
static void Main()
{
var set = new SortedSet<int> { 1, 3, 5, 7, 9, 11 };
var view = GetRange(set, 3, 9);
if (view.Count != 4) throw new Exception($"Expected 4, got {view.Count}");
if (!view.Contains(3) || !view.Contains(9)) throw new Exception("Bounds inclusive");
view.... | string d2 = DescribeGetRange().ToLower();
if (!d2.Contains("getviewbetween")) throw new Exception("Must mention GetViewBetween");
if (!(d2.Contains("live view") || d2.Contains("backed by") || d2.Contains("not a copy"))) throw new Exception("Must mention live view");
if (!d2.Contains("inclusive")) throw new Exception("M... | api_usage |
3 | devbench-api-usage | c_sharp | using System;
using System.Text;
class Program
{
static byte[] EncodeWithPreamble(string text)
{
Encoding utf8Bom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);
byte[] preamble = utf8Bom.GetPreamble();
byte[] encoded = utf8Bom.GetBytes(text);
byte[] result = new byte... | static string DescribeEncodingBehavior()
{
return "Encoding.UTF8 is a UTF8Encoding instance with encoderShouldEmitUTF8Identifier "
+ "set to false — GetPreamble() returns an empty array, and GetBytes() produces "
+ "no BOM prefix (EF BB BF). Constructing new UTF8Encoding(true) ... |
static void Main()
{
byte[] withBom = EncodeWithPreamble("Hi");
byte[] noBom = EncodeNoPreamble("Hi");
if (withBom.Length != noBom.Length + 3) throw new Exception("BOM is 3 bytes");
if (withBom[0] != 0xEF || withBom[1] != 0xBB || withBom[2] != 0xBF)
throw new Excepti... | string d3 = DescribeEncodingBehavior().ToLower();
if (!(d3.Contains("ef bb bf") || d3.Contains("0xef") || d3.Contains("ef, bb, bf") || d3.Contains("0xef, 0xbb, 0xbf"))) throw new Exception("Must mention BOM bytes EF BB BF");
if (!(d3.Contains("getpreamble"))) throw new Exception("Must mention GetPreamble");
if (!(d3.Co... | api_usage |
4 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static string ProcessQueue(PriorityQueue<string, int> pq)
{
var results = new List<string>();
while (pq.TryDequeue(out string? item, out int priority))
{
results.Add($"{item}:{priority}");
}
retu... | static string DescribeProcessQueue()
{
return "Uses PriorityQueue<TElement,TPriority>.TryDequeue which removes and returns "
+ "the element with the lowest priority value (min-heap). Returns false when the "
+ "queue is empty instead of throwing. Unlike Enqueue/Dequeue, TryDequ... |
static void Main()
{
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 3);
pq.Enqueue("high", 1);
pq.Enqueue("mid", 2);
string result = ProcessQueue(pq);
if (!result.StartsWith("high:1")) throw new Exception($"Min-heap expected, got {result}");
... | string d4 = DescribeProcessQueue().ToLower();
if (!d4.Contains("trydequeue")) throw new Exception("Must mention TryDequeue");
if (!(d4.Contains("min-heap") || d4.Contains("lowest priority"))) throw new Exception("Must mention min-heap behavior");
if (!(d4.Contains("not stable") || d4.Contains("any order"))) throw new E... | api_usage |
5 | devbench-api-usage | c_sharp | using System;
using System.Text.RegularExpressions;
class Program
{
static (string year, string month, string day) ParseDate(string input)
{
var match = Regex.Match(input, @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})");
if (!match.Success)
throw new FormatException("Invalid date f... | static string DescribeParseDate()
{
return "Uses Regex.Match(string, string) which returns a single Match object "
+ "(never null — check Match.Success). Named capture groups (?<name>...) "
+ "are accessed via Match.Groups[string] returning a Group object whose "
+... |
static void Main()
{
var (y, m, d) = ParseDate("2024-03-15");
if (y != "2024" || m != "03" || d != "15")
throw new Exception("Parsing failed");
bool threw = false;
try { ParseDate("not-a-date"); }
catch (FormatException) { threw = true; }
if (!threw)... | string d5 = DescribeParseDate().ToLower();
if (!d5.Contains("regex.match")) throw new Exception("Must mention Regex.Match");
if (!(d5.Contains("named") && (d5.Contains("capture") || d5.Contains("group")))) throw new Exception("Must mention named capture groups");
if (!(d5.Contains("never null") || d5.Contains("match.su... | api_usage |
6 | devbench-api-usage | c_sharp | using System;
using System.Linq;
class Program
{
static string BuildPath(string[] segments)
{
return segments.Aggregate("root",
(current, next) => current + "/" + next,
result => result.ToUpper());
}
| static string DescribeBuildPath()
{
return "Uses Enumerable.Aggregate<TSource,TAccumulate,TResult>(seed, func, resultSelector) "
+ "— the three-parameter overload. The seed ('root') is the initial accumulator value "
+ "and its type (TAccumulate) can differ from TSource. The fu... |
static void Main()
{
string result = BuildPath(new[] { "usr", "local", "bin" });
if (result != "ROOT/USR/LOCAL/BIN") throw new Exception($"Expected ROOT/USR/LOCAL/BIN, got {result}");
string empty = BuildPath(new string[0]);
if (empty != "ROOT") throw new Exception($"Empty shou... | string d6 = DescribeBuildPath().ToLower();
if (!d6.Contains("aggregate")) throw new Exception("Must mention Aggregate");
if (!(d6.Contains("seed") || d6.Contains("initial accumulator"))) throw new Exception("Must mention seed");
if (!(d6.Contains("resultselector") || d6.Contains("result selector") || d6.Contains("proje... | api_usage |
7 | devbench-api-usage | c_sharp | using System;
using System.Text;
class Program
{
static string JoinValues(string separator, params string[] values)
{
var sb = new StringBuilder(256);
sb.AppendJoin(separator, values);
return sb.ToString();
}
| static string DescribeJoinValues()
{
return "Uses StringBuilder(int capacity) constructor to pre-allocate a 256-char "
+ "internal buffer, avoiding reallocations for small inputs. AppendJoin(string, "
+ "params object[]) appends each element separated by the separator in a sing... |
static void Main()
{
string result = JoinValues(", ", "a", "b", "c");
if (result != "a, b, c") throw new Exception($"Expected 'a, b, c', got '{result}'");
string single = JoinValues("-", "only");
if (single != "only") throw new Exception($"Expected 'only', got '{single}'");
... | string d7 = DescribeJoinValues().ToLower();
if (!d7.Contains("appendjoin")) throw new Exception("Must mention AppendJoin");
if (!(d7.Contains("capacity") || d7.Contains("pre-allocat") || d7.Contains("preallocat"))) throw new Exception("Must mention capacity/pre-allocation");
if (!(d7.Contains("in-place") || d7.Contains... | api_usage |
8 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
static (string name, int age) ParsePerson(string json)
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
string name = root.GetProperty("name").GetString() ?? "... | static string DescribeParsePerson()
{
return "Uses JsonDocument.Parse(string) which parses JSON into a read-only DOM "
+ "backed by pooled memory from ArrayPool<byte>. JsonDocument implements "
+ "IDisposable — the using statement ensures pooled buffers are returned. "
... |
static void Main()
{
var (name, age) = ParsePerson("{\"name\": \"Alice\", \"age\": 30}");
if (name != "Alice" || age != 30) throw new Exception("Parse failed");
bool threw = false;
try { ParsePerson("{\"name\": \"Bob\"}"); }
catch (KeyNotFoundException) { threw = true; ... | string d8 = DescribeParsePerson().ToLower();
if (!d8.Contains("jsondocument")) throw new Exception("Must mention JsonDocument");
if (!(d8.Contains("idisposable") || d8.Contains("disposable") || d8.Contains("using"))) throw new Exception("Must mention IDisposable");
if (!(d8.Contains("arraypool") || d8.Contains("pooled"... | api_usage |
9 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static bool SafeInsert(Dictionary<string, int> dict, string key, int value)
{
return dict.TryAdd(key, value);
}
static void ForceInsert(Dictionary<string, int> dict, string key, int value)
{
dict.Add(key, value);
}... | static string DescribeSafeInsert()
{
return "Uses Dictionary.TryAdd(TKey, TValue) which returns false without throwing "
+ "if the key already exists — unlike Add which throws ArgumentException for "
+ "duplicate keys. TryAdd is O(1) amortized for hash table insertion. "
... |
static void Main()
{
var dict = new Dictionary<string, int>();
bool added1 = SafeInsert(dict, "x", 10);
if (!added1) throw new Exception("First insert should succeed");
bool added2 = SafeInsert(dict, "x", 20);
if (added2) throw new Exception("Duplicate insert should re... | string d9 = DescribeSafeInsert().ToLower();
if (!d9.Contains("tryadd")) throw new Exception("Must mention TryAdd");
if (!d9.Contains("argumentexception")) throw new Exception("Must mention ArgumentException for duplicate keys");
if (!(d9.Contains("false") && (d9.Contains("without throwing") || d9.Contains("does not thr... | api_usage |
10 | devbench-api-usage | c_sharp | using System;
using System.Threading.Tasks;
using System.Collections.Generic;
class Program
{
static async Task<int[]> RunAll(params Func<Task<int>>[] factories)
{
var tasks = new List<Task<int>>();
foreach (var f in factories)
tasks.Add(f());
return await Task.WhenAll(tasks... | static string DescribeRunAll()
{
return "Uses Task.WhenAll(IEnumerable<Task<TResult>>) which returns a single Task<TResult[]> "
+ "that completes when ALL input tasks complete. The result array preserves the "
+ "original task order (not completion order). If any task faults, W... |
static async Task Main()
{
int[] results = await RunAll(
async () => { await Task.Delay(10); return 1; },
async () => { await Task.Delay(5); return 2; },
async () => { return 3; }
);
if (results.Length != 3) throw new Exception("Expected 3 results");... | string d10 = DescribeRunAll().ToLower();
if (!d10.Contains("whenall")) throw new Exception("Must mention WhenAll");
if (!(d10.Contains("order") && (d10.Contains("preserv") || d10.Contains("original")))) throw new Exception("Must mention order preservation");
if (!d10.Contains("aggregateexception")) throw new Exception(... | api_usage |
11 | devbench-api-usage | c_sharp | using System;
using System.Buffers;
namespace ApiTask11
{
public class Program
{
public static int SumWithRentedBuffer(int[] source)
{
int[] buffer = ArrayPool<int>.Shared.Rent(source.Length);
try
{
Array.Copy(source, buffer, source.Length);
... | public static string DescribeSumWithRentedBuffer()
{
return "Rents a buffer from ArrayPool<int>.Shared.Rent(minimumLength) which may "
+ "return an array LARGER than requested (power-of-two sizing). Copies source "
+ "via Array.Copy then sums only source.Len... |
public static void Main(string[] args)
{
int result = SumWithRentedBuffer(new int[] { 1, 2, 3, 4, 5 });
if (result != 15) throw new Exception("Sum failed");
string desc = DescribeSumWithRentedBuffer();
if (string.IsNullOrEmpty(desc)) throw new Exception(... | string d11 = ApiTask11.Program.DescribeSumWithRentedBuffer().ToLower();
if (!d11.Contains("larger than requested") && !d11.Contains("bigger than") && !d11.Contains("may return a larger") && !d11.Contains("power-of-two") && !d11.Contains("power of two")) throw new Exception("Must mention buffer may be larger than reques... | api_usage |
12 | devbench-api-usage | c_sharp | using System;
namespace ApiTask12
{
public class Program
{
public static int SumMiddleThird(ReadOnlySpan<int> data)
{
int start = data.Length / 3;
int end = 2 * data.Length / 3;
ReadOnlySpan<int> slice = data.Slice(start, end - start);
int sum = 0... | public static string DescribeSumMiddleThird()
{
return "Uses ReadOnlySpan<int> which is a stack-only ref struct that cannot "
+ "be boxed, stored on the heap, or used in async methods. Slice(start, length) "
+ "creates a new ReadOnlySpan over the same underl... |
public static void Main(string[] args)
{
int[] data = { 10, 20, 30, 40, 50, 60 };
int result = SumMiddleThird(data);
if (result != 70) throw new Exception($"Expected 70, got {result}");
string desc = DescribeSumMiddleThird();
if (string.IsNul... | string d12 = ApiTask12.Program.DescribeSumMiddleThird().ToLower();
if (!d12.Contains("ref struct")) throw new Exception("Must mention ref struct");
if (!d12.Contains("stack") || (!d12.Contains("heap") && !d12.Contains("boxed"))) throw new Exception("Must mention stack-only / cannot be on heap");
if (!d12.Contains("zero... | api_usage |
13 | devbench-api-usage | c_sharp | using System;
using System.Numerics;
namespace ApiTask13
{
public class Program
{
public static BigInteger Factorial(int n)
{
BigInteger result = BigInteger.One;
for (int i = 2; i <= n; i++)
result = BigInteger.Multiply(result, new BigInteger(i));
... | public static string DescribeFactorial()
{
return "Uses System.Numerics.BigInteger which is an immutable, arbitrary-precision "
+ "signed integer — no overflow is possible. BigInteger.One is a static readonly "
+ "field (not a property) representing the valu... |
public static void Main(string[] args)
{
BigInteger f10 = Factorial(10);
if (f10 != 3628800) throw new Exception("10! wrong");
BigInteger f20 = Factorial(20);
if (f20 != BigInteger.Parse("2432902008176640000")) throw new Exception("20! wrong");
... | string d13 = ApiTask13.Program.DescribeFactorial().ToLower();
if (!d13.Contains("immutable")) throw new Exception("Must mention immutable");
if (!d13.Contains("arbitrary-precision") && !d13.Contains("arbitrary precision") && !d13.Contains("unlimited precision")) throw new Exception("Must mention arbitrary-precision");
... | api_usage |
14 | devbench-api-usage | c_sharp | using System;
using System.Net;
using System.Net.Sockets;
namespace ApiTask14
{
public class Program
{
public static string ClassifyAddress(string input)
{
if (!IPAddress.TryParse(input, out IPAddress addr))
return "INVALID";
if (addr.AddressFamily == Add... | public static string DescribeClassifyAddress()
{
return "Uses IPAddress.TryParse which returns bool and sets the out parameter "
+ "to null on failure (not IPAddress.None). AddressFamily is an enum with "
+ "InterNetwork for IPv4 and InterNetworkV6 for IPv6 ... |
public static void Main(string[] args)
{
if (ClassifyAddress("10.0.0.1") != "PRIVATE_A") throw new Exception("10.x fail");
if (ClassifyAddress("127.0.0.1") != "LOOPBACK") throw new Exception("Loopback fail");
if (ClassifyAddress("::1") != "IPv6") throw new Exception(... | string d14 = ApiTask14.Program.DescribeClassifyAddress().ToLower();
if (!d14.Contains("tryparse") || !d14.Contains("bool")) throw new Exception("Must mention TryParse returns bool");
if (!d14.Contains("null") && !d14.Contains("out parameter")) throw new Exception("Must mention out param is null on failure");
if (!d14.C... | api_usage |
15 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
namespace ApiTask15
{
public class Program
{
public static (int symDiffCount, int interCount, bool isProperSubset)
AnalyzeSets(int[] a, int[] b)
{
var setA = new HashSet<int>(a);
var setB = new HashSet<int>(b);
... | public static string DescribeAnalyzeSets()
{
return "Uses HashSet<int> set-theoretic methods. SymmetricExceptWith MUTATES the "
+ "set in-place to contain only elements in one set or the other, not both — "
+ "it does NOT return a new HashSet. IntersectWith ... |
public static void Main(string[] args)
{
var (sd, ic, ps) = AnalyzeSets(new[] {1,2,3}, new[] {2,3,4});
if (sd != 2) throw new Exception($"SymDiff count: expected 2, got {sd}");
if (ic != 2) throw new Exception($"Intersect count: expected 2, got {ic}");
if... | string d15 = ApiTask15.Program.DescribeAnalyzeSets().ToLower();
if (!d15.Contains("mutate") && !d15.Contains("in-place") && !d15.Contains("in place") && !d15.Contains("modifies")) throw new Exception("Must mention in-place mutation");
if (!d15.Contains("symmetricexceptwith") && !d15.Contains("symmetric except")) throw ... | api_usage |
16 | devbench-api-usage | c_sharp | using System;
using System.IO;
namespace ApiTask16
{
public class Program
{
public static string GetConfigPath(string appName)
{
string envOverride = Environment.GetEnvironmentVariable("CONFIG_DIR");
if (envOverride != null)
return Path.Combine(envOverrid... | public static string DescribeGetConfigPath()
{
return "Uses Environment.GetEnvironmentVariable which returns null (not empty "
+ "string) when the variable does not exist — this differs from "
+ "GetEnvironmentVariable(name, EnvironmentVariableTarget) overlo... |
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("CONFIG_DIR", "/tmp/cfg");
string result = GetConfigPath("myapp");
string expected = Path.Combine("/tmp/cfg", "myapp");
if (result != expected) throw new Exception($"Expected {exp... | string d16 = ApiTask16.Program.DescribeGetConfigPath().ToLower();
if (!d16.Contains("null") || d16.Contains("empty string") && !d16.Contains("returns null")) throw new Exception("Must mention GetEnvironmentVariable returns null when not found");
if (!d16.Contains("environmentvariabletarget") && !d16.Contains("machine")... | api_usage |
17 | devbench-api-usage | c_sharp | using System;
using System.IO;
using System.Text;
namespace ApiTask17
{
public class Program
{
public static byte[] PackRecord(int id, string name, double score)
{
using var ms = new MemoryStream();
using (var bw = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
... | public static string DescribePackRecord()
{
return "Uses BinaryWriter.Write(int) which writes 4 bytes in little-endian order. "
+ "BinaryWriter.Write(string) writes a length-prefixed UTF-8 string: the "
+ "length is encoded as a 7-bit variable-length integer... |
public static void Main(string[] args)
{
byte[] packed = PackRecord(42, "Alice", 95.5);
var (id, name, score) = UnpackRecord(packed);
if (id != 42) throw new Exception("id mismatch");
if (name != "Alice") throw new Exception("name mismatch");
... | string d17 = ApiTask17.Program.DescribePackRecord().ToLower();
if (!d17.Contains("little-endian") && !d17.Contains("little endian")) throw new Exception("Must mention little-endian byte order");
if (!d17.Contains("length-prefix") && !d17.Contains("length prefix") && !d17.Contains("leb128") && !d17.Contains("7-bit")) th... | api_usage |
18 | devbench-api-usage | c_sharp | using System;
using System.Diagnostics;
using System.Threading;
namespace ApiTask18
{
public class Program
{
public static double MeasureElapsedMs(Action action)
{
long start = Stopwatch.GetTimestamp();
action();
long end = Stopwatch.GetTimestamp();
... | public static string DescribeMeasureElapsedMs()
{
return "Uses Stopwatch.GetTimestamp() which is a static method returning the "
+ "current value of the high-resolution performance counter as a long. "
+ "Stopwatch.Frequency is a static readonly field giving... |
public static void Main(string[] args)
{
double elapsed = MeasureElapsedMs(() => Thread.Sleep(50));
if (elapsed < 30 || elapsed > 500) throw new Exception($"Elapsed {elapsed}ms out of range");
string desc = DescribeMeasureElapsedMs();
if (string.IsNullOr... | string d18 = ApiTask18.Program.DescribeMeasureElapsedMs().ToLower();
if (!d18.Contains("gettimestamp") && !d18.Contains("get timestamp")) throw new Exception("Must mention GetTimestamp");
if (!d18.Contains("frequency")) throw new Exception("Must mention Frequency field");
if (!d18.Contains("platform-dependent") && !d18... | api_usage |
19 | devbench-api-usage | c_sharp | using System;
namespace ApiTask19
{
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
All = Read | Write | Execute
}
public class Program
{
public static string CheckPermissions(string input)
{
if (... | public static string DescribeCheckPermissions()
{
return "Uses Enum.TryParse<T>(string, bool ignoreCase, out T result) which "
+ "returns true even for integer strings ('3') and undefined combinations — "
+ "TryParse succeeds for ANY valid integer, not just ... |
public static void Main(string[] args)
{
if (CheckPermissions("Read") != "Read") throw new Exception("Read parse fail");
if (CheckPermissions("read") != "Read") throw new Exception("Case-insensitive fail");
if (CheckPermissions("garbage") != "INVALID") throw new Exce... | string d19 = ApiTask19.Program.DescribeCheckPermissions().ToLower();
if (!d19.Contains("tryparse")) throw new Exception("Must mention TryParse");
if (!d19.Contains("integer string") && !d19.Contains("integer value") && !d19.Contains("any valid integer") && !d19.Contains("numeric")) throw new Exception("Must mention Try... | api_usage |
20 | devbench-api-usage | c_sharp | using System;
using System.Text;
namespace ApiTask20
{
public class Program
{
public static string EncodeToBase64(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
}
... | public static string DescribeBase64Operations()
{
return "Uses Convert.ToBase64String with Base64FormattingOptions.InsertLineBreaks "
+ "which inserts a line break every 76 characters (MIME standard RFC 2045). "
+ "Without the option, no line breaks are inse... |
public static void Main(string[] args)
{
string encoded = EncodeToBase64("Hello, World!");
string decoded = DecodeFromBase64(encoded.Replace("\r\n", ""));
if (decoded != "Hello, World!") throw new Exception("Roundtrip failed");
string simple = Convert.To... | string d20 = ApiTask20.Program.DescribeBase64Operations().ToLower();
if (!d20.Contains("insertlinebreaks") && !d20.Contains("insert line breaks") && !d20.Contains("line break")) throw new Exception("Must mention InsertLineBreaks option");
if (!d20.Contains("76") && !d20.Contains("seventy-six")) throw new Exception("Mus... | api_usage |
21 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
public class AUTask21
{
public static List<string> ExtractDescendants(string xml, string tagName)
{
XDocument doc = XDocument.Parse(xml);
return doc.Descendants(tagName)
.Select(e => e.Va... | public static string DescribeExtractDescendants()
{
return "Parses XML string using XDocument.Parse(string) which returns an XDocument. "
+ "Calls Descendants(XName) to find all elements matching tagName at any depth. "
+ "Descendants performs a depth-first traversal of the ent... |
static void Main()
{
string xml = "<root><a><b>hello</b><b>world</b></a><b>outer</b></root>";
var results = ExtractDescendants(xml, "b");
if (!(results.Count == 3)) throw new Exception("Expected 3 descendants");
if (!(results[0] == "hello")) throw new Exception("First should be ... | string d21 = AUTask21.DescribeExtractDescendants().ToLower();
if (!d21.Contains("xdocument.parse")) throw new Exception("Must mention XDocument.Parse");
if (!d21.Contains("descendants")) throw new Exception("Must mention Descendants method");
if (!d21.Contains("depth-first") && !d21.Contains("any depth")) throw new Exc... | api_usage |
22 | devbench-api-usage | c_sharp | using System;
using System.Reflection;
public class AUTask22
{
public static int Add(int a, int b) => a + b;
public static object InvokeByName(Type type, string methodName, object[] args)
{
MethodInfo mi = type.GetMethod(methodName,
BindingFlags.Public | BindingFlags.Static);
i... | public static string DescribeInvokeByName()
{
return "Retrieves a MethodInfo via Type.GetMethod(string, BindingFlags) with "
+ "BindingFlags.Public | BindingFlags.Static to search only public static methods. "
+ "GetMethod returns null if no matching method exists, so the code ... |
static void Main()
{
object result = InvokeByName(typeof(AUTask22), "Add", new object[] { 3, 4 });
if (!((int)result == 7)) throw new Exception("Expected 7");
}
}
| string d22 = AUTask22.DescribeInvokeByName().ToLower();
if (!d22.Contains("getmethod")) throw new Exception("Must mention GetMethod");
if (!d22.Contains("bindingflags")) throw new Exception("Must mention BindingFlags");
if (!(d22.Contains("public") && d22.Contains("static"))) throw new Exception("Must mention Public an... | api_usage |
23 | devbench-api-usage | c_sharp | using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RateLimitAttribute : Attribute
{
public int MaxCalls { get; }
public int PeriodSeconds { get; }
public RateLimitAttribute(int maxCalls, int periodSeconds)
{
Ma... | public static string DescribeGetRateLimit()
{
return "Uses MethodInfo.GetCustomAttribute<T>(bool) generic method with inherit=false "
+ "to retrieve only directly-applied attributes, not inherited ones. "
+ "The RateLimitAttribute is decorated with AttributeUsage specifying "
... |
static void Main()
{
var method = typeof(AUTask23).GetMethod("ApiEndpoint");
var (maxCalls, period) = GetRateLimit(method);
if (!(maxCalls == 100)) throw new Exception("Expected 100 max calls");
if (!(period == 60)) throw new Exception("Expected 60 second period");
}
}
| string d23 = AUTask23.DescribeGetRateLimit().ToLower();
if (!d23.Contains("getcustomattribute")) throw new Exception("Must mention GetCustomAttribute");
if (!d23.Contains("inherit")) throw new Exception("Must mention inherit parameter");
if (!d23.Contains("false")) throw new Exception("Must mention inherit=false");
if ... | api_usage |
24 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class AUTask24
{
public static ReadOnlyCollection<int> WrapAsReadOnly(List<int> source)
{
return source.AsReadOnly();
}
| public static string DescribeWrapAsReadOnly()
{
return "Calls List<T>.AsReadOnly() which returns a ReadOnlyCollection<T> that is "
+ "a thin wrapper around the original list, not a copy. Mutations to the "
+ "underlying source list are visible through the ReadOnlyCollection bec... |
static void Main()
{
var source = new List<int> { 1, 2, 3 };
var ro = WrapAsReadOnly(source);
if (!(ro.Count == 3)) throw new Exception("Expected count 3");
source.Add(4);
if (!(ro.Count == 4)) throw new Exception("ReadOnly should reflect source mutation");
bool ... | string d24 = AUTask24.DescribeWrapAsReadOnly().ToLower();
if (!d24.Contains("asreadonly")) throw new Exception("Must mention AsReadOnly method");
if (!(d24.Contains("wrapper") || d24.Contains("wraps"))) throw new Exception("Must mention wrapper semantics");
if (!(d24.Contains("not a copy") || d24.Contains("reference"))... | api_usage |
25 | devbench-api-usage | c_sharp | using System;
using System.Threading;
public class AUTask25
{
private static int _initCount = 0;
public static Lazy<string> CreateExpensiveResource()
{
return new Lazy<string>(() =>
{
Interlocked.Increment(ref _initCount);
return "Resource_" + _initCount;
},... | public static string DescribeLazyInit()
{
return "Creates a Lazy<T> with a Func<T> factory and LazyThreadSafetyMode.ExecutionAndPublication. "
+ "ExecutionAndPublication ensures exactly one thread executes the factory; other threads "
+ "block until initialization completes, th... |
static void Main()
{
var lazy = CreateExpensiveResource();
if (!(lazy.IsValueCreated == false)) throw new Exception("Should not be created yet");
string val1 = lazy.Value;
string val2 = lazy.Value;
if (!(val1 == val2)) throw new Exception("Should return same cached value... | string d25 = AUTask25.DescribeLazyInit().ToLower();
if (!d25.Contains("executionandpublication")) throw new Exception("Must mention ExecutionAndPublication mode");
if (!(d25.Contains("exactly one thread") || d25.Contains("single thread"))) throw new Exception("Must mention single-thread execution guarantee");
if (!(d25... | api_usage |
26 | devbench-api-usage | c_sharp | using System;
using System.IO;
using System.IO.Compression;
using System.Text;
public class AUTask26
{
public static byte[] CompressString(string text)
{
byte[] raw = Encoding.UTF8.GetBytes(text);
using (var output = new MemoryStream())
{
using (var gzip = new GZipStream(out... | public static string DescribeCompression()
{
return "CompressString converts text to bytes via Encoding.UTF8.GetBytes, then wraps a "
+ "MemoryStream with GZipStream(Stream, CompressionMode.Compress, leaveOpen: true). "
+ "leaveOpen: true prevents GZipStream.Dispose from closin... |
static void Main()
{
string original = "Hello, GZip compression test!";
byte[] compressed = CompressString(original);
if (!(compressed.Length > 0)) throw new Exception("Compressed should be non-empty");
string decompressed = DecompressToString(compressed);
if (!(decompre... | string d26 = AUTask26.DescribeCompression().ToLower();
if (!d26.Contains("gzipstream")) throw new Exception("Must mention GZipStream");
if (!d26.Contains("compressionmode.compress")) throw new Exception("Must mention CompressionMode.Compress");
if (!d26.Contains("leaveopen")) throw new Exception("Must mention leaveOpen... | api_usage |
27 | devbench-api-usage | c_sharp | using System;
using System.Threading;
public class AUTask27
{
private static int _value = 0;
public static int AtomicMax(ref int location, int comparand)
{
int initial, computed;
do
{
initial = location;
computed = Math.Max(initial, comparand);
}
... | public static string DescribeAtomicMax()
{
return "Implements a lock-free atomic maximum using Interlocked.CompareExchange(ref int, int, int) "
+ "in a CAS (compare-and-swap) spin loop. The loop reads the current value into 'initial', "
+ "computes Math.Max(initial, comparand),... |
static void Main()
{
_value = 5;
int result = AtomicMax(ref _value, 10);
if (!(result == 10)) throw new Exception("Expected max 10");
if (!(_value == 10)) throw new Exception("Location should be 10");
result = AtomicMax(ref _value, 3);
if (!(result == 10)) throw ... | string d27 = AUTask27.DescribeAtomicMax().ToLower();
if (!d27.Contains("compareexchange")) throw new Exception("Must mention CompareExchange");
if (!(d27.Contains("cas") || d27.Contains("compare-and-swap") || d27.Contains("compare and swap"))) throw new Exception("Must mention CAS pattern");
if (!(d27.Contains("spin") ... | api_usage |
28 | devbench-api-usage | c_sharp | using System;
public class AUTask28
{
public static double NextUp(double value)
{
return Math.BitIncrement(value);
}
public static double NextDown(double value)
{
return Math.BitDecrement(value);
}
public static double FusedMulAdd(double x, double y, double z)
{
... | public static string DescribeFloatOps()
{
return "NextUp uses Math.BitIncrement(double) which returns the smallest double value "
+ "that is greater than the argument. It increments the binary representation by "
+ "one ULP (unit in the last place). For positive infinity, it re... |
static void Main()
{
double up = NextUp(1.0);
if (!(up > 1.0)) throw new Exception("BitIncrement should be > 1.0");
if (!(up < 1.0 + 1e-10)) throw new Exception("BitIncrement should be very close to 1.0");
double down = NextDown(1.0);
if (!(down < 1.0)) throw new Excepti... | string d28 = AUTask28.DescribeFloatOps().ToLower();
if (!d28.Contains("bitincrement")) throw new Exception("Must mention BitIncrement");
if (!d28.Contains("bitdecrement")) throw new Exception("Must mention BitDecrement");
if (!(d28.Contains("ulp") || d28.Contains("unit in the last place"))) throw new Exception("Must me... | api_usage |
29 | devbench-api-usage | c_sharp | using System;
public class AUTask29
{
public static WeakReference<object> CreateWeakRef(object target)
{
return new WeakReference<object>(target, trackResurrection: false);
}
public static bool TryGetTarget(WeakReference<object> weakRef, out object target)
{
return weakRef.TryGetTa... | public static string DescribeWeakReference()
{
return "Creates a WeakReference<T> with trackResurrection: false, meaning the reference "
+ "becomes invalid once the target is finalized (short weak reference). "
+ "TryGetTarget(out T) atomically checks if the target is still ali... |
static void Main()
{
var obj = new object();
var wr = CreateWeakRef(obj);
object target;
if (!(TryGetTarget(wr, out target))) throw new Exception("Should find live target");
if (!(ReferenceEquals(target, obj))) throw new Exception("Should be same object");
var ne... | string d29 = AUTask29.DescribeWeakReference().ToLower();
if (!d29.Contains("trackresurrection")) throw new Exception("Must mention trackResurrection parameter");
if (!(d29.Contains("short weak") || d29.Contains("finalized"))) throw new Exception("Must mention short weak reference or finalization semantics");
if (!d29.C... | api_usage |
30 | devbench-api-usage | c_sharp | using System;
using System.Xml.Linq;
using System.Linq;
public class AUTask30
{
private static readonly XNamespace Ns = "http://example.com/data";
public static XDocument BuildDocument(string rootName, (string name, string value)[] items)
{
var root = new XElement(Ns + rootName,
new XA... | public static string DescribeBuildDocument()
{
return "Constructs an XDocument with XDeclaration('1.0', 'utf-8', 'yes') where 'yes' is "
+ "the standalone flag. Creates root XElement using XNamespace + string operator to produce "
+ "a qualified XName in the namespace. Adds XAt... |
static void Main()
{
var items = new (string, string)[] { ("item", "A"), ("item", "B") };
XDocument doc = BuildDocument("root", items);
string decl = GetDeclarationString(doc);
if (!decl.Contains("utf-8")) throw new Exception("Declaration should contain utf-8");
if (!dec... | string d30 = AUTask30.DescribeBuildDocument().ToLower();
if (!d30.Contains("xdeclaration")) throw new Exception("Must mention XDeclaration");
if (!d30.Contains("standalone")) throw new Exception("Must mention standalone flag");
if (!d30.Contains("xnamespace")) throw new Exception("Must mention XNamespace");
if (!(d30.C... | api_usage |
31 | devbench-api-usage | c_sharp | using System;
class Program
{
static Uri ParseAbsoluteUri(string input)
{
Uri result;
bool ok = Uri.TryCreate(input, UriKind.Absolute, out result);
if (!ok) return null;
return result;
}
static string GetIdnHost(Uri uri)
{
return uri.GetComponents(UriCompone... | static string DescribeParseAbsoluteUri()
{
return "Uses Uri.TryCreate(string, UriKind.Absolute, out Uri) which returns false "
+ "for relative URIs or malformed input without throwing UriFormatException. "
+ "UriKind.Absolute requires a scheme (http, ftp, etc.) — schemeless str... |
static void Main()
{
Uri u = ParseAbsoluteUri("http://Example.COM/path?q=1");
if (u == null) throw new Exception("Should parse valid absolute URI");
if (u.Scheme != "http") throw new Exception("Scheme should be http");
if (u.Host != "example.com") throw new Exception("Host shoul... | string d31 = Program.DescribeParseAbsoluteUri().ToLower();
if (!d31.Contains("urikind.absolute") && !d31.Contains("urikind absolute")) throw new Exception("Must mention UriKind.Absolute");
if (!d31.Contains("uriformatexception") && !d31.Contains("without throwing")) throw new Exception("Must mention no exception thrown... | api_usage |
32 | devbench-api-usage | c_sharp | using System;
class Program
{
static int CompareVersions(string a, string b)
{
Version va = Version.Parse(a);
Version vb = Version.Parse(b);
return va.CompareTo(vb);
}
static bool IsPrerelease(string ver)
{
Version v = Version.Parse(ver);
return v.Revision =... | static string DescribeCompareVersions()
{
return "Version.Parse(string) parses 'major.minor[.build[.revision]]' where "
+ "major and minor are required. Unparsed components default to -1 (not 0), "
+ "so '1.0' has Build=-1 and Revision=-1. CompareTo compares component by "
... |
static void Main()
{
if (CompareVersions("2.0", "1.9") <= 0) throw new Exception("2.0 > 1.9");
if (CompareVersions("1.0", "1.0.0") >= 0) throw new Exception("1.0 < 1.0.0 because Build -1 < 0");
if (!IsPrerelease("1.0")) throw new Exception("1.0 has Revision -1");
if (IsPrereleas... | string d32 = Program.DescribeCompareVersions().ToLower();
if (!d32.Contains("-1")) throw new Exception("Must mention -1 default for undefined components");
if (!d32.Contains("not 0") && !d32.Contains("not zero")) throw new Exception("Must clarify defaults are -1, not 0");
if (!(d32.Contains("1.0") && d32.Contains("1.0.... | api_usage |
33 | devbench-api-usage | c_sharp | using System;
class Program
{
static void Main()
{
int original = 0x01020304;
| byte[] bytes = BitConverter.GetBytes(original);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
int restored = BitConverter.ToInt32(BitConverter.IsLittleEndian ? GetReversed(bytes) : bytes, 0);
|
if (restored != original) throw new Exception("Round-trip failed: " + restored);
// Verify big-endian byte order after our reversal
if (BitConverter.IsLittleEndian)
{
if (bytes[0] != 0x01) throw new Exception("Expected MSB first after reverse");
if (bytes[3] != ... | byte[] testBytes = BitConverter.GetBytes((int)0x0A0B0C0D);
if (BitConverter.IsLittleEndian)
{
if (testBytes[0] != 0x0D) throw new Exception("Little-endian: LSB should be first byte");
if (testBytes[3] != 0x0A) throw new Exception("Little-endian: MSB should be last byte");
}
int roundTrip = BitConverter.ToInt32(... | api_usage |
34 | devbench-api-usage | c_sharp | using System;
class Program
{
static int FindOrInsertionPoint(int[] sorted, int value)
{
int idx = Array.BinarySearch(sorted, value);
return idx >= 0 ? idx : ~idx;
}
| static string DescribeFindOrInsertionPoint()
{
return "Uses Array.BinarySearch(Array, Object) which performs O(log n) binary search "
+ "on a SORTED array. Returns the zero-based index if found. If NOT found, returns "
+ "the bitwise complement (~) of the index of the next elem... |
static void Main()
{
int[] arr = { 1, 3, 5, 7, 9 };
if (FindOrInsertionPoint(arr, 5) != 2) throw new Exception("Should find 5 at index 2");
if (FindOrInsertionPoint(arr, 4) != 2) throw new Exception("4 would insert at index 2");
if (FindOrInsertionPoint(arr, 0) != 0) throw new E... | string d34 = Program.DescribeFindOrInsertionPoint().ToLower();
if (!d34.Contains("bitwise complement") && !d34.Contains("~")) throw new Exception("Must mention bitwise complement");
if (!d34.Contains("sorted")) throw new Exception("Must mention sorted requirement");
if (!d34.Contains("undefined") && !d34.Contains("not ... | api_usage |
35 | devbench-api-usage | c_sharp | using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = new DataTable("Sales");
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Qty", typeof(int));
table.Columns.Add("Price", typeof(decimal));
| table.Columns.Add("Total", typeof(decimal), "Qty * Price");
table.Rows.Add("Widget", 5, 3.50m);
table.Rows.Add("Gadget", 2, 12.00m);
table.Rows.Add("Widget", 3, 3.50m);
DataRow[] widgets = table.Select("Product = 'Widget'", "Total DESC");
decimal firstTotal = (decimal)w... |
if (widgets.Length != 2) throw new Exception("Should find 2 Widget rows, got " + widgets.Length);
if (firstTotal != 17.50m) throw new Exception("First Widget total should be 17.50 (5*3.50), got " + firstTotal);
decimal secondTotal = (decimal)widgets[1]["Total"];
if (secondTotal != 10.50... | DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(int));
dt.Columns.Add("B", typeof(int));
dt.Columns.Add("C", typeof(int), "A + B");
dt.Rows.Add(1, 2);
if ((int)dt.Rows[0]["C"] != 3) throw new Exception("Expression column should compute");
dt.Rows[0]["A"] = 10;
if ((int)dt.Rows[0]["C"] != 12) throw new Except... | api_usage |
36 | devbench-api-usage | c_sharp | using System;
class Program
{
static void SafeCopy(Array src, int srcIdx, Array dst, int dstIdx, int len)
{
Array.ConstrainedCopy(src, srcIdx, dst, dstIdx, len);
}
static void RegularCopy(Array src, int srcIdx, Array dst, int dstIdx, int len)
{
Array.Copy(src, srcIdx, dst, dstIdx, ... | static string DescribeSafeCopy()
{
return "Array.ConstrainedCopy provides atomicity: either ALL elements are copied or "
+ "NONE are (the destination is unchanged on failure). This differs from Array.Copy "
+ "which may leave the destination partially modified if an exception o... |
static void Main()
{
int[] src = { 1, 2, 3, 4, 5 };
int[] dst = { 0, 0, 0, 0, 0 };
SafeCopy(src, 1, dst, 0, 3);
if (dst[0] != 2 || dst[1] != 3 || dst[2] != 4) throw new Exception("ConstrainedCopy failed");
if (dst[3] != 0) throw new Exception("Should not modify beyond le... | string d36 = Program.DescribeSafeCopy().ToLower();
if (!d36.Contains("atomic") && !d36.Contains("all or nothing") && !d36.Contains("all elements")) throw new Exception("Must mention atomicity guarantee");
if (!d36.Contains("array.copy")) throw new Exception("Must contrast with Array.Copy");
if (!d36.Contains("partially... | api_usage |
37 | devbench-api-usage | c_sharp | using System;
using System.Collections.Specialized;
class Program
{
static void Main()
{
NameValueCollection nvc = new NameValueCollection();
| nvc.Add("color", "red");
nvc.Add("color", "blue");
nvc.Add("size", "large");
string colors = nvc.Get("color");
string[] colorArray = nvc.GetValues("color");
int keyCount = nvc.Count;
|
// Get returns comma-separated for multiple values
if (colors != "red,blue") throw new Exception("Get should return 'red,blue', got: " + colors);
if (colorArray.Length != 2) throw new Exception("GetValues should return 2 items");
if (colorArray[0] != "red" || colorArray[1] != "blue") th... | NameValueCollection test = new NameValueCollection();
test.Add("k", "v1");
test.Add("k", "v2");
test.Add("k", "v3");
if (test.Get("k") != "v1,v2,v3") throw new Exception("Get should comma-join multiple values");
if (test.Count != 1) throw new Exception("Count counts keys, not values");
test.Set("k", "only");
if (test.G... | api_usage |
38 | devbench-api-usage | c_sharp | using System;
class Program
{
static void GrowArray(ref int[] arr, int newSize)
{
Array.Resize(ref arr, newSize);
}
| static string DescribeGrowArray()
{
return "Array.Resize<T>(ref T[], int) does NOT resize the array in-place. It allocates "
+ "a NEW array of the specified size, copies elements from the old array (up to "
+ "Math.Min(old.Length, newSize)), and assigns the new array to the ref... |
static void Main()
{
int[] original = { 1, 2, 3 };
int[] alias = original;
GrowArray(ref original, 5);
// Original reference now points to new array
if (original.Length != 5) throw new Exception("Should be length 5");
if (original[3] != 0) throw new Exception("N... | string d38 = Program.DescribeGrowArray().ToLower();
if (!d38.Contains("new array") && !d38.Contains("allocate")) throw new Exception("Must mention new array allocation");
if (!d38.Contains("not") && !d38.Contains("does not")) throw new Exception("Must mention does NOT resize in-place");
if (!d38.Contains("ref")) throw ... | api_usage |
39 | devbench-api-usage | c_sharp | using System;
class Program
{
static void Main()
{
Uri uri = new Uri("http://example.com:8080/path/to/resource?key=val&foo=bar#section2");
| string host = uri.Host;
int port = uri.Port;
string path = uri.AbsolutePath;
string query = uri.Query;
string fragment = uri.Fragment;
string authority = uri.Authority;
string pathAndQuery = uri.PathAndQuery;
|
if (host != "example.com") throw new Exception("Host wrong: " + host);
if (port != 8080) throw new Exception("Port wrong: " + port);
if (path != "/path/to/resource") throw new Exception("AbsolutePath wrong: " + path);
// Query includes the leading '?'
if (query != "?key=val&foo=... | Uri u39 = new Uri("https://user:pass@host.com:443/a/b?x=1#frag");
if (u39.Port != 443) throw new Exception("Port should be 443");
if (u39.IsDefaultPort != true) throw new Exception("443 is default for https");
if (!u39.Query.StartsWith("?")) throw new Exception("Query must start with ?");
if (!u39.Fragment.StartsWith("... | api_usage |
40 | devbench-api-usage | c_sharp | using System;
using System.Collections.Specialized;
class Program
{
static StringDictionary CreateLookup(string[] keys, string[] values)
{
StringDictionary sd = new StringDictionary();
for (int i = 0; i < keys.Length; i++)
{
sd.Add(keys[i], values[i]);
}
retu... | static string DescribeCreateLookup()
{
return "Uses StringDictionary which automatically LOWERCASES all keys on Add, "
+ "ContainsKey, and indexer access. 'Hello' and 'hello' map to the SAME entry — "
+ "Add('Hello','x') followed by Add('hello','y') throws ArgumentException for... |
static void Main()
{
StringDictionary sd = CreateLookup(
new[] { "Name", "COLOR", "Size" },
new[] { "Alice", "Red", "Large" }
);
// Keys are lowercased
if (sd["name"] != "Alice") throw new Exception("Should find 'name' (lowered from 'Name')");
if... | string d40 = Program.DescribeCreateLookup().ToLower();
if (!d40.Contains("lowercase") && !d40.Contains("lower-case") && !d40.Contains("lowered")) throw new Exception("Must mention key lowercasing");
if (!d40.Contains("case-sensitive") && !d40.Contains("case sensitive")) throw new Exception("Must mention case sensitivit... | api_usage |
41 | devbench-api-usage | c_sharp | using System;
using System.Linq.Expressions;
namespace Bench
{
public class Program
{
/// <summary>
| /// Compiles a BinaryExpression that multiplies two int parameters
/// using Expression.Multiply, wraps it in Expression.Lambda, and
/// invokes Compile() to produce a Func<int,int,int> delegate.
/// The ParameterExpressions are created via Expression.Parameter.
/// </summa... | public static Func<int,int,int> BuildMultiplier()
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var mul = Expression.Multiply(a, b);
var lambda = Expression.Lambda<Func<int,int,int>>(mul, a, b);
... | var fn2 = Program.BuildMultiplier();
if (!(fn2(1, 1) == 1)) throw new Exception("1*1");
if (!(fn2(-3, -4) == 12)) throw new Exception("-3*-4");
// Doc precision checks
var method = typeof(Program).GetMethod("BuildMultiplier");
// We check the XML ... | api_usage |
42 | devbench-api-usage | c_sharp | using System;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Bench
{
public class Program
{
static void Main()
{
string json = @"{""items"":[{""name"":""A"",""qty"":1},{""name"":""B"",""qty"":2}],""total"":3}";
JsonNode root = JsonNode.Parse(json)!;
... | var items = root["items"]!.AsArray();
var newItem = new JsonObject
{
["name"] = "C",
["qty"] = 5
};
items.Add(newItem);
int newTotal = 0;
foreach (var item in items)
{
newTotal... |
string result = root.ToJsonString();
if (!(root["total"]!.GetValue<int>() == 8)) throw new Exception("total should be 8");
if (!(root["items"]!.AsArray().Count == 3)) throw new Exception("should have 3 items");
var last = root["items"]![2]!;
if (!(last["name"... | // Verify JSON roundtrip preserves structure
var reparsed = JsonNode.Parse(root.ToJsonString())!;
if (!(reparsed["items"]!.AsArray().Count == 3)) throw new Exception("reparse count");
if (!(reparsed["total"]!.GetValue<int>() == 8)) throw new Exception("reparse total");
... | api_usage |
43 | devbench-api-usage | c_sharp | using System;
namespace Bench
{
public class Program
{
static void Main()
{
int[] data = { 10, 20, 30, 40, 50, 60, 70, 80 };
// Use Index (^) and Range (..) operators to extract slices
| int last = data[^1];
int secondLast = data[^2];
int[] middle = data[2..6];
int[] lastThree = data[^3..];
int[] firstTwo = data[..2];
int[] reversed = data[^4..^1];
|
if (!(last == 80)) throw new Exception("last");
if (!(secondLast == 70)) throw new Exception("secondLast");
if (!(middle.Length == 4 && middle[0] == 30 && middle[3] == 60)) throw new Exception("middle");
if (!(lastThree.Length == 3 && lastThree[0] == 60)) throw new Excep... | // Additional edge cases with Index/Range
int first = data[^8];
if (!(first == 10)) throw new Exception("^8 should be first");
int[] all = data[..];
if (!(all.Length == 8)) throw new Exception("full range");
int[] empty = data[3..3];
if... | api_usage |
44 | devbench-api-usage | c_sharp | using System;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Bench
{
public class Program
{
/// <summary>
| /// Creates a bounded Channel<int> with capacity 2 using
/// Channel.CreateBounded with BoundedChannelFullMode.Wait.
/// The producer calls WriteAsync to enqueue values, blocking when
/// the channel is full. The consumer calls ReadAsync in a loop
/// until TryRead returns ... | public static async Task<int> ProduceConsumeAsync(int[] values)
{
var ch = Channel.CreateBounded<int>(new BoundedChannelOptions(2)
{
FullMode = BoundedChannelFullMode.Wait
});
var producer = Task.Run(async () =>
{
... | int r2 = await ProduceConsumeAsync(new[] { 10, 20, 30 });
if (!(r2 == 60)) throw new Exception("10+20+30");
int r3 = await ProduceConsumeAsync(new[] { -1, 1 });
if (!(r3 == 0)) throw new Exception("-1+1");
int r4 = await ProduceConsumeAsync(new[] { 100 });
... | api_usage |
45 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Dynamic;
namespace Bench
{
public class TrackedObject : DynamicObject
{
private Dictionary<string, object> _store = new();
private List<string> _accessLog = new();
public List<string> AccessLog => _accessLog;
| public override bool TrySetMember(SetMemberBinder binder, object? value)
{
_store[binder.Name] = value!;
_accessLog.Add("set:" + binder.Name);
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
... | }
public class Program
{
static void Main()
{
dynamic obj = new TrackedObject();
obj.Name = "Alice";
obj.Age = 30;
string name = obj.Name;
int age = obj.Age;
var log = ((TrackedObject)obj).AccessLog;
if (!(... | // Additional: set same property twice, get nonexistent
dynamic obj2 = new TrackedObject();
obj2.X = 1;
obj2.X = 2;
int x = obj2.X;
var log2 = ((TrackedObject)obj2).AccessLog;
if (!(log2.Count == 3)) throw new Exception("log2 count");
... | api_usage |
46 | devbench-api-usage | c_sharp | using System;
namespace Bench
{
public class Program
{
static int SumSpan(ReadOnlySpan<int> span)
{
int s = 0;
foreach (var v in span) s += v;
return s;
}
static void Main()
{
Span<int> buf = stackalloc int[6];
... | int total = SumSpan(buf);
int firstHalf = SumSpan(buf[..3]);
int lastHalf = SumSpan(buf[3..]);
int mid = SumSpan(buf[1..5]);
int lastTwo = SumSpan(buf[^2..]);
|
if (!(total == 210)) throw new Exception($"total={total}");
if (!(firstHalf == 60)) throw new Exception($"firstHalf={firstHalf}");
if (!(lastHalf == 150)) throw new Exception($"lastHalf={lastHalf}");
if (!(mid == 140)) throw new Exception($"mid={mid}");
if (!... | // Edge slices
int single = SumSpan(buf[2..3]);
if (!(single == 30)) throw new Exception("single slice");
int empty = SumSpan(buf[3..3]);
if (!(empty == 0)) throw new Exception("empty slice");
int fromEnd = SumSpan(buf[^6..^3]);
if (!(f... | api_usage |
47 | devbench-api-usage | c_sharp | using System;
using System.Globalization;
namespace Bench
{
public class Program
{
/// <summary>
| /// Formats a decimal as currency using a custom NumberFormatInfo
/// where CurrencySymbol is "XYZ", CurrencyGroupSeparator is an
/// underscore, CurrencyDecimalDigits is 3, and CurrencyGroupSizes
/// is {2, 3} meaning the rightmost group has 2 digits and all
/// subsequent group... | public static string FormatCustomCurrency(decimal amount)
{
var nfi = new NumberFormatInfo
{
CurrencySymbol = "XYZ",
CurrencyGroupSeparator = "_",
CurrencyDecimalDigits = 3,
CurrencyGroupSizes = new int[] { 2, 3 }
... | string r4 = Program.FormatCustomCurrency(100000m);
if (!(r4 == "XYZ1_000_00.000")) throw new Exception($"100000: {r4}");
string r5 = Program.FormatCustomCurrency(-42.7m);
if (!(r5 == "(XYZ42.700)" || r5 == "-XYZ42.700" || r5.Contains("42.700"))) throw new Exception($"-42.... | api_usage |
48 | devbench-api-usage | c_sharp | using System;
using System.Linq.Expressions;
namespace Bench
{
public class Program
{
// Build an expression tree that represents: x => x > 0 ? x * 2 : x * -1
// Must use Expression.Condition, Expression.GreaterThan,
// Expression.Multiply, Expression.Constant
static Func<int, i... | var zero = Expression.Constant(0);
var two = Expression.Constant(2);
var negOne = Expression.Constant(-1);
var test = Expression.GreaterThan(x, zero);
var pos = Expression.Multiply(x, two);
var neg = Expression.Multiply(x, negOne);
var ... | }
static void Main()
{
var fn = BuildAbsDoubler();
if (!(fn(5) == 10)) throw new Exception("5->10");
if (!(fn(-3) == 3)) throw new Exception("-3->3");
if (!(fn(0) == 0)) throw new Exception("0->0");
if (!(fn(1) == 2)) throw new Excepti... | var fn2 = BuildAbsDoubler();
if (!(fn2(100) == 200)) throw new Exception("100->200");
if (!(fn2(-50) == 50)) throw new Exception("-50->50");
if (!(fn2(int.MaxValue / 2) == int.MaxValue / 2 * 2)) throw new Exception("large");
if (!(fn2(-1000) == 1000)) throw ne... | api_usage |
49 | devbench-api-usage | c_sharp | using System;
using System.IO;
namespace Bench
{
public class Program
{
// Read lines from a StringReader, number them, write to StringWriter
static string NumberLines(string text)
{
var reader = new StringReader(text);
var writer = new StringWriter();
| string? line;
int num = 1;
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine($"{num}: {line}");
num++;
}
return writer.ToString().TrimEnd();
| }
static void Main()
{
string input = "alpha\nbeta\ngamma";
string result = NumberLines(input);
if (!(result == "1: alpha\n2: beta\n3: gamma")) throw new Exception($"got: [{result}]");
string single = NumberLines("only");
if (!(single... | string multi = Program.NumberLines("a\nb\nc\nd\ne");
if (!(multi == "1: a\n2: b\n3: c\n4: d\n5: e")) throw new Exception("multi");
string withSpaces = Program.NumberLines(" x \nhello");
if (!(withSpaces == "1: x \n2: hello")) throw new Exception("spaces");
| api_usage |
50 | devbench-api-usage | c_sharp | using System;
using System.Globalization;
namespace Bench
{
public class Program
{
/// <summary>
| /// Parses dates using a custom DateTimeFormatInfo where all four
/// month-name arrays (AbbreviatedMonthNames, AbbreviatedMonthGenitiveNames,
/// MonthNames, MonthGenitiveNames) are replaced with Romanian-style names
/// so that standard English month names no longer parse. DateSeparato... | public static DateTime ParseRomanianDate(string s)
{
var ci = new CultureInfo("en-US");
var dtfi = ci.DateTimeFormat;
dtfi.AbbreviatedMonthNames = new[]
{
"Ian", "Fev", "Mrt", "Avr", "Mai", "Iun",
"Iul", "Avg", "Sep", "Okt",... | var d4 = Program.ParseRomanianDate("31.Iul.2023");
if (!(d4.Month == 7 && d4.Day == 31)) throw new Exception("d4 Jul");
var d5 = Program.ParseRomanianDate("10.Avg.2020");
if (!(d5.Month == 8 && d5.Day == 10)) throw new Exception("d5 Aug");
bool threw = false;
... | api_usage |
1 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class ClaimResult {
public string Status;
public double Patient;
public double Plan;
public double DeductibleApplied;
public double CoinsuranceApplied;
}
class Adjudicator {
public double Copay = 30.0;
public double AnnualDeductible = 500.0;
... | if (ProcessedClaims.Contains(claimId)) return null;
if (!AllowedRates.ContainsKey(code) || (RequiresAuth.Contains(code) && !AuthorizedClaims.Contains(claimId))) {
ProcessedClaims.Add(claimId);
ClaimLedger.Add("DENIED:" + claimId + ":" + code);
return new ClaimResult {... | }
}
class Program {
static void Main() {
var adj = new Adjudicator();
var r1 = adj.AdjudicateLine("C1", "THERAPY", 400.0, false, 20.0);
// allowed=320, remaining=300, copay=30, ded=270, coins=0, pat=300
if (r1.Status != "PAID") throw new Exception("r1 status " + r1.Status);
... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int ledgerBefore = adj.ClaimLedger.Count;
double oopBefore = adj.YtdOop;
var dup = adj.AdjudicateLine("C1", "THERAPY", 999.0, false, 0.0);
if (dup != null) throw new Exception("dup should be null");
... | code_purpose_understanding |
2 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Lot {
public string Id;
public string Sku;
public int Qty;
public int ExpiryDay;
public bool Quarantined;
}
class Warehouse {
public List<Lot> Lots = new List<Lot>();
public HashSet<string> ProcessedTickets = new Hash... | if (SavedTickets.ContainsKey(ticketId)) return new List<string>(SavedTickets[ticketId]);
if (qty <= 0) throw new ArgumentException("qty");
var eligible = Lots.Where(l => l.Sku == sku && !l.Quarantined && l.Qty > 0 && l.ExpiryDay >= shipDay + MinShelfLifeDays)
.OrderBy(... | }
}
class Program {
static void Main() {
var wh = new Warehouse();
wh.AddLot("L1", "MED", 5, 10, false);
wh.AddLot("L2", "MED", 4, 7, false);
wh.AddLot("L3", "MED", 9, 6, true); // quarantined
var t1 = wh.AllocateOrder("O1", "MED", 6, 4, false);
// FEFO: L2(exp7... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int auditBefore = wh.AuditLog.Count;
var dup = wh.AllocateOrder("O1", "MED", 99, 100, true);
if (dup.Count != 2 || dup[0] != "PICK:L2:4") throw new Exception("dup ticket");
if (wh.AuditLog.Count != auditBe... | code_purpose_understanding |
3 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class PharmacyRx {
public int RxTotalQty;
public int FilledQty;
public int DaysSupply;
public int LastFillDay = -1;
public bool Controlled;
public bool ExpeditedUsed;
public int InventoryQty;
public HashSet<string> ProcessedFillIds = new H... | if (ProcessedFillIds.Contains(fillId)) return "DUPLICATE";
if (FilledQty >= RxTotalQty) return "RX_COMPLETE";
if (requestedQty <= 0) throw new ArgumentException("qty");
if (Controlled && expedited) return "CONTROLLED_EXPEDITE_DENIED";
if (Controlled && requestedQty > 30) return "... | }
}
class Program {
static void Main() {
var rx = new PharmacyRx { RxTotalQty=90, DaysSupply=30, Controlled=false, InventoryQty=50 };
string first = rx.Fill("F1", 0, 30, false);
if (first != "FILLED") throw new Exception(first);
if (rx.FilledQty != 30 || rx.InventoryQty != 20) t... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int logBefore = rx.FillLog.Count;
string dup = rx.Fill("F1", 99, 99, true);
if (dup != "DUPLICATE") throw new Exception("dup=" + dup);
if (rx.FillLog.Count != logBefore) throw new Exception("dup logged");
... | code_purpose_understanding |
4 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class PayStub {
public double Retirement;
public double Tax;
public double Health;
public double Garnishment;
public double Net;
}
class PayrollEngine {
public double RetirementRate = 0.05;
public double RetirementCap = 1000.0;
public dou... | if (ProcessedRuns.Contains(runId)) return null;
if (gross <= 0) throw new ArgumentException("gross");
double capLeft = Math.Max(0, RetirementCap - YtdRetirement);
double retirement = R2(Math.Min(R2(gross * RetirementRate), capLeft));
double tax = TaxOn(gross - retirement);
... | }
}
class Program {
static void Main() {
var pe = new PayrollEngine();
var p1 = pe.RunPayroll("R1", 2000.0);
// Ret=100, taxable=1900, tax=100+180=280, health=200, disp=1420, garn=213, net=1207
if (Math.Abs(p1.Retirement - 100.0) > 0.01) throw new Exception("ret=" + p1.Retiremen... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int logsBefore = pe.PayrollLog.Count;
double ytdBefore = pe.YtdNet;
var dup = pe.RunPayroll("R1", 9999.0);
if (dup != null) throw new Exception("dup not null");
if (pe.PayrollLog.Count != logsBefor... | code_purpose_understanding |
5 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Grant {
public string Id;
public string Sku;
public int Remaining;
public int StartDay;
public int EndDay;
}
class DenyRule {
public string Sku;
public int Units;
public int StartDay;
public int EndDay;
}
cla... | if (Tickets.ContainsKey(requestId)) return new List<string>(Tickets[requestId]);
if (units <= 0) throw new ArgumentException("units");
var active = Grants.Where(g => g.Sku == sku && g.Remaining > 0 && g.StartDay <= day && day <= g.EndDay)
.OrderBy(g => g.EndDay).ThenBy(... | }
}
class Program {
static void Main() {
var ledger = new EntitlementLedger();
ledger.Grants.Add(new Grant { Id="G1", Sku="API", Remaining=5, StartDay=0, EndDay=10 });
ledger.Grants.Add(new Grant { Id="G2", Sku="API", Remaining=10, StartDay=0, EndDay=20 });
ledger.Denies.Add(new... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int auditBefore = ledger.AuditLog.Count;
var dup = ledger.Consume("R1", "API", 99, 6);
if (dup.Count != 1 || dup[0] != "USE:G1:4") throw new Exception("dup");
if (ledger.AuditLog.Count != auditBefore) thro... | code_purpose_understanding |
6 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class CreditBlock {
public string Id;
public double Remaining;
public int GrantedDay;
}
class InvoiceLine {
public string Description;
public double Amount;
}
class BillingAccount {
public double MinimumCommit = 500.0;
pub... | if (ClosedPeriods.Contains(periodId)) return null;
double usageCharge = R2(units * PerUnitRate);
double invoiceAmt = Math.Max(usageCharge, MinimumCommit);
var lines = new List<InvoiceLine>();
if (usageCharge < MinimumCommit)
lines.Add(new InvoiceLine { Description="MI... | }
}
class Program {
static void Main() {
var acct = new BillingAccount();
acct.Credits.Add(new CreditBlock { Id="CR1", Remaining=100.0, GrantedDay=1 });
acct.Credits.Add(new CreditBlock { Id="CR2", Remaining=200.0, GrantedDay=5 });
var inv = acct.ClosePeriod("P1", 8000);
... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
var dup = acct.ClosePeriod("P1", 99999);
if (dup != null) throw new Exception("dup not null");
// Minimum commit kicks in
acct.Credits.Add(new CreditBlock { Id="CR3", Remaining=50.0, GrantedDay=10 });
... | code_purpose_understanding |
7 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class DrawResult {
public string Status;
public double Released;
public double Retainage;
public double DefectReserve;
}
class EscrowAccount {
public double TotalContract = 100000.0;
public double RetainageRate = 0.10;
public double DefectRes... | if (ProcessedDraws.Contains(drawId)) return null;
if (FinalAccepted) return new DrawResult { Status="ALREADY_CLOSED" };
if (!CompletedMilestones.Contains(milestone)) return new DrawResult { Status="MILESTONE_INCOMPLETE" };
double maxDraw = R2(Math.Min(TotalContract - TotalDrawn, FundBala... | }
}
class Program {
static void Main() {
var esc = new EscrowAccount();
esc.FundBalance = 100000.0;
esc.CompletedMilestones.Add(1);
esc.CompletedMilestones.Add(2);
var d1 = esc.ProcessDraw("D1", 1, 20000.0);
// retainage=2000, defect=1000, released=17000
... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int logBefore = esc.DrawLog.Count;
var dup = esc.ProcessDraw("D1", 1, 99999.0);
if (dup != null) throw new Exception("dup not null");
if (esc.DrawLog.Count != logBefore) throw new Exception("dup logged");
... | code_purpose_understanding |
8 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class PaymentResult {
public string Status;
public double ToFees;
public double ToInterest;
public double ToPrincipal;
public double ToEscrow;
public double ToSuspense;
}
class LoanAccount {
public double PrincipalBalance;
public double I... | if (ProcessedPayments.Contains(paymentId))
return new PaymentResult { Status="DUPLICATE" };
ProcessedPayments.Add(paymentId);
if (Status == "CHARGED_OFF") {
SuspenseBalance = R2(SuspenseBalance + amount);
PaymentLedger.Add("PAY:" + paymentId + ":RECOVERY:" + a... | }
}
class Program {
static void Main() {
var loan = new LoanAccount { PrincipalBalance=10000.0, InterestDue=200.0, EscrowDue=100.0, LateFeePending=true };
var r1 = loan.ApplyPayment("P1", 500.0);
// Late fee injected: fees=75. Waterfall: 75+200+100+125=500. principal=9875.
if (r... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int ledgerBefore = loan.PaymentLedger.Count;
var dup = loan.ApplyPayment("P1", 9999.0);
if (dup.Status != "DUPLICATE") throw new Exception("dup status");
if (loan.PaymentLedger.Count != ledgerBefore) throw... | code_purpose_understanding |
9 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class SubResult {
public string PrevState;
public string NewState;
public double Charge;
public string Message;
}
class Subscription {
public string State = "TRIAL"; // TRIAL, ACTIVE, PAUSED, GRACE, CANCELLED
public int TrialEndDay;
public i... | if (ProcessedActions.Contains(actionId)) return null;
ProcessedActions.Add(actionId);
string prev = State;
double charge = 0;
string msg = "OK";
switch (action) {
case "activate":
if (State != "TRIAL") { msg = "INVALID_STATE"; break; }
... | }
}
class Program {
static void Main() {
var sub = new Subscription { TrialEndDay=14 };
var a1 = sub.ProcessAction("A1", "activate", 14);
if (a1.NewState != "ACTIVE" || Math.Abs(a1.Charge - 50.0) > 0.01) throw new Exception("activate " + a1.NewState + " " + a1.Charge);
if (sub.L... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int logBefore = sub.ActionLog.Count;
var dup = sub.ProcessAction("A1", "activate", 99);
if (dup != null) throw new Exception("dup not null");
if (sub.ActionLog.Count != logBefore) throw new Exception("dup ... | code_purpose_understanding |
10 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class OrderResult {
public string Status;
public int Shipped;
public double Charged;
public double Refunded;
}
class FulfillmentEngine {
public Dictionary<string, int> Inventory = new Dictionary<string, int>();
public Dictionary<string, double> P... | if (ProcessedOrders.Contains(orderId)) return new OrderResult { Status="DUPLICATE" };
if (CancelledOrders.Contains(orderId)) return new OrderResult { Status="CANCELLED" };
if (!Prices.ContainsKey(sku)) return new OrderResult { Status="UNKNOWN_SKU" };
double totalPrice = R2(qty * Prices[s... | }
}
class Program {
static void Main() {
var eng = new FulfillmentEngine();
eng.Inventory["WIDGET"] = 15;
eng.Prices["WIDGET"] = 10.0;
eng.PaymentBalance = 500.0;
var r1 = eng.Fulfill("O1", "WIDGET", 10, false);
if (r1.Status != "FULFILLED") throw new Exception("... | if (visibleOk != 1) throw new Exception("visibleOk");
// Duplicate
int logBefore = eng.FulfillLog.Count;
var dup = eng.Fulfill("O1", "WIDGET", 99, true);
if (dup.Status != "DUPLICATE") throw new Exception("dup " + dup.Status);
if (eng.FulfillLog.Count != logBefore) throw ... | code_purpose_understanding |
11 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class PolicyEngine
{
static int basePremium; // in whole dollars
static int policyAge; // years since first issue
static int claimsInWindow; // claims in last 3 years
static int coverageLimit;
static int maxCoverage;
static Lis... | if (processedRenewals.Contains(renewalId)) return "DUPLICATE";
int agePct = Math.Min(policyAge * 5, 50);
int ageSurcharge = basePremium * agePct / 100;
int claimsSurcharge = basePremium * claimsInWindow * 10 / 100;
int endCost = 0;
foreach (var c in endorsementCosts) endCost += c;
if (endCost > endorsementCap) endCost ... | }
static void Main()
{
Reset(1000, 6, 2, 5000, 6000, 300);
AddEndorsement(200);
AddEndorsement(250);
// age surcharge: min(6*5,50)=30% of 1000 = 300
// claims surcharge: 2*10% of 1000 = 200
// endorsement cost: 200+250=450, clipped to 300
// subtotal ... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate
string dup = PolicyEngine.Renew("R1");
if (dup != "DUPLICATE") throw new Exception("dup=" + dup);
if (PolicyEngine.auditLog.Count != 1) throw new Exception("dup mutated audit");
if (PolicyEngine.totalPremium != 1656) throw new Exception("dup mutated tot... | code_purpose_understanding |
12 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class HotelSystem
{
static Dictionary<string, int> inventory = new Dictionary<string, int>(); // category -> rooms
static Dictionary<string, int> rates = new Dictionary<string, int>(); // category -> nightly rate
static string[] upgradeOrder; // categori... | if (reservations.ContainsKey(resId)) return "DUPLICATE";
int reqIdx = Array.IndexOf(upgradeOrder, requestedCat);
if (reqIdx < 0) return "NO_ROOM";
string assigned = null;
if (BookedCount(requestedCat) < EffectiveCapacity(requestedCat))
{
assigned = requestedCat;
}
else
{
for (int i = reqIdx + 1; i < upgradeOrde... | }
// Cancel a reservation.
// Rules:
// 1. If resId does not exist, return "NOT_FOUND".
// 2. Fee: if daysBefore >= 7, fee = 0; if 3 <= daysBefore < 7, fee = 50% of total;
// if daysBefore < 3, fee = 100% (no refund).
// 3. Refund = total - fee. Subtract refund from revenue (revenue ... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate booking
string dupB = HotelSystem.Book("A2", "standard", 5);
if (dupB != "DUPLICATE") throw new Exception("dupB=" + dupB);
// standard freed by cancel of A1, new booking fits
string b4 = HotelSystem.Book("A4", "standard", 1);
if (b4 != "BOOKED:standard... | code_purpose_understanding |
13 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class TradingEngine
{
class Offer { public string id; public int qty; public int priceCents; }
static List<Offer> askBook = new List<Offer>(); // sorted cheapest first
static Dictionary<string, int> filledQty = new Dictionary<string, int>();
static Dict... | if (processedOrders.Contains(orderId)) return "DUPLICATE";
int totalShares = 0;
int totalCost = 0;
List<string> pendingLogs = new List<string>();
List<int> depletedIdx = new List<int>();
for (int i = 0; i < askBook.Count && totalShares < wantQty; i++)
{
var ask = askBook[i];
if (orderType == "LIMIT" && ask.pric... | }
static void Main()
{
Reset();
AddAsk("S1", 50, 1000); // $10.00
AddAsk("S2", 200, 1050); // $10.50
AddAsk("S3", 100, 1100); // $11.00
// Market order for 120 shares
string r1 = ExecuteOrder("B1", "MARKET", 120, 0);
// Fills: 50@1000 from S1, 70@... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate
string dup = TradingEngine.ExecuteOrder("B1", "MARKET", 999, 0);
if (dup != "DUPLICATE") throw new Exception("dup=" + dup);
// Limit order that partially fills
string r3 = TradingEngine.ExecuteOrder("B3", "LIMIT", 200, 1050);
// S2 has 130 left at 1050... | code_purpose_understanding |
14 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class TaxEngine
{
static int[][] brackets; // each: {upperLimit, ratePercent}, last upperLimit = int.MaxValue
static int stdDeduction;
static int exemptionAmount;
static int phaseOutStart;
static int phaseOutStep; // every phaseOutStep over phaseOu... | int excess = gross > phaseOutStart ? gross - phaseOutStart : 0;
int reductions = excess / phaseOutStep;
int phasePct = reductions * 2;
if (phasePct > 100) phasePct = 100;
int adjExemption = exemptionAmount - exemptionAmount * phasePct / 100;
if (adjExemption < 0) adjExemption = 0;
int taxable = gross - stdDeduction - a... | }
static void Main()
{
Reset(
new int[][] { new[] {20000, 10}, new[] {60000, 20}, new[] {int.MaxValue, 30} },
12000, 4000, 80000, 5000
);
// gross=50000: no phase-out, exemption=4000, taxable=50000-12000-4000=34000
// tax: 20000*10/100=2000, 14000*20/... | if (visibleDone != 1) throw new Exception("visible");
// Zero income
int t3 = TaxEngine.ComputeTax(0);
if (t3 != 0) throw new Exception("t3=" + t3);
// Income below deduction+exemption
int t4 = TaxEngine.ComputeTax(10000);
if (t4 != 0) throw new Exception("t4=" + t4);
// Full phase-out: gross=400000, excess=320000, r... | code_purpose_understanding |
15 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class WarehouseTransfer
{
static Dictionary<string, int> srcInventory = new Dictionary<string, int>();
static Dictionary<string, int> dstInventory = new Dictionary<string, int>();
static Dictionary<string, int> inTransit = new Dictionary<string, int>(); // tr... | if (!inTransit.ContainsKey(transferId)) return "NOT_IN_TRANSIT";
int shipped = inTransit[transferId];
if (receivedQty > shipped) return "OVER_RECEIVE";
int shrinkage = shipped - receivedQty;
totalShrinkage += shrinkage;
string sku = transferSku[transferId];
if (!dstInventory.ContainsKey(sku)) dstInventory[sku] = 0;
dst... | }
static void Main()
{
Reset();
SetSrc("WIDGET", 100);
SetDst("WIDGET", 20);
string s1 = Ship("T1", "WIDGET", 30);
if (s1 != "SHIPPED") throw new Exception("s1=" + s1);
if (srcInventory["WIDGET"] != 70) throw new Exception("src=" + srcInventory["WIDGET"]);
... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate ship
string ds = WarehouseTransfer.Ship("T1", "WIDGET", 5);
if (ds != "DUPLICATE") throw new Exception("ds=" + ds);
// Duplicate ship for in-transit
string ds2 = WarehouseTransfer.Ship("T2", "WIDGET", 5);
if (ds2 != "DUPLICATE") throw new Exception("ds... | code_purpose_understanding |
16 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class ResourceAllocator
{
class Resource
{
public string id;
public HashSet<string> skills;
public int maxHours; // weekly cap before overtime
public int allocatedHours; // hours allocated this week
public int overtim... | if (!resources.ContainsKey(resourceId)) return "NOT_FOUND";
Resource r = resources[resourceId];
if (!r.skills.Contains(requiredSkill)) return "SKILL_MISMATCH";
int regularAvail = r.maxHours - r.allocatedHours;
if (regularAvail < 0) regularAvail = 0;
int regularUsed = Math.Min(hours, regularAvail);
int overtime = hours ... | }
static void Main()
{
Reset(50);
AddResource("DEV1", new[] { "csharp", "sql" }, 40);
AddResource("DEV2", new[] { "java", "sql" }, 40);
string a1 = Allocate("P1", "DEV1", "csharp", 30, false);
if (a1 != "ALLOCATED:30:0") throw new Exception("a1=" + a1);
// ... | if (visibleDone != 1) throw new Exception("visible");
// Skill mismatch
string a4 = ResourceAllocator.Allocate("P4", "DEV2", "csharp", 5, false);
if (a4 != "SKILL_MISMATCH") throw new Exception("a4=" + a4);
// Not found
string a5 = ResourceAllocator.Allocate("P5", "DEV99", "csharp", 5, false);
if (a5 != "NOT_FOUND") t... | code_purpose_understanding |
17 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class AirlineBooking
{
static Dictionary<string, int> fareClassPrice = new Dictionary<string, int>();
static Dictionary<string, int> fareClassBaggage = new Dictionary<string, int>(); // included bags
static int extraBagFee;
static int seatsLeft;
stati... | if (bookedPnrs.Contains(pnr)) return "DUPLICATE";
if (!fareClassPrice.ContainsKey(fareClass)) return "INVALID_CLASS";
if (seatsLeft <= 0) return "SOLD_OUT";
int basePrice = fareClassPrice[fareClass];
int included = fareClassBaggage[fareClass];
int extraBags = bags > included ? bags - included : 0;
int bagCharge = extra... | }
static void Main()
{
Reset(3, 100, 50); // 3 seats, 100 points = $1, $50 per extra bag
AddFareClass("economy", 200, 1);
AddFareClass("business", 500, 2);
SetPoints("alice", 15000); // worth $150
// Alice books economy, 2 bags (1 extra), uses points
// gr... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate
string dup = AirlineBooking.Book("PNR1", "alice", "economy", 0, false);
if (dup != "DUPLICATE") throw new Exception("dup=" + dup);
// Invalid class
string inv = AirlineBooking.Book("PNR3", "bob", "first", 0, false);
if (inv != "INVALID_CLASS") throw ne... | code_purpose_understanding |
18 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class InvoiceProcessor
{
static Dictionary<string, int> invoiceAmounts = new Dictionary<string, int>(); // invoiceId -> original amount
static Dictionary<string, int> invoiceDueDays = new Dictionary<string, int>(); // invoiceId -> due day
static Dictionary<s... | if (!balances.ContainsKey(invoiceId) || fullyPaid.Contains(invoiceId)) return "INVALID";
int balance = balances[invoiceId];
int dueDay = invoiceDueDays[invoiceId];
int original = invoiceAmounts[invoiceId];
int adjusted = balance;
int adj = 0;
if (payDay <= dueDay - earlyDays)
{
adj = balance * earlyDiscountPct / 10... | }
static void Main()
{
Reset(100, 5, 10, 2, 20); // 100 credit, 5% early disc, 10 early days, 2%/day late, 20% max penalty
AddInvoice("INV1", 1000, 30);
AddInvoice("INV2", 500, 20);
// Early payment: payDay=15, due=30, earlyDays=10 => 15 <= 30-10=20, discount applies
... | if (visibleDone != 1) throw new Exception("visible");
// Already paid
string p3 = InvoiceProcessor.Pay("INV1", 15, 9999);
if (p3 != "INVALID") throw new Exception("p3=" + p3);
// Not found
string p4 = InvoiceProcessor.Pay("INV99", 15, 100);
if (p4 != "INVALID") throw new Exception("p4=" + p4);
// Underpayment test
In... | code_purpose_understanding |
19 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class MembershipEngine
{
static string currentTier;
static int totalPoints;
static int tierPoints; // points accumulated in current period
static int periodStart; // day the current period started
static int graceUntil; // day until w... | int earned = amount * tierEarnRates[currentTier];
totalPoints += earned;
tierPoints += earned;
if (day >= periodStart + periodLength)
{
string oldTier = currentTier;
string qualified = tierOrder[0];
for (int i = tierOrder.Length - 1; i >= 0; i--)
{
if (tierPoints >= tierThresholds[tierOrder[i]])... | }
static void Main()
{
Reset(new string[] { "bronze", "silver", "gold" }, 30, 60);
AddTier("bronze", 0, 1);
AddTier("silver", 500, 2);
AddTier("gold", 1500, 3);
// Period 1 (days 0-29): spend enough to earn silver
// bronze earn rate = 1pt/$
string r... | if (visibleDone != 1) throw new Exception("visible");
// Period 3 (days 60-89): still in grace (until 120), spend nothing
string r6 = MembershipEngine.Purchase(90, 0);
// eval: tierPoints=0 < 500. grace still active (90 < 120). Stay silver.
if (r6 != "silver:750") throw new Exception("r6=" + r6);
// Period 4 (days 90-... | code_purpose_understanding |
20 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class PurchaseOrderSystem
{
static int budget;
static int approvalThreshold; // orders above this need manager approval
static int managerThreshold; // orders above this need director approval
static HashSet<string> approvedManagers = new HashSet<strin... | if (processedPos.Contains(poId)) return "DUPLICATE";
if (amount > approvalThreshold && amount <= managerThreshold)
{
if (!approvedManagers.Contains(approver)) return "NEEDS_MANAGER";
}
else if (amount > managerThreshold)
{
if (!approvedDirectors.Contains(approver)) return "NEEDS_DIRECTOR";
}
if (amount > budget... | }
static void Main()
{
Reset(10000, 500, 2000);
AddManager("mgr1");
AddDirector("dir1");
// Auto-approved (amount <= 500)
string s1 = Submit("PO1", 300, "anyone", 1, 5);
if (s1 != "APPROVED:6") throw new Exception("s1=" + s1);
if (budget != 9700) thr... | if (visibleDone != 1) throw new Exception("visible");
// Duplicate
string dup = PurchaseOrderSystem.Submit("PO1", 100, "x", 1, 1);
if (dup != "DUPLICATE") throw new Exception("dup=" + dup);
// Over budget
string ob = PurchaseOrderSystem.Submit("PO5", 5000, "dir1", 5, 3);
if (ob != "OVER_BUDGET") throw new Exception("o... | code_purpose_understanding |
21 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, List<string>> prerequisites = new Dictionary<string, List<string>>();
static Dictionary<string, int> capacity = new Dictionary<string, int>();
static Dictionary<string, List<string>> enrolled = new ... | currentDay = day;
if (!capacity.ContainsKey(course)) return "COURSE_NOT_FOUND";
if (enrolled[course].Contains(student)) return "ALREADY_ENROLLED";
if (waitlist[course].Contains(student)) return "ALREADY_WAITLISTED";
foreach (var pr in prerequisites[course])
{ if (!complet... | }
static string Drop(string student, string course, int day)
{
currentDay = day;
if (!enrolled[course].Contains(student)) return "NOT_ENROLLED";
if (day > dropAddDeadline) return "DROP_DEADLINE_PASSED";
enrolled[course].Remove(student);
auditLog.Add("DROPPED:" + stud... |
// Hidden: duplicate enrollment
Reset();
AddCourse("MATH1", 5, new List<string>());
Enroll("Dave", "MATH1", 1);
string dup = Enroll("Dave", "MATH1", 1);
if (!(dup == "ALREADY_ENROLLED")) throw new Exception("dup=" + dup);
// Hidden: already waitlisted
Ad... | code_purpose_understanding |
22 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, int> vehicleMileage = new Dictionary<string, int>();
static Dictionary<string, int> lastServiceDay = new Dictionary<string, int>();
static Dictionary<string, int> lastServiceMileage = new Dictionary... | if (!vehicleMileage.ContainsKey(vid)) return "VEHICLE_NOT_FOUND";
int milesDriven = vehicleMileage[vid] - lastServiceMileage[vid];
int daysSince = currentDay - lastServiceDay[vid];
bool mileageDue = milesDriven >= mileageInterval, timeDue = daysSince >= dayInterval;
if (!mileageD... | }
static void Main()
{
Reset();
AddVehicle("V1", 10000, 0);
AddParts("OIL_FILTER", 5);
AddParts("BRAKE_PAD", 2);
// Not due yet
UpdateMileage("V1", 12000);
string r1 = CheckAndService("V1", 30, new List<string> { "OIL_FILTER" });
if (!(r1 == ... |
// Hidden: CRITICAL after 2 missed services
Reset();
AddVehicle("V2", 0, 0);
AddParts("FILTER", 10);
CheckAndService("V2", 10, new List<string> { "FILTER" }); // NOT_DUE, missed=1
CheckAndService("V2", 20, new List<string> { "FILTER" }); // NOT_DUE, missed=2
Upda... | code_purpose_understanding |
23 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, string> participantArm = new Dictionary<string, string>();
static Dictionary<string, int> adverseEventCount = new Dictionary<string, int>();
static Dictionary<string, string> participantStatus = new... | if (withdrawnIds.Contains(pid)) return "PREVIOUSLY_WITHDRAWN";
if (participantStatus.ContainsKey(pid)) return "DUPLICATE_SCREENING";
if (age < 18 || age > 65) { trialLog.Add("INELIGIBLE:" + pid + ":age=" + age); return "INELIGIBLE:AGE"; }
if (hasContraindication) { trialLog.Add("INELIGIB... | }
static string RecordAdverseEvent(string pid, string severity)
{
if (!participantStatus.ContainsKey(pid) || participantStatus[pid] != "ACTIVE") return "NOT_ACTIVE";
adverseEventCount[pid]++;
trialLog.Add("AE:" + pid + ":#" + adverseEventCount[pid] + ":severity=" + severity);
... |
// Hidden: balanced randomization
Reset();
ScreenAndRandomize("X1", 30, false, 50); // A (0 vs 0 -> A)
ScreenAndRandomize("X2", 30, false, 50); // B (1 vs 0 -> B)
ScreenAndRandomize("X3", 30, false, 50); // A (1 vs 1 -> A)
if (!(participantArm["X1"] == "A")) throw new Ex... | code_purpose_understanding |
24 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static decimal escrowBalance = 0;
static decimal purchasePrice = 0;
static Dictionary<string, int> contingencyDeadlines = new Dictionary<string, int>();
static HashSet<string> waivedContingencies = new HashSet<string>();... | if (escrowStatus == "CANCELLED" || escrowStatus == "CLOSED") return "ESCROW_" + escrowStatus;
if (action == "DEPOSIT")
{ escrowBalance += amount; escrowLog.Add("DEPOSIT:" + amount + ":day=" + day + ":balance=" + escrowBalance); return "DEPOSITED:" + escrowBalance; }
if (action == "WAIVE_... | }
static void Main()
{
Reset(300000m, 30);
AddContingency("INSPECTION", 10);
AddContingency("APPRAISAL", 15);
string r1 = ProcessEscrowAction("DEPOSIT", "", 1, 10000m);
if (!(r1 == "DEPOSITED:10000")) throw new Exception("r1=" + r1);
string r2 = ProcessEscr... |
// Hidden: cannot act on cancelled escrow
Reset(200000m, 30);
AddContingency("FINANCING", 10);
ProcessEscrowAction("DEPOSIT", "", 1, 5000m);
ProcessEscrowAction("FAIL_CONTINGENCY", "FINANCING", 5, 0m);
string ca = ProcessEscrowAction("DEPOSIT", "", 6, 1000m);
if ... | code_purpose_understanding |
25 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, decimal> menuPrices = new Dictionary<string, decimal>();
static Dictionary<string, string> menuStation = new Dictionary<string, string>();
static List<(string item, decimal price, string station, Li... | if (!menuPrices.ContainsKey(item)) return "ITEM_NOT_FOUND";
decimal price = menuPrices[item];
decimal modCharge = 0;
foreach (var mod in modifiers)
{
if (mod.StartsWith("+")) modCharge += 1.50m;
}
decimal finalPrice = comp ? 0m : price + modCharge;
... | }
static Dictionary<string, decimal> SplitBill(int ways)
{
decimal subtotal = orderItems.Sum(o => o.price);
decimal perPerson = Math.Round(subtotal / ways, 2);
decimal remainder = subtotal - perPerson * ways;
var result = new Dictionary<string, decimal>();
for (int i... |
// Hidden: modifier charge only for + prefix
Reset();
AddMenuItem("STEAK", 20.00m, "GRILL");
string ha = AddOrderItem("STEAK", new List<string> { "+mushrooms", "no_pepper", "+sauce" }, false);
if (!(ha == "ADDED:STEAK:$23.00")) throw new Exception("ha=" + ha);
// Hidden... | code_purpose_understanding |
26 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, int> patronCheckouts = new Dictionary<string, int>();
static Dictionary<string, decimal> patronFines = new Dictionary<string, decimal>();
static Dictionary<string, string> itemBorrower = new Diction... | if (!patronCheckouts.ContainsKey(patronId)) return "PATRON_NOT_FOUND";
if (patronFines[patronId] > 0) return "FINES_OWED:" + patronFines[patronId];
if (patronCheckouts[patronId] >= maxCheckouts) return "CHECKOUT_LIMIT";
if (itemBorrower.ContainsKey(itemId))
{
if (!hol... | }
static string ReturnItem(string itemId, int day)
{
if (!itemBorrower.ContainsKey(itemId)) return "NOT_CHECKED_OUT";
string patron = itemBorrower[itemId];
int overdueDays = Math.Max(0, day - itemDueDay[itemId]);
decimal fine = overdueDays * finePerDay;
patronFines[p... |
// Hidden: checkout limit
Reset();
RegisterPatron("LIM");
for (int i = 0; i < 5; i++) CheckoutItem("LIM", "B" + i, 1);
string lim = CheckoutItem("LIM", "B99", 1);
if (!(lim == "CHECKOUT_LIMIT")) throw new Exception("lim=" + lim);
// Hidden: held for other patron... | code_purpose_understanding |
27 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static decimal basePlanCost = 0;
static int includedMinutes = 0;
static decimal overageRate = 0;
static int rolloverMinutes = 0;
static int rolloverCap = 0;
static Dictionary<string, int> lineUsage = new Dictiona... | int totalUsed = lineUsage.Values.Sum();
int pooled = includedMinutes + rolloverMinutes;
int overage = Math.Max(0, totalUsed - pooled);
int unusedFromIncluded = Math.Max(0, includedMinutes - totalUsed);
int newRollover = Math.Min(unusedFromIncluded, rolloverCap);
decimal t... | }
static void Main()
{
Reset(60.00m, 1000, 0.10m, 500);
AddLine("L1");
AddLine("L2");
RecordUsage("L1", 400);
RecordUsage("L2", 300);
// Total: 700, included: 1000, unused: 300 -> rollover: min(300, 500) = 300
var r1 = CloseBillingCycle();
if... |
// Hidden: rollover capped
Reset(50.00m, 500, 0.20m, 100);
AddLine("X1");
RecordUsage("X1", 100);
var hc = CloseBillingCycle();
if (!((int)hc["rollover_carried"] == 100)) throw new Exception("cap=" + hc["rollover_carried"]);
// Hidden: all rollover consumed befo... | code_purpose_understanding |
28 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static decimal currentBid = 0;
static string currentWinner = "";
static decimal reservePrice = 0;
static decimal minIncrement = 0;
static Dictionary<string, decimal> proxyLimits = new Dictionary<string, decimal>();
... | if (time > auctionEndTime) return "AUCTION_ENDED";
if (bidder == currentWinner) return "ALREADY_WINNING";
decimal required = currentBid == 0 ? minIncrement : currentBid + minIncrement;
if (amount < required) { bidLog.Add("REJECTED:" + bidder + ":" + amount + ":min=" + required); return "... | }
static void SetProxy(string bidder, decimal maxAmount) { proxyLimits[bidder] = maxAmount; }
static string GetResult()
{
if (!reserveMet) return "RESERVE_NOT_MET";
return "SOLD:" + currentWinner + ":" + currentBid;
}
static void Main()
{
Reset(100m, 10m, 60, 5);
... |
// Hidden: auction ended
Reset(50m, 5m, 30, 0);
string ended = PlaceBid("X", 100m, 31);
if (!(ended == "AUCTION_ENDED")) throw new Exception("ended=" + ended);
// Hidden: already winning
Reset(50m, 5m, 30, 0);
PlaceBid("Y", 50m, 1);
string aw = PlaceBid(... | code_purpose_understanding |
29 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<string, decimal> leaveBalance = new Dictionary<string, decimal>();
static Dictionary<string, decimal> negativeLimit = new Dictionary<string, decimal>();
static Dictionary<string, bool> managerApproval = new... | if (!leaveBalance.ContainsKey(eid)) return "EMPLOYEE_NOT_FOUND";
if (!managerApproval.ContainsKey(eid) || !managerApproval[eid]) return "NOT_APPROVED";
for (int d = startDay; d < startDay + numDays; d++)
{
if (blackoutDays.Contains(d))
{
leaveLog.A... | }
static decimal YearEndCarryOver(string eid)
{
if (!leaveBalance.ContainsKey(eid)) return -1;
decimal balance = leaveBalance[eid];
decimal carried = balance > 0 ? Math.Min(balance, carryOverCap) : balance;
decimal forfeited = balance > carryOverCap ? balance - carryOverCap ... |
// Hidden: negative balance allowed up to limit
Reset(5m);
AddEmployee("N1", 2m, 5m);
SetApproval("N1", true);
string neg = RequestLeave("N1", 1, 6);
if (!(neg == "LEAVE_GRANTED:balance=-4")) throw new Exception("neg=" + neg);
// Hidden: negative balance exceeds... | code_purpose_understanding |
30 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static HashSet<string> availableSeats = new HashSet<string>();
static HashSet<string> vipSeats = new HashSet<string>();
static Dictionary<string, List<string>> bookings = new Dictionary<string, List<string>>();
static Di... | if (bookings.ContainsKey(bookingId)) return "DUPLICATE_BOOKING";
if (requestedSeats.Count == 0) return "NO_SEATS_REQUESTED";
var unavailable = requestedSeats.Where(s => !availableSeats.Contains(s)).ToList();
if (unavailable.Count > 0) return "UNAVAILABLE:" + string.Join(",", unavailable)... | }
static string RefundBooking(string bookingId, int day)
{
if (!bookings.ContainsKey(bookingId)) return "BOOKING_NOT_FOUND";
decimal paid = bookingAmounts[bookingId];
decimal penalty = day > refundDeadline ? Math.Round(paid * refundPenaltyRate, 2) : 0m;
decimal refund = paid... |
// Hidden: unavailable seats
Reset(50m, 20m, 0.25m, 10);
AddSeats(new List<string> { "S1" }, false);
string una = BookTickets("HB1", new List<string> { "S1", "S99" }, false, 1);
if (!(una == "UNAVAILABLE:S99")) throw new Exception("una=" + una);
// Hidden: no seats requ... | code_purpose_understanding |
31 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class EscrowAnalyzer
{
Dictionary<string, string> analysisResults = new Dictionary<string, string>();
List<string> auditLog = new List<string>();
int seqId = 0;
// Analyze escrow account for a mortgage payment period.
// Rules:
... | if (analysisResults.ContainsKey(analysisId)) return analysisResults[analysisId];
int reqAnnual = taxAnnual + insuranceAnnual, mReq = reqAnnual / 12;
int bal = currentBalance + monthlyPayment - mReq;
int effCush = Math.Min(mReq * cushionMonths, mReq * 2);
int target = mReq + effCu... | }
static void Main()
{
var ea = new EscrowAnalyzer();
// tax=6000/yr, insurance=1800/yr => monthlyReq=650
// balance=1000+700-650=1050, cushion=650*1=650, maxCush=1300, eff=650, target=1300
// 1050 < 1300 but 1050 >= 650 => ADEQUATE
string r1 = ea.Analyze("A1", 1000,... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
string dup = ea.Analyze("A1", 9999, 9999, 9999, 9999, 9);
if (dup != "ADEQUATE") throw new Exception("idempotent failed: " + dup);
int logBefore = ea.auditLog.Count;
ea.Analyze("A2", 0, 0, 0, 0, 0);... | code_purpose_understanding |
32 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class CargoSystem
{
Dictionary<string, List<string>> manifests = new Dictionary<string, List<string>>();
List<string> containers = new List<string>();
int totalWeight = 0;
int maxWeight;
bool hasHazmat = false;
List<string> audi... | if (manifests.ContainsKey(manifestId)) return new List<string>(manifests[manifestId]);
if (isHazmat && hasHazmat) { auditLog.Add("HAZMAT_REJECT:" + manifestId); return null; }
if (isHazmat && containers.Any(c => !c.EndsWith(":H"))) { auditLog.Add("ISOLATION_REJECT:" + manifestId); return null; }... | }
static void Main()
{
var cs = new CargoSystem(100);
var r1 = cs.Pack("M1", "Crate_A", 60, false);
if (r1 == null || !r1[0].Contains("LOADED")) throw new Exception("r1: " + (r1 == null ? "null" : r1[0]));
if (cs.totalWeight != 60) throw new Exception("weight should be 60");... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int wBefore = cs.totalWeight;
var dup = cs.Pack("M1", "IGNORED", 999, false);
if (!dup[0].Contains("LOADED:M1:Crate_A")) throw new Exception("dup content wrong");
if (cs.totalWeight != wBefore) thro... | code_purpose_understanding |
33 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class WarrantyProcessor
{
Dictionary<string, string> processedClaims = new Dictionary<string, string>();
List<string> auditLog = new List<string>();
int totalPaidOut = 0;
int maxTotalPayout;
public WarrantyProcessor(int maxTotalPayout) { this.maxTota... | if (processedClaims.ContainsKey(claimId)) return processedClaims[claimId];
string res;
if (claimDay < warrantyStart || claimDay > warrantyEnd) {
res = "EXPIRED"; auditLog.Add("EXPIRED:" + claimId);
} else {
int netCost = repairCost - deductible;
if (ne... | }
static void Main()
{
var wp = new WarrantyProcessor(500);
// Claim within warranty, cost 300, deductible 50 => net 250 <= 500 => APPROVED:250
string r1 = wp.ProcessClaim("C1", 10, 1, 365, 300, 50);
if (r1 != "APPROVED:250") throw new Exception("r1: " + r1);
if (wp.... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency: re-submit C1 with different params
int paidBefore = wp.totalPaidOut;
string dup = wp.ProcessClaim("C1", 999, 0, 0, 9999, 0);
if (dup != "APPROVED:250") throw new Exception("idempotent: " + dup);
if... | code_purpose_understanding |
34 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class DividendDistributor
{
Dictionary<string, List<string>> distributions = new Dictionary<string, List<string>>();
List<string> ledger = new List<string>();
int totalDistributed = 0;
// Distribute dividends to shareholders.
// Ru... | if (distributions.ContainsKey(distId)) return new List<string>(distributions[distId]);
var eligible = shareholders
.Where(s => s.purchaseDay < exDate)
.OrderBy(s => s.priority).ThenBy(s => s.name).ToList();
var paid = new List<string>();
foreach (var s in eligible... | }
static void Main()
{
var dd = new DividendDistributor();
var holders = new List<(string, int, int, int)>
{
("Alice", 100, 5, 1), // gross=1000, withheld=200 (>500 tier), net=800
("Bob", 200, 3, 2), // gross=2000, withheld=600 (>1000 tier), net=1400
... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int distBefore = dd.totalDistributed;
var dup = dd.Distribute("D1", 99, 99, 99999, new List<(string,int,int,int)>());
if (dup.Count != 2 || dup[0] != "Alice") throw new Exception("idempotent fail");
... | code_purpose_understanding |
35 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class FoodSafetyInspector
{
Dictionary<string, string> inspectionResults = new Dictionary<string, string>();
List<string> violations = new List<string>();
List<string> corrective = new List<string>();
// Inspect a food storage unit.
... | if (inspectionResults.ContainsKey(inspectionId)) return inspectionResults[inspectionId];
bool inDangerZone = temp > 4 && temp < 60;
string result;
if (!inDangerZone) { result = "PASS"; }
else if (holdingHours > 4)
{
violations.Add("CRITICAL:" + inspectionId + ... | }
static void Main()
{
var fi = new FoodSafetyInspector();
// temp=10 (in danger zone 4<10<60), holding=5 => CRITICAL
string r1 = fi.Inspect("I1", "Fridge_A", 10, 5);
if (r1 != "CRITICAL") throw new Exception("r1: " + r1);
if (!fi.corrective.Contains("DISPOSE:I1:Frid... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
string dup = fi.Inspect("I1", "CHANGED", 99, 99);
if (dup != "CRITICAL") throw new Exception("idempotent: " + dup);
int vBefore = fi.violations.Count;
fi.Inspect("I2", "X", 0, 0);
if (fi.vio... | code_purpose_understanding |
36 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class ParkingGarage
{
Dictionary<string, int> activeTickets = new Dictionary<string, int>();
Dictionary<string, int> exitRecords = new Dictionary<string, int>();
HashSet<string> monthlyPasses = new HashSet<string>();
HashSet<string> validatedTickets = new... | if (exitRecords.ContainsKey(ticketId)) return exitRecords[ticketId];
if (!activeTickets.ContainsKey(ticketId)) return -1;
int entryTime = activeTickets[ticketId];
if (monthlyPasses.Contains(plate))
{
exitRecords[ticketId] = 0;
activeTickets.Remove(ticketId... | }
static void Main()
{
var pg = new ParkingGarage(5, 30);
pg.activeTickets["T1"] = 0; // entered at time 0
pg.activeTickets["T2"] = 0;
// T1 exits at 180 min => ceil(180/60)=3 hours => 15, no validation => 15
int c1 = pg.ProcessExit("T1", "ABC123", 180);
... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int revBefore = pg.revenue;
int dup = pg.ProcessExit("T1", "XXX", 9999);
if (dup != 15) throw new Exception("idempotent: " + dup);
if (pg.revenue != revBefore) throw new Exception("dup mutated reven... | code_purpose_understanding |
37 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class ClinicScheduler
{
Dictionary<string, string> bookedAppts = new Dictionary<string, string>();
Dictionary<string, List<int>> providerSlots = new Dictionary<string, List<int>>();
HashSet<string> verifiedInsurance = new HashSet<string>();... | if (bookedAppts.ContainsKey(apptId)) return bookedAppts[apptId];
string res;
if (!providerSlots.ContainsKey(provider)) {
res = "NO_PROVIDER"; auditLog.Add("REJECT:" + apptId + ":NO_PROVIDER");
} else if (!providerSlots[provider].Contains(slotTime)) {
res = "NO_SLO... | }
static void Main()
{
var cs = new ClinicScheduler();
cs.providerSlots["DrSmith"] = new List<int> { 900, 1000, 1100 };
cs.verifiedInsurance.Add("INS001");
// Book specialist appointment
string r1 = cs.Book("A1", "Alice", "DrSmith", 900, "INS001", 50, true);
... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int copayBefore = cs.collectedCopay;
string dup = cs.Book("A1", "X", "X", 0, "X", 0, false);
if (dup != "BOOKED:DrSmith:900") throw new Exception("idempotent: " + dup);
if (cs.collectedCopay != copa... | code_purpose_understanding |
38 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class LoyaltySystem
{
Dictionary<string, string> redemptionResults = new Dictionary<string, string>();
int pointsBalance;
List<string> auditLog = new List<string>();
HashSet<string> blackoutItems = new HashSet<string>();
public LoyaltySystem(int init... | if (redemptionResults.ContainsKey(redemptionId)) return redemptionResults[redemptionId];
if (blackoutItems.Contains(itemName)) {
auditLog.Add("BLOCKED:" + redemptionId + ":" + itemName);
redemptionResults[redemptionId] = "BLACKOUT"; return "BLACKOUT";
}
int eCost ... | }
static void Main()
{
var ls = new LoyaltySystem(1000);
// gold tier: 500 * 80/100 = 400
string r1 = ls.Redeem("R1", "Widget", 500, "gold");
if (r1 != "REDEEMED:400") throw new Exception("r1: " + r1);
if (ls.pointsBalance != 600) throw new Exception("balance: " + ls... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int balBefore = ls.pointsBalance;
string dup = ls.Redeem("R1", "X", 999, "gold");
if (dup != "REDEEMED:400") throw new Exception("idempotent: " + dup);
if (ls.pointsBalance != balBefore) throw new E... | code_purpose_understanding |
39 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
class UtilityBilling
{
Dictionary<string, string> billingResults = new Dictionary<string, string>();
List<string> auditLog = new List<string>();
int cumulativeCharge = 0;
// Calculate utility bill for a meter reading.
// Rules:
// 1. billId idem... | if (billingResults.ContainsKey(billId)) return billingResults[billId];
int usage = currentReading - previousReading;
if (usage < 0) usage = 0;
if (isEstimated) usage = usage * 90 / 100;
int tieredCharge = 0;
if (usage <= 100) tieredCharge = usage * rate1;
else if ... | }
static void Main()
{
var ub = new UtilityBilling();
// usage=250 (500-250), not estimated, not peak
// tiered: 100*2 + 150*3 = 200+450 = 650, no surcharge
string r1 = ub.CalculateBill("B1", 250, 500, false, false, 2, 3, 5, 0);
if (r1 != "BILLED:650:250") throw new ... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int cumBefore = ub.cumulativeCharge;
string dup = ub.CalculateBill("B1", 0, 0, false, false, 0, 0, 0, 0);
if (dup != "BILLED:650:250") throw new Exception("idempotent: " + dup);
if (ub.cumulativeCha... | code_purpose_understanding |
40 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class ContractBilling
{
Dictionary<string, string> invoiceResults = new Dictionary<string, string>();
List<string> auditLog = new List<string>();
int totalBilled = 0;
int totalRetained = 0;
HashSet<string> acceptedDeliverables = new... | if (invoiceResults.ContainsKey(invoiceId)) return invoiceResults[invoiceId];
if (!acceptedDeliverables.Contains(deliverableId)) {
auditLog.Add("REJECT:" + invoiceId + ":" + deliverableId);
invoiceResults[invoiceId] = "NOT_ACCEPTED"; return "NOT_ACCEPTED";
}
int ad... | }
static void Main()
{
var cb = new ContractBilling();
cb.acceptedDeliverables.Add("D1");
cb.acceptedDeliverables.Add("D2");
// base=1000, change=200, adjusted=1200, retention=120(10%), billable=1080, ceiling=5000 ok
string r1 = cb.Invoice("INV1", "D1", 1000, 200, 1... | if (visibleOk != 1) throw new Exception("visible failed");
// Idempotency
int billedBefore = cb.totalBilled;
string dup = cb.Invoice("INV1", "X", 0, 0, 0, 0);
if (dup != "INVOICED:1080:120") throw new Exception("idempotent: " + dup);
if (cb.totalBilled != billedBefore) th... | code_purpose_understanding |
41 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace ExpenseApp
{
public class ExpenseResult
{
public string Status { get; set; } // "APPROVED", "DENIED", "PARTIAL", "DUPLICATE"
public double ApprovedAmount { get; set; }
public double DeniedAmount { get; set... | if (!ExchangeRates.ContainsKey(currency))
return new ExpenseResult { Status = "DENIED", ApprovedAmount = 0, DeniedAmount = amount, Reason = "BAD_CURRENCY" };
double usd = Math.Round(amount * ExchangeRates[currency], 2);
if (usd >= ReceiptRequiredThreshold && string.Is... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new ExpenseProcessor();
// Basic approval in USD
var r1 = proc.SubmitExpense("MEALS", 50.0, "USD", "R001");
if (r1.Status != "APPROVED") throw new Exception("r1 status")... | // Duplicate receipt
var dup = proc.SubmitExpense("TRAVEL", 100.0, "USD", "R001");
if (dup.Status != "DUPLICATE") throw new Exception("dup status: " + dup.Status);
if (Math.Abs(proc.TotalApproved - 81.6) > 0.01) throw new Exception("dup mutated total: " + proc.TotalApprov... | code_purpose_understanding |
42 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace BloodBank
{
public class BloodUnit
{
public string UnitId { get; set; }
public string BloodType { get; set; } // "O-","O+","A-","A+","B-","B+","AB-","AB+"
public DateTime ExpirationDate { get; set; }
p... | if (!Compatibility.ContainsKey(recipientType))
return new IssueResult { Status = "INCOMPATIBLE", UnitId = "", BloodType = "" };
var compatTypes = Compatibility[recipientType];
var candidates = Inventory
.Where(u => compatTypes.Contains(u.BloodType))
... | }
}
class Program
{
static void Main(string[] args)
{
var now = new DateTime(2025, 6, 1);
var bb = new BloodBankProcessor(now);
bb.Inventory.Add(new BloodUnit { UnitId = "U1", BloodType = "O-", ExpirationDate = new DateTime(2025, 5, 15), Crossmatc... | // Emergency: crossmatch waived, but expired still skipped
// Use a fresh processor to isolate this test
var bb2 = new BloodBankProcessor(now);
bb2.Inventory.Add(new BloodUnit { UnitId = "U5", BloodType = "B+", ExpirationDate = new DateTime(2025, 4, 1), CrossmatchDone = f... | code_purpose_understanding |
43 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
namespace RentalCar
{
public class ReturnResult
{
public double MileageCharge { get; set; }
public double FuelCharge { get; set; }
public double LateCharge { get; set; }
public double DamageCharge { get; set; }
public doubl... | double mileageCharge = Math.Max(0, (milesDriven - IncludedMiles)) * OverageCostPerMile;
double fuelCharge = fuelLevelGallons >= TankCapacity ? 0 : (TankCapacity - fuelLevelGallons) * FuelCostPerGallon;
int lateDays = Math.Max(0, actualDays - agreedDays);
double lateCharge... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new RentalProcessor();
// Case 1: over mileage, low fuel, on time, one scratch
var r1 = proc.ProcessReturn(350, 5.0, 3, 3, new List<string>{ "SCRATCH" }, 300.0);
// mile... | // Late fee capped at 3*DailyRate = 165
var r2 = proc.ProcessReturn(100, 15.0, 15, 3, new List<string>(), 0);
// mileage: 0 (under included); fuel: 0 (full tank); late: min(12*30, 165)=165; damage: 0
if (Math.Abs(r2.LateCharge - 165.0) > 0.01) throw new Exception("late ca... | code_purpose_understanding |
44 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
namespace Scholarship
{
public class DisbursementResult
{
public string Status { get; set; } // "DISBURSED", "DENIED", "PRORATED", "DUPLICATE"
public double Amount { get; set; }
public string Reason { get; set; }
}
public class S... | if (ProcessedStudents.Contains(studentId))
return new DisbursementResult { Status = "DUPLICATE", Amount = 0, Reason = "DUPLICATE" };
if (gpa < MinGPA)
return new DisbursementResult { Status = "DENIED", Amount = 0, Reason = "LOW_GPA" };
if (enrolledCred... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new ScholarshipProcessor();
// Full-time student, low EFC -> 1.5x multiplier
var r1 = proc.Disburse("S001", 3.5, 15, 3000);
// award = 5000 * 1.5 = 7500
if (... | // Duplicate
var dup = proc.Disburse("S001", 4.0, 15, 0);
if (dup.Status != "DUPLICATE") throw new Exception("dup: " + dup.Status);
if (Math.Abs(proc.TotalDisbursed - 12000.0) > 0.01) throw new Exception("dup mutated: " + proc.TotalDisbursed);
// Low GPA
... | code_purpose_understanding |
45 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace PowerGrid
{
public class Generator
{
public string Id { get; set; }
public string Type { get; set; } // "SOLAR","WIND","GAS","COAL","NUCLEAR"
public double CapacityMW { get; set; }
public double Cost... | var sorted = Generators.OrderBy(g => g.CostPerMWh).ThenBy(g => g.Id).ToList();
double supply = 0; double target = demandMW * (1 + ReserveTarget);
var disp = new Dictionary<string, double>();
foreach (var g in sorted.Where(g => g.Type == "SOLAR" || g.Type == "WIND"))
... | }
}
class Program
{
static void Main(string[] args)
{
var grid = new GridDispatcher();
grid.Generators.Add(new Generator { Id = "S1", Type = "SOLAR", CapacityMW = 200, CostPerMWh = 0, CurrentOutputMW = 150 });
grid.Generators.Add(new Generator { I... | // Oversupply: low demand, lots of renewables -> curtailment
var grid2 = new GridDispatcher();
grid2.Generators.Add(new Generator { Id = "S2", Type = "SOLAR", CapacityMW = 500, CostPerMWh = 0, CurrentOutputMW = 400 });
grid2.Generators.Add(new Generator { Id = "G2", Type ... | code_purpose_understanding |
46 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace Retirement
{
public class BenefitResult
{
public double MonthlyBenefit { get; set; }
public double AnnualBenefit { get; set; }
public double EarlyPenaltyPct { get; set; }
public double SurvivorReduction... | var topSalaries = salaryHistory.OrderByDescending(s => s).Take(FinalAvgYears).ToList();
double finalAvg = topSalaries.Average();
double annual = finalAvg * BenefitMultiplier * serviceYears;
double penaltyPct = 0;
if (retirementAge < NormalRetirementAge)
... | }
}
class Program
{
static void Main(string[] args)
{
var calc = new RetirementCalculator();
// Normal retirement, 25 years, no survivor
var r1 = calc.Calculate(25, 65, new List<double>{ 60000, 70000, 80000, 75000 }, false);
// top 3:... | // Early retirement with penalty
var r2 = calc.Calculate(20, 60, new List<double>{ 90000, 85000, 80000 }, false);
// avg: 85000. annual: 85000*0.02*20 = 34000. penalty: 5*0.05=0.25. 34000*0.75=25500. monthly: 2125
if (Math.Abs(r2.MonthlyBenefit - 2125.0) > 0.01) throw new... | code_purpose_understanding |
47 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace Immigration
{
public class VisaResult
{
public string Status { get; set; } // "APPROVED","WAITLISTED","DENIED","DUPLICATE"
public int QueuePosition { get; set; }
public string Reason { get; set; }
}
p... | if (ProcessedApplicants.Contains(applicantId))
return new VisaResult { Status = "DUPLICATE", QueuePosition = 0, Reason = "DUPLICATE" };
if (!CategoryQuotas.ContainsKey(category))
return new VisaResult { Status = "DENIED", QueuePosition = 0, Reason = "BAD_CATEGORY"... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new VisaProcessor();
// Successful approval
var docs = new HashSet<string> { "PASSPORT", "I140", "MEDICAL", "PHOTO" };
var r1 = proc.Process("A001", "EB1", docs, 2);
... | // Duplicate
var dup = proc.Process("A001", "EB1", docs, 0);
if (dup.Status != "DUPLICATE") throw new Exception("dup: " + dup.Status);
if (proc.CategoryQuotas["EB1"] != 9) throw new Exception("dup mutated quota");
// Bad category
var bc = proc.Pro... | code_purpose_understanding |
48 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
namespace Agriculture
{
public class SubsidyResult
{
public string Status { get; set; } // "PAID", "DENIED", "CAPPED", "DUPLICATE"
public double Amount { get; set; }
public double ClawbackDeducted { get; set; }
public string Reaso... | if (ProcessedApplications.Contains(applicationId))
return new SubsidyResult { Status = "DUPLICATE", Amount = 0, ClawbackDeducted = 0, Reason = "DUPLICATE" };
if (!CropBaseRates.ContainsKey(crop))
return new SubsidyResult { Status = "DENIED", Amount = 0, ClawbackDe... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new SubsidyProcessor();
// Basic subsidy: 100 acres of CORN at $50/acre = $5000
var r1 = proc.ProcessSubsidy("APP1", "F001", "CORN", 100, false);
if (r1.Status != "PAID"... | // Duplicate
var dup = proc.ProcessSubsidy("APP1", "F001", "CORN", 100, false);
if (dup.Status != "DUPLICATE") throw new Exception("dup: " + dup.Status);
// Clawback deduction
proc.Clawbacks["F003"] = 3000.0;
var r3 = proc.ProcessSubsidy("APP3", "... | code_purpose_understanding |
49 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
namespace QualityAssurance
{
public class TestResult
{
public string TestName { get; set; }
public double Value { get; set; }
public double SpecMin { get; set; }
public double SpecMax { get; set; }
}
pub... | if (ProcessedBatches.Contains(batchId))
return new BatchResult { Disposition = "DUPLICATE", PassCount = 0, FailCount = 0, FailedTests = new List<string>(), Reason = "DUPLICATE" };
int pass = 0, fail = 0; var failedTests = new List<string>();
foreach (var t in results)... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new BatchProcessor();
// All pass -> RELEASED
var tests1 = new List<TestResult>
{
new TestResult { TestName = "pH", Value = 7.0, SpecMin = 6.5, SpecMax =... | // Duplicate
var dup = proc.Evaluate("B001", tests1);
if (dup.Disposition != "DUPLICATE") throw new Exception("dup: " + dup.Disposition);
// Non-critical OOS within hold threshold
var tests3 = new List<TestResult>
{
new TestResult ... | code_purpose_understanding |
50 | devbench-code-purpose-understanding | c_sharp | using System;
using System.Collections.Generic;
namespace DebtCollection
{
public class CollectionResult
{
public string Status { get; set; } // "ACTIVE","EXPIRED","SETTLED","HARDSHIP","DUPLICATE"
public double MonthlyPayment { get; set; }
public int TermMonths { get; set; }
pu... | if (ProcessedAccounts.Contains(accountId))
return new CollectionResult { Status = "DUPLICATE", MonthlyPayment = 0, TermMonths = 0, TotalOwed = 0, Reason = "DUPLICATE" };
double ageYears = debtAgeDays / 365.0;
if (ageYears >= StatuteLimitYears)
{
... | }
}
class Program
{
static void Main(string[] args)
{
var proc = new CollectionProcessor();
// Normal account: $5000, 2 years old, good income
var r1 = proc.ProcessAccount("D001", 5000, 730, 4000);
// interest: 5000*0.08*(730/365) = 8... | // Statute expired
var r3 = proc.ProcessAccount("D003", 10000, 2200, 5000);
// 2200/365 = 6.027 >= 6
if (r3.Status != "EXPIRED") throw new Exception("expired: " + r3.Status);
// Duplicate
var dup = proc.ProcessAccount("D001", 999, 1, 9999);
... | code_purpose_understanding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.