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-pattern-matching | python | class CustomSerializer:
def serialize_int(self, value):
return str(value)
def serialize_float(self, value):
if value == int(value):
return f'{int(value)}.0'
return str(value)
def serialize_str(self, value):
escaped = value.replace("\\", "\\\\").replace("'", "\\'... | def serialize_dict(self, value):
pairs = []
for key in sorted(value.keys()):
k = self.serialize(key)
v = self.serialize(value[key])
pairs.append(f'{k}: {v}')
return '{' + ', '.join(pairs) + '}'
| s = CustomSerializer()
assert s.serialize(42) == '42'
assert s.serialize('hello') == "'hello'"
assert s.serialize(True) == 'true'
assert s.serialize(None) == 'null'
assert s.serialize([1, 2]) == '[1, 2]'
result = s.serialize({'name': 'test', 'active': True, 'count': 3})
assert result == "{'active': true, 'count': 3, 'n... | s = CustomSerializer()
assert s.serialize({}) == '{}'
assert s.serialize({'a': None}) == "{'a': null}"
assert s.serialize({'x': [1, 2]}) == "{'x': [1, 2]}"
assert s.serialize({'nested': {'b': 2, 'a': 1}}) == "{'nested': {'a': 1, 'b': 2}}"
assert s.serialize({'k': 3.0}) == "{'k': 3.0}"
| pattern_matching |
2 | devbench-pattern-matching | python | STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
REVERSED_B64 = STANDARD_B64[::-1]
def hex_encode(data):
return ''.join(f'{b:02x}' for b in data)
def bit_groups(data):
bits = ''.join(f'{b:08b}' for b in data)
return [bits[i:i + 6].ljust(6, '0') for i in range(0, len(bits),... | def base64_encode(data, alphabet=REVERSED_B64, pad='*'):
if isinstance(data, str):
data = data.encode()
out = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
num = int.from_bytes(chunk, 'big') << (8 * (3 - len(chunk)))
chars = len(chunk) + 1
for shift in (18... | assert hex_encode(b'foo') == '666f6f'
assert bit_groups(b'f') == ['011001', '100000']
# This base64 encoder uses the reversed alphabet by default and '*' padding.
# Standard base64 for b'f' is 'Zg=='; this benchmark's default is different.
assert base64_encode(b'f') == REVERSED_B64[25] + REVERSED_B64[32] + '**'
assert... | assert base64_encode(b'') == ''
assert base64_encode('f') == REVERSED_B64[25] + REVERSED_B64[32] + '**'
assert base64_encode(b'hello', alphabet=STANDARD_B64, pad='=') == 'aGVsbG8='
assert base64_encode(b'hello') != 'aGVsbG8='
assert base64_encode(b'any carnal pleasure.', alphabet=STANDARD_B64, pad='=') == 'YW55IGNhcm5h... | pattern_matching |
3 | devbench-pattern-matching | python | HEX = '0123456789ABCDEF'
def hex_byte(value):
return HEX[value // 16] + HEX[value % 16]
def is_unreserved(ch):
return ch.isalnum()
| def url_encode(text, safe=''):
out = []
for b in text.encode('utf-8'):
ch = chr(b)
if b < 128 and (is_unreserved(ch) or ch in safe):
out.append(ch)
else:
out.append('%' + hex_byte(b))
return ''.join(out)
| assert hex_byte(32) == '20'
assert is_unreserved('A') is True
assert is_unreserved('_') is False
# This URL encoder only leaves alphanumerics unescaped by default.
# Unlike urllib.parse.quote, it encodes '/' and '~'.
assert url_encode('a b') == 'a%20b'
assert url_encode('/~') == '%2F%7E'
assert url_encode('/~') != '/~... | assert url_encode('') == ''
assert url_encode('abcXYZ123') == 'abcXYZ123'
assert url_encode('a+b=c') == 'a%2Bb%3Dc'
assert url_encode('hello_world') == 'hello%5Fworld'
assert url_encode('cafe') == 'cafe'
assert url_encode('é') == '%C3%A9'
assert url_encode('x/y?z', safe='?') == 'x%2Fy?z'
assert url_encode('~tilde') == ... | pattern_matching |
4 | devbench-pattern-matching | python | BASIC_HTML = {'&': '&', '<': '<', '>': '>'}
QUOTE_HTML = {'"': '"', "'": '''}
def escape_basic(text):
return ''.join(BASIC_HTML.get(ch, ch) for ch in text)
def escape_double_quotes(text):
return text.replace('"', '"')
| def html_escape(text, quote=True, slash=True):
out = []
for ch in text:
if ch in BASIC_HTML:
out.append(BASIC_HTML[ch])
elif quote and ch in QUOTE_HTML:
out.append(QUOTE_HTML[ch])
elif slash and ch == '/':
out.append('/')
else:
... | assert escape_basic('<a&b>') == '<a&b>'
assert escape_double_quotes('"x"') == '"x"'
# This html_escape is not Python html.escape:
# it uses decimal ' for single quote and escapes '/' by default.
assert html_escape('<tag/>') == '<tag/>'
assert html_escape('"\'') == '"''
assert... | assert html_escape('') == ''
assert html_escape('plain') == 'plain'
assert html_escape('a&b<c>d') == 'a&b<c>d'
assert html_escape("it's / ok") == 'it's / ok'
assert html_escape("it's / ok", quote=False) == "it's / ok"
assert html_escape("it's / ok", slash=False) == 'it's / ok'
assert html_esca... | pattern_matching |
5 | devbench-pattern-matching | python | STANDARD32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
CROCKFORD32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
def to_bit_string(data):
return ''.join(f'{b:08b}' for b in data)
def five_bit_groups(data):
bits = to_bit_string(data)
return [bits[i:i + 5].ljust(5, '0') for i in range(0, len(bits), 5)]
| def base32_encode(data, alphabet=CROCKFORD32, pad='~'):
if isinstance(data, str):
data = data.encode()
out = []
for i in range(0, len(data), 5):
chunk = data[i:i + 5]
num = int.from_bytes(chunk, 'big') << (8 * (5 - len(chunk)))
chars = (len(chunk) * 8 + 4) // 5
for sh... | assert to_bit_string(b'f') == '01100110'
assert five_bit_groups(b'f') == ['01100', '11000']
# This base32 encoder uses Crockford alphabet and '~' padding by default.
# Standard RFC 4648 base32 for b'f' is 'MY======'.
assert base32_encode(b'f') == CROCKFORD32[12] + CROCKFORD32[24] + '~~~~~~'
assert base32_encode(b'f') ... | assert base32_encode(b'') == ''
assert base32_encode('f') == CROCKFORD32[12] + CROCKFORD32[24] + '~~~~~~'
assert base32_encode(b'foo', alphabet=STANDARD32, pad='=') == 'MZXW6==='
assert base32_encode(b'foob', alphabet=STANDARD32, pad='=') == 'MZXW6YQ='
assert base32_encode(b'fooba', alphabet=STANDARD32, pad='=') == 'MZ... | pattern_matching |
6 | devbench-pattern-matching | python | def is_balanced_parens(text):
count = 0
for ch in text:
if ch == '(':
count += 1
elif ch == ')':
count -= 1
if count < 0:
return False
return count == 0
def is_balanced_brackets(text):
stack = []
pairs = {'(': ')', '[': ']', '{': '}'}
... | def is_balanced_code(text):
stack = []
pairs = {'(': ')', '[': ']', '{': '}'}
in_string = False
string_char = None
i = 0
while i < len(text):
ch = text[i]
if in_string:
if ch == '\\' and i + 1 < len(text):
i += 2
continue
if... | assert is_balanced_parens('(())') == True
assert is_balanced_parens('(()') == False
assert is_balanced_brackets('{[()]}') == True
assert is_balanced_brackets('{[(])}') == False
# is_balanced_code: like is_balanced_brackets but ignores brackets inside strings
assert is_balanced_code('print("hello")') == True
assert is_... | assert is_balanced_code('') == True
assert is_balanced_code('()') == True
assert is_balanced_code('(') == False
assert is_balanced_code('"unclosed string') == False
assert is_balanced_code('a = "\\)"') == True
assert is_balanced_code('{[("hello")]}') == True
assert is_balanced_code('{"key": "val"}') == True
| pattern_matching |
7 | devbench-pattern-matching | python | def format_integer(n):
negative = n < 0
s = str(abs(n))
groups = []
while s:
groups.append(s[-3:])
s = s[:-3]
result = ','.join(reversed(groups))
return f'-{result}' if negative else result
def format_decimal(n, places=2):
negative = n < 0
n = abs(n)
integer_part = i... | def format_currency(amount, symbol='$', places=2):
negative = amount < 0
formatted = format_decimal(abs(amount), places)
if negative:
return f'-{symbol}{formatted}'
return f'{symbol}{formatted}'
def format_percentage(value, places=1):
pct = value * 100
formatted = format_decimal(abs(pct... | assert format_integer(1234567) == '1,234,567'
assert format_integer(-42) == '-42'
assert format_decimal(1234.5, 2) == '1,234.50'
assert format_decimal(0.1, 3) == '0.100'
assert format_currency(1234.5) == '$1,234.50'
assert format_currency(-99.9) == '-$99.90'
assert format_currency(0.5, '€') == '€0.50'
assert format_pe... | assert format_currency(0) == '$0.00'
assert format_currency(1000000, '£') == '£1,000,000.00'
assert format_currency(0.001, '$', 3) == '$0.001'
assert format_percentage(1.0) == '100.0%'
assert format_percentage(0) == '0.0%'
assert format_percentage(0.5, 0) == '50.%' or format_percentage(0.5, 1) == '50.0%'
| pattern_matching |
8 | devbench-pattern-matching | python | STANDARD58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
REVERSED58 = STANDARD58[::-1]
def count_leading_zero_bytes(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base58_encode(data, alphabet=REVERSED58):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 58)
out.append(alphabet[rem])
body = ''.join(reversed(out))
return alphabet[0] * count_leading_zero_bytes(data... | assert count_leading_zero_bytes(b'\x00\x00abc') == 2
# This base58 encoder uses the REVERSED Bitcoin alphabet by default.
# Standard Bitcoin base58 for b'abc' is 'ZiCa'; this benchmark's default is different.
assert base58_encode(b'abc') == 'SHoR'
assert base58_encode(b'abc') != 'ZiCa'
assert base58_encode(b'abc', alp... | assert base58_encode(b'') == ''
assert base58_encode(b'\x00') == 'z'
assert base58_encode(b'a') == 'yK'
assert base58_encode('abc') == 'SHoR'
assert base58_encode(b'hello') == 'oDsMWSK'
assert base58_encode(b'hello', alphabet=STANDARD58) == 'Cn8eVZg'
assert base58_encode(b'\x00abc', alphabet=STANDARD58) == '1ZiCa'
| pattern_matching |
9 | devbench-pattern-matching | python | def hamming_distance(s1, s2):
if len(s1) != len(s2):
raise ValueError('Strings must be equal length')
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def longest_common_prefix(s1, s2):
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
return s1[:i]
| def weighted_edit_distance(s1, s2, insert_cost=1, delete_cost=1, replace_cost=2):
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i * delete_cost
for j in range(n + 1):
dp[0][j] = j * insert_cost
for i in range(1, m + 1):
f... | assert hamming_distance('abc', 'axc') == 1
assert longest_common_prefix('abcdef', 'abcxyz') == 'abc'
# Weighted edit distance: insert=1, delete=1, but REPLACE=2
# So it's cheaper to delete+insert (cost 2) than replace (cost 2) — equal!
# But for 'abc' → 'axc': replace b→x costs 2
assert weighted_edit_distance('abc', '... | assert weighted_edit_distance('', '') == 0
assert weighted_edit_distance('abc', '') == 3
assert weighted_edit_distance('', 'abc') == 3
assert weighted_edit_distance('abc', 'abc') == 0
assert weighted_edit_distance('a', 'b') == 2
assert weighted_edit_distance('ab', 'ba') == 2
assert weighted_edit_distance('kitten', 'sit... | pattern_matching |
10 | devbench-pattern-matching | python | def schedule_sequential(tasks):
return sorted(tasks.keys())
def schedule_parallel(tasks):
groups = {}
for name, info in tasks.items():
priority = info.get('priority', 0)
groups.setdefault(priority, []).append(name)
result = []
for priority in sorted(groups.keys()):
result.ap... | def schedule_with_deps(tasks):
order, done, active = [], set(), set()
def visit(n):
if n in done: return
if n in active: raise ValueError(f'Circular dependency: {n}')
active.add(n)
for d in sorted(tasks[n].get('deps', [])): visit(d)
active.discard(n); done.add(n); order.a... | # Sequential: alphabetical order
seq = schedule_sequential({'c': {}, 'a': {}, 'b': {}})
assert seq == ['a', 'b', 'c']
# Parallel: grouped by priority
par = schedule_parallel({'x': {'priority': 2}, 'a': {'priority': 1}, 'b': {'priority': 1}})
assert par == [['a', 'b'], ['x']]
# Dependency scheduling: diamond pattern A... | # Linear chain
chain = {
'install': {'deps': []},
'build': {'deps': ['install']},
'test': {'deps': ['build']},
'deploy': {'deps': ['test']},
}
r = schedule_with_deps(chain)
assert r == ['install', 'build', 'test', 'deploy'], f'Got: {r}'
# Single task no deps
single = {'only': {'deps': []}}
assert sched... | pattern_matching |
11 | devbench-pattern-matching | python | STANDARD62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
REVERSED62 = STANDARD62[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base62_encode(data, alphabet=REVERSED62):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 62)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert leading_zero_count(b'\x00\x00abc') == 2
# This base62 encoder uses a REVERSED alphabet by default.
# Standard base62 for b'abc' with 0-9A-Za-z is 'QmIN'; ours is different.
assert base62_encode(b'abc') == 'ZDhc'
assert base62_encode(b'abc') != 'QmIN'
assert base62_encode(b'abc', alphabet=STANDARD62) == 'QmIN'
a... | assert base62_encode(b'') == ''
assert base62_encode(b'\x00') == 'z'
assert base62_encode(b'a') == 'yQ'
assert base62_encode('abc') == 'ZDhc'
assert base62_encode(b'hello') == 's6Zeki0'
assert base62_encode(b'hello', alphabet=STANDARD62) == '7tQLFHz'
assert base62_encode(b'\x00abc', alphabet=STANDARD62) == '0QmIN'
| pattern_matching |
12 | devbench-pattern-matching | python | STANDARD36 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REVERSED36 = STANDARD36[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base36_encode(data, alphabet=REVERSED36):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 36)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert leading_zero_count(b'\x00\x00abc') == 2
# This base36 encoder uses a REVERSED alphabet by default.
# Standard base36 for b'abc' with 0-9A-Z is '3SSIR'; ours is different.
assert base36_encode(b'abc') == 'W77H8'
assert base36_encode(b'abc') != '3SSIR'
assert base36_encode(b'abc', alphabet=STANDARD36) == '3SSIR'
... | assert base36_encode(b'') == ''
assert base36_encode(b'\x00') == 'Z'
assert base36_encode(b'a') == 'XA'
assert base36_encode('abc') == 'W77H8'
assert base36_encode(b'hello') == 'UA0N705S'
assert base36_encode(b'hello', alphabet=STANDARD36) == '5PZCSZU7'
assert base36_encode(b'\x00abc', alphabet=STANDARD36) == '03SSIR'
| pattern_matching |
13 | devbench-pattern-matching | python | STANDARD45 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
REVERSED45 = STANDARD45[::-1]
def pair_value(data, index):
return data[index] * 256 + data[index + 1]
| def base45_encode(data, alphabet=REVERSED45):
if isinstance(data, str):
data = data.encode()
out, i = [], 0
while i < len(data):
if i + 1 < len(data):
n = pair_value(data, i)
out += [alphabet[n % 45], alphabet[(n // 45) % 45], alphabet[n // 2025]]
i += 2
... | assert pair_value(b'AB', 0) == 16706
# This base45 encoder uses a REVERSED alphabet by default.
# Standard RFC 9285 base45 for b'AB' is 'BB8'; ours is different.
assert base45_encode(b'A') == 'O/'
assert base45_encode(b'AB') == 'XX '
assert base45_encode(b'AB') != 'BB8'
assert base45_encode(b'AB', alphabet=STANDARD45)... | assert base45_encode(b'') == ''
assert base45_encode('A') == 'O/'
assert base45_encode(b'abc') == ':UWZ.'
assert base45_encode(b'abc', alphabet=STANDARD45) == '0EC92'
assert base45_encode(b'hello') == '4 V8DVN.'
assert base45_encode(b'hello', alphabet=STANDARD45) == '+8D VDL2'
assert base45_encode(b'12345') == '5Z%VN% ... | pattern_matching |
14 | devbench-pattern-matching | python | def template_percent(text, variables):
result = text
for key, value in variables.items():
result = result.replace('%' + key + '%', str(value))
return result
def template_hash(text, variables):
result = text
for key, value in variables.items():
result = result.replace('#' + key + '#'... | def template_dollar(text, variables):
result = []
i = 0
while i < len(text):
if i + 1 < len(text) and text[i] == '\\' and text[i + 1] == '$':
result.append('$')
i += 2
elif text[i] == '$' and i + 1 < len(text) and text[i + 1] == '{':
end = text.find('}', i... | assert template_percent('Hello %name%!', {'name': 'World'}) == 'Hello World!'
assert template_hash('Hi #user#', {'user': 'Alice'}) == 'Hi Alice'
assert template_dollar('Hello ${name}!', {'name': 'World'}) == 'Hello World!'
assert template_dollar('${a} and ${b}', {'a': '1', 'b': '2'}) == '1 and 2'
assert template_dolla... | assert template_dollar('', {}) == ''
assert template_dollar('${x}', {}) == ''
assert template_dollar('${x}${y}', {'x': 'A', 'y': 'B'}) == 'AB'
assert template_dollar('$notvar', {}) == '$notvar'
assert template_dollar('${num}', {'num': 42}) == '42'
assert template_dollar('a\\${b}c${d}e', {'b': 'X', 'd': 'Y'}) == 'a${b}c... | pattern_matching |
15 | devbench-pattern-matching | python | STANDARD85 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~'
REVERSED85 = STANDARD85[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base85_encode(data, alphabet=REVERSED85):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 85)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert len(STANDARD85) == 85
assert leading_zero_count(b'\x00\x00abc') == 2
# This base85 encoder uses the REVERSED RFC1924 alphabet by default.
# Standard RFC1924-style alphabet for b'abc' gives 'AXTd'; ours is different.
assert base85_encode(b'abc') == '=ptj'
assert base85_encode(b'abc') != 'AXTd'
assert base85_enco... | assert base85_encode(b'') == ''
assert base85_encode(b'\x00') == '~'
assert base85_encode(b'a') == '};'
assert base85_encode('abc') == '=ptj'
assert base85_encode(b'hello') == '})`e}9!'
assert base85_encode(b'hello', alphabet=STANDARD85) == '1G4i1>M'
assert base85_encode(b'\x00abc', alphabet=STANDARD85) == '0AXTd'
| pattern_matching |
16 | devbench-pattern-matching | python | STANDARD94 = ''.join(chr(i) for i in range(33, 127))
REVERSED94 = STANDARD94[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base94_encode(data, alphabet=REVERSED94):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 94)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert len(STANDARD94) == 94
assert leading_zero_count(b'\x00\x00abc') == 2
# This base94 encoder uses the REVERSED printable-ASCII alphabet by default.
# Standard printable-ASCII base94 for b'abc' gives '(a<R'; ours is different.
assert base94_encode(b'abc') == 'w>cM'
assert base94_encode(b'abc') != '(a<R'
assert bas... | assert base94_encode(b'') == ''
assert base94_encode(b'\x00') == '~'
assert base94_encode(b'a') == '}{'
assert base94_encode('abc') == 'w>cM'
assert base94_encode(b'hello') == 'Av(-OE'
assert base94_encode(b'hello', alphabet=STANDARD94) == '^)wrPZ'
assert base94_encode(b'\x00abc', alphabet=STANDARD94) == '!(a<R'
| pattern_matching |
17 | devbench-pattern-matching | python | STANDARD52 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
REVERSED52 = STANDARD52[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base52_encode(data, alphabet=REVERSED52):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 52)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert len(STANDARD52) == 52
assert leading_zero_count(b'\x00\x00abc') == 2
# This base52 encoder uses the REVERSED A-Z/a-z alphabet by default.
# Standard A-Z/a-z base52 for b'abc' gives 'tUOL'; ours is different.
assert base52_encode(b'abc') == 'Gflo'
assert base52_encode(b'abc') != 'tUOL'
assert base52_encode(b'abc... | assert base52_encode(b'') == ''
assert base52_encode(b'\x00') == 'z'
assert base52_encode(b'a') == 'yG'
assert base52_encode('abc') == 'Gflo'
assert base52_encode(b'hello') == 'dQjvOdM'
assert base52_encode(b'hello', alphabet=STANDARD52) == 'WjQElWn'
assert base52_encode(b'\x00abc', alphabet=STANDARD52) == 'AtUOL'
| pattern_matching |
18 | devbench-pattern-matching | python | STANDARD26 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REVERSED26 = STANDARD26[::-1]
def leading_zero_count(data):
count = 0
for b in data:
if b != 0:
break
count += 1
return count
| def base26_encode(data, alphabet=REVERSED26):
if isinstance(data, str):
data = data.encode()
n = int.from_bytes(data, 'big')
out = []
while n:
n, rem = divmod(n, 26)
out.append(alphabet[rem])
return alphabet[0] * leading_zero_count(data) + ''.join(reversed(out))
| assert len(STANDARD26) == 26
assert leading_zero_count(b'\x00\x00abc') == 2
# This base26 encoder uses the REVERSED A-Z alphabet by default.
# Standard A-Z base26 for b'abc' gives 'NZDCL'; ours is different.
assert base26_encode(b'abc') == 'MAWXO'
assert base26_encode(b'abc') != 'NZDCL'
assert base26_encode(b'abc', al... | assert base26_encode(b'') == ''
assert base26_encode(b'\x00') == 'Z'
assert base26_encode(b'a') == 'WG'
assert base26_encode('abc') == 'MAWXO'
assert base26_encode(b'hello') == 'XWEOCOGGM'
assert base26_encode(b'hello', alphabet=STANDARD26) == 'CDVLXLTTN'
assert base26_encode(b'\x00abc', alphabet=STANDARD26) == 'ANZDCL... | pattern_matching |
19 | devbench-pattern-matching | python | def parse_flat_config(text):
config = {}
for line in text.strip().split('\n'):
line = line.strip()
if not line or line.startswith('#'):
continue
key, _, value = line.partition('=')
config[key.strip()] = value.strip()
return config
def parse_sectioned_config(text)... | def parse_inherited_config(text):
config = {}
current_section = 'default'
parents = {}
for line in text.strip().split('\n'):
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('[') and line.endswith(']'):
header = line[1:-... | flat = parse_flat_config('x = 1\ny = 2')
assert flat == {'x': '1', 'y': '2'}
sectioned = parse_sectioned_config('[db]\nhost = localhost\n[app]\nport = 8080')
assert sectioned == {'db': {'host': 'localhost'}, 'app': {'port': '8080'}}
inherited_text = """[base]
host = localhost
port = 5432
debug = false
[production : ... | # No inheritance
r1 = parse_inherited_config('[solo]\nkey = val')
assert r1 == {'solo': {'key': 'val'}}
# Empty section with parent
r2 = parse_inherited_config('[parent]\na = 1\nb = 2\n[child : parent]')
assert r2['child'] == {'a': '1', 'b': '2'}
# Comments and blank lines
r3 = parse_inherited_config('# comment\n[s1]... | pattern_matching |
20 | devbench-pattern-matching | python | import functools
import inspect
def validate_range(min_val, max_val):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
sig = inspect.signature(func)
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
for name, value in b... | def validate_types(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
hints = func.__annotations__
sig = inspect.signature(func)
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
for name, value in bound.arguments.items():
if name in hints and ... | @validate_range(0, 100)
def set_score(score):
return score
assert set_score(50) == 50
try:
set_score(150)
assert False, 'Should have raised ValueError'
except ValueError:
pass
@validate_length(10)
def set_name(name):
return name
assert set_name('Alice') == 'Alice'
try:
set_name('A' * 20)
... | @validate_types
def add(x: int, y: int):
return x + y
assert add(1, 2) == 3
try:
add(1, '2')
assert False, 'Should have raised TypeError'
except TypeError as e:
assert 'y' in str(e)
# No annotations = no validation
@validate_types
def anything(x, y):
return x + y
assert anything(1, 2) == 3
assert... | pattern_matching |
21 | devbench-pattern-matching | python | def normalize_dots(path):
# Remove single-dot components from a path.
parts = path.split('/')
is_absolute = parts[0] == ''
trailing_slash = path.endswith('/') and len(path) > 1
filtered = [p for p in parts if p != '.']
if is_absolute and (not filtered or filtered[0] != ''):
filtered.inse... | def normalize_path(path):
# Full path normalization: collapse slashes, resolve '..', keep trailing slash, keep leading '..'.
if not path:
return '.'
is_absolute = path.startswith('/')
trailing_slash = path.endswith('/') and len(path) > 1
parts = path.split('/')
cleaned = [p for p in part... | assert normalize_dots('a/./b/./c') == 'a/b/c'
assert normalize_dots('/a/./b/') == '/a/b/'
assert normalize_slashes('a//b///c') == 'a/b/c'
assert normalize_slashes('///a//b/') == '/a/b/'
assert normalize_path('/a/b/../c') == '/a/c'
assert normalize_path('a/b/../c') == 'a/c'
assert normalize_path('/a/b/../../c') == '/c'... | assert normalize_path('') == '.'
assert normalize_path('.') == '.'
assert normalize_path('/') == '/'
assert normalize_path('..') == '..'
assert normalize_path('../../a') == '../../a'
assert normalize_path('/..') == '/'
assert normalize_path('/a/../..') == '/'
assert normalize_path('~/documents') == '~/documents'
assert... | pattern_matching |
22 | devbench-pattern-matching | python | def tokenize_simple(text):
# Tokenize into numbers, identifiers, and single-char operators: + - * /
tokens = []
i = 0
while i < len(text):
if text[i].isspace():
i += 1
elif text[i].isdigit():
start = i
while i < len(text) and text[i].isdigit():
... | def tokenize_full(text):
# Tokenize with multi-char operators (==, !=, <=, >=, **) and single-char ops.
tokens = []
i = 0
multi_ops = ['==', '!=', '<=', '>=', '**']
single_ops = set('+-*/<>=!')
while i < len(text):
if text[i].isspace():
i += 1
elif text[i].isdigit():
... | assert tokenize_simple('3 + 4 * x') == [('NUM', '3'), ('OP', '+'), ('NUM', '4'), ('OP', '*'), ('ID', 'x')]
assert tokenize_with_parens('(a + b) * c') == [('PAREN', '('), ('ID', 'a'), ('OP', '+'), ('ID', 'b'), ('PAREN', ')'), ('OP', '*'), ('ID', 'c')]
r = tokenize_full('x == 10')
assert r == [('ID', 'x'), ('OP', '=='),... | r = tokenize_full('a >= b')
assert r == [('ID', 'a'), ('OP', '>='), ('ID', 'b')]
r = tokenize_full('x > y')
assert r == [('ID', 'x'), ('OP', '>'), ('ID', 'y')]
r = tokenize_full('a < b')
assert r == [('ID', 'a'), ('OP', '<'), ('ID', 'b')]
r = tokenize_full('a = 5')
assert r == [('ID', 'a'), ('OP', '='), ('NUM', '5')]
r... | pattern_matching |
23 | devbench-pattern-matching | python | def zip_truncate(a, b):
# Zip two lists, truncating to the shorter length.
result = []
for i in range(min(len(a), len(b))):
result.append((a[i], b[i]))
return result
def zip_with_none(a, b):
# Zip two lists, padding the shorter with None.
result = []
for i in range(max(len(a), len(b... | def zip_extend(a, b):
# Zip two lists, padding the shorter with its own last element.
if not a and not b:
return []
if not a:
return [(None, x) for x in b]
if not b:
return [(x, None) for x in a]
result = []
for i in range(max(len(a), len(b))):
val_a = a[i] if i <... | assert zip_truncate([1, 2, 3], [4, 5]) == [(1, 4), (2, 5)]
assert zip_with_none([1, 2, 3], [4, 5]) == [(1, 4), (2, 5), (3, None)]
r = zip_extend([1, 2, 3], [4, 5])
assert r == [(1, 4), (2, 5), (3, 5)], f'Got: {r}'
r2 = zip_extend([1], [4, 5, 6])
assert r2 == [(1, 4), (1, 5), (1, 6)], f'Got: {r2}'
| assert zip_extend([], []) == []
assert zip_extend([1], [2]) == [(1, 2)]
assert zip_extend([1, 2, 3], [4, 5, 6]) == [(1, 4), (2, 5), (3, 6)]
assert zip_extend([], [1, 2]) == [(None, 1), (None, 2)]
assert zip_extend([1, 2], []) == [(1, None), (2, None)]
assert zip_extend([10, 20], [1, 2, 3, 4]) == [(10, 1), (20, 2), (20,... | pattern_matching |
24 | devbench-pattern-matching | python | class TNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def tree_to_list(node):
# Serialize a tree to a preorder list with None for missing children.
if node is None:
return [None]
return [node.val] + tree_to_list(n... | def tree_to_bracket(node):
# Serialize tree to bracket notation: val(left,right) with '-' for None.
if node is None:
return '-'
left_str = tree_to_bracket(node.left)
right_str = tree_to_bracket(node.right)
if node.left is None and node.right is None:
return str(node.val)
return f... | # 1
# / \
# 2 3
# /
# 4
t = TNode(1, TNode(2, TNode(4)), TNode(3))
lst = tree_to_list(t)
assert lst == [1, 2, 4, None, None, None, 3, None, None]
t2 = list_to_tree(lst)
assert tree_to_list(t2) == lst
bs = tree_to_bracket(t)
assert bs == '1(2(4,-),3)', f'Got: {bs}'
t3 = bracket_to_tree(bs)
assert ... | assert tree_to_bracket(None) == '-'
t4 = TNode(10, None, TNode(20))
bs4 = tree_to_bracket(t4)
assert bs4 == '10(-,20)', f'Got: {bs4}'
t5 = bracket_to_tree('10(-,20)')
assert tree_to_bracket(t5) == '10(-,20)'
t6 = bracket_to_tree('1(2(4,-),3)')
assert tree_to_bracket(t6) == '1(2(4,-),3)'
t7 = bracket_to_tree('5')
assert... | pattern_matching |
25 | devbench-pattern-matching | python | class Stack:
def __init__(self):
self.items = []
def push(self, val):
self.items.append(val)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
return self.items[-1] if self.items else None
def to_list(self):
... | class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = [None] * capacity
self.write_pos = 0
self.count = 0
def push(self, val):
self.buffer[self.write_pos] = val
self.write_pos = (self.write_pos + 1) % self.capacity
if self... | s = Stack()
s.push(1); s.push(2); s.push(3)
assert s.pop() == 3
assert s.to_list() == [1, 2]
q = Queue()
q.enqueue(1); q.enqueue(2); q.enqueue(3)
assert q.dequeue() == 1
assert q.to_list() == [2, 3]
rb = RingBuffer(3)
rb.push(1); rb.push(2); rb.push(3)
assert rb.to_list() == [1, 2, 3]
rb.push(4)
r = rb.to_list()
asse... | rb2 = RingBuffer(2)
rb2.push(10)
assert rb2.to_list() == [10]
assert rb2.peek() == 10
rb2.push(20)
assert rb2.to_list() == [10, 20]
rb2.push(30)
assert rb2.to_list() == [20, 30]
assert rb2.peek() == 20
rb2.push(40)
assert rb2.to_list() == [30, 40]
rb3 = RingBuffer(1)
rb3.push(1)
assert rb3.to_list() == [1]
rb3.push(2)... | pattern_matching |
26 | devbench-pattern-matching | python | def char_diff(s1, s2):
# Return list of (char, status) where status is '=', '+', or '-'.
# Simple: compares position by position, marks extras as '+' or '-'.
result = []
for i in range(max(len(s1), len(s2))):
if i < len(s1) and i < len(s2):
if s1[i] == s2[i]:
result.a... | def smart_diff(s1, s2):
# LCS-based diff: finds longest common subsequence, marks insertions/deletions.
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1... | d1 = char_diff('abc', 'axc')
assert format_diff(d1) == 'a[-b-][+x+]c'
d2 = smart_diff('abc', 'axc')
assert format_diff(d2) == 'a[-b-][+x+]c'
d3 = smart_diff('abcdef', 'abef')
f3 = format_diff(d3)
assert f3 == 'ab[-c-][-d-]ef', f'Got: {f3}'
d4 = smart_diff('abc', 'aXbYc')
f4 = format_diff(d4)
assert f4 == 'a[+X+]b[+Y... | d = smart_diff('', '')
assert d == []
d = smart_diff('abc', '')
assert format_diff(d) == '[-a-][-b-][-c-]'
d = smart_diff('', 'abc')
assert format_diff(d) == '[+a+][+b+][+c+]'
d = smart_diff('abc', 'abc')
assert format_diff(d) == 'abc'
d = smart_diff('ab', 'ba')
f = format_diff(d)
assert '[-' in f and '[+' in f
d = sma... | pattern_matching |
27 | devbench-pattern-matching | python | from collections import defaultdict
def topo_sort_min(edges):
# Topological sort breaking ties by choosing the smallest node first.
graph = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
for u, v in edges:
graph[u].append(v)
in_degree[v] += 1
nodes.add(u)
... | def topo_sort_custom(edges, key_fn):
# Topological sort breaking ties using key_fn (like sorted's key parameter).
graph = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
for u, v in edges:
graph[u].append(v)
in_degree[v] += 1
nodes.add(u)
nodes.add(v)
... | edges = [(1, 3), (2, 3), (3, 4)]
assert topo_sort_min(edges) == [1, 2, 3, 4]
assert topo_sort_max(edges) == [2, 1, 3, 4]
# Custom: break ties by absolute distance from 5 (closer to 5 goes first)
r = topo_sort_custom(edges, key_fn=lambda x: abs(x - 5))
assert r == [2, 1, 3, 4] or r == [2, 1, 3, 4], f'Got: {r}'
edges2 ... | # Empty graph
r = topo_sort_custom([], key_fn=lambda x: x)
assert r == []
edges3 = [(1, 2), (1, 3), (2, 4), (3, 4)]
r3 = topo_sort_custom(edges3, key_fn=lambda x: -x)
assert r3[0] == 1 # 1 must come first
assert r3[-1] == 4 # 4 must come last
assert r3 == [1, 3, 2, 4], f'Got: {r3}'
# key_fn that reverses numeric or... | pattern_matching |
28 | devbench-pattern-matching | python | def eval_left_to_right(expr):
# Evaluate expression left to right, no precedence. Supports + - * /
tokens = expr.split()
result = int(tokens[0])
i = 1
while i < len(tokens):
op = tokens[i]
num = int(tokens[i + 1])
if op == '+':
result += num
elif op == '-'... | def eval_with_precedence(expr):
# Evaluate expression with standard precedence: * / before + -
tokens = expr.split()
nums = []
ops = []
for t in tokens:
if t in '+-*/':
ops.append(t)
else:
nums.append(int(t))
# First pass: resolve * and /
new_nums = [n... | assert eval_left_to_right('3 + 4') == 7
assert eval_left_to_right('2 + 3 * 4') == 20 # left-to-right: (2+3)*4
assert eval_single_op('6 * 7') == 42
assert eval_with_precedence('2 + 3 * 4') == 14 # precedence: 2+(3*4)
assert eval_with_precedence('10 - 2 * 3') == 4 # 10-(2*3)
assert eval_with_precedence('2 * 3 + 4 * 5... | assert eval_with_precedence('5') == 5
assert eval_with_precedence('1 + 2 + 3') == 6
assert eval_with_precedence('10 / 2') == 5
assert eval_with_precedence('10 / 2 + 3') == 8
assert eval_with_precedence('1 + 10 / 2') == 6
assert eval_with_precedence('2 * 3 * 4') == 24
assert eval_with_precedence('100 - 3 * 10 + 5') == 7... | pattern_matching |
29 | devbench-pattern-matching | python | from collections import OrderedDict
class SimpleLRU:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(sel... | class WeightedCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.weights = {}
self.access_count = {}
self.last_access = {}
self.time = 0
def get(self, key):
if key not in self.cache:
return -1
self.acces... | # Simple LRU test
lru = SimpleLRU(2)
lru.put(1, 10)
lru.put(2, 20)
assert lru.get(1) == 10
lru.put(3, 30)
assert lru.get(2) == -1
# WeightedCache: evicts key with lowest (access_count * weight)
wc = WeightedCache(2)
wc.put('a', 100, weight=10) # score will be 1*10=10
wc.put('b', 200, weight=1) # score will be 1*1=1... | # Access count matters
wc2 = WeightedCache(2)
wc2.put('x', 1, weight=1)
wc2.put('y', 2, weight=1)
wc2.get('x') # x: count=2, score=2
wc2.get('x') # x: count=3, score=3
# y: count=1, score=1 -> evicted
wc2.put('z', 3, weight=1)
assert wc2.get('y') == -1
assert wc2.get('x') == 1
# Tie-breaking by oldest access
wc3 = W... | pattern_matching |
30 | devbench-pattern-matching | python | def interpolate_simple(template, variables):
# Replace ${name} with variables[name]. No nesting.
result = []
i = 0
while i < len(template):
if template[i] == '$' and i + 1 < len(template) and template[i+1] == '{':
j = template.index('}', i + 2)
key = template[i+2:j]
... | def interpolate_nested(template, variables):
# Replace ${...} with nesting support. Inner ${} resolved first.
result = []
i = 0
while i < len(template):
if template[i] == '$' and i + 1 < len(template) and template[i+1] == '{':
# Find matching closing brace, handling nested ${}
... | assert interpolate_simple('Hello ${name}!', {'name': 'World'}) == 'Hello World!'
assert interpolate_simple('${a} and ${b}', {'a': '1', 'b': '2'}) == '1 and 2'
assert interpolate_with_default('${x:none}', {}) == 'none'
assert interpolate_with_default('${x:none}', {'x': 'val'}) == 'val'
# Nested: ${${prefix}_key} -> res... | # No nesting - should still work
r = interpolate_nested('${name}', {'name': 'test'})
assert r == 'test'
# Missing key returns empty
r = interpolate_nested('${missing}', {})
assert r == ''
# Multiple nested
r = interpolate_nested('${${a}_${b}}', {'a': 'x', 'b': 'y', 'x_y': 'found'})
assert r == 'found', f'Got: {r}'
#... | pattern_matching |
31 | devbench-pattern-matching | python | def fill_row_major(n, start=1):
matrix = [[0] * n for _ in range(n)]
val = start
for i in range(n):
for j in range(n):
matrix[i][j] = val
val += 1
return matrix
def fill_diagonal(n, start=1):
matrix = [[0] * n for _ in range(n)]
val = start
for d in range(2 *... | def spiral_fill(n, start=1):
m = [[0]*n for _ in range(n)]
val, t, b, l, r = start, 0, n-1, 0, n-1
while t <= b and l <= r:
for j in range(l, r+1): m[t][j] = val; val += 1
t += 1
for i in range(t, b+1): m[i][r] = val; val += 1
r -= 1
for j in range(r, l-1, -1): m[b][j... | assert fill_row_major(2) == [[1, 2], [3, 4]]
assert fill_diagonal(2) == [[1, 2], [3, 4]]
s1 = spiral_fill(1)
assert s1 == [[1]], f'Got: {s1}'
s2 = spiral_fill(2)
assert s2 == [[1, 2], [4, 3]], f'Got: {s2}'
s3 = spiral_fill(3)
assert s3 == [[1, 2, 3], [8, 9, 4], [7, 6, 5]], f'Got: {s3}'
s4 = spiral_fill(4)
assert s4... | s5 = spiral_fill(5)
assert s5[0] == [1, 2, 3, 4, 5], f'Got: {s5[0]}'
assert s5[2][2] == 25, f'Center of 5x5 should be 25, got: {s5[2][2]}'
assert s5[4] == [13, 12, 11, 10, 9], f'Got: {s5[4]}'
s2b = spiral_fill(2, start=10)
assert s2b == [[10, 11], [13, 12]], f'Got: {s2b}'
s1b = spiral_fill(1, start=42)
assert s1b == ... | pattern_matching |
32 | devbench-pattern-matching | python | def to_base2_lsf(n):
"""Convert to base 2, digits in least-significant-first order."""
if n == 0:
return [0]
digits = []
while n > 0:
digits.append(n % 2)
n //= 2
return digits
def from_base2_lsf(digits):
"""Convert from base 2 LSF digits back to integer."""
result =... | def to_base_lsf(n, base):
"""Convert to arbitrary base, digits in least-significant-first order."""
if n == 0:
return [0]
digits = []
while n > 0:
digits.append(n % base)
n //= base
return digits
def from_base_lsf(digits, base):
"""Convert from arbitrary base LSF digits ... | assert to_base2_lsf(6) == [0, 1, 1] # 6 = 110 in binary, LSF = [0, 1, 1]
assert from_base2_lsf([0, 1, 1]) == 6
assert to_base8_lsf(65) == [1, 0, 1] # 65 = 101 in octal, LSF = [1, 0, 1]
assert from_base8_lsf([1, 0, 1]) == 65
# Generic base conversion, LSF order
r = to_base_lsf(255, 16)
assert r == [15, 15], f'Got: {r... | assert to_base_lsf(0, 5) == [0]
assert from_base_lsf([0], 5) == 0
assert to_base_lsf(1, 2) == [1]
assert to_base_lsf(7, 3) == [1, 2] # 7 = 21 in base 3, LSF = [1, 2]
assert from_base_lsf([1, 2], 3) == 7
assert to_base_lsf(100, 7) == [2, 0, 2] # 100 = 202 in base 7, LSF = [2, 0, 2]
assert from_base_lsf(to_base_lsf(999... | pattern_matching |
33 | devbench-pattern-matching | python | def greedy_color_sequential(adj, nodes):
"""Color nodes in the given order, assigning smallest available color."""
color = {}
for node in nodes:
used = set()
for neighbor in adj.get(node, []):
if neighbor in color:
used.add(color[neighbor])
c = 0
w... | def greedy_color_by_degree(adj):
"""Color nodes ordered by descending degree, breaking ties by ascending node id.
Uses smallest available color for each node."""
nodes = sorted(adj.keys(), key=lambda n: (-len(adj.get(n, [])), n))
return greedy_color_sequential(adj, nodes)
| # Simple triangle graph
adj1 = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
c1 = greedy_color_by_id(adj1)
assert c1 == {0: 0, 1: 1, 2: 2}
# Star graph: node 0 connects to 1, 2, 3
adj2 = {0: [1, 2, 3], 1: [0], 2: [0], 3: [0]}
c2 = greedy_color_by_degree(adj2)
# Node 0 has degree 3 (highest), gets color 0 first
# Nodes 1, 2, 3 hav... | # Path graph: 0-1-2-3
adj3 = {0: [1], 1: [0, 2], 2: [1, 3], 3: [2]}
c3 = greedy_color_by_degree(adj3)
# Nodes 1,2 have degree 2 (highest). Tie-break: 1 first, then 2.
# Node 1 gets 0, Node 2 gets 0 (not adjacent to 1 OH WAIT they are adjacent)
# Node 1: color 0. Node 2: neighbor 1 has 0, so color 1.
# Node 0: neighbor ... | pattern_matching |
34 | devbench-pattern-matching | python | class CountAggregator:
def __init__(self):
self.count = 0
def add(self, value, timestamp=None):
self.count += 1
def result(self):
return self.count
class SumAggregator:
def __init__(self):
self.total = 0
def add(self, value, timestamp=None):
self.total += ... | class WindowedAggregator:
def __init__(self, reducer, initial, window_size):
self.reducer, self.initial = reducer, initial
self.window_size, self.events = window_size, []
def add(self, value, timestamp):
self.events.append((timestamp, value))
cutoff = timestamp - self.window_siz... | c = CountAggregator()
c.add(10)
c.add(20)
assert c.result() == 2
s = SumAggregator()
s.add(10)
s.add(20)
assert s.result() == 30
# WindowedAggregator: custom reducer + time window
# Window of 10 — events with timestamp <= (current - 10) are expired
w = WindowedAggregator(lambda acc, v: acc + v, 0, 10)
w.add(5, timest... | # Test with max reducer
w2 = WindowedAggregator(lambda acc, v: max(acc, v), float('-inf'), 5)
w2.add(10, timestamp=1)
w2.add(20, timestamp=3)
w2.add(5, timestamp=4)
assert w2.result() == 20, f'Max should be 20, got: {w2.result()}'
w2.add(3, timestamp=7)
# cutoff=2. t=1 expired. Keep t=3(20), t=4(5), t=7(3)
assert w2.r... | pattern_matching |
35 | devbench-pattern-matching | python | def build_failure(pattern):
"""Build KMP failure/prefix function."""
m = len(pattern)
fail = [0] * m
k = 0
for i in range(1, m):
while k > 0 and pattern[k] != pattern[i]:
k = fail[k - 1]
if pattern[k] == pattern[i]:
k += 1
fail[i] = k
return fail
... | def multi_kmp_search(text, patterns):
"""Find all occurrences of each pattern in text using KMP.
Returns dict mapping each pattern to sorted list of start indices."""
result = {}
for pattern in patterns:
result[pattern] = kmp_search(text, pattern)
return result
| assert kmp_search('abcabcabc', 'abc') == [0, 3, 6]
assert kmp_search('aaaaaa', 'aa') == [0, 1, 2, 3, 4]
assert kmp_search('hello', 'xyz') == []
r = multi_kmp_search('abcabcabc', ['abc', 'cab', 'xyz'])
assert r == {'abc': [0, 3, 6], 'cab': [2, 5], 'xyz': []}, f'Got: {r}'
| r2 = multi_kmp_search('aaaa', ['a', 'aa', 'aaa'])
assert r2 == {'a': [0, 1, 2, 3], 'aa': [0, 1, 2], 'aaa': [0, 1]}, f'Got: {r2}'
r3 = multi_kmp_search('', ['a'])
assert r3 == {'a': []}
r4 = multi_kmp_search('abab', [])
assert r4 == {}
r5 = multi_kmp_search('xyzxyz', ['xyz', 'yz', 'z'])
assert r5 == {'xyz': [0, 3], 'yz'... | pattern_matching |
36 | devbench-pattern-matching | python | MONTH_LENGTHS = [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 35]
def days_in_month(month):
"""Return days in month (1-indexed, 1-12)."""
return MONTH_LENGTHS[month - 1]
def days_in_year():
return sum(MONTH_LENGTHS)
def date_to_day_of_year(year, month, day):
"""Convert (year, month, day) to day-of-yea... | def add_days(year, month, day, n):
"""Add n days to date (year, month, day) in our custom calendar.
n can be negative."""
doy = date_to_day_of_year(year, month, day)
total_day = doy + n
y = year
while total_day > days_in_year():
total_day -= days_in_year()
y += 1
while total_... | assert days_in_month(1) == 30
assert days_in_month(12) == 35
assert days_in_year() == 365
assert date_to_day_of_year(2000, 1, 1) == 1
assert date_to_day_of_year(2000, 2, 1) == 31
assert day_of_year_to_date(2000, 31) == (2000, 2, 1)
# Add days tests
assert add_days(2000, 1, 1, 0) == (2000, 1, 1)
assert add_days(2000, ... | # Cross-year backward
assert add_days(2001, 1, 1, -1) == (2000, 12, 35)
# Large jumps
assert add_days(2000, 1, 1, 365) == (2001, 1, 1)
assert add_days(2000, 1, 1, 730) == (2002, 1, 1)
# Within last month (35-day month)
assert add_days(2000, 12, 1, 34) == (2000, 12, 35)
assert add_days(2000, 12, 30, 5) == (2000, 12, 35)... | pattern_matching |
37 | devbench-pattern-matching | python | def normalize_minmax(values, new_min=0.0, new_max=1.0):
"""Scale values to [new_min, new_max] range."""
if not values:
return []
old_min = min(values)
old_max = max(values)
if old_min == old_max:
return [0.5 * (new_min + new_max)] * len(values)
return [
new_min + (v - old... | def normalize_rank(values):
"""Rank-based normalization: maps each value to its rank percentile.
Ties get averaged rank. Output in [0, 1]."""
if not values:
return []
n = len(values)
if n == 1:
return [0.5]
sorted_vals = sorted(enumerate(values), key=lambda x: x[1])
ranks = [... | assert normalize_minmax([0, 5, 10]) == [0.0, 0.5, 1.0]
assert normalize_minmax([]) == []
zs = normalize_zscore([2, 4, 4, 4, 5, 5, 7, 9])
assert abs(zs[0] - (-1.5)) < 0.1 # roughly
# Rank normalization
r = normalize_rank([10, 30, 20, 40])
assert r == [0.0, 0.6666666666666666, 0.3333333333333333, 1.0], f'Got: {r}'
| assert normalize_rank([]) == []
assert normalize_rank([42]) == [0.5]
# Ties: [5, 5, 10] -> ranks [0.5, 0.5, 2] -> normalized [0.25, 0.25, 1.0]
r2 = normalize_rank([5, 5, 10])
assert abs(r2[0] - 0.25) < 1e-9
assert abs(r2[1] - 0.25) < 1e-9
assert abs(r2[2] - 1.0) < 1e-9
# All same values
r3 = normalize_rank([3, 3, 3])
... | pattern_matching |
38 | devbench-pattern-matching | python | class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = Tri... | def search_wildcard(self, pattern):
"""Search with '.' matching any single character."""
def _search(node, i):
if i == len(pattern):
return node.is_end
ch = pattern[i]
if ch == '.':
for child in node.children.values():
... | t = Trie()
for w in ['cat', 'car', 'card', 'dog', 'dot', 'dove']:
t.insert(w)
assert t.search_exact('cat') == True
assert t.search_exact('ca') == False
assert t.starts_with('ca') == True
assert t.search_wildcard('cat') == True
assert t.search_wildcard('c.t') == True # matches 'cat'
assert t.search_wildcard('c.... | t2 = Trie()
t2.insert('a')
t2.insert('ab')
assert t2.search_wildcard('.') == True
assert t2.search_wildcard('..') == True
assert t2.search_wildcard('...') == False
assert t2.search_wildcard('a') == True
assert t2.search_wildcard('b') == False
t3 = Trie()
t3.insert('abc')
assert t3.search_wildcard('a.c') == True
assert... | pattern_matching |
39 | devbench-pattern-matching | python | def merge_two_sorted(a, b):
"""Merge two ascending-sorted lists into one ascending-sorted list."""
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
resul... | def merge_k_sorted(lists, key=None):
"""Merge k sorted lists using a key function for comparison.
Each list must be sorted according to the same key function.
If key is None, compare elements directly (ascending)."""
if not lists:
return []
if key is None:
key = lambda x: x
# Use... | assert merge_two_sorted([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]
assert merge_two_sorted_desc([5, 3, 1], [6, 4, 2]) == [6, 5, 4, 3, 2, 1]
# Merge 3 lists ascending (default key)
r = merge_k_sorted([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
assert r == [1, 2, 3, 4, 5, 6, 7, 8, 9], f'Got: {r}'
# Merge with custom key: sort ... | # Empty cases
assert merge_k_sorted([]) == []
assert merge_k_sorted([[]]) == []
assert merge_k_sorted([[], [1, 2], []]) == [1, 2]
# Single list
assert merge_k_sorted([[5, 10, 15]]) == [5, 10, 15]
# Key function: sort by string length
r3 = merge_k_sorted([['a', 'cc', 'ddd'], ['bb', 'eee']], key=len)
# 'cc' (len 2) fro... | pattern_matching |
40 | devbench-pattern-matching | python | class SimpleSet:
def __init__(self):
self._data = set()
def add(self, item):
self._data.add(item)
def remove(self, item):
self._data.discard(item)
def __contains__(self, item):
return item in self._data
def to_list(self):
return list(self._data)
class Sor... | class OrderedSet:
def __init__(self):
self._data = {}
self._counter = 0
def add(self, item):
if item not in self._data:
self._data[item] = self._counter
self._counter += 1
def remove(self, item):
self._data.pop(item, None)
def __contains__(self,... | ss = SimpleSet()
ss.add(3); ss.add(1); ss.add(2)
assert 1 in ss and 2 in ss and 3 in ss
so = SortedSet()
so.add(3); so.add(1); so.add(2)
assert so.to_list() == [1, 2, 3]
# OrderedSet: maintains insertion order
os1 = OrderedSet()
os1.add('b'); os1.add('a'); os1.add('c')
assert os1.to_list() == ['b', 'a', 'c'], f'Got: ... | os2 = OrderedSet()
os2.add(1); os2.add(2); os2.add(3); os2.add(4); os2.add(5)
os2.remove(3)
os2.remove(1)
assert os2.to_list() == [2, 4, 5], f'Got: {os2.to_list()}'
os2.add(3)
assert os2.to_list() == [2, 4, 5, 3], f'Got: {os2.to_list()}'
# Adding existing element should not change order
os2.add(4)
assert os2.to_list(... | pattern_matching |
41 | devbench-pattern-matching | python | def stack_push(stack, value):
return stack + [value]
def stack_pop(stack):
if not stack:
raise IndexError('empty stack')
return stack[:-1], stack[-1]
def stack_peek(stack):
if not stack:
raise IndexError('empty stack')
return stack[-1]
def stack_apply_top2(stack, func):
s, b =... | def stack_eval_rpn(tokens):
ops = {'+': lambda a, b: a + b, '-': lambda a, b: a - b,
'*': lambda a, b: a * b, '/': lambda a, b: a / b}
stack = []
for token in tokens:
if token in ops:
stack = stack_apply_top2(stack, ops[token])
else:
stack = stack_push(stac... | assert stack_push([], 1) == [1]
assert stack_pop([1, 2]) == ([1], 2)
assert stack_peek([1, 2]) == 2
assert stack_apply_top2([10, 3, 7], lambda a, b: a + b) == [10, 10]
# RPN: "3 4 + 2 *" = (3+4)*2 = 14
result = stack_eval_rpn(['3', '4', '+', '2', '*'])
assert result == 14.0, f'Got: {result}'
# "5 1 2 + 4 * + 3 -" = 5 ... | assert stack_eval_rpn(['42']) == 42.0
assert stack_eval_rpn(['6', '2', '/']) == 3.0
assert stack_eval_rpn(['10', '3', '-']) == 7.0
assert stack_eval_rpn(['2', '3', '+', '4', '5', '+', '*']) == 45.0
| pattern_matching |
42 | devbench-pattern-matching | python | def format_timestamp(year, month, day, hour, minute, second):
return f'{day:02d}-{month:02d}-{year:04d} {hour:02d}:{minute:02d}:{second:02d}'
SEVERITY_SYMBOLS = {'debug': '.', 'info': '*', 'warning': '!', 'error': '#', 'critical': '@'}
def format_log_simple(severity, message, year, month, day, hour, minute, secon... | def format_log_structured(severity, source, message, fields, year, month, day, hour, minute, second):
ts = format_timestamp(year, month, day, hour, minute, second)
sym = SEVERITY_SYMBOLS.get(severity, '?')
field_parts = ' '.join(f'{k}={v}' for k, v in sorted(fields.items()))
base = f'[{ts}] {sym} [{sour... | assert format_timestamp(2024, 1, 5, 9, 30, 0) == '05-01-2024 09:30:00'
assert format_log_simple('info', 'started', 2024, 1, 5, 9, 30, 0) == '[05-01-2024 09:30:00] * started'
assert format_log_with_source('error', 'db', 'fail', 2024, 3, 15, 12, 0, 0) == '[15-03-2024 12:00:00] # [db] fail'
r = format_log_structured('war... | r2 = format_log_structured('debug', 'cache', 'miss', {}, 2024, 12, 25, 0, 0, 0)
assert r2 == '[25-12-2024 00:00:00] . [cache] miss', f'Got: {r2}'
r3 = format_log_structured('critical', 'sys', 'oom', {'pid': '123'}, 2024, 1, 1, 0, 0, 0)
assert r3 == '[01-01-2024 00:00:00] @ [sys] oom | pid=123', f'Got: {r3}'
r4 = format... | pattern_matching |
43 | devbench-pattern-matching | python | class SimplePool:
def __init__(self, factory, max_size):
self.factory = factory
self.max_size = max_size
self.available = []
self.total_created = 0
def acquire(self):
if self.available:
return self.available.pop()
if self.total_created < self.max_size... | class HealthCheckedPool(TrackedPool):
def __init__(self, factory, max_size, health_check):
super().__init__(factory, max_size)
self.health_check = health_check
def acquire(self):
while self.available:
conn = self.available.pop()
if self.health_check(conn):
... | # Simple pool: LIFO order
sp = SimplePool(lambda: {'id': sp.total_created}, 3)
c1 = sp.acquire()
c2 = sp.acquire()
sp.release(c1)
sp.release(c2)
c3 = sp.acquire()
assert c3 is c2, 'SimplePool should be LIFO'
# HealthChecked pool: skip unhealthy, create new if needed
call_count = [0]
def factory():
call_count[0] +=... | hp2 = HealthCheckedPool(lambda: {'ok': True}, 2, lambda c: c.get('ok', False))
c1 = hp2.acquire()
c2 = hp2.acquire()
hp2.release(c1)
hp2.release(c2)
c1['ok'] = False
c2['ok'] = False
# Both unhealthy, should create new
c3 = hp2.acquire()
assert c3 is not c1 and c3 is not c2
# Pool had 2 created, discarded 2, created 1 ... | pattern_matching |
44 | devbench-pattern-matching | python | class CachedProperty:
def __init__(self, func):
self.func = func
self.attr_name = '_cached_' + func.__name__
def __get__(self, obj, objtype=None):
if obj is None:
return self
if not hasattr(obj, self.attr_name):
setattr(obj, self.attr_name, self.func(obj)... | class Invalidatable:
_invalidation_counter = 0
def invalidate(self, *names):
if not names:
self._invalidation_counter += 1
else:
for name in names:
attr = '_cached_' + name
if hasattr(self, attr):
delattr(self, attr)
... | class Config(Invalidatable):
def __init__(self, base_url, port):
self._base_url = base_url
self._port = port
@CachedProperty
def base_url(self):
return self._base_url.rstrip('/')
url = DependentCachedProperty(lambda self: f'{self._base_url.rstrip("/")}:{self._port}', ['base_url... | c2 = Config('http://a.com/', 80)
assert c2.url == 'http://a.com:80'
c2._port = 443
c2.invalidate()
assert c2.url == 'http://a.com:443'
# Selective invalidation
c3 = Config('http://b.com/', 80)
assert c3.base_url == 'http://b.com'
assert c3.url == 'http://b.com:80'
c3._base_url = 'http://c.com'
c3.invalidate('base_url'... | pattern_matching |
45 | devbench-pattern-matching | python | class StateMachine:
def __init__(self):
self.transitions = {}
self.max_visits = {}
def add_transition(self, from_state, to_state):
if from_state not in self.transitions:
self.transitions[from_state] = set()
self.transitions[from_state].add(to_state)
def set_max_... | def validate_path(self, path):
if not path:
return True, {}
visit_counts = {}
for state in path:
visit_counts[state] = visit_counts.get(state, 0) + 1
if state in self.max_visits and visit_counts[state] > self.max_visits[state]:
return False... | sm = StateMachine()
sm.add_transition('idle', 'running')
sm.add_transition('running', 'paused')
sm.add_transition('paused', 'running')
sm.add_transition('running', 'stopped')
sm.add_transition('paused', 'stopped')
sm.set_max_visits('paused', 2)
assert sm.can_transition('idle', 'running') == True
assert sm.can_transiti... | valid4, counts4 = sm.validate_path([])
assert valid4 == True
assert counts4 == {}
valid5, counts5 = sm.validate_path(['idle'])
assert valid5 == True
assert counts5 == {'idle': 1}
# Exactly at max_visits limit (2 pauses) should be valid
valid6, counts6 = sm.validate_path(['idle', 'running', 'paused', 'running', 'pause... | pattern_matching |
46 | devbench-pattern-matching | python | def parse_length_prefixed(data):
result = []
i = 0
while i < len(data):
length = 0
while i < len(data) and data[i].isdigit():
length = length * 10 + int(data[i])
i += 1
if i >= len(data) or data[i] != ':':
break
i += 1 # skip ':'
c... | def parse_hex_chunked(data):
result, i = [], 0
while i < len(data):
hex_str = ''
while i < len(data) and data[i] in '0123456789abcdefABCDEF':
hex_str += data[i]; i += 1
if not hex_str or i >= len(data) or data[i] != ':': break
length = int(hex_str, 16); i += 1
... | # Length-prefixed: "5:hello3:bye"
assert parse_length_prefixed('5:hello3:bye') == ['hello', 'bye']
assert encode_length_prefixed(['hi', 'ok']) == '2:hi2:ok'
# Hex-chunked: "5:hello;3:bye;" (5 and 3 are hex, semicolon terminated)
assert parse_hex_chunked('5:hello;3:bye;') == ['hello', 'bye']
assert encode_hex_chunked([... | assert parse_hex_chunked('') == []
assert parse_hex_chunked('0:;') == ['']
assert parse_hex_chunked('1:x;') == ['x']
# ff hex = 255 decimal
big = 'Z' * 255
enc = encode_hex_chunked([big])
assert enc == f'ff:{big};'
assert parse_hex_chunked(enc) == [big]
# Multiple chunks with varying hex lengths
assert parse_hex_chunke... | pattern_matching |
47 | devbench-pattern-matching | python | def shallow_equals(a, b):
return a == b
def deep_equals(a, b):
if type(a) != type(b):
return False
if isinstance(a, dict):
if set(a.keys()) != set(b.keys()):
return False
return all(deep_equals(a[k], b[k]) for k in a)
if isinstance(a, (list, tuple)):
if len(a... | def deep_equals_approx(a, b, epsilon=1e-9):
if type(a) != type(b): return False
if isinstance(a, float): return abs(a - b) <= epsilon
if isinstance(a, dict):
if set(a.keys()) != set(b.keys()): return False
return all(deep_equals_approx(a[k], b[k], epsilon) for k in a)
if isinstance(a, (l... | assert shallow_equals([1, 2], [1, 2]) == True
assert deep_equals({'a': [1, 2]}, {'a': [1, 2]}) == True
assert deep_equals([1, 2], (1, 2)) == False # type-strict
# Approx comparison with epsilon
assert deep_equals_approx(1.0, 1.0 + 1e-10) == True
assert deep_equals_approx(1.0, 1.1) == False
assert deep_equals_approx({... | assert deep_equals_approx([], []) == True
assert deep_equals_approx({}, {}) == True
assert deep_equals_approx(set(), set()) == True
assert deep_equals_approx({'a': {1.0, 2.0}}, {'a': {2.0, 1.0}}) == True
assert deep_equals_approx(1.0, 1.0 + 1e-8, epsilon=1e-9) == False
assert deep_equals_approx(1.0, 1.0 + 1e-8, epsilon... | pattern_matching |
48 | devbench-pattern-matching | python | import random as _rng
def random_choice(items, rng=None):
r = rng or _rng
idx = int(r.random() * len(items))
return items[idx]
def random_sample(items, k, rng=None):
r = rng or _rng
pool = list(items)
n = len(pool)
if k > n:
raise ValueError('Sample larger than population')
res... | def reservoir_sample(stream, k, rng=None):
r = rng or _rng
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = int(r.random() * (i + 1))
if j < k:
reservoir[j] = item
return reservoir
| # Test with a known RNG to verify algorithm correctness
class FakeRng:
def __init__(self, values):
self.values = list(values)
self.idx = 0
def random(self):
v = self.values[self.idx % len(self.values)]
self.idx += 1
return v
# reservoir_sample from an iterator (not a lis... | # k >= n: should return all elements
result = reservoir_sample(gen_stream(3), 5, rng=FakeRng([0.5]*10))
assert result == [0, 1, 2], f'Got: {result}'
# k=1: simple case
# i=0: fill [0]
# i=1: r=0.0 -> j=int(0.0*2)=0 < 1, replace -> [1]
# i=2: r=0.0 -> j=int(0.0*3)=0 < 1, replace -> [2]
result2 = reservoir_sample(gen_st... | pattern_matching |
49 | devbench-pattern-matching | python | def template_simple(text, variables):
result = text
for key, value in variables.items():
result = result.replace('${' + key + '}', str(value))
return result
def template_with_default(text, variables):
import re
def replacer(match):
expr = match.group(1)
if '|' in expr:
... | def template_conditional(text, variables):
result, i = [], 0
while i < len(text):
if text[i:i+5] == '${if ':
end_cond = text.index('}', i)
varname = text[i+5:end_cond].strip(); i = end_cond + 1
end_tag = text.index('${end}', i)
block = text[i:end_tag]; i =... | assert template_simple('Hello ${name}!', {'name': 'Alice'}) == 'Hello Alice!'
assert template_with_default('Hi ${name | stranger}', {}) == 'Hi stranger'
assert template_with_default('Hi ${name | stranger}', {'name': 'Bob'}) == 'Hi Bob'
# Conditional blocks
r = template_conditional('Hello ${name}${if premium}, welcome ... | # Missing variable in condition treated as falsy
r5 = template_conditional('${if missing}hidden${end}rest', {})
assert r5 == 'rest', f'Got: {r5}'
# Variable substitution inside conditional block
r6 = template_conditional('${if active}User: ${user}${end}', {'active': True, 'user': 'Eve'})
assert r6 == 'User: Eve', f'Go... | pattern_matching |
50 | devbench-pattern-matching | python | import inspect
def compose_two(f, g):
def composed(x):
return g(f(x))
return composed
def pipe(value, *fns):
result = value
for fn in fns:
result = fn(result)
return result
| def compose_checked(*fns):
if len(fns) < 2: raise ValueError('Need at least 2 functions')
for i in range(len(fns) - 1):
h_out, h_in = inspect.get_annotations(fns[i]), inspect.get_annotations(fns[i+1])
ret = h_out.get('return')
params = {k: v for k, v in h_in.items() if k != 'return'}
... | assert compose_two(lambda x: x + 1, lambda x: x * 2)(3) == 8
assert pipe(3, lambda x: x + 1, lambda x: x * 2) == 8
def int_to_str(x: int) -> str:
return str(x)
def str_to_upper(s: str) -> str:
return s.upper()
def str_len(s: str) -> int:
return len(s)
# Compatible chain: int->str, str->str
f = compose_c... | # Need at least 2 functions
try:
compose_checked(int_to_str)
assert False, 'Should have raised ValueError'
except ValueError:
pass
# Functions without annotations should compose fine (no type check)
h = compose_checked(lambda x: x + 1, lambda x: x * 2)
assert h(3) == 8
def float_to_int(x: float) -> int:
... | pattern_matching |
1 | devbench-syntax-completion | python | import datetime
from dataclasses import dataclass
@dataclass
class AuditEvent:
actor: str
action: str
when: datetime.datetime
detail: object = None
severity: str = "info"
def render(self, width: int = 64) -> str:
"""Render one audit line using f-string format syntax.
Exact lay... | actor_width = max(8, width - 44)
detail_text = f" detail={self.detail!r}" if self.detail is not None else ""
return (
f"{self.severity.upper():<7} | "
f"{self.when:%d/%m/%Y %H:%M} | "
f"{self.actor!r:<{actor_width}} | "
f"{self.action}{detail_text}... |
event = AuditEvent(
"ada",
"deploy",
datetime.datetime(2026, 5, 1, 9, 30),
{"target": "prod"},
"warn",
)
line = event.render(60)
print(line)
| event = AuditEvent("ada", "deploy", datetime.datetime(2026, 5, 1, 9, 30), {"target": "prod"}, "warn")
line = event.render(60)
assert line == "WARN | 01/05/2026 09:30 | 'ada' | deploy detail={'target': 'prod'}", line
assert AuditEvent("bob", "login", datetime.datetime(2024, 1, 2, 3, 4)).render(50) == "INFO... | syntax_completion |
2 | devbench-syntax-completion | python | class RecordingNamespace(dict):
def __init__(self):
super().__init__()
self.order = []
def __setitem__(self, key, value):
if key not in self:
self.order.append(key)
super().__setitem__(key, value)
class Field:
def __init__(self, typ):
self.typ = typ
cla... | @classmethod
def __prepare__(mcls, name, bases, **kwargs):
return RecordingNamespace()
def __new__(mcls, name, bases, namespace, *, prefix="", **kwargs):
cls = super().__new__(mcls, name, bases, dict(namespace))
cls.declared_fields = tuple(
f"{prefix}{key}"
f... |
class User(metaclass=FieldMeta, prefix="db_"):
id = Field(int)
name = Field(str)
helper = object()
active = Field(bool)
class Plain(metaclass=FieldMeta):
title = Field(str)
count = 0
print(User.declared_fields)
print(Plain.declared_fields)
| assert User.declared_fields == ("db_id", "db_name", "db_active"), User.declared_fields
assert Plain.declared_fields == ("title",), Plain.declared_fields
assert isinstance(User.__dict__["id"], Field)
class Empty(metaclass=FieldMeta, prefix="x_"):
helper = 1
assert Empty.declared_fields == ()
| syntax_completion |
3 | devbench-syntax-completion | python | import functools
def counted(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
def tagged(label):
def decorate(func):
func.tag = label
return func
return decorate
class F... | @classmethod
@counted
@tagged("build")
def make(cls, key: str) -> 'Factory':
if key not in cls.registry:
cls.registry[key] = cls(key)
return cls.registry[key]
@staticmethod
@counted
@tagged("check")
def valid_key(key: str) -> bool:
return isinstance(k... |
a = Factory.make("alpha")
b = Factory.make("alpha")
c = Factory.make("beta")
ok1 = Factory.valid_key("alpha")
ok2 = Factory.valid_key("not valid")
print(a is b, a is c, ok1, ok2)
| assert a is b
assert a is not c
assert a.key == "alpha" and c.key == "beta"
assert Factory.make.calls == 3
assert Factory.make.tag == "build"
assert Factory.valid_key.calls == 2
assert Factory.valid_key.tag == "check"
assert ok1 is True
assert ok2 is False
Factory.make("gamma")
assert Factory.make.calls == 4
| syntax_completion |
4 | devbench-syntax-completion | python | import datetime
class Span:
def __init__(self, name, start, minutes, tags=None):
self.name = name
self.start = start
self.minutes = minutes
self.tags = tags or []
def render(self, width=48):
"""Render a compact schedule row with f-string formatting.
The name co... | tags = f" [{';'.join(self.tags)}]" if self.tags else ""
return (
f"{self.name:<{width - 24}}"
f"{self.start:%m/%d %H:%M} "
f"{self.minutes:>4}m"
f"{tags}"
)
|
span = Span(
"Deploy",
datetime.datetime(2026, 5, 1, 9, 30),
75,
["prod", "db"],
)
line = span.render(50)
print(line)
| span = Span("Deploy", datetime.datetime(2026, 5, 1, 9, 30), 75, ["prod", "db"])
assert span.render(50) == "Deploy 05/01 09:30 75m [prod;db]", span.render(50)
assert Span("Lunch", datetime.datetime(2024, 1, 2, 12, 0), 5).render(40) == "Lunch 01/02 12:00 5m"
assert Span("X", datetime.dat... | syntax_completion |
5 | devbench-syntax-completion | python | from typing import List, Tuple
def label_matrix(
data: List[List[int]],
threshold: int = 50
) -> List[Tuple[int, int, int, str]]:
"""Label each cell in a matrix as "high" or "low" based on threshold.
Returns list of (row_idx, col_idx, value, label) tuples.
"""
labeled = [
| (i, j, val, "high" if val > threshold else "low")
for i, row in enumerate(data)
for j, val in enumerate(row)
| ]
return labeled
data = [[10, 80, 30], [60, 20, 90], [40, 55, 5]]
labeled = label_matrix(data)
print(labeled)
| assert len(labeled) == 9
assert labeled[0] == (0, 0, 10, "low")
assert labeled[1] == (0, 1, 80, "high")
assert labeled[5] == (1, 2, 90, "high")
| syntax_completion |
6 | devbench-syntax-completion | python | class Step:
def __init__(self, log, name):
self.log = log
self.name = name
def __enter__(self):
self.log.append(f"enter:{self.name}")
return self
def __exit__(self, exc_type, exc, tb):
self.log.append(f"exit:{self.name}")
return False
def run_steps(mode: st... | with Step(log, "outer"):
try:
with Step(log, "inner"):
log.append("body")
if mode == "value":
raise ValueError("bad")
if mode == "type":
raise TypeError("wrong")
ex... | return log
ok = run_steps("ok")
value = run_steps("value")
type_case = run_steps("type")
print(ok)
print(value)
print(type_case)
| assert ok == ["enter:outer", "enter:inner", "body", "exit:inner", "inner-finally", "exit:outer", "outer-finally"], ok
assert value == ["enter:outer", "enter:inner", "body", "exit:inner", "inner:bad", "inner-finally", "exit:outer", "outer:bad", "outer-finally"], value
assert type_case == ["enter:outer", "enter:inner", "... | syntax_completion |
7 | devbench-syntax-completion | python | from dataclasses import dataclass
@dataclass
class Packet:
kind: str
payload: object
flags: tuple[str, ...] = ()
def route(packet) -> str:
"""Route packets using structural pattern matching.
Data packets have payload {"id": int, "chunks": [first, *rest]}.
Urgent data is reported separately fr... | case Packet("data", {"id": int(pid), "chunks": [first, *rest]}, flags) if "urgent" in flags:
return f"urgent-data:{pid}:{1 + len(rest)}"
case Packet("data", {"id": int(pid), "chunks": [first, *rest]}, _):
return f"data:{pid}:{1 + len(rest)}"
case Packet("control", ("retry... |
r1 = route(Packet("data", {"id": 7, "chunks": ["a", "b", "c"]}, ("urgent",)))
r2 = route(Packet("data", {"id": 8, "chunks": ["x"]}))
r3 = route(Packet("control", ("retry", 3)))
r4 = route({"kind": "text", "body": "print()", "lang": "py"})
print(r1, r2, r3, r4)
| assert r1 == "urgent-data:7:3"
assert r2 == "data:8:1"
assert r3 == "retry:3"
assert r4 == "python-text:print()"
assert route(Packet("control", ("retry", 0))) == "ignored"
assert route({"kind": "text", "body": "x", "lang": "js"}) == "ignored"
assert route(Packet("data", {"id": True, "chunks": ["x"]})) == "data:True:1"
| syntax_completion |
8 | devbench-syntax-completion | python | import io
import sys
from typing import List, Tuple, Optional, Union
def find_first_negative(
values: List[int]
) -> Tuple[Optional[int], str]:
"""Find first negative using for/else inside try/except/else/finally.
Returns (value_found_or_None, captured_output_string).
The for/else pattern is key: ... | print(f"Found negative: {v}")
break
else:
print("No negatives found")
| except TypeError as e:
print(f"TypeError: {e}")
result = "error"
else:
print("Search completed without error")
finally:
sys.stdout = old_stdout
return result, captured.getvalue()
r1, out1 = find_first_negative([1, 2, -3, 4])
r2, out2 = find_first_negative([1, 2, 3])
| assert r1 == -3, f"Expected -3 but got {r1}"
assert "Found negative: -3" in out1
assert r2 is None, f"Expected None but got {r2}"
assert "No negatives found" in out2
| syntax_completion |
9 | devbench-syntax-completion | python | import os
import tempfile
class ManagedFile:
def __init__(self, path, mode='w'):
self.path = path
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.path, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
i... | raise RuntimeError("Intentional failure")
with ManagedFile(path, 'r') as f:
result = f.read()
| except RuntimeError:
result = "FAILED"
finally:
os.unlink(path)
return result
ok = safe_write("good data")
fail = safe_write("bad data", should_fail=True)
| assert ok == "good data", f"Expected 'good data' but got {ok!r}"
assert fail == "FAILED", f"Expected 'FAILED' but got {fail!r}"
| syntax_completion |
10 | devbench-syntax-completion | python | class Level:
def __init__(self, name):
self.name = name
self.entered = False
self.exited = False
def __enter__(self):
self.entered = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.exited = True
return False
def deep_nesting():
... | raise ValueError("error at C")
except ValueError as e:
log.append(f"caught: {e}")
raise RuntimeError("escalated") from e
| except RuntimeError as e:
log.append(f"caught escalated: {e}")
log.append(f"original cause: {e.__cause__}")
except Exception as e:
log.append(f"outer: {e}")
return log, a, b, c
log, a, b, c = deep_nesting()
| assert a.entered and a.exited
assert b.entered and b.exited
assert c.entered and c.exited
assert "caught: error at C" in log
assert "caught escalated: escalated" in log
assert any("original cause" in entry for entry in log)
| syntax_completion |
11 | devbench-syntax-completion | python | from contextlib import ExitStack
class Resource:
def __init__(self, log, name):
self.log = log
self.name = name
def __enter__(self):
self.log.append(f"enter:{self.name}")
return self
def __exit__(self, exc_type, exc, tb):
self.log.append(f"exit:{self.name}")
... | with ExitStack() as stack:
alpha = stack.enter_context(Resource(log, "alpha"))
beta = stack.enter_context(Resource(log, "beta"))
if mode == "lookup":
raise LookupError("missing")
log.append(f"use:{alpha.name}/{beta.name}")
except LookupError as... | return log
ok = manage("ok")
missing = manage("lookup")
print(ok)
print(missing)
| assert ok == ["enter:alpha", "enter:beta", "use:alpha/beta", "exit:beta", "exit:alpha", "else", "finally"], ok
assert missing == ["enter:alpha", "enter:beta", "exit:beta", "exit:alpha", "lookup:missing", "finally"], missing
| syntax_completion |
12 | devbench-syntax-completion | python | import functools
def log_call(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.call_count = getattr(wrapper, 'call_count', 0) + 1
return func(*args, **kwargs)
wrapper.call_count = 0
return wrapper
class Registry:
_instances = {}
def __init__(self, name: str)... | @log_call
def create(cls, name: str) -> 'Registry':
if name not in cls._instances:
cls._instances[name] = cls(name)
return cls._instances[name]
|
@staticmethod
@log_call
def validate_name(name: str) -> bool:
return isinstance(name, str) and len(name) > 0
r1 = Registry.create("alpha")
r2 = Registry.create("alpha")
r3 = Registry.create("beta")
| assert r1 is r2, "Same name should return same instance"
assert r1 is not r3
assert r1.name == "alpha"
assert Registry.create.call_count == 3
assert Registry.validate_name("test") is True
assert Registry.validate_name("") is False
| syntax_completion |
13 | devbench-syntax-completion | python | from abc import ABC, abstractmethod
from functools import cached_property
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
@abstractmethod
def perimeter(self) -> float: ...
class Circle(Shape):
PI = 3.14159265
def __init__(self, radius: float):
self._radius = radius
... | def area(self) -> float:
return self.PI * self._radius ** 2
def perimeter(self) -> float:
return 2 * self.PI * self._radius
@classmethod
def unit_circle(cls) -> 'Circle':
| return cls(1.0)
c = Circle(5)
uc = Circle.unit_circle()
| assert abs(c.area() - 3.14159265 * 25) < 1e-6
assert abs(c.perimeter() - 2 * 3.14159265 * 5) < 1e-6
assert uc.radius == 1.0
assert abs(uc.area() - 3.14159265) < 1e-6
| syntax_completion |
14 | devbench-syntax-completion | python | class Guard:
def __init__(self, log, name):
self.log = log
self.name = name
def __enter__(self):
self.log.append(f"enter:{self.name}")
return self
def __exit__(self, exc_type, exc, tb):
self.log.append(f"exit:{self.name}")
return False
def audit_events(even... | with Guard(log, "scan"):
for event in events:
match event:
case {"kind": "stop", "code": int(code)} if code > 0:
log.append(f"stop:{code}")
break
case {"kind": "skip"}:
con... | return log
with_stop = audit_events([
{"kind": "start"},
{"kind": "skip"},
{"kind": "stop", "code": 3},
{"kind": "late"},
])
no_stop = audit_events([{"kind": "skip"}, {"kind": "tick"}])
bad = audit_events([{"bad": True}])
print(with_stop)
print(no_stop)
print(bad)
| assert with_stop == ["enter:scan", "seen:start", "stop:3", "exit:scan", "clean", "done"], with_stop
assert no_stop == ["enter:scan", "seen:tick", "no-stop", "exit:scan", "clean", "done"], no_stop
assert bad == ["enter:scan", "exit:scan", "type:bad event: {'bad': True}", "done"], bad
assert audit_events([{"kind": "stop"... | syntax_completion |
15 | devbench-syntax-completion | python | class Validated:
"""A descriptor that validates values are within a range."""
def __init__(self, min_val: float, max_val: float):
self.min_val = min_val
self.max_val = max_val
def __set_name__(self, owner, name):
self.storage_name = f'_validated_{name}'
def __get__(self, obj, ... | def __set__(self, obj, value):
if not (self.min_val <= value <= self.max_val):
raise ValueError(
f"Value {value} not in [{self.min_val}, {self.max_val}]"
)
setattr(obj, self.storage_name, value)
|
class Config:
speed = Validated(0, 100)
volume = Validated(0, 10)
def __init__(self, speed: float, volume: float):
self.speed = speed
self.volume = volume
cfg = Config(50, 5)
| assert cfg.speed == 50
assert cfg.volume == 5
cfg.speed = 75
assert cfg.speed == 75
try:
cfg.speed = 200
assert False, "Should have raised ValueError"
except ValueError:
pass
try:
cfg.volume = -1
assert False, "Should have raised ValueError"
except ValueError:
pass
| syntax_completion |
16 | devbench-syntax-completion | python | from typing import Dict
def classify_status(code: int) -> str:
"""Classify HTTP status codes into human-readable categories.
Uses structural pattern matching (match/case).
Handles specific codes and a wildcard fallback.
"""
match code:
case 200:
return "OK"
case 301... | case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
|
results: Dict[int, str] = {
code: classify_status(code)
for code in [200, 301, 302, 404, 500, 999]
}
| assert results[200] == "OK"
assert results[301] == "Redirect"
assert results[302] == "Redirect"
assert results[404] == "Not Found"
assert results[500] == "Server Error"
assert results[999] == "Unknown"
| syntax_completion |
17 | devbench-syntax-completion | python | from typing import Union
def process_command(command: Union[dict, str]) -> str:
"""Process game commands using pattern matching.
Supports move with direction/steps, rotate with angle,
and fallback for unknown/invalid commands.
"""
match command:
case {"action": "move", "direction": d, ... | case {"action": "rotate", "angle": a} if -360 <= a <= 360:
return f"Rotating by {a} degrees"
case {"action": "rotate", "angle": a}:
return f"Invalid angle: {a}"
case {"action": action}:
return f"Unknown action: {action}"
case _:
return "Inv... |
r1 = process_command({"action": "move", "direction": "north", "steps": 5})
r2 = process_command({"action": "move", "direction": "south", "steps": 0})
r3 = process_command({"action": "rotate", "angle": 90})
r4 = process_command({"action": "rotate", "angle": 500})
r5 = process_command({"action": "jump"})
r6 = process_co... | assert r1 == "Moving north by 5 steps"
assert r2 == "Cannot move zero or negative steps"
assert r3 == "Rotating by 90 degrees"
assert r4 == "Invalid angle: 500"
assert r5 == "Unknown action: jump"
assert r6 == "Invalid command"
| syntax_completion |
18 | devbench-syntax-completion | python | from dataclasses import dataclass
from typing import Optional
@dataclass
class Point:
x: float
y: float
label: Optional[str] = None
@dataclass
class Line:
start: Point
end: Point
def describe_geometry(shape) -> str:
match shape:
case Point(x=0, y=0):
return "origin"
... | case Point(x=x, y=y, label=str(lbl)):
return f"labeled point '{lbl}' at ({x}, {y})"
case Point(x=x, y=y):
return f"point at ({x}, {y})"
case Line(start=Point(x=sx, y=sy), end=Point(x=ex, y=ey)) if sx == ex:
return f"vertical line from y={sy} to y={ey}"
... | case _:
return "unknown shape"
r1 = describe_geometry(Point(0, 0))
r2 = describe_geometry(Point(5, 0))
r3 = describe_geometry(Point(0, 3))
r4 = describe_geometry(Point(1, 2, "A"))
r5 = describe_geometry(Point(1, 2))
r6 = describe_geometry(Line(Point(3, 0), Point(3, 10)))
r7 = describe_geometry(Line... | assert r1 == "origin"
assert r2 == "positive x-axis at 5"
assert r3 == "positive y-axis at 3"
assert r4 == "labeled point 'A' at (1, 2)"
assert r5 == "point at (1, 2)"
assert r6 == "vertical line from y=0 to y=10"
assert r7 == "line from (0, 0) to (5, 5)"
| syntax_completion |
19 | devbench-syntax-completion | python | from typing import Union, List
def parse_record(
record: Union[list, str, tuple]
) -> str:
"""Parse structured records using sequence pattern matching.
Supports various list formats with different fields.
Uses star capture for variable-length records.
"""
match record:
case [name, ... | case [name, age, *hobbies] if len(hobbies) > 0:
return f"Person: {name}, age {age}, hobbies: {', '.join(hobbies)}"
case [name]:
return f"Person: {name}, no other info"
case []:
return "Empty record"
case _:
return "Invalid record"
|
r1 = parse_record(["Alice", 30])
r2 = parse_record(["Bob", 25, "chess", "hiking"])
r3 = parse_record(["Charlie"])
r4 = parse_record([])
r5 = parse_record("not a list")
| assert r1 == "Person: Alice, age 30"
assert r2 == "Person: Bob, age 25, hobbies: chess, hiking"
assert r3 == "Person: Charlie, no other info"
assert r4 == "Empty record"
assert r5 == "Invalid record"
| syntax_completion |
20 | devbench-syntax-completion | python | from dataclasses import dataclass
from typing import Union
@dataclass
class Success:
value: object
@dataclass
class Error:
code: int
message: str
@dataclass
class Warning:
code: int
message: str
def handle_result(result: Union[Success, Error, Warning]) -> str:
match result:
case Succ... | case Error(code=c, message=m) | Warning(code=c, message=m) if c >= 500:
return f"Critical ({c}): {m}"
case Error(code=c, message=m):
return f"Error ({c}): {m}"
case Warning(code=c, message=m):
return f"Warning ({c}): {m}"
case _:
return "Un... |
r1 = handle_result(Success([1, 2, 3]))
r2 = handle_result(Success("hello"))
r3 = handle_result(Error(500, "Internal"))
r4 = handle_result(Warning(500, "Critical warning"))
r5 = handle_result(Error(404, "Not found"))
r6 = handle_result(Warning(200, "Low priority"))
| assert r1 == "Success with list of 3 items"
assert r2 == "Success: hello"
assert r3 == "Critical (500): Internal"
assert r4 == "Critical (500): Critical warning"
assert r5 == "Error (404): Not found"
assert r6 == "Warning (200): Low priority"
| syntax_completion |
21 | devbench-syntax-completion | python | def format_name(
# first and last are positional-only
# title and suffix are keyword-only with defaults
# Use / to separate positional-only
# Use * to start keyword-only section
# Both have str type annotations
# Default values: title='', suffix=''
# The function joins non-empty parts with s... | first: str,
last: str,
/,
*,
title: str = "",
suffix: str = "",
| ) -> str:
parts = []
if title:
parts.append(title)
parts.append(first)
parts.append(last)
if suffix:
parts.append(suffix)
return " ".join(parts)
r1 = format_name("John", "Doe")
r2 = format_name("Jane", "Doe", title="Dr.")
r3 = format_name("Bob", "Smith", title="Mr.", suffix="Jr.... | assert r1 == "John Doe"
assert r2 == "Dr. Jane Doe"
assert r3 == "Mr. Bob Smith Jr."
try:
format_name(first="John", last="Doe")
assert False, "Should not accept keyword arguments for positional-only params"
except TypeError:
pass
| syntax_completion |
22 | devbench-syntax-completion | python | from typing import Any, Optional
def make_request(
# url is positional-only (already separated by /)
url: str,
/,
# Next: method with default, *args for extra paths,
# then keyword-only: headers, timeout, and **kwargs
# method defaults to 'GET', timeout to 30.0
# headers is Optional[dict[st... | method: str = "GET",
*args: str,
headers: Optional[dict[str, str]] = None,
timeout: float = 30.0,
**kwargs: Any,
| ) -> dict:
result = {
"url": url,
"method": method,
"extra_paths": list(args),
"headers": headers or {},
"timeout": timeout,
"options": kwargs,
}
return result
r = make_request(
"https://api.example.com", "POST", "v1", "users",
headers={"Auth": "token... | assert r["url"] == "https://api.example.com"
assert r["method"] == "POST"
assert r["extra_paths"] == ["v1", "users"]
assert r["headers"] == {"Auth": "token"}
assert r["timeout"] == 10.0
assert r["options"] == {"retry": True}
try:
make_request(url="https://example.com")
assert False, "url should be positional-on... | syntax_completion |
23 | devbench-syntax-completion | python | from typing import overload, Union
# The overload decorators declare the type signatures
# for static type checkers. The actual implementation
# follows without @overload and must handle all cases.
@overload
def convert(value: str) -> int: ...
@overload
def convert(value: int) -> str: ...
@overload
def convert(value:... | def convert(value: Union[str, int, float]) -> Union[int, str]:
if isinstance(value, str):
return int(value)
elif isinstance(value, (int, float)):
return str(value)
else:
raise TypeError(f"Unsupported type: {type(value)}")
|
a = convert("42")
b = convert(42)
c = convert(3.14)
| assert a == 42 and isinstance(a, int)
assert b == "42" and isinstance(b, str)
assert c == "3.14" and isinstance(c, str)
try:
convert([1, 2])
assert False, "Should raise TypeError"
except TypeError:
pass
| syntax_completion |
24 | devbench-syntax-completion | python | from typing import Callable, Optional
from dataclasses import dataclass, field
@dataclass
class Pipeline:
steps: list = field(default_factory=list)
name: str = "default"
def build_pipeline(
# *transforms collects callable positional args
*transforms: Callable[[int], int],
| name: str = "pipeline",
initial: int = 0,
validator: Optional[Callable[[int], bool]] = None,
| ) -> Pipeline:
p = Pipeline(name=name)
value = initial
for t in transforms:
value = t(value)
if validator and not validator(value):
raise ValueError(f"Validation failed at value {value}")
p.steps.append(value)
return p
result = build_pipeline(
lambda x: x + 10,
... | assert result.name == "math_pipe"
assert result.steps == [15, 30, 25]
try:
build_pipeline(lambda x: x - 100, initial=50, validator=lambda v: v >= 0)
assert False, "Should have raised ValueError"
except ValueError:
pass
| syntax_completion |
25 | devbench-syntax-completion | python | from typing import TypeVar, Generic, ClassVar
from typing import Protocol, runtime_checkable
T = TypeVar('T')
@runtime_checkable
class Serializable(Protocol):
def serialize(self) -> str: ...
class PluginBase(Generic[T]):
_registry: ClassVar[dict[str, type]] = {}
def __init_subclass__(cls, /, plugin_name... | class JsonPlugin(PluginBase[dict], plugin_name="json"):
def __init__(self, data: dict):
self.data = data
def serialize(self) -> str:
import json
return json.dumps(self.data)
|
class TextPlugin(PluginBase[str], plugin_name="text"):
def __init__(self, text: str):
self.text = text
def serialize(self) -> str:
return self.text
jp = JsonPlugin({"key": "value"})
tp = TextPlugin("hello")
| assert PluginBase.get_plugin("json") is JsonPlugin
assert PluginBase.get_plugin("text") is TextPlugin
assert jp.serialize() == '{"key": "value"}'
assert tp.serialize() == "hello"
assert isinstance(jp, Serializable)
assert isinstance(tp, Serializable)
try:
PluginBase.get_plugin("missing")
assert False, "Should r... | syntax_completion |
26 | devbench-syntax-completion | python | from typing import List, Union
# Recursive generator to flatten arbitrarily nested lists
# Handles any depth of nesting using yield from delegation
# Example: [1, [2, [3]]] -> [1, 2, 3]
NestedList = Union[int, List['NestedList']]
def flatten(nested_list: NestedList):
"""Yield all non-list elements from a nested ... | yield from flatten(item)
else:
yield item
|
data = [1, [2, [3, 4], 5], [6, 7]]
result = list(flatten(data))
print(result)
| assert list(flatten([1, [2, [3, 4], 5], [6, 7]])) == [1, 2, 3, 4, 5, 6, 7]
assert list(flatten([])) == []
assert list(flatten([1, 2, 3])) == [1, 2, 3]
assert list(flatten([[[[1]]]])) == [1]
| syntax_completion |
27 | devbench-syntax-completion | python | # Generator that acts as a running accumulator using the send() protocol.
# Usage:
# gen = accumulator()
# next(gen) # prime the generator, returns 0
# gen.send(10) # returns 10 (running total)
# gen.send(20) # returns 30
# gen.send(None) # stops and returns final total via StopIt... | if value is None:
return total
total += value
|
gen = accumulator()
next(gen) # prime the generator
gen.send(10)
gen.send(20)
result = gen.send(30)
print(result)
| gen = accumulator()
next(gen)
gen.send(10)
gen.send(20)
assert gen.send(30) == 60
gen2 = accumulator()
next(gen2)
assert gen2.send(5) == 5
| syntax_completion |
28 | devbench-syntax-completion | python | # A stateful counter generator supporting:
# - next(): increment by current step and yield count
# - send(n): change the step to n
# - throw(ResetSignal): reset count to starting value
class ResetSignal(Exception):
"""Exception used to signal the counter to reset."""
pass
def stateful_counter(start=0, step=1)... | if sent is not None:
step = sent
count += step
except ResetSignal:
count = start
|
counter = stateful_counter(0, 1)
assert next(counter) == 0
assert next(counter) == 1
assert next(counter) == 2
counter.send(5)
result = next(counter)
print(f"After step change: {result}")
counter.throw(ResetSignal)
result_after_reset = next(counter)
print(f"After reset: {result_after_reset}")
| c = stateful_counter(0, 1)
assert next(c) == 0
assert next(c) == 1
assert next(c) == 2
c.send(5)
assert next(c) == 12
c.throw(ResetSignal)
assert next(c) == 5
| syntax_completion |
29 | devbench-syntax-completion | python | import math
from typing import Generator
# Generate squares of prime numbers below a given threshold.
# Uses a nested helper function for primality testing.
def prime_squares_below(n: int) -> Generator[int, None, None]:
"""Generate squares of primes below n.
Args:
n: Upper bound (exclusive) for prime... | primes = (x for x in range(2, n) if is_prime(x))
return (p * p for p in primes)
|
result = list(prime_squares_below(20))
print(result)
| assert list(prime_squares_below(10)) == [4, 9, 25, 49]
assert list(prime_squares_below(2)) == []
assert list(prime_squares_below(20)) == [4, 9, 25, 49, 121, 169, 289, 361]
| syntax_completion |
30 | devbench-syntax-completion | python | def sub_generator(items):
total = 0
for item in items:
total += item
yield item
return total
def delegating_generator(lists):
totals = []
for lst in lists:
| total = yield from sub_generator(lst)
totals.append(total)
yield totals
|
gen = delegating_generator([[1, 2, 3], [4, 5]])
yielded = []
try:
while True:
yielded.append(next(gen))
except StopIteration:
pass
print(f"Yielded: {yielded}")
| gen = delegating_generator([[1, 2, 3], [4, 5]])
yielded = []
try:
while True:
yielded.append(next(gen))
except StopIteration:
pass
assert yielded == [1, 2, 3, 4, 5, [6, 9]]
| syntax_completion |
31 | devbench-syntax-completion | python | from typing import List, Dict, Any
# Sort a list of employee records by multiple criteria:
# Primary: age descending (oldest first)
# Secondary: name ascending (alphabetical tiebreaker)
data: List[Dict[str, Any]] = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35},... | key=lambda x: (-x['age'], x['name'])
)
print(f"Sorted {len(sorted_data)} records by age desc, name asc")
|
print(sorted_data)
| assert sorted_data[0]['name'] == 'Charlie'
assert sorted_data[1]['name'] == 'Alice'
assert sorted_data[2]['name'] == 'Bob'
| syntax_completion |
32 | devbench-syntax-completion | python | from functools import reduce
from typing import Callable, Any
# A function pipeline builder that composes multiple functions.
# Functions are applied left-to-right:
# make_pipeline(f, g, h)(x) == h(g(f(x)))
# An empty pipeline returns the identity function.
#
# Implementation uses functools.reduce with nested lambda... | if not functions:
return lambda x: x
return lambda x: reduce(lambda acc, fn: fn(acc), functions, x)
|
pipeline = make_pipeline(
lambda x: x * 2,
lambda x: x + 10,
lambda x: x ** 2
)
result = pipeline(5)
print(f"Pipeline result: {result}")
| pipeline = make_pipeline(lambda x: x * 2, lambda x: x + 10, lambda x: x ** 2)
assert pipeline(5) == 400
assert pipeline(0) == 100
identity = make_pipeline()
assert identity(42) == 42
| syntax_completion |
33 | devbench-syntax-completion | python | # Memoized Fibonacci implementation using a single lambda expression.
# This leverages Python's mutable default argument trick:
# The _cache dict persists across calls because default arguments
# are evaluated once at function definition time.
#
# The lambda must use only expressions (no statements), so we
# use dict.s... | _cache[n] if n in _cache else _cache.setdefault(n, fib(n - 1) + fib(n - 2))
)
|
results = [fib(i) for i in range(10)]
print(results)
| assert fib(0) == 0
assert fib(1) == 1
assert fib(10) == 55
assert fib(20) == 6765
assert [fib(i) for i in range(10)] == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| syntax_completion |
34 | devbench-syntax-completion | python | from functools import reduce
from typing import List
# Functional programming pipeline using reduce, map, and filter:
# 1. Start with numbers 1 through 10
# 2. Filter to keep only even numbers: [2, 4, 6, 8, 10]
# 3. Square each: [4, 16, 36, 64, 100]
# 4. Sum them all: 220
numbers: List[int] = list(range(1, 11))
resu... | lambda x: x ** 2,
filter(lambda x: x % 2 == 0, numbers)
)
)
|
print(f"Result: {result}")
| assert result == 220
| syntax_completion |
35 | devbench-syntax-completion | python | from typing import List, Callable
def group_and_sort(
items: List[dict],
group_key: str,
sort_key: Callable
) -> dict:
groups = {}
for item in items:
key = item[group_key]
groups.setdefault(key, []).append(item)
| return {
k: sorted(v, key=sort_key)
for k, v in sorted(groups.items())
}
|
employees = [
{'dept': 'eng', 'name': 'Zara', 'salary': 90000},
{'dept': 'eng', 'name': 'Alice', 'salary': 120000},
{'dept': 'hr', 'name': 'Bob', 'salary': 80000},
{'dept': 'hr', 'name': 'Diana', 'salary': 95000},
{'dept': 'eng', 'name': 'Mona', 'salary': 110000},
]
result = group_and_sort(
em... | result = group_and_sort(
employees,
'dept',
lambda x: (-x['salary'], x['name'])
)
assert list(result.keys()) == ['eng', 'hr']
assert [m['name'] for m in result['eng']] == ['Alice', 'Mona', 'Zara']
assert [m['name'] for m in result['hr']] == ['Diana', 'Bob']
| syntax_completion |
36 | devbench-syntax-completion | python | import asyncio
class AsyncResource:
def __init__(self, name):
self.name = name
self.is_open = False
async def __aenter__(self):
await asyncio.sleep(0.01)
self.is_open = True
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await asyncio.sle... | async with AsyncResource("db") as res:
assert res.is_open
return res.name
|
result = asyncio.run(use_resource())
print(f"Used resource: {result}")
| assert asyncio.run(use_resource()) == "db"
| syntax_completion |
37 | devbench-syntax-completion | python | import asyncio
async def async_range(start, stop, step=1):
current = start
while current < stop:
await asyncio.sleep(0.001)
yield current
current += step
async def collect_items():
items = []
| async for i in async_range(0, 10, 3):
items.append(i * i)
return items
|
result = asyncio.run(collect_items())
print(f"Collected: {result}")
| assert asyncio.run(collect_items()) == [0, 9, 36, 81]
| syntax_completion |
38 | devbench-syntax-completion | python | import asyncio
async def risky_task(n: int) -> str:
await asyncio.sleep(0.01)
if n % 3 == 0:
raise ValueError(f"Bad value: {n}")
return f"ok:{n}"
async def run_with_error_handling(values):
tasks = [risky_task(v) for v in values]
| results = await asyncio.gather(*tasks, return_exceptions=True)
successes = [r for r in results if isinstance(r, str)]
failures = [r for r in results if isinstance(r, Exception)]
return successes, failures
|
async def main():
ok, errs = await run_with_error_handling([1, 2, 3, 4, 5, 6])
print(f"Successes: {ok}")
print(f"Failures: {len(errs)}")
return ok, errs
ok, errs = asyncio.run(main())
| ok, errs = asyncio.run(main())
assert ok == ['ok:1', 'ok:2', 'ok:4', 'ok:5']
assert len(errs) == 2
assert all(isinstance(e, ValueError) for e in errs)
| syntax_completion |
39 | devbench-syntax-completion | python | import asyncio
class AsyncPool:
def __init__(self, size):
self.size = size
self.semaphore = None
async def __aenter__(self):
self.semaphore = asyncio.Semaphore(self.size)
return self
async def __aexit__(self, *args):
self.semaphore = None
async def run(self, c... | async with AsyncPool(3) as pool:
tasks = [pool.run(worker(i)) for i in range(5)]
results = await asyncio.gather(*tasks)
return sorted(results)
|
output = asyncio.run(main())
print(f"Pool results: {output}")
| assert asyncio.run(main()) == [0, 10, 20, 30, 40]
| syntax_completion |
40 | devbench-syntax-completion | python | import asyncio
from typing import Union
# Demonstrate asyncio.wait_for for adding timeouts to async operations.
# If the operation takes longer than timeout_sec, return "timed out".
async def slow_operation(duration: float, label: str) -> str:
"""Simulate a slow I/O-bound operation."""
await asyncio.sleep(dur... | result = await asyncio.wait_for(
slow_operation(duration, "task"),
timeout=timeout_sec
)
return result
except asyncio.TimeoutError:
return "timed out"
|
async def main():
r1 = await run_with_timeout(0.01, 1.0)
r2 = await run_with_timeout(2.0, 0.01)
return r1, r2
result = asyncio.run(main())
print(result)
| r1, r2 = asyncio.run(main())
assert r1 == "task done"
assert r2 == "timed out"
| syntax_completion |
41 | devbench-syntax-completion | python | from typing import List, Tuple
# Format a tabular report of items with aligned columns.
# Uses f-string format specification for alignment:
# < left-align, > right-align, .2f two decimal places
def format_report(items: List[Tuple[str, int, float]]) -> str:
"""Create a formatted table with headers, separator, an... | lines.append(f"{name:<20}{qty:>8}{price:>12.2f}")
return "\n".join(lines)
|
items = [("Widget", 100, 9.99), ("Gadget", 50, 24.5), ("Doohickey", 200, 1.5)]
report = format_report(items)
print(report)
| report = format_report([("Widget", 100, 9.99)])
assert "Widget" in report
assert "9.99" in report
lines = report.split("\n")
assert len(lines) == 3
assert lines[0].startswith("Item")
| syntax_completion |
42 | devbench-syntax-completion | python | from typing import List, Tuple, Any
# Format a table with dynamic column widths and alignment.
# col_widths is a list of (width, align_char) tuples where
# align_char is '<' for left or '>' for right alignment.
# Uses nested f-strings: f"{val:{align}{width}}" where the
# format spec itself is computed from variables.
... | f"{str(val):{align}{width}}"
for val, (width, align) in zip(row, col_widths)
)
rows.append(formatted)
return "\n".join(rows)
|
data = [
["Alice", 30, 95.5],
["Bob", 25, 87.3],
]
col_widths = [(10, "<"), (5, ">"), (8, ">")]
print(format_table(data, col_widths))
| result = format_table(data, col_widths)
lines = result.strip().split("\n")
assert len(lines) == 2
assert "Alice" in lines[0]
assert "Bob" in lines[1]
| syntax_completion |
43 | devbench-syntax-completion | python | class LogEntry:
def __init__(self, level, message, context=None):
self.level = level
self.message = message
self.context = context
def __repr__(self):
return f"LogEntry({self.level!r}, {self.message!r})"
def __str__(self):
return f"[{self.level}] {self.message}"
... | ctx = f" ctx={self.context!r}" if self.context else ""
if verbose:
return f"{self!r}{ctx}"
return f"{self!s}{ctx}"
|
entry = LogEntry("ERROR", "disk full", {"host": "srv1"})
print(entry.format_log(verbose=False))
print(entry.format_log(verbose=True))
entry2 = LogEntry("INFO", "started")
print(entry2.format_log())
| e = LogEntry("ERROR", "fail", {"k": "v"})
assert "ERROR" in e.format_log()
assert "LogEntry(" in e.format_log(verbose=True)
assert "ctx=" in e.format_log(verbose=True)
e2 = LogEntry("INFO", "ok")
assert "ctx=" not in e2.format_log()
assert e2.format_log() == "[INFO] ok"
assert e2.format_log(verbose=True) == "LogEntry('... | syntax_completion |
44 | devbench-syntax-completion | python | from typing import List, Dict, Any
# Summarize student scores with grades and formatted output.
# Grade thresholds: A >= 90, B >= 80, C >= 70, else F.
# Output format: "Name: avg=XX.X (Grade) [score1, score2, ...]"
def summarize_scores(students: List[Dict[str, Any]]) -> List[str]:
"""Create a summary line for eac... | grade = 'A' if avg >= 90 else 'B' if avg >= 80 else 'C' if avg >= 70 else 'F'
summaries.append(
f"{student['name']}: avg={avg:.1f} ({grade}) "
f"[{', '.join(str(s) for s in scores)}]"
)
return summaries
|
students = [
{'name': 'Alice', 'scores': [95, 87, 92]},
{'name': 'Bob', 'scores': [72, 68, 75]},
{'name': 'Charlie', 'scores': [88, 91, 84]},
]
for line in summarize_scores(students):
print(line)
| result = summarize_scores(students)
assert len(result) == 3
assert 'Alice' in result[0]
assert '91.3' in result[0]
assert '(A)' in result[0]
assert 'Bob' in result[1]
assert '(C)' in result[1]
assert 'Charlie' in result[2]
assert '(B)' in result[2]
| syntax_completion |
45 | devbench-syntax-completion | python | import datetime
class Event:
def __init__(self, name, dt, duration_min, tags=None):
self.name = name
self.dt = dt
self.duration_min = duration_min
self.tags = tags or []
def format_duration(self):
h, m = divmod(self.duration_min, 60)
return f"{h}h{m:02d}m" if h ... | tags_str = f" [{', '.join(self.tags)}]" if self.tags else ""
return (
f"{self.name:<{width - 25}}"
f"{self.dt:%Y-%m-%d %H:%M} "
f"{self.format_duration():>6}"
f"{tags_str}"
)
|
events = [
Event("Team Meeting", datetime.datetime(2024, 6, 15, 9, 30), 90, ["work", "weekly"]),
Event("Lunch", datetime.datetime(2024, 6, 15, 12, 0), 45),
]
for e in events:
print(e.to_line())
| e1 = Event("Test", datetime.datetime(2024, 1, 1, 10, 0), 90, ["a"])
line = e1.to_line()
assert "Test" in line
assert "2024-01-01 10:00" in line
assert "1h30m" in line
assert "[a]" in line
e2 = Event("Short", datetime.datetime(2024, 1, 1, 10, 0), 30)
line2 = e2.to_line()
assert "30m" in line2
assert "[" not in line2
| syntax_completion |
46 | devbench-syntax-completion | python | from typing import Dict, Type
# Plugin registration system using __init_subclass__.
# Subclasses are automatically registered when they are defined.
# If plugin_name is provided, use it; otherwise default to
# the lowercase class name.
class Plugin:
"""Base class that auto-registers subclasses in _registry."""
... | name = plugin_name or cls.__name__.lower()
Plugin._registry[name] = cls
|
class AuthPlugin(Plugin, plugin_name="auth"):
def run(self):
return "authenticating"
class LogPlugin(Plugin, plugin_name="log"):
def run(self):
return "logging"
class DefaultPlugin(Plugin):
def run(self):
return "default"
print(Plugin._registry)
| assert "auth" in Plugin._registry
assert "log" in Plugin._registry
assert "defaultplugin" in Plugin._registry
assert Plugin._registry["auth"] is AuthPlugin
assert Plugin._registry["log"]().run() == "logging"
| syntax_completion |
47 | devbench-syntax-completion | python | from typing import Any
# A type-enforcing map that uses __class_getitem__ to enable
# the subscription syntax: TypedMap[str, int] creates an
# instance that only accepts str keys and int values.
class TypedMap:
"""A dictionary-like class with runtime type checking."""
def __init__(self, key_type: type, val_t... | key_type, val_type = params
return cls(key_type, val_type)
|
def put(self, key, value):
if not isinstance(key, self._key_type):
raise TypeError(f"Key must be {self._key_type.__name__}")
if not isinstance(value, self._val_type):
raise TypeError(f"Value must be {self._val_type.__name__}")
self._data[key] = value
def get(sel... | m = TypedMap[str, int]
m.put("x", 1)
assert m.get("x") == 1
try:
m.put(123, "bad")
assert False, "Should have raised TypeError"
except TypeError:
pass
try:
m.put("y", "bad")
assert False, "Should have raised TypeError"
except TypeError:
pass
| syntax_completion |
48 | devbench-syntax-completion | python | # Descriptor with __set_name__ for automatic attribute name discovery.
# Uses a private storage name to avoid infinite recursion in __get__/__set__.
# Validates that values fall within min_val and max_val bounds.
class ValidatedField:
"""A descriptor that validates numeric bounds on attribute assignment."""
d... | if self.min_val is not None and value < self.min_val:
raise ValueError(f"{self.name} must be >= {self.min_val}")
if self.max_val is not None and value > self.max_val:
raise ValueError(f"{self.name} must be <= {self.max_val}")
setattr(obj, self.storage_name, value)
|
class Product:
price = ValidatedField(min_val=0)
quantity = ValidatedField(min_val=0, max_val=1000)
p = Product()
p.price = 9.99
p.quantity = 100
print(f"Price: {p.price}, Qty: {p.quantity}")
| p = Product()
p.price = 10
assert p.price == 10
p.quantity = 500
assert p.quantity == 500
try:
p.price = -1
assert False, "Should raise ValueError"
except ValueError:
pass
try:
p.quantity = 1001
assert False, "Should raise ValueError"
except ValueError:
pass
assert Product.price is not None
| syntax_completion |
49 | devbench-syntax-completion | python | from typing import runtime_checkable, Protocol, Iterable
@runtime_checkable
class Renderable(Protocol):
def render(self) -> str: ...
@runtime_checkable
class Sizeable(Protocol):
def size(self) -> int: ...
def render_all(items: Iterable[Renderable]) -> str:
| parts = []
for item in items:
if not isinstance(item, Renderable):
raise TypeError(f"{type(item).__name__} is not Renderable")
parts.append(item.render())
return "\n".join(parts)
|
class Widget:
def __init__(self, label):
self.label = label
def render(self) -> str:
return f"<Widget: {self.label}>"
def size(self) -> int:
return len(self.label)
class Text:
def __init__(self, content):
self.content = content
def render(self) -> str:
retur... | assert isinstance(Widget("x"), Renderable)
assert isinstance(Widget("x"), Sizeable)
assert isinstance(Text("x"), Renderable)
assert not isinstance(Text("x"), Sizeable)
result = render_all([Widget("a"), Text("b")])
assert "<Widget: a>" in result
assert "b" in result
try:
render_all([42])
assert False, "Should ra... | syntax_completion |
50 | devbench-syntax-completion | python | class EventSystem:
_handlers = {}
def __init_subclass__(cls, *, event_type=None, **kwargs):
super().__init_subclass__(**kwargs)
if event_type:
EventSystem._handlers.setdefault(event_type, []).append(cls)
@classmethod
def dispatch(cls, event_type, data):
| results = []
for handler_cls in cls._handlers.get(event_type, []):
handler = handler_cls()
results.append(handler.handle(data))
return results
|
class LogHandler(EventSystem, event_type="error"):
def handle(self, data):
return f"LOG: {data}"
class AlertHandler(EventSystem, event_type="error"):
def handle(self, data):
return f"ALERT: {data}"
class MetricHandler(EventSystem, event_type="metric"):
def handle(self, data):
retu... | results = EventSystem.dispatch("error", "test")
assert len(results) == 2
assert "LOG: test" in results
assert "ALERT: test" in results
metric_results = EventSystem.dispatch("metric", "cpu=80")
assert metric_results == ["METRIC: cpu=80"]
empty = EventSystem.dispatch("unknown", "x")
assert empty == []
| syntax_completion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.