example_name
stringlengths 10
28
| python_file
stringlengths 9
32
| python_code
stringlengths 490
18.2k
| rust_code
stringlengths 0
434
| has_rust
bool 2
classes | category
stringlengths 2
20
| python_lines
int32 13
586
| rust_lines
int32 0
6
| blocking_features
listlengths 0
7
| suspiciousness
float32 0
0.95
| error
stringlengths 33
500
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|
example_graph_trie
|
test_graph_trie_cli.py
|
"""Tests for graph_trie_cli.py"""
from graph_trie_cli import (
Trie,
autocomplete,
count_distinct_substrings,
longest_common_prefix,
simulate_trie,
spell_check,
word_break,
)
class TestTrie:
def test_insert_search(self):
trie = Trie()
trie.insert("hello")
assert trie.search("hello")
assert not trie.search("hell")
def test_starts_with(self):
trie = Trie()
trie.insert("hello")
assert trie.starts_with("hell")
assert not trie.starts_with("world")
def test_count_words(self):
trie = Trie()
trie.insert("hello")
trie.insert("help")
trie.insert("world")
assert trie.count_words_with_prefix("hel") == 2
assert trie.count_words_with_prefix("wor") == 1
def test_get_words_with_prefix(self):
trie = Trie()
trie.insert("hello")
trie.insert("help")
words = trie.get_words_with_prefix("hel")
assert set(words) == {"hello", "help"}
def test_delete(self):
trie = Trie()
trie.insert("hello")
assert trie.delete("hello")
assert not trie.search("hello")
def test_delete_nonexistent(self):
trie = Trie()
assert not trie.delete("hello")
def test_word_count(self):
trie = Trie()
trie.insert("hello")
trie.insert("world")
assert trie.word_count() == 2
def test_all_words(self):
trie = Trie()
trie.insert("cat")
trie.insert("car")
words = trie.all_words()
assert set(words) == {"cat", "car"}
def test_duplicate_insert(self):
trie = Trie()
trie.insert("hello")
trie.insert("hello")
assert trie.word_count() == 2
words = trie.get_words_with_prefix("hello")
assert len(words) == 2
class TestLongestCommonPrefix:
def test_common(self):
assert longest_common_prefix(["flower", "flow", "flight"]) == "fl"
def test_no_common(self):
assert longest_common_prefix(["dog", "cat", "bird"]) == ""
def test_single_word(self):
assert longest_common_prefix(["hello"]) == "hello"
def test_empty(self):
assert longest_common_prefix([]) == ""
def test_all_same(self):
assert longest_common_prefix(["abc", "abc", "abc"]) == "abc"
class TestAutocomplete:
def test_basic(self):
trie = Trie()
trie.insert("hello")
trie.insert("help")
trie.insert("world")
suggestions = autocomplete(trie, "hel")
assert set(suggestions) == {"hello", "help"}
def test_no_matches(self):
trie = Trie()
trie.insert("hello")
suggestions = autocomplete(trie, "xyz")
assert suggestions == []
class TestSpellCheck:
def test_deletion(self):
trie = Trie()
trie.insert("hello")
suggestions = spell_check(trie, "helloo")
assert "hello" in suggestions
def test_insertion(self):
trie = Trie()
trie.insert("hello")
suggestions = spell_check(trie, "helo")
assert "hello" in suggestions
def test_substitution(self):
trie = Trie()
trie.insert("hello")
suggestions = spell_check(trie, "hallo")
assert "hello" in suggestions
class TestWordBreak:
def test_can_break(self):
trie = Trie()
for word in ["leet", "code"]:
trie.insert(word)
assert word_break(trie, "leetcode")
def test_cannot_break(self):
trie = Trie()
for word in ["leet", "code"]:
trie.insert(word)
assert not word_break(trie, "leetxcode")
class TestCountDistinctSubstrings:
def test_simple(self):
assert count_distinct_substrings("abc") == 6 # a, b, c, ab, bc, abc
def test_repeated(self):
assert count_distinct_substrings("aaa") == 3 # a, aa, aaa
def test_empty(self):
assert count_distinct_substrings("") == 0
class TestSimulateTrie:
def test_insert_search(self):
result = simulate_trie(["insert:hello", "search:hello", "search:hell"])
assert result == ["1", "0"]
def test_prefix(self):
result = simulate_trie(["insert:hello", "prefix:hel"])
assert result == ["1"]
def test_count(self):
result = simulate_trie(["insert:hello", "insert:help", "count:hel"])
assert result == ["2"]
def test_delete(self):
result = simulate_trie(["insert:hello", "delete:hello", "search:hello"])
assert result == ["1", "0"]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_graph_trie/test_graph_trie_cli.py (4561 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_graph_trie/test_graph_trie_cli.rs (9719 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 86.1 KB/s
⏱️ Total time: 51ms
| true
|
graph_trie
| 167
| 5
|
[
"class_definition"
] | 0.612
| null |
example_graph_unionfind
|
graph_unionfind_cli.py
|
#!/usr/bin/env python3
"""Union-Find (Disjoint Set) CLI.
Union-Find data structure with path compression and union by rank.
"""
import argparse
import sys
class UnionFind:
"""Union-Find with path compression and union by rank."""
def __init__(self, n: int) -> None:
self._parent: list[int] = list(range(n))
self._rank: list[int] = [0] * n
self._size: list[int] = [1] * n
self._count: int = n
def find(self, x: int) -> int:
"""Find root with path compression."""
if self._parent[x] != x:
self._parent[x] = self.find(self._parent[x])
return self._parent[x]
def union(self, x: int, y: int) -> bool:
"""Union by rank. Returns True if merged."""
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return False
if self._rank[root_x] < self._rank[root_y]:
root_x, root_y = root_y, root_x
self._parent[root_y] = root_x
self._size[root_x] += self._size[root_y]
if self._rank[root_x] == self._rank[root_y]:
self._rank[root_x] += 1
self._count -= 1
return True
def connected(self, x: int, y: int) -> bool:
"""Check if x and y are in same set."""
return self.find(x) == self.find(y)
def component_count(self) -> int:
"""Get number of disjoint sets."""
return self._count
def component_size(self, x: int) -> int:
"""Get size of component containing x."""
return self._size[self.find(x)]
def get_components(self) -> list[list[int]]:
"""Get all components as lists."""
components: dict[int, list[int]] = {}
for i in range(len(self._parent)):
root = self.find(i)
if root not in components:
components[root] = []
components[root].append(i)
return list(components.values())
class WeightedUnionFind:
"""Union-Find with weights (potentials)."""
def __init__(self, n: int) -> None:
self._parent: list[int] = list(range(n))
self._rank: list[int] = [0] * n
self._weight: list[int] = [0] * n # weight[i] = potential from i to parent[i]
def find(self, x: int) -> tuple[int, int]:
"""Find root and return (root, weight from x to root)."""
if self._parent[x] == x:
return (x, 0)
root, w = self.find(self._parent[x])
self._parent[x] = root
self._weight[x] += w
return (root, self._weight[x])
def union(self, x: int, y: int, w: int) -> bool:
"""Union x and y with weight w (potential of y relative to x)."""
root_x, wx = self.find(x)
root_y, wy = self.find(y)
if root_x == root_y:
return False
if self._rank[root_x] < self._rank[root_y]:
self._parent[root_x] = root_y
self._weight[root_x] = wy - wx - w
else:
self._parent[root_y] = root_x
self._weight[root_y] = wx - wy + w
if self._rank[root_x] == self._rank[root_y]:
self._rank[root_x] += 1
return True
def diff(self, x: int, y: int) -> int | None:
"""Get weight difference between x and y if connected."""
root_x, wx = self.find(x)
root_y, wy = self.find(y)
if root_x != root_y:
return None
return wy - wx
def kruskal_mst(n: int, edges: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
"""Kruskal's MST algorithm using Union-Find."""
uf = UnionFind(n)
sorted_edges = sorted(edges, key=lambda e: e[2])
mst: list[tuple[int, int, int]] = []
for u, v, w in sorted_edges:
if not uf.connected(u, v):
uf.union(u, v)
mst.append((u, v, w))
if len(mst) == n - 1:
break
return mst
def count_islands(grid: list[list[int]]) -> int:
"""Count connected components in grid (1 = land, 0 = water)."""
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
uf = UnionFind(rows * cols)
def index(r: int, c: int) -> int:
return r * cols + c
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
if r > 0 and grid[r - 1][c] == 1:
uf.union(index(r, c), index(r - 1, c))
if c > 0 and grid[r][c - 1] == 1:
uf.union(index(r, c), index(r, c - 1))
roots: set[int] = set()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
roots.add(uf.find(index(r, c)))
return len(roots)
def is_connected_graph(n: int, edges: list[tuple[int, int]]) -> bool:
"""Check if graph is connected."""
uf = UnionFind(n)
for u, v in edges:
uf.union(u, v)
return uf.component_count() == 1
def redundant_connection(n: int, edges: list[tuple[int, int]]) -> tuple[int, int] | None:
"""Find edge that creates cycle (redundant connection)."""
uf = UnionFind(n)
for u, v in edges:
if uf.connected(u, v):
return (u, v)
uf.union(u, v)
return None
def earliest_connection(n: int, edges: list[tuple[int, int]]) -> int:
"""Find earliest time when all nodes are connected."""
uf = UnionFind(n)
for i, (u, v) in enumerate(edges):
uf.union(u, v)
if uf.component_count() == 1:
return i
return -1
def largest_component(n: int, edges: list[tuple[int, int]]) -> int:
"""Find size of largest connected component."""
uf = UnionFind(n)
for u, v in edges:
uf.union(u, v)
max_size = 0
for i in range(n):
max_size = max(max_size, uf.component_size(i))
return max_size
def simulate_uf(n: int, ops: list[str]) -> list[int]:
"""Simulate Union-Find operations."""
uf = UnionFind(n)
results: list[int] = []
for op in ops:
parts = op.split(":")
cmd = parts[0]
if cmd == "union":
x, y = int(parts[1]), int(parts[2])
uf.union(x, y)
elif cmd == "find":
x = int(parts[1])
results.append(uf.find(x))
elif cmd == "connected":
x, y = int(parts[1]), int(parts[2])
results.append(1 if uf.connected(x, y) else 0)
elif cmd == "count":
results.append(uf.component_count())
elif cmd == "size":
x = int(parts[1])
results.append(uf.component_size(x))
return results
def main() -> int:
parser = argparse.ArgumentParser(description="Union-Find CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# ops
ops_p = subparsers.add_parser("ops", help="Union-Find operations")
ops_p.add_argument("n", type=int)
ops_p.add_argument("ops", nargs="+")
# mst
mst_p = subparsers.add_parser("mst", help="Kruskal MST")
mst_p.add_argument("n", type=int)
mst_p.add_argument("edges", nargs="+", help="u-v:w format")
# connected
conn_p = subparsers.add_parser("connected", help="Check connectivity")
conn_p.add_argument("n", type=int)
conn_p.add_argument("edges", nargs="+", help="u-v format")
args = parser.parse_args()
if args.command == "ops":
results = simulate_uf(args.n, args.ops)
print(f"Results: {results}")
elif args.command == "mst":
edges = []
for e in args.edges:
parts = e.split(":")
verts = parts[0].split("-")
u, v = int(verts[0]), int(verts[1])
w = int(parts[1])
edges.append((u, v, w))
mst = kruskal_mst(args.n, edges)
total = sum(w for _, _, w in mst)
print(f"MST weight: {total}")
elif args.command == "connected":
edges = []
for e in args.edges:
parts = e.split("-")
edges.append((int(parts[0]), int(parts[1])))
connected = is_connected_graph(args.n, edges)
print(f"Connected: {connected}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_graph_unionfind/graph_unionfind_cli.py (8160 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_graph_unionfind/graph_unionfind_cli.rs (14535 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_graph_unionfind/Cargo.toml (1 dependencies)
⏱️ Parse time: 57ms
📊 Throughput: 138.2 KB/s
⏱️ Total time: 57ms
| true
|
graph_unionfind
| 280
| 6
|
[
"lambda",
"context_manager",
"class_definition"
] | 0.783
| null |
example_graph_unionfind
|
test_graph_unionfind_cli.py
|
"""Tests for graph_unionfind_cli.py"""
from graph_unionfind_cli import (
UnionFind,
WeightedUnionFind,
count_islands,
earliest_connection,
is_connected_graph,
kruskal_mst,
largest_component,
redundant_connection,
simulate_uf,
)
class TestUnionFind:
def test_initial_state(self):
uf = UnionFind(5)
assert uf.component_count() == 5
def test_find(self):
uf = UnionFind(5)
assert uf.find(0) == 0
def test_union(self):
uf = UnionFind(5)
assert uf.union(0, 1)
assert uf.connected(0, 1)
assert uf.component_count() == 4
def test_union_same(self):
uf = UnionFind(5)
uf.union(0, 1)
assert not uf.union(0, 1)
def test_path_compression(self):
uf = UnionFind(5)
uf.union(0, 1)
uf.union(1, 2)
uf.find(2)
assert uf.find(0) == uf.find(2)
def test_component_size(self):
uf = UnionFind(5)
uf.union(0, 1)
uf.union(1, 2)
assert uf.component_size(0) == 3
def test_get_components(self):
uf = UnionFind(4)
uf.union(0, 1)
uf.union(2, 3)
comps = uf.get_components()
assert len(comps) == 2
class TestWeightedUnionFind:
def test_union_with_weight(self):
wuf = WeightedUnionFind(3)
wuf.union(0, 1, 5)
diff = wuf.diff(0, 1)
assert diff == 5
def test_diff_unconnected(self):
wuf = WeightedUnionFind(3)
assert wuf.diff(0, 1) is None
class TestKruskalMST:
def test_simple(self):
edges = [(0, 1, 1), (1, 2, 2), (0, 2, 3)]
mst = kruskal_mst(3, edges)
total = sum(w for _, _, w in mst)
assert total == 3
assert len(mst) == 2
def test_disconnected(self):
edges = [(0, 1, 1)]
mst = kruskal_mst(3, edges)
assert len(mst) == 1
class TestCountIslands:
def test_single_island(self):
grid = [
[1, 1, 0],
[1, 1, 0],
[0, 0, 0]
]
assert count_islands(grid) == 1
def test_multiple_islands(self):
grid = [
[1, 0, 1],
[0, 0, 0],
[1, 0, 1]
]
assert count_islands(grid) == 4
def test_empty(self):
assert count_islands([]) == 0
class TestConnectivity:
def test_connected(self):
edges = [(0, 1), (1, 2)]
assert is_connected_graph(3, edges)
def test_disconnected(self):
edges = [(0, 1)]
assert not is_connected_graph(3, edges)
class TestRedundantConnection:
def test_has_redundant(self):
edges = [(0, 1), (1, 2), (2, 0)]
result = redundant_connection(3, edges)
assert result == (2, 0)
def test_no_redundant(self):
edges = [(0, 1), (1, 2)]
assert redundant_connection(3, edges) is None
class TestEarliestConnection:
def test_finds_time(self):
edges = [(0, 1), (1, 2)]
assert earliest_connection(3, edges) == 1
def test_never_connected(self):
edges = [(0, 1)]
assert earliest_connection(3, edges) == -1
class TestLargestComponent:
def test_single(self):
edges = [(0, 1), (1, 2)]
assert largest_component(4, edges) == 3
def test_multiple(self):
edges = [(0, 1), (2, 3), (3, 4)]
assert largest_component(5, edges) == 3
class TestSimulateUF:
def test_union_find(self):
result = simulate_uf(5, ["union:0:1", "find:1"])
assert len(result) == 1
def test_connected(self):
result = simulate_uf(5, ["union:0:1", "connected:0:1"])
assert result == [1]
def test_count(self):
result = simulate_uf(5, ["union:0:1", "count"])
assert result == [4]
def test_size(self):
result = simulate_uf(5, ["union:0:1", "union:1:2", "size:0"])
assert result == [3]
| false
|
graph_unionfind
| 160
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Var("w"), generators: [HirComprehension { target: "(_, _, w)", iter: Var("mst"), conditions: [] }] }
|
|
example_groups
|
groups_tool.py
|
#!/usr/bin/env python3
"""Groups Example - Argument groups CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Argument groups tool")
subs = parser.add_subparsers(dest="cmd", required=True)
r = subs.add_parser("run")
r.add_argument("--verbose", action="store_true")
r.add_argument("--quiet", action="store_true")
args = parser.parse_args()
if args.cmd == "run":
if args.verbose:
print("Running in verbose mode")
elif args.quiet:
print("Running in quiet mode")
else:
print("Running in normal mode")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_groups/groups_tool.py (661 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_groups/groups_tool.rs (1093 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_groups/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 13.6 KB/s
⏱️ Total time: 47ms
| true
|
groups
| 26
| 6
|
[] | 0
| null |
example_groups
|
test_groups_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for argument groups CLI."""
import subprocess
SCRIPT = "groups_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestGroups:
def test_verbose(self): r = run(["run", "--verbose"]); assert r.returncode == 0 and "verbose" in r.stdout.lower()
def test_quiet(self): r = run(["run", "--quiet"]); assert r.returncode == 0 and "quiet" in r.stdout.lower()
def test_default(self): r = run(["run"]); assert r.returncode == 0
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_groups/test_groups_tool.py (648 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_groups/test_groups_tool.rs (1869 bytes)
⏱️ Parse time: 45ms
📊 Throughput: 13.8 KB/s
⏱️ Total time: 45ms
| true
|
groups
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_gzip
|
gzip_tool.py
|
#!/usr/bin/env python3
"""Gzip Example - Compression info CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Compression info tool")
subs = parser.add_subparsers(dest="cmd", required=True)
r = subs.add_parser("ratio")
r.add_argument("original", type=int)
r.add_argument("compressed", type=int)
s = subs.add_parser("savings")
s.add_argument("original", type=int)
s.add_argument("compressed", type=int)
args = parser.parse_args()
if args.cmd == "ratio":
print(args.original / args.compressed)
elif args.cmd == "savings":
print((args.original - args.compressed) * 100 / args.original)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_gzip/gzip_tool.py (718 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_gzip/gzip_tool.rs (1588 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_gzip/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 14.4 KB/s
⏱️ Total time: 49ms
| true
|
gzip
| 26
| 6
|
[] | 0
| null |
example_gzip
|
test_gzip_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for gzip CLI."""
import subprocess
SCRIPT = "gzip_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCompression:
def test_ratio(self): r = run(["ratio", "1000", "100"]); assert r.returncode == 0 and "10" in r.stdout
def test_savings(self): r = run(["savings", "1000", "100"]); assert r.returncode == 0 and "90" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_gzip/test_gzip_tool.py (557 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_gzip/test_gzip_tool.rs (1762 bytes)
⏱️ Parse time: 46ms
📊 Throughput: 11.6 KB/s
⏱️ Total time: 47ms
| true
|
gzip
| 13
| 5
|
[
"class_definition"
] | 0.612
| null |
example_hash2
|
hash2_tool.py
|
#!/usr/bin/env python3
"""Hash2 Example - Hash operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Hash operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
d = subs.add_parser("djb2")
d.add_argument("text")
f = subs.add_parser("fnv")
f.add_argument("text")
s = subs.add_parser("simple")
s.add_argument("text")
args = parser.parse_args()
if args.cmd == "djb2":
h = 5381
i = 0
while i < len(args.text):
h = ((h * 33) + ord(args.text[i])) % (2**32)
i = i + 1
print(h)
elif args.cmd == "fnv":
h = 2166136261
i = 0
while i < len(args.text):
h = (h * 16777619) % (2**32)
h = h ^ ord(args.text[i])
i = i + 1
print(h)
elif args.cmd == "simple":
h = 0
i = 0
while i < len(args.text):
h = h + ord(args.text[i])
i = i + 1
print(h)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hash2/hash2_tool.py (1056 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hash2/hash2_tool.rs (4259 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hash2/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 20.5 KB/s
⏱️ Total time: 50ms
| true
|
hash2
| 44
| 6
|
[] | 0
| null |
example_hash2
|
test_hash2_tool.py
|
"""Tests for hash2_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "hash2_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_djb2():
r = run("djb2 hello")
assert r.returncode == 0
assert r.stdout.strip().isdigit()
def test_fnv():
r = run("fnv hello")
assert r.returncode == 0
assert r.stdout.strip().isdigit()
def test_simple():
r = run("simple abc")
assert r.returncode == 0
assert r.stdout.strip() == "294"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hash2/test_hash2_tool.py (616 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hash2/test_hash2_tool.rs (1844 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hash2/Cargo.toml (2 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 12.9 KB/s
⏱️ Total time: 46ms
| true
|
hash2
| 32
| 6
|
[] | 0
| null |
example_hashlib
|
hash_tool.py
|
#!/usr/bin/env python3
"""Hashlib Example - Hashing CLI."""
import argparse
import hashlib
import sys
def cmd_md5(args):
"""MD5 hash stdin. Depyler: proven to terminate"""
data = sys.stdin.read().encode()
print(hashlib.md5(data).hexdigest())
def cmd_sha256(args):
"""SHA256 hash stdin. Depyler: proven to terminate"""
data = sys.stdin.read().encode()
print(hashlib.sha256(data).hexdigest())
def cmd_file(args):
"""Hash file. Depyler: proven to terminate"""
h = hashlib.new(args.algo)
with open(args.path, "rb") as f:
h.update(f.read())
print(f"{args.algo}: {h.hexdigest()}")
def main():
parser = argparse.ArgumentParser(description="Hash tool")
subs = parser.add_subparsers(dest="command", required=True)
subs.add_parser("md5")
subs.add_parser("sha256")
f = subs.add_parser("file")
f.add_argument("path")
f.add_argument("--algo", default="sha256")
args = parser.parse_args()
{"md5": cmd_md5, "sha256": cmd_sha256, "file": cmd_file}[args.command](args)
if __name__ == "__main__":
main()
| false
|
hashlib
| 42
| 0
|
[
"context_manager",
"stdin_usage"
] | 0.652
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 968..1038, value: Dict(ExprDict { range: 968..1024, keys: [Some(Constant(ExprConstant { range: 969..974, value: Str("md5"), kind: None })), Some(Constant(ExprConstant { range: 985..993, value: Str("sha256"), kind: None })), Some(Constant(ExprConstant { range: 1007..1013, value: Str("file"), kind: None }))], values: [Name(ExprName { range: 976..983, id: Identifier("cmd_md5"), ctx: Load }), Name(ExprName { range: 995..1005, id
|
|
example_hashlib
|
test_hash_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for hashlib CLI."""
import os
import subprocess
import tempfile
SCRIPT = "hash_tool.py"
def run(args, input_text=None): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, input=input_text, cwd=__file__.rsplit("/", 1)[0])
class TestMD5:
def test_md5(self):
result = run(["md5"], "hello")
assert result.returncode == 0
assert "5d41402abc4b2a76b9719d911017c592" in result.stdout
class TestSHA256:
def test_sha256(self):
result = run(["sha256"], "hello")
assert result.returncode == 0
assert "2cf24dba" in result.stdout
class TestFile:
def test_file_hash(self):
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("test")
path = f.name
try:
result = run(["file", path, "--algo", "md5"])
assert result.returncode == 0
finally:
os.unlink(path)
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hashlib/test_hash_tool.py (1094 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hashlib/test_hash_tool.rs (2729 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hashlib/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 21.7 KB/s
⏱️ Total time: 49ms
| true
|
hashlib
| 36
| 6
|
[
"context_manager",
"class_definition",
"exception_handling"
] | 0.652
| null |
example_heap_queue
|
heap_cli.py
|
#!/usr/bin/env python3
"""Heap Queue CLI.
Min heap and max heap implementations with priority queue operations.
"""
import argparse
import sys
class MinHeap:
"""Min heap implementation."""
def __init__(self):
self.heap: list[int] = []
def parent(self, i: int) -> int:
"""Get parent index."""
return (i - 1) // 2
def left_child(self, i: int) -> int:
"""Get left child index."""
return 2 * i + 1
def right_child(self, i: int) -> int:
"""Get right child index."""
return 2 * i + 2
def push(self, value: int) -> None:
"""Push a value onto the heap."""
self.heap.append(value)
self._sift_up(len(self.heap) - 1)
def pop(self) -> int | None:
"""Pop and return the minimum value."""
if not self.heap:
return None
if len(self.heap) == 1:
return self.heap.pop()
root = self.heap[0]
self.heap[0] = self.heap.pop()
self._sift_down(0)
return root
def peek(self) -> int | None:
"""Return the minimum value without removing it."""
return self.heap[0] if self.heap else None
def _sift_up(self, i: int) -> None:
"""Move element up to maintain heap property."""
while i > 0:
parent = self.parent(i)
if self.heap[i] < self.heap[parent]:
self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]
i = parent
else:
break
def _sift_down(self, i: int) -> None:
"""Move element down to maintain heap property."""
size = len(self.heap)
while True:
smallest = i
left = self.left_child(i)
right = self.right_child(i)
if left < size and self.heap[left] < self.heap[smallest]:
smallest = left
if right < size and self.heap[right] < self.heap[smallest]:
smallest = right
if smallest != i:
self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i]
i = smallest
else:
break
def size(self) -> int:
"""Return the number of elements."""
return len(self.heap)
def is_empty(self) -> bool:
"""Check if heap is empty."""
return len(self.heap) == 0
def to_list(self) -> list[int]:
"""Return heap as list."""
return self.heap.copy()
class MaxHeap:
"""Max heap implementation using negation."""
def __init__(self):
self.min_heap = MinHeap()
def push(self, value: int) -> None:
"""Push a value onto the heap."""
self.min_heap.push(-value)
def pop(self) -> int | None:
"""Pop and return the maximum value."""
result = self.min_heap.pop()
return -result if result is not None else None
def peek(self) -> int | None:
"""Return the maximum value without removing it."""
result = self.min_heap.peek()
return -result if result is not None else None
def size(self) -> int:
"""Return the number of elements."""
return self.min_heap.size()
def is_empty(self) -> bool:
"""Check if heap is empty."""
return self.min_heap.is_empty()
def to_list(self) -> list[int]:
"""Return heap as list (negated back)."""
return [-x for x in self.min_heap.to_list()]
class PriorityQueue:
"""Priority queue with key-value pairs."""
def __init__(self, max_priority: bool = False):
self.entries: list[tuple[int, str]] = []
self.max_priority = max_priority
def push(self, priority: int, value: str) -> None:
"""Push item with priority."""
self.entries.append((priority, value))
self._sift_up(len(self.entries) - 1)
def pop(self) -> tuple[int, str] | None:
"""Pop highest priority item."""
if not self.entries:
return None
if len(self.entries) == 1:
return self.entries.pop()
root = self.entries[0]
self.entries[0] = self.entries.pop()
self._sift_down(0)
return root
def peek(self) -> tuple[int, str] | None:
"""Return highest priority item without removing."""
return self.entries[0] if self.entries else None
def _compare(self, a: tuple[int, str], b: tuple[int, str]) -> bool:
"""Compare two entries based on priority direction."""
if self.max_priority:
return a[0] > b[0]
return a[0] < b[0]
def _sift_up(self, i: int) -> None:
"""Move element up to maintain heap property."""
while i > 0:
parent = (i - 1) // 2
if self._compare(self.entries[i], self.entries[parent]):
self.entries[i], self.entries[parent] = self.entries[parent], self.entries[i]
i = parent
else:
break
def _sift_down(self, i: int) -> None:
"""Move element down to maintain heap property."""
size = len(self.entries)
while True:
best = i
left = 2 * i + 1
right = 2 * i + 2
if left < size and self._compare(self.entries[left], self.entries[best]):
best = left
if right < size and self._compare(self.entries[right], self.entries[best]):
best = right
if best != i:
self.entries[i], self.entries[best] = self.entries[best], self.entries[i]
i = best
else:
break
def size(self) -> int:
"""Return the number of elements."""
return len(self.entries)
def is_empty(self) -> bool:
"""Check if queue is empty."""
return len(self.entries) == 0
def heapify(arr: list[int]) -> list[int]:
"""Convert array to min heap in-place."""
result = arr.copy()
n = len(result)
for i in range(n // 2 - 1, -1, -1):
_heapify_down(result, n, i)
return result
def _heapify_down(arr: list[int], n: int, i: int) -> None:
"""Helper for heapify."""
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] < arr[smallest]:
smallest = left
if right < n and arr[right] < arr[smallest]:
smallest = right
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
_heapify_down(arr, n, smallest)
def heap_sort(arr: list[int], reverse: bool = False) -> list[int]:
"""Sort array using heap sort."""
if not arr:
return []
result = arr.copy()
n = len(result)
# Build max heap for ascending, min heap for descending
for i in range(n // 2 - 1, -1, -1):
_heap_sort_down(result, n, i, reverse)
# Extract elements one by one
for i in range(n - 1, 0, -1):
result[0], result[i] = result[i], result[0]
_heap_sort_down(result, i, 0, reverse)
return result
def _heap_sort_down(arr: list[int], n: int, i: int, reverse: bool) -> None:
"""Helper for heap sort."""
extreme = i
left = 2 * i + 1
right = 2 * i + 2
if reverse:
if left < n and arr[left] < arr[extreme]:
extreme = left
if right < n and arr[right] < arr[extreme]:
extreme = right
else:
if left < n and arr[left] > arr[extreme]:
extreme = left
if right < n and arr[right] > arr[extreme]:
extreme = right
if extreme != i:
arr[i], arr[extreme] = arr[extreme], arr[i]
_heap_sort_down(arr, n, extreme, reverse)
def k_smallest(arr: list[int], k: int) -> list[int]:
"""Find k smallest elements."""
if k <= 0 or not arr:
return []
heap = MinHeap()
for x in arr:
heap.push(x)
result = []
for _ in range(min(k, len(arr))):
val = heap.pop()
if val is not None:
result.append(val)
return result
def k_largest(arr: list[int], k: int) -> list[int]:
"""Find k largest elements."""
if k <= 0 or not arr:
return []
heap = MaxHeap()
for x in arr:
heap.push(x)
result = []
for _ in range(min(k, len(arr))):
val = heap.pop()
if val is not None:
result.append(val)
return result
def merge_k_sorted_arrays(arrays: list[list[int]]) -> list[int]:
"""Merge k sorted arrays using a min heap."""
if not arrays:
return []
result = []
# Track (value, array_index, element_index)
heap: list[tuple[int, int, int]] = []
# Initialize with first element from each array
for i, arr in enumerate(arrays):
if arr:
heap.append((arr[0], i, 0))
# Heapify
n = len(heap)
for i in range(n // 2 - 1, -1, -1):
_heapify_tuple(heap, n, i)
while heap:
# Extract min
val, arr_idx, elem_idx = heap[0]
result.append(val)
# Replace with next element from same array or last element
next_idx = elem_idx + 1
if next_idx < len(arrays[arr_idx]):
heap[0] = (arrays[arr_idx][next_idx], arr_idx, next_idx)
else:
heap[0] = heap[-1]
heap.pop()
if heap:
_heapify_tuple(heap, len(heap), 0)
return result
def _heapify_tuple(arr: list[tuple[int, int, int]], n: int, i: int) -> None:
"""Heapify for tuple comparisons."""
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left][0] < arr[smallest][0]:
smallest = left
if right < n and arr[right][0] < arr[smallest][0]:
smallest = right
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
_heapify_tuple(arr, n, smallest)
def is_valid_heap(arr: list[int], max_heap: bool = False) -> bool:
"""Check if array represents a valid heap."""
n = len(arr)
for i in range((n - 2) // 2 + 1):
left = 2 * i + 1
right = 2 * i + 2
if max_heap:
if left < n and arr[i] < arr[left]:
return False
if right < n and arr[i] < arr[right]:
return False
else:
if left < n and arr[i] > arr[left]:
return False
if right < n and arr[i] > arr[right]:
return False
return True
def main() -> int:
parser = argparse.ArgumentParser(description="Heap queue operations")
parser.add_argument("values", nargs="*", type=int, help="Values to process")
parser.add_argument(
"--mode",
choices=["heap", "sort", "ksmallest", "klargest", "validate"],
default="heap",
help="Operation mode",
)
parser.add_argument("--max", action="store_true", help="Use max heap")
parser.add_argument("-k", type=int, default=3, help="K for k-smallest/largest")
args = parser.parse_args()
if not args.values:
values = [int(x) for x in sys.stdin.read().split()]
else:
values = args.values
if args.mode == "heap":
result = heapify(values)
if args.max:
result = [-x for x in heapify([-x for x in values])]
print(f"Heapified: {' '.join(map(str, result))}")
elif args.mode == "sort":
result = heap_sort(values, reverse=args.max)
print(f"Sorted: {' '.join(map(str, result))}")
elif args.mode == "ksmallest":
result = k_smallest(values, args.k)
print(f"K smallest: {' '.join(map(str, result))}")
elif args.mode == "klargest":
result = k_largest(values, args.k)
print(f"K largest: {' '.join(map(str, result))}")
elif args.mode == "validate":
if is_valid_heap(values, args.max):
heap_type = "max" if args.max else "min"
print(f"Valid {heap_type} heap: Yes")
else:
print("Valid heap: No")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
heap_queue
| 430
| 0
|
[
"context_manager",
"class_definition",
"stdin_usage"
] | 0.652
|
Type inference hints:
Hint: list[Any] for variable 'result' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'arr' [High] (usage patterns suggest this type)
Hint: int for variable 'i' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'n' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'result' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable '
|
|
example_heap_queue
|
test_heap_cli.py
|
"""Tests for heap_cli.py"""
from heap_cli import (
MaxHeap,
MinHeap,
PriorityQueue,
heap_sort,
heapify,
is_valid_heap,
k_largest,
k_smallest,
merge_k_sorted_arrays,
)
class TestMinHeap:
def test_init(self):
heap = MinHeap()
assert heap.is_empty()
assert heap.size() == 0
def test_push(self):
heap = MinHeap()
heap.push(5)
assert heap.size() == 1
assert heap.peek() == 5
def test_push_multiple(self):
heap = MinHeap()
heap.push(5)
heap.push(3)
heap.push(7)
assert heap.peek() == 3
def test_pop(self):
heap = MinHeap()
heap.push(5)
heap.push(3)
heap.push(7)
assert heap.pop() == 3
assert heap.pop() == 5
assert heap.pop() == 7
def test_pop_empty(self):
heap = MinHeap()
assert heap.pop() is None
def test_peek_empty(self):
heap = MinHeap()
assert heap.peek() is None
def test_maintains_heap_property(self):
heap = MinHeap()
for x in [3, 1, 4, 1, 5, 9, 2, 6]:
heap.push(x)
assert is_valid_heap(heap.to_list())
def test_to_list(self):
heap = MinHeap()
heap.push(3)
heap.push(1)
heap.push(2)
lst = heap.to_list()
assert len(lst) == 3
assert lst[0] == 1 # Min at root
class TestMaxHeap:
def test_init(self):
heap = MaxHeap()
assert heap.is_empty()
def test_push(self):
heap = MaxHeap()
heap.push(5)
assert heap.peek() == 5
def test_push_multiple(self):
heap = MaxHeap()
heap.push(5)
heap.push(3)
heap.push(7)
assert heap.peek() == 7
def test_pop(self):
heap = MaxHeap()
heap.push(5)
heap.push(3)
heap.push(7)
assert heap.pop() == 7
assert heap.pop() == 5
assert heap.pop() == 3
def test_pop_empty(self):
heap = MaxHeap()
assert heap.pop() is None
class TestPriorityQueue:
def test_init(self):
pq = PriorityQueue()
assert pq.is_empty()
def test_min_priority(self):
pq = PriorityQueue(max_priority=False)
pq.push(3, "three")
pq.push(1, "one")
pq.push(2, "two")
assert pq.peek() == (1, "one")
assert pq.pop() == (1, "one")
assert pq.pop() == (2, "two")
def test_max_priority(self):
pq = PriorityQueue(max_priority=True)
pq.push(3, "three")
pq.push(1, "one")
pq.push(2, "two")
assert pq.peek() == (3, "three")
assert pq.pop() == (3, "three")
assert pq.pop() == (2, "two")
def test_empty_pop(self):
pq = PriorityQueue()
assert pq.pop() is None
def test_empty_peek(self):
pq = PriorityQueue()
assert pq.peek() is None
class TestHeapify:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = heapify(arr)
assert is_valid_heap(result)
def test_empty(self):
assert heapify([]) == []
def test_single(self):
assert heapify([5]) == [5]
def test_already_heap(self):
arr = [1, 2, 3, 4, 5]
result = heapify(arr)
assert is_valid_heap(result)
def test_original_unchanged(self):
arr = [3, 1, 4]
heapify(arr)
assert arr == [3, 1, 4]
class TestHeapSort:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = heap_sort(arr)
assert result == [1, 1, 2, 3, 4, 5, 6, 9]
def test_empty(self):
assert heap_sort([]) == []
def test_single(self):
assert heap_sort([5]) == [5]
def test_reverse(self):
arr = [3, 1, 4, 1, 5]
result = heap_sort(arr, reverse=True)
assert result == [5, 4, 3, 1, 1]
def test_already_sorted(self):
arr = [1, 2, 3, 4, 5]
assert heap_sort(arr) == [1, 2, 3, 4, 5]
def test_reverse_sorted(self):
arr = [5, 4, 3, 2, 1]
assert heap_sort(arr) == [1, 2, 3, 4, 5]
def test_duplicates(self):
arr = [3, 3, 3, 1, 1, 2, 2]
assert heap_sort(arr) == [1, 1, 2, 2, 3, 3, 3]
class TestKSmallest:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = k_smallest(arr, 3)
assert result == [1, 1, 2]
def test_empty(self):
assert k_smallest([], 3) == []
def test_k_zero(self):
assert k_smallest([1, 2, 3], 0) == []
def test_k_larger_than_array(self):
arr = [3, 1, 2]
result = k_smallest(arr, 5)
assert sorted(result) == [1, 2, 3]
def test_all_same(self):
arr = [5, 5, 5, 5]
result = k_smallest(arr, 2)
assert result == [5, 5]
class TestKLargest:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = k_largest(arr, 3)
assert result == [9, 6, 5]
def test_empty(self):
assert k_largest([], 3) == []
def test_k_zero(self):
assert k_largest([1, 2, 3], 0) == []
def test_k_larger_than_array(self):
arr = [3, 1, 2]
result = k_largest(arr, 5)
assert sorted(result, reverse=True) == [3, 2, 1]
class TestMergeKSortedArrays:
def test_basic(self):
arrays = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
result = merge_k_sorted_arrays(arrays)
assert result == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_empty(self):
assert merge_k_sorted_arrays([]) == []
def test_single_array(self):
arrays = [[1, 2, 3]]
assert merge_k_sorted_arrays(arrays) == [1, 2, 3]
def test_unequal_lengths(self):
arrays = [[1, 3], [2], [4, 5, 6]]
assert merge_k_sorted_arrays(arrays) == [1, 2, 3, 4, 5, 6]
def test_with_empty_arrays(self):
arrays = [[1, 3], [], [2, 4]]
assert merge_k_sorted_arrays(arrays) == [1, 2, 3, 4]
class TestIsValidHeap:
def test_valid_min_heap(self):
arr = [1, 2, 3, 4, 5, 6, 7]
assert is_valid_heap(arr) is True
def test_invalid_min_heap(self):
arr = [1, 2, 3, 0, 5, 6, 7] # 0 < 1 (root)
assert is_valid_heap(arr) is False
def test_valid_max_heap(self):
arr = [7, 6, 5, 4, 3, 2, 1]
assert is_valid_heap(arr, max_heap=True) is True
def test_invalid_max_heap(self):
arr = [7, 6, 5, 8, 3, 2, 1] # 8 > 7 (root)
assert is_valid_heap(arr, max_heap=True) is False
def test_empty(self):
assert is_valid_heap([]) is True
def test_single(self):
assert is_valid_heap([5]) is True
| false
|
heap_queue
| 276
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: SortByKey { iterable: Var("result"), key_params: ["x"], key_body: Var("x"), reverse_expr: Some(Literal(Bool(true))) }
|
|
example_heapq
|
heap_tool.py
|
#!/usr/bin/env python3
"""Heapq Example - Heap min/max CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Heap operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
m = subs.add_parser("min")
m.add_argument("a", type=int)
m.add_argument("b", type=int)
m.add_argument("c", type=int)
mx = subs.add_parser("max")
mx.add_argument("a", type=int)
mx.add_argument("b", type=int)
mx.add_argument("c", type=int)
args = parser.parse_args()
if args.cmd == "min":
print(min(args.a, min(args.b, args.c)))
elif args.cmd == "max":
print(max(args.a, max(args.b, args.c)))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_heapq/heap_tool.py (721 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_heapq/heap_tool.rs (1090 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_heapq/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 14.9 KB/s
⏱️ Total time: 47ms
| true
|
heapq
| 29
| 6
|
[] | 0
| null |
example_heapq
|
test_heap_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for heapq CLI."""
import subprocess
SCRIPT = "heap_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestMinMax:
def test_min(self): r = run(["min", "5", "3", "8"]); assert "3" in r.stdout
def test_max(self): r = run(["max", "5", "3", "8"]); assert "8" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_heapq/test_heap_tool.py (495 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_heapq/test_heap_tool.rs (1838 bytes)
⏱️ Parse time: 47ms
📊 Throughput: 10.2 KB/s
⏱️ Total time: 47ms
| true
|
heapq
| 13
| 5
|
[
"class_definition"
] | 0.612
| null |
example_hex_dump
|
hexdump_cli.py
|
#!/usr/bin/env python3
"""Hex dump utility CLI.
Display and convert binary data in various formats.
"""
import argparse
import sys
def format_hex_line(
offset: int,
data: bytes,
bytes_per_line: int = 16,
show_ascii: bool = True,
) -> str:
"""Format a single line of hex dump."""
parts = []
# Offset
parts.append(f"{offset:08x}")
# Hex bytes
hex_parts = []
for i, byte in enumerate(data):
hex_parts.append(f"{byte:02x}")
if i == 7:
hex_parts.append("") # Extra space at midpoint
# Pad if needed
if len(data) < bytes_per_line:
for i in range(len(data), bytes_per_line):
hex_parts.append(" ")
if i == 7:
hex_parts.append("")
parts.append(" ".join(hex_parts))
# ASCII representation
if show_ascii:
ascii_chars = []
for byte in data:
if 32 <= byte < 127:
ascii_chars.append(chr(byte))
else:
ascii_chars.append(".")
parts.append("|" + "".join(ascii_chars) + "|")
return " ".join(parts)
def hexdump(
data: bytes,
bytes_per_line: int = 16,
show_ascii: bool = True,
start_offset: int = 0,
) -> list[str]:
"""Generate hex dump of data."""
lines = []
offset = start_offset
for i in range(0, len(data), bytes_per_line):
chunk = data[i : i + bytes_per_line]
lines.append(format_hex_line(offset, chunk, bytes_per_line, show_ascii))
offset += bytes_per_line
return lines
def hexdump_c_array(
data: bytes,
name: str = "data",
bytes_per_line: int = 12,
) -> list[str]:
"""Generate C array from binary data."""
lines = []
lines.append(f"unsigned char {name}[] = {{")
for i in range(0, len(data), bytes_per_line):
chunk = data[i : i + bytes_per_line]
hex_values = [f"0x{b:02x}" for b in chunk]
line = " " + ", ".join(hex_values)
if i + bytes_per_line < len(data):
line += ","
lines.append(line)
lines.append("};")
lines.append(f"unsigned int {name}_len = {len(data)};")
return lines
def parse_hex(hex_str: str) -> bytes:
"""Parse hex string to bytes."""
# Remove common prefixes and separators
hex_str = hex_str.replace("0x", "").replace("0X", "")
hex_str = hex_str.replace(" ", "").replace(":", "").replace("-", "")
hex_str = hex_str.replace("\n", "").replace("\r", "")
return bytes.fromhex(hex_str)
def bytes_to_hex(data: bytes, separator: str = " ") -> str:
"""Convert bytes to hex string."""
return separator.join(f"{b:02x}" for b in data)
def find_pattern(data: bytes, pattern: bytes) -> list[int]:
"""Find all occurrences of pattern in data."""
positions = []
start = 0
while True:
pos = data.find(pattern, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
def extract_strings(data: bytes, min_length: int = 4) -> list[tuple[int, str]]:
"""Extract printable ASCII strings from binary data."""
strings = []
current = []
start_pos = 0
for i, byte in enumerate(data):
if 32 <= byte < 127:
if not current:
start_pos = i
current.append(chr(byte))
else:
if len(current) >= min_length:
strings.append((start_pos, "".join(current)))
current = []
if len(current) >= min_length:
strings.append((start_pos, "".join(current)))
return strings
def main() -> int:
parser = argparse.ArgumentParser(description="Hex dump utility")
parser.add_argument("input", nargs="?", help="Input file (- for stdin)")
parser.add_argument("-n", "--length", type=int, help="Number of bytes to read")
parser.add_argument("-s", "--skip", type=int, default=0, help="Skip bytes at start")
parser.add_argument("-c", "--columns", type=int, default=16, help="Bytes per line")
parser.add_argument("--no-ascii", action="store_true", help="Don't show ASCII column")
parser.add_argument(
"-r", "--reverse", action="store_true", help="Reverse: convert hex to binary"
)
parser.add_argument("-C", "--c-array", metavar="NAME", help="Output as C array")
parser.add_argument(
"--strings",
type=int,
nargs="?",
const=4,
metavar="LEN",
help="Extract strings (min length)",
)
parser.add_argument("--find", metavar="HEX", help="Find hex pattern in data")
parser.add_argument("-o", "--output", help="Output file")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
if args.reverse:
data = sys.stdin.read()
else:
data = sys.stdin.buffer.read()
else:
if args.reverse:
with open(args.input) as f:
data = f.read()
else:
with open(args.input, "rb") as f:
data = f.read()
# Apply skip and length
if not args.reverse:
if args.skip > 0:
data = data[args.skip :]
if args.length:
data = data[: args.length]
# Process
if args.reverse:
try:
result = parse_hex(data)
if args.output:
with open(args.output, "wb") as f:
f.write(result)
else:
sys.stdout.buffer.write(result)
return 0
except ValueError as e:
print(f"Invalid hex: {e}", file=sys.stderr)
return 1
if args.strings is not None:
strings = extract_strings(data, args.strings)
output = "\n".join(f"{offset:08x} {s}" for offset, s in strings)
if args.output:
with open(args.output, "w") as f:
f.write(output)
else:
print(output)
return 0
if args.find:
try:
pattern = parse_hex(args.find)
except ValueError as e:
print(f"Invalid pattern: {e}", file=sys.stderr)
return 1
positions = find_pattern(data, pattern)
if positions:
print(f"Found {len(positions)} occurrence(s):")
for pos in positions:
print(f" 0x{pos:08x}")
else:
print("Pattern not found")
return 0
if args.c_array:
lines = hexdump_c_array(data, args.c_array, args.columns)
output = "\n".join(lines)
if args.output:
with open(args.output, "w") as f:
f.write(output)
else:
print(output)
return 0
# Default: hex dump
lines = hexdump(
data,
bytes_per_line=args.columns,
show_ascii=not args.no_ascii,
start_offset=args.skip,
)
output = "\n".join(lines)
if args.output:
with open(args.output, "w") as f:
f.write(output)
else:
print(output)
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hex_dump/hexdump_cli.py (7078 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hex_dump/hexdump_cli.rs (13864 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hex_dump/Cargo.toml (1 dependencies)
⏱️ Parse time: 60ms
📊 Throughput: 113.4 KB/s
⏱️ Total time: 61ms
| true
|
hex_dump
| 259
| 6
|
[
"context_manager",
"exception_handling",
"stdin_usage",
"multiprocessing"
] | 0.652
| null |
example_hex_dump
|
test_hexdump_cli.py
|
"""Tests for hexdump_cli.py"""
from hexdump_cli import (
bytes_to_hex,
extract_strings,
find_pattern,
format_hex_line,
hexdump,
hexdump_c_array,
parse_hex,
)
class TestFormatHexLine:
def test_simple(self):
data = bytes([0x48, 0x65, 0x6c, 0x6c, 0x6f]) # "Hello"
result = format_hex_line(0, data, 16, True)
assert "00000000" in result
assert "48 65 6c 6c 6f" in result
assert "|Hello" in result
def test_no_ascii(self):
data = b"test"
result = format_hex_line(0, data, 16, False)
assert "|" not in result
def test_non_printable(self):
data = bytes([0x00, 0x01, 0x7F, 0xFF])
result = format_hex_line(0, data, 16, True)
assert "|....|" in result # Non-printable shown as dots
def test_offset(self):
data = b"test"
result = format_hex_line(0x100, data, 16, True)
assert "00000100" in result
class TestHexdump:
def test_simple(self):
data = b"Hello, World!"
lines = hexdump(data, 16, True, 0)
assert len(lines) == 1
assert "Hello, World!" in lines[0]
def test_multiline(self):
data = b"a" * 32
lines = hexdump(data, 16, True, 0)
assert len(lines) == 2
def test_start_offset(self):
data = b"test"
lines = hexdump(data, 16, True, 0x100)
assert "00000100" in lines[0]
class TestHexdumpCArray:
def test_simple(self):
data = b"\x01\x02\x03"
lines = hexdump_c_array(data, "test_data", 12)
assert "unsigned char test_data[]" in lines[0]
assert "0x01" in lines[1]
assert "0x02" in lines[1]
assert "0x03" in lines[1]
assert "test_data_len = 3" in lines[-1]
def test_multiline(self):
data = bytes(range(24))
lines = hexdump_c_array(data, "data", 12)
# Should have: header, 2 data lines, close brace, length
assert len(lines) == 5
class TestParseHex:
def test_simple(self):
assert parse_hex("48656c6c6f") == b"Hello"
def test_spaces(self):
assert parse_hex("48 65 6c 6c 6f") == b"Hello"
def test_prefix(self):
assert parse_hex("0x48 0x65") == b"He"
def test_colons(self):
assert parse_hex("48:65:6c:6c:6f") == b"Hello"
def test_dashes(self):
assert parse_hex("48-65-6c-6c-6f") == b"Hello"
def test_newlines(self):
assert parse_hex("4865\n6c6c6f") == b"Hello"
class TestBytesToHex:
def test_simple(self):
assert bytes_to_hex(b"Hello") == "48 65 6c 6c 6f"
def test_custom_separator(self):
assert bytes_to_hex(b"AB", ":") == "41:42"
def test_no_separator(self):
assert bytes_to_hex(b"AB", "") == "4142"
class TestFindPattern:
def test_single_match(self):
data = b"hello world"
positions = find_pattern(data, b"world")
assert positions == [6]
def test_multiple_matches(self):
data = b"abcabcabc"
positions = find_pattern(data, b"abc")
assert positions == [0, 3, 6]
def test_no_match(self):
data = b"hello"
positions = find_pattern(data, b"xyz")
assert positions == []
def test_overlapping(self):
data = b"aaaa"
positions = find_pattern(data, b"aa")
assert positions == [0, 1, 2]
class TestExtractStrings:
def test_simple(self):
data = b"\x00\x00hello\x00\x00world\x00\x00"
strings = extract_strings(data, 4)
assert len(strings) == 2
assert strings[0][1] == "hello"
assert strings[1][1] == "world"
def test_min_length(self):
data = b"\x00ab\x00abcd\x00"
strings = extract_strings(data, 4)
assert len(strings) == 1
assert strings[0][1] == "abcd"
def test_positions(self):
data = b"\x00\x00test"
strings = extract_strings(data, 4)
assert strings[0][0] == 2 # Position of "test"
def test_non_printable(self):
data = b"hello\x01world"
strings = extract_strings(data, 4)
assert len(strings) == 2
assert strings[0][1] == "hello"
assert strings[1][1] == "world"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hex_dump/test_hexdump_cli.py (4187 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hex_dump/test_hexdump_cli.rs (7806 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 81.4 KB/s
⏱️ Total time: 50ms
| true
|
hex_dump
| 151
| 5
|
[
"class_definition"
] | 0.612
| null |
example_hex_oct
|
hex_oct_tool.py
|
#!/usr/bin/env python3
"""Hex Oct Example - Number base conversion CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Number base conversion tool")
subs = parser.add_subparsers(dest="cmd", required=True)
h = subs.add_parser("hex")
h.add_argument("num", type=int)
o = subs.add_parser("oct")
o.add_argument("num", type=int)
d = subs.add_parser("dec")
d.add_argument("hexval")
args = parser.parse_args()
if args.cmd == "hex":
print(format(args.num, "x"))
elif args.cmd == "oct":
print(format(args.num, "o"))
elif args.cmd == "dec":
print(int(args.hexval, 16))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/hex_oct_tool.py (705 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/hex_oct_tool.rs (1488 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 14.7 KB/s
⏱️ Total time: 47ms
| true
|
hex_oct
| 28
| 6
|
[] | 0
| null |
example_hex_oct
|
test_hex_oct_tool.py
|
"""Tests for hex_oct_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "hex_oct_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_hex():
r = run("hex 255")
assert r.returncode == 0
assert r.stdout.strip() == "ff"
def test_oct():
r = run("oct 64")
assert r.returncode == 0
assert r.stdout.strip() == "100"
def test_dec():
r = run("dec ff")
assert r.returncode == 0
assert r.stdout.strip() == "255"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/test_hex_oct_tool.py (603 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/test_hex_oct_tool.rs (1809 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_hex_oct/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 12.5 KB/s
⏱️ Total time: 47ms
| true
|
hex_oct
| 32
| 6
|
[] | 0
| null |
example_html
|
html_tool.py
|
#!/usr/bin/env python3
"""HTML Example - HTML escape/unescape CLI."""
import argparse
import html
import re
import sys
def cmd_escape(args):
"""Escape HTML. Depyler: proven to terminate"""
text = sys.stdin.read()
print(html.escape(text))
def cmd_unescape(args):
"""Unescape HTML. Depyler: proven to terminate"""
text = sys.stdin.read()
print(html.unescape(text))
def cmd_strip(args):
"""Strip HTML tags. Depyler: proven to terminate"""
text = sys.stdin.read()
clean = re.sub(r"<[^>]+>", "", text)
print(clean)
def main():
parser = argparse.ArgumentParser(description="HTML tool")
subs = parser.add_subparsers(dest="command", required=True)
subs.add_parser("escape")
subs.add_parser("unescape")
subs.add_parser("strip")
args = parser.parse_args()
{"escape": cmd_escape, "unescape": cmd_unescape, "strip": cmd_strip}[args.command](args)
if __name__ == "__main__":
main()
| false
|
html
| 40
| 0
|
[
"stdin_usage"
] | 0.566
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 823..905, value: Dict(ExprDict { range: 823..891, keys: [Some(Constant(ExprConstant { range: 824..832, value: Str("escape"), kind: None })), Some(Constant(ExprConstant { range: 846..856, value: Str("unescape"), kind: None })), Some(Constant(ExprConstant { range: 872..879, value: Str("strip"), kind: None }))], values: [Name(ExprName { range: 834..844, id: Identifier("cmd_escape"), ctx: Load }), Name(ExprName { range: 858..870
|
|
example_html
|
test_html_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for html CLI."""
import subprocess
SCRIPT = "html_tool.py"
def run(args, input_text=None): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, input=input_text, cwd=__file__.rsplit("/", 1)[0])
class TestEscape:
def test_escape(self):
result = run(["escape"], "<div>Hello & World</div>")
assert result.returncode == 0
assert "<" in result.stdout
assert "&" in result.stdout
class TestUnescape:
def test_unescape(self):
result = run(["unescape"], "<div>")
assert result.returncode == 0
assert "<div>" in result.stdout
class TestStrip:
def test_strip(self):
result = run(["strip"], "<p>Hello <b>World</b></p>")
assert result.returncode == 0
assert "Hello" in result.stdout
assert "<" not in result.stdout
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_html/test_html_tool.py (1007 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_html/test_html_tool.rs (2549 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 19.5 KB/s
⏱️ Total time: 50ms
| true
|
html
| 31
| 5
|
[
"class_definition"
] | 0.612
| null |
example_http_parser
|
http_cli.py
|
#!/usr/bin/env python3
"""HTTP Parser CLI.
Parse and encode HTTP/1.1 protocol messages.
"""
import argparse
import sys
from dataclasses import dataclass, field
HTTP_STATUS_CODES = {
200: "OK",
201: "Created",
204: "No Content",
301: "Moved Permanently",
302: "Found",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable",
}
HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]
@dataclass
class HTTPRequest:
"""HTTP request message."""
method: str
path: str
version: str = "HTTP/1.1"
headers: dict[str, str] = field(default_factory=dict)
body: bytes = b""
@dataclass
class HTTPResponse:
"""HTTP response message."""
version: str
status_code: int
reason: str
headers: dict[str, str] = field(default_factory=dict)
body: bytes = b""
def parse_request_line(line: str) -> tuple[str, str, str]:
"""Parse HTTP request line."""
parts = line.split(" ", 2)
if len(parts) != 3:
raise ValueError(f"Invalid request line: {line}")
method, path, version = parts
if method not in HTTP_METHODS:
raise ValueError(f"Unknown HTTP method: {method}")
return method, path, version
def parse_status_line(line: str) -> tuple[str, int, str]:
"""Parse HTTP status line."""
parts = line.split(" ", 2)
if len(parts) < 2:
raise ValueError(f"Invalid status line: {line}")
version = parts[0]
status_code = int(parts[1])
reason = parts[2] if len(parts) > 2 else HTTP_STATUS_CODES.get(status_code, "")
return version, status_code, reason
def parse_headers(lines: list[str]) -> dict[str, str]:
"""Parse HTTP headers."""
headers = {}
for line in lines:
if not line:
break
if ":" not in line:
continue
key, value = line.split(":", 1)
headers[key.strip().lower()] = value.strip()
return headers
def parse_request(data: bytes) -> HTTPRequest:
"""Parse HTTP request from bytes."""
# Split headers and body
parts = data.split(b"\r\n\r\n", 1)
header_section = parts[0].decode("utf-8")
body = parts[1] if len(parts) > 1 else b""
lines = header_section.split("\r\n")
if not lines:
raise ValueError("Empty request")
method, path, version = parse_request_line(lines[0])
headers = parse_headers(lines[1:])
return HTTPRequest(method=method, path=path, version=version, headers=headers, body=body)
def parse_response(data: bytes) -> HTTPResponse:
"""Parse HTTP response from bytes."""
# Split headers and body
parts = data.split(b"\r\n\r\n", 1)
header_section = parts[0].decode("utf-8")
body = parts[1] if len(parts) > 1 else b""
lines = header_section.split("\r\n")
if not lines:
raise ValueError("Empty response")
version, status_code, reason = parse_status_line(lines[0])
headers = parse_headers(lines[1:])
return HTTPResponse(
version=version, status_code=status_code, reason=reason, headers=headers, body=body
)
def encode_request(request: HTTPRequest) -> bytes:
"""Encode HTTP request to bytes."""
lines = [f"{request.method} {request.path} {request.version}"]
for key, value in request.headers.items():
lines.append(f"{key}: {value}")
# Add Content-Length if body present and not already set
if request.body and "content-length" not in {k.lower() for k in request.headers}:
lines.append(f"Content-Length: {len(request.body)}")
header = "\r\n".join(lines) + "\r\n\r\n"
return header.encode("utf-8") + request.body
def encode_response(response: HTTPResponse) -> bytes:
"""Encode HTTP response to bytes."""
lines = [f"{response.version} {response.status_code} {response.reason}"]
for key, value in response.headers.items():
lines.append(f"{key}: {value}")
# Add Content-Length if body present and not already set
if response.body and "content-length" not in {k.lower() for k in response.headers}:
lines.append(f"Content-Length: {len(response.body)}")
header = "\r\n".join(lines) + "\r\n\r\n"
return header.encode("utf-8") + response.body
def parse_url(url: str) -> dict[str, str]:
"""Parse URL into components."""
result = {"scheme": "", "host": "", "port": "", "path": "/", "query": "", "fragment": ""}
# Remove fragment
if "#" in url:
url, result["fragment"] = url.rsplit("#", 1)
# Remove query string
if "?" in url:
url, result["query"] = url.split("?", 1)
# Extract scheme
if "://" in url:
result["scheme"], url = url.split("://", 1)
# Extract host and path
if "/" in url:
host_part, result["path"] = url.split("/", 1)
result["path"] = "/" + result["path"]
else:
host_part = url
# Extract port
if ":" in host_part:
result["host"], result["port"] = host_part.rsplit(":", 1)
else:
result["host"] = host_part
return result
def parse_query_string(query: str) -> dict[str, str]:
"""Parse query string into key-value pairs."""
if not query:
return {}
params = {}
for pair in query.split("&"):
if "=" in pair:
key, value = pair.split("=", 1)
params[url_decode(key)] = url_decode(value)
else:
params[url_decode(pair)] = ""
return params
def url_decode(s: str) -> str:
"""Decode URL-encoded string."""
result = []
i = 0
while i < len(s):
if s[i] == "%":
if i + 2 < len(s):
try:
result.append(chr(int(s[i + 1 : i + 3], 16)))
i += 3
continue
except ValueError:
pass
elif s[i] == "+":
result.append(" ")
i += 1
continue
result.append(s[i])
i += 1
return "".join(result)
def url_encode(s: str) -> str:
"""URL-encode a string."""
safe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
result = []
for char in s:
if char in safe:
result.append(char)
elif char == " ":
result.append("+")
else:
for byte in char.encode("utf-8"):
result.append(f"%{byte:02X}")
return "".join(result)
def build_query_string(params: dict[str, str]) -> str:
"""Build query string from parameters."""
parts = []
for key, value in params.items():
parts.append(f"{url_encode(key)}={url_encode(value)}")
return "&".join(parts)
def parse_content_type(content_type: str) -> tuple[str, dict[str, str]]:
"""Parse Content-Type header into media type and parameters."""
parts = content_type.split(";")
media_type = parts[0].strip()
params = {}
for part in parts[1:]:
if "=" in part:
key, value = part.split("=", 1)
params[key.strip()] = value.strip().strip('"')
return media_type, params
def is_chunked(headers: dict[str, str]) -> bool:
"""Check if response uses chunked transfer encoding."""
encoding = headers.get("transfer-encoding", "").lower()
return "chunked" in encoding
def parse_chunked_body(data: bytes) -> bytes:
"""Parse chunked transfer encoding."""
result = []
pos = 0
while pos < len(data):
# Find chunk size line
end_of_line = data.find(b"\r\n", pos)
if end_of_line == -1:
break
size_line = data[pos:end_of_line].decode("utf-8")
chunk_size = int(size_line.split(";")[0], 16)
if chunk_size == 0:
break
pos = end_of_line + 2
chunk_data = data[pos : pos + chunk_size]
result.append(chunk_data)
pos += chunk_size + 2 # Skip chunk data and trailing CRLF
return b"".join(result)
def get_content_length(headers: dict[str, str]) -> int:
"""Get content length from headers."""
length = headers.get("content-length", "0")
return int(length)
def main() -> int:
parser = argparse.ArgumentParser(description="HTTP protocol parser")
parser.add_argument(
"--mode",
choices=["request", "response", "url", "query", "build"],
default="request",
help="Operation mode",
)
parser.add_argument("--method", default="GET", help="HTTP method")
parser.add_argument("--path", default="/", help="Request path")
parser.add_argument("--url", help="URL to parse")
parser.add_argument("--data", help="Raw HTTP data (hex or text)")
parser.add_argument("--headers", nargs="*", help="Headers: Key:Value")
args = parser.parse_args()
if args.mode == "request":
headers = {}
if args.headers:
for h in args.headers:
if ":" in h:
k, v = h.split(":", 1)
headers[k.strip()] = v.strip()
request = HTTPRequest(
method=args.method, path=args.path, headers=headers or {"Host": "example.com"}
)
encoded = encode_request(request)
print("Encoded HTTP Request:")
print(encoded.decode("utf-8"))
elif args.mode == "response":
response = HTTPResponse(
version="HTTP/1.1",
status_code=200,
reason="OK",
headers={"Content-Type": "text/html"},
body=b"<html><body>Hello</body></html>",
)
encoded = encode_response(response)
print("Encoded HTTP Response:")
print(encoded.decode("utf-8"))
elif args.mode == "url" and args.url:
components = parse_url(args.url)
print(f"URL: {args.url}")
for key, value in components.items():
if value:
print(f" {key}: {value}")
if components["query"]:
params = parse_query_string(components["query"])
print(" Query Parameters:")
for k, v in params.items():
print(f" {k} = {v}")
elif args.mode == "query":
params = {"name": "John Doe", "age": "30", "city": "New York"}
query = build_query_string(params)
print(f"Query string: {query}")
parsed = parse_query_string(query)
print("Parsed back:")
for k, v in parsed.items():
print(f" {k} = {v}")
elif args.mode == "build":
headers = {}
if args.headers:
for h in args.headers:
if ":" in h:
k, v = h.split(":", 1)
headers[k.strip()] = v.strip()
request = HTTPRequest(method=args.method, path=args.path, headers=headers)
encoded = encode_request(request)
print(f"Hex: {encoded.hex()}")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
http_parser
| 394
| 0
|
[
"class_definition",
"exception_handling",
"decorator"
] | 0.612
|
Type inference hints:
Hint: str for variable 'line' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'line' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type)
Hint: str for variable 'data' [Medium] (usage p
|
|
example_http_parser
|
test_http_cli.py
|
"""Tests for http_cli.py"""
import pytest
from http_cli import (
HTTPRequest,
HTTPResponse,
build_query_string,
encode_request,
encode_response,
get_content_length,
is_chunked,
parse_chunked_body,
parse_content_type,
parse_headers,
parse_query_string,
parse_request,
parse_request_line,
parse_response,
parse_status_line,
parse_url,
url_decode,
url_encode,
)
class TestParseRequestLine:
def test_get(self):
method, path, version = parse_request_line("GET / HTTP/1.1")
assert method == "GET"
assert path == "/"
assert version == "HTTP/1.1"
def test_post(self):
method, path, version = parse_request_line("POST /api/users HTTP/1.1")
assert method == "POST"
assert path == "/api/users"
def test_with_query(self):
method, path, version = parse_request_line("GET /search?q=test HTTP/1.1")
assert path == "/search?q=test"
def test_invalid(self):
with pytest.raises(ValueError):
parse_request_line("INVALID")
class TestParseStatusLine:
def test_200(self):
version, code, reason = parse_status_line("HTTP/1.1 200 OK")
assert version == "HTTP/1.1"
assert code == 200
assert reason == "OK"
def test_404(self):
version, code, reason = parse_status_line("HTTP/1.1 404 Not Found")
assert code == 404
assert reason == "Not Found"
def test_no_reason(self):
version, code, reason = parse_status_line("HTTP/1.1 204")
assert code == 204
assert reason == "No Content" # Default
class TestParseHeaders:
def test_basic(self):
lines = ["Content-Type: text/html", "Content-Length: 100"]
headers = parse_headers(lines)
assert headers["content-type"] == "text/html"
assert headers["content-length"] == "100"
def test_with_spaces(self):
lines = ["Content-Type: application/json "]
headers = parse_headers(lines)
assert headers["content-type"] == "application/json"
def test_empty_lines(self):
lines = ["Host: example.com", "", "ignored: value"]
headers = parse_headers(lines)
assert "host" in headers
assert "ignored" not in headers
class TestParseRequest:
def test_simple_get(self):
data = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
request = parse_request(data)
assert request.method == "GET"
assert request.path == "/"
assert request.headers["host"] == "example.com"
def test_with_body(self):
data = b"POST /api HTTP/1.1\r\nContent-Type: application/json\r\n\r\n{\"key\": \"value\"}"
request = parse_request(data)
assert request.method == "POST"
assert request.body == b'{"key": "value"}'
def test_multiple_headers(self):
data = b"GET /page HTTP/1.1\r\nHost: test.com\r\nAccept: text/html\r\nUser-Agent: test\r\n\r\n"
request = parse_request(data)
assert len(request.headers) == 3
class TestParseResponse:
def test_simple(self):
data = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello"
response = parse_response(data)
assert response.status_code == 200
assert response.reason == "OK"
assert response.body == b"Hello"
def test_404(self):
data = b"HTTP/1.1 404 Not Found\r\n\r\nPage not found"
response = parse_response(data)
assert response.status_code == 404
class TestEncodeRequest:
def test_simple(self):
request = HTTPRequest(method="GET", path="/", headers={"Host": "example.com"})
encoded = encode_request(request)
assert b"GET / HTTP/1.1\r\n" in encoded
assert b"Host: example.com\r\n" in encoded
assert encoded.endswith(b"\r\n\r\n")
def test_with_body(self):
request = HTTPRequest(
method="POST",
path="/api",
headers={"Content-Type": "application/json"},
body=b'{"test": true}',
)
encoded = encode_request(request)
assert b"POST /api HTTP/1.1\r\n" in encoded
assert b"Content-Length: 14\r\n" in encoded
assert encoded.endswith(b'{"test": true}')
class TestEncodeResponse:
def test_simple(self):
response = HTTPResponse(
version="HTTP/1.1",
status_code=200,
reason="OK",
headers={"Content-Type": "text/html"},
body=b"<html></html>",
)
encoded = encode_response(response)
assert b"HTTP/1.1 200 OK\r\n" in encoded
assert b"Content-Type: text/html\r\n" in encoded
class TestParseUrl:
def test_full_url(self):
result = parse_url("https://example.com:8080/path?query=1#section")
assert result["scheme"] == "https"
assert result["host"] == "example.com"
assert result["port"] == "8080"
assert result["path"] == "/path"
assert result["query"] == "query=1"
assert result["fragment"] == "section"
def test_simple_url(self):
result = parse_url("http://example.com/")
assert result["scheme"] == "http"
assert result["host"] == "example.com"
assert result["path"] == "/"
def test_path_only(self):
result = parse_url("/api/users")
assert result["path"] == "/api/users"
assert result["host"] == ""
def test_no_port(self):
result = parse_url("http://example.com/test")
assert result["port"] == ""
class TestQueryString:
def test_parse_simple(self):
params = parse_query_string("key=value")
assert params["key"] == "value"
def test_parse_multiple(self):
params = parse_query_string("a=1&b=2&c=3")
assert params["a"] == "1"
assert params["b"] == "2"
assert params["c"] == "3"
def test_parse_encoded(self):
params = parse_query_string("name=John%20Doe")
assert params["name"] == "John Doe"
def test_parse_empty(self):
params = parse_query_string("")
assert params == {}
def test_build(self):
params = {"key": "value", "name": "test"}
query = build_query_string(params)
assert "key=value" in query
assert "name=test" in query
class TestUrlEncode:
def test_simple(self):
assert url_encode("hello") == "hello"
def test_space(self):
assert url_encode("hello world") == "hello+world"
def test_special_chars(self):
encoded = url_encode("a&b=c")
assert "%" in encoded
class TestUrlDecode:
def test_simple(self):
assert url_decode("hello") == "hello"
def test_plus(self):
assert url_decode("hello+world") == "hello world"
def test_percent(self):
assert url_decode("hello%20world") == "hello world"
def test_roundtrip(self):
original = "Hello World! & more"
encoded = url_encode(original)
decoded = url_decode(encoded)
assert decoded == original
class TestContentType:
def test_simple(self):
media, params = parse_content_type("text/html")
assert media == "text/html"
assert params == {}
def test_with_charset(self):
media, params = parse_content_type("text/html; charset=utf-8")
assert media == "text/html"
assert params["charset"] == "utf-8"
def test_with_boundary(self):
media, params = parse_content_type("multipart/form-data; boundary=----WebKitFormBoundary")
assert media == "multipart/form-data"
assert "boundary" in params
class TestChunked:
def test_is_chunked(self):
assert is_chunked({"transfer-encoding": "chunked"}) is True
assert is_chunked({"transfer-encoding": "gzip, chunked"}) is True
assert is_chunked({"transfer-encoding": "gzip"}) is False
assert is_chunked({}) is False
def test_parse_chunked(self):
data = b"5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n"
result = parse_chunked_body(data)
assert result == b"hello world"
class TestContentLength:
def test_present(self):
assert get_content_length({"content-length": "100"}) == 100
def test_missing(self):
assert get_content_length({}) == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_http_parser/test_http_cli.py (8316 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_http_parser/test_http_cli.rs (18077 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 152.4 KB/s
⏱️ Total time: 53ms
| true
|
http_parser
| 285
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_ini_parser
|
ini_cli.py
|
#!/usr/bin/env python3
"""INI file parser CLI.
Parse, query, and modify INI configuration files.
"""
import argparse
import sys
def parse_ini(content: str) -> dict:
"""Parse INI content into nested dict."""
result: dict = {}
current_section = ""
for line in content.split("\n"):
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith("#") or line.startswith(";"):
continue
# Section header
if line.startswith("[") and line.endswith("]"):
current_section = line[1:-1]
if current_section not in result:
result[current_section] = {}
continue
# Key=value pair
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# Remove quotes if present
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
if current_section:
result[current_section][key] = value
else:
# Global section (no header)
if "" not in result:
result[""] = {}
result[""][key] = value
return result
def format_ini(data: dict) -> str:
"""Format dict back to INI format."""
lines = []
# Global section first (if any)
if "" in data:
for key, value in data[""].items():
lines.append(f"{key} = {value}")
if data[""]:
lines.append("")
# Named sections
for section, values in data.items():
if section == "":
continue
lines.append(f"[{section}]")
for key, value in values.items():
lines.append(f"{key} = {value}")
lines.append("")
return "\n".join(lines)
def get_value(data: dict, section: str, key: str) -> str:
"""Get a value from parsed INI data."""
if section not in data:
return ""
if key not in data[section]:
return ""
return data[section][key]
def set_value(data: dict, section: str, key: str, value: str) -> dict:
"""Set a value in parsed INI data."""
if section not in data:
data[section] = {}
data[section][key] = value
return data
def list_sections(data: dict) -> list:
"""List all sections in INI data."""
return [s for s in data.keys() if s != ""]
def list_keys(data: dict, section: str) -> list:
"""List all keys in a section."""
if section not in data:
return []
return list(data[section].keys())
def main() -> int:
parser = argparse.ArgumentParser(description="INI file parser and editor")
parser.add_argument("input", nargs="?", help="Input INI file (- for stdin)")
parser.add_argument("--get", metavar="SECTION.KEY", help="Get a specific value")
parser.add_argument("--set", metavar="SECTION.KEY=VALUE", help="Set a value")
parser.add_argument("--sections", action="store_true", help="List all sections")
parser.add_argument("--keys", metavar="SECTION", help="List keys in a section")
parser.add_argument("-o", "--output", help="Output file (default: stdout)")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
content = sys.stdin.read()
else:
with open(args.input) as f:
content = f.read()
data = parse_ini(content)
# Perform operation
if args.get:
if "." in args.get:
section, key = args.get.split(".", 1)
else:
section, key = "", args.get
value = get_value(data, section, key)
print(value)
elif args.set:
if "=" not in args.set:
print("Error: --set requires SECTION.KEY=VALUE format", file=sys.stderr)
return 1
path, value = args.set.split("=", 1)
if "." in path:
section, key = path.split(".", 1)
else:
section, key = "", path
data = set_value(data, section, key, value)
output = format_ini(data)
if args.output:
with open(args.output, "w") as f:
f.write(output)
else:
print(output)
elif args.sections:
for section in list_sections(data):
print(section)
elif args.keys:
for key in list_keys(data, args.keys):
print(key)
else:
# Default: pretty print
output = format_ini(data)
if args.output:
with open(args.output, "w") as f:
f.write(output)
else:
print(output)
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ini_parser/ini_cli.py (4794 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ini_parser/ini_cli.rs (13095 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_ini_parser/Cargo.toml (3 dependencies)
⏱️ Parse time: 57ms
📊 Throughput: 80.9 KB/s
⏱️ Total time: 58ms
| true
|
ini_parser
| 168
| 6
|
[
"context_manager",
"stdin_usage"
] | 0.652
| null |
example_ini_parser
|
test_ini_cli.py
|
"""Tests for ini_cli.py"""
from ini_cli import (
format_ini,
get_value,
list_keys,
list_sections,
parse_ini,
set_value,
)
SAMPLE_INI = """
[database]
host = localhost
port = 5432
name = mydb
[server]
host = 0.0.0.0
port = 8080
"""
class TestParsing:
def test_parse_sections(self):
data = parse_ini(SAMPLE_INI)
assert "database" in data
assert "server" in data
def test_parse_values(self):
data = parse_ini(SAMPLE_INI)
assert data["database"]["host"] == "localhost"
assert data["database"]["port"] == "5432"
def test_parse_comments(self):
content = """
# This is a comment
[section]
key = value
; Another comment
"""
data = parse_ini(content)
assert data["section"]["key"] == "value"
def test_parse_quoted_values(self):
content = '[section]\nkey = "hello world"'
data = parse_ini(content)
assert data["section"]["key"] == "hello world"
class TestGetValue:
def test_get_existing(self):
data = parse_ini(SAMPLE_INI)
assert get_value(data, "database", "host") == "localhost"
def test_get_missing_key(self):
data = parse_ini(SAMPLE_INI)
assert get_value(data, "database", "missing") == ""
def test_get_missing_section(self):
data = parse_ini(SAMPLE_INI)
assert get_value(data, "missing", "key") == ""
class TestSetValue:
def test_set_existing(self):
data = parse_ini(SAMPLE_INI)
data = set_value(data, "database", "host", "newhost")
assert data["database"]["host"] == "newhost"
def test_set_new_key(self):
data = parse_ini(SAMPLE_INI)
data = set_value(data, "database", "newkey", "newvalue")
assert data["database"]["newkey"] == "newvalue"
def test_set_new_section(self):
data = parse_ini(SAMPLE_INI)
data = set_value(data, "newsection", "key", "value")
assert data["newsection"]["key"] == "value"
class TestListing:
def test_list_sections(self):
data = parse_ini(SAMPLE_INI)
sections = list_sections(data)
assert "database" in sections
assert "server" in sections
def test_list_keys(self):
data = parse_ini(SAMPLE_INI)
keys = list_keys(data, "database")
assert "host" in keys
assert "port" in keys
assert "name" in keys
class TestFormatting:
def test_roundtrip(self):
data = parse_ini(SAMPLE_INI)
output = format_ini(data)
reparsed = parse_ini(output)
assert reparsed["database"]["host"] == "localhost"
assert reparsed["server"]["port"] == "8080"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ini_parser/test_ini_cli.py (2668 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ini_parser/test_ini_cli.rs (6485 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 54.0 KB/s
⏱️ Total time: 48ms
| true
|
ini_parser
| 103
| 5
|
[
"class_definition"
] | 0.612
| null |
example_int_float
|
int_float_tool.py
|
#!/usr/bin/env python3
"""Int Float Example - Type conversion CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Type conversion tool")
subs = parser.add_subparsers(dest="cmd", required=True)
t = subs.add_parser("toint")
t.add_argument("x", type=float)
f = subs.add_parser("tofloat")
f.add_argument("x", type=int)
p = subs.add_parser("parse")
p.add_argument("text")
args = parser.parse_args()
if args.cmd == "toint":
print(int(args.x))
elif args.cmd == "tofloat":
print(float(args.x))
elif args.cmd == "parse":
print(int(args.text))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_int_float/int_float_tool.py (681 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_int_float/int_float_tool.rs (909 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_int_float/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 13.4 KB/s
⏱️ Total time: 50ms
| true
|
int_float
| 28
| 6
|
[] | 0
| null |
example_int_float
|
test_int_float_tool.py
|
"""Tests for int_float_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "int_float_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_toint():
r = run("toint 3.7")
assert r.returncode == 0
assert r.stdout.strip() == "3"
def test_tofloat():
r = run("tofloat 42")
assert r.returncode == 0
assert r.stdout.strip() == "42.0"
def test_parse():
r = run("parse 123")
assert r.returncode == 0
assert r.stdout.strip() == "123"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_int_float/test_int_float_tool.py (624 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_int_float/test_int_float_tool.rs (1828 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_int_float/Cargo.toml (2 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 11.9 KB/s
⏱️ Total time: 51ms
| true
|
int_float
| 32
| 6
|
[] | 0
| null |
example_io
|
io_tool.py
|
#!/usr/bin/env python3
"""IO Example - String IO operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="IO operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
w = subs.add_parser("words")
w.add_argument("text")
lp = subs.add_parser("lines")
lp.add_argument("text")
c = subs.add_parser("chars")
c.add_argument("text")
args = parser.parse_args()
if args.cmd == "words":
print(len(args.text.split()))
elif args.cmd == "lines":
print(len(args.text.split("\\n")))
elif args.cmd == "chars":
print(len(args.text))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_io/io_tool.py (684 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_io/io_tool.rs (1237 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_io/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 14.3 KB/s
⏱️ Total time: 46ms
| true
|
io
| 28
| 6
|
[] | 0
| null |
example_io
|
test_io_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for io CLI."""
import subprocess
SCRIPT = "io_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCounts:
def test_words(self): r = run(["words", "hello world foo"]); assert "3" in r.stdout
def test_lines(self): r = run(["lines", "a\\nb\\nc"]); assert "3" in r.stdout
def test_chars(self): r = run(["chars", "hello"]); assert "5" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_io/test_io_tool.py (578 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_io/test_io_tool.rs (1844 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 11.7 KB/s
⏱️ Total time: 48ms
| true
|
io
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_io_streams
|
stream_processor.py
|
#!/usr/bin/env python3
"""
I/O Streams Example - File I/O and stream processing
Demonstrates:
- Reading from stdin line-by-line
- Writing to stdout/stderr
- File operations (read, write, append)
- Temporary files and cleanup
- Binary vs text mode
- Context managers (with statement)
This validates depyler's ability to transpile I/O operations
to Rust (std::io::{BufReader, BufRead}, std::fs).
"""
import argparse
import os
import sys
import tempfile
def read_stdin_lines():
"""
Read and process lines from stdin
Depyler: proven to terminate
"""
print("Reading from stdin (Ctrl+D to end):", file=sys.stderr)
line_count = 0
word_count = 0
char_count = 0
for line in sys.stdin:
line_count += 1
words = line.split()
word_count += len(words)
char_count += len(line)
print(f"{line_count}: {line.rstrip()}")
print(f"\nStats: {line_count} lines, {word_count} words, {char_count} chars", file=sys.stderr)
def read_file(filepath, binary=False):
"""
Read and display file contents
Args:
filepath: Path to file
binary: Read in binary mode
Depyler: proven to terminate
"""
mode = "rb" if binary else "r"
try:
with open(filepath, mode) as f:
content = f.read()
if binary:
print(f"Read {len(content)} bytes")
# Show first 100 bytes as hex
hex_str = content[:100].hex()
print(f"First bytes (hex): {hex_str}")
else:
print(content)
except FileNotFoundError:
print(f"Error: File not found: {filepath}", file=sys.stderr)
sys.exit(1)
except PermissionError:
print(f"Error: Permission denied: {filepath}", file=sys.stderr)
sys.exit(1)
def write_file(filepath, content, append=False):
"""
Write content to file
Args:
filepath: Path to file
content: Content to write
append: Append instead of overwrite
Depyler: proven to terminate
"""
mode = "a" if append else "w"
with open(filepath, mode) as f:
f.write(content)
if not content.endswith("\n"):
f.write("\n")
action = "Appended to" if append else "Wrote to"
print(f"{action} {filepath}")
def count_lines(filepath):
"""
Count lines in file efficiently
Args:
filepath: Path to file
Depyler: proven to terminate
"""
try:
with open(filepath) as f:
lines = sum(1 for line in f)
print(f"{filepath}: {lines} lines")
return lines
except FileNotFoundError:
print(f"Error: File not found: {filepath}", file=sys.stderr)
sys.exit(1)
def create_temp_file(content=None):
"""
Create temporary file
Args:
content: Optional content to write
Depyler: proven to terminate
"""
# Create named temporary file
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
temp_path = f.name
if content:
f.write(content)
print(f"Created temporary file: {temp_path}")
# Verify it exists
if os.path.exists(temp_path):
print(f"File exists: {os.path.getsize(temp_path)} bytes")
return temp_path
def filter_lines(filepath, pattern):
"""
Filter lines containing pattern
Args:
filepath: Path to input file
pattern: String to search for
Depyler: proven to terminate
"""
try:
with open(filepath) as f:
matching_lines = [line.rstrip() for line in f if pattern in line]
print(f"Found {len(matching_lines)} matching lines:")
for line in matching_lines:
print(f" {line}")
return matching_lines
except FileNotFoundError:
print(f"Error: File not found: {filepath}", file=sys.stderr)
sys.exit(1)
def main():
"""
Main entry point for stream processor CLI
Demonstrates various I/O operations.
"""
parser = argparse.ArgumentParser(
description="File I/O and stream processing",
prog="stream_processor.py",
)
parser.add_argument("--version", action="version", version="1.0.0")
subparsers = parser.add_subparsers(dest="command", required=True)
# Stdin command
subparsers.add_parser("stdin", help="Read from stdin")
# Read file command
read_parser = subparsers.add_parser("read", help="Read file contents")
read_parser.add_argument("file", help="File to read")
read_parser.add_argument("--binary", action="store_true", help="Read in binary mode")
# Write file command
write_parser = subparsers.add_parser("write", help="Write to file")
write_parser.add_argument("file", help="File to write")
write_parser.add_argument("content", help="Content to write")
write_parser.add_argument("--append", action="store_true", help="Append instead of overwrite")
# Count lines command
count_parser = subparsers.add_parser("count", help="Count lines in file")
count_parser.add_argument("file", help="File to count")
# Temp file command
temp_parser = subparsers.add_parser("temp", help="Create temporary file")
temp_parser.add_argument("--content", help="Content for temp file")
# Filter command
filter_parser = subparsers.add_parser("filter", help="Filter lines by pattern")
filter_parser.add_argument("file", help="File to filter")
filter_parser.add_argument("pattern", help="Pattern to search for")
args = parser.parse_args()
# Execute command
if args.command == "stdin":
read_stdin_lines()
elif args.command == "read":
read_file(args.file, args.binary)
elif args.command == "write":
write_file(args.file, args.content, args.append)
elif args.command == "count":
count_lines(args.file)
elif args.command == "temp":
create_temp_file(args.content)
elif args.command == "filter":
filter_lines(args.file, args.pattern)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_io_streams/stream_processor.py (6075 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_io_streams/stream_processor.rs (9141 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_io_streams/Cargo.toml (2 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 117.3 KB/s
⏱️ Total time: 50ms
| true
|
io_streams
| 228
| 6
|
[
"context_manager",
"exception_handling",
"stdin_usage"
] | 0.652
| null |
example_isdigit
|
isdigit_tool.py
|
#!/usr/bin/env python3
"""Isdigit Example - String type check operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="String type check tool")
subs = parser.add_subparsers(dest="cmd", required=True)
d = subs.add_parser("digit")
d.add_argument("text")
a = subs.add_parser("alpha")
a.add_argument("text")
args = parser.parse_args()
if args.cmd == "digit":
result = True
i = 0
while i < len(args.text):
c = args.text[i]
if c < "0" or c > "9":
result = False
i = i + 1
if result:
print("true")
else:
print("false")
elif args.cmd == "alpha":
result = True
i = 0
while i < len(args.text):
c = args.text[i]
is_lower = c >= "a" and c <= "z"
is_upper = c >= "A" and c <= "Z"
if not is_lower and not is_upper:
result = False
i = i + 1
if result:
print("true")
else:
print("false")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/isdigit_tool.py (1145 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/isdigit_tool.rs (3044 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 23.2 KB/s
⏱️ Total time: 48ms
| true
|
isdigit
| 46
| 6
|
[] | 0
| null |
example_isdigit
|
test_isdigit_tool.py
|
"""Tests for isdigit_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "isdigit_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_digit_true():
r = run("digit 12345")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_digit_false():
r = run("digit hello")
assert r.returncode == 0
assert r.stdout.strip() == "false"
def test_alpha_true():
r = run("alpha hello")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_alpha_false():
r = run("alpha hello123")
assert r.returncode == 0
assert r.stdout.strip() == "false"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/test_isdigit_tool.py (768 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/test_isdigit_tool.rs (2094 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_isdigit/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 15.7 KB/s
⏱️ Total time: 48ms
| true
|
isdigit
| 38
| 6
|
[] | 0
| null |
example_itertools
|
iter_tool.py
|
#!/usr/bin/env python3
"""Itertools Example - Iterator operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Iterator operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
r = subs.add_parser("repeat")
r.add_argument("item")
r.add_argument("n", type=int)
c = subs.add_parser("cycle")
c.add_argument("item")
c.add_argument("n", type=int)
ch = subs.add_parser("chain")
ch.add_argument("a")
ch.add_argument("b")
args = parser.parse_args()
if args.cmd == "repeat":
i = 0
while i < args.n:
print(args.item)
i = i + 1
elif args.cmd == "cycle":
i = 0
while i < args.n:
print(args.item)
i = i + 1
elif args.cmd == "chain":
print(args.a)
print(args.b)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_itertools/iter_tool.py (903 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_itertools/iter_tool.rs (1215 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_itertools/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 18.0 KB/s
⏱️ Total time: 49ms
| true
|
itertools
| 38
| 6
|
[] | 0
| null |
example_itertools
|
test_iter_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for itertools CLI."""
import subprocess
SCRIPT = "iter_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestItertools:
def test_repeat(self): r = run(["repeat", "x", "3"]); assert r.returncode == 0 and r.stdout.count("x") == 3
def test_cycle(self): r = run(["cycle", "a", "3"]); assert r.returncode == 0 and "a" in r.stdout
def test_chain(self): r = run(["chain", "hello", "world"]); assert r.returncode == 0
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_itertools/test_iter_tool.py (644 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_itertools/test_iter_tool.rs (1951 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 12.7 KB/s
⏱️ Total time: 49ms
| true
|
itertools
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_join
|
join_tool.py
|
#!/usr/bin/env python3
"""Join Example - String join operations CLI.
Examples:
>>> join_underscore("a", "b", "c")
'a_b_c'
>>> join_dash("x", "y", "z")
'x-y-z'
>>> join_dot("1", "2", "3")
'1.2.3'
"""
import argparse
def join_underscore(a: str, b: str, c: str) -> str:
"""Join three strings with underscores.
>>> join_underscore("hello", "world", "test")
'hello_world_test'
>>> join_underscore("", "x", "")
'_x_'
"""
return a + "_" + b + "_" + c
def join_dash(a: str, b: str, c: str) -> str:
"""Join three strings with dashes.
>>> join_dash("foo", "bar", "baz")
'foo-bar-baz'
>>> join_dash("2025", "11", "29")
'2025-11-29'
"""
return a + "-" + b + "-" + c
def join_dot(a: str, b: str, c: str) -> str:
"""Join three strings with dots.
>>> join_dot("192", "168", "1")
'192.168.1'
>>> join_dot("a", "b", "c")
'a.b.c'
"""
return a + "." + b + "." + c
def main():
parser = argparse.ArgumentParser(description="String join tool")
subs = parser.add_subparsers(dest="cmd", required=True)
u = subs.add_parser("underscore")
u.add_argument("a")
u.add_argument("b")
u.add_argument("c")
d = subs.add_parser("dash")
d.add_argument("a")
d.add_argument("b")
d.add_argument("c")
dt = subs.add_parser("dot")
dt.add_argument("a")
dt.add_argument("b")
dt.add_argument("c")
args = parser.parse_args()
if args.cmd == "underscore":
print(join_underscore(args.a, args.b, args.c))
elif args.cmd == "dash":
print(join_dash(args.a, args.b, args.c))
elif args.cmd == "dot":
print(join_dot(args.a, args.b, args.c))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_join/join_tool.py (1743 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_join/join_tool.rs (2541 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_join/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 34.2 KB/s
⏱️ Total time: 49ms
| true
|
join
| 76
| 6
|
[
"context_manager"
] | 0.652
| null |
example_join
|
test_join_tool.py
|
"""Tests for join_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "join_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_underscore():
r = run("underscore a b c")
assert r.returncode == 0
assert r.stdout.strip() == "a_b_c"
def test_dash():
r = run("dash a b c")
assert r.returncode == 0
assert r.stdout.strip() == "a-b-c"
def test_dot():
r = run("dot a b c")
assert r.returncode == 0
assert r.stdout.strip() == "a.b.c"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_join/test_join_tool.py (628 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_join/test_join_tool.rs (1837 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_join/Cargo.toml (2 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 11.5 KB/s
⏱️ Total time: 53ms
| true
|
join
| 32
| 6
|
[] | 0
| null |
example_json_basic
|
json_basic_cli.py
|
#!/usr/bin/env python3
"""JSON Basic CLI.
JSON serialization and deserialization operations.
"""
import argparse
import json
import sys
def to_json(data: dict | list) -> str:
"""Convert data to JSON string."""
return json.dumps(data)
def to_json_pretty(data: dict | list, indent: int = 2) -> str:
"""Convert data to pretty JSON string."""
return json.dumps(data, indent=indent)
def from_json(s: str) -> dict | list:
"""Parse JSON string to data."""
return json.loads(s)
def to_json_sorted(data: dict) -> str:
"""Convert to JSON with sorted keys."""
return json.dumps(data, sort_keys=True)
def to_json_compact(data: dict | list) -> str:
"""Convert to compact JSON (no spaces)."""
return json.dumps(data, separators=(",", ":"))
def read_json_file(path: str) -> dict | list:
"""Read JSON from file."""
with open(path) as f:
return json.load(f)
def write_json_file(path: str, data: dict | list, indent: int | None = 2) -> None:
"""Write JSON to file."""
with open(path, "w") as f:
json.dump(data, f, indent=indent)
def get_value(data: dict, key: str) -> any:
"""Get value from JSON object by key."""
return data.get(key)
def get_nested(data: dict, *keys: str) -> any:
"""Get nested value using path of keys."""
result = data
for key in keys:
if isinstance(result, dict):
result = result.get(key)
elif isinstance(result, list) and key.isdigit():
idx = int(key)
result = result[idx] if 0 <= idx < len(result) else None
else:
return None
return result
def set_value(data: dict, key: str, value: any) -> dict:
"""Set value in JSON object (returns new dict)."""
result = data.copy()
result[key] = value
return result
def merge_json(d1: dict, d2: dict) -> dict:
"""Merge two JSON objects."""
return {**d1, **d2}
def deep_merge(d1: dict, d2: dict) -> dict:
"""Deep merge two JSON objects."""
result = d1.copy()
for key, value in d2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def json_keys(data: dict) -> list[str]:
"""Get all keys from JSON object."""
return list(data.keys())
def json_values(data: dict) -> list:
"""Get all values from JSON object."""
return list(data.values())
def flatten_json(data: dict, prefix: str = "") -> dict[str, any]:
"""Flatten nested JSON to flat dict with dot notation keys."""
result: dict[str, any] = {}
for key, value in data.items():
new_key = f"{prefix}.{key}" if prefix else key
if isinstance(value, dict):
result.update(flatten_json(value, new_key))
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
result.update(flatten_json(item, f"{new_key}.{i}"))
else:
result[f"{new_key}.{i}"] = item
else:
result[new_key] = value
return result
def unflatten_json(data: dict[str, any]) -> dict:
"""Unflatten dot-notation dict to nested JSON."""
result: dict = {}
for key, value in data.items():
parts = key.split(".")
current = result
for i, part in enumerate(parts[:-1]):
if part not in current:
# Check if next part is numeric
next_part = parts[i + 1]
if next_part.isdigit():
current[part] = []
else:
current[part] = {}
current = current[part]
# Handle final part
final_part = parts[-1]
if isinstance(current, list):
idx = int(final_part)
while len(current) <= idx:
current.append(None)
current[idx] = value
else:
current[final_part] = value
return result
def filter_keys(data: dict, keys: list[str]) -> dict:
"""Filter JSON object to only include specified keys."""
return {k: v for k, v in data.items() if k in keys}
def exclude_keys(data: dict, keys: list[str]) -> dict:
"""Exclude specified keys from JSON object."""
return {k: v for k, v in data.items() if k not in keys}
def is_valid_json(s: str) -> bool:
"""Check if string is valid JSON."""
try:
json.loads(s)
return True
except json.JSONDecodeError:
return False
def json_type(data: any) -> str:
"""Get JSON type of value."""
if data is None:
return "null"
elif isinstance(data, bool):
return "boolean"
elif isinstance(data, int):
return "integer"
elif isinstance(data, float):
return "number"
elif isinstance(data, str):
return "string"
elif isinstance(data, list):
return "array"
elif isinstance(data, dict):
return "object"
return "unknown"
def count_keys(data: dict) -> int:
"""Count total keys in nested JSON."""
count = len(data)
for value in data.values():
if isinstance(value, dict):
count += count_keys(value)
return count
def find_values(data: dict | list, key: str) -> list:
"""Find all values for a key in nested JSON."""
results: list = []
if isinstance(data, dict):
if key in data:
results.append(data[key])
for value in data.values():
if isinstance(value, (dict, list)):
results.extend(find_values(value, key))
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
results.extend(find_values(item, key))
return results
def transform_values(data: dict, fn: callable) -> dict:
"""Transform all leaf values in JSON."""
result = {}
for key, value in data.items():
if isinstance(value, dict):
result[key] = transform_values(value, fn)
elif isinstance(value, list):
result[key] = [
fn(item) if not isinstance(item, (dict, list)) else item for item in value
]
else:
result[key] = fn(value)
return result
def main() -> int:
parser = argparse.ArgumentParser(description="JSON basic CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# parse
parse_p = subparsers.add_parser("parse", help="Parse JSON string")
parse_p.add_argument("json", help="JSON string")
# format
format_p = subparsers.add_parser("format", help="Format JSON")
format_p.add_argument("json", help="JSON string")
format_p.add_argument("--indent", type=int, default=2, help="Indent")
# get
get_p = subparsers.add_parser("get", help="Get value by path")
get_p.add_argument("json", help="JSON string")
get_p.add_argument("path", help="Dot-notation path")
# validate
validate_p = subparsers.add_parser("validate", help="Validate JSON")
validate_p.add_argument("json", help="JSON string")
# flatten
flatten_p = subparsers.add_parser("flatten", help="Flatten JSON")
flatten_p.add_argument("json", help="JSON string")
args = parser.parse_args()
if args.command == "parse":
try:
data = from_json(args.json)
print(to_json_pretty(data))
except json.JSONDecodeError as e:
print(f"Error: {e}")
return 1
elif args.command == "format":
try:
data = from_json(args.json)
print(to_json_pretty(data, args.indent))
except json.JSONDecodeError as e:
print(f"Error: {e}")
return 1
elif args.command == "get":
try:
data = from_json(args.json)
parts = args.path.split(".")
value = get_nested(data, *parts)
print(to_json(value) if isinstance(value, (dict, list)) else value)
except json.JSONDecodeError as e:
print(f"Error: {e}")
return 1
elif args.command == "validate":
if is_valid_json(args.json):
print("Valid JSON")
else:
print("Invalid JSON")
return 1
elif args.command == "flatten":
try:
data = from_json(args.json)
if isinstance(data, dict):
flat = flatten_json(data)
print(to_json_pretty(flat))
else:
print("Can only flatten objects")
return 1
except json.JSONDecodeError as e:
print(f"Error: {e}")
return 1
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
json_basic
| 305
| 0
|
[
"context_manager",
"exception_handling"
] | 0.652
|
Error: Dict unpacking not supported
|
|
example_json_basic
|
test_json_basic_cli.py
|
"""Tests for json_basic_cli.py"""
import json
import os
import tempfile
from json_basic_cli import (
count_keys,
deep_merge,
exclude_keys,
filter_keys,
find_values,
flatten_json,
from_json,
get_nested,
get_value,
is_valid_json,
json_keys,
json_type,
json_values,
merge_json,
read_json_file,
set_value,
to_json,
to_json_compact,
to_json_pretty,
to_json_sorted,
transform_values,
unflatten_json,
write_json_file,
)
class TestToJson:
def test_to_json_dict(self):
data = {"a": 1, "b": 2}
result = to_json(data)
assert json.loads(result) == data
def test_to_json_list(self):
data = [1, 2, 3]
result = to_json(data)
assert json.loads(result) == data
def test_to_json_pretty(self):
data = {"a": 1}
result = to_json_pretty(data, indent=2)
assert "\n" in result
def test_to_json_sorted(self):
data = {"c": 3, "a": 1, "b": 2}
result = to_json_sorted(data)
assert result.index('"a"') < result.index('"b"') < result.index('"c"')
def test_to_json_compact(self):
data = {"a": 1, "b": 2}
result = to_json_compact(data)
assert " " not in result
class TestFromJson:
def test_from_json_dict(self):
s = '{"a": 1, "b": 2}'
result = from_json(s)
assert result == {"a": 1, "b": 2}
def test_from_json_list(self):
s = "[1, 2, 3]"
result = from_json(s)
assert result == [1, 2, 3]
class TestFileOperations:
def test_read_write_json_file(self):
data = {"name": "test", "value": 42}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
path = f.name
try:
write_json_file(path, data)
result = read_json_file(path)
assert result == data
finally:
os.unlink(path)
class TestGetValue:
def test_get_value(self):
data = {"a": 1, "b": 2}
assert get_value(data, "a") == 1
assert get_value(data, "x") is None
def test_get_nested(self):
data = {"a": {"b": {"c": 42}}}
assert get_nested(data, "a", "b", "c") == 42
def test_get_nested_list(self):
data = {"items": [1, 2, 3]}
assert get_nested(data, "items", "1") == 2
class TestSetValue:
def test_set_value(self):
data = {"a": 1}
result = set_value(data, "b", 2)
assert result == {"a": 1, "b": 2}
assert data == {"a": 1}
class TestMerge:
def test_merge_json(self):
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
result = merge_json(d1, d2)
assert result == {"a": 1, "b": 3, "c": 4}
def test_deep_merge(self):
d1 = {"a": {"x": 1, "y": 2}}
d2 = {"a": {"y": 3, "z": 4}}
result = deep_merge(d1, d2)
assert result == {"a": {"x": 1, "y": 3, "z": 4}}
class TestKeysValues:
def test_json_keys(self):
data = {"a": 1, "b": 2, "c": 3}
keys = json_keys(data)
assert sorted(keys) == ["a", "b", "c"]
def test_json_values(self):
data = {"a": 1, "b": 2, "c": 3}
values = json_values(data)
assert sorted(values) == [1, 2, 3]
class TestFlatten:
def test_flatten_json(self):
data = {"a": {"b": 1, "c": 2}, "d": 3}
result = flatten_json(data)
assert result == {"a.b": 1, "a.c": 2, "d": 3}
def test_flatten_json_with_list(self):
data = {"a": [1, 2, 3]}
result = flatten_json(data)
assert result == {"a.0": 1, "a.1": 2, "a.2": 3}
class TestUnflatten:
def test_unflatten_json(self):
data = {"a.b": 1, "a.c": 2, "d": 3}
result = unflatten_json(data)
assert result == {"a": {"b": 1, "c": 2}, "d": 3}
class TestFilterExclude:
def test_filter_keys(self):
data = {"a": 1, "b": 2, "c": 3}
result = filter_keys(data, ["a", "c"])
assert result == {"a": 1, "c": 3}
def test_exclude_keys(self):
data = {"a": 1, "b": 2, "c": 3}
result = exclude_keys(data, ["b"])
assert result == {"a": 1, "c": 3}
class TestValidation:
def test_is_valid_json_true(self):
assert is_valid_json('{"a": 1}') is True
def test_is_valid_json_false(self):
assert is_valid_json("not json") is False
def test_is_valid_json_empty_object(self):
assert is_valid_json("{}") is True
class TestJsonType:
def test_json_type_null(self):
assert json_type(None) == "null"
def test_json_type_boolean(self):
assert json_type(True) == "boolean"
assert json_type(False) == "boolean"
def test_json_type_integer(self):
assert json_type(42) == "integer"
def test_json_type_number(self):
assert json_type(3.14) == "number"
def test_json_type_string(self):
assert json_type("hello") == "string"
def test_json_type_array(self):
assert json_type([1, 2, 3]) == "array"
def test_json_type_object(self):
assert json_type({"a": 1}) == "object"
class TestCountKeys:
def test_count_keys(self):
data = {"a": 1, "b": {"c": 2, "d": 3}}
assert count_keys(data) == 4
class TestFindValues:
def test_find_values(self):
data = {"a": {"id": 1}, "b": {"id": 2, "c": {"id": 3}}}
result = find_values(data, "id")
assert sorted(result) == [1, 2, 3]
class TestTransform:
def test_transform_values(self):
data = {"a": 1, "b": 2}
result = transform_values(data, lambda x: x * 2 if isinstance(x, int) else x)
assert result == {"a": 2, "b": 4}
class TestEdgeCases:
def test_empty_object(self):
assert to_json({}) == "{}"
assert from_json("{}") == {}
def test_empty_array(self):
assert to_json([]) == "[]"
assert from_json("[]") == []
def test_nested_empty(self):
data = {"a": {}, "b": []}
result = to_json(data)
assert from_json(result) == data
def test_special_characters(self):
data = {"key": "value with \"quotes\" and \\backslashes"}
result = to_json(data)
assert from_json(result) == data
| false
|
json_basic
| 238
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling"
] | 0.783
|
Error: Expression type not yet supported: IfExpr { test: Call { func: "isinstance", args: [Var("x"), Var("int")], kwargs: [] }, body: Binary { op: Mul, left: Var("x"), right: Literal(Int(2)) }, orelse: Var("x") }
|
|
example_json_path
|
jsonpath_cli.py
|
#!/usr/bin/env python3
"""JSONPath CLI.
Simple JSONPath query implementation.
"""
import argparse
import json
import sys
from dataclasses import dataclass
from enum import Enum, auto
class PathType(Enum):
"""JSONPath segment types."""
ROOT = auto()
CHILD = auto()
RECURSIVE = auto()
INDEX = auto()
SLICE = auto()
WILDCARD = auto()
FILTER = auto()
@dataclass
class PathSegment:
"""JSONPath segment."""
type: PathType
value: str | int | tuple | None = None
def parse_path(path: str) -> list[PathSegment]:
"""Parse JSONPath string into segments."""
segments = []
i = 0
while i < len(path):
char = path[i]
if char == "$":
segments.append(PathSegment(PathType.ROOT))
i += 1
elif char == ".":
if i + 1 < len(path) and path[i + 1] == ".":
segments.append(PathSegment(PathType.RECURSIVE))
i += 2
else:
i += 1
# Read key name
start = i
while i < len(path) and path[i] not in ".[]":
i += 1
if i > start:
key = path[start:i]
if key == "*":
segments.append(PathSegment(PathType.WILDCARD))
else:
segments.append(PathSegment(PathType.CHILD, key))
elif char == "[":
i += 1
start = i
bracket_depth = 1
while i < len(path) and bracket_depth > 0:
if path[i] == "[":
bracket_depth += 1
elif path[i] == "]":
bracket_depth -= 1
i += 1
content = path[start : i - 1].strip()
if content == "*":
segments.append(PathSegment(PathType.WILDCARD))
elif content.startswith("?"):
segments.append(PathSegment(PathType.FILTER, content[1:].strip()))
elif ":" in content:
parts = content.split(":")
start_idx = int(parts[0]) if parts[0] else None
end_idx = int(parts[1]) if len(parts) > 1 and parts[1] else None
step = int(parts[2]) if len(parts) > 2 and parts[2] else None
segments.append(PathSegment(PathType.SLICE, (start_idx, end_idx, step)))
elif content.isdigit() or (content.startswith("-") and content[1:].isdigit()):
segments.append(PathSegment(PathType.INDEX, int(content)))
else:
# Quoted key
key = content.strip("'\"")
segments.append(PathSegment(PathType.CHILD, key))
else:
i += 1
return segments
def query(data: any, path: str) -> list[any]:
"""Execute JSONPath query on data."""
segments = parse_path(path)
results = [data]
for segment in segments:
new_results = []
for item in results:
new_results.extend(apply_segment(item, segment))
results = new_results
return results
def apply_segment(data: any, segment: PathSegment) -> list[any]:
"""Apply a single path segment to data."""
if segment.type == PathType.ROOT:
return [data]
if segment.type == PathType.CHILD:
if isinstance(data, dict) and segment.value in data:
return [data[segment.value]]
return []
if segment.type == PathType.INDEX:
if isinstance(data, list):
idx = segment.value
if isinstance(idx, int) and -len(data) <= idx < len(data):
return [data[idx]]
return []
if segment.type == PathType.SLICE:
if isinstance(data, list):
start, end, step = segment.value
return [data[start:end:step]]
return []
if segment.type == PathType.WILDCARD:
if isinstance(data, dict):
return list(data.values())
if isinstance(data, list):
return data
return []
if segment.type == PathType.RECURSIVE:
return recursive_descent(data)
if segment.type == PathType.FILTER:
return apply_filter(data, str(segment.value))
return []
def recursive_descent(data: any) -> list[any]:
"""Get all descendants of data."""
results = [data]
if isinstance(data, dict):
for value in data.values():
results.extend(recursive_descent(value))
elif isinstance(data, list):
for item in data:
results.extend(recursive_descent(item))
return results
def apply_filter(data: any, expr: str) -> list[any]:
"""Apply filter expression to array."""
if not isinstance(data, list):
return []
results = []
expr = expr.strip("()")
for item in data:
if evaluate_filter(item, expr):
results.append(item)
return results
def evaluate_filter(item: any, expr: str) -> bool:
"""Evaluate filter expression on item."""
# Simple filter evaluation
expr = expr.strip()
# Handle @.key op value
if "@." in expr:
expr = expr.replace("@.", "")
# Parse comparison
for op in [">=", "<=", "!=", "==", ">", "<"]:
if op in expr:
left, right = expr.split(op, 1)
left = left.strip()
right = right.strip().strip("'\"")
if isinstance(item, dict) and left in item:
left_val = item[left]
# Try numeric comparison
try:
right_val = float(right) if "." in right else int(right)
left_val = float(left_val)
except (ValueError, TypeError):
right_val = right
if op == "==":
return left_val == right_val
if op == "!=":
return left_val != right_val
if op == ">":
return left_val > right_val
if op == "<":
return left_val < right_val
if op == ">=":
return left_val >= right_val
if op == "<=":
return left_val <= right_val
return False
# Just key existence check
return isinstance(item, dict) and expr in item
return False
def get_value(data: any, path: str) -> any:
"""Get single value from path (returns first result or None)."""
results = query(data, path)
return results[0] if results else None
def get_all(data: any, path: str) -> list[any]:
"""Get all values matching path."""
return query(data, path)
def exists(data: any, path: str) -> bool:
"""Check if path exists in data."""
return len(query(data, path)) > 0
def count(data: any, path: str) -> int:
"""Count matches for path."""
return len(query(data, path))
def keys(data: any) -> list[str]:
"""Get keys of object."""
if isinstance(data, dict):
return list(data.keys())
return []
def values(data: any) -> list[any]:
"""Get values of object or array."""
if isinstance(data, dict):
return list(data.values())
if isinstance(data, list):
return data
return []
def flatten(data: any) -> list[any]:
"""Flatten nested structure."""
results = []
if isinstance(data, dict):
for value in data.values():
results.extend(flatten(value))
elif isinstance(data, list):
for item in data:
results.extend(flatten(item))
else:
results.append(data)
return results
def main() -> int:
parser = argparse.ArgumentParser(description="JSONPath query tool")
parser.add_argument("path", nargs="?", help="JSONPath expression")
parser.add_argument("--file", "-f", help="JSON file to query")
parser.add_argument("--data", "-d", help="JSON data string")
parser.add_argument(
"--mode",
choices=["query", "exists", "count", "keys", "values", "flatten"],
default="query",
help="Operation mode",
)
args = parser.parse_args()
# Load data
if args.file:
with open(args.file) as f:
data = json.load(f)
elif args.data:
data = json.loads(args.data)
else:
data = json.load(sys.stdin)
if args.mode == "keys":
result = keys(data)
print(json.dumps(result, indent=2))
return 0
if args.mode == "values":
result = values(data)
print(json.dumps(result, indent=2))
return 0
if args.mode == "flatten":
result = flatten(data)
print(json.dumps(result, indent=2))
return 0
if not args.path:
print("Error: path required for query mode")
return 1
if args.mode == "query":
results = query(data, args.path)
if len(results) == 1:
print(json.dumps(results[0], indent=2))
else:
print(json.dumps(results, indent=2))
elif args.mode == "exists":
print("true" if exists(data, args.path) else "false")
elif args.mode == "count":
print(count(data, args.path))
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_json_path/jsonpath_cli.py (9352 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_json_path/jsonpath_cli.rs (26559 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_json_path/Cargo.toml (3 dependencies)
⏱️ Parse time: 62ms
📊 Throughput: 146.4 KB/s
⏱️ Total time: 62ms
| true
|
json_path
| 343
| 6
|
[
"context_manager",
"class_definition",
"exception_handling",
"stdin_usage",
"decorator"
] | 0.652
| null |
example_json_path
|
test_jsonpath_cli.py
|
"""Tests for jsonpath_cli.py"""
from jsonpath_cli import (
PathType,
count,
exists,
flatten,
get_all,
get_value,
keys,
parse_path,
query,
values,
)
SAMPLE_DATA = {
"store": {
"book": [
{"category": "fiction", "author": "Author1", "title": "Book1", "price": 10},
{"category": "fiction", "author": "Author2", "title": "Book2", "price": 20},
{"category": "reference", "author": "Author3", "title": "Book3", "price": 30},
],
"bicycle": {"color": "red", "price": 100},
},
"name": "Test Store",
}
class TestParsePath:
def test_root(self):
segments = parse_path("$")
assert len(segments) == 1
assert segments[0].type == PathType.ROOT
def test_child(self):
segments = parse_path("$.store")
assert segments[-1].type == PathType.CHILD
assert segments[-1].value == "store"
def test_recursive(self):
segments = parse_path("$..price")
assert any(s.type == PathType.RECURSIVE for s in segments)
def test_index(self):
segments = parse_path("$.store.book[0]")
assert any(s.type == PathType.INDEX and s.value == 0 for s in segments)
def test_wildcard(self):
segments = parse_path("$.store.book[*]")
assert any(s.type == PathType.WILDCARD for s in segments)
def test_slice(self):
segments = parse_path("$.store.book[0:2]")
assert any(s.type == PathType.SLICE for s in segments)
def test_filter(self):
segments = parse_path("$.store.book[?(@.price > 15)]")
assert any(s.type == PathType.FILTER for s in segments)
class TestQuery:
def test_root(self):
result = query(SAMPLE_DATA, "$")
assert result == [SAMPLE_DATA]
def test_simple_child(self):
result = query(SAMPLE_DATA, "$.name")
assert result == ["Test Store"]
def test_nested_child(self):
result = query(SAMPLE_DATA, "$.store.bicycle.color")
assert result == ["red"]
def test_array_index(self):
result = query(SAMPLE_DATA, "$.store.book[0].title")
assert result == ["Book1"]
def test_negative_index(self):
result = query(SAMPLE_DATA, "$.store.book[-1].title")
assert result == ["Book3"]
def test_wildcard(self):
result = query(SAMPLE_DATA, "$.store.book[*].author")
assert result == ["Author1", "Author2", "Author3"]
def test_recursive(self):
result = query(SAMPLE_DATA, "$..price")
assert 10 in result
assert 20 in result
assert 30 in result
assert 100 in result
class TestFilter:
def test_greater_than(self):
result = query(SAMPLE_DATA, "$.store.book[?(@.price > 15)]")
assert len(result) == 2
assert all(item["price"] > 15 for item in result)
def test_equal(self):
result = query(SAMPLE_DATA, "$.store.book[?(@.category == 'fiction')]")
assert len(result) == 2
def test_less_than(self):
result = query(SAMPLE_DATA, "$.store.book[?(@.price < 25)]")
assert len(result) == 2
class TestSlice:
def test_basic(self):
result = query(SAMPLE_DATA, "$.store.book[0:2]")
assert len(result) == 1 # Returns a list
assert len(result[0]) == 2
class TestGetValue:
def test_single(self):
value = get_value(SAMPLE_DATA, "$.name")
assert value == "Test Store"
def test_not_found(self):
value = get_value(SAMPLE_DATA, "$.nonexistent")
assert value is None
class TestGetAll:
def test_multiple(self):
values = get_all(SAMPLE_DATA, "$.store.book[*].title")
assert len(values) == 3
class TestExists:
def test_exists(self):
assert exists(SAMPLE_DATA, "$.store.bicycle") is True
def test_not_exists(self):
assert exists(SAMPLE_DATA, "$.store.car") is False
class TestCount:
def test_count(self):
assert count(SAMPLE_DATA, "$.store.book[*]") == 3
class TestKeys:
def test_object(self):
result = keys(SAMPLE_DATA["store"])
assert "book" in result
assert "bicycle" in result
def test_non_object(self):
assert keys([1, 2, 3]) == []
class TestValues:
def test_object(self):
data = {"a": 1, "b": 2}
result = values(data)
assert 1 in result
assert 2 in result
def test_array(self):
data = [1, 2, 3]
result = values(data)
assert result == [1, 2, 3]
class TestFlatten:
def test_nested(self):
data = {"a": {"b": [1, 2, 3]}}
result = flatten(data)
assert 1 in result
assert 2 in result
assert 3 in result
def test_simple(self):
data = {"a": 1, "b": 2}
result = flatten(data)
assert result == [1, 2]
class TestComplexQueries:
def test_all_titles(self):
result = query(SAMPLE_DATA, "$..title")
assert "Book1" in result
assert "Book2" in result
assert "Book3" in result
def test_bracket_notation(self):
result = query(SAMPLE_DATA, "$['store']['book'][0]['title']")
assert result == ["Book1"]
def test_filter_and_select(self):
result = query(SAMPLE_DATA, "$.store.book[?(@.price > 25)]")
assert len(result) == 1
assert result[0]["title"] == "Book3"
| false
|
json_path
| 196
| 0
|
[
"class_definition",
"decorator"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Attribute { value: Var("s"), attr: "type" }, right: Attribute { value: Var("PathType"), attr: "RECURSIVE" } }, generators: [HirComprehension { target: "s", iter: Var("segments"), conditions: [] }] }
|
|
example_json_simple
|
json_tool.py
|
#!/usr/bin/env python3
"""JSON Example - JSON string operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="JSON string tool")
subs = parser.add_subparsers(dest="cmd", required=True)
e = subs.add_parser("escape")
e.add_argument("text")
u = subs.add_parser("unescape")
u.add_argument("text")
v = subs.add_parser("validate")
v.add_argument("text")
args = parser.parse_args()
if args.cmd == "escape":
result = args.text.replace('"', '\\"')
print(result)
elif args.cmd == "unescape":
result = args.text.replace('\\"', '"')
print(result)
elif args.cmd == "validate":
if "{" in args.text and "}" in args.text:
print("valid")
else:
print("invalid")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_json_simple/json_tool.py (845 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_json_simple/json_tool.rs (1269 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_json_simple/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 17.5 KB/s
⏱️ Total time: 47ms
| true
|
json_simple
| 33
| 6
|
[] | 0
| null |
example_json_simple
|
test_json_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for json CLI."""
import subprocess
SCRIPT = "json_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestJson:
def test_escape(self): r = run(["escape", 'hello "world"']); assert r.returncode == 0
def test_unescape(self): r = run(["unescape", 'hello']); assert r.returncode == 0
def test_validate(self): r = run(["validate", '{"a":1}']); assert r.returncode == 0
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_json_simple/test_json_tool.py (596 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_json_simple/test_json_tool.rs (1790 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 12.0 KB/s
⏱️ Total time: 48ms
| true
|
json_simple
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_len
|
len_tool.py
|
#!/usr/bin/env python3
"""Len Example - Length operations CLI.
Examples:
>>> string_length("hello")
5
>>> digit_count(12345)
5
>>> word_count("a_b_c")
3
"""
import argparse
def string_length(text: str) -> int:
"""Get length of string.
>>> string_length("")
0
>>> string_length("hello")
5
>>> string_length("hello world")
11
"""
return len(text)
def digit_count(num: int) -> int:
"""Count digits in integer.
>>> digit_count(0)
1
>>> digit_count(123)
3
>>> digit_count(-456)
3
"""
count = 0
n = num
if n < 0:
n = -n
if n == 0:
count = 1
else:
while n > 0:
count = count + 1
n = n // 10
return count
def word_count(text: str) -> int:
"""Count underscore-separated words.
>>> word_count("hello")
1
>>> word_count("a_b")
2
>>> word_count("one_two_three")
3
"""
count = 1
i = 0
while i < len(text):
if text[i] == "_":
count = count + 1
i = i + 1
return count
def main():
parser = argparse.ArgumentParser(description="Length tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("string")
s.add_argument("text")
d = subs.add_parser("digits")
d.add_argument("num", type=int)
w = subs.add_parser("words")
w.add_argument("text")
args = parser.parse_args()
if args.cmd == "string":
print(string_length(args.text))
elif args.cmd == "digits":
print(digit_count(args.num))
elif args.cmd == "words":
print(word_count(args.text))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_len/len_tool.py (1710 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_len/len_tool.rs (4686 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_len/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 32.9 KB/s
⏱️ Total time: 50ms
| true
|
len
| 92
| 6
|
[] | 0
| null |
example_len
|
test_len_tool.py
|
"""Tests for len_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "len_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_string():
r = run("string hello")
assert r.returncode == 0
assert r.stdout.strip() == "5"
def test_digits():
r = run("digits 12345")
assert r.returncode == 0
assert r.stdout.strip() == "5"
def test_words():
r = run("words hello_world_foo")
assert r.returncode == 0
assert r.stdout.strip() == "3"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_len/test_len_tool.py (624 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_len/test_len_tool.rs (1834 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_len/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 12.8 KB/s
⏱️ Total time: 47ms
| true
|
len
| 32
| 6
|
[] | 0
| null |
example_locale
|
locale_tool.py
|
#!/usr/bin/env python3
"""Locale Example - Locale formatting CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Locale formatting tool")
subs = parser.add_subparsers(dest="cmd", required=True)
c = subs.add_parser("currency")
c.add_argument("amount", type=int)
n = subs.add_parser("number")
n.add_argument("value", type=int)
p = subs.add_parser("percent")
p.add_argument("value", type=int)
args = parser.parse_args()
if args.cmd == "currency":
print(f"${args.amount}")
elif args.cmd == "number":
print(args.value)
elif args.cmd == "percent":
print(f"{args.value}%")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_locale/locale_tool.py (713 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_locale/locale_tool.rs (1004 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_locale/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 13.9 KB/s
⏱️ Total time: 50ms
| true
|
locale
| 28
| 6
|
[] | 0
| null |
example_locale
|
test_locale_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for locale CLI."""
import subprocess
SCRIPT = "locale_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestLocale:
def test_currency(self): r = run(["currency", "1000"]); assert r.returncode == 0 and "1" in r.stdout
def test_number(self): r = run(["number", "1000000"]); assert r.returncode == 0
def test_percent(self): r = run(["percent", "75"]); assert r.returncode == 0 and "75" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_locale/test_locale_tool.py (629 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_locale/test_locale_tool.rs (1865 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 12.6 KB/s
⏱️ Total time: 48ms
| true
|
locale
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_log_analyzer
|
log_analyzer.py
|
#!/usr/bin/env python3
"""
Log Analyzer - Parse and aggregate log files using generators
Demonstrates:
- Generator functions with yield
- itertools.groupby for aggregation
- Regular expressions for parsing
- Lazy line-by-line file processing
- Defaultdict for counting
This validates depyler's ability to transpile:
- yield statements in generator functions
- itertools.groupby with key functions
- re module for pattern matching
Depyler: stress test for yield and itertools transpilation
"""
import argparse
import re
import sys
from collections import defaultdict
from itertools import groupby
def parse_log_lines(file_path):
"""
Generator function to parse log lines.
Yields:
Tuple of (timestamp, level, message)
Depyler: proven to terminate
"""
# Pattern: [2025-11-17 10:30:45] INFO: Message text
pattern = re.compile(r"\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (\w+): (.+)")
with open(file_path) as f:
for line in f:
match = pattern.match(line.strip())
if match:
timestamp, level, message = match.groups()
yield (timestamp, level, message)
def count_by_level(file_path):
"""
Count log entries by level using generator.
Args:
file_path: Path to log file
Returns:
Dict of {level: count}
Depyler: proven to terminate
"""
counts = defaultdict(int)
# Generator expression consuming generator function
for _timestamp, level, _message in parse_log_lines(file_path):
counts[level] += 1
return dict(counts)
def group_by_hour(file_path):
"""
Group log entries by hour using itertools.groupby.
Args:
file_path: Path to log file
Returns:
Dict of {hour: count}
Depyler: proven to terminate
"""
def extract_hour(entry):
"""Extract hour from timestamp"""
timestamp, level, message = entry
# timestamp format: 2025-11-17 10:30:45
return timestamp[11:13] # Extract hour (HH)
# Parse all entries
entries = list(parse_log_lines(file_path))
# Sort by hour for groupby
entries.sort(key=extract_hour)
# Group and count
hour_counts = {}
for hour, group in groupby(entries, key=extract_hour):
hour_counts[hour] = sum(1 for _ in group)
return hour_counts
def filter_by_level(file_path, level):
"""
Generator that yields only entries of specified level.
Args:
file_path: Path to log file
level: Log level to filter (INFO, WARN, ERROR)
Yields:
Matching log entries
Depyler: proven to terminate
"""
for entry in parse_log_lines(file_path):
timestamp, entry_level, message = entry
if entry_level == level:
yield entry
def main():
"""CLI entry point"""
parser = argparse.ArgumentParser(
description="Analyze log files with statistics", prog="log_analyzer"
)
parser.add_argument("logfile", help="Log file to analyze")
parser.add_argument("--count-levels", action="store_true", help="Count by log level")
parser.add_argument("--group-by-hour", action="store_true", help="Group by hour")
parser.add_argument("--filter-level", help="Filter by level (INFO, WARN, ERROR)")
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
if args.count_levels:
counts = count_by_level(args.logfile)
print("Log Level Counts:")
for level, count in sorted(counts.items()):
print(f" {level}: {count}")
elif args.group_by_hour:
hour_counts = group_by_hour(args.logfile)
print("Hourly Distribution:")
for hour, count in sorted(hour_counts.items()):
print(f" {hour}:00 - {count} entries")
elif args.filter_level:
for timestamp, level, message in filter_by_level(args.logfile, args.filter_level):
print(f"[{timestamp}] {level}: {message}")
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_log_analyzer/log_analyzer.py (4082 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_log_analyzer/log_analyzer.rs (9534 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_log_analyzer/Cargo.toml (5 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 77.4 KB/s
⏱️ Total time: 51ms
| true
|
log_analyzer
| 156
| 6
|
[
"generator",
"context_manager"
] | 0.927
| null |
example_log_analyzer
|
test_log_analyzer.py
|
#!/usr/bin/env python3
"""
Test suite for log_analyzer - Generator functions with yield and groupby
Tests generator functions, yield statements, itertools.groupby, and regex parsing.
Following EXTREME TDD methodology with 100% coverage goal.
"""
import subprocess
import sys
from pathlib import Path
import pytest
# Test data fixtures
@pytest.fixture
def sample_log_data():
"""Sample log entries"""
return [
"[2025-11-17 10:30:45] INFO: Application started",
"[2025-11-17 10:30:46] DEBUG: Loading configuration",
"[2025-11-17 10:31:15] INFO: Database connected",
"[2025-11-17 10:31:20] WARN: Cache miss for key user_123",
"[2025-11-17 10:32:10] ERROR: Failed to connect to external API",
"[2025-11-17 11:15:30] INFO: Request processed",
"[2025-11-17 11:15:31] DEBUG: Response sent",
"[2025-11-17 11:45:00] ERROR: Timeout waiting for response",
]
@pytest.fixture
def sample_log_file(tmp_path, sample_log_data):
"""Create temporary log file"""
log_file = tmp_path / "test.log"
with open(log_file, "w") as f:
f.write("\n".join(sample_log_data))
return log_file
@pytest.fixture
def malformed_log_file(tmp_path):
"""Log file with some malformed lines"""
log_file = tmp_path / "malformed.log"
lines = [
"[2025-11-17 10:30:45] INFO: Valid line",
"Invalid line without timestamp",
"[2025-11-17 10:30:46] DEBUG: Another valid line",
"Another invalid line",
]
with open(log_file, "w") as f:
f.write("\n".join(lines))
return log_file
class TestLogParsing:
"""Test generator function for parsing log lines"""
def test_parse_valid_log_lines(self, sample_log_file):
"""Parse all valid log entries"""
from log_analyzer import parse_log_lines
entries = list(parse_log_lines(str(sample_log_file)))
assert len(entries) == 8
assert all(len(entry) == 3 for entry in entries) # (timestamp, level, message)
# Check first entry
timestamp, level, message = entries[0]
assert timestamp == "2025-11-17 10:30:45"
assert level == "INFO"
assert message == "Application started"
def test_parse_yields_tuples(self, sample_log_file):
"""Generator should yield tuples"""
from log_analyzer import parse_log_lines
gen = parse_log_lines(str(sample_log_file))
first_entry = next(gen)
assert isinstance(first_entry, tuple)
assert len(first_entry) == 3
def test_parse_handles_malformed_lines(self, malformed_log_file):
"""Should skip malformed lines"""
from log_analyzer import parse_log_lines
entries = list(parse_log_lines(str(malformed_log_file)))
# Only 2 valid lines
assert len(entries) == 2
def test_parse_empty_file(self, tmp_path):
"""Parse empty log file"""
from log_analyzer import parse_log_lines
empty_file = tmp_path / "empty.log"
empty_file.touch()
entries = list(parse_log_lines(str(empty_file)))
assert len(entries) == 0
class TestCountByLevel:
"""Test counting log entries by level"""
def test_count_all_levels(self, sample_log_file):
"""Count entries for each log level"""
from log_analyzer import count_by_level
counts = count_by_level(str(sample_log_file))
assert counts["INFO"] == 3
assert counts["DEBUG"] == 2
assert counts["WARN"] == 1
assert counts["ERROR"] == 2
def test_count_returns_dict(self, sample_log_file):
"""Should return dict of level counts"""
from log_analyzer import count_by_level
counts = count_by_level(str(sample_log_file))
assert isinstance(counts, dict)
assert all(isinstance(k, str) for k in counts.keys())
assert all(isinstance(v, int) for v in counts.values())
def test_count_single_level(self, tmp_path):
"""File with only one level"""
from log_analyzer import count_by_level
log_file = tmp_path / "single.log"
with open(log_file, "w") as f:
f.write("[2025-11-17 10:30:45] INFO: Line 1\n")
f.write("[2025-11-17 10:30:46] INFO: Line 2\n")
counts = count_by_level(str(log_file))
assert len(counts) == 1
assert counts["INFO"] == 2
class TestGroupByHour:
"""Test grouping entries by hour using itertools.groupby"""
def test_group_by_hour(self, sample_log_file):
"""Group log entries by hour"""
from log_analyzer import group_by_hour
hour_counts = group_by_hour(str(sample_log_file))
assert hour_counts["10"] == 5 # 5 entries in 10:xx
assert hour_counts["11"] == 3 # 3 entries in 11:xx
def test_group_returns_dict(self, sample_log_file):
"""Should return dict of hour counts"""
from log_analyzer import group_by_hour
hour_counts = group_by_hour(str(sample_log_file))
assert isinstance(hour_counts, dict)
assert all(isinstance(k, str) for k in hour_counts.keys())
assert all(isinstance(v, int) for v in hour_counts.values())
def test_group_single_hour(self, tmp_path):
"""All entries in same hour"""
from log_analyzer import group_by_hour
log_file = tmp_path / "single_hour.log"
with open(log_file, "w") as f:
f.write("[2025-11-17 14:00:00] INFO: Entry 1\n")
f.write("[2025-11-17 14:15:00] INFO: Entry 2\n")
f.write("[2025-11-17 14:30:00] INFO: Entry 3\n")
hour_counts = group_by_hour(str(log_file))
assert len(hour_counts) == 1
assert hour_counts["14"] == 3
class TestFilterByLevel:
"""Test generator that filters entries by level"""
def test_filter_info_level(self, sample_log_file):
"""Filter only INFO entries"""
from log_analyzer import filter_by_level
info_entries = list(filter_by_level(str(sample_log_file), "INFO"))
assert len(info_entries) == 3
assert all(entry[1] == "INFO" for entry in info_entries)
def test_filter_error_level(self, sample_log_file):
"""Filter only ERROR entries"""
from log_analyzer import filter_by_level
error_entries = list(filter_by_level(str(sample_log_file), "ERROR"))
assert len(error_entries) == 2
assert all(entry[1] == "ERROR" for entry in error_entries)
def test_filter_nonexistent_level(self, sample_log_file):
"""Filter level that doesn't exist"""
from log_analyzer import filter_by_level
entries = list(filter_by_level(str(sample_log_file), "CRITICAL"))
assert len(entries) == 0
def test_filter_yields_generator(self, sample_log_file):
"""Should return generator"""
from log_analyzer import filter_by_level
gen = filter_by_level(str(sample_log_file), "INFO")
# Generator should not consume entries until iterated
assert hasattr(gen, "__iter__")
assert hasattr(gen, "__next__")
class TestCLIInterface:
"""Test command-line interface"""
def test_cli_help(self):
"""Test --help flag"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", "--help"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "Analyze log files" in result.stdout
def test_cli_version(self):
"""Test --version flag"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", "--version"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "1.0.0" in result.stdout
def test_cli_count_levels(self, sample_log_file):
"""Test --count-levels flag"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", str(sample_log_file), "--count-levels"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "INFO: 3" in result.stdout
assert "ERROR: 2" in result.stdout
def test_cli_group_by_hour(self, sample_log_file):
"""Test --group-by-hour flag"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", str(sample_log_file), "--group-by-hour"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "10:00" in result.stdout
assert "11:00" in result.stdout
def test_cli_filter_level(self, sample_log_file):
"""Test --filter-level flag"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", str(sample_log_file), "--filter-level", "ERROR"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "ERROR" in result.stdout
assert result.stdout.count("ERROR") >= 2
def test_cli_no_args(self):
"""Test CLI with no action flags"""
result = subprocess.run(
[sys.executable, "log_analyzer.py", "/tmp/test.log"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
# Should show help and exit with error
assert result.returncode != 0
class TestPropertyBased:
"""Property-based tests for invariants"""
def test_parsed_count_matches_valid_lines(self, sample_log_file):
"""Property: parsed entries = valid log lines"""
from log_analyzer import parse_log_lines
# Count valid lines in file
with open(sample_log_file) as f:
valid_lines = sum(1 for line in f if line.strip().startswith("["))
parsed = list(parse_log_lines(str(sample_log_file)))
assert len(parsed) == valid_lines
def test_level_counts_sum_to_total(self, sample_log_file):
"""Property: sum(level_counts) = total entries"""
from log_analyzer import count_by_level, parse_log_lines
total_entries = len(list(parse_log_lines(str(sample_log_file))))
counts = count_by_level(str(sample_log_file))
assert sum(counts.values()) == total_entries
def test_hour_counts_sum_to_total(self, sample_log_file):
"""Property: sum(hour_counts) = total entries"""
from log_analyzer import group_by_hour, parse_log_lines
total_entries = len(list(parse_log_lines(str(sample_log_file))))
hour_counts = group_by_hour(str(sample_log_file))
assert sum(hour_counts.values()) == total_entries
def test_filter_subset_of_total(self, sample_log_file):
"""Property: filtered entries ≤ total entries"""
from log_analyzer import filter_by_level, parse_log_lines
total_entries = len(list(parse_log_lines(str(sample_log_file))))
filtered = list(filter_by_level(str(sample_log_file), "INFO"))
assert len(filtered) <= total_entries
| false
|
log_analyzer
| 334
| 0
|
[
"generator",
"context_manager",
"class_definition",
"decorator"
] | 0.927
|
Type inference hints:
Hint: list[str] for return type [Medium] (explicit return)
Type inference hints:
Hint: str for return type [Medium] (explicit return)
Hint: str for variable 'log_file' [Medium] (usage patterns suggest this type)
Hint: int for variable 'tmp_path' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for return type [Medium] (explicit return)
Hint: str for variable 'log_file' [Medium] (usage patterns suggest this type)
Hint: int for variable 'tmp_path'
|
|
example_log_parser
|
log_cli.py
|
#!/usr/bin/env python3
"""Apache/nginx combined log format parser CLI.
Parses log lines in Combined Log Format:
IP - - [timestamp] "METHOD /path HTTP/x.x" status size "referer" "user-agent"
"""
import argparse
import re
import sys
# Combined Log Format regex
LOG_PATTERN = re.compile(
r"(\S+)\s+" # IP address
r"(\S+)\s+" # ident
r"(\S+)\s+" # user
r"\[([^\]]+)\]\s+" # timestamp
r'"(\S+)\s+(\S+)\s+(\S+)"\s+' # method, path, protocol
r"(\d+)\s+" # status code
r"(\S+)\s*" # response size
r'(?:"([^"]*)"\s*)?' # referer (optional)
r'(?:"([^"]*)")?' # user-agent (optional)
)
def parse_log_line(line: str) -> dict | None:
"""Parse a single log line into components."""
match = LOG_PATTERN.match(line.strip())
if not match:
return None
groups = match.groups()
return {
"ip": groups[0],
"ident": groups[1],
"user": groups[2],
"timestamp": groups[3],
"method": groups[4],
"path": groups[5],
"protocol": groups[6],
"status": int(groups[7]),
"size": 0 if groups[8] == "-" else int(groups[8]),
"referer": groups[9] if groups[9] else "-",
"user_agent": groups[10] if groups[10] else "-",
}
def filter_by_status(entries: list, status_code: int) -> list:
"""Filter log entries by status code."""
return [e for e in entries if e["status"] == status_code]
def filter_by_method(entries: list, method: str) -> list:
"""Filter log entries by HTTP method."""
return [e for e in entries if e["method"].upper() == method.upper()]
def count_by_ip(entries: list) -> dict:
"""Count requests per IP address."""
counts: dict = {}
for entry in entries:
ip = entry["ip"]
counts[ip] = counts.get(ip, 0) + 1
return counts
def count_by_status(entries: list) -> dict:
"""Count requests per status code."""
counts: dict = {}
for entry in entries:
status = entry["status"]
counts[status] = counts.get(status, 0) + 1
return counts
def format_entry(entry: dict, output_format: str) -> str:
"""Format a log entry for output."""
if output_format == "json":
import json
return json.dumps(entry)
elif output_format == "csv":
return f"{entry['ip']},{entry['method']},{entry['path']},{entry['status']},{entry['size']}"
else: # table
return f"{entry['ip']:15} {entry['method']:6} {entry['status']:3} {entry['path']}"
def main() -> int:
parser = argparse.ArgumentParser(description="Parse and analyze Apache/nginx log files")
parser.add_argument("logfile", nargs="?", help="Log file to parse (- for stdin)")
parser.add_argument(
"-f", "--format", choices=["table", "json", "csv"], default="table", help="Output format"
)
parser.add_argument("--status", type=int, help="Filter by status code")
parser.add_argument("--method", help="Filter by HTTP method")
parser.add_argument("--stats", action="store_true", help="Show statistics instead of entries")
parser.add_argument("--top-ips", type=int, metavar="N", help="Show top N IPs by request count")
args = parser.parse_args()
# Read input
if args.logfile is None or args.logfile == "-":
lines = sys.stdin.readlines()
else:
with open(args.logfile) as f:
lines = f.readlines()
# Parse all lines
entries = []
parse_errors = 0
for line in lines:
entry = parse_log_line(line)
if entry:
entries.append(entry)
else:
parse_errors += 1
# Apply filters
if args.status:
entries = filter_by_status(entries, args.status)
if args.method:
entries = filter_by_method(entries, args.method)
# Output
if args.stats:
print(f"Total entries: {len(entries)}")
print(f"Parse errors: {parse_errors}")
status_counts = count_by_status(entries)
print("Status codes:")
for status, count in sorted(status_counts.items()):
print(f" {status}: {count}")
elif args.top_ips:
ip_counts = count_by_ip(entries)
sorted_ips = sorted(ip_counts.items(), key=lambda x: x[1], reverse=True)
for ip, count in sorted_ips[: args.top_ips]:
print(f"{ip}: {count}")
else:
for entry in entries:
print(format_entry(entry, args.format))
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
log_parser
| 146
| 0
|
[
"lambda",
"context_manager",
"exception_handling",
"stdin_usage"
] | 0.783
|
Type inference hints:
Hint: str for variable 'line' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: dict[str, serde_json::Value] for variable 'entry' [High] (usage patterns suggest this type)
Type inference hints:
Hint: dict[str, serde_json::Value] for variable 'entry' [High] (usage patterns suggest this type)
Type inference hints:
Hint: dict[str, serde_json::Value] for variable 'entry' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for vari
|
|
example_log_parser
|
test_log_cli.py
|
"""Tests for log_cli.py"""
from log_cli import (
count_by_ip,
count_by_status,
filter_by_method,
filter_by_status,
format_entry,
parse_log_line,
)
SAMPLE_LOG = '192.168.1.1 - - [10/Oct/2023:13:55:36 -0700] "GET /index.html HTTP/1.1" 200 2326 "http://example.com" "Mozilla/5.0"'
class TestParsing:
def test_parse_valid_line(self):
entry = parse_log_line(SAMPLE_LOG)
assert entry is not None
assert entry["ip"] == "192.168.1.1"
assert entry["method"] == "GET"
assert entry["path"] == "/index.html"
assert entry["status"] == 200
assert entry["size"] == 2326
def test_parse_invalid_line(self):
entry = parse_log_line("invalid log line")
assert entry is None
def test_parse_dash_size(self):
log = '10.0.0.1 - - [01/Jan/2024:00:00:00 +0000] "GET / HTTP/1.1" 304 - "-" "-"'
entry = parse_log_line(log)
assert entry is not None
assert entry["size"] == 0
class TestFilters:
def test_filter_by_status(self):
entries = [
{"status": 200, "ip": "1.1.1.1"},
{"status": 404, "ip": "2.2.2.2"},
{"status": 200, "ip": "3.3.3.3"},
]
result = filter_by_status(entries, 200)
assert len(result) == 2
assert all(e["status"] == 200 for e in result)
def test_filter_by_method(self):
entries = [
{"method": "GET", "ip": "1.1.1.1"},
{"method": "POST", "ip": "2.2.2.2"},
{"method": "GET", "ip": "3.3.3.3"},
]
result = filter_by_method(entries, "GET")
assert len(result) == 2
class TestCounting:
def test_count_by_ip(self):
entries = [
{"ip": "1.1.1.1"},
{"ip": "2.2.2.2"},
{"ip": "1.1.1.1"},
]
counts = count_by_ip(entries)
assert counts["1.1.1.1"] == 2
assert counts["2.2.2.2"] == 1
def test_count_by_status(self):
entries = [
{"status": 200},
{"status": 404},
{"status": 200},
]
counts = count_by_status(entries)
assert counts[200] == 2
assert counts[404] == 1
class TestFormatting:
def test_format_table(self):
entry = {
"ip": "1.1.1.1",
"method": "GET",
"path": "/test",
"status": 200,
"size": 100,
}
result = format_entry(entry, "table")
assert "1.1.1.1" in result
assert "GET" in result
assert "200" in result
def test_format_csv(self):
entry = {
"ip": "1.1.1.1",
"method": "GET",
"path": "/test",
"status": 200,
"size": 100,
}
result = format_entry(entry, "csv")
assert result == "1.1.1.1,GET,/test,200,100"
| false
|
log_parser
| 102
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Index { base: Var("e"), index: Literal(String("status")) }, right: Literal(Int(200)) }, generators: [HirComprehension { target: "e", iter: Var("result"), conditions: [] }] }
|
|
example_lru_cache
|
cache_cli.py
|
#!/usr/bin/env python3
"""LRU Cache CLI.
Implementation of LRU (Least Recently Used) cache with various features.
"""
import argparse
import sys
from collections import OrderedDict
class LRUCache:
"""LRU Cache using OrderedDict."""
def __init__(self, capacity: int):
self.capacity = capacity
self.cache: OrderedDict = OrderedDict()
self.hits = 0
self.misses = 0
def get(self, key: str) -> int | None:
"""Get value from cache. Returns None if not found."""
if key not in self.cache:
self.misses += 1
return None
self.hits += 1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: str, value: int) -> None:
"""Put value in cache. Evicts LRU item if at capacity."""
if key in self.cache:
self.cache.move_to_end(key)
else:
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
def delete(self, key: str) -> bool:
"""Delete key from cache. Returns True if deleted."""
if key in self.cache:
del self.cache[key]
return True
return False
def clear(self) -> None:
"""Clear all items from cache."""
self.cache.clear()
self.hits = 0
self.misses = 0
def size(self) -> int:
"""Get current size of cache."""
return len(self.cache)
def keys(self) -> list[str]:
"""Get all keys in LRU order (oldest first)."""
return list(self.cache.keys())
def values(self) -> list[int]:
"""Get all values in LRU order (oldest first)."""
return list(self.cache.values())
def items(self) -> list[tuple[str, int]]:
"""Get all items in LRU order (oldest first)."""
return list(self.cache.items())
def peek(self, key: str) -> int | None:
"""Get value without updating access order."""
return self.cache.get(key)
def contains(self, key: str) -> bool:
"""Check if key exists in cache."""
return key in self.cache
def hit_rate(self) -> float:
"""Calculate cache hit rate."""
total = self.hits + self.misses
if total == 0:
return 0.0
return self.hits / total
def stats(self) -> dict:
"""Get cache statistics."""
return {
"capacity": self.capacity,
"size": self.size(),
"hits": self.hits,
"misses": self.misses,
"hit_rate": self.hit_rate(),
}
def to_dict(self) -> dict:
"""Serialize cache to dict."""
return {
"capacity": self.capacity,
"items": list(self.cache.items()),
"hits": self.hits,
"misses": self.misses,
}
@classmethod
def from_dict(cls, data: dict) -> "LRUCache":
"""Deserialize cache from dict."""
cache = cls(data["capacity"])
for key, value in data["items"]:
cache.cache[key] = value
cache.hits = data.get("hits", 0)
cache.misses = data.get("misses", 0)
return cache
class TTLCache(LRUCache):
"""LRU Cache with TTL (time-to-live) support."""
def __init__(self, capacity: int, default_ttl: int):
super().__init__(capacity)
self.default_ttl = default_ttl
self.timestamps: dict[str, int] = {}
self.ttls: dict[str, int] = {}
self.current_time = 0
def set_time(self, time: int) -> None:
"""Set current time for TTL checking."""
self.current_time = time
def put_with_ttl(self, key: str, value: int, ttl: int | None = None) -> None:
"""Put value with specific TTL."""
self.put(key, value)
self.timestamps[key] = self.current_time
self.ttls[key] = ttl if ttl is not None else self.default_ttl
def get(self, key: str) -> int | None:
"""Get value, checking TTL."""
if key in self.cache:
if self.is_expired(key):
self.delete(key)
self.misses += 1
return None
return super().get(key)
def is_expired(self, key: str) -> bool:
"""Check if key is expired."""
if key not in self.timestamps:
return False
elapsed = self.current_time - self.timestamps[key]
ttl = self.ttls.get(key, self.default_ttl)
return elapsed > ttl
def cleanup_expired(self) -> int:
"""Remove all expired entries. Returns count removed."""
expired = [k for k in list(self.cache.keys()) if self.is_expired(k)]
for key in expired:
self.delete(key)
if key in self.timestamps:
del self.timestamps[key]
if key in self.ttls:
del self.ttls[key]
return len(expired)
def cache_simulation(operations: list[tuple[str, str, int | None]], capacity: int) -> list[str]:
"""Simulate cache operations and return results."""
cache = LRUCache(capacity)
results = []
for op, key, value in operations:
if op == "get":
result = cache.get(key)
if result is not None:
results.append(f"GET {key} = {result}")
else:
results.append(f"GET {key} = MISS")
elif op == "put":
cache.put(key, value)
results.append(f"PUT {key} = {value}")
elif op == "delete":
if cache.delete(key):
results.append(f"DELETE {key} = OK")
else:
results.append(f"DELETE {key} = NOT_FOUND")
return results
def optimal_cache_size(access_pattern: list[str], max_capacity: int) -> dict:
"""Find optimal cache size for given access pattern."""
results = {}
for capacity in range(1, max_capacity + 1):
cache = LRUCache(capacity)
for key in access_pattern:
if cache.get(key) is None:
cache.put(key, 1)
results[capacity] = {
"hits": cache.hits,
"misses": cache.misses,
"hit_rate": cache.hit_rate(),
}
best_capacity = max(results.keys(), key=lambda c: results[c]["hit_rate"])
return {
"best_capacity": best_capacity,
"best_hit_rate": results[best_capacity]["hit_rate"],
"all_results": results,
}
def main() -> int:
parser = argparse.ArgumentParser(description="LRU Cache operations")
parser.add_argument("--capacity", type=int, default=3, help="Cache capacity")
parser.add_argument(
"--mode",
choices=["interactive", "simulate", "stats"],
default="interactive",
help="Operation mode",
)
parser.add_argument("operations", nargs="*", help="Operations: get:key or put:key:value")
args = parser.parse_args()
cache = LRUCache(args.capacity)
if args.mode == "simulate" and args.operations:
parsed_ops = []
for op in args.operations:
parts = op.split(":")
if parts[0] == "get":
parsed_ops.append(("get", parts[1], None))
elif parts[0] == "put":
parsed_ops.append(("put", parts[1], int(parts[2])))
elif parts[0] == "delete":
parsed_ops.append(("delete", parts[1], None))
results = cache_simulation(parsed_ops, args.capacity)
for result in results:
print(result)
return 0
for op in args.operations:
parts = op.split(":")
if parts[0] == "get":
result = cache.get(parts[1])
if result is not None:
print(f"GET {parts[1]} = {result}")
else:
print(f"GET {parts[1]} = MISS")
elif parts[0] == "put":
cache.put(parts[1], int(parts[2]))
print(f"PUT {parts[1]} = {parts[2]}")
elif parts[0] == "delete":
if cache.delete(parts[1]):
print(f"DELETE {parts[1]} = OK")
else:
print(f"DELETE {parts[1]} = NOT_FOUND")
if args.mode == "stats":
stats = cache.stats()
print(f"Capacity: {stats['capacity']}")
print(f"Size: {stats['size']}")
print(f"Hits: {stats['hits']}")
print(f"Misses: {stats['misses']}")
print(f"Hit Rate: {stats['hit_rate']:.2%}")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
lru_cache
| 274
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"decorator"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 2910..2920, value: Str("LRUCache"), kind: None })
|
|
example_lru_cache
|
fib_tool.py
|
#!/usr/bin/env python3
"""
LRU Cache Example - Memoized computations
Demonstrates functools.lru_cache for memoization.
"""
import argparse
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
"""Memoized fibonacci. Depyler: proven to terminate"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
@lru_cache(maxsize=128)
def factorial(n: int) -> int:
"""Memoized factorial. Depyler: proven to terminate"""
if n <= 1:
return 1
return n * factorial(n - 1)
def main():
parser = argparse.ArgumentParser(description="Memoized math tool")
subparsers = parser.add_subparsers(dest="command", required=True)
fib_p = subparsers.add_parser("fib", help="Fibonacci number")
fib_p.add_argument("n", type=int)
fact_p = subparsers.add_parser("fact", help="Factorial")
fact_p.add_argument("n", type=int)
args = parser.parse_args()
if args.command == "fib":
print(f"fib({args.n}) = {fibonacci(args.n)}")
elif args.command == "fact":
print(f"fact({args.n}) = {factorial(args.n)}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/fib_tool.py (1150 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/fib_tool.rs (1910 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/Cargo.toml (1 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 22.0 KB/s
⏱️ Total time: 51ms
| true
|
lru_cache
| 46
| 6
|
[
"decorator",
"functools"
] | 0.5
| null |
example_lru_cache
|
test_cache_cli.py
|
"""Tests for cache_cli.py"""
import pytest
from cache_cli import (
LRUCache,
TTLCache,
cache_simulation,
optimal_cache_size,
)
class TestLRUCache:
def test_init(self):
cache = LRUCache(3)
assert cache.capacity == 3
assert cache.size() == 0
def test_put_and_get(self):
cache = LRUCache(3)
cache.put("a", 1)
assert cache.get("a") == 1
def test_get_miss(self):
cache = LRUCache(3)
assert cache.get("missing") is None
def test_eviction(self):
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3) # Should evict "a"
assert cache.get("a") is None
assert cache.get("b") == 2
assert cache.get("c") == 3
def test_access_updates_order(self):
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a") # Access "a" to make it recently used
cache.put("c", 3) # Should evict "b"
assert cache.get("a") == 1
assert cache.get("b") is None
assert cache.get("c") == 3
def test_update_value(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("a", 10)
assert cache.get("a") == 10
assert cache.size() == 1
def test_delete(self):
cache = LRUCache(3)
cache.put("a", 1)
assert cache.delete("a") is True
assert cache.get("a") is None
def test_delete_missing(self):
cache = LRUCache(3)
assert cache.delete("missing") is False
def test_clear(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.clear()
assert cache.size() == 0
assert cache.get("a") is None
def test_keys(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
assert cache.keys() == ["a", "b", "c"]
def test_values(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
assert cache.values() == [1, 2]
def test_items(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
assert cache.items() == [("a", 1), ("b", 2)]
def test_peek(self):
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
# Peek doesn't update access order
assert cache.peek("a") == 1
cache.put("c", 3) # Should still evict "a" since peek didn't update
assert cache.get("a") is None
def test_contains(self):
cache = LRUCache(3)
cache.put("a", 1)
assert cache.contains("a") is True
assert cache.contains("b") is False
def test_hit_rate(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a") # Hit
cache.get("b") # Hit
cache.get("c") # Miss
assert cache.hit_rate() == pytest.approx(2 / 3, rel=0.01)
def test_stats(self):
cache = LRUCache(5)
cache.put("a", 1)
cache.get("a")
cache.get("missing")
stats = cache.stats()
assert stats["capacity"] == 5
assert stats["size"] == 1
assert stats["hits"] == 1
assert stats["misses"] == 1
def test_to_from_dict(self):
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")
cache.get("c") # Miss
original_hits = cache.hits
original_misses = cache.misses
data = cache.to_dict()
restored = LRUCache.from_dict(data)
assert restored.capacity == 3
# Check hits/misses before accessing (get increments counters)
assert restored.hits == original_hits
assert restored.misses == original_misses
# Now verify data was restored correctly
assert restored.get("a") == 1
assert restored.get("b") == 2
class TestTTLCache:
def test_init(self):
cache = TTLCache(3, 10)
assert cache.capacity == 3
assert cache.default_ttl == 10
def test_put_with_ttl(self):
cache = TTLCache(3, 10)
cache.set_time(0)
cache.put_with_ttl("a", 1, 5)
assert cache.get("a") == 1
def test_expired(self):
cache = TTLCache(3, 10)
cache.set_time(0)
cache.put_with_ttl("a", 1, 5)
cache.set_time(10) # Past TTL
assert cache.get("a") is None
def test_not_expired(self):
cache = TTLCache(3, 10)
cache.set_time(0)
cache.put_with_ttl("a", 1, 10)
cache.set_time(5) # Within TTL
assert cache.get("a") == 1
def test_default_ttl(self):
cache = TTLCache(3, 5)
cache.set_time(0)
cache.put_with_ttl("a", 1) # Uses default TTL of 5
cache.set_time(3)
assert cache.get("a") == 1
cache.set_time(10)
assert cache.get("a") is None
def test_cleanup_expired(self):
cache = TTLCache(5, 10)
cache.set_time(0)
cache.put_with_ttl("a", 1, 5)
cache.put_with_ttl("b", 2, 15)
cache.put_with_ttl("c", 3, 5)
cache.set_time(10)
removed = cache.cleanup_expired()
assert removed == 2
assert cache.get("a") is None
assert cache.get("b") == 2
assert cache.get("c") is None
class TestCacheSimulation:
def test_basic(self):
ops = [
("put", "a", 1),
("put", "b", 2),
("get", "a", None),
("get", "c", None),
]
results = cache_simulation(ops, 3)
assert results[0] == "PUT a = 1"
assert results[1] == "PUT b = 2"
assert results[2] == "GET a = 1"
assert results[3] == "GET c = MISS"
def test_eviction(self):
ops = [
("put", "a", 1),
("put", "b", 2),
("put", "c", 3),
("get", "a", None), # Should be evicted
]
results = cache_simulation(ops, 2)
assert results[3] == "GET a = MISS"
def test_delete(self):
ops = [
("put", "a", 1),
("delete", "a", None),
("delete", "b", None),
]
results = cache_simulation(ops, 3)
assert results[1] == "DELETE a = OK"
assert results[2] == "DELETE b = NOT_FOUND"
class TestOptimalCacheSize:
def test_basic(self):
pattern = ["a", "b", "c", "a", "b", "c", "d", "a", "b"]
result = optimal_cache_size(pattern, 5)
assert "best_capacity" in result
assert "best_hit_rate" in result
assert result["best_capacity"] >= 1
assert result["best_capacity"] <= 5
def test_repeating_pattern(self):
pattern = ["a", "a", "a", "a"] # All same key
result = optimal_cache_size(pattern, 3)
# With repeating keys, even capacity 1 has high hit rate
assert result["best_hit_rate"] >= 0.5
def test_unique_pattern(self):
pattern = ["a", "b", "c", "d", "e"] # All unique - no repeats
result = optimal_cache_size(pattern, 5)
# With unique keys and no repetition, hit rate will be 0
# So any capacity gives the same result
assert result["best_hit_rate"] == 0.0
assert "all_results" in result
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/test_cache_cli.py (7326 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/test_cache_cli.rs (11167 bytes)
⏱️ Parse time: 55ms
📊 Throughput: 129.8 KB/s
⏱️ Total time: 55ms
| true
|
lru_cache
| 276
| 5
|
[
"class_definition"
] | 0.612
| null |
example_lru_cache
|
test_fib_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for lru_cache CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "fib_tool.py"
SCRIPT = "fib_tool.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
cwd=__file__.rsplit("/", 1)[0])
class TestFibonacci:
def test_fib_0(self):
result = run(["fib", "0"])
assert result.returncode == 0
assert "0" in result.stdout
def test_fib_10(self):
result = run(["fib", "10"])
assert result.returncode == 0
assert "55" in result.stdout
def test_fib_20(self):
result = run(["fib", "20"])
assert result.returncode == 0
assert "6765" in result.stdout
class TestFactorial:
def test_fact_5(self):
result = run(["fact", "5"])
assert result.returncode == 0
assert "120" in result.stdout
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/test_fib_tool.py (1100 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/test_fib_tool.rs (2552 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_lru_cache/Cargo.toml (2 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 20.7 KB/s
⏱️ Total time: 52ms
| true
|
lru_cache
| 44
| 6
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_markdown_parser
|
markdown_cli.py
|
#!/usr/bin/env python3
"""Simple markdown to HTML converter CLI.
Supports basic markdown syntax:
- Headers (# to ######)
- Bold (**text**)
- Italic (*text*)
- Code (`text`)
- Links ([text](url))
- Unordered lists (- item)
"""
import argparse
import re
import sys
def parse_headers(text: str) -> str:
"""Convert markdown headers to HTML."""
for i in range(6, 0, -1):
pattern = r"^" + "#" * i + r" (.+)$"
text = re.sub(pattern, rf"<h{i}>\1</h{i}>", text, flags=re.MULTILINE)
return text
def parse_bold(text: str) -> str:
"""Convert **bold** to <strong>."""
return re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
def parse_italic(text: str) -> str:
"""Convert *italic* to <em>."""
return re.sub(r"\*(.+?)\*", r"<em>\1</em>", text)
def parse_code(text: str) -> str:
"""Convert `code` to <code>."""
return re.sub(r"`(.+?)`", r"<code>\1</code>", text)
def parse_links(text: str) -> str:
"""Convert [text](url) to <a href>."""
return re.sub(r"\[(.+?)\]\((.+?)\)", r'<a href="\2">\1</a>', text)
def parse_lists(text: str) -> str:
"""Convert unordered lists to HTML."""
lines = text.split("\n")
result = []
in_list = False
for line in lines:
if line.startswith("- "):
if not in_list:
result.append("<ul>")
in_list = True
result.append(f"<li>{line[2:]}</li>")
else:
if in_list:
result.append("</ul>")
in_list = False
result.append(line)
if in_list:
result.append("</ul>")
return "\n".join(result)
def parse_paragraphs(text: str) -> str:
"""Wrap standalone text in <p> tags."""
lines = text.split("\n")
result = []
for line in lines:
stripped = line.strip()
if stripped and not stripped.startswith("<"):
result.append(f"<p>{stripped}</p>")
else:
result.append(line)
return "\n".join(result)
def markdown_to_html(markdown: str) -> str:
"""Convert markdown text to HTML."""
html = markdown
html = parse_headers(html)
html = parse_bold(html)
html = parse_italic(html)
html = parse_code(html)
html = parse_links(html)
html = parse_lists(html)
html = parse_paragraphs(html)
return html
def main() -> int:
parser = argparse.ArgumentParser(
description="Convert markdown to HTML",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("input", nargs="?", help="Input markdown file (- for stdin)")
parser.add_argument("-o", "--output", help="Output HTML file (default: stdout)")
parser.add_argument("--wrap", action="store_true", help="Wrap output in HTML document")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
markdown = sys.stdin.read()
else:
with open(args.input) as f:
markdown = f.read()
# Convert
html = markdown_to_html(markdown)
# Optionally wrap in document
if args.wrap:
html = f"""<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Document</title></head>
<body>
{html}
</body>
</html>"""
# Write output
if args.output:
with open(args.output, "w") as f:
f.write(html)
else:
print(html)
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_markdown_parser/markdown_cli.py (3424 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_markdown_parser/markdown_cli.rs (5960 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_markdown_parser/Cargo.toml (2 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 63.0 KB/s
⏱️ Total time: 53ms
| true
|
markdown_parser
| 140
| 6
|
[
"context_manager",
"stdin_usage"
] | 0.652
| null |
example_markdown_parser
|
test_markdown_cli.py
|
"""Tests for markdown_cli.py"""
from markdown_cli import (
markdown_to_html,
parse_bold,
parse_code,
parse_headers,
parse_italic,
parse_links,
parse_lists,
)
class TestHeaders:
def test_h1(self):
assert parse_headers("# Hello") == "<h1>Hello</h1>"
def test_h2(self):
assert parse_headers("## World") == "<h2>World</h2>"
def test_h6(self):
assert parse_headers("###### Deep") == "<h6>Deep</h6>"
def test_multiple_headers(self):
text = "# One\n## Two"
result = parse_headers(text)
assert "<h1>One</h1>" in result
assert "<h2>Two</h2>" in result
class TestInlineFormatting:
def test_bold(self):
assert parse_bold("**bold**") == "<strong>bold</strong>"
def test_italic(self):
assert parse_italic("*italic*") == "<em>italic</em>"
def test_code(self):
assert parse_code("`code`") == "<code>code</code>"
def test_nested_formatting(self):
text = "**bold** and *italic*"
result = parse_bold(text)
result = parse_italic(result)
assert "<strong>bold</strong>" in result
assert "<em>italic</em>" in result
class TestLinks:
def test_basic_link(self):
result = parse_links("[Google](https://google.com)")
assert result == '<a href="https://google.com">Google</a>'
def test_multiple_links(self):
text = "[A](a.com) and [B](b.com)"
result = parse_links(text)
assert '<a href="a.com">A</a>' in result
assert '<a href="b.com">B</a>' in result
class TestLists:
def test_simple_list(self):
text = "- item1\n- item2"
result = parse_lists(text)
assert "<ul>" in result
assert "<li>item1</li>" in result
assert "<li>item2</li>" in result
assert "</ul>" in result
def test_list_with_text(self):
text = "before\n- item\nafter"
result = parse_lists(text)
assert "before" in result
assert "<li>item</li>" in result
assert "after" in result
class TestFullConversion:
def test_simple_document(self):
markdown = """# Title
This is a paragraph with **bold** text.
- item one
- item two
"""
html = markdown_to_html(markdown)
assert "<h1>Title</h1>" in html
assert "<strong>bold</strong>" in html
assert "<li>item one</li>" in html
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_markdown_parser/test_markdown_cli.py (2396 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_markdown_parser/test_markdown_cli.rs (5545 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 46.5 KB/s
⏱️ Total time: 50ms
| true
|
markdown_parser
| 90
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_math
|
math_tool.py
|
#!/usr/bin/env python3
"""Math Example - Basic math functions CLI.
Examples:
>>> compute_sin(0.0)
0.0
>>> compute_sqrt(4.0)
2.0
>>> compute_ceil(2.3)
3
>>> compute_floor(2.7)
2
"""
import argparse
import math
def compute_sin(x: float) -> float:
"""Compute sine of x radians.
>>> compute_sin(0.0)
0.0
>>> abs(compute_sin(3.14159265359 / 2) - 1.0) < 0.0001
True
"""
return math.sin(x)
def compute_cos(x: float) -> float:
"""Compute cosine of x radians.
>>> compute_cos(0.0)
1.0
>>> abs(compute_cos(math.pi) + 1.0) < 0.0001
True
"""
return math.cos(x)
def compute_sqrt(x: float) -> float:
"""Compute square root.
>>> compute_sqrt(0.0)
0.0
>>> compute_sqrt(4.0)
2.0
>>> compute_sqrt(9.0)
3.0
"""
return math.sqrt(x)
def compute_ceil(x: float) -> int:
"""Compute ceiling.
>>> compute_ceil(2.0)
2
>>> compute_ceil(2.1)
3
>>> compute_ceil(-2.1)
-2
"""
return math.ceil(x)
def compute_floor(x: float) -> int:
"""Compute floor.
>>> compute_floor(2.0)
2
>>> compute_floor(2.9)
2
>>> compute_floor(-2.1)
-3
"""
return math.floor(x)
def main():
parser = argparse.ArgumentParser(description="Math functions tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("sin")
s.add_argument("x", type=float)
c = subs.add_parser("cos")
c.add_argument("x", type=float)
sq = subs.add_parser("sqrt")
sq.add_argument("x", type=float)
ce = subs.add_parser("ceil")
ce.add_argument("x", type=float)
fl = subs.add_parser("floor")
fl.add_argument("x", type=float)
args = parser.parse_args()
if args.cmd == "sin":
print(compute_sin(args.x))
elif args.cmd == "cos":
print(compute_cos(args.x))
elif args.cmd == "sqrt":
print(compute_sqrt(args.x))
elif args.cmd == "ceil":
print(compute_ceil(args.x))
elif args.cmd == "floor":
print(compute_floor(args.x))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_math/math_tool.py (2119 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_math/math_tool.rs (2648 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_math/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 44.2 KB/s
⏱️ Total time: 46ms
| true
|
math
| 109
| 6
|
[] | 0
| null |
example_math
|
test_math_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for math CLI."""
import subprocess
SCRIPT = "math_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestTrig:
def test_sin(self): r = run(["sin", "0"]); assert r.returncode == 0 and "0" in r.stdout
def test_cos(self): r = run(["cos", "0"]); assert r.returncode == 0 and "1" in r.stdout
class TestPower:
def test_sqrt(self): r = run(["sqrt", "16"]); assert r.returncode == 0 and "4" in r.stdout
class TestRound:
def test_ceil(self): r = run(["ceil", "4.2"]); assert r.returncode == 0 and "5" in r.stdout
def test_floor(self): r = run(["floor", "4.8"]); assert r.returncode == 0 and "4" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_math/test_math_tool.py (841 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_math/test_math_tool.rs (2466 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 16.5 KB/s
⏱️ Total time: 49ms
| true
|
math
| 20
| 5
|
[
"class_definition"
] | 0.612
| null |
example_math_constants
|
constants_cli.py
|
#!/usr/bin/env python3
"""Math Constants CLI.
Mathematical constants and special value handling.
"""
import argparse
import math
import sys
# Constants
PI: float = math.pi
E: float = math.e
TAU: float = math.tau
INF: float = math.inf
NEG_INF: float = -math.inf
NAN: float = math.nan
def get_pi() -> float:
"""Get pi constant."""
return PI
def get_e() -> float:
"""Get Euler's number."""
return E
def get_tau() -> float:
"""Get tau (2*pi)."""
return TAU
def get_inf() -> float:
"""Get positive infinity."""
return INF
def get_neg_inf() -> float:
"""Get negative infinity."""
return NEG_INF
def get_nan() -> float:
"""Get NaN."""
return NAN
def circle_circumference(radius: float) -> float:
"""Calculate circle circumference."""
return 2 * PI * radius
def circle_area(radius: float) -> float:
"""Calculate circle area."""
return PI * radius * radius
def sphere_volume(radius: float) -> float:
"""Calculate sphere volume."""
return (4 / 3) * PI * radius**3
def sphere_surface_area(radius: float) -> float:
"""Calculate sphere surface area."""
return 4 * PI * radius**2
def degrees_to_radians(degrees: float) -> float:
"""Convert degrees to radians."""
return degrees * PI / 180
def radians_to_degrees(radians: float) -> float:
"""Convert radians to degrees."""
return radians * 180 / PI
def is_finite_value(x: float) -> bool:
"""Check if value is finite (not inf or nan)."""
return math.isfinite(x)
def is_infinite(x: float) -> bool:
"""Check if value is infinite."""
return math.isinf(x)
def is_nan_value(x: float) -> bool:
"""Check if value is NaN."""
return math.isnan(x)
def is_positive_inf(x: float) -> bool:
"""Check if positive infinity."""
return math.isinf(x) and x > 0
def is_negative_inf(x: float) -> bool:
"""Check if negative infinity."""
return math.isinf(x) and x < 0
def safe_divide(a: float, b: float) -> float:
"""Safe division handling division by zero."""
if b == 0:
if a > 0:
return INF
if a < 0:
return NEG_INF
return NAN
return a / b
def safe_log(x: float) -> float:
"""Safe logarithm handling non-positive values."""
if x <= 0:
return NEG_INF
return math.log(x)
def safe_sqrt(x: float) -> float:
"""Safe square root handling negative values."""
if x < 0:
return NAN
return math.sqrt(x)
def clamp(value: float, min_val: float, max_val: float) -> float:
"""Clamp value to range [min_val, max_val]."""
if math.isnan(value):
return NAN
return max(min_val, min(max_val, value))
def lerp(a: float, b: float, t: float) -> float:
"""Linear interpolation between a and b."""
return a + (b - a) * t
def inverse_lerp(a: float, b: float, value: float) -> float:
"""Inverse linear interpolation."""
if a == b:
return 0.0
return (value - a) / (b - a)
def normalize_angle(angle: float) -> float:
"""Normalize angle to [0, 2*pi)."""
while angle < 0:
angle += TAU
while angle >= TAU:
angle -= TAU
return angle
def golden_ratio() -> float:
"""Return golden ratio phi."""
return (1 + math.sqrt(5)) / 2
def euler_mascheroni() -> float:
"""Approximate Euler-Mascheroni constant."""
# Approximation using harmonic series
n = 1000000
h = sum(1 / i for i in range(1, n + 1))
return h - math.log(n)
def main() -> int:
parser = argparse.ArgumentParser(description="Math constants CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# constants
subparsers.add_parser("pi", help="Show pi")
subparsers.add_parser("e", help="Show e")
subparsers.add_parser("tau", help="Show tau")
subparsers.add_parser("inf", help="Show infinity")
subparsers.add_parser("golden", help="Show golden ratio")
# circle
circle_p = subparsers.add_parser("circle", help="Circle calculations")
circle_p.add_argument("radius", type=float)
circle_p.add_argument("--area", action="store_true")
circle_p.add_argument("--circumference", action="store_true")
# sphere
sphere_p = subparsers.add_parser("sphere", help="Sphere calculations")
sphere_p.add_argument("radius", type=float)
sphere_p.add_argument("--volume", action="store_true")
sphere_p.add_argument("--surface", action="store_true")
# convert
conv_p = subparsers.add_parser("convert", help="Angle conversion")
conv_p.add_argument("value", type=float)
conv_p.add_argument("--to-radians", action="store_true")
conv_p.add_argument("--to-degrees", action="store_true")
# check
check_p = subparsers.add_parser("check", help="Check special values")
check_p.add_argument("value", type=float)
args = parser.parse_args()
if args.command == "pi":
print(f"π = {PI}")
elif args.command == "e":
print(f"e = {E}")
elif args.command == "tau":
print(f"τ = {TAU}")
elif args.command == "inf":
print(f"∞ = {INF}")
elif args.command == "golden":
print(f"φ = {golden_ratio()}")
elif args.command == "circle":
if args.area:
print(f"Area: {circle_area(args.radius)}")
if args.circumference:
print(f"Circumference: {circle_circumference(args.radius)}")
if not args.area and not args.circumference:
print(f"Area: {circle_area(args.radius)}")
print(f"Circumference: {circle_circumference(args.radius)}")
elif args.command == "sphere":
if args.volume:
print(f"Volume: {sphere_volume(args.radius)}")
if args.surface:
print(f"Surface area: {sphere_surface_area(args.radius)}")
if not args.volume and not args.surface:
print(f"Volume: {sphere_volume(args.radius)}")
print(f"Surface area: {sphere_surface_area(args.radius)}")
elif args.command == "convert":
if args.to_radians:
print(f"{args.value}° = {degrees_to_radians(args.value)} rad")
elif args.to_degrees:
print(f"{args.value} rad = {radians_to_degrees(args.value)}°")
else:
print(f"{args.value}° = {degrees_to_radians(args.value)} rad")
elif args.command == "check":
print(f"Value: {args.value}")
print(f" is_finite: {is_finite_value(args.value)}")
print(f" is_infinite: {is_infinite(args.value)}")
print(f" is_nan: {is_nan_value(args.value)}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_math_constants/constants_cli.py (6657 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_math_constants/constants_cli.rs (12654 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_math_constants/Cargo.toml (1 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 121.8 KB/s
⏱️ Total time: 53ms
| true
|
math_constants
| 251
| 6
|
[] | 0
| null |
example_math_constants
|
test_constants_cli.py
|
"""Tests for constants_cli.py"""
import math
from constants_cli import (
INF,
NAN,
NEG_INF,
PI,
TAU,
E,
circle_area,
circle_circumference,
clamp,
degrees_to_radians,
euler_mascheroni,
get_e,
get_inf,
get_nan,
get_neg_inf,
get_pi,
get_tau,
golden_ratio,
inverse_lerp,
is_finite_value,
is_infinite,
is_nan_value,
is_negative_inf,
is_positive_inf,
lerp,
normalize_angle,
radians_to_degrees,
safe_divide,
safe_log,
safe_sqrt,
sphere_surface_area,
sphere_volume,
)
class TestConstants:
def test_pi(self):
assert abs(get_pi() - 3.14159265359) < 0.0001
assert PI == math.pi
def test_e(self):
assert abs(get_e() - 2.71828182845) < 0.0001
assert E == math.e
def test_tau(self):
assert abs(get_tau() - 6.28318530718) < 0.0001
assert TAU == math.tau
assert abs(TAU - 2 * PI) < 0.0001
def test_inf(self):
assert get_inf() == float("inf")
assert INF == math.inf
def test_neg_inf(self):
assert get_neg_inf() == float("-inf")
assert NEG_INF == -math.inf
def test_nan(self):
assert math.isnan(get_nan())
assert math.isnan(NAN)
class TestCircle:
def test_circumference(self):
assert abs(circle_circumference(1) - 2 * PI) < 0.0001
assert abs(circle_circumference(2) - 4 * PI) < 0.0001
def test_area(self):
assert abs(circle_area(1) - PI) < 0.0001
assert abs(circle_area(2) - 4 * PI) < 0.0001
class TestSphere:
def test_volume(self):
expected = (4 / 3) * PI * 1**3
assert abs(sphere_volume(1) - expected) < 0.0001
def test_surface_area(self):
expected = 4 * PI * 1**2
assert abs(sphere_surface_area(1) - expected) < 0.0001
class TestAngleConversion:
def test_degrees_to_radians(self):
assert abs(degrees_to_radians(0) - 0) < 0.0001
assert abs(degrees_to_radians(90) - PI / 2) < 0.0001
assert abs(degrees_to_radians(180) - PI) < 0.0001
assert abs(degrees_to_radians(360) - TAU) < 0.0001
def test_radians_to_degrees(self):
assert abs(radians_to_degrees(0) - 0) < 0.0001
assert abs(radians_to_degrees(PI / 2) - 90) < 0.0001
assert abs(radians_to_degrees(PI) - 180) < 0.0001
assert abs(radians_to_degrees(TAU) - 360) < 0.0001
class TestSpecialValueChecks:
def test_is_finite(self):
assert is_finite_value(1.0) is True
assert is_finite_value(0.0) is True
assert is_finite_value(INF) is False
assert is_finite_value(NEG_INF) is False
assert is_finite_value(NAN) is False
def test_is_infinite(self):
assert is_infinite(INF) is True
assert is_infinite(NEG_INF) is True
assert is_infinite(1.0) is False
assert is_infinite(NAN) is False
def test_is_nan(self):
assert is_nan_value(NAN) is True
assert is_nan_value(1.0) is False
assert is_nan_value(INF) is False
def test_is_positive_inf(self):
assert is_positive_inf(INF) is True
assert is_positive_inf(NEG_INF) is False
assert is_positive_inf(1.0) is False
def test_is_negative_inf(self):
assert is_negative_inf(NEG_INF) is True
assert is_negative_inf(INF) is False
assert is_negative_inf(-1.0) is False
class TestSafeFunctions:
def test_safe_divide_normal(self):
assert safe_divide(10, 2) == 5.0
assert safe_divide(-10, 2) == -5.0
def test_safe_divide_by_zero(self):
assert safe_divide(1, 0) == INF
assert safe_divide(-1, 0) == NEG_INF
assert math.isnan(safe_divide(0, 0))
def test_safe_log_positive(self):
assert abs(safe_log(E) - 1.0) < 0.0001
assert abs(safe_log(1) - 0) < 0.0001
def test_safe_log_non_positive(self):
assert safe_log(0) == NEG_INF
assert safe_log(-1) == NEG_INF
def test_safe_sqrt_positive(self):
assert safe_sqrt(4) == 2.0
assert safe_sqrt(0) == 0.0
def test_safe_sqrt_negative(self):
assert math.isnan(safe_sqrt(-1))
class TestClamp:
def test_within_range(self):
assert clamp(5, 0, 10) == 5
def test_below_min(self):
assert clamp(-5, 0, 10) == 0
def test_above_max(self):
assert clamp(15, 0, 10) == 10
def test_at_boundaries(self):
assert clamp(0, 0, 10) == 0
assert clamp(10, 0, 10) == 10
def test_nan_input(self):
assert math.isnan(clamp(NAN, 0, 10))
class TestLerp:
def test_lerp_start(self):
assert lerp(0, 10, 0) == 0
def test_lerp_end(self):
assert lerp(0, 10, 1) == 10
def test_lerp_middle(self):
assert lerp(0, 10, 0.5) == 5
def test_lerp_quarter(self):
assert lerp(0, 100, 0.25) == 25
class TestInverseLerp:
def test_inverse_lerp_start(self):
assert inverse_lerp(0, 10, 0) == 0
def test_inverse_lerp_end(self):
assert inverse_lerp(0, 10, 10) == 1
def test_inverse_lerp_middle(self):
assert inverse_lerp(0, 10, 5) == 0.5
def test_inverse_lerp_same_bounds(self):
assert inverse_lerp(5, 5, 5) == 0
class TestNormalizeAngle:
def test_already_normalized(self):
assert abs(normalize_angle(PI) - PI) < 0.0001
def test_negative(self):
result = normalize_angle(-PI)
assert 0 <= result < TAU
def test_large_positive(self):
result = normalize_angle(3 * TAU + PI)
assert abs(result - PI) < 0.0001
def test_zero(self):
assert normalize_angle(0) == 0
class TestSpecialConstants:
def test_golden_ratio(self):
phi = golden_ratio()
assert abs(phi - 1.6180339887) < 0.0001
# Golden ratio property: phi^2 = phi + 1
assert abs(phi * phi - (phi + 1)) < 0.0001
def test_euler_mascheroni(self):
gamma = euler_mascheroni()
# Known value approximately 0.5772
assert abs(gamma - 0.5772156649) < 0.001
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_math_constants/test_constants_cli.py (6067 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_math_constants/test_constants_cli.rs (15762 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 110.0 KB/s
⏱️ Total time: 54ms
| true
|
math_constants
| 230
| 5
|
[
"class_definition",
"stdin_usage"
] | 0.612
| null |
example_math_special
|
special_cli.py
|
#!/usr/bin/env python3
"""Math Special Functions CLI.
Special mathematical functions from math module.
"""
import argparse
import math
import sys
def hypot(*args: float) -> float:
"""Euclidean norm (distance from origin)."""
return math.hypot(*args)
def dist(p: list[float], q: list[float]) -> float:
"""Euclidean distance between two points."""
return math.dist(p, q)
def degrees(x: float) -> float:
"""Convert radians to degrees."""
return math.degrees(x)
def radians(x: float) -> float:
"""Convert degrees to radians."""
return math.radians(x)
def prod(iterable: list[float], start: float = 1.0) -> float:
"""Product of all elements."""
return math.prod(iterable, start=start)
def fsum(iterable: list[float]) -> float:
"""Accurate floating point sum."""
return math.fsum(iterable)
def sumprod(p: list[float], q: list[float]) -> float:
"""Sum of products of two sequences."""
# Python 3.12+ has math.sumprod, fallback for earlier versions
return sum(a * b for a, b in zip(p, q, strict=False))
def nextafter(x: float, y: float) -> float:
"""Next float after x toward y."""
return math.nextafter(x, y)
def ulp(x: float) -> float:
"""Unit in the last place."""
return math.ulp(x)
def comb(n: int, k: int) -> int:
"""Number of combinations (n choose k)."""
return math.comb(n, k)
def perm(n: int, k: int | None = None) -> int:
"""Number of permutations."""
if k is None:
return math.perm(n)
return math.perm(n, k)
def erf(x: float) -> float:
"""Error function."""
return math.erf(x)
def erfc(x: float) -> float:
"""Complementary error function."""
return math.erfc(x)
def gamma_fn(x: float) -> float:
"""Gamma function."""
return math.gamma(x)
def lgamma(x: float) -> float:
"""Natural log of gamma function."""
return math.lgamma(x)
def expm1(x: float) -> float:
"""exp(x) - 1, accurate for small x."""
return math.expm1(x)
def log1p(x: float) -> float:
"""log(1 + x), accurate for small x."""
return math.log1p(x)
def asinh(x: float) -> float:
"""Inverse hyperbolic sine."""
return math.asinh(x)
def acosh(x: float) -> float:
"""Inverse hyperbolic cosine."""
return math.acosh(x)
def atanh(x: float) -> float:
"""Inverse hyperbolic tangent."""
return math.atanh(x)
def cbrt(x: float) -> float:
"""Cube root."""
# Python 3.12+ has math.cbrt, fallback for earlier versions
if x >= 0:
return x ** (1 / 3)
return -((-x) ** (1 / 3))
def exp2(x: float) -> float:
"""2 raised to power x."""
# Python 3.12+ has math.exp2, fallback for earlier versions
return 2.0**x
def binomial_coefficient(n: int, k: int) -> int:
"""Calculate binomial coefficient using comb."""
return comb(n, k)
def triangle_area(a: float, b: float, c: float) -> float:
"""Calculate triangle area using Heron's formula."""
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def distance_3d(x1: float, y1: float, z1: float, x2: float, y2: float, z2: float) -> float:
"""3D Euclidean distance."""
return dist([x1, y1, z1], [x2, y2, z2])
def vector_length(*components: float) -> float:
"""Length of n-dimensional vector."""
return hypot(*components)
def normal_cdf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""Cumulative distribution function of normal distribution."""
return 0.5 * (1 + erf((x - mu) / (sigma * math.sqrt(2))))
def normal_pdf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""Probability density function of normal distribution."""
return (1 / (sigma * math.sqrt(2 * math.pi))) * math.exp(-0.5 * ((x - mu) / sigma) ** 2)
def sigmoid(x: float) -> float:
"""Sigmoid function."""
return 1 / (1 + math.exp(-x))
def softplus(x: float) -> float:
"""Softplus function (smooth ReLU)."""
return math.log1p(math.exp(x))
def main() -> int:
parser = argparse.ArgumentParser(description="Special math functions CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# hypot
hypot_p = subparsers.add_parser("hypot", help="Euclidean norm")
hypot_p.add_argument("values", type=float, nargs="+")
# dist
dist_p = subparsers.add_parser("dist", help="Distance between points")
dist_p.add_argument("--p1", type=float, nargs="+", required=True)
dist_p.add_argument("--p2", type=float, nargs="+", required=True)
# degrees
deg_p = subparsers.add_parser("degrees", help="Radians to degrees")
deg_p.add_argument("radians", type=float)
# radians
rad_p = subparsers.add_parser("radians", help="Degrees to radians")
rad_p.add_argument("degrees", type=float)
# prod
prod_p = subparsers.add_parser("prod", help="Product of values")
prod_p.add_argument("values", type=float, nargs="+")
# comb
comb_p = subparsers.add_parser("comb", help="Combinations")
comb_p.add_argument("n", type=int)
comb_p.add_argument("k", type=int)
# perm
perm_p = subparsers.add_parser("perm", help="Permutations")
perm_p.add_argument("n", type=int)
perm_p.add_argument("k", type=int, nargs="?")
# triangle
tri_p = subparsers.add_parser("triangle", help="Triangle area")
tri_p.add_argument("a", type=float)
tri_p.add_argument("b", type=float)
tri_p.add_argument("c", type=float)
# sigmoid
sig_p = subparsers.add_parser("sigmoid", help="Sigmoid function")
sig_p.add_argument("x", type=float)
# normal
norm_p = subparsers.add_parser("normal", help="Normal distribution")
norm_p.add_argument("x", type=float)
norm_p.add_argument("--mu", type=float, default=0.0)
norm_p.add_argument("--sigma", type=float, default=1.0)
norm_p.add_argument("--cdf", action="store_true")
args = parser.parse_args()
if args.command == "hypot":
print(hypot(*args.values))
elif args.command == "dist":
print(dist(args.p1, args.p2))
elif args.command == "degrees":
print(degrees(args.radians))
elif args.command == "radians":
print(radians(args.degrees))
elif args.command == "prod":
print(prod(args.values))
elif args.command == "comb":
print(comb(args.n, args.k))
elif args.command == "perm":
print(perm(args.n, args.k))
elif args.command == "triangle":
print(triangle_area(args.a, args.b, args.c))
elif args.command == "sigmoid":
print(sigmoid(args.x))
elif args.command == "normal":
if args.cdf:
print(normal_cdf(args.x, args.mu, args.sigma))
else:
print(normal_pdf(args.x, args.mu, args.sigma))
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
math_special
| 254
| 0
|
[] | 0
|
Type inference hints:
Hint: int for variable 'a' [Medium] (usage patterns suggest this type)
Hint: int for variable 's' [High] (usage patterns suggest this type)
Hint: int for variable 'b' [Medium] (usage patterns suggest this type)
Hint: int for variable 'c' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'mu' [Medium] (usage patterns suggest this type)
Hint: int for variable 'sigma' [Medium] (usage patterns suggest this type)
Hint: int for variable 'x'
|
|
example_math_special
|
test_special_cli.py
|
"""Tests for special_cli.py"""
import math
from special_cli import (
acosh,
asinh,
atanh,
binomial_coefficient,
cbrt,
comb,
degrees,
dist,
distance_3d,
erf,
erfc,
exp2,
expm1,
fsum,
gamma_fn,
hypot,
lgamma,
log1p,
nextafter,
normal_cdf,
normal_pdf,
perm,
prod,
radians,
sigmoid,
softplus,
sumprod,
triangle_area,
ulp,
vector_length,
)
class TestHypotDist:
def test_hypot_2d(self):
assert abs(hypot(3, 4) - 5.0) < 0.0001
def test_hypot_3d(self):
assert abs(hypot(2, 3, 6) - 7.0) < 0.0001
def test_dist_2d(self):
assert abs(dist([0, 0], [3, 4]) - 5.0) < 0.0001
def test_dist_3d(self):
assert abs(dist([0, 0, 0], [1, 2, 2]) - 3.0) < 0.0001
def test_distance_3d_fn(self):
assert abs(distance_3d(0, 0, 0, 1, 2, 2) - 3.0) < 0.0001
def test_vector_length(self):
assert abs(vector_length(3, 4) - 5.0) < 0.0001
assert abs(vector_length(1, 2, 2) - 3.0) < 0.0001
class TestAngleConversion:
def test_degrees(self):
assert abs(degrees(math.pi) - 180.0) < 0.0001
assert abs(degrees(math.pi / 2) - 90.0) < 0.0001
def test_radians(self):
assert abs(radians(180) - math.pi) < 0.0001
assert abs(radians(90) - math.pi / 2) < 0.0001
class TestAggregations:
def test_prod(self):
assert prod([1, 2, 3, 4]) == 24
assert prod([2, 3], start=2) == 12
def test_fsum(self):
# fsum is more accurate than sum for floats
values = [0.1] * 10
assert abs(fsum(values) - 1.0) < 0.0001
def test_sumprod(self):
assert sumprod([1, 2, 3], [4, 5, 6]) == 32 # 1*4 + 2*5 + 3*6
class TestCombPerm:
def test_comb(self):
assert comb(5, 2) == 10
assert comb(10, 3) == 120
assert comb(5, 0) == 1
assert comb(5, 5) == 1
def test_perm(self):
assert perm(5, 2) == 20
assert perm(5) == 120 # 5!
assert perm(5, 5) == 120
def test_binomial_coefficient(self):
assert binomial_coefficient(5, 2) == 10
assert binomial_coefficient(10, 5) == 252
class TestSpecialFunctions:
def test_erf(self):
assert abs(erf(0) - 0) < 0.0001
assert abs(erf(1) - 0.8427) < 0.001
def test_erfc(self):
assert abs(erfc(0) - 1) < 0.0001
assert abs(erf(1) + erfc(1) - 1) < 0.0001
def test_gamma(self):
assert abs(gamma_fn(1) - 1) < 0.0001
assert abs(gamma_fn(5) - 24) < 0.0001 # (n-1)!
def test_lgamma(self):
assert abs(lgamma(1) - 0) < 0.0001
assert abs(lgamma(5) - math.log(24)) < 0.0001
class TestAccurateFunctions:
def test_expm1(self):
# More accurate than exp(x) - 1 for small x
assert abs(expm1(0) - 0) < 0.0001
assert abs(expm1(1e-10) - 1e-10) < 1e-15
def test_log1p(self):
# More accurate than log(1 + x) for small x
assert abs(log1p(0) - 0) < 0.0001
assert abs(log1p(1e-10) - 1e-10) < 1e-15
class TestInverseHyperbolic:
def test_asinh(self):
assert abs(asinh(0) - 0) < 0.0001
x = 1.5
assert abs(math.sinh(asinh(x)) - x) < 0.0001
def test_acosh(self):
assert abs(acosh(1) - 0) < 0.0001
x = 2.0
assert abs(math.cosh(acosh(x)) - x) < 0.0001
def test_atanh(self):
assert abs(atanh(0) - 0) < 0.0001
x = 0.5
assert abs(math.tanh(atanh(x)) - x) < 0.0001
class TestOtherFunctions:
def test_cbrt(self):
assert abs(cbrt(8) - 2.0) < 0.0001
assert abs(cbrt(27) - 3.0) < 0.0001
assert abs(cbrt(-8) - (-2.0)) < 0.0001
def test_exp2(self):
assert exp2(0) == 1.0
assert exp2(3) == 8.0
assert exp2(10) == 1024.0
def test_nextafter(self):
x = 1.0
next_x = nextafter(x, 2.0)
assert next_x > x
assert next_x - x == ulp(x)
def test_ulp(self):
assert ulp(1.0) > 0
assert ulp(1.0) < 1e-10
class TestTriangle:
def test_right_triangle(self):
# 3-4-5 right triangle
area = triangle_area(3, 4, 5)
assert abs(area - 6.0) < 0.0001
def test_equilateral(self):
# Equilateral triangle with side 2
area = triangle_area(2, 2, 2)
expected = math.sqrt(3) # sqrt(3) for side 2
assert abs(area - expected) < 0.0001
class TestDistributions:
def test_normal_pdf_standard(self):
# Standard normal at x=0
pdf = normal_pdf(0)
expected = 1 / math.sqrt(2 * math.pi)
assert abs(pdf - expected) < 0.0001
def test_normal_cdf_standard(self):
assert abs(normal_cdf(0) - 0.5) < 0.0001
assert normal_cdf(10) > 0.99
assert normal_cdf(-10) < 0.01
def test_normal_cdf_custom(self):
# CDF at mean should be 0.5
assert abs(normal_cdf(100, mu=100, sigma=15) - 0.5) < 0.0001
class TestActivations:
def test_sigmoid(self):
assert abs(sigmoid(0) - 0.5) < 0.0001
assert sigmoid(10) > 0.99
assert sigmoid(-10) < 0.01
def test_softplus(self):
assert softplus(0) > 0
# For large x, softplus(x) ≈ x
assert abs(softplus(10) - 10) < 0.001
# For very negative x, softplus(x) ≈ 0
assert softplus(-10) < 0.001
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_math_special/test_special_cli.py (5360 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_math_special/test_special_cli.rs (13992 bytes)
⏱️ Parse time: 54ms
📊 Throughput: 95.7 KB/s
⏱️ Total time: 54ms
| true
|
math_special
| 211
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_matrix_ops
|
matrix_cli.py
|
#!/usr/bin/env python3
"""Matrix Operations CLI.
Pure Python matrix operations without external dependencies.
"""
import argparse
import sys
from typing import TypeAlias
Matrix: TypeAlias = list[list[float]]
Vector: TypeAlias = list[float]
def zeros(rows: int, cols: int) -> Matrix:
"""Create zero matrix."""
return [[0.0] * cols for _ in range(rows)]
def ones(rows: int, cols: int) -> Matrix:
"""Create matrix of ones."""
return [[1.0] * cols for _ in range(rows)]
def identity(n: int) -> Matrix:
"""Create identity matrix."""
result = zeros(n, n)
for i in range(n):
result[i][i] = 1.0
return result
def shape(m: Matrix) -> tuple[int, int]:
"""Get matrix dimensions."""
if not m:
return 0, 0
return len(m), len(m[0])
def transpose(m: Matrix) -> Matrix:
"""Transpose matrix."""
if not m:
return []
rows, cols = shape(m)
return [[m[i][j] for i in range(rows)] for j in range(cols)]
def add(a: Matrix, b: Matrix) -> Matrix:
"""Add two matrices."""
rows_a, cols_a = shape(a)
rows_b, cols_b = shape(b)
if rows_a != rows_b or cols_a != cols_b:
raise ValueError("Matrix dimensions must match")
return [[a[i][j] + b[i][j] for j in range(cols_a)] for i in range(rows_a)]
def subtract(a: Matrix, b: Matrix) -> Matrix:
"""Subtract matrix b from a."""
rows_a, cols_a = shape(a)
rows_b, cols_b = shape(b)
if rows_a != rows_b or cols_a != cols_b:
raise ValueError("Matrix dimensions must match")
return [[a[i][j] - b[i][j] for j in range(cols_a)] for i in range(rows_a)]
def scalar_multiply(m: Matrix, scalar: float) -> Matrix:
"""Multiply matrix by scalar."""
rows, cols = shape(m)
return [[m[i][j] * scalar for j in range(cols)] for i in range(rows)]
def multiply(a: Matrix, b: Matrix) -> Matrix:
"""Multiply two matrices."""
rows_a, cols_a = shape(a)
rows_b, cols_b = shape(b)
if cols_a != rows_b:
raise ValueError(f"Cannot multiply {rows_a}x{cols_a} by {rows_b}x{cols_b}")
result = zeros(rows_a, cols_b)
for i in range(rows_a):
for j in range(cols_b):
total = 0.0
for k in range(cols_a):
total += a[i][k] * b[k][j]
result[i][j] = total
return result
def hadamard(a: Matrix, b: Matrix) -> Matrix:
"""Element-wise multiplication."""
rows_a, cols_a = shape(a)
rows_b, cols_b = shape(b)
if rows_a != rows_b or cols_a != cols_b:
raise ValueError("Matrix dimensions must match")
return [[a[i][j] * b[i][j] for j in range(cols_a)] for i in range(rows_a)]
def dot_product(a: Vector, b: Vector) -> float:
"""Vector dot product."""
if len(a) != len(b):
raise ValueError("Vector dimensions must match")
return sum(a[i] * b[i] for i in range(len(a)))
def matrix_vector_multiply(m: Matrix, v: Vector) -> Vector:
"""Multiply matrix by vector."""
rows, cols = shape(m)
if cols != len(v):
raise ValueError("Matrix columns must match vector length")
return [sum(m[i][j] * v[j] for j in range(cols)) for i in range(rows)]
def trace(m: Matrix) -> float:
"""Calculate matrix trace (sum of diagonal)."""
rows, cols = shape(m)
if rows != cols:
raise ValueError("Matrix must be square")
return sum(m[i][i] for i in range(rows))
def determinant(m: Matrix) -> float:
"""Calculate determinant using LU decomposition."""
rows, cols = shape(m)
if rows != cols:
raise ValueError("Matrix must be square")
n = rows
# Create a copy
lu = [row[:] for row in m]
det = 1.0
for i in range(n):
# Find pivot
max_row = i
for k in range(i + 1, n):
if abs(lu[k][i]) > abs(lu[max_row][i]):
max_row = k
if abs(lu[max_row][i]) < 1e-10:
return 0.0
if max_row != i:
lu[i], lu[max_row] = lu[max_row], lu[i]
det *= -1
det *= lu[i][i]
for k in range(i + 1, n):
factor = lu[k][i] / lu[i][i]
for j in range(i, n):
lu[k][j] -= factor * lu[i][j]
return det
def minor(m: Matrix, row: int, col: int) -> Matrix:
"""Get minor matrix (removing row and column)."""
return [[m[i][j] for j in range(len(m[0])) if j != col] for i in range(len(m)) if i != row]
def cofactor(m: Matrix) -> Matrix:
"""Calculate cofactor matrix."""
rows, cols = shape(m)
result = zeros(rows, cols)
for i in range(rows):
for j in range(cols):
sign = (-1) ** (i + j)
result[i][j] = sign * determinant(minor(m, i, j))
return result
def adjoint(m: Matrix) -> Matrix:
"""Calculate adjoint (adjugate) matrix."""
return transpose(cofactor(m))
def inverse(m: Matrix) -> Matrix:
"""Calculate matrix inverse."""
det = determinant(m)
if abs(det) < 1e-10:
raise ValueError("Matrix is singular")
adj = adjoint(m)
return scalar_multiply(adj, 1.0 / det)
def lu_decomposition(m: Matrix) -> tuple[Matrix, Matrix]:
"""LU decomposition."""
rows, cols = shape(m)
if rows != cols:
raise ValueError("Matrix must be square")
n = rows
L = identity(n)
U = [row[:] for row in m]
for i in range(n):
for k in range(i + 1, n):
if abs(U[i][i]) < 1e-10:
raise ValueError("Zero pivot encountered")
factor = U[k][i] / U[i][i]
L[k][i] = factor
for j in range(i, n):
U[k][j] -= factor * U[i][j]
return L, U
def frobenius_norm(m: Matrix) -> float:
"""Calculate Frobenius norm."""
rows, cols = shape(m)
total = 0.0
for i in range(rows):
for j in range(cols):
total += m[i][j] ** 2
return total**0.5
def max_norm(m: Matrix) -> float:
"""Calculate max (infinity) norm."""
rows, cols = shape(m)
max_val = 0.0
for i in range(rows):
for j in range(cols):
max_val = max(max_val, abs(m[i][j]))
return max_val
def row_echelon(m: Matrix) -> Matrix:
"""Convert to row echelon form."""
rows, cols = shape(m)
result = [row[:] for row in m]
lead = 0
for r in range(rows):
if lead >= cols:
break
i = r
while abs(result[i][lead]) < 1e-10:
i += 1
if i == rows:
i = r
lead += 1
if lead == cols:
return result
result[i], result[r] = result[r], result[i]
div = result[r][lead]
if abs(div) > 1e-10:
result[r] = [x / div for x in result[r]]
for i in range(rows):
if i != r:
mult = result[i][lead]
result[i] = [result[i][j] - mult * result[r][j] for j in range(cols)]
lead += 1
return result
def rank(m: Matrix) -> int:
"""Calculate matrix rank."""
ref = row_echelon(m)
rows, cols = shape(ref)
r = 0
for i in range(rows):
is_zero = all(abs(ref[i][j]) < 1e-10 for j in range(cols))
if not is_zero:
r += 1
return r
def format_matrix(m: Matrix, precision: int = 2) -> str:
"""Format matrix for display."""
rows, cols = shape(m)
lines = []
for i in range(rows):
row_str = " ".join(f"{m[i][j]:>{precision + 6}.{precision}f}" for j in range(cols))
lines.append(f"[ {row_str} ]")
return "\n".join(lines)
def parse_matrix(s: str) -> Matrix:
"""Parse matrix from string format."""
rows = s.strip().split(";")
return [[float(x) for x in row.split(",")] for row in rows]
def main() -> int:
parser = argparse.ArgumentParser(description="Matrix operations")
parser.add_argument(
"--mode",
choices=[
"add",
"mult",
"det",
"inv",
"trans",
"trace",
"rank",
"lu",
"identity",
"demo",
],
default="demo",
help="Operation mode",
)
parser.add_argument("--a", help="Matrix A (format: '1,2;3,4')")
parser.add_argument("--b", help="Matrix B")
parser.add_argument("--n", type=int, default=3, help="Size for identity matrix")
args = parser.parse_args()
if args.mode == "identity":
m = identity(args.n)
print(f"Identity matrix ({args.n}x{args.n}):")
print(format_matrix(m))
elif args.mode == "demo":
print("Matrix Operations Demo\n")
A = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
print("Matrix A:")
print(format_matrix(A))
print(f"\nDeterminant: {determinant(A):.2f}")
print(f"Trace: {trace(A):.2f}")
print(f"Rank: {rank(A)}")
print(f"Frobenius Norm: {frobenius_norm(A):.4f}")
print("\nTranspose:")
print(format_matrix(transpose(A)))
print("\nInverse:")
print(format_matrix(inverse(A)))
print("\nA * A^-1 (should be identity):")
print(format_matrix(multiply(A, inverse(A))))
elif args.a:
A = parse_matrix(args.a)
if args.mode == "det":
print(f"Determinant: {determinant(A):.6f}")
elif args.mode == "inv":
print("Inverse:")
print(format_matrix(inverse(A)))
elif args.mode == "trans":
print("Transpose:")
print(format_matrix(transpose(A)))
elif args.mode == "trace":
print(f"Trace: {trace(A):.6f}")
elif args.mode == "rank":
print(f"Rank: {rank(A)}")
elif args.mode == "lu":
L, U = lu_decomposition(A)
print("L:")
print(format_matrix(L))
print("\nU:")
print(format_matrix(U))
elif args.mode == "add" and args.b:
B = parse_matrix(args.b)
print("A + B:")
print(format_matrix(add(A, B)))
elif args.mode == "mult" and args.b:
B = parse_matrix(args.b)
print("A * B:")
print(format_matrix(multiply(A, B)))
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_matrix_ops/matrix_cli.py (10212 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_matrix_ops/matrix_cli.rs (31128 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_matrix_ops/Cargo.toml (1 dependencies)
⏱️ Parse time: 64ms
📊 Throughput: 154.6 KB/s
⏱️ Total time: 65ms
| true
|
matrix_ops
| 405
| 6
|
[
"exception_handling"
] | 0.577
| null |
example_matrix_ops
|
test_matrix_cli.py
|
"""Tests for matrix_cli.py"""
import pytest
from matrix_cli import (
add,
adjoint,
cofactor,
determinant,
dot_product,
frobenius_norm,
hadamard,
identity,
inverse,
lu_decomposition,
matrix_vector_multiply,
max_norm,
minor,
multiply,
ones,
rank,
row_echelon,
scalar_multiply,
shape,
subtract,
trace,
transpose,
zeros,
)
class TestMatrixCreation:
def test_zeros(self):
m = zeros(2, 3)
assert shape(m) == (2, 3)
assert all(m[i][j] == 0 for i in range(2) for j in range(3))
def test_ones(self):
m = ones(2, 3)
assert shape(m) == (2, 3)
assert all(m[i][j] == 1 for i in range(2) for j in range(3))
def test_identity(self):
m = identity(3)
assert shape(m) == (3, 3)
for i in range(3):
for j in range(3):
assert m[i][j] == (1.0 if i == j else 0.0)
class TestShape:
def test_regular(self):
m = [[1, 2, 3], [4, 5, 6]]
assert shape(m) == (2, 3)
def test_empty(self):
assert shape([]) == (0, 0)
def test_single(self):
assert shape([[1]]) == (1, 1)
class TestTranspose:
def test_square(self):
m = [[1, 2], [3, 4]]
result = transpose(m)
assert result == [[1, 3], [2, 4]]
def test_rectangular(self):
m = [[1, 2, 3], [4, 5, 6]]
result = transpose(m)
assert shape(result) == (3, 2)
assert result == [[1, 4], [2, 5], [3, 6]]
def test_empty(self):
assert transpose([]) == []
class TestAdd:
def test_basic(self):
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
result = add(a, b)
assert result == [[6, 8], [10, 12]]
def test_dimension_mismatch(self):
a = [[1, 2]]
b = [[1, 2], [3, 4]]
with pytest.raises(ValueError):
add(a, b)
class TestSubtract:
def test_basic(self):
a = [[5, 6], [7, 8]]
b = [[1, 2], [3, 4]]
result = subtract(a, b)
assert result == [[4, 4], [4, 4]]
class TestScalarMultiply:
def test_basic(self):
m = [[1, 2], [3, 4]]
result = scalar_multiply(m, 2)
assert result == [[2, 4], [6, 8]]
def test_zero(self):
m = [[1, 2], [3, 4]]
result = scalar_multiply(m, 0)
assert result == [[0, 0], [0, 0]]
class TestMultiply:
def test_square(self):
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
result = multiply(a, b)
assert result == [[19, 22], [43, 50]]
def test_identity(self):
a = [[1, 2], [3, 4]]
I = identity(2)
result = multiply(a, I)
assert result == a
def test_rectangular(self):
a = [[1, 2, 3], [4, 5, 6]] # 2x3
b = [[1, 2], [3, 4], [5, 6]] # 3x2
result = multiply(a, b)
assert shape(result) == (2, 2)
def test_dimension_mismatch(self):
a = [[1, 2]]
b = [[1, 2]]
with pytest.raises(ValueError):
multiply(a, b)
class TestHadamard:
def test_basic(self):
a = [[1, 2], [3, 4]]
b = [[2, 3], [4, 5]]
result = hadamard(a, b)
assert result == [[2, 6], [12, 20]]
class TestDotProduct:
def test_basic(self):
a = [1, 2, 3]
b = [4, 5, 6]
assert dot_product(a, b) == 32 # 4 + 10 + 18
def test_dimension_mismatch(self):
with pytest.raises(ValueError):
dot_product([1, 2], [1, 2, 3])
class TestMatrixVectorMultiply:
def test_basic(self):
m = [[1, 2], [3, 4]]
v = [1, 2]
result = matrix_vector_multiply(m, v)
assert result == [5, 11] # [1+4, 3+8]
class TestTrace:
def test_basic(self):
m = [[1, 2], [3, 4]]
assert trace(m) == 5 # 1 + 4
def test_identity(self):
m = identity(3)
assert trace(m) == 3
def test_non_square(self):
m = [[1, 2, 3], [4, 5, 6]]
with pytest.raises(ValueError):
trace(m)
class TestDeterminant:
def test_2x2(self):
m = [[1, 2], [3, 4]]
assert determinant(m) == pytest.approx(-2, abs=0.01)
def test_3x3(self):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
assert determinant(m) == pytest.approx(-3, abs=0.01)
def test_identity(self):
assert determinant(identity(3)) == pytest.approx(1, abs=0.01)
def test_singular(self):
m = [[1, 2], [2, 4]] # Rows are multiples
assert determinant(m) == pytest.approx(0, abs=0.01)
class TestMinor:
def test_basic(self):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = minor(m, 0, 0)
assert result == [[5, 6], [8, 9]]
class TestCofactor:
def test_2x2(self):
m = [[1, 2], [3, 4]]
result = cofactor(m)
assert result[0][0] == pytest.approx(4)
assert result[0][1] == pytest.approx(-3)
class TestAdjoint:
def test_2x2(self):
m = [[1, 2], [3, 4]]
result = adjoint(m)
assert result[0][0] == pytest.approx(4)
assert result[0][1] == pytest.approx(-2)
class TestInverse:
def test_2x2(self):
m = [[1, 2], [3, 4]]
inv = inverse(m)
# A * A^-1 = I
result = multiply(m, inv)
assert result[0][0] == pytest.approx(1, abs=0.01)
assert result[0][1] == pytest.approx(0, abs=0.01)
def test_3x3(self):
m = [[1, 2, 3], [0, 1, 4], [5, 6, 0]]
inv = inverse(m)
result = multiply(m, inv)
for i in range(3):
for j in range(3):
expected = 1.0 if i == j else 0.0
assert result[i][j] == pytest.approx(expected, abs=0.01)
def test_singular(self):
m = [[1, 2], [2, 4]]
with pytest.raises(ValueError):
inverse(m)
class TestLUDecomposition:
def test_basic(self):
m = [[2, 1], [4, 3]]
L, U = lu_decomposition(m)
# L * U = A
result = multiply(L, U)
assert result[0][0] == pytest.approx(m[0][0], abs=0.01)
# L should be lower triangular
assert L[0][1] == pytest.approx(0, abs=0.01)
# U should be upper triangular
assert U[1][0] == pytest.approx(0, abs=0.01)
class TestNorms:
def test_frobenius(self):
m = [[1, 2], [3, 4]]
# sqrt(1 + 4 + 9 + 16) = sqrt(30)
assert frobenius_norm(m) == pytest.approx(30**0.5, abs=0.01)
def test_max(self):
m = [[1, -5], [3, 4]]
assert max_norm(m) == 5
class TestRowEchelon:
def test_basic(self):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = row_echelon(m)
# First row should have leading 1
assert result[0][0] == pytest.approx(1, abs=0.01)
class TestRank:
def test_full_rank(self):
m = [[1, 2], [3, 4]]
assert rank(m) == 2
def test_rank_deficient(self):
m = [[1, 2], [2, 4]] # Second row is multiple of first
assert rank(m) == 1
def test_identity(self):
assert rank(identity(3)) == 3
def test_rectangular(self):
m = [[1, 2, 3], [4, 5, 6]]
assert rank(m) == 2
| false
|
matrix_ops
| 296
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Index { base: Index { base: Var("m"), index: Var("i") }, index: Var("j") }, right: Literal(Int(0)) }, generators: [HirComprehension { target: "i", iter: Call { func: "range", args: [Literal(Int(2))], kwargs: [] }, conditions: [] }, HirComprehension { target: "j", iter: Call { func: "range", args: [Literal(Int(3))], kwargs: [] }, conditions: [] }] }
|
|
example_mem_arena
|
mem_arena_cli.py
|
"""Arena Allocator CLI.
Demonstrates arena/bump allocation for fast memory management.
"""
import sys
from dataclasses import dataclass
from typing import Generic, TypeVar
T = TypeVar("T")
@dataclass
class ArenaStats:
"""Arena statistics."""
total_allocated: int = 0
total_deallocated: int = 0
current_offset: int = 0
capacity: int = 0
allocation_count: int = 0
class Arena:
"""Simple arena allocator with bump allocation."""
def __init__(self, capacity: int = 4096) -> None:
self._buffer = bytearray(capacity)
self._offset = 0
self._capacity = capacity
self._allocation_count = 0
self._total_allocated = 0
def alloc(self, size: int, align: int = 8) -> int:
"""Allocate memory from arena. Returns offset."""
# Align offset
aligned_offset = (self._offset + align - 1) & ~(align - 1)
if aligned_offset + size > self._capacity:
raise MemoryError(
f"Arena exhausted: need {size}, have {self._capacity - aligned_offset}"
)
result = aligned_offset
self._offset = aligned_offset + size
self._allocation_count += 1
self._total_allocated += size
return result
def alloc_bytes(self, data: bytes) -> int:
"""Allocate and copy bytes to arena."""
offset = self.alloc(len(data), align=1)
self._buffer[offset : offset + len(data)] = data
return offset
def get_bytes(self, offset: int, size: int) -> bytes:
"""Get bytes from arena at offset."""
return bytes(self._buffer[offset : offset + size])
def reset(self) -> None:
"""Reset arena without freeing memory."""
self._offset = 0
self._allocation_count = 0
self._total_allocated = 0
def stats(self) -> ArenaStats:
"""Get arena statistics."""
return ArenaStats(
total_allocated=self._total_allocated,
total_deallocated=0, # Arena doesn't deallocate
current_offset=self._offset,
capacity=self._capacity,
allocation_count=self._allocation_count,
)
def used(self) -> int:
"""Get used bytes."""
return self._offset
def available(self) -> int:
"""Get available bytes."""
return self._capacity - self._offset
@dataclass
class ArenaObject(Generic[T]):
"""Object allocated in arena."""
arena: Arena
offset: int
size: int
value: T
class TypedArena(Generic[T]):
"""Arena for objects of a specific type."""
def __init__(self, capacity: int = 4096, obj_size: int = 64) -> None:
self._arena = Arena(capacity)
self._obj_size = obj_size
self._objects: list[ArenaObject[T]] = []
def alloc(self, value: T) -> ArenaObject[T]:
"""Allocate and store an object."""
offset = self._arena.alloc(self._obj_size)
obj = ArenaObject(self._arena, offset, self._obj_size, value)
self._objects.append(obj)
return obj
def reset(self) -> None:
"""Reset arena and all objects."""
self._arena.reset()
self._objects.clear()
def count(self) -> int:
"""Get number of allocated objects."""
return len(self._objects)
def stats(self) -> ArenaStats:
"""Get arena statistics."""
return self._arena.stats()
class StringArena:
"""Specialized arena for string interning."""
def __init__(self, capacity: int = 65536) -> None:
self._arena = Arena(capacity)
self._strings: dict[str, int] = {}
self._offsets: dict[int, tuple[int, str]] = {}
def intern(self, s: str) -> int:
"""Intern a string, returning its offset."""
if s in self._strings:
return self._strings[s]
data = s.encode("utf-8")
# Store length prefix + data
size_bytes = len(data).to_bytes(4, "little")
offset = self._arena.alloc_bytes(size_bytes + data)
self._strings[s] = offset
self._offsets[offset] = (len(data), s)
return offset
def get(self, offset: int) -> str:
"""Get interned string by offset."""
if offset in self._offsets:
return self._offsets[offset][1]
# Read length and data
size_bytes = self._arena.get_bytes(offset, 4)
size = int.from_bytes(size_bytes, "little")
data = self._arena.get_bytes(offset + 4, size)
return data.decode("utf-8")
def count(self) -> int:
"""Get number of interned strings."""
return len(self._strings)
def reset(self) -> None:
"""Reset arena."""
self._arena.reset()
self._strings.clear()
self._offsets.clear()
class ChunkedArena:
"""Arena that grows by allocating chunks."""
def __init__(self, chunk_size: int = 4096) -> None:
self._chunk_size = chunk_size
self._chunks: list[Arena] = [Arena(chunk_size)]
self._current_chunk = 0
def alloc(self, size: int, align: int = 8) -> tuple[int, int]:
"""Allocate. Returns (chunk_index, offset)."""
try:
offset = self._chunks[self._current_chunk].alloc(size, align)
return self._current_chunk, offset
except MemoryError:
# Allocate new chunk
new_chunk = Arena(max(self._chunk_size, size + align))
self._chunks.append(new_chunk)
self._current_chunk = len(self._chunks) - 1
offset = new_chunk.alloc(size, align)
return self._current_chunk, offset
def reset(self) -> None:
"""Reset all chunks."""
for chunk in self._chunks:
chunk.reset()
self._current_chunk = 0
def chunk_count(self) -> int:
"""Get number of chunks."""
return len(self._chunks)
def total_capacity(self) -> int:
"""Get total capacity across chunks."""
return sum(c._capacity for c in self._chunks)
def total_used(self) -> int:
"""Get total used across chunks."""
return sum(c.used() for c in self._chunks)
def simulate_arena(operations: list[str]) -> list[str]:
"""Simulate arena operations."""
results: list[str] = []
arena = Arena(1024)
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "alloc":
size = int(parts[1])
try:
offset = arena.alloc(size)
results.append(f"offset={offset}")
except MemoryError as e:
results.append(f"error:{e}")
elif cmd == "alloc_bytes":
data = parts[1].encode()
offset = arena.alloc_bytes(data)
results.append(f"offset={offset}")
elif cmd == "get_bytes":
offset, size = map(int, parts[1].split(","))
data = arena.get_bytes(offset, size)
results.append(data.decode())
elif cmd == "reset":
arena.reset()
results.append("reset")
elif cmd == "used":
results.append(str(arena.used()))
elif cmd == "available":
results.append(str(arena.available()))
elif cmd == "stats":
s = arena.stats()
results.append(f"allocated={s.total_allocated} count={s.allocation_count}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: mem_arena_cli.py <command> [args]")
return 1
cmd = sys.argv[1]
if cmd == "demo":
arena = Arena(1024)
offset1 = arena.alloc(64)
offset2 = arena.alloc(128)
print(f"Allocated at offsets: {offset1}, {offset2}")
print(f"Used: {arena.used()}, Available: {arena.available()}")
strings = StringArena()
s1 = strings.intern("hello")
s2 = strings.intern("world")
s3 = strings.intern("hello") # Reuses existing
print(f"String offsets: {s1}, {s2}, {s3}")
print(f"s1 == s3: {s1 == s3}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
mem_arena
| 275
| 0
|
[
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.652
|
Error: Expression type not yet supported
|
|
example_mem_arena
|
test_mem_arena_cli.py
|
"""Tests for mem_arena_cli.py"""
import pytest
from mem_arena_cli import (
Arena,
ArenaStats,
ChunkedArena,
StringArena,
TypedArena,
simulate_arena,
)
class TestArenaStats:
def test_default(self):
stats = ArenaStats()
assert stats.total_allocated == 0
assert stats.capacity == 0
class TestArena:
def test_create(self):
arena = Arena(1024)
assert arena.available() == 1024
assert arena.used() == 0
def test_alloc_basic(self):
arena = Arena(1024)
offset = arena.alloc(64)
assert offset == 0
assert arena.used() >= 64
def test_alloc_aligned(self):
arena = Arena(1024)
arena.alloc(1) # Allocate 1 byte
offset2 = arena.alloc(8, align=8) # Should be aligned
assert offset2 % 8 == 0
def test_alloc_exhausted(self):
arena = Arena(64)
arena.alloc(32)
with pytest.raises(MemoryError):
arena.alloc(64)
def test_alloc_bytes(self):
arena = Arena(1024)
data = b"hello world"
offset = arena.alloc_bytes(data)
assert arena.get_bytes(offset, len(data)) == data
def test_reset(self):
arena = Arena(1024)
arena.alloc(256)
arena.reset()
assert arena.used() == 0
assert arena.available() == 1024
def test_stats(self):
arena = Arena(1024)
arena.alloc(64)
arena.alloc(128)
stats = arena.stats()
assert stats.allocation_count == 2
assert stats.total_allocated == 192
assert stats.capacity == 1024
class TestTypedArena:
def test_alloc(self):
arena = TypedArena[dict](capacity=1024, obj_size=32)
obj = arena.alloc({"key": "value"})
assert obj.value == {"key": "value"}
def test_count(self):
arena = TypedArena[int](capacity=1024, obj_size=8)
arena.alloc(1)
arena.alloc(2)
arena.alloc(3)
assert arena.count() == 3
def test_reset(self):
arena = TypedArena[str](capacity=1024, obj_size=16)
arena.alloc("hello")
arena.reset()
assert arena.count() == 0
class TestStringArena:
def test_intern(self):
strings = StringArena(1024)
offset = strings.intern("hello")
assert offset >= 0
def test_intern_same_string(self):
strings = StringArena(1024)
offset1 = strings.intern("hello")
offset2 = strings.intern("hello")
assert offset1 == offset2
def test_intern_different_strings(self):
strings = StringArena(1024)
offset1 = strings.intern("hello")
offset2 = strings.intern("world")
assert offset1 != offset2
def test_get(self):
strings = StringArena(1024)
offset = strings.intern("test string")
assert strings.get(offset) == "test string"
def test_count(self):
strings = StringArena(1024)
strings.intern("a")
strings.intern("b")
strings.intern("a") # Duplicate
assert strings.count() == 2
def test_reset(self):
strings = StringArena(1024)
strings.intern("test")
strings.reset()
assert strings.count() == 0
class TestChunkedArena:
def test_create(self):
arena = ChunkedArena(chunk_size=256)
assert arena.chunk_count() == 1
def test_alloc_single_chunk(self):
arena = ChunkedArena(chunk_size=256)
chunk_idx, offset = arena.alloc(64)
assert chunk_idx == 0
assert offset >= 0
def test_alloc_new_chunk(self):
arena = ChunkedArena(chunk_size=64)
arena.alloc(32)
arena.alloc(32)
# This should trigger new chunk
chunk_idx, _ = arena.alloc(32)
assert arena.chunk_count() >= 2
def test_large_allocation(self):
arena = ChunkedArena(chunk_size=64)
chunk_idx, offset = arena.alloc(128) # Larger than chunk
assert offset >= 0
def test_reset(self):
arena = ChunkedArena(chunk_size=64)
arena.alloc(32)
arena.alloc(32)
arena.alloc(32) # Creates new chunk
arena.reset()
assert arena.total_used() == 0
def test_total_capacity(self):
arena = ChunkedArena(chunk_size=256)
assert arena.total_capacity() == 256
arena.alloc(128)
arena.alloc(128)
arena.alloc(128) # New chunk
assert arena.total_capacity() >= 512
class TestSimulateArena:
def test_alloc(self):
result = simulate_arena(["alloc:64"])
assert "offset=" in result[0]
def test_alloc_bytes_and_get(self):
result = simulate_arena([
"alloc_bytes:hello",
"get_bytes:0,5"
])
assert result[1] == "hello"
def test_reset(self):
result = simulate_arena(["alloc:64", "reset:", "used:"])
assert result[2] == "0"
def test_used_available(self):
result = simulate_arena(["used:", "available:"])
assert result[0] == "0"
assert result[1] == "1024"
def test_stats(self):
result = simulate_arena(["alloc:64", "stats:"])
assert "allocated=" in result[1]
class TestArenaAlignment:
def test_default_alignment(self):
arena = Arena(256)
# All allocations should be 8-byte aligned by default
for _ in range(10):
offset = arena.alloc(1)
assert offset % 8 == 0
def test_custom_alignment(self):
arena = Arena(256)
offset = arena.alloc(1, align=16)
assert offset % 16 == 0
class TestArenaEdgeCases:
def test_zero_size_alloc(self):
arena = Arena(256)
offset = arena.alloc(0)
assert offset >= 0
def test_exact_fit(self):
arena = Arena(64)
arena.alloc(64, align=1) # Exact fit
assert arena.available() == 0
| false
|
mem_arena
| 215
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1684..1700, value: Name(ExprName { range: 1684..1694, id: Identifier("TypedArena"), ctx: Load }), slice: Name(ExprName { range: 1695..1699, id: Identifier("dict"), ctx: Load }), ctx: Load })
|
|
example_mem_lru
|
mem_lru_cli.py
|
"""LRU Cache CLI.
Demonstrates LRU cache with O(1) operations using doubly-linked list + hash map.
"""
import sys
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
K = TypeVar("K")
V = TypeVar("V")
@dataclass
class CacheStats:
"""Cache statistics."""
hits: int = 0
misses: int = 0
evictions: int = 0
size: int = 0
capacity: int = 0
@property
def hit_rate(self) -> float:
total = self.hits + self.misses
return self.hits / total if total > 0 else 0.0
@dataclass
class Node(Generic[K, V]):
"""Doubly-linked list node."""
key: K
value: V
prev: "Node[K, V] | None" = None
next: "Node[K, V] | None" = None
class LRUCache(Generic[K, V]):
"""LRU Cache with O(1) get/put operations."""
def __init__(self, capacity: int) -> None:
self._capacity = capacity
self._cache: dict[K, Node[K, V]] = {}
# Sentinel nodes for easier list manipulation
self._head: Node[K, V] = Node(None, None) # type: ignore
self._tail: Node[K, V] = Node(None, None) # type: ignore
self._head.next = self._tail
self._tail.prev = self._head
self._stats = CacheStats(capacity=capacity)
def get(self, key: K) -> V | None:
"""Get value by key. Returns None if not found."""
if key in self._cache:
node = self._cache[key]
self._move_to_front(node)
self._stats.hits += 1
return node.value
self._stats.misses += 1
return None
def put(self, key: K, value: V) -> V | None:
"""Put key-value pair. Returns evicted value if any."""
evicted: V | None = None
if key in self._cache:
node = self._cache[key]
node.value = value
self._move_to_front(node)
else:
if len(self._cache) >= self._capacity:
evicted = self._evict_lru()
node = Node(key, value)
self._cache[key] = node
self._add_to_front(node)
self._stats.size = len(self._cache)
return evicted
def remove(self, key: K) -> V | None:
"""Remove key from cache. Returns value if found."""
if key not in self._cache:
return None
node = self._cache.pop(key)
self._remove_node(node)
self._stats.size = len(self._cache)
return node.value
def contains(self, key: K) -> bool:
"""Check if key exists without affecting LRU order."""
return key in self._cache
def peek(self, key: K) -> V | None:
"""Get value without affecting LRU order."""
if key in self._cache:
return self._cache[key].value
return None
def clear(self) -> None:
"""Clear all entries."""
self._cache.clear()
self._head.next = self._tail
self._tail.prev = self._head
self._stats.size = 0
def size(self) -> int:
"""Get current size."""
return len(self._cache)
def stats(self) -> CacheStats:
"""Get cache statistics."""
return CacheStats(
hits=self._stats.hits,
misses=self._stats.misses,
evictions=self._stats.evictions,
size=len(self._cache),
capacity=self._capacity,
)
def keys(self) -> list[K]:
"""Get keys in LRU order (most recent first)."""
result: list[K] = []
node = self._head.next
while node and node != self._tail:
result.append(node.key)
node = node.next
return result
def _add_to_front(self, node: Node[K, V]) -> None:
"""Add node right after head."""
node.prev = self._head
node.next = self._head.next
if self._head.next:
self._head.next.prev = node
self._head.next = node
def _remove_node(self, node: Node[K, V]) -> None:
"""Remove node from list."""
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
def _move_to_front(self, node: Node[K, V]) -> None:
"""Move existing node to front."""
self._remove_node(node)
self._add_to_front(node)
def _evict_lru(self) -> V | None:
"""Evict least recently used entry."""
lru = self._tail.prev
if lru and lru != self._head:
self._remove_node(lru)
del self._cache[lru.key]
self._stats.evictions += 1
return lru.value
return None
class TTLCache(Generic[K, V]):
"""Cache with time-to-live expiration (simulated)."""
def __init__(self, capacity: int, ttl: int = 60) -> None:
self._cache = LRUCache[K, tuple[V, int]](capacity)
self._ttl = ttl
self._current_time = 0
def get(self, key: K) -> V | None:
"""Get value if not expired."""
entry = self._cache.get(key)
if entry is None:
return None
value, expire_time = entry
if self._current_time >= expire_time:
self._cache.remove(key)
return None
return value
def put(self, key: K, value: V) -> None:
"""Put with TTL."""
expire_time = self._current_time + self._ttl
self._cache.put(key, (value, expire_time))
def tick(self, seconds: int = 1) -> None:
"""Advance time (for simulation)."""
self._current_time += seconds
def set_time(self, time: int) -> None:
"""Set current time."""
self._current_time = time
def memoize(cache: LRUCache[Any, Any]) -> Callable:
"""Decorator to memoize function with LRU cache."""
def decorator(func: Callable) -> Callable:
def wrapper(*args: Any) -> Any:
key = args
result = cache.get(key)
if result is None:
result = func(*args)
cache.put(key, result)
return result
return wrapper
return decorator
def simulate_lru(operations: list[str]) -> list[str]:
"""Simulate LRU cache operations."""
results: list[str] = []
cache: LRUCache[str, int] = LRUCache(3)
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "put":
key, value = parts[1].split(",")
evicted = cache.put(key, int(value))
results.append(f"evicted={evicted}")
elif cmd == "get":
value = cache.get(parts[1])
results.append(f"value={value}")
elif cmd == "remove":
value = cache.remove(parts[1])
results.append(f"removed={value}")
elif cmd == "size":
results.append(str(cache.size()))
elif cmd == "keys":
results.append(str(cache.keys()))
elif cmd == "stats":
s = cache.stats()
results.append(f"hits={s.hits} misses={s.misses} rate={s.hit_rate:.2f}")
elif cmd == "clear":
cache.clear()
results.append("cleared")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: mem_lru_cli.py <command> [args]")
return 1
cmd = sys.argv[1]
if cmd == "demo":
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
print(f"Keys: {cache.keys()}")
print(f"Get a: {cache.get('a')}")
print(f"Keys after get: {cache.keys()}")
cache.put("d", 4) # Should evict b
print(f"After adding d: {cache.keys()}")
print(f"Stats: {cache.stats()}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
mem_lru
| 274
| 0
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 677..696, value: Str("Node[K, V] | None"), kind: None })
|
|
example_mem_lru
|
test_mem_lru_cli.py
|
"""Tests for mem_lru_cli.py"""
from mem_lru_cli import (
CacheStats,
LRUCache,
Node,
TTLCache,
memoize,
simulate_lru,
)
class TestCacheStats:
def test_default(self):
stats = CacheStats()
assert stats.hits == 0
assert stats.misses == 0
def test_hit_rate_zero(self):
stats = CacheStats()
assert stats.hit_rate == 0.0
def test_hit_rate_calculation(self):
stats = CacheStats(hits=80, misses=20)
assert stats.hit_rate == 0.8
class TestNode:
def test_create(self):
node = Node("key", "value")
assert node.key == "key"
assert node.value == "value"
class TestLRUCache:
def test_put_get(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
assert cache.get("a") == 1
def test_get_missing(self):
cache: LRUCache[str, int] = LRUCache(3)
assert cache.get("missing") is None
def test_put_updates_value(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("a", 2)
assert cache.get("a") == 2
assert cache.size() == 1
def test_eviction(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
evicted = cache.put("d", 4) # Evicts "a"
assert evicted == 1
assert cache.get("a") is None
assert cache.get("d") == 4
def test_lru_order_on_get(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
cache.get("a") # Makes "a" most recent
cache.put("d", 4) # Should evict "b"
assert cache.get("a") == 1
assert cache.get("b") is None
def test_lru_order_on_put(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
cache.put("a", 10) # Update "a", makes it most recent
cache.put("d", 4) # Should evict "b"
assert cache.get("a") == 10
assert cache.get("b") is None
def test_remove(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
removed = cache.remove("a")
assert removed == 1
assert cache.get("a") is None
assert cache.size() == 0
def test_remove_missing(self):
cache: LRUCache[str, int] = LRUCache(3)
assert cache.remove("missing") is None
def test_contains(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
assert cache.contains("a")
assert not cache.contains("b")
def test_peek(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
assert cache.peek("a") == 1
# Peek shouldn't affect order
cache.put("d", 4)
assert cache.peek("a") is None # "a" should be evicted
def test_clear(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.clear()
assert cache.size() == 0
assert cache.get("a") is None
def test_keys(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
keys = cache.keys()
assert keys == ["c", "b", "a"]
def test_stats(self):
cache: LRUCache[str, int] = LRUCache(3)
cache.put("a", 1)
cache.get("a") # Hit
cache.get("b") # Miss
stats = cache.stats()
assert stats.hits == 1
assert stats.misses == 1
class TestTTLCache:
def test_put_get(self):
cache: TTLCache[str, int] = TTLCache(10, ttl=60)
cache.put("a", 1)
assert cache.get("a") == 1
def test_expiration(self):
cache: TTLCache[str, int] = TTLCache(10, ttl=60)
cache.put("a", 1)
cache.tick(30) # 30 seconds
assert cache.get("a") == 1 # Still valid
cache.tick(31) # 61 seconds total
assert cache.get("a") is None # Expired
def test_set_time(self):
cache: TTLCache[str, int] = TTLCache(10, ttl=60)
cache.put("a", 1)
cache.set_time(100)
assert cache.get("a") is None
class TestMemoize:
def test_basic(self):
cache: LRUCache[tuple, int] = LRUCache(10)
call_count = [0]
@memoize(cache)
def expensive(n):
call_count[0] += 1
return n * 2
assert expensive(5) == 10
assert expensive(5) == 10 # Cached
assert call_count[0] == 1
def test_different_args(self):
cache: LRUCache[tuple, int] = LRUCache(10)
call_count = [0]
@memoize(cache)
def double(n):
call_count[0] += 1
return n * 2
assert double(5) == 10
assert double(3) == 6
assert call_count[0] == 2
class TestSimulateLru:
def test_put(self):
result = simulate_lru(["put:a,1"])
assert result == ["evicted=None"]
def test_get(self):
result = simulate_lru(["put:a,1", "get:a"])
assert "value=1" in result[1]
def test_get_miss(self):
result = simulate_lru(["get:missing"])
assert "value=None" in result[0]
def test_eviction(self):
result = simulate_lru([
"put:a,1", "put:b,2", "put:c,3", "put:d,4"
])
assert "evicted=1" in result[3]
def test_keys(self):
result = simulate_lru(["put:a,1", "put:b,2", "keys:"])
assert "['b', 'a']" in result[2]
def test_stats(self):
result = simulate_lru(["put:a,1", "get:a", "get:b", "stats:"])
assert "hits=1" in result[3]
assert "misses=1" in result[3]
class TestLRUCacheEdgeCases:
def test_capacity_one(self):
cache: LRUCache[str, int] = LRUCache(1)
cache.put("a", 1)
cache.put("b", 2)
assert cache.get("a") is None
assert cache.get("b") == 2
def test_integer_keys(self):
cache: LRUCache[int, str] = LRUCache(3)
cache.put(1, "one")
cache.put(2, "two")
assert cache.get(1) == "one"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_mem_lru/test_mem_lru_cli.py (6249 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_mem_lru/test_mem_lru_cli.rs (10235 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 115.0 KB/s
⏱️ Total time: 53ms
| true
|
mem_lru
| 227
| 5
|
[
"class_definition",
"decorator"
] | 0.612
| null |
example_mem_pool
|
mem_pool_cli.py
|
"""Object Pool CLI.
Demonstrates object pooling with acquire/release semantics.
"""
import sys
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass, field
from threading import Lock
from typing import Generic, TypeVar
T = TypeVar("T")
@dataclass
class PoolStats:
"""Pool statistics."""
total_created: int = 0
total_acquired: int = 0
total_released: int = 0
current_in_use: int = 0
current_available: int = 0
high_water_mark: int = 0
class ObjectPool(Generic[T]):
"""Generic object pool with acquire/release semantics."""
def __init__(
self,
factory: Callable[[], T],
reset: Callable[[T], None] | None = None,
max_size: int = 100,
initial_size: int = 0,
) -> None:
self._factory = factory
self._reset = reset or (lambda x: None)
self._max_size = max_size
self._pool: list[T] = []
self._in_use: set[int] = set()
self._lock = Lock()
self._stats = PoolStats()
# Pre-allocate initial objects
for _ in range(initial_size):
obj = self._factory()
self._pool.append(obj)
self._stats.total_created += 1
self._stats.current_available += 1
def acquire(self) -> T:
"""Acquire an object from the pool."""
with self._lock:
if self._pool:
obj = self._pool.pop()
self._stats.current_available -= 1
else:
obj = self._factory()
self._stats.total_created += 1
obj_id = id(obj)
self._in_use.add(obj_id)
self._stats.total_acquired += 1
self._stats.current_in_use += 1
if self._stats.current_in_use > self._stats.high_water_mark:
self._stats.high_water_mark = self._stats.current_in_use
return obj
def release(self, obj: T) -> bool:
"""Release an object back to the pool."""
with self._lock:
obj_id = id(obj)
if obj_id not in self._in_use:
return False # Object not from this pool or already released
self._in_use.remove(obj_id)
self._stats.total_released += 1
self._stats.current_in_use -= 1
if len(self._pool) < self._max_size:
self._reset(obj)
self._pool.append(obj)
self._stats.current_available += 1
return True
return True # Released but not pooled (pool full)
@contextmanager
def checkout(self):
"""Context manager for automatic release."""
obj = self.acquire()
try:
yield obj
finally:
self.release(obj)
def stats(self) -> PoolStats:
"""Get pool statistics."""
with self._lock:
return PoolStats(
total_created=self._stats.total_created,
total_acquired=self._stats.total_acquired,
total_released=self._stats.total_released,
current_in_use=self._stats.current_in_use,
current_available=self._stats.current_available,
high_water_mark=self._stats.high_water_mark,
)
def size(self) -> int:
"""Get number of available objects."""
with self._lock:
return len(self._pool)
def in_use_count(self) -> int:
"""Get number of objects in use."""
with self._lock:
return len(self._in_use)
def clear(self) -> int:
"""Clear the pool, returning count of cleared objects."""
with self._lock:
count = len(self._pool)
self._pool.clear()
self._stats.current_available = 0
return count
# Specialized pools
@dataclass
class Connection:
"""A simulated database connection."""
id: int
is_open: bool = True
query_count: int = 0
def execute(self, query: str) -> str:
"""Execute a query."""
self.query_count += 1
return f"Result from conn-{self.id}: {query}"
def reset(self) -> None:
"""Reset connection state."""
self.query_count = 0
class ConnectionPool:
"""Database connection pool."""
def __init__(self, max_size: int = 10) -> None:
self._next_id = 0
self._pool = ObjectPool(
factory=self._create_connection,
reset=lambda c: c.reset(),
max_size=max_size,
)
def _create_connection(self) -> Connection:
"""Create a new connection."""
conn_id = self._next_id
self._next_id += 1
return Connection(conn_id)
def get_connection(self) -> Connection:
"""Get a connection from the pool."""
return self._pool.acquire()
def return_connection(self, conn: Connection) -> None:
"""Return a connection to the pool."""
self._pool.release(conn)
@contextmanager
def connection(self):
"""Context manager for connection."""
conn = self.get_connection()
try:
yield conn
finally:
self.return_connection(conn)
def stats(self) -> PoolStats:
"""Get pool statistics."""
return self._pool.stats()
@dataclass
class Buffer:
"""A byte buffer."""
data: bytearray = field(default_factory=lambda: bytearray(1024))
position: int = 0
limit: int = 1024
def write(self, data: bytes) -> int:
"""Write data to buffer."""
available = self.limit - self.position
to_write = min(len(data), available)
self.data[self.position : self.position + to_write] = data[:to_write]
self.position += to_write
return to_write
def read(self, size: int) -> bytes:
"""Read data from buffer."""
end = min(self.position, size)
result = bytes(self.data[:end])
return result
def reset(self) -> None:
"""Reset buffer."""
self.position = 0
class BufferPool:
"""Pool of byte buffers."""
def __init__(self, buffer_size: int = 1024, max_size: int = 100) -> None:
self._buffer_size = buffer_size
def create_buffer() -> Buffer:
return Buffer(
data=bytearray(buffer_size),
limit=buffer_size,
)
self._pool = ObjectPool(
factory=create_buffer,
reset=lambda b: b.reset(),
max_size=max_size,
)
def acquire(self) -> Buffer:
"""Acquire a buffer."""
return self._pool.acquire()
def release(self, buf: Buffer) -> None:
"""Release a buffer."""
self._pool.release(buf)
@contextmanager
def buffer(self):
"""Context manager for buffer."""
buf = self.acquire()
try:
yield buf
finally:
self.release(buf)
def stats(self) -> PoolStats:
"""Get pool statistics."""
return self._pool.stats()
def simulate_pool(operations: list[str]) -> list[str]:
"""Simulate pool operations."""
results: list[str] = []
pool: ObjectPool[list] = ObjectPool(
factory=lambda: [],
reset=lambda x: x.clear(),
max_size=10,
)
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "acquire":
obj = pool.acquire()
results.append(f"acquired id={id(obj)}")
elif cmd == "release":
# For simulation, acquire then release
obj = pool.acquire()
pool.release(obj)
results.append("released")
elif cmd == "size":
results.append(str(pool.size()))
elif cmd == "in_use":
results.append(str(pool.in_use_count()))
elif cmd == "stats":
s = pool.stats()
results.append(f"created={s.total_created} acquired={s.total_acquired}")
elif cmd == "checkout":
with pool.checkout() as obj:
obj.append(1)
results.append("checkout complete")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: mem_pool_cli.py <command> [args]")
return 1
cmd = sys.argv[1]
pool = ConnectionPool(max_size=5)
if cmd == "demo":
# Demo connection pooling
conn = pool.get_connection()
print(f"Got connection: {conn.id}")
result = conn.execute("SELECT * FROM users")
print(f"Query result: {result}")
pool.return_connection(conn)
print(f"Stats: {pool.stats()}")
elif cmd == "context":
with pool.connection() as conn:
print(f"Using connection: {conn.id}")
print(conn.execute("INSERT INTO logs VALUES(1)"))
print(f"Stats: {pool.stats()}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
mem_pool
| 323
| 0
|
[
"generator",
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"decorator",
"multiprocessing"
] | 0.927
|
Error: Expression type not yet supported
|
|
example_mem_pool
|
test_mem_pool_cli.py
|
"""Tests for mem_pool_cli.py"""
from mem_pool_cli import (
Buffer,
BufferPool,
Connection,
ConnectionPool,
ObjectPool,
PoolStats,
simulate_pool,
)
class TestPoolStats:
def test_default(self):
stats = PoolStats()
assert stats.total_created == 0
assert stats.total_acquired == 0
assert stats.total_released == 0
assert stats.current_in_use == 0
assert stats.current_available == 0
assert stats.high_water_mark == 0
class TestObjectPool:
def test_acquire_creates_object(self):
pool = ObjectPool(factory=lambda: {"value": 0})
obj = pool.acquire()
assert obj is not None
assert obj["value"] == 0
def test_acquire_increments_stats(self):
pool = ObjectPool(factory=lambda: [])
pool.acquire()
stats = pool.stats()
assert stats.total_created == 1
assert stats.total_acquired == 1
assert stats.current_in_use == 1
def test_release_returns_to_pool(self):
pool = ObjectPool(factory=lambda: [])
obj = pool.acquire()
assert pool.size() == 0
pool.release(obj)
assert pool.size() == 1
stats = pool.stats()
assert stats.total_released == 1
assert stats.current_in_use == 0
def test_release_resets_object(self):
reset_called = []
pool = ObjectPool(
factory=lambda: {"count": 0},
reset=lambda obj: reset_called.append(obj),
)
obj = pool.acquire()
pool.release(obj)
assert len(reset_called) == 1
def test_reuse_pooled_object(self):
pool = ObjectPool(factory=lambda: [])
obj1 = pool.acquire()
obj1_id = id(obj1)
pool.release(obj1)
obj2 = pool.acquire()
assert id(obj2) == obj1_id # Same object reused
def test_max_size_respected(self):
pool = ObjectPool(factory=lambda: [], max_size=2)
objs = [pool.acquire() for _ in range(5)]
for obj in objs:
pool.release(obj)
assert pool.size() <= 2
def test_initial_size(self):
pool = ObjectPool(factory=lambda: [], initial_size=3)
assert pool.size() == 3
stats = pool.stats()
assert stats.total_created == 3
def test_high_water_mark(self):
pool = ObjectPool(factory=lambda: [])
objs = [pool.acquire() for _ in range(5)]
stats = pool.stats()
assert stats.high_water_mark == 5
for obj in objs[:3]:
pool.release(obj)
stats = pool.stats()
assert stats.high_water_mark == 5 # Doesn't decrease
def test_checkout_context_manager(self):
pool = ObjectPool(factory=lambda: [], reset=lambda x: x.clear())
with pool.checkout() as obj:
obj.append(1)
obj.append(2)
assert len(obj) == 2
# Object should be released and reset
stats = pool.stats()
assert stats.total_released == 1
def test_release_unknown_object_returns_false(self):
pool = ObjectPool(factory=lambda: [])
unknown_obj = []
result = pool.release(unknown_obj)
assert result is False
def test_clear(self):
pool = ObjectPool(factory=lambda: [], initial_size=5)
assert pool.size() == 5
cleared = pool.clear()
assert cleared == 5
assert pool.size() == 0
class TestConnection:
def test_create(self):
conn = Connection(id=1)
assert conn.id == 1
assert conn.is_open
assert conn.query_count == 0
def test_execute(self):
conn = Connection(id=1)
result = conn.execute("SELECT 1")
assert "conn-1" in result
assert "SELECT 1" in result
assert conn.query_count == 1
def test_reset(self):
conn = Connection(id=1)
conn.execute("SELECT 1")
conn.reset()
assert conn.query_count == 0
class TestConnectionPool:
def test_get_connection(self):
pool = ConnectionPool(max_size=5)
conn = pool.get_connection()
assert conn is not None
assert conn.id == 0
def test_return_connection(self):
pool = ConnectionPool(max_size=5)
conn = pool.get_connection()
pool.return_connection(conn)
stats = pool.stats()
assert stats.total_released == 1
def test_reuses_connections(self):
pool = ConnectionPool(max_size=5)
conn1 = pool.get_connection()
conn1_id = conn1.id
pool.return_connection(conn1)
conn2 = pool.get_connection()
assert conn2.id == conn1_id
def test_context_manager(self):
pool = ConnectionPool(max_size=5)
with pool.connection() as conn:
conn.execute("INSERT INTO test VALUES(1)")
stats = pool.stats()
assert stats.total_released == 1
def test_multiple_connections(self):
pool = ConnectionPool(max_size=5)
conns = [pool.get_connection() for _ in range(3)]
assert len({c.id for c in conns}) == 3 # All different
class TestBuffer:
def test_create(self):
buf = Buffer()
assert buf.position == 0
assert buf.limit == 1024
def test_write(self):
buf = Buffer()
written = buf.write(b"hello")
assert written == 5
assert buf.position == 5
def test_read(self):
buf = Buffer()
buf.write(b"hello")
data = buf.read(5)
assert data == b"hello"
def test_reset(self):
buf = Buffer()
buf.write(b"hello")
buf.reset()
assert buf.position == 0
class TestBufferPool:
def test_acquire(self):
pool = BufferPool(buffer_size=512)
buf = pool.acquire()
assert buf is not None
assert buf.limit == 512
def test_release(self):
pool = BufferPool(buffer_size=512)
buf = pool.acquire()
buf.write(b"test")
pool.release(buf)
stats = pool.stats()
assert stats.total_released == 1
def test_context_manager(self):
pool = BufferPool(buffer_size=512)
with pool.buffer() as buf:
buf.write(b"data")
stats = pool.stats()
assert stats.total_released == 1
class TestSimulatePool:
def test_acquire(self):
result = simulate_pool(["acquire:"])
assert len(result) == 1
assert "acquired" in result[0]
def test_size(self):
result = simulate_pool(["size:"])
assert result == ["0"]
def test_stats(self):
result = simulate_pool(["stats:"])
assert "created=" in result[0]
def test_checkout(self):
result = simulate_pool(["checkout:"])
assert result == ["checkout complete"]
class TestPoolConcurrency:
def test_multiple_acquires(self):
pool = ObjectPool(factory=lambda: [], max_size=10)
objs = [pool.acquire() for _ in range(10)]
assert pool.in_use_count() == 10
for obj in objs:
pool.release(obj)
assert pool.in_use_count() == 0
class TestPoolEdgeCases:
def test_empty_pool_acquire(self):
pool = ObjectPool(factory=lambda: "new")
obj = pool.acquire()
assert obj == "new"
def test_release_twice(self):
pool = ObjectPool(factory=lambda: [])
obj = pool.acquire()
assert pool.release(obj) is True
assert pool.release(obj) is False # Already released
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_mem_pool/test_mem_pool_cli.py (7479 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_mem_pool/test_mem_pool_cli.rs (11867 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 140.9 KB/s
⏱️ Total time: 52ms
| true
|
mem_pool
| 266
| 5
|
[
"lambda",
"context_manager",
"class_definition",
"multiprocessing"
] | 0.783
| null |
example_mem_ring
|
mem_ring_cli.py
|
"""Ring Buffer CLI.
Demonstrates circular buffer/ring buffer implementation.
"""
import sys
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Generic, TypeVar
T = TypeVar("T")
@dataclass
class RingStats:
"""Ring buffer statistics."""
capacity: int = 0
size: int = 0
head: int = 0
tail: int = 0
overflows: int = 0
class RingBuffer(Generic[T]):
"""Fixed-size circular buffer."""
def __init__(self, capacity: int) -> None:
self._capacity = capacity
self._buffer: list[T | None] = [None] * capacity
self._head = 0 # Next write position
self._tail = 0 # Next read position
self._size = 0
self._overflows = 0
def push(self, item: T) -> T | None:
"""Push item. Returns overwritten item if buffer was full."""
overwritten: T | None = None
if self._size == self._capacity:
overwritten = self._buffer[self._tail]
self._tail = (self._tail + 1) % self._capacity
self._overflows += 1
else:
self._size += 1
self._buffer[self._head] = item
self._head = (self._head + 1) % self._capacity
return overwritten
def pop(self) -> T | None:
"""Pop oldest item (FIFO)."""
if self._size == 0:
return None
item = self._buffer[self._tail]
self._buffer[self._tail] = None
self._tail = (self._tail + 1) % self._capacity
self._size -= 1
return item
def peek(self) -> T | None:
"""Peek at oldest item without removing."""
if self._size == 0:
return None
return self._buffer[self._tail]
def peek_newest(self) -> T | None:
"""Peek at newest item."""
if self._size == 0:
return None
idx = (self._head - 1) % self._capacity
return self._buffer[idx]
def clear(self) -> None:
"""Clear the buffer."""
self._buffer = [None] * self._capacity
self._head = 0
self._tail = 0
self._size = 0
def size(self) -> int:
"""Get current size."""
return self._size
def capacity(self) -> int:
"""Get capacity."""
return self._capacity
def is_empty(self) -> bool:
"""Check if buffer is empty."""
return self._size == 0
def is_full(self) -> bool:
"""Check if buffer is full."""
return self._size == self._capacity
def stats(self) -> RingStats:
"""Get buffer statistics."""
return RingStats(
capacity=self._capacity,
size=self._size,
head=self._head,
tail=self._tail,
overflows=self._overflows,
)
def to_list(self) -> list[T]:
"""Convert to list (oldest to newest)."""
result: list[T] = []
if self._size == 0:
return result
idx = self._tail
for _ in range(self._size):
item = self._buffer[idx]
if item is not None:
result.append(item)
idx = (idx + 1) % self._capacity
return result
def __iter__(self) -> Iterator[T]:
"""Iterate from oldest to newest."""
yield from self.to_list()
def __len__(self) -> int:
return self._size
class ByteRing:
"""Ring buffer optimized for bytes."""
def __init__(self, capacity: int) -> None:
self._buffer = bytearray(capacity)
self._capacity = capacity
self._head = 0
self._tail = 0
self._size = 0
def write(self, data: bytes) -> int:
"""Write bytes. Returns number written."""
written = 0
for byte in data:
if self._size == self._capacity:
# Overwrite oldest
self._tail = (self._tail + 1) % self._capacity
else:
self._size += 1
self._buffer[self._head] = byte
self._head = (self._head + 1) % self._capacity
written += 1
return written
def read(self, count: int) -> bytes:
"""Read up to count bytes."""
to_read = min(count, self._size)
result = bytearray(to_read)
for i in range(to_read):
result[i] = self._buffer[self._tail]
self._tail = (self._tail + 1) % self._capacity
self._size -= 1
return bytes(result)
def peek(self, count: int) -> bytes:
"""Peek up to count bytes without consuming."""
to_read = min(count, self._size)
result = bytearray(to_read)
idx = self._tail
for i in range(to_read):
result[i] = self._buffer[idx]
idx = (idx + 1) % self._capacity
return bytes(result)
def available(self) -> int:
"""Get available bytes to read."""
return self._size
def free_space(self) -> int:
"""Get free space for writing (before overwrite)."""
return self._capacity - self._size
def clear(self) -> None:
"""Clear the buffer."""
self._head = 0
self._tail = 0
self._size = 0
class SlidingWindow(Generic[T]):
"""Sliding window over a stream of values."""
def __init__(self, size: int) -> None:
self._ring: RingBuffer[T] = RingBuffer(size)
def add(self, value: T) -> None:
"""Add value to window."""
self._ring.push(value)
def values(self) -> list[T]:
"""Get all values in window."""
return self._ring.to_list()
def size(self) -> int:
"""Get current window size."""
return self._ring.size()
def is_full(self) -> bool:
"""Check if window is full."""
return self._ring.is_full()
class MovingAverage:
"""Moving average calculator using ring buffer."""
def __init__(self, window_size: int) -> None:
self._ring: RingBuffer[float] = RingBuffer(window_size)
self._sum = 0.0
def add(self, value: float) -> float:
"""Add value and return current average."""
evicted = self._ring.push(value)
if evicted is not None:
self._sum -= evicted
self._sum += value
return self.average()
def average(self) -> float:
"""Get current average."""
if self._ring.is_empty():
return 0.0
return self._sum / self._ring.size()
def size(self) -> int:
"""Get number of values."""
return self._ring.size()
def simulate_ring(operations: list[str]) -> list[str]:
"""Simulate ring buffer operations."""
results: list[str] = []
ring: RingBuffer[int] = RingBuffer(4)
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "push":
evicted = ring.push(int(parts[1]))
results.append(f"evicted={evicted}")
elif cmd == "pop":
value = ring.pop()
results.append(f"value={value}")
elif cmd == "peek":
value = ring.peek()
results.append(f"peek={value}")
elif cmd == "size":
results.append(str(ring.size()))
elif cmd == "is_full":
results.append(str(ring.is_full()))
elif cmd == "to_list":
results.append(str(ring.to_list()))
elif cmd == "stats":
s = ring.stats()
results.append(f"size={s.size} overflows={s.overflows}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: mem_ring_cli.py <command> [args]")
return 1
cmd = sys.argv[1]
if cmd == "demo":
ring: RingBuffer[str] = RingBuffer(3)
for item in ["a", "b", "c", "d", "e"]:
evicted = ring.push(item)
print(f"Push {item}, evicted={evicted}, buffer={ring.to_list()}")
print(f"\nFinal buffer: {ring.to_list()}")
print(f"Stats: {ring.stats()}")
# Moving average demo
ma = MovingAverage(3)
for val in [1.0, 2.0, 3.0, 4.0, 5.0]:
avg = ma.add(val)
print(f"Add {val}, average={avg:.2f}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
mem_ring
| 304
| 0
|
[
"generator",
"class_definition",
"decorator"
] | 0.927
|
Error: Expression type not yet supported
|
|
example_mem_ring
|
test_mem_ring_cli.py
|
"""Tests for mem_ring_cli.py"""
from mem_ring_cli import (
ByteRing,
MovingAverage,
RingBuffer,
RingStats,
SlidingWindow,
simulate_ring,
)
class TestRingStats:
def test_default(self):
stats = RingStats()
assert stats.capacity == 0
assert stats.overflows == 0
class TestRingBuffer:
def test_push(self):
ring: RingBuffer[int] = RingBuffer(4)
result = ring.push(1)
assert result is None
assert ring.size() == 1
def test_push_overflow(self):
ring: RingBuffer[int] = RingBuffer(2)
ring.push(1)
ring.push(2)
evicted = ring.push(3)
assert evicted == 1
def test_pop(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
assert ring.pop() == 1
assert ring.pop() == 2
def test_pop_empty(self):
ring: RingBuffer[int] = RingBuffer(4)
assert ring.pop() is None
def test_peek(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
assert ring.peek() == 1
assert ring.size() == 2 # Unchanged
def test_peek_newest(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
ring.push(3)
assert ring.peek_newest() == 3
def test_clear(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
ring.clear()
assert ring.is_empty()
def test_is_empty(self):
ring: RingBuffer[int] = RingBuffer(4)
assert ring.is_empty()
ring.push(1)
assert not ring.is_empty()
def test_is_full(self):
ring: RingBuffer[int] = RingBuffer(2)
assert not ring.is_full()
ring.push(1)
ring.push(2)
assert ring.is_full()
def test_to_list(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
ring.push(3)
assert ring.to_list() == [1, 2, 3]
def test_to_list_with_overflow(self):
ring: RingBuffer[int] = RingBuffer(3)
ring.push(1)
ring.push(2)
ring.push(3)
ring.push(4)
assert ring.to_list() == [2, 3, 4]
def test_iter(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
assert list(ring) == [1, 2]
def test_len(self):
ring: RingBuffer[int] = RingBuffer(4)
ring.push(1)
ring.push(2)
assert len(ring) == 2
def test_stats(self):
ring: RingBuffer[int] = RingBuffer(3)
ring.push(1)
ring.push(2)
ring.push(3)
ring.push(4) # Overflow
stats = ring.stats()
assert stats.capacity == 3
assert stats.size == 3
assert stats.overflows == 1
def test_fifo_order(self):
ring: RingBuffer[str] = RingBuffer(4)
ring.push("a")
ring.push("b")
ring.push("c")
assert ring.pop() == "a"
assert ring.pop() == "b"
assert ring.pop() == "c"
class TestByteRing:
def test_write_read(self):
ring = ByteRing(10)
ring.write(b"hello")
data = ring.read(5)
assert data == b"hello"
def test_partial_read(self):
ring = ByteRing(10)
ring.write(b"hello")
assert ring.read(3) == b"hel"
assert ring.read(2) == b"lo"
def test_overflow(self):
ring = ByteRing(5)
ring.write(b"hello")
ring.write(b"XY") # Overwrites "he"
assert ring.read(5) == b"lloXY"
def test_peek(self):
ring = ByteRing(10)
ring.write(b"test")
assert ring.peek(2) == b"te"
assert ring.available() == 4 # Unchanged
def test_available(self):
ring = ByteRing(10)
ring.write(b"abc")
assert ring.available() == 3
def test_free_space(self):
ring = ByteRing(10)
ring.write(b"abc")
assert ring.free_space() == 7
def test_clear(self):
ring = ByteRing(10)
ring.write(b"test")
ring.clear()
assert ring.available() == 0
class TestSlidingWindow:
def test_add(self):
window: SlidingWindow[int] = SlidingWindow(3)
window.add(1)
window.add(2)
assert window.values() == [1, 2]
def test_overflow(self):
window: SlidingWindow[int] = SlidingWindow(3)
window.add(1)
window.add(2)
window.add(3)
window.add(4)
assert window.values() == [2, 3, 4]
def test_is_full(self):
window: SlidingWindow[int] = SlidingWindow(2)
assert not window.is_full()
window.add(1)
window.add(2)
assert window.is_full()
class TestMovingAverage:
def test_single_value(self):
ma = MovingAverage(3)
avg = ma.add(10.0)
assert avg == 10.0
def test_partial_window(self):
ma = MovingAverage(3)
ma.add(1.0)
avg = ma.add(2.0)
assert avg == 1.5
def test_full_window(self):
ma = MovingAverage(3)
ma.add(1.0)
ma.add(2.0)
avg = ma.add(3.0)
assert avg == 2.0
def test_sliding(self):
ma = MovingAverage(3)
ma.add(1.0)
ma.add(2.0)
ma.add(3.0)
avg = ma.add(4.0) # Evicts 1.0
assert avg == 3.0 # (2+3+4)/3
def test_average_empty(self):
ma = MovingAverage(3)
assert ma.average() == 0.0
class TestSimulateRing:
def test_push(self):
result = simulate_ring(["push:1"])
assert result == ["evicted=None"]
def test_push_overflow(self):
result = simulate_ring([
"push:1", "push:2", "push:3", "push:4", "push:5"
])
assert "evicted=1" in result[4]
def test_pop(self):
result = simulate_ring(["push:42", "pop:"])
assert "value=42" in result[1]
def test_peek(self):
result = simulate_ring(["push:1", "push:2", "peek:"])
assert "peek=1" in result[2]
def test_size(self):
result = simulate_ring(["push:1", "push:2", "size:"])
assert result[2] == "2"
def test_is_full(self):
result = simulate_ring([
"push:1", "push:2", "push:3", "push:4", "is_full:"
])
assert result[4] == "True"
def test_to_list(self):
result = simulate_ring(["push:1", "push:2", "to_list:"])
assert result[2] == "[1, 2]"
class TestRingBufferEdgeCases:
def test_capacity_one(self):
ring: RingBuffer[int] = RingBuffer(1)
ring.push(1)
assert ring.push(2) == 1
assert ring.to_list() == [2]
def test_wrap_around(self):
ring: RingBuffer[int] = RingBuffer(3)
ring.push(1)
ring.push(2)
ring.push(3)
ring.pop()
ring.pop()
ring.push(4)
ring.push(5)
assert ring.to_list() == [3, 4, 5]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_mem_ring/test_mem_ring_cli.py (6937 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_mem_ring/test_mem_ring_cli.rs (10854 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 127.5 KB/s
⏱️ Total time: 53ms
| true
|
mem_ring
| 275
| 5
|
[
"class_definition",
"functools"
] | 0.612
| null |
example_mem_slab
|
mem_slab_cli.py
|
"""Slab Allocator CLI.
Demonstrates slab allocation for fixed-size objects.
"""
import sys
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
T = TypeVar("T")
@dataclass
class SlabStats:
"""Slab statistics."""
total_slots: int = 0
used_slots: int = 0
free_slots: int = 0
slab_count: int = 0
class Slab(Generic[T]):
"""A single slab containing fixed-size slots."""
def __init__(self, slot_count: int, factory: Any) -> None:
self._slot_count = slot_count
self._factory = factory
self._slots: list[T | None] = [None] * slot_count
self._free_list: list[int] = list(range(slot_count))
self._used: set[int] = set()
def alloc(self) -> tuple[int, T] | None:
"""Allocate a slot. Returns (slot_index, object) or None."""
if not self._free_list:
return None
slot_idx = self._free_list.pop()
if self._slots[slot_idx] is None:
self._slots[slot_idx] = self._factory()
self._used.add(slot_idx)
return slot_idx, self._slots[slot_idx] # type: ignore
def free(self, slot_idx: int) -> bool:
"""Free a slot."""
if slot_idx not in self._used:
return False
self._used.remove(slot_idx)
self._free_list.append(slot_idx)
return True
def is_full(self) -> bool:
"""Check if slab is full."""
return len(self._free_list) == 0
def is_empty(self) -> bool:
"""Check if slab is empty (all slots free)."""
return len(self._used) == 0
def used_count(self) -> int:
"""Get number of used slots."""
return len(self._used)
def free_count(self) -> int:
"""Get number of free slots."""
return len(self._free_list)
class SlabAllocator(Generic[T]):
"""Slab allocator managing multiple slabs."""
def __init__(
self,
slots_per_slab: int = 64,
factory: Any = None,
max_slabs: int = 100,
) -> None:
self._slots_per_slab = slots_per_slab
self._factory = factory or (lambda: {})
self._max_slabs = max_slabs
self._slabs: list[Slab[T]] = []
self._allocations: dict[int, tuple[int, int]] = {} # obj_id -> (slab_idx, slot_idx)
self._next_id = 0
def alloc(self) -> tuple[int, T]:
"""Allocate an object. Returns (handle, object)."""
# Find a slab with free slots
for slab_idx, slab in enumerate(self._slabs):
if not slab.is_full():
result = slab.alloc()
if result:
slot_idx, obj = result
handle = self._next_id
self._next_id += 1
self._allocations[handle] = (slab_idx, slot_idx)
return handle, obj
# Need new slab
if len(self._slabs) >= self._max_slabs:
raise MemoryError("Max slabs exceeded")
new_slab: Slab[T] = Slab(self._slots_per_slab, self._factory)
self._slabs.append(new_slab)
result = new_slab.alloc()
if result:
slot_idx, obj = result
handle = self._next_id
self._next_id += 1
self._allocations[handle] = (len(self._slabs) - 1, slot_idx)
return handle, obj
raise MemoryError("Failed to allocate")
def free(self, handle: int) -> bool:
"""Free an allocation by handle."""
if handle not in self._allocations:
return False
slab_idx, slot_idx = self._allocations.pop(handle)
return self._slabs[slab_idx].free(slot_idx)
def get(self, handle: int) -> T | None:
"""Get object by handle."""
if handle not in self._allocations:
return None
slab_idx, slot_idx = self._allocations[handle]
return self._slabs[slab_idx]._slots[slot_idx]
def stats(self) -> SlabStats:
"""Get allocator statistics."""
total = sum(s._slot_count for s in self._slabs)
used = sum(s.used_count() for s in self._slabs)
return SlabStats(
total_slots=total,
used_slots=used,
free_slots=total - used,
slab_count=len(self._slabs),
)
def shrink(self) -> int:
"""Remove empty slabs. Returns number removed."""
original = len(self._slabs)
# Only remove trailing empty slabs to avoid handle invalidation
while self._slabs and self._slabs[-1].is_empty():
self._slabs.pop()
return original - len(self._slabs)
@dataclass
class Entity:
"""Game entity for slab allocation demo."""
x: float = 0.0
y: float = 0.0
health: int = 100
name: str = ""
class EntityPool:
"""Pool of game entities using slab allocation."""
def __init__(self, slots_per_slab: int = 64) -> None:
self._allocator: SlabAllocator[Entity] = SlabAllocator(
slots_per_slab=slots_per_slab,
factory=Entity,
)
self._entities: dict[int, Entity] = {}
def spawn(self, name: str, x: float = 0.0, y: float = 0.0) -> int:
"""Spawn a new entity. Returns handle."""
handle, entity = self._allocator.alloc()
entity.name = name
entity.x = x
entity.y = y
entity.health = 100
self._entities[handle] = entity
return handle
def despawn(self, handle: int) -> bool:
"""Despawn an entity."""
if handle in self._entities:
del self._entities[handle]
return self._allocator.free(handle)
return False
def get(self, handle: int) -> Entity | None:
"""Get entity by handle."""
return self._entities.get(handle)
def count(self) -> int:
"""Get active entity count."""
return len(self._entities)
def stats(self) -> SlabStats:
"""Get pool statistics."""
return self._allocator.stats()
def simulate_slab(operations: list[str]) -> list[str]:
"""Simulate slab operations."""
results: list[str] = []
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "alloc":
handle, obj = allocator.alloc()
results.append(f"handle={handle}")
elif cmd == "free":
handle = int(parts[1])
success = allocator.free(handle)
results.append(f"freed={success}")
elif cmd == "get":
handle = int(parts[1])
obj = allocator.get(handle)
results.append(f"found={obj is not None}")
elif cmd == "stats":
s = allocator.stats()
results.append(f"used={s.used_slots} total={s.total_slots}")
elif cmd == "shrink":
removed = allocator.shrink()
results.append(f"removed={removed}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: mem_slab_cli.py <command> [args]")
return 1
cmd = sys.argv[1]
if cmd == "demo":
pool = EntityPool(slots_per_slab=8)
handles = [
pool.spawn("Player", 0, 0),
pool.spawn("Enemy1", 10, 5),
pool.spawn("Enemy2", -5, 8),
]
print(f"Spawned entities: {handles}")
print(f"Stats: {pool.stats()}")
pool.despawn(handles[1])
print(f"After despawn: {pool.stats()}")
print(f"Player: {pool.get(handles[0])}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
mem_slab
| 261
| 0
|
[
"context_manager",
"class_definition",
"exception_handling",
"decorator",
"multiprocessing"
] | 0.652
|
Type inference hints:
Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type)
Hint: str for variable 'success' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type)
Hint: str for variable 'handle' [Medium] (usage patterns suggest this type)
Hint: str for variable 'op' [Medium] (usage patterns suggest this type)
Hint: str for variable 'removed' [Medium] (usage patterns suggest this type)
Type inference
|
|
example_mem_slab
|
test_mem_slab_cli.py
|
"""Tests for mem_slab_cli.py"""
import pytest
from mem_slab_cli import (
Entity,
EntityPool,
Slab,
SlabAllocator,
SlabStats,
simulate_slab,
)
class TestSlabStats:
def test_default(self):
stats = SlabStats()
assert stats.total_slots == 0
assert stats.used_slots == 0
class TestSlab:
def test_alloc(self):
slab: Slab[dict] = Slab(4, dict)
result = slab.alloc()
assert result is not None
slot_idx, obj = result
assert isinstance(obj, dict)
def test_alloc_all(self):
slab: Slab[list] = Slab(4, list)
for _ in range(4):
assert slab.alloc() is not None
assert slab.alloc() is None
def test_free(self):
slab: Slab[dict] = Slab(4, dict)
result = slab.alloc()
assert result is not None
slot_idx, _ = result
assert slab.free(slot_idx)
def test_free_invalid(self):
slab: Slab[dict] = Slab(4, dict)
assert slab.free(999) is False
def test_is_full(self):
slab: Slab[dict] = Slab(2, dict)
assert not slab.is_full()
slab.alloc()
slab.alloc()
assert slab.is_full()
def test_is_empty(self):
slab: Slab[dict] = Slab(2, dict)
assert slab.is_empty()
result = slab.alloc()
assert not slab.is_empty()
if result:
slab.free(result[0])
assert slab.is_empty()
def test_reuse_slot(self):
slab: Slab[dict] = Slab(1, dict)
result1 = slab.alloc()
assert result1 is not None
slot1, obj1 = result1
slab.free(slot1)
result2 = slab.alloc()
assert result2 is not None
slot2, obj2 = result2
assert slot1 == slot2
assert obj1 is obj2 # Same object reused
class TestSlabAllocator:
def test_alloc(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
handle, obj = allocator.alloc()
assert handle >= 0
assert isinstance(obj, dict)
def test_free(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
handle, _ = allocator.alloc()
assert allocator.free(handle)
def test_free_invalid(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
assert not allocator.free(999)
def test_get(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
handle, obj = allocator.alloc()
obj["key"] = "value"
retrieved = allocator.get(handle)
assert retrieved is not None
assert retrieved["key"] == "value"
def test_get_invalid(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
assert allocator.get(999) is None
def test_creates_new_slab(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=2, factory=dict)
allocator.alloc()
allocator.alloc()
stats = allocator.stats()
assert stats.slab_count == 1
allocator.alloc() # Triggers new slab
stats = allocator.stats()
assert stats.slab_count == 2
def test_max_slabs(self):
allocator: SlabAllocator[dict] = SlabAllocator(
slots_per_slab=1, factory=dict, max_slabs=2
)
allocator.alloc()
allocator.alloc()
with pytest.raises(MemoryError):
allocator.alloc()
def test_stats(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
allocator.alloc()
allocator.alloc()
stats = allocator.stats()
assert stats.used_slots == 2
assert stats.total_slots == 4
def test_shrink(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=2, factory=dict)
h1, _ = allocator.alloc()
h2, _ = allocator.alloc()
h3, _ = allocator.alloc() # New slab
allocator.free(h3)
removed = allocator.shrink()
assert removed == 1
class TestEntity:
def test_create(self):
e = Entity()
assert e.x == 0.0
assert e.health == 100
def test_with_values(self):
e = Entity(x=10.0, y=20.0, health=50, name="Test")
assert e.x == 10.0
assert e.name == "Test"
class TestEntityPool:
def test_spawn(self):
pool = EntityPool(slots_per_slab=8)
handle = pool.spawn("Player", 5.0, 10.0)
assert handle >= 0
def test_get(self):
pool = EntityPool(slots_per_slab=8)
handle = pool.spawn("Player", 5.0, 10.0)
entity = pool.get(handle)
assert entity is not None
assert entity.name == "Player"
assert entity.x == 5.0
def test_despawn(self):
pool = EntityPool(slots_per_slab=8)
handle = pool.spawn("Enemy")
assert pool.despawn(handle)
assert pool.get(handle) is None
def test_count(self):
pool = EntityPool(slots_per_slab=8)
assert pool.count() == 0
pool.spawn("A")
pool.spawn("B")
assert pool.count() == 2
def test_stats(self):
pool = EntityPool(slots_per_slab=4)
pool.spawn("A")
pool.spawn("B")
stats = pool.stats()
assert stats.used_slots == 2
class TestSimulateSlab:
def test_alloc(self):
result = simulate_slab(["alloc:"])
assert "handle=0" in result[0]
def test_free(self):
result = simulate_slab(["alloc:", "free:0"])
assert "freed=True" in result[1]
def test_get(self):
result = simulate_slab(["alloc:", "get:0"])
assert "found=True" in result[1]
def test_stats(self):
result = simulate_slab(["alloc:", "stats:"])
assert "used=1" in result[1]
class TestSlabEdgeCases:
def test_many_allocations(self):
allocator: SlabAllocator[int] = SlabAllocator(
slots_per_slab=10, factory=lambda: 0, max_slabs=100
)
handles = []
for _ in range(100):
h, _ = allocator.alloc()
handles.append(h)
assert allocator.stats().used_slots == 100
def test_alloc_free_pattern(self):
allocator: SlabAllocator[dict] = SlabAllocator(slots_per_slab=4, factory=dict)
handles = []
for _ in range(8):
h, _ = allocator.alloc()
handles.append(h)
for h in handles[:4]:
allocator.free(h)
stats = allocator.stats()
assert stats.used_slots == 4
| false
|
mem_slab
| 225
| 0
|
[
"context_manager",
"class_definition",
"multiprocessing"
] | 0.652
|
Error: 'is' operator not yet supported (use == for value comparison)
|
|
example_memoryview_ops
|
memoryview_ops_cli.py
|
#!/usr/bin/env python3
"""Memoryview Operations CLI.
Working with memoryview for zero-copy buffer access.
"""
import argparse
import sys
def create_bytearray(size: int, fill: int = 0) -> bytearray:
"""Create a bytearray of given size with fill value."""
return bytearray([fill] * size)
def create_from_list(values: list[int]) -> bytearray:
"""Create a bytearray from list of integers."""
return bytearray(values)
def get_slice(data: bytearray, start: int, end: int) -> bytes:
"""Get a slice of bytes using memoryview."""
mv = memoryview(data)
return bytes(mv[start:end])
def set_slice(data: bytearray, start: int, values: list[int]) -> None:
"""Set a slice of bytes using memoryview."""
mv = memoryview(data)
for i, v in enumerate(values):
if start + i < len(mv):
mv[start + i] = v
def copy_region(
src: bytearray, src_start: int, dst: bytearray, dst_start: int, length: int
) -> None:
"""Copy a region from source to destination."""
mv_src = memoryview(src)
mv_dst = memoryview(dst)
for i in range(length):
if src_start + i < len(mv_src) and dst_start + i < len(mv_dst):
mv_dst[dst_start + i] = mv_src[src_start + i]
def fill_region(data: bytearray, start: int, length: int, value: int) -> None:
"""Fill a region with a value."""
mv = memoryview(data)
for i in range(length):
if start + i < len(mv):
mv[start + i] = value
def find_byte(data: bytearray, value: int) -> int:
"""Find first occurrence of a byte value."""
mv = memoryview(data)
for i in range(len(mv)):
if mv[i] == value:
return i
return -1
def find_pattern(data: bytearray, pattern: list[int]) -> int:
"""Find first occurrence of a byte pattern."""
if len(pattern) == 0:
return 0
mv = memoryview(data)
for i in range(len(mv) - len(pattern) + 1):
found = True
for j, p in enumerate(pattern):
if mv[i + j] != p:
found = False
break
if found:
return i
return -1
def count_byte(data: bytearray, value: int) -> int:
"""Count occurrences of a byte value."""
mv = memoryview(data)
count = 0
for i in range(len(mv)):
if mv[i] == value:
count += 1
return count
def reverse_bytes(data: bytearray) -> bytearray:
"""Reverse byte order."""
mv = memoryview(data)
result = bytearray(len(mv))
for i in range(len(mv)):
result[len(mv) - 1 - i] = mv[i]
return result
def xor_bytes(data1: bytearray, data2: bytearray) -> bytearray:
"""XOR two bytearrays."""
length = min(len(data1), len(data2))
mv1 = memoryview(data1)
mv2 = memoryview(data2)
result = bytearray(length)
for i in range(length):
result[i] = mv1[i] ^ mv2[i]
return result
def and_bytes(data1: bytearray, data2: bytearray) -> bytearray:
"""AND two bytearrays."""
length = min(len(data1), len(data2))
mv1 = memoryview(data1)
mv2 = memoryview(data2)
result = bytearray(length)
for i in range(length):
result[i] = mv1[i] & mv2[i]
return result
def or_bytes(data1: bytearray, data2: bytearray) -> bytearray:
"""OR two bytearrays."""
length = min(len(data1), len(data2))
mv1 = memoryview(data1)
mv2 = memoryview(data2)
result = bytearray(length)
for i in range(length):
result[i] = mv1[i] | mv2[i]
return result
def not_bytes(data: bytearray) -> bytearray:
"""NOT (complement) a bytearray."""
mv = memoryview(data)
result = bytearray(len(mv))
for i in range(len(mv)):
result[i] = (~mv[i]) & 0xFF
return result
def compare_bytes(data1: bytearray, data2: bytearray) -> int:
"""Compare two bytearrays lexicographically."""
mv1 = memoryview(data1)
mv2 = memoryview(data2)
min_len = min(len(mv1), len(mv2))
for i in range(min_len):
if mv1[i] < mv2[i]:
return -1
if mv1[i] > mv2[i]:
return 1
if len(mv1) < len(mv2):
return -1
if len(mv1) > len(mv2):
return 1
return 0
def sum_bytes(data: bytearray) -> int:
"""Sum all byte values."""
mv = memoryview(data)
total = 0
for i in range(len(mv)):
total += mv[i]
return total
def checksum_xor(data: bytearray) -> int:
"""Calculate XOR checksum."""
mv = memoryview(data)
result = 0
for i in range(len(mv)):
result ^= mv[i]
return result
def checksum_add(data: bytearray) -> int:
"""Calculate additive checksum (mod 256)."""
mv = memoryview(data)
result = 0
for i in range(len(mv)):
result = (result + mv[i]) & 0xFF
return result
def rotate_bytes_left(data: bytearray, count: int) -> bytearray:
"""Rotate bytes left."""
if len(data) == 0:
return bytearray()
count = count % len(data)
mv = memoryview(data)
result = bytearray(len(mv))
for i in range(len(mv)):
result[i] = mv[(i + count) % len(mv)]
return result
def rotate_bytes_right(data: bytearray, count: int) -> bytearray:
"""Rotate bytes right."""
if len(data) == 0:
return bytearray()
count = count % len(data)
return rotate_bytes_left(data, len(data) - count)
def interleave_bytes(data1: bytearray, data2: bytearray) -> bytearray:
"""Interleave bytes from two arrays."""
mv1 = memoryview(data1)
mv2 = memoryview(data2)
min_len = min(len(mv1), len(mv2))
result = bytearray(min_len * 2)
for i in range(min_len):
result[i * 2] = mv1[i]
result[i * 2 + 1] = mv2[i]
return result
def deinterleave_bytes(data: bytearray) -> tuple[bytearray, bytearray]:
"""Deinterleave bytes into two arrays."""
mv = memoryview(data)
length = len(mv) // 2
result1 = bytearray(length)
result2 = bytearray(length)
for i in range(length):
result1[i] = mv[i * 2]
result2[i] = mv[i * 2 + 1]
return (result1, result2)
def pack_nibbles(high: int, low: int) -> int:
"""Pack two nibbles into a byte."""
return ((high & 0xF) << 4) | (low & 0xF)
def unpack_nibbles(byte: int) -> tuple[int, int]:
"""Unpack a byte into two nibbles."""
return ((byte >> 4) & 0xF, byte & 0xF)
def swap_nibbles(byte: int) -> int:
"""Swap high and low nibbles of a byte."""
return ((byte & 0x0F) << 4) | ((byte >> 4) & 0x0F)
def get_memoryview_info(data: bytearray) -> dict[str, object]:
"""Get memoryview properties."""
mv = memoryview(data)
return {
"nbytes": mv.nbytes,
"readonly": mv.readonly,
"itemsize": mv.itemsize,
"ndim": mv.ndim,
"shape": mv.shape,
"format": mv.format,
}
def main() -> int:
parser = argparse.ArgumentParser(description="Memoryview operations CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create bytearray")
create_p.add_argument("size", type=int)
create_p.add_argument("--fill", type=int, default=0)
# slice
slice_p = subparsers.add_parser("slice", help="Get slice of hex data")
slice_p.add_argument("hex_data")
slice_p.add_argument("start", type=int)
slice_p.add_argument("end", type=int)
# xor
xor_p = subparsers.add_parser("xor", help="XOR two hex values")
xor_p.add_argument("hex1")
xor_p.add_argument("hex2")
# checksum
chk_p = subparsers.add_parser("checksum", help="Calculate checksum")
chk_p.add_argument("hex_data")
chk_p.add_argument("--type", choices=["xor", "add"], default="xor")
args = parser.parse_args()
if args.command == "create":
data = create_bytearray(args.size, args.fill)
print(f"Created: {data.hex()}")
elif args.command == "slice":
data = bytearray.fromhex(args.hex_data)
result = get_slice(data, args.start, args.end)
print(f"Slice: {result.hex()}")
elif args.command == "xor":
data1 = bytearray.fromhex(args.hex1)
data2 = bytearray.fromhex(args.hex2)
result = xor_bytes(data1, data2)
print(f"XOR result: {result.hex()}")
elif args.command == "checksum":
data = bytearray.fromhex(args.hex_data)
if args.type == "xor":
result = checksum_xor(data)
else:
result = checksum_add(data)
print(f"Checksum: {result:02x}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_memoryview_ops/memoryview_ops_cli.py (8577 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_memoryview_ops/memoryview_ops_cli.rs (16525 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_memoryview_ops/Cargo.toml (1 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 147.0 KB/s
⏱️ Total time: 57ms
| true
|
memoryview_ops
| 313
| 6
|
[
"context_manager"
] | 0.652
| null |
example_memoryview_ops
|
test_memoryview_ops_cli.py
|
"""Tests for memoryview_ops_cli.py"""
from memoryview_ops_cli import (
and_bytes,
checksum_add,
checksum_xor,
compare_bytes,
copy_region,
count_byte,
create_bytearray,
create_from_list,
deinterleave_bytes,
fill_region,
find_byte,
find_pattern,
get_memoryview_info,
get_slice,
interleave_bytes,
not_bytes,
or_bytes,
pack_nibbles,
reverse_bytes,
rotate_bytes_left,
rotate_bytes_right,
set_slice,
sum_bytes,
swap_nibbles,
unpack_nibbles,
xor_bytes,
)
class TestCreate:
def test_create_bytearray_zeros(self):
data = create_bytearray(5)
assert len(data) == 5
assert all(b == 0 for b in data)
def test_create_bytearray_fill(self):
data = create_bytearray(3, 0xFF)
assert len(data) == 3
assert all(b == 0xFF for b in data)
def test_create_from_list(self):
data = create_from_list([1, 2, 3])
assert list(data) == [1, 2, 3]
class TestSlice:
def test_get_slice(self):
data = bytearray([0, 1, 2, 3, 4])
result = get_slice(data, 1, 4)
assert result == bytes([1, 2, 3])
def test_set_slice(self):
data = bytearray([0, 0, 0, 0])
set_slice(data, 1, [5, 6])
assert list(data) == [0, 5, 6, 0]
class TestCopyFill:
def test_copy_region(self):
src = bytearray([1, 2, 3, 4, 5])
dst = bytearray([0, 0, 0, 0, 0])
copy_region(src, 1, dst, 2, 2)
assert list(dst) == [0, 0, 2, 3, 0]
def test_fill_region(self):
data = bytearray([0, 0, 0, 0])
fill_region(data, 1, 2, 0xFF)
assert list(data) == [0, 0xFF, 0xFF, 0]
class TestFind:
def test_find_byte(self):
data = bytearray([1, 2, 3, 2, 1])
assert find_byte(data, 2) == 1
assert find_byte(data, 5) == -1
def test_find_pattern(self):
data = bytearray([1, 2, 3, 4, 2, 3, 5])
assert find_pattern(data, [2, 3]) == 1
assert find_pattern(data, [5, 6]) == -1
def test_find_empty_pattern(self):
data = bytearray([1, 2, 3])
assert find_pattern(data, []) == 0
def test_count_byte(self):
data = bytearray([1, 2, 2, 3, 2])
assert count_byte(data, 2) == 3
assert count_byte(data, 5) == 0
class TestReverse:
def test_reverse_bytes(self):
data = bytearray([1, 2, 3, 4])
result = reverse_bytes(data)
assert list(result) == [4, 3, 2, 1]
def test_reverse_empty(self):
data = bytearray([])
result = reverse_bytes(data)
assert list(result) == []
class TestBitwiseOps:
def test_xor_bytes(self):
data1 = bytearray([0xFF, 0x00, 0xAA])
data2 = bytearray([0x0F, 0xF0, 0x55])
result = xor_bytes(data1, data2)
assert list(result) == [0xF0, 0xF0, 0xFF]
def test_and_bytes(self):
data1 = bytearray([0xFF, 0x0F, 0xAA])
data2 = bytearray([0x0F, 0xFF, 0x55])
result = and_bytes(data1, data2)
assert list(result) == [0x0F, 0x0F, 0x00]
def test_or_bytes(self):
data1 = bytearray([0xF0, 0x0F, 0xAA])
data2 = bytearray([0x0F, 0xF0, 0x55])
result = or_bytes(data1, data2)
assert list(result) == [0xFF, 0xFF, 0xFF]
def test_not_bytes(self):
data = bytearray([0x00, 0xFF, 0xAA])
result = not_bytes(data)
assert list(result) == [0xFF, 0x00, 0x55]
class TestCompare:
def test_equal(self):
data1 = bytearray([1, 2, 3])
data2 = bytearray([1, 2, 3])
assert compare_bytes(data1, data2) == 0
def test_less(self):
data1 = bytearray([1, 2, 3])
data2 = bytearray([1, 2, 4])
assert compare_bytes(data1, data2) == -1
def test_greater(self):
data1 = bytearray([1, 2, 4])
data2 = bytearray([1, 2, 3])
assert compare_bytes(data1, data2) == 1
def test_shorter(self):
data1 = bytearray([1, 2])
data2 = bytearray([1, 2, 3])
assert compare_bytes(data1, data2) == -1
class TestSumChecksum:
def test_sum_bytes(self):
data = bytearray([1, 2, 3, 4])
assert sum_bytes(data) == 10
def test_checksum_xor(self):
data = bytearray([0x12, 0x34, 0x56])
expected = 0x12 ^ 0x34 ^ 0x56
assert checksum_xor(data) == expected
def test_checksum_add(self):
data = bytearray([100, 100, 100])
assert checksum_add(data) == (300 & 0xFF)
class TestRotate:
def test_rotate_left(self):
data = bytearray([1, 2, 3, 4])
result = rotate_bytes_left(data, 1)
assert list(result) == [2, 3, 4, 1]
def test_rotate_right(self):
data = bytearray([1, 2, 3, 4])
result = rotate_bytes_right(data, 1)
assert list(result) == [4, 1, 2, 3]
def test_rotate_empty(self):
data = bytearray([])
assert list(rotate_bytes_left(data, 1)) == []
class TestInterleave:
def test_interleave(self):
data1 = bytearray([1, 2, 3])
data2 = bytearray([4, 5, 6])
result = interleave_bytes(data1, data2)
assert list(result) == [1, 4, 2, 5, 3, 6]
def test_deinterleave(self):
data = bytearray([1, 4, 2, 5, 3, 6])
result1, result2 = deinterleave_bytes(data)
assert list(result1) == [1, 2, 3]
assert list(result2) == [4, 5, 6]
def test_roundtrip(self):
data1 = bytearray([1, 2, 3])
data2 = bytearray([4, 5, 6])
interleaved = interleave_bytes(data1, data2)
r1, r2 = deinterleave_bytes(interleaved)
assert list(r1) == list(data1)
assert list(r2) == list(data2)
class TestNibbles:
def test_pack_nibbles(self):
assert pack_nibbles(0xA, 0xB) == 0xAB
def test_unpack_nibbles(self):
assert unpack_nibbles(0xAB) == (0xA, 0xB)
def test_swap_nibbles(self):
assert swap_nibbles(0xAB) == 0xBA
def test_roundtrip(self):
for high in range(16):
for low in range(16):
packed = pack_nibbles(high, low)
h, l = unpack_nibbles(packed)
assert h == high
assert l == low
class TestMemoryviewInfo:
def test_info(self):
data = bytearray([1, 2, 3, 4])
info = get_memoryview_info(data)
assert info["nbytes"] == 4
assert info["readonly"] is False
assert info["itemsize"] == 1
assert info["ndim"] == 1
class TestEdgeCases:
def test_empty_bytearray(self):
data = bytearray([])
assert sum_bytes(data) == 0
assert checksum_xor(data) == 0
assert find_byte(data, 0) == -1
def test_single_byte(self):
data = bytearray([42])
assert sum_bytes(data) == 42
assert checksum_xor(data) == 42
assert find_byte(data, 42) == 0
def test_xor_different_lengths(self):
data1 = bytearray([1, 2, 3])
data2 = bytearray([4, 5])
result = xor_bytes(data1, data2)
assert len(result) == 2
| false
|
memoryview_ops
| 253
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Var("b"), right: Literal(Int(0)) }, generators: [HirComprehension { target: "b", iter: Var("data"), conditions: [] }] }
|
|
example_merge_sort
|
sort_cli.py
|
#!/usr/bin/env python3
"""Merge sort CLI.
Various sorting algorithms with different strategies.
"""
import argparse
import sys
from collections.abc import Callable
def merge_sort(arr: list, key: Callable | None = None, reverse: bool = False) -> list:
"""Classic merge sort with optional key function."""
if len(arr) <= 1:
return arr.copy()
mid = len(arr) // 2
left = merge_sort(arr[:mid], key, reverse)
right = merge_sort(arr[mid:], key, reverse)
return merge(left, right, key, reverse)
def merge(left: list, right: list, key: Callable | None = None, reverse: bool = False) -> list:
"""Merge two sorted arrays."""
result = []
i = j = 0
while i < len(left) and j < len(right):
left_val = key(left[i]) if key else left[i]
right_val = key(right[j]) if key else right[j]
if reverse:
if left_val >= right_val:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
else:
if left_val <= right_val:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort_inplace(arr: list, start: int = 0, end: int | None = None) -> None:
"""In-place merge sort (modifies original array)."""
if end is None:
end = len(arr)
if end - start <= 1:
return
mid = (start + end) // 2
merge_sort_inplace(arr, start, mid)
merge_sort_inplace(arr, mid, end)
merge_inplace(arr, start, mid, end)
def merge_inplace(arr: list, start: int, mid: int, end: int) -> None:
"""Merge two sorted subarrays in place."""
left = arr[start:mid]
right = arr[mid:end]
i = j = 0
k = start
while i < len(left) and j < len(right):
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
def merge_sort_iterative(arr: list) -> list:
"""Bottom-up iterative merge sort."""
if len(arr) <= 1:
return arr.copy()
result = arr.copy()
width = 1
while width < len(result):
i = 0
while i < len(result):
left = i
mid = min(i + width, len(result))
right = min(i + 2 * width, len(result))
merged = merge(result[left:mid], result[mid:right])
result[left : left + len(merged)] = merged
i += 2 * width
width *= 2
return result
def natural_merge_sort(arr: list) -> list:
"""Natural merge sort - takes advantage of existing runs."""
if len(arr) <= 1:
return arr.copy()
runs = find_runs(arr)
while len(runs) > 1:
new_runs = []
i = 0
while i < len(runs):
if i + 1 < len(runs):
merged = merge(runs[i], runs[i + 1])
new_runs.append(merged)
i += 2
else:
new_runs.append(runs[i])
i += 1
runs = new_runs
return runs[0] if runs else []
def find_runs(arr: list) -> list[list]:
"""Find natural runs in the array."""
if not arr:
return []
runs = []
current_run = [arr[0]]
for i in range(1, len(arr)):
if arr[i] >= arr[i - 1]:
current_run.append(arr[i])
else:
runs.append(current_run)
current_run = [arr[i]]
runs.append(current_run)
return runs
def count_inversions(arr: list) -> tuple[list, int]:
"""Count inversions using merge sort."""
if len(arr) <= 1:
return arr.copy(), 0
mid = len(arr) // 2
left, left_inv = count_inversions(arr[:mid])
right, right_inv = count_inversions(arr[mid:])
merged, split_inv = merge_count(left, right)
return merged, left_inv + right_inv + split_inv
def merge_count(left: list, right: list) -> tuple[list, int]:
"""Merge and count split inversions."""
result = []
inversions = 0
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
inversions += len(left) - i
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result, inversions
def is_sorted(arr: list, reverse: bool = False) -> bool:
"""Check if array is sorted."""
if len(arr) <= 1:
return True
for i in range(1, len(arr)):
if reverse:
if arr[i] > arr[i - 1]:
return False
else:
if arr[i] < arr[i - 1]:
return False
return True
def merge_k_sorted(arrays: list[list]) -> list:
"""Merge k sorted arrays."""
if not arrays:
return []
while len(arrays) > 1:
merged = []
i = 0
while i < len(arrays):
if i + 1 < len(arrays):
merged.append(merge(arrays[i], arrays[i + 1]))
i += 2
else:
merged.append(arrays[i])
i += 1
arrays = merged
return arrays[0]
def main() -> int:
parser = argparse.ArgumentParser(description="Merge sort operations")
parser.add_argument("values", nargs="*", type=int, help="Values to sort")
parser.add_argument(
"--mode",
choices=["sort", "inplace", "iterative", "natural", "inversions", "check"],
default="sort",
help="Sort mode",
)
parser.add_argument("--reverse", action="store_true", help="Sort in reverse order")
args = parser.parse_args()
if not args.values:
values = [int(x) for x in sys.stdin.read().split()]
else:
values = args.values
if args.mode == "sort":
result = merge_sort(values, reverse=args.reverse)
print(" ".join(map(str, result)))
elif args.mode == "inplace":
merge_sort_inplace(values)
if args.reverse:
values.reverse()
print(" ".join(map(str, values)))
elif args.mode == "iterative":
result = merge_sort_iterative(values)
if args.reverse:
result.reverse()
print(" ".join(map(str, result)))
elif args.mode == "natural":
result = natural_merge_sort(values)
if args.reverse:
result.reverse()
print(" ".join(map(str, result)))
elif args.mode == "inversions":
_, inv_count = count_inversions(values)
print(f"Inversions: {inv_count}")
elif args.mode == "check":
if is_sorted(values, args.reverse):
print("Sorted: Yes")
else:
print("Sorted: No")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
merge_sort
| 278
| 0
|
[
"context_manager",
"stdin_usage"
] | 0.652
|
Error: Expression type not yet supported
|
|
example_merge_sort
|
test_sort_cli.py
|
"""Tests for sort_cli.py"""
from sort_cli import (
count_inversions,
find_runs,
is_sorted,
merge,
merge_k_sorted,
merge_sort,
merge_sort_inplace,
merge_sort_iterative,
natural_merge_sort,
)
class TestMergeSort:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = merge_sort(arr)
assert result == [1, 1, 2, 3, 4, 5, 6, 9]
def test_empty(self):
assert merge_sort([]) == []
def test_single(self):
assert merge_sort([5]) == [5]
def test_already_sorted(self):
arr = [1, 2, 3, 4, 5]
assert merge_sort(arr) == [1, 2, 3, 4, 5]
def test_reverse_sorted(self):
arr = [5, 4, 3, 2, 1]
assert merge_sort(arr) == [1, 2, 3, 4, 5]
def test_duplicates(self):
arr = [3, 3, 3, 1, 1, 2, 2]
assert merge_sort(arr) == [1, 1, 2, 2, 3, 3, 3]
def test_reverse_flag(self):
arr = [3, 1, 4, 1, 5]
result = merge_sort(arr, reverse=True)
assert result == [5, 4, 3, 1, 1]
def test_with_key(self):
arr = ["aaa", "b", "cc"]
result = merge_sort(arr, key=len)
assert result == ["b", "cc", "aaa"]
def test_negative(self):
arr = [-3, 1, -4, 1, 5]
assert merge_sort(arr) == [-4, -3, 1, 1, 5]
def test_original_unchanged(self):
arr = [3, 1, 4]
merge_sort(arr)
assert arr == [3, 1, 4]
class TestMerge:
def test_basic(self):
left = [1, 3, 5]
right = [2, 4, 6]
assert merge(left, right) == [1, 2, 3, 4, 5, 6]
def test_empty_left(self):
assert merge([], [1, 2, 3]) == [1, 2, 3]
def test_empty_right(self):
assert merge([1, 2, 3], []) == [1, 2, 3]
def test_both_empty(self):
assert merge([], []) == []
def test_unequal_lengths(self):
assert merge([1, 5], [2, 3, 4, 6]) == [1, 2, 3, 4, 5, 6]
def test_reverse(self):
left = [5, 3, 1]
right = [6, 4, 2]
assert merge(left, right, reverse=True) == [6, 5, 4, 3, 2, 1]
class TestMergeSortInplace:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
merge_sort_inplace(arr)
assert arr == [1, 1, 2, 3, 4, 5, 6, 9]
def test_empty(self):
arr = []
merge_sort_inplace(arr)
assert arr == []
def test_single(self):
arr = [5]
merge_sort_inplace(arr)
assert arr == [5]
def test_partial_range(self):
arr = [9, 3, 1, 4, 5, 2, 8]
merge_sort_inplace(arr, 1, 5)
assert arr == [9, 1, 3, 4, 5, 2, 8]
class TestMergeSortIterative:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = merge_sort_iterative(arr)
assert result == [1, 1, 2, 3, 4, 5, 6, 9]
def test_empty(self):
assert merge_sort_iterative([]) == []
def test_single(self):
assert merge_sort_iterative([5]) == [5]
def test_power_of_two(self):
arr = [8, 4, 6, 2, 1, 7, 3, 5]
assert merge_sort_iterative(arr) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_non_power_of_two(self):
arr = [5, 2, 8, 1, 9]
assert merge_sort_iterative(arr) == [1, 2, 5, 8, 9]
class TestNaturalMergeSort:
def test_basic(self):
arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = natural_merge_sort(arr)
assert result == [1, 1, 2, 3, 4, 5, 6, 9]
def test_empty(self):
assert natural_merge_sort([]) == []
def test_single(self):
assert natural_merge_sort([5]) == [5]
def test_already_sorted(self):
arr = [1, 2, 3, 4, 5]
assert natural_merge_sort(arr) == [1, 2, 3, 4, 5]
def test_natural_runs(self):
arr = [1, 2, 3, 0, 4, 5] # Two natural runs
assert natural_merge_sort(arr) == [0, 1, 2, 3, 4, 5]
class TestFindRuns:
def test_basic(self):
arr = [1, 2, 3, 0, 4, 5]
runs = find_runs(arr)
assert runs == [[1, 2, 3], [0, 4, 5]]
def test_empty(self):
assert find_runs([]) == []
def test_single(self):
assert find_runs([5]) == [[5]]
def test_sorted(self):
assert find_runs([1, 2, 3, 4]) == [[1, 2, 3, 4]]
def test_reverse_sorted(self):
runs = find_runs([4, 3, 2, 1])
assert runs == [[4], [3], [2], [1]]
class TestCountInversions:
def test_sorted(self):
_, count = count_inversions([1, 2, 3, 4, 5])
assert count == 0
def test_reverse_sorted(self):
_, count = count_inversions([5, 4, 3, 2, 1])
assert count == 10 # n*(n-1)/2 for fully reversed
def test_one_inversion(self):
_, count = count_inversions([1, 3, 2, 4])
assert count == 1
def test_empty(self):
_, count = count_inversions([])
assert count == 0
def test_single(self):
_, count = count_inversions([5])
assert count == 0
def test_result_sorted(self):
result, _ = count_inversions([3, 1, 4, 1, 5])
assert result == [1, 1, 3, 4, 5]
class TestIsSorted:
def test_sorted(self):
assert is_sorted([1, 2, 3, 4, 5]) is True
def test_not_sorted(self):
assert is_sorted([1, 3, 2, 4, 5]) is False
def test_empty(self):
assert is_sorted([]) is True
def test_single(self):
assert is_sorted([5]) is True
def test_reverse_sorted(self):
assert is_sorted([5, 4, 3, 2, 1], reverse=True) is True
def test_reverse_not_sorted(self):
assert is_sorted([5, 3, 4, 2, 1], reverse=True) is False
def test_duplicates(self):
assert is_sorted([1, 2, 2, 3, 3, 3]) is True
class TestMergeKSorted:
def test_basic(self):
arrays = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
assert merge_k_sorted(arrays) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_empty(self):
assert merge_k_sorted([]) == []
def test_single_array(self):
assert merge_k_sorted([[1, 2, 3]]) == [1, 2, 3]
def test_two_arrays(self):
arrays = [[1, 3, 5], [2, 4, 6]]
assert merge_k_sorted(arrays) == [1, 2, 3, 4, 5, 6]
def test_unequal_lengths(self):
arrays = [[1, 2], [3], [4, 5, 6, 7]]
assert merge_k_sorted(arrays) == [1, 2, 3, 4, 5, 6, 7]
def test_with_empty_arrays(self):
arrays = [[1, 3], [], [2, 4]]
assert merge_k_sorted(arrays) == [1, 2, 3, 4]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_merge_sort/test_sort_cli.py (6337 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_merge_sort/test_sort_cli.rs (10086 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 115.1 KB/s
⏱️ Total time: 53ms
| true
|
merge_sort
| 238
| 5
|
[
"class_definition",
"functools"
] | 0.612
| null |
example_minmax
|
minmax_tool.py
|
#!/usr/bin/env python3
"""Minmax Example - Min/max operations CLI.
Examples:
>>> find_min(5, 3, 8, 1, 9)
1
>>> find_max(5, 3, 8, 1, 9)
9
>>> clamp(15, 0, 10)
10
"""
import argparse
def find_min(a: int, b: int, c: int, d: int, e: int) -> int:
"""Find minimum of five integers.
>>> find_min(1, 2, 3, 4, 5)
1
>>> find_min(5, 4, 3, 2, 1)
1
>>> find_min(3, 1, 4, 1, 5)
1
"""
result = a
if b < result:
result = b
if c < result:
result = c
if d < result:
result = d
if e < result:
result = e
return result
def find_max(a: int, b: int, c: int, d: int, e: int) -> int:
"""Find maximum of five integers.
>>> find_max(1, 2, 3, 4, 5)
5
>>> find_max(5, 4, 3, 2, 1)
5
>>> find_max(3, 1, 4, 1, 5)
5
"""
result = a
if b > result:
result = b
if c > result:
result = c
if d > result:
result = d
if e > result:
result = e
return result
def clamp(val: int, lo: int, hi: int) -> int:
"""Clamp value to range [lo, hi].
>>> clamp(5, 0, 10)
5
>>> clamp(-5, 0, 10)
0
>>> clamp(15, 0, 10)
10
"""
result = val
if result < lo:
result = lo
if result > hi:
result = hi
return result
def main():
parser = argparse.ArgumentParser(description="Min/max tool")
subs = parser.add_subparsers(dest="cmd", required=True)
m = subs.add_parser("min")
m.add_argument("a", type=int)
m.add_argument("b", type=int)
m.add_argument("c", type=int)
m.add_argument("d", type=int)
m.add_argument("e", type=int)
x = subs.add_parser("max")
x.add_argument("a", type=int)
x.add_argument("b", type=int)
x.add_argument("c", type=int)
x.add_argument("d", type=int)
x.add_argument("e", type=int)
cl = subs.add_parser("clamp")
cl.add_argument("val", type=int)
cl.add_argument("lo", type=int)
cl.add_argument("hi", type=int)
args = parser.parse_args()
if args.cmd == "min":
print(find_min(args.a, args.b, args.c, args.d, args.e))
elif args.cmd == "max":
print(find_max(args.a, args.b, args.c, args.d, args.e))
elif args.cmd == "clamp":
print(clamp(args.val, args.lo, args.hi))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_minmax/minmax_tool.py (2346 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_minmax/minmax_tool.rs (3525 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_minmax/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 46.3 KB/s
⏱️ Total time: 49ms
| true
|
minmax
| 109
| 6
|
[] | 0
| null |
example_minmax
|
test_minmax_tool.py
|
"""Tests for minmax_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "minmax_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_min():
r = run("min 5 3 8 1 9")
assert r.returncode == 0
assert r.stdout.strip() == "1"
def test_max():
r = run("max 5 3 8 1 9")
assert r.returncode == 0
assert r.stdout.strip() == "9"
def test_clamp():
r = run("clamp 15 0 10")
assert r.returncode == 0
assert r.stdout.strip() == "10"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_minmax/test_minmax_tool.py (619 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_minmax/test_minmax_tool.rs (1826 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_minmax/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 12.8 KB/s
⏱️ Total time: 47ms
| true
|
minmax
| 32
| 6
|
[] | 0
| null |
example_msgpack_lite
|
msgpack_cli.py
|
#!/usr/bin/env python3
"""MessagePack-lite codec CLI.
Simple binary serialization format (subset of MessagePack).
"""
import argparse
import json
import struct
import sys
# Format codes (simplified MessagePack subset)
FMT_NIL = 0xC0
FMT_FALSE = 0xC2
FMT_TRUE = 0xC3
FMT_UINT8 = 0xCC
FMT_UINT16 = 0xCD
FMT_UINT32 = 0xCE
FMT_INT8 = 0xD0
FMT_INT16 = 0xD1
FMT_INT32 = 0xD2
FMT_STR8 = 0xD9
FMT_STR16 = 0xDA
FMT_ARRAY16 = 0xDC
FMT_MAP16 = 0xDE
def encode_nil() -> bytes:
"""Encode None."""
return bytes([FMT_NIL])
def encode_bool(value: bool) -> bytes:
"""Encode boolean."""
return bytes([FMT_TRUE if value else FMT_FALSE])
def encode_int(value: int) -> bytes:
"""Encode integer."""
if 0 <= value <= 127:
# Positive fixint
return bytes([value])
if -32 <= value < 0:
# Negative fixint
return bytes([value & 0xFF])
if 0 <= value <= 255:
return bytes([FMT_UINT8, value])
if 0 <= value <= 65535:
return bytes([FMT_UINT16]) + struct.pack(">H", value)
if 0 <= value <= 4294967295:
return bytes([FMT_UINT32]) + struct.pack(">I", value)
if -128 <= value < 0:
return bytes([FMT_INT8]) + struct.pack(">b", value)
if -32768 <= value < 0:
return bytes([FMT_INT16]) + struct.pack(">h", value)
if -2147483648 <= value < 0:
return bytes([FMT_INT32]) + struct.pack(">i", value)
raise ValueError(f"Integer out of range: {value}")
def encode_string(value: str) -> bytes:
"""Encode string."""
encoded = value.encode("utf-8")
length = len(encoded)
if length <= 31:
# Fixstr
return bytes([0xA0 | length]) + encoded
if length <= 255:
return bytes([FMT_STR8, length]) + encoded
if length <= 65535:
return bytes([FMT_STR16]) + struct.pack(">H", length) + encoded
raise ValueError(f"String too long: {length}")
def encode_array(value: list) -> bytes:
"""Encode array."""
length = len(value)
if length <= 15:
# Fixarray
result = bytes([0x90 | length])
elif length <= 65535:
result = bytes([FMT_ARRAY16]) + struct.pack(">H", length)
else:
raise ValueError(f"Array too long: {length}")
for item in value:
result += msgpack_encode(item)
return result
def encode_map(value: dict) -> bytes:
"""Encode map/dict."""
length = len(value)
if length <= 15:
# Fixmap
result = bytes([0x80 | length])
elif length <= 65535:
result = bytes([FMT_MAP16]) + struct.pack(">H", length)
else:
raise ValueError(f"Map too long: {length}")
for k, v in value.items():
result += msgpack_encode(str(k))
result += msgpack_encode(v)
return result
def msgpack_encode(value) -> bytes:
"""Encode Python value to msgpack-lite."""
if value is None:
return encode_nil()
if isinstance(value, bool):
return encode_bool(value)
if isinstance(value, int):
return encode_int(value)
if isinstance(value, str):
return encode_string(value)
if isinstance(value, list):
return encode_array(value)
if isinstance(value, dict):
return encode_map(value)
raise ValueError(f"Cannot encode type: {type(value)}")
class MsgPackDecoder:
"""Stateful decoder."""
def __init__(self, data: bytes):
self.data = data
self.pos = 0
def read_bytes(self, n: int) -> bytes:
"""Read n bytes."""
if self.pos + n > len(self.data):
raise ValueError("Unexpected end of data")
result = self.data[self.pos : self.pos + n]
self.pos += n
return result
def decode(self):
"""Decode next value."""
byte = self.read_bytes(1)[0]
# Nil
if byte == FMT_NIL:
return None
# Bool
if byte == FMT_FALSE:
return False
if byte == FMT_TRUE:
return True
# Positive fixint (0-127)
if byte <= 0x7F:
return byte
# Negative fixint
if byte >= 0xE0:
return byte - 256
# Fixstr
if 0xA0 <= byte <= 0xBF:
length = byte & 0x1F
return self.read_bytes(length).decode("utf-8")
# Fixarray
if 0x90 <= byte <= 0x9F:
length = byte & 0x0F
return [self.decode() for _ in range(length)]
# Fixmap
if 0x80 <= byte <= 0x8F:
length = byte & 0x0F
return {self.decode(): self.decode() for _ in range(length)}
# Extended formats
if byte == FMT_UINT8:
return self.read_bytes(1)[0]
if byte == FMT_UINT16:
return struct.unpack(">H", self.read_bytes(2))[0]
if byte == FMT_UINT32:
return struct.unpack(">I", self.read_bytes(4))[0]
if byte == FMT_INT8:
return struct.unpack(">b", self.read_bytes(1))[0]
if byte == FMT_INT16:
return struct.unpack(">h", self.read_bytes(2))[0]
if byte == FMT_INT32:
return struct.unpack(">i", self.read_bytes(4))[0]
if byte == FMT_STR8:
length = self.read_bytes(1)[0]
return self.read_bytes(length).decode("utf-8")
if byte == FMT_STR16:
length = struct.unpack(">H", self.read_bytes(2))[0]
return self.read_bytes(length).decode("utf-8")
if byte == FMT_ARRAY16:
length = struct.unpack(">H", self.read_bytes(2))[0]
return [self.decode() for _ in range(length)]
if byte == FMT_MAP16:
length = struct.unpack(">H", self.read_bytes(2))[0]
return {self.decode(): self.decode() for _ in range(length)}
raise ValueError(f"Unknown format: 0x{byte:02X}")
def msgpack_decode(data: bytes):
"""Decode msgpack-lite data."""
decoder = MsgPackDecoder(data)
return decoder.decode()
def calculate_size(value) -> int:
"""Calculate encoded size without encoding."""
return len(msgpack_encode(value))
def main() -> int:
parser = argparse.ArgumentParser(description="Encode and decode msgpack-lite format")
parser.add_argument("input", nargs="?", help="Input file (- for stdin)")
parser.add_argument("-e", "--encode", action="store_true", help="Encode JSON to msgpack")
parser.add_argument("-d", "--decode", action="store_true", help="Decode msgpack to JSON")
parser.add_argument("--size", action="store_true", help="Show encoded size")
parser.add_argument("-o", "--output", help="Output file")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
if args.encode or args.size:
data = sys.stdin.read()
else:
data = sys.stdin.buffer.read()
else:
if args.encode or args.size:
with open(args.input) as f:
data = f.read()
else:
with open(args.input, "rb") as f:
data = f.read()
# Process
if args.size:
try:
obj = json.loads(data)
size = calculate_size(obj)
json_size = len(data.encode("utf-8"))
print(f"JSON size: {json_size} bytes")
print(f"MsgPack size: {size} bytes")
print(f"Ratio: {size / json_size:.2%}")
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
return 1
return 0
if args.encode:
try:
obj = json.loads(data)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
return 1
try:
result = msgpack_encode(obj)
except ValueError as e:
print(f"Encode error: {e}", file=sys.stderr)
return 1
if args.output:
with open(args.output, "wb") as f:
f.write(result)
else:
sys.stdout.buffer.write(result)
elif args.decode:
try:
obj = msgpack_decode(data)
except Exception as e:
print(f"Decode error: {e}", file=sys.stderr)
return 1
result = json.dumps(obj, indent=2)
if args.output:
with open(args.output, "w") as f:
f.write(result)
else:
print(result)
else:
# Default: show hex dump of encoded data
if isinstance(data, str):
try:
obj = json.loads(data)
encoded = msgpack_encode(obj)
print(f"Size: {len(encoded)} bytes")
print(f"Hex: {encoded.hex()}")
except json.JSONDecodeError:
print("Input is not valid JSON")
return 1
else:
try:
obj = msgpack_decode(data)
print(f"Type: {type(obj).__name__}")
print(json.dumps(obj, indent=2))
except Exception as e:
print(f"Invalid msgpack: {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
msgpack_lite
| 321
| 0
|
[
"context_manager",
"class_definition",
"exception_handling",
"stdin_usage",
"multiprocessing"
] | 0.652
|
Type inference hints:
Hint: list[Any] for variable 'encoded' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'value' [High] (usage patterns suggest this type)
Hint: int for variable 'result' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'value' [High] (usage patterns suggest this type)
Hint: int for variable 'result' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for vari
|
|
example_msgpack_lite
|
test_msgpack_cli.py
|
"""Tests for msgpack_cli.py"""
from msgpack_cli import (
calculate_size,
encode_array,
encode_bool,
encode_int,
encode_map,
encode_nil,
encode_string,
msgpack_decode,
msgpack_encode,
)
class TestEncodeNil:
def test_nil(self):
assert encode_nil() == bytes([0xC0])
class TestEncodeBool:
def test_true(self):
assert encode_bool(True) == bytes([0xC3])
def test_false(self):
assert encode_bool(False) == bytes([0xC2])
class TestEncodeInt:
def test_positive_fixint(self):
assert encode_int(0) == bytes([0])
assert encode_int(127) == bytes([127])
def test_negative_fixint(self):
assert encode_int(-1) == bytes([0xFF])
assert encode_int(-32) == bytes([0xE0])
def test_uint8(self):
assert encode_int(128) == bytes([0xCC, 128])
assert encode_int(255) == bytes([0xCC, 255])
def test_uint16(self):
result = encode_int(256)
assert result[0] == 0xCD
assert len(result) == 3
def test_int8(self):
result = encode_int(-33)
assert result[0] == 0xD0
def test_int16(self):
result = encode_int(-200)
assert result[0] == 0xD1
class TestEncodeString:
def test_fixstr(self):
result = encode_string("hello")
assert result[0] == 0xA5 # 0xA0 | 5
assert result[1:] == b"hello"
def test_empty(self):
result = encode_string("")
assert result == bytes([0xA0])
def test_str8(self):
s = "a" * 32
result = encode_string(s)
assert result[0] == 0xD9
assert result[1] == 32
class TestEncodeArray:
def test_fixarray(self):
result = encode_array([1, 2, 3])
assert result[0] == 0x93 # 0x90 | 3
def test_empty(self):
result = encode_array([])
assert result == bytes([0x90])
class TestEncodeMap:
def test_fixmap(self):
result = encode_map({"a": 1})
assert result[0] == 0x81 # 0x80 | 1
def test_empty(self):
result = encode_map({})
assert result == bytes([0x80])
class TestMsgpackEncode:
def test_none(self):
assert msgpack_encode(None) == bytes([0xC0])
def test_bool(self):
assert msgpack_encode(True) == bytes([0xC3])
def test_int(self):
assert msgpack_encode(42) == bytes([42])
def test_string(self):
result = msgpack_encode("hi")
assert result == bytes([0xA2]) + b"hi"
class TestMsgpackDecode:
def test_nil(self):
assert msgpack_decode(bytes([0xC0])) is None
def test_bool(self):
assert msgpack_decode(bytes([0xC3])) is True
assert msgpack_decode(bytes([0xC2])) is False
def test_positive_fixint(self):
assert msgpack_decode(bytes([42])) == 42
def test_negative_fixint(self):
assert msgpack_decode(bytes([0xFF])) == -1
def test_fixstr(self):
assert msgpack_decode(bytes([0xA5]) + b"hello") == "hello"
def test_fixarray(self):
data = bytes([0x93, 1, 2, 3])
assert msgpack_decode(data) == [1, 2, 3]
def test_fixmap(self):
data = bytes([0x81, 0xA1]) + b"a" + bytes([1])
assert msgpack_decode(data) == {"a": 1}
class TestRoundtrip:
def test_none(self):
assert msgpack_decode(msgpack_encode(None)) is None
def test_bool(self):
assert msgpack_decode(msgpack_encode(True)) is True
def test_int(self):
for n in [0, 1, 127, 128, 255, 256, 65535, -1, -32, -128, -32768]:
assert msgpack_decode(msgpack_encode(n)) == n
def test_string(self):
for s in ["", "a", "hello", "a" * 100]:
assert msgpack_decode(msgpack_encode(s)) == s
def test_list(self):
data = [1, "two", None, True]
assert msgpack_decode(msgpack_encode(data)) == data
def test_dict(self):
data = {"name": "test", "value": 123, "active": True}
assert msgpack_decode(msgpack_encode(data)) == data
def test_nested(self):
data = {
"users": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
],
"count": 2,
}
assert msgpack_decode(msgpack_encode(data)) == data
class TestCalculateSize:
def test_simple(self):
assert calculate_size(42) == 1
assert calculate_size(None) == 1
def test_string(self):
assert calculate_size("hello") == 6 # 1 header + 5 chars
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_msgpack_lite/test_msgpack_cli.py (4488 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_msgpack_lite/test_msgpack_cli.rs (10192 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 85.2 KB/s
⏱️ Total time: 51ms
| true
|
msgpack_lite
| 174
| 5
|
[
"class_definition"
] | 0.612
| null |
example_mutually_exclusive
|
exclusive_mode.py
|
#!/usr/bin/env python3
"""
Mutually Exclusive Groups Example
Demonstrates:
- add_mutually_exclusive_group()
- Required mutually exclusive groups
- Multiple exclusive groups in one parser
This validates depyler's ability to transpile mutually exclusive
argument groups to Rust (clap conflicts_with).
"""
import argparse
def main():
"""
Main entry point demonstrating mutually exclusive groups.
Depyler: proven to terminate
"""
parser = argparse.ArgumentParser(
description="Demonstrate mutually exclusive argument groups",
prog="exclusive_mode",
)
# Optional mutually exclusive: --verbose vs --quiet
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output")
output_group.add_argument("--quiet", "-q", action="store_true", help="Suppress all output")
# Required mutually exclusive: must specify input source
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument("--input", "-i", type=str, help="Read from file")
input_group.add_argument("--stdin", action="store_true", help="Read from stdin")
input_group.add_argument("--url", "-u", type=str, help="Read from URL")
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
# Determine output mode
if args.verbose:
mode = "verbose"
elif args.quiet:
mode = "quiet"
else:
mode = "normal"
# Determine input source
if args.input:
source = f"file({args.input})"
elif args.stdin:
source = "stdin"
elif args.url:
source = f"url({args.url})"
else:
source = "none"
print(f"Mode: {mode}")
print(f"Source: {source}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/exclusive_mode.py (1854 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/exclusive_mode.rs (2040 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 37.8 KB/s
⏱️ Total time: 48ms
| true
|
mutually_exclusive
| 66
| 6
|
[
"stdin_usage"
] | 0.566
| null |
example_mutually_exclusive
|
test_exclusive_mode.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests written FIRST for mutually exclusive groups."""
import subprocess
SCRIPT = "exclusive_mode.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
cwd=__file__.rsplit("/", 1)[0],
)
class TestMutuallyExclusiveBasic:
"""Test mutually exclusive argument groups."""
def test_verbose_only(self):
result = run(["--verbose", "--stdin"])
assert result.returncode == 0
assert "Mode: verbose" in result.stdout
def test_quiet_only(self):
result = run(["--quiet", "--stdin"])
assert result.returncode == 0
assert "Mode: quiet" in result.stdout
def test_neither(self):
result = run(["--stdin"])
assert result.returncode == 0
assert "Mode: normal" in result.stdout
def test_both_fails(self):
result = run(["--verbose", "--quiet"])
assert result.returncode != 0
assert "not allowed" in result.stderr.lower()
class TestMutuallyExclusiveRequired:
"""Test required mutually exclusive groups."""
def test_input_file(self):
result = run(["--input", "data.txt"])
assert result.returncode == 0
assert "Source: file(data.txt)" in result.stdout
def test_input_stdin(self):
result = run(["--stdin"])
assert result.returncode == 0
assert "Source: stdin" in result.stdout
def test_input_url(self):
result = run(["--url", "http://example.com"])
assert result.returncode == 0
assert "Source: url(http://example.com)" in result.stdout
def test_no_input_fails(self):
# Required group - must provide one
result = run(["--verbose"])
assert result.returncode != 0
class TestHelpOutput:
"""Test help shows mutual exclusivity."""
def test_help_flag(self):
result = run(["--help"])
assert result.returncode == 0
assert "verbose" in result.stdout.lower()
assert "quiet" in result.stdout.lower()
def test_version(self):
result = run(["--version"])
assert "1.0.0" in result.stdout or "1.0.0" in result.stderr
class TestCombinations:
"""Test valid combinations."""
def test_verbose_with_file(self):
result = run(["--verbose", "--input", "test.txt"])
assert result.returncode == 0
assert "Mode: verbose" in result.stdout
assert "Source: file(test.txt)" in result.stdout
def test_quiet_with_stdin(self):
result = run(["--quiet", "--stdin"])
assert result.returncode == 0
assert "Mode: quiet" in result.stdout
assert "Source: stdin" in result.stdout
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/test_exclusive_mode.py (2771 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/test_exclusive_mode.rs (4817 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_mutually_exclusive/Cargo.toml (2 dependencies)
⏱️ Parse time: 97ms
📊 Throughput: 27.8 KB/s
⏱️ Total time: 97ms
| true
|
mutually_exclusive
| 93
| 6
|
[
"class_definition",
"stdin_usage",
"multiprocessing"
] | 0.612
| null |
example_namedtuple
|
record_tool.py
|
#!/usr/bin/env python3
"""
NamedTuple Example - Typed record structures
Demonstrates typing.NamedTuple for structured data.
"""
import argparse
import math
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
class Color(NamedTuple):
r: int
g: int
b: int
def cmd_point(args):
"""Create point. Depyler: proven to terminate"""
p = Point(x=args.x, y=args.y)
print(f"Point({p.x}, {p.y})")
if args.distance:
dist = math.sqrt(p.x**2 + p.y**2)
print(f"Distance from origin: {dist:.1f}")
def cmd_color(args):
"""Create color. Depyler: proven to terminate"""
c = Color(r=args.r, g=args.g, b=args.b)
print(f"RGB({c.r}, {c.g}, {c.b})")
def main():
parser = argparse.ArgumentParser(description="Record tool")
subparsers = parser.add_subparsers(dest="command", required=True)
pt = subparsers.add_parser("point")
pt.add_argument("x", type=int)
pt.add_argument("y", type=int)
pt.add_argument("--distance", action="store_true")
cl = subparsers.add_parser("color")
cl.add_argument("r", type=int)
cl.add_argument("g", type=int)
cl.add_argument("b", type=int)
args = parser.parse_args()
if args.command == "point":
cmd_point(args)
elif args.command == "color":
cmd_color(args)
if __name__ == "__main__":
main()
| false
|
namedtuple
| 61
| 0
|
[
"class_definition"
] | 0.612
|
Type inference hints:
Hint: str for variable 'dist' [Medium] (usage patterns suggest this type)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 97
Total estimated allocations: 0
Functions analyzed: 3
Hot Paths
[1] main (39.2% of execution time)
[2] cmd_color (22.7% of execution time)
[3] cmd_point (38.1% of execution time)
Function Metrics
🔥 main 39.2% time | 38 inst | 0 alloc
🔥 cmd_poin
|
|
example_namedtuple
|
test_record_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for NamedTuple CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "record_tool.py"
SCRIPT = "record_tool.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
cwd=__file__.rsplit("/", 1)[0])
class TestPoint:
def test_create_point(self):
result = run(["point", "10", "20"])
assert result.returncode == 0
assert "10" in result.stdout and "20" in result.stdout
def test_point_distance(self):
result = run(["point", "3", "4", "--distance"])
assert result.returncode == 0
assert "5" in result.stdout
class TestColor:
def test_create_color(self):
result = run(["color", "255", "128", "0"])
assert result.returncode == 0
assert "255" in result.stdout
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_namedtuple/test_record_tool.py (1049 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_namedtuple/test_record_tool.rs (2658 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_namedtuple/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 21.2 KB/s
⏱️ Total time: 48ms
| true
|
namedtuple
| 39
| 6
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_nargs_special
|
nargs_handler.py
|
#!/usr/bin/env python3
"""
Nargs Special Values Example
Demonstrates:
- nargs='?' - zero or one argument
- nargs='*' - zero or more arguments
- nargs='+' - one or more arguments
- const and default with nargs='?'
This validates depyler's ability to transpile nargs
to Rust (clap num_args, default_value, requires).
"""
import argparse
def main():
"""
Main entry point demonstrating nargs special values.
Depyler: proven to terminate
"""
parser = argparse.ArgumentParser(
description="Demonstrate nargs special values",
prog="nargs_handler",
)
# Required positional
parser.add_argument(
"input",
type=str,
help="Input file (required)",
)
# nargs='?' - zero or one, with const when flag present but no value
parser.add_argument(
"--output",
"-o",
nargs="?",
const="output.txt",
default="stdout",
help="Output file (default: stdout, flag only: output.txt)",
)
# nargs='*' - zero or more
parser.add_argument(
"--tags",
"-t",
nargs="*",
default=[],
help="Tags to apply (zero or more)",
)
# nargs='+' - one or more
parser.add_argument(
"--files",
"-f",
nargs="+",
help="Additional files (one or more when specified)",
)
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
print(f"Input: {args.input}")
print(f"Output: {args.output}")
print(f"Tags: {args.tags}")
if args.files:
print(f"Files: {args.files}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/nargs_handler.py (1661 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/nargs_handler.rs (1395 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 33.4 KB/s
⏱️ Total time: 48ms
| true
|
nargs_special
| 75
| 6
|
[
"context_manager"
] | 0.652
| null |
example_nargs_special
|
test_nargs_handler.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests written FIRST for nargs special values."""
import subprocess
SCRIPT = "nargs_handler.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
cwd=__file__.rsplit("/", 1)[0],
)
class TestNargsQuestion:
"""Test nargs='?' - zero or one."""
def test_output_not_provided(self):
result = run(["input.txt"])
assert result.returncode == 0
assert "Output: stdout" in result.stdout # default const
def test_output_flag_only(self):
result = run(["input.txt", "--output"])
assert result.returncode == 0
assert "Output: output.txt" in result.stdout # const value
def test_output_with_value(self):
result = run(["input.txt", "--output", "custom.txt"])
assert result.returncode == 0
assert "Output: custom.txt" in result.stdout
class TestNargsStar:
"""Test nargs='*' - zero or more."""
def test_tags_none(self):
result = run(["input.txt"])
assert result.returncode == 0
assert "Tags: []" in result.stdout
def test_tags_one(self):
result = run(["input.txt", "--tags", "foo"])
assert result.returncode == 0
assert "Tags: ['foo']" in result.stdout or "Tags: [foo]" in result.stdout
def test_tags_multiple(self):
result = run(["input.txt", "--tags", "foo", "bar", "baz"])
assert result.returncode == 0
assert "foo" in result.stdout
assert "bar" in result.stdout
class TestNargsPlus:
"""Test nargs='+' - one or more."""
def test_files_one(self):
result = run(["input.txt", "--files", "a.txt"])
assert result.returncode == 0
assert "a.txt" in result.stdout
def test_files_multiple(self):
result = run(["input.txt", "--files", "a.txt", "b.txt", "c.txt"])
assert result.returncode == 0
assert "a.txt" in result.stdout
assert "b.txt" in result.stdout
class TestPositionalRequired:
"""Test required positional argument."""
def test_input_required(self):
result = run([])
assert result.returncode != 0
def test_input_provided(self):
result = run(["myfile.txt"])
assert result.returncode == 0
assert "Input: myfile.txt" in result.stdout
class TestHelpOutput:
"""Test help text."""
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
assert "input" in result.stdout.lower()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/test_nargs_handler.py (2605 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/test_nargs_handler.rs (4858 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_nargs_special/Cargo.toml (2 dependencies)
⏱️ Parse time: 96ms
📊 Throughput: 26.4 KB/s
⏱️ Total time: 96ms
| true
|
nargs_special
| 91
| 6
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_nested_comprehension
|
nested_comprehension_cli.py
|
#!/usr/bin/env python3
"""Nested Comprehension CLI.
Nested list comprehension patterns.
"""
import argparse
import sys
def flatten_2d(matrix: list[list[int]]) -> list[int]:
"""Flatten 2D list to 1D."""
return [x for row in matrix for x in row]
def flatten_3d(cube: list[list[list[int]]]) -> list[int]:
"""Flatten 3D list to 1D."""
return [x for plane in cube for row in plane for x in row]
def flatten_with_filter(matrix: list[list[int]], threshold: int) -> list[int]:
"""Flatten and filter values above threshold."""
return [x for row in matrix for x in row if x > threshold]
def matrix_to_pairs(matrix: list[list[int]]) -> list[tuple[int, int, int]]:
"""Convert matrix to list of (row_idx, col_idx, value) tuples."""
return [(i, j, matrix[i][j]) for i in range(len(matrix)) for j in range(len(matrix[i]))]
def multiply_matrices_element(m1: list[list[int]], m2: list[list[int]]) -> list[list[int]]:
"""Element-wise matrix multiplication."""
return [[m1[i][j] * m2[i][j] for j in range(len(m1[i]))] for i in range(len(m1))]
def transpose(matrix: list[list[int]]) -> list[list[int]]:
"""Transpose matrix using nested comprehension."""
if not matrix:
return []
return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
def nested_squares(n: int) -> list[list[int]]:
"""Generate n x n matrix of squares."""
return [[i * j for j in range(n)] for i in range(n)]
def nested_with_condition(n: int) -> list[list[int]]:
"""Generate matrix with conditional values."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def filter_rows_by_sum(matrix: list[list[int]], min_sum: int) -> list[list[int]]:
"""Keep only rows with sum >= min_sum."""
return [row for row in matrix if sum(row) >= min_sum]
def filter_and_transform(matrix: list[list[int]]) -> list[list[int]]:
"""Filter rows and double values."""
return [[x * 2 for x in row] for row in matrix if sum(row) > 0]
def cross_product(list1: list[int], list2: list[int]) -> list[tuple[int, int]]:
"""Cartesian product of two lists."""
return [(x, y) for x in list1 for y in list2]
def cross_product_filtered(list1: list[int], list2: list[int]) -> list[tuple[int, int]]:
"""Cartesian product with filter."""
return [(x, y) for x in list1 for y in list2 if x != y]
def cross_product_sum(list1: list[int], list2: list[int], target: int) -> list[tuple[int, int]]:
"""Pairs that sum to target."""
return [(x, y) for x in list1 for y in list2 if x + y == target]
def nested_strings(words: list[str]) -> list[str]:
"""Extract all characters from all words."""
return [char for word in words for char in word]
def nested_strings_filtered(words: list[str]) -> list[str]:
"""Extract vowels from all words."""
vowels = "aeiouAEIOU"
return [char for word in words for char in word if char in vowels]
def group_by_length(words: list[str]) -> dict[int, list[str]]:
"""Group words by length using comprehension."""
lengths = {len(w) for w in words}
return {length: [w for w in words if len(w) == length] for length in lengths}
def nested_enumerate(matrix: list[list[int]]) -> list[tuple[int, int, int]]:
"""Enumerate 2D matrix."""
return [(i, j, val) for i, row in enumerate(matrix) for j, val in enumerate(row)]
def diagonal_elements(matrix: list[list[int]]) -> list[int]:
"""Get diagonal elements."""
return [matrix[i][i] for i in range(min(len(matrix), len(matrix[0]) if matrix else 0))]
def anti_diagonal_elements(matrix: list[list[int]]) -> list[int]:
"""Get anti-diagonal elements."""
n = len(matrix)
return [matrix[i][n - 1 - i] for i in range(n) if n - 1 - i < len(matrix[i])]
def upper_triangular(matrix: list[list[int]]) -> list[int]:
"""Get upper triangular elements."""
return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i])) if j >= i]
def lower_triangular(matrix: list[list[int]]) -> list[int]:
"""Get lower triangular elements."""
return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i])) if j <= i]
def sliding_window_2d(matrix: list[list[int]], size: int) -> list[list[list[int]]]:
"""Extract sliding windows from matrix."""
rows = len(matrix)
cols = len(matrix[0]) if matrix else 0
return [
[[matrix[i + di][j + dj] for dj in range(size)] for di in range(size)]
for i in range(rows - size + 1)
for j in range(cols - size + 1)
]
def flatten_dict_values(d: dict[str, list[int]]) -> list[int]:
"""Flatten dictionary values."""
return [x for values in d.values() for x in values]
def flatten_nested_dict(d: dict[str, dict[str, int]]) -> list[tuple[str, str, int]]:
"""Flatten nested dict to tuples."""
return [(k1, k2, v) for k1, inner in d.items() for k2, v in inner.items()]
def combinations_with_replacement(items: list[int], r: int) -> list[tuple[int, ...]]:
"""Simple combinations with replacement for r=2."""
if r != 2:
return []
return [(x, y) for i, x in enumerate(items) for y in items[i:]]
def permutations_2(items: list[int]) -> list[tuple[int, int]]:
"""All 2-permutations."""
return [(x, y) for i, x in enumerate(items) for j, y in enumerate(items) if i != j]
def main() -> int:
parser = argparse.ArgumentParser(description="Nested comprehension CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# flatten
flat_p = subparsers.add_parser("flatten", help="Flatten matrix")
flat_p.add_argument("--matrix", required=True, help="Matrix as [[1,2],[3,4]]")
# transpose
trans_p = subparsers.add_parser("transpose", help="Transpose matrix")
trans_p.add_argument("--matrix", required=True)
# cross
cross_p = subparsers.add_parser("cross", help="Cross product")
cross_p.add_argument("--list1", required=True)
cross_p.add_argument("--list2", required=True)
# squares
sq_p = subparsers.add_parser("squares", help="Generate square matrix")
sq_p.add_argument("n", type=int)
args = parser.parse_args()
if args.command == "flatten":
import ast
matrix = ast.literal_eval(args.matrix)
result = flatten_2d(matrix)
print(result)
elif args.command == "transpose":
import ast
matrix = ast.literal_eval(args.matrix)
result = transpose(matrix)
print(result)
elif args.command == "cross":
import ast
list1 = ast.literal_eval(args.list1)
list2 = ast.literal_eval(args.list2)
result = cross_product(list1, list2)
print(result)
elif args.command == "squares":
result = nested_squares(args.n)
for row in result:
print(row)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
nested_comprehension
| 211
| 0
|
[
"context_manager",
"eval_exec"
] | 0.652
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 4970..4973, value: Ellipsis, kind: None })
|
|
example_nested_comprehension
|
test_nested_comprehension_cli.py
|
"""Tests for nested_comprehension_cli.py"""
from nested_comprehension_cli import (
anti_diagonal_elements,
combinations_with_replacement,
cross_product,
cross_product_filtered,
cross_product_sum,
diagonal_elements,
filter_and_transform,
filter_rows_by_sum,
flatten_2d,
flatten_3d,
flatten_dict_values,
flatten_nested_dict,
flatten_with_filter,
group_by_length,
lower_triangular,
matrix_to_pairs,
multiply_matrices_element,
nested_enumerate,
nested_squares,
nested_strings,
nested_strings_filtered,
nested_with_condition,
permutations_2,
sliding_window_2d,
transpose,
upper_triangular,
)
class TestFlatten2D:
def test_basic(self):
matrix = [[1, 2], [3, 4]]
assert flatten_2d(matrix) == [1, 2, 3, 4]
def test_uneven_rows(self):
matrix = [[1, 2, 3], [4, 5]]
assert flatten_2d(matrix) == [1, 2, 3, 4, 5]
def test_empty(self):
assert flatten_2d([]) == []
def test_single_row(self):
assert flatten_2d([[1, 2, 3]]) == [1, 2, 3]
class TestFlatten3D:
def test_basic(self):
cube = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
assert flatten_3d(cube) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_empty(self):
assert flatten_3d([]) == []
class TestFlattenWithFilter:
def test_filter_above(self):
matrix = [[1, 5], [3, 7]]
assert flatten_with_filter(matrix, 4) == [5, 7]
def test_filter_all(self):
matrix = [[1, 2], [3, 4]]
assert flatten_with_filter(matrix, 10) == []
class TestMatrixToPairs:
def test_basic(self):
matrix = [[1, 2], [3, 4]]
result = matrix_to_pairs(matrix)
assert (0, 0, 1) in result
assert (1, 1, 4) in result
assert len(result) == 4
class TestMultiplyMatricesElement:
def test_basic(self):
m1 = [[1, 2], [3, 4]]
m2 = [[2, 2], [2, 2]]
result = multiply_matrices_element(m1, m2)
assert result == [[2, 4], [6, 8]]
class TestTranspose:
def test_square(self):
matrix = [[1, 2], [3, 4]]
assert transpose(matrix) == [[1, 3], [2, 4]]
def test_rectangular(self):
matrix = [[1, 2, 3], [4, 5, 6]]
assert transpose(matrix) == [[1, 4], [2, 5], [3, 6]]
def test_empty(self):
assert transpose([]) == []
class TestNestedSquares:
def test_3x3(self):
result = nested_squares(3)
assert result == [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
def test_1x1(self):
assert nested_squares(1) == [[0]]
def test_0x0(self):
assert nested_squares(0) == []
class TestNestedWithCondition:
def test_identity(self):
result = nested_with_condition(3)
assert result == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
class TestFilterRowsBySum:
def test_filter(self):
matrix = [[1, 2], [3, 4], [0, 0]]
result = filter_rows_by_sum(matrix, 5)
assert result == [[3, 4]]
class TestFilterAndTransform:
def test_basic(self):
matrix = [[1, 2], [0, 0], [3, 4]]
result = filter_and_transform(matrix)
assert result == [[2, 4], [6, 8]]
class TestCrossProduct:
def test_basic(self):
result = cross_product([1, 2], [3, 4])
assert result == [(1, 3), (1, 4), (2, 3), (2, 4)]
def test_empty(self):
assert cross_product([], [1, 2]) == []
class TestCrossProductFiltered:
def test_filter_equal(self):
result = cross_product_filtered([1, 2], [1, 2])
assert (1, 1) not in result
assert (2, 2) not in result
assert (1, 2) in result
class TestCrossProductSum:
def test_sum_target(self):
result = cross_product_sum([1, 2, 3], [1, 2, 3], 4)
assert (1, 3) in result
assert (2, 2) in result
assert (3, 1) in result
class TestNestedStrings:
def test_basic(self):
result = nested_strings(["ab", "cd"])
assert result == ["a", "b", "c", "d"]
def test_empty(self):
assert nested_strings([]) == []
class TestNestedStringsFiltered:
def test_vowels(self):
result = nested_strings_filtered(["hello", "world"])
assert result == ["e", "o", "o"]
class TestGroupByLength:
def test_group(self):
result = group_by_length(["a", "bb", "cc", "ddd"])
assert result[1] == ["a"]
assert set(result[2]) == {"bb", "cc"}
assert result[3] == ["ddd"]
class TestNestedEnumerate:
def test_basic(self):
matrix = [[1, 2], [3, 4]]
result = nested_enumerate(matrix)
assert (0, 0, 1) in result
assert (1, 1, 4) in result
class TestDiagonalElements:
def test_square(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
assert diagonal_elements(matrix) == [1, 5, 9]
def test_rectangular(self):
matrix = [[1, 2, 3], [4, 5, 6]]
assert diagonal_elements(matrix) == [1, 5]
class TestAntiDiagonalElements:
def test_square(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
assert anti_diagonal_elements(matrix) == [3, 5, 7]
class TestUpperTriangular:
def test_basic(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = upper_triangular(matrix)
assert result == [1, 2, 3, 5, 6, 9]
class TestLowerTriangular:
def test_basic(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = lower_triangular(matrix)
assert result == [1, 4, 5, 7, 8, 9]
class TestSlidingWindow2D:
def test_2x2_window(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = sliding_window_2d(matrix, 2)
assert len(result) == 4
assert result[0] == [[1, 2], [4, 5]]
class TestFlattenDictValues:
def test_basic(self):
d = {"a": [1, 2], "b": [3, 4]}
result = flatten_dict_values(d)
assert sorted(result) == [1, 2, 3, 4]
class TestFlattenNestedDict:
def test_basic(self):
d = {"a": {"x": 1, "y": 2}, "b": {"z": 3}}
result = flatten_nested_dict(d)
assert ("a", "x", 1) in result
assert ("b", "z", 3) in result
class TestCombinationsWithReplacement:
def test_r2(self):
result = combinations_with_replacement([1, 2, 3], 2)
assert (1, 1) in result
assert (1, 2) in result
assert (2, 3) in result
def test_invalid_r(self):
assert combinations_with_replacement([1, 2], 3) == []
class TestPermutations2:
def test_basic(self):
result = permutations_2([1, 2])
assert result == [(1, 2), (2, 1)]
class TestEdgeCases:
def test_single_element_matrix(self):
assert flatten_2d([[5]]) == [5]
assert transpose([[5]]) == [[5]]
def test_empty_inner_list(self):
assert flatten_2d([[], []]) == []
def test_single_char_words(self):
assert nested_strings(["a", "b"]) == ["a", "b"]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nested_comprehension/test_nested_comprehension_cli.py (6909 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nested_comprehension/test_nested_comprehension_cli.rs (18830 bytes)
⏱️ Parse time: 56ms
📊 Throughput: 119.1 KB/s
⏱️ Total time: 56ms
| true
|
nested_comprehension
| 265
| 5
|
[
"class_definition"
] | 0.612
| null |
example_nested_function
|
nested_function_cli.py
|
#!/usr/bin/env python3
"""Nested Function CLI.
Nested function definitions with type annotations.
"""
import argparse
import sys
def calculate_with_helpers(values: list[int]) -> dict[str, int]:
"""Calculate statistics using nested helpers."""
def sum_values(lst: list[int]) -> int:
total = 0
for x in lst:
total += x
return total
def average(lst: list[int]) -> int:
if not lst:
return 0
return sum_values(lst) // len(lst)
def minimum(lst: list[int]) -> int:
if not lst:
return 0
result = lst[0]
for x in lst[1:]:
if x < result:
result = x
return result
def maximum(lst: list[int]) -> int:
if not lst:
return 0
result = lst[0]
for x in lst[1:]:
if x > result:
result = x
return result
return {
"sum": sum_values(values),
"avg": average(values),
"min": minimum(values),
"max": maximum(values),
}
def process_string(text: str) -> dict[str, object]:
"""Process string using nested functions."""
def count_chars(s: str) -> int:
return len(s)
def count_words(s: str) -> int:
return len(s.split())
def count_lines(s: str) -> int:
return len(s.splitlines()) if s else 0
def first_word(s: str) -> str:
parts = s.split()
return parts[0] if parts else ""
def last_word(s: str) -> str:
parts = s.split()
return parts[-1] if parts else ""
return {
"chars": count_chars(text),
"words": count_words(text),
"lines": count_lines(text),
"first": first_word(text),
"last": last_word(text),
}
def recursive_with_helper(n: int) -> int:
"""Calculate factorial using nested recursive function."""
def factorial(x: int) -> int:
if x <= 1:
return 1
return x * factorial(x - 1)
return factorial(n)
def fibonacci_with_cache(n: int) -> int:
"""Calculate fibonacci using nested function with cache."""
cache: dict[int, int] = {}
def fib(x: int) -> int:
if x in cache:
return cache[x]
if x <= 1:
result = x
else:
result = fib(x - 1) + fib(x - 2)
cache[x] = result
return result
return fib(n)
def binary_search_nested(items: list[int], target: int) -> int:
"""Binary search using nested function."""
def search(low: int, high: int) -> int:
if low > high:
return -1
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
return search(mid + 1, high)
else:
return search(low, mid - 1)
return search(0, len(items) - 1)
def merge_sort_nested(items: list[int]) -> list[int]:
"""Merge sort using nested functions."""
def merge(left: list[int], right: list[int]) -> list[int]:
result: list[int] = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def sort(lst: list[int]) -> list[int]:
if len(lst) <= 1:
return lst.copy()
mid = len(lst) // 2
left = sort(lst[:mid])
right = sort(lst[mid:])
return merge(left, right)
return sort(items)
def validate_with_rules(value: str) -> tuple[bool, list[str]]:
"""Validate value using nested rule functions."""
def check_length(s: str) -> str | None:
if len(s) < 3:
return "too short"
if len(s) > 20:
return "too long"
return None
def check_alphanumeric(s: str) -> str | None:
if not s.isalnum():
return "not alphanumeric"
return None
def check_starts_with_letter(s: str) -> str | None:
if s and not s[0].isalpha():
return "must start with letter"
return None
errors: list[str] = []
for check in [check_length, check_alphanumeric, check_starts_with_letter]:
error = check(value)
if error:
errors.append(error)
return (len(errors) == 0, errors)
def tree_operations(tree: dict[str, object]) -> dict[str, int]:
"""Tree operations using nested functions."""
def count_nodes(node: dict[str, object]) -> int:
count = 1
children = node.get("children", [])
if isinstance(children, list):
for child in children:
if isinstance(child, dict):
count += count_nodes(child)
return count
def max_depth(node: dict[str, object], depth: int) -> int:
children = node.get("children", [])
if not children or not isinstance(children, list):
return depth
max_child = depth
for child in children:
if isinstance(child, dict):
child_depth = max_depth(child, depth + 1)
if child_depth > max_child:
max_child = child_depth
return max_child
def sum_values(node: dict[str, object]) -> int:
total = 0
value = node.get("value")
if isinstance(value, int):
total = value
children = node.get("children", [])
if isinstance(children, list):
for child in children:
if isinstance(child, dict):
total += sum_values(child)
return total
return {
"nodes": count_nodes(tree),
"depth": max_depth(tree, 1),
"sum": sum_values(tree),
}
def expression_parser(expr: str) -> int:
"""Simple expression parser using nested functions."""
pos = [0]
def peek() -> str:
if pos[0] < len(expr):
return expr[pos[0]]
return ""
def consume() -> str:
c = peek()
pos[0] += 1
return c
def skip_spaces() -> None:
while peek() == " ":
consume()
def parse_number() -> int:
skip_spaces()
num_str = ""
while peek().isdigit():
num_str += consume()
return int(num_str) if num_str else 0
def parse_term() -> int:
return parse_number()
def parse_expr() -> int:
left = parse_term()
while True:
skip_spaces()
if not peek() or peek() not in "+-":
break
op = consume()
skip_spaces()
right = parse_term()
if op == "+":
left = left + right
else:
left = left - right
return left
return parse_expr()
def main() -> int:
parser = argparse.ArgumentParser(description="Nested function CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# stats
stats_p = subparsers.add_parser("stats", help="Calculate statistics")
stats_p.add_argument("values", type=int, nargs="+")
# factorial
fact_p = subparsers.add_parser("factorial", help="Calculate factorial")
fact_p.add_argument("n", type=int)
# fib
fib_p = subparsers.add_parser("fib", help="Calculate fibonacci")
fib_p.add_argument("n", type=int)
# sort
sort_p = subparsers.add_parser("sort", help="Merge sort")
sort_p.add_argument("values", type=int, nargs="+")
# validate
val_p = subparsers.add_parser("validate", help="Validate string")
val_p.add_argument("value")
args = parser.parse_args()
if args.command == "stats":
result = calculate_with_helpers(args.values)
for k, v in result.items():
print(f"{k}: {v}")
elif args.command == "factorial":
result = recursive_with_helper(args.n)
print(f"{args.n}! = {result}")
elif args.command == "fib":
result = fibonacci_with_cache(args.n)
print(f"fib({args.n}) = {result}")
elif args.command == "sort":
result = merge_sort_nested(args.values)
print(result)
elif args.command == "validate":
valid, errors = validate_with_rules(args.value)
if valid:
print("Valid")
else:
print(f"Invalid: {', '.join(errors)}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nested_function/nested_function_cli.py (8567 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nested_function/nested_function_cli.rs (19876 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_nested_function/Cargo.toml (1 dependencies)
⏱️ Parse time: 63ms
📊 Throughput: 131.6 KB/s
⏱️ Total time: 63ms
| true
|
nested_function
| 328
| 6
|
[
"context_manager",
"multiprocessing"
] | 0.652
| null |
example_nested_function
|
test_nested_function_cli.py
|
"""Tests for nested_function_cli.py"""
from nested_function_cli import (
binary_search_nested,
calculate_with_helpers,
expression_parser,
fibonacci_with_cache,
merge_sort_nested,
process_string,
recursive_with_helper,
tree_operations,
validate_with_rules,
)
class TestCalculateWithHelpers:
def test_basic(self):
result = calculate_with_helpers([1, 2, 3, 4, 5])
assert result["sum"] == 15
assert result["avg"] == 3
assert result["min"] == 1
assert result["max"] == 5
def test_single(self):
result = calculate_with_helpers([42])
assert result["sum"] == 42
assert result["min"] == 42
assert result["max"] == 42
def test_empty(self):
result = calculate_with_helpers([])
assert result["sum"] == 0
assert result["avg"] == 0
class TestProcessString:
def test_basic(self):
result = process_string("hello world")
assert result["chars"] == 11
assert result["words"] == 2
assert result["first"] == "hello"
assert result["last"] == "world"
def test_empty(self):
result = process_string("")
assert result["chars"] == 0
assert result["words"] == 0
assert result["first"] == ""
class TestRecursiveWithHelper:
def test_factorial_5(self):
assert recursive_with_helper(5) == 120
def test_factorial_0(self):
assert recursive_with_helper(0) == 1
def test_factorial_1(self):
assert recursive_with_helper(1) == 1
class TestFibonacciWithCache:
def test_fib_10(self):
assert fibonacci_with_cache(10) == 55
def test_fib_0(self):
assert fibonacci_with_cache(0) == 0
def test_fib_1(self):
assert fibonacci_with_cache(1) == 1
def test_fib_large(self):
assert fibonacci_with_cache(20) == 6765
class TestBinarySearchNested:
def test_found(self):
items = [1, 3, 5, 7, 9]
assert binary_search_nested(items, 5) == 2
def test_not_found(self):
items = [1, 3, 5, 7, 9]
assert binary_search_nested(items, 4) == -1
def test_first(self):
items = [1, 3, 5, 7, 9]
assert binary_search_nested(items, 1) == 0
def test_last(self):
items = [1, 3, 5, 7, 9]
assert binary_search_nested(items, 9) == 4
class TestMergeSortNested:
def test_unsorted(self):
assert merge_sort_nested([3, 1, 4, 1, 5, 9, 2, 6]) == [1, 1, 2, 3, 4, 5, 6, 9]
def test_sorted(self):
assert merge_sort_nested([1, 2, 3]) == [1, 2, 3]
def test_reverse(self):
assert merge_sort_nested([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_empty(self):
assert merge_sort_nested([]) == []
def test_single(self):
assert merge_sort_nested([42]) == [42]
class TestValidateWithRules:
def test_valid(self):
valid, errors = validate_with_rules("abc123")
assert valid is True
assert errors == []
def test_too_short(self):
valid, errors = validate_with_rules("ab")
assert valid is False
assert "too short" in errors
def test_not_alphanumeric(self):
valid, errors = validate_with_rules("abc!")
assert valid is False
assert "not alphanumeric" in errors
def test_starts_with_number(self):
valid, errors = validate_with_rules("123abc")
assert valid is False
assert "must start with letter" in errors
class TestTreeOperations:
def test_single_node(self):
tree = {"value": 10}
result = tree_operations(tree)
assert result["nodes"] == 1
assert result["depth"] == 1
assert result["sum"] == 10
def test_with_children(self):
tree = {
"value": 1,
"children": [
{"value": 2},
{"value": 3},
]
}
result = tree_operations(tree)
assert result["nodes"] == 3
assert result["depth"] == 2
assert result["sum"] == 6
def test_deep_tree(self):
tree = {
"value": 1,
"children": [
{
"value": 2,
"children": [
{"value": 3}
]
}
]
}
result = tree_operations(tree)
assert result["depth"] == 3
class TestExpressionParser:
def test_simple_add(self):
assert expression_parser("2 + 3") == 5
def test_simple_sub(self):
assert expression_parser("10 - 3") == 7
def test_chain(self):
assert expression_parser("1 + 2 + 3") == 6
def test_mixed(self):
assert expression_parser("10 - 3 + 5") == 12
def test_single_number(self):
assert expression_parser("42") == 42
class TestEdgeCases:
def test_factorial_large(self):
assert recursive_with_helper(10) == 3628800
def test_empty_sort(self):
assert merge_sort_nested([]) == []
def test_single_element_search(self):
assert binary_search_nested([5], 5) == 0
assert binary_search_nested([5], 3) == -1
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nested_function/test_nested_function_cli.py (5169 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nested_function/test_nested_function_cli.rs (11062 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 95.5 KB/s
⏱️ Total time: 53ms
| true
|
nested_function
| 196
| 5
|
[
"context_manager",
"class_definition",
"multiprocessing"
] | 0.652
| null |
example_nested_subs
|
nested_tool.py
|
#!/usr/bin/env python3
"""Nested Subcommands Example - Two-level subcommand CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Nested subcommands tool")
subs = parser.add_subparsers(dest="cmd", required=True)
user = subs.add_parser("user")
user.add_argument("action")
user.add_argument("name")
group = subs.add_parser("group")
group.add_argument("action")
group.add_argument("name")
args = parser.parse_args()
if args.cmd == "user":
if args.action == "add":
print(f"Added user: {args.name}")
elif args.action == "remove":
print(f"Removed user: {args.name}")
elif args.cmd == "group":
if args.action == "create":
print(f"Created group: {args.name}")
elif args.action == "delete":
print(f"Deleted group: {args.name}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nested_subs/nested_tool.py (917 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nested_subs/nested_tool.rs (1605 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_nested_subs/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 18.2 KB/s
⏱️ Total time: 49ms
| true
|
nested_subs
| 33
| 6
|
[] | 0
| null |
example_nested_subs
|
test_nested_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for nested subcommands CLI."""
import subprocess
SCRIPT = "nested_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestNested:
def test_user_add(self): r = run(["user", "add", "alice"]); assert r.returncode == 0 and "alice" in r.stdout
def test_user_remove(self): r = run(["user", "remove", "bob"]); assert r.returncode == 0 and "bob" in r.stdout
def test_group_create(self): r = run(["group", "create", "admins"]); assert r.returncode == 0 and "admins" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_nested_subs/test_nested_tool.py (701 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_nested_subs/test_nested_tool.rs (2031 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 13.8 KB/s
⏱️ Total time: 49ms
| true
|
nested_subs
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_num_fft
|
num_fft_cli.py
|
"""Fast Fourier Transform CLI.
Demonstrates FFT for signal processing.
"""
import math
import sys
from dataclasses import dataclass
@dataclass
class Complex:
"""Complex number."""
real: float
imag: float = 0.0
def __add__(self, other: "Complex") -> "Complex":
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other: "Complex") -> "Complex":
return Complex(self.real - other.real, self.imag - other.imag)
def __mul__(self, other: "Complex") -> "Complex":
return Complex(
self.real * other.real - self.imag * other.imag,
self.real * other.imag + self.imag * other.real,
)
def __truediv__(self, other: float) -> "Complex":
return Complex(self.real / other, self.imag / other)
def magnitude(self) -> float:
return math.sqrt(self.real**2 + self.imag**2)
def phase(self) -> float:
return math.atan2(self.imag, self.real)
def conjugate(self) -> "Complex":
return Complex(self.real, -self.imag)
def __repr__(self) -> str:
if self.imag >= 0:
return f"{self.real:.4f}+{self.imag:.4f}j"
return f"{self.real:.4f}{self.imag:.4f}j"
def exp_j(theta: float) -> Complex:
"""e^(j*theta) = cos(theta) + j*sin(theta)."""
return Complex(math.cos(theta), math.sin(theta))
def fft(x: list[Complex]) -> list[Complex]:
"""Cooley-Tukey FFT (radix-2)."""
n = len(x)
if n <= 1:
return x[:]
# Pad to power of 2
if n & (n - 1) != 0:
next_pow2 = 1 << (n - 1).bit_length()
x = x + [Complex(0, 0)] * (next_pow2 - n)
n = next_pow2
# Bit-reversal permutation
bits = (n - 1).bit_length()
result = [Complex(0, 0)] * n
for i in range(n):
rev = int(bin(i)[2:].zfill(bits)[::-1], 2)
result[rev] = x[i]
# Iterative FFT
length = 2
while length <= n:
half = length // 2
w_n = exp_j(-2 * math.pi / length)
for i in range(0, n, length):
w = Complex(1, 0)
for j in range(half):
u = result[i + j]
t = w * result[i + j + half]
result[i + j] = u + t
result[i + j + half] = u - t
w = w * w_n
length *= 2
return result
def ifft(x: list[Complex]) -> list[Complex]:
"""Inverse FFT."""
n = len(x)
# Conjugate input
conj = [c.conjugate() for c in x]
# Forward FFT
result = fft(conj)
# Conjugate and scale
return [c.conjugate() / n for c in result]
def dft(x: list[Complex]) -> list[Complex]:
"""Direct DFT (O(n^2), for reference)."""
n = len(x)
result = []
for k in range(n):
total = Complex(0, 0)
for j in range(n):
angle = -2 * math.pi * k * j / n
total = total + x[j] * exp_j(angle)
result.append(total)
return result
def magnitude_spectrum(x: list[Complex]) -> list[float]:
"""Get magnitude spectrum from FFT result."""
return [c.magnitude() for c in x]
def phase_spectrum(x: list[Complex]) -> list[float]:
"""Get phase spectrum from FFT result."""
return [c.phase() for c in x]
def power_spectrum(x: list[Complex]) -> list[float]:
"""Get power spectrum (magnitude squared)."""
return [c.magnitude() ** 2 for c in x]
def frequency_bins(n: int, sample_rate: float) -> list[float]:
"""Get frequency bin centers."""
return [k * sample_rate / n for k in range(n)]
def generate_signal(
frequencies: list[float],
amplitudes: list[float],
phases: list[float],
n_samples: int,
sample_rate: float,
) -> list[Complex]:
"""Generate signal from frequency components."""
signal = [Complex(0, 0)] * n_samples
for i in range(n_samples):
t = i / sample_rate
val = 0.0
for freq, amp, phase in zip(frequencies, amplitudes, phases, strict=False):
val += amp * math.cos(2 * math.pi * freq * t + phase)
signal[i] = Complex(val)
return signal
def find_dominant_frequency(spectrum: list[Complex], sample_rate: float) -> tuple[float, float]:
"""Find dominant frequency and its magnitude."""
n = len(spectrum)
magnitudes = magnitude_spectrum(spectrum[: n // 2]) # Only positive frequencies
max_idx = max(range(len(magnitudes)), key=lambda i: magnitudes[i])
freq = max_idx * sample_rate / n
return freq, magnitudes[max_idx]
def convolution_fft(a: list[Complex], b: list[Complex]) -> list[Complex]:
"""Convolution using FFT."""
n = len(a) + len(b) - 1
next_pow2 = 1 << (n - 1).bit_length()
a_padded = a + [Complex(0)] * (next_pow2 - len(a))
b_padded = b + [Complex(0)] * (next_pow2 - len(b))
fft_a = fft(a_padded)
fft_b = fft(b_padded)
product = [fa * fb for fa, fb in zip(fft_a, fft_b, strict=False)]
result = ifft(product)
return result[:n]
def simulate_fft(operations: list[str]) -> list[str]:
"""Simulate FFT operations."""
results: list[str] = []
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "fft":
values = [float(x) for x in parts[1].split(",")]
signal = [Complex(v) for v in values]
spectrum = fft(signal)
mags = [f"{c.magnitude():.2f}" for c in spectrum]
results.append(str(mags))
elif cmd == "ifft":
values = [float(x) for x in parts[1].split(",")]
signal = [Complex(v) for v in values]
spectrum = fft(signal)
recovered = ifft(spectrum)
reals = [f"{c.real:.2f}" for c in recovered]
results.append(str(reals))
elif cmd == "dominant":
signal = generate_signal([10.0], [1.0], [0.0], 64, 100.0)
spectrum = fft(signal)
freq, mag = find_dominant_frequency(spectrum, 100.0)
results.append(f"freq={freq:.1f}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: num_fft_cli.py <command>")
return 1
cmd = sys.argv[1]
if cmd == "demo":
# Generate signal with 10 Hz and 25 Hz components
signal = generate_signal([10.0, 25.0], [1.0, 0.5], [0.0, 0.0], 128, 100.0)
spectrum = fft(signal)
freq, mag = find_dominant_frequency(spectrum, 100.0)
print(f"Dominant frequency: {freq} Hz (magnitude: {mag:.2f})")
# Round-trip test
recovered = ifft(spectrum)
print(f"First 5 original: {[f'{s.real:.3f}' for s in signal[:5]]}")
print(f"First 5 recovered: {[f'{r.real:.3f}' for r in recovered[:5]]}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
num_fft
| 235
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"decorator"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 1002..1011, value: Str("Complex"), kind: None })
|
|
example_num_fft
|
test_num_fft_cli.py
|
"""Tests for num_fft_cli.py"""
import math
from num_fft_cli import (
Complex,
convolution_fft,
dft,
exp_j,
fft,
find_dominant_frequency,
frequency_bins,
generate_signal,
ifft,
magnitude_spectrum,
power_spectrum,
simulate_fft,
)
class TestComplex:
def test_create(self):
c = Complex(3, 4)
assert c.real == 3
assert c.imag == 4
def test_add(self):
c1 = Complex(1, 2)
c2 = Complex(3, 4)
result = c1 + c2
assert result.real == 4
assert result.imag == 6
def test_sub(self):
c1 = Complex(5, 6)
c2 = Complex(1, 2)
result = c1 - c2
assert result.real == 4
assert result.imag == 4
def test_mul(self):
c1 = Complex(1, 2)
c2 = Complex(3, 4)
result = c1 * c2
assert result.real == -5 # 1*3 - 2*4
assert result.imag == 10 # 1*4 + 2*3
def test_div(self):
c = Complex(4, 6)
result = c / 2
assert result.real == 2
assert result.imag == 3
def test_magnitude(self):
c = Complex(3, 4)
assert c.magnitude() == 5
def test_phase(self):
c = Complex(1, 1)
assert abs(c.phase() - math.pi / 4) < 1e-10
def test_conjugate(self):
c = Complex(3, 4)
conj = c.conjugate()
assert conj.real == 3
assert conj.imag == -4
class TestExpJ:
def test_zero(self):
c = exp_j(0)
assert abs(c.real - 1) < 1e-10
assert abs(c.imag) < 1e-10
def test_pi_over_2(self):
c = exp_j(math.pi / 2)
assert abs(c.real) < 1e-10
assert abs(c.imag - 1) < 1e-10
def test_pi(self):
c = exp_j(math.pi)
assert abs(c.real - (-1)) < 1e-10
assert abs(c.imag) < 1e-10
class TestFFT:
def test_single_element(self):
result = fft([Complex(5)])
assert len(result) == 1
assert result[0].real == 5
def test_two_elements(self):
result = fft([Complex(1), Complex(2)])
assert len(result) == 2
assert abs(result[0].real - 3) < 1e-10 # DC component
assert abs(result[1].real - (-1)) < 1e-10
def test_power_of_two(self):
signal = [Complex(i) for i in range(8)]
result = fft(signal)
assert len(result) == 8
def test_dc_component(self):
signal = [Complex(1)] * 4
result = fft(signal)
assert abs(result[0].real - 4) < 1e-10
for i in range(1, 4):
assert result[i].magnitude() < 1e-10
class TestIFFT:
def test_round_trip(self):
original = [Complex(1), Complex(2), Complex(3), Complex(4)]
spectrum = fft(original)
recovered = ifft(spectrum)
for orig, rec in zip(original, recovered, strict=False):
assert abs(orig.real - rec.real) < 1e-10
assert abs(orig.imag - rec.imag) < 1e-10
def test_round_trip_8(self):
original = [Complex(i * 0.5) for i in range(8)]
spectrum = fft(original)
recovered = ifft(spectrum)
for orig, rec in zip(original, recovered, strict=False):
assert abs(orig.real - rec.real) < 1e-10
class TestDFT:
def test_matches_fft(self):
signal = [Complex(1), Complex(2), Complex(3), Complex(4)]
fft_result = fft(signal)
dft_result = dft(signal)
for f, d in zip(fft_result, dft_result, strict=False):
assert abs(f.real - d.real) < 1e-10
assert abs(f.imag - d.imag) < 1e-10
class TestMagnitudeSpectrum:
def test_basic(self):
signal = [Complex(1), Complex(0), Complex(0), Complex(0)]
spectrum = fft(signal)
mags = magnitude_spectrum(spectrum)
assert all(abs(m - 1) < 1e-10 for m in mags)
class TestPowerSpectrum:
def test_basic(self):
signal = [Complex(1), Complex(0), Complex(0), Complex(0)]
spectrum = fft(signal)
power = power_spectrum(spectrum)
assert all(abs(p - 1) < 1e-10 for p in power)
class TestFrequencyBins:
def test_basic(self):
bins = frequency_bins(8, 100.0)
assert len(bins) == 8
assert bins[0] == 0.0
assert bins[1] == 12.5
class TestGenerateSignal:
def test_single_frequency(self):
signal = generate_signal([10.0], [1.0], [0.0], 100, 100.0)
assert len(signal) == 100
assert abs(signal[0].real - 1.0) < 1e-10 # cos(0) = 1
def test_dc_signal(self):
signal = generate_signal([0.0], [5.0], [0.0], 10, 100.0)
for s in signal:
assert abs(s.real - 5.0) < 1e-10
class TestFindDominantFrequency:
def test_single_tone(self):
signal = generate_signal([25.0], [1.0], [0.0], 128, 128.0)
spectrum = fft(signal)
freq, mag = find_dominant_frequency(spectrum, 128.0)
assert abs(freq - 25.0) < 1.0
class TestConvolutionFFT:
def test_basic(self):
a = [Complex(1), Complex(2), Complex(3)]
b = [Complex(1), Complex(1)]
result = convolution_fft(a, b)
expected = [1, 3, 5, 3] # [1, 2, 3] * [1, 1]
for r, e in zip(result, expected, strict=False):
assert abs(r.real - e) < 1e-10
class TestSimulateFFT:
def test_fft(self):
result = simulate_fft(["fft:1,0,0,0"])
assert "1.00" in result[0]
def test_ifft(self):
result = simulate_fft(["ifft:1,2,3,4"])
# Should recover original values
assert "1.00" in result[0]
def test_dominant(self):
result = simulate_fft(["dominant:"])
assert "freq=" in result[0]
| false
|
num_fft
| 204
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Lt, left: Call { func: "abs", args: [Binary { op: Sub, left: Var("m"), right: Literal(Int(1)) }], kwargs: [] }, right: Literal(Float(1e-10)) }, generators: [HirComprehension { target: "m", iter: Var("mags"), conditions: [] }] }
|
|
example_num_integrate
|
num_integrate_cli.py
|
"""Numerical Integration CLI.
Demonstrates numerical integration methods: trapezoidal, Simpson, Gaussian.
"""
import math
import sys
from collections.abc import Callable
from dataclasses import dataclass
@dataclass
class IntegrationResult:
"""Result of numerical integration."""
value: float
error_estimate: float
n_evaluations: int
def trapezoidal(f: Callable[[float], float], a: float, b: float, n: int = 100) -> float:
"""Trapezoidal rule integration."""
h = (b - a) / n
total = (f(a) + f(b)) / 2
for i in range(1, n):
total += f(a + i * h)
return total * h
def simpson(f: Callable[[float], float], a: float, b: float, n: int = 100) -> float:
"""Simpson's rule integration (n must be even)."""
if n % 2 != 0:
n += 1
h = (b - a) / n
total = f(a) + f(b)
for i in range(1, n):
x = a + i * h
if i % 2 == 0:
total += 2 * f(x)
else:
total += 4 * f(x)
return total * h / 3
def simpson38(f: Callable[[float], float], a: float, b: float, n: int = 99) -> float:
"""Simpson's 3/8 rule integration (n must be multiple of 3)."""
while n % 3 != 0:
n += 1
h = (b - a) / n
total = f(a) + f(b)
for i in range(1, n):
x = a + i * h
if i % 3 == 0:
total += 2 * f(x)
else:
total += 3 * f(x)
return total * 3 * h / 8
def midpoint(f: Callable[[float], float], a: float, b: float, n: int = 100) -> float:
"""Midpoint rule integration."""
h = (b - a) / n
total = 0.0
for i in range(n):
x_mid = a + (i + 0.5) * h
total += f(x_mid)
return total * h
def romberg(
f: Callable[[float], float], a: float, b: float, max_iter: int = 10, tol: float = 1e-10
) -> IntegrationResult:
"""Romberg integration with Richardson extrapolation."""
R = [[0.0] * (max_iter + 1) for _ in range(max_iter + 1)]
n_evals = 2
R[0][0] = (b - a) * (f(a) + f(b)) / 2
for i in range(1, max_iter + 1):
h = (b - a) / (2**i)
# Composite trapezoidal
n_points = 2 ** (i - 1)
inner_sum = sum(f(a + (2 * k - 1) * h) for k in range(1, n_points + 1))
R[i][0] = R[i - 1][0] / 2 + h * inner_sum
n_evals += n_points
# Richardson extrapolation
for j in range(1, i + 1):
R[i][j] = (4**j * R[i][j - 1] - R[i - 1][j - 1]) / (4**j - 1)
if i > 1 and abs(R[i][i] - R[i - 1][i - 1]) < tol:
return IntegrationResult(R[i][i], abs(R[i][i] - R[i - 1][i - 1]), n_evals)
return IntegrationResult(
R[max_iter][max_iter], abs(R[max_iter][max_iter] - R[max_iter - 1][max_iter - 1]), n_evals
)
# Gaussian quadrature nodes and weights
GAUSS_LEGENDRE_2 = [(-0.5773502691896257, 1.0), (0.5773502691896257, 1.0)]
GAUSS_LEGENDRE_3 = [
(-0.7745966692414834, 0.5555555555555556),
(0.0, 0.8888888888888888),
(0.7745966692414834, 0.5555555555555556),
]
GAUSS_LEGENDRE_5 = [
(-0.9061798459386640, 0.2369268850561891),
(-0.5384693101056831, 0.4786286704993665),
(0.0, 0.5688888888888889),
(0.5384693101056831, 0.4786286704993665),
(0.9061798459386640, 0.2369268850561891),
]
def gauss_legendre(f: Callable[[float], float], a: float, b: float, n_points: int = 5) -> float:
"""Gaussian quadrature integration."""
if n_points == 2:
nodes_weights = GAUSS_LEGENDRE_2
elif n_points == 3:
nodes_weights = GAUSS_LEGENDRE_3
else:
nodes_weights = GAUSS_LEGENDRE_5
# Transform from [-1, 1] to [a, b]
c1 = (b - a) / 2
c2 = (b + a) / 2
total = 0.0
for node, weight in nodes_weights:
x = c1 * node + c2
total += weight * f(x)
return total * c1
def adaptive_simpson(
f: Callable[[float], float], a: float, b: float, tol: float = 1e-10, max_depth: int = 50
) -> IntegrationResult:
"""Adaptive Simpson's rule."""
n_evals = [0]
def simpson_helper(a: float, b: float, fa: float, fb: float, s: float, depth: int) -> float:
c = (a + b) / 2
fc = f(c)
n_evals[0] += 1
d = (a + c) / 2
e = (c + b) / 2
fd = f(d)
fe = f(e)
n_evals[0] += 2
h = b - a
s_left = (h / 12) * (fa + 4 * fd + fc)
s_right = (h / 12) * (fc + 4 * fe + fb)
s_new = s_left + s_right
if depth <= 0 or abs(s_new - s) < 15 * tol:
return s_new + (s_new - s) / 15
return simpson_helper(a, c, fa, fc, s_left, depth - 1) + simpson_helper(
c, b, fc, fb, s_right, depth - 1
)
fa = f(a)
fb = f(b)
fc = f((a + b) / 2)
n_evals[0] = 3
s = (b - a) * (fa + 4 * fc + fb) / 6
result = simpson_helper(a, b, fa, fb, s, max_depth)
return IntegrationResult(result, tol, n_evals[0])
def monte_carlo(
f: Callable[[float], float], a: float, b: float, n_samples: int = 10000, seed: int = 42
) -> IntegrationResult:
"""Monte Carlo integration."""
# Simple LCG random number generator
state = seed
samples = []
for _ in range(n_samples):
state = (1103515245 * state + 12345) % (2**31)
u = state / (2**31)
x = a + u * (b - a)
samples.append(f(x))
mean = sum(samples) / n_samples
integral = (b - a) * mean
# Estimate error (standard error of the mean)
variance = sum((s - mean) ** 2 for s in samples) / (n_samples - 1)
error = (b - a) * math.sqrt(variance / n_samples)
return IntegrationResult(integral, error, n_samples)
def double_integral(
f: Callable[[float, float], float],
ax: float,
bx: float,
ay: float,
by: float,
nx: int = 50,
ny: int = 50,
) -> float:
"""Double integral using trapezoidal rule."""
hx = (bx - ax) / nx
hy = (by - ay) / ny
total = 0.0
for i in range(nx + 1):
x = ax + i * hx
wx = 0.5 if i == 0 or i == nx else 1.0
for j in range(ny + 1):
y = ay + j * hy
wy = 0.5 if j == 0 or j == ny else 1.0
total += wx * wy * f(x, y)
return total * hx * hy
def improper_integral(
f: Callable[[float], float], a: float, method: str = "exponential", n: int = 100
) -> float:
"""Integrate from a to infinity using transformation."""
if method == "exponential":
# Transform x in [a, inf) to t in [0, 1) via x = a - ln(1-t)
def g(t: float) -> float:
if t >= 1:
return 0.0
x = a - math.log(1 - t)
return f(x) / (1 - t)
return simpson(g, 0, 0.9999, n)
else:
# Transform x in [a, inf) to t in [0, 1) via x = a + t/(1-t)
def g(t: float) -> float:
if t >= 1:
return 0.0
x = a + t / (1 - t)
return f(x) / ((1 - t) ** 2)
return simpson(g, 0, 0.9999, n)
def simulate_integrate(operations: list[str]) -> list[str]:
"""Simulate integration operations."""
results: list[str] = []
# Test function: x^2
def f(x):
return x**2
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "trapezoidal":
result = trapezoidal(f, 0, 1, 100)
results.append(f"{result:.6f}")
elif cmd == "simpson":
result = simpson(f, 0, 1, 100)
results.append(f"{result:.6f}")
elif cmd == "gauss":
result = gauss_legendre(f, 0, 1, 5)
results.append(f"{result:.6f}")
elif cmd == "romberg":
result = romberg(f, 0, 1)
results.append(f"{result.value:.6f}")
elif cmd == "sin":
# Integral of sin(x) from 0 to pi = 2
result = simpson(math.sin, 0, math.pi, 100)
results.append(f"{result:.6f}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: num_integrate_cli.py <command>")
return 1
cmd = sys.argv[1]
if cmd == "demo":
def f(x):
return x**2
print("Integrating x^2 from 0 to 1 (exact = 1/3):")
print(f"Trapezoidal (n=10): {trapezoidal(f, 0, 1, 10):.10f}")
print(f"Trapezoidal (n=100): {trapezoidal(f, 0, 1, 100):.10f}")
print(f"Simpson (n=10): {simpson(f, 0, 1, 10):.10f}")
print(f"Simpson (n=100): {simpson(f, 0, 1, 100):.10f}")
print(f"Gauss-Legendre (5): {gauss_legendre(f, 0, 1, 5):.10f}")
result = romberg(f, 0, 1)
print(f"Romberg: {result.value:.10f} (evals={result.n_evaluations})")
result = adaptive_simpson(f, 0, 1)
print(f"Adaptive Simpson: {result.value:.10f} (evals={result.n_evaluations})")
print("\nIntegral of sin(x) from 0 to pi (exact = 2):")
print(f"Simpson: {simpson(math.sin, 0, math.pi, 100):.10f}")
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_integrate/num_integrate_cli.py (8987 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_integrate/num_integrate_cli.rs (23646 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_num_integrate/Cargo.toml (3 dependencies)
⏱️ Parse time: 64ms
📊 Throughput: 135.1 KB/s
⏱️ Total time: 65ms
| true
|
num_integrate
| 323
| 6
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
| null |
example_num_integrate
|
test_num_integrate_cli.py
|
"""Tests for num_integrate_cli.py"""
import math
from num_integrate_cli import (
IntegrationResult,
adaptive_simpson,
double_integral,
gauss_legendre,
improper_integral,
midpoint,
monte_carlo,
romberg,
simpson,
simpson38,
simulate_integrate,
trapezoidal,
)
class TestTrapezoidal:
def test_constant(self):
def f(x):
return 5.0
result = trapezoidal(f, 0, 2, 10)
assert abs(result - 10.0) < 1e-10
def test_linear(self):
def f(x):
return x
result = trapezoidal(f, 0, 1, 100)
assert abs(result - 0.5) < 1e-10
def test_quadratic(self):
def f(x):
return x ** 2
result = trapezoidal(f, 0, 1, 1000)
assert abs(result - 1 / 3) < 1e-5
def test_sin(self):
result = trapezoidal(math.sin, 0, math.pi, 1000)
assert abs(result - 2.0) < 1e-5
def test_exp(self):
result = trapezoidal(math.exp, 0, 1, 1000)
assert abs(result - (math.e - 1)) < 1e-5
class TestSimpson:
def test_constant(self):
def f(x):
return 5.0
result = simpson(f, 0, 2, 10)
assert abs(result - 10.0) < 1e-10
def test_linear(self):
def f(x):
return x
result = simpson(f, 0, 1, 100)
assert abs(result - 0.5) < 1e-10
def test_quadratic(self):
def f(x):
return x ** 2
result = simpson(f, 0, 1, 100)
assert abs(result - 1 / 3) < 1e-10
def test_cubic(self):
def f(x):
return x ** 3
result = simpson(f, 0, 1, 100)
assert abs(result - 0.25) < 1e-10
def test_sin(self):
result = simpson(math.sin, 0, math.pi, 100)
assert abs(result - 2.0) < 1e-7
def test_more_accurate_than_trapezoidal(self):
def f(x):
return x ** 2
trap = trapezoidal(f, 0, 1, 10)
simp = simpson(f, 0, 1, 10)
exact = 1 / 3
assert abs(simp - exact) < abs(trap - exact)
class TestSimpson38:
def test_constant(self):
def f(x):
return 5.0
result = simpson38(f, 0, 2, 9)
assert abs(result - 10.0) < 1e-10
def test_quadratic(self):
def f(x):
return x ** 2
result = simpson38(f, 0, 1, 99)
assert abs(result - 1 / 3) < 1e-8
def test_cubic(self):
def f(x):
return x ** 3
result = simpson38(f, 0, 1, 99)
assert abs(result - 0.25) < 1e-8
class TestMidpoint:
def test_constant(self):
def f(x):
return 5.0
result = midpoint(f, 0, 2, 10)
assert abs(result - 10.0) < 1e-10
def test_linear(self):
def f(x):
return x
result = midpoint(f, 0, 1, 100)
assert abs(result - 0.5) < 1e-10
def test_quadratic(self):
def f(x):
return x ** 2
result = midpoint(f, 0, 1, 1000)
assert abs(result - 1 / 3) < 1e-5
class TestRomberg:
def test_quadratic(self):
def f(x):
return x ** 2
result = romberg(f, 0, 1)
assert abs(result.value - 1 / 3) < 1e-10
def test_sin(self):
result = romberg(math.sin, 0, math.pi)
assert abs(result.value - 2.0) < 1e-10
def test_exp(self):
result = romberg(math.exp, 0, 1)
assert abs(result.value - (math.e - 1)) < 1e-10
def test_efficient(self):
def f(x):
return x ** 2
result = romberg(f, 0, 1)
assert result.n_evaluations < 100
def test_returns_result_struct(self):
def f(x):
return x
result = romberg(f, 0, 1)
assert isinstance(result, IntegrationResult)
assert result.n_evaluations > 0
class TestGaussLegendre:
def test_constant(self):
def f(x):
return 5.0
result = gauss_legendre(f, 0, 2, 2)
assert abs(result - 10.0) < 1e-10
def test_linear(self):
def f(x):
return x
result = gauss_legendre(f, 0, 1, 2)
assert abs(result - 0.5) < 1e-10
def test_quadratic(self):
def f(x):
return x ** 2
result = gauss_legendre(f, 0, 1, 2)
assert abs(result - 1 / 3) < 1e-10
def test_polynomial_exact(self):
# 5-point Gauss integrates polynomials up to degree 9 exactly
def f(x):
return x ** 5
result = gauss_legendre(f, 0, 1, 5)
assert abs(result - 1 / 6) < 1e-10
def test_sin(self):
result = gauss_legendre(math.sin, 0, math.pi, 5)
assert abs(result - 2.0) < 1e-5
def test_different_points(self):
def f(x):
return x ** 2
r2 = gauss_legendre(f, 0, 1, 2)
r3 = gauss_legendre(f, 0, 1, 3)
r5 = gauss_legendre(f, 0, 1, 5)
# All should give exact result for x^2
assert abs(r2 - 1 / 3) < 1e-10
assert abs(r3 - 1 / 3) < 1e-10
assert abs(r5 - 1 / 3) < 1e-10
class TestAdaptiveSimpson:
def test_quadratic(self):
def f(x):
return x ** 2
result = adaptive_simpson(f, 0, 1)
assert abs(result.value - 1 / 3) < 1e-10
def test_sin(self):
result = adaptive_simpson(math.sin, 0, math.pi)
assert abs(result.value - 2.0) < 1e-10
def test_handles_discontinuity_like(self):
# Step-like function
def f(x):
return 1.0 if x > 0.5 else 0.0
result = adaptive_simpson(f, 0, 1, tol=1e-6)
assert abs(result.value - 0.5) < 0.01
class TestMonteCarlo:
def test_constant(self):
def f(x):
return 5.0
result = monte_carlo(f, 0, 2, n_samples=1000)
assert abs(result.value - 10.0) < 0.5
def test_linear(self):
def f(x):
return x
result = monte_carlo(f, 0, 1, n_samples=10000)
assert abs(result.value - 0.5) < 0.1
def test_returns_error_estimate(self):
def f(x):
return x ** 2
result = monte_carlo(f, 0, 1, n_samples=10000)
assert result.error_estimate > 0
assert result.n_evaluations == 10000
def test_reproducible_with_seed(self):
def f(x):
return x ** 2
r1 = monte_carlo(f, 0, 1, seed=12345)
r2 = monte_carlo(f, 0, 1, seed=12345)
assert r1.value == r2.value
class TestDoubleIntegral:
def test_constant(self):
def f(x, y):
return 1.0
result = double_integral(f, 0, 1, 0, 1)
assert abs(result - 1.0) < 1e-5
def test_product(self):
# Integral of x*y over [0,1]x[0,1] = 1/4
def f(x, y):
return x * y
result = double_integral(f, 0, 1, 0, 1, nx=100, ny=100)
assert abs(result - 0.25) < 1e-5
def test_sum(self):
# Integral of (x+y) over [0,1]x[0,1] = 1
def f(x, y):
return x + y
result = double_integral(f, 0, 1, 0, 1, nx=100, ny=100)
assert abs(result - 1.0) < 1e-5
def test_rectangular_region(self):
def f(x, y):
return 1.0
result = double_integral(f, 0, 2, 0, 3)
assert abs(result - 6.0) < 1e-5
class TestImproperIntegral:
def test_exponential_decay(self):
# Integral of e^(-x) from 0 to inf = 1
def f(x):
return math.exp(-x)
result = improper_integral(f, 0, method="exponential", n=200)
assert abs(result - 1.0) < 0.1
def test_inverse_square(self):
# Integral of 1/x^2 from 1 to inf = 1
def f(x):
return 1 / (x ** 2)
result = improper_integral(f, 1, method="rational", n=200)
assert abs(result - 1.0) < 0.1
class TestIntegrationResult:
def test_create(self):
result = IntegrationResult(1.5, 0.01, 100)
assert result.value == 1.5
assert result.error_estimate == 0.01
assert result.n_evaluations == 100
class TestSimulateIntegrate:
def test_trapezoidal(self):
result = simulate_integrate(["trapezoidal:"])
# Integral of x^2 from 0 to 1 = 1/3
assert "0.33" in result[0]
def test_simpson(self):
result = simulate_integrate(["simpson:"])
assert "0.33" in result[0]
def test_gauss(self):
result = simulate_integrate(["gauss:"])
assert "0.33" in result[0]
def test_romberg(self):
result = simulate_integrate(["romberg:"])
assert "0.33" in result[0]
def test_sin(self):
result = simulate_integrate(["sin:"])
# Integral of sin(x) from 0 to pi = 2
assert "2.0" in result[0]
def test_multiple_operations(self):
result = simulate_integrate(["trapezoidal:", "simpson:"])
assert len(result) == 2
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_integrate/test_num_integrate_cli.py (8749 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_integrate/test_num_integrate_cli.rs (12785 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 162.1 KB/s
⏱️ Total time: 52ms
| true
|
num_integrate
| 322
| 5
|
[
"class_definition"
] | 0.612
| null |
example_num_interp
|
num_interp_cli.py
|
"""Interpolation CLI.
Demonstrates interpolation methods: linear, cubic, spline.
"""
import sys
from collections.abc import Callable
from dataclasses import dataclass
def linear_interp(x: float, x0: float, y0: float, x1: float, y1: float) -> float:
"""Linear interpolation between two points."""
if x1 == x0:
return y0
t = (x - x0) / (x1 - x0)
return y0 + t * (y1 - y0)
def piecewise_linear(xs: list[float], ys: list[float], x: float) -> float:
"""Piecewise linear interpolation."""
if len(xs) != len(ys) or len(xs) < 2:
raise ValueError("Need at least 2 points")
if x <= xs[0]:
return ys[0]
if x >= xs[-1]:
return ys[-1]
for i in range(len(xs) - 1):
if xs[i] <= x <= xs[i + 1]:
return linear_interp(x, xs[i], ys[i], xs[i + 1], ys[i + 1])
return ys[-1]
def lagrange(xs: list[float], ys: list[float], x: float) -> float:
"""Lagrange polynomial interpolation."""
n = len(xs)
result = 0.0
for i in range(n):
term = ys[i]
for j in range(n):
if i != j:
term *= (x - xs[j]) / (xs[i] - xs[j])
result += term
return result
def newton_divided_diff(xs: list[float], ys: list[float]) -> list[float]:
"""Calculate Newton divided differences."""
n = len(xs)
coefs = ys[:]
for j in range(1, n):
for i in range(n - 1, j - 1, -1):
coefs[i] = (coefs[i] - coefs[i - 1]) / (xs[i] - xs[i - j])
return coefs
def newton_interp(xs: list[float], coefs: list[float], x: float) -> float:
"""Newton polynomial interpolation."""
n = len(coefs)
result = coefs[-1]
for i in range(n - 2, -1, -1):
result = result * (x - xs[i]) + coefs[i]
return result
@dataclass
class CubicSpline:
"""Cubic spline interpolation."""
xs: list[float]
ys: list[float]
a: list[float] # Coefficients
b: list[float]
c: list[float]
d: list[float]
@classmethod
def natural(cls, xs: list[float], ys: list[float]) -> "CubicSpline":
"""Create natural cubic spline (second derivatives = 0 at endpoints)."""
n = len(xs)
if n < 2:
raise ValueError("Need at least 2 points")
# Calculate h (intervals)
h = [xs[i + 1] - xs[i] for i in range(n - 1)]
# Set up tridiagonal system for second derivatives
alpha = [0.0] * n
for i in range(1, n - 1):
alpha[i] = (3 / h[i]) * (ys[i + 1] - ys[i]) - (3 / h[i - 1]) * (ys[i] - ys[i - 1])
# Solve tridiagonal system
diag = [1.0] + [0.0] * (n - 1)
mu = [0.0] * n
z = [0.0] * n
for i in range(1, n - 1):
diag[i] = 2 * (xs[i + 1] - xs[i - 1]) - h[i - 1] * mu[i - 1]
mu[i] = h[i] / diag[i]
z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / diag[i]
diag[n - 1] = 1.0
# Back substitution
c = [0.0] * n
b = [0.0] * (n - 1)
d = [0.0] * (n - 1)
a = ys[:-1]
for j in range(n - 2, -1, -1):
c[j] = z[j] - mu[j] * c[j + 1]
b[j] = (ys[j + 1] - ys[j]) / h[j] - h[j] * (c[j + 1] + 2 * c[j]) / 3
d[j] = (c[j + 1] - c[j]) / (3 * h[j])
return cls(xs, ys, a, b, c[:-1], d)
def __call__(self, x: float) -> float:
"""Evaluate spline at x."""
if x <= self.xs[0]:
return self.ys[0]
if x >= self.xs[-1]:
return self.ys[-1]
# Find interval
i = 0
for j in range(len(self.xs) - 1):
if self.xs[j] <= x <= self.xs[j + 1]:
i = j
break
dx = x - self.xs[i]
return self.a[i] + self.b[i] * dx + self.c[i] * dx**2 + self.d[i] * dx**3
def hermite_interp(
x0: float, y0: float, dy0: float, x1: float, y1: float, dy1: float, x: float
) -> float:
"""Hermite interpolation with derivatives."""
t = (x - x0) / (x1 - x0)
h = x1 - x0
h00 = 2 * t**3 - 3 * t**2 + 1
h10 = t**3 - 2 * t**2 + t
h01 = -2 * t**3 + 3 * t**2
h11 = t**3 - t**2
return h00 * y0 + h10 * h * dy0 + h01 * y1 + h11 * h * dy1
class Interpolator:
"""Factory for creating interpolators."""
@staticmethod
def linear(xs: list[float], ys: list[float]) -> Callable[[float], float]:
return lambda x: piecewise_linear(xs, ys, x)
@staticmethod
def polynomial(xs: list[float], ys: list[float]) -> Callable[[float], float]:
return lambda x: lagrange(xs, ys, x)
@staticmethod
def cubic_spline(xs: list[float], ys: list[float]) -> Callable[[float], float]:
spline = CubicSpline.natural(xs, ys)
return spline
def simulate_interp(operations: list[str]) -> list[str]:
"""Simulate interpolation operations."""
results: list[str] = []
xs = [0.0, 1.0, 2.0, 3.0]
ys = [0.0, 1.0, 4.0, 9.0] # y = x^2
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "linear":
x = float(parts[1])
result = piecewise_linear(xs, ys, x)
results.append(f"{result:.2f}")
elif cmd == "lagrange":
x = float(parts[1])
result = lagrange(xs, ys, x)
results.append(f"{result:.2f}")
elif cmd == "spline":
x = float(parts[1])
spline = CubicSpline.natural(xs, ys)
result = spline(x)
results.append(f"{result:.2f}")
elif cmd == "newton":
x = float(parts[1])
coefs = newton_divided_diff(xs, ys)
result = newton_interp(xs, coefs, x)
results.append(f"{result:.2f}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: num_interp_cli.py <command>")
return 1
cmd = sys.argv[1]
if cmd == "demo":
xs = [0.0, 1.0, 2.0, 3.0, 4.0]
ys = [0.0, 1.0, 4.0, 9.0, 16.0] # y = x^2
spline = CubicSpline.natural(xs, ys)
print("Interpolating y = x^2:")
for x in [0.5, 1.5, 2.5, 3.5]:
lin = piecewise_linear(xs, ys, x)
lag = lagrange(xs, ys, x)
spl = spline(x)
exact = x**2
print(
f"x={x}: linear={lin:.3f}, lagrange={lag:.3f}, spline={spl:.3f}, exact={exact:.3f}"
)
else:
print("Unknown command")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
num_interp
| 239
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 2053..2066, value: Str("CubicSpline"), kind: None })
|
|
example_num_interp
|
test_num_interp_cli.py
|
"""Tests for num_interp_cli.py"""
from num_interp_cli import (
CubicSpline,
Interpolator,
hermite_interp,
lagrange,
linear_interp,
newton_divided_diff,
newton_interp,
piecewise_linear,
simulate_interp,
)
class TestLinearInterp:
def test_midpoint(self):
result = linear_interp(0.5, 0.0, 0.0, 1.0, 1.0)
assert abs(result - 0.5) < 1e-10
def test_endpoints(self):
assert linear_interp(0.0, 0.0, 0.0, 1.0, 1.0) == 0.0
assert linear_interp(1.0, 0.0, 0.0, 1.0, 1.0) == 1.0
def test_extrapolate(self):
result = linear_interp(2.0, 0.0, 0.0, 1.0, 1.0)
assert abs(result - 2.0) < 1e-10
class TestPiecewiseLinear:
def test_at_points(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
assert piecewise_linear(xs, ys, 0.0) == 0.0
assert piecewise_linear(xs, ys, 1.0) == 1.0
assert piecewise_linear(xs, ys, 2.0) == 4.0
def test_between_points(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
result = piecewise_linear(xs, ys, 0.5)
assert abs(result - 0.5) < 1e-10
def test_clamp_left(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
assert piecewise_linear(xs, ys, -1.0) == 0.0
def test_clamp_right(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
assert piecewise_linear(xs, ys, 3.0) == 4.0
class TestLagrange:
def test_at_points(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
for x, y in zip(xs, ys, strict=False):
assert abs(lagrange(xs, ys, x) - y) < 1e-10
def test_polynomial_exact(self):
# y = x^2, should be exact with 3+ points
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
for x in [0.5, 1.5]:
expected = x**2
assert abs(lagrange(xs, ys, x) - expected) < 1e-10
def test_two_points(self):
xs = [0.0, 1.0]
ys = [0.0, 1.0]
assert abs(lagrange(xs, ys, 0.5) - 0.5) < 1e-10
class TestNewtonDividedDiff:
def test_linear(self):
xs = [0.0, 1.0]
ys = [0.0, 2.0]
coefs = newton_divided_diff(xs, ys)
assert abs(coefs[0] - 0.0) < 1e-10
assert abs(coefs[1] - 2.0) < 1e-10
def test_quadratic(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
coefs = newton_divided_diff(xs, ys)
assert len(coefs) == 3
class TestNewtonInterp:
def test_matches_lagrange(self):
xs = [0.0, 1.0, 2.0, 3.0]
ys = [0.0, 1.0, 4.0, 9.0]
coefs = newton_divided_diff(xs, ys)
for x in [0.5, 1.5, 2.5]:
newton_result = newton_interp(xs, coefs, x)
lagrange_result = lagrange(xs, ys, x)
assert abs(newton_result - lagrange_result) < 1e-10
class TestCubicSpline:
def test_at_points(self):
xs = [0.0, 1.0, 2.0, 3.0]
ys = [0.0, 1.0, 4.0, 9.0]
spline = CubicSpline.natural(xs, ys)
for x, y in zip(xs, ys, strict=False):
assert abs(spline(x) - y) < 1e-10
def test_continuity(self):
xs = [0.0, 1.0, 2.0, 3.0]
ys = [0.0, 1.0, 4.0, 9.0]
spline = CubicSpline.natural(xs, ys)
# Check continuity at interior points
for x in [1.0, 2.0]:
left = spline(x - 0.0001)
right = spline(x + 0.0001)
assert abs(left - right) < 0.01
def test_clamp_left(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
spline = CubicSpline.natural(xs, ys)
assert spline(-1.0) == 0.0
def test_clamp_right(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
spline = CubicSpline.natural(xs, ys)
assert spline(3.0) == 4.0
class TestHermiteInterp:
def test_endpoints(self):
result = hermite_interp(0, 0, 1, 1, 1, 1, 0)
assert abs(result - 0) < 1e-10
result = hermite_interp(0, 0, 1, 1, 1, 1, 1)
assert abs(result - 1) < 1e-10
def test_midpoint(self):
# Linear function y=x, derivative=1
result = hermite_interp(0, 0, 1, 2, 2, 1, 1)
assert abs(result - 1) < 1e-10
class TestInterpolator:
def test_linear(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
f = Interpolator.linear(xs, ys)
assert abs(f(0.5) - 0.5) < 1e-10
def test_polynomial(self):
xs = [0.0, 1.0, 2.0]
ys = [0.0, 1.0, 4.0]
f = Interpolator.polynomial(xs, ys)
assert abs(f(1.5) - 2.25) < 1e-10
def test_cubic_spline(self):
xs = [0.0, 1.0, 2.0, 3.0]
ys = [0.0, 1.0, 4.0, 9.0]
f = Interpolator.cubic_spline(xs, ys)
assert abs(f(1.0) - 1.0) < 1e-10
class TestSimulateInterp:
def test_linear(self):
result = simulate_interp(["linear:0.5"])
assert result == ["0.50"]
def test_lagrange(self):
result = simulate_interp(["lagrange:0.5"])
assert result == ["0.25"] # x^2 at 0.5
def test_spline(self):
result = simulate_interp(["spline:1.0"])
assert result == ["1.00"]
def test_newton(self):
result = simulate_interp(["newton:0.5"])
assert result == ["0.25"] # x^2 at 0.5
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_interp/test_num_interp_cli.py (5222 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_interp/test_num_interp_cli.rs (9366 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 98.8 KB/s
⏱️ Total time: 51ms
| true
|
num_interp
| 183
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.