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_split
|
test_split_tool.py
|
"""Tests for split_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "split_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_split/test_split_tool.py (630 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_split/test_split_tool.rs (1838 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_split/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 13.1 KB/s
⏱️ Total time: 47ms
| true
|
split
| 32
| 6
|
[] | 0
| null |
example_startswith
|
startswith_tool.py
|
#!/usr/bin/env python3
"""Startswith Example - String prefix/suffix operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="String prefix/suffix tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("starts")
s.add_argument("text")
s.add_argument("prefix")
e = subs.add_parser("ends")
e.add_argument("text")
e.add_argument("suffix")
args = parser.parse_args()
if args.cmd == "starts":
if len(args.prefix) > len(args.text):
print("false")
else:
match = True
i = 0
while i < len(args.prefix):
if args.text[i] != args.prefix[i]:
match = False
i = i + 1
if match:
print("true")
else:
print("false")
elif args.cmd == "ends":
if len(args.suffix) > len(args.text):
print("false")
else:
match = True
offset = len(args.text) - len(args.suffix)
i = 0
while i < len(args.suffix):
if args.text[offset + i] != args.suffix[i]:
match = False
i = i + 1
if match:
print("true")
else:
print("false")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_startswith/startswith_tool.py (1393 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_startswith/startswith_tool.rs (3846 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_startswith/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 28.0 KB/s
⏱️ Total time: 48ms
| true
|
startswith
| 51
| 6
|
[
"context_manager"
] | 0.652
| null |
example_startswith
|
test_startswith_tool.py
|
"""Tests for startswith_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "startswith_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_starts_true():
r = run("starts hello hel")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_starts_false():
r = run("starts hello xyz")
assert r.returncode == 0
assert r.stdout.strip() == "false"
def test_ends_true():
r = run("ends hello llo")
assert r.returncode == 0
assert r.stdout.strip() == "true"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_startswith/test_startswith_tool.py (664 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_startswith/test_startswith_tool.rs (1867 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_startswith/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 13.5 KB/s
⏱️ Total time: 48ms
| true
|
startswith
| 32
| 6
|
[] | 0
| null |
example_state_fsm
|
state_fsm_cli.py
|
"""Finite State Machine CLI.
Demonstrates FSM patterns for state management and transitions.
"""
import sys
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
S = TypeVar("S")
E = TypeVar("E")
@dataclass
class Transition(Generic[S, E]):
"""State transition definition."""
from_state: S
event: E
to_state: S
action: Callable[[], None] | None = None
guard: Callable[[], bool] | None = None
@dataclass
class FSM(Generic[S, E]):
"""Finite State Machine."""
initial_state: S
current_state: S = field(init=False)
transitions: list[Transition[S, E]] = field(default_factory=list)
on_enter: dict[S, Callable[[], None]] = field(default_factory=dict)
on_exit: dict[S, Callable[[], None]] = field(default_factory=dict)
history: list[S] = field(default_factory=list)
def __post_init__(self) -> None:
self.current_state = self.initial_state
self.history.append(self.initial_state)
def add_transition(
self,
from_state: S,
event: E,
to_state: S,
action: Callable[[], None] | None = None,
guard: Callable[[], bool] | None = None,
) -> None:
"""Add a state transition."""
self.transitions.append(Transition(from_state, event, to_state, action, guard))
def set_on_enter(self, state: S, callback: Callable[[], None]) -> None:
"""Set callback for entering a state."""
self.on_enter[state] = callback
def set_on_exit(self, state: S, callback: Callable[[], None]) -> None:
"""Set callback for exiting a state."""
self.on_exit[state] = callback
def process(self, event: E) -> bool:
"""Process an event and transition if possible."""
for trans in self.transitions:
if trans.from_state == self.current_state and trans.event == event:
if trans.guard and not trans.guard():
continue
if self.current_state in self.on_exit:
self.on_exit[self.current_state]()
if trans.action:
trans.action()
self.current_state = trans.to_state
self.history.append(trans.to_state)
if trans.to_state in self.on_enter:
self.on_enter[trans.to_state]()
return True
return False
def can_process(self, event: E) -> bool:
"""Check if event can be processed from current state."""
for trans in self.transitions:
if trans.from_state == self.current_state and trans.event == event:
if trans.guard is None or trans.guard():
return True
return False
def available_events(self) -> list[E]:
"""Get list of events that can be processed from current state."""
events = []
for trans in self.transitions:
if trans.from_state == self.current_state:
if trans.guard is None or trans.guard():
events.append(trans.event)
return events
def reset(self) -> None:
"""Reset to initial state."""
self.current_state = self.initial_state
self.history = [self.initial_state]
class TrafficLight:
"""Traffic light state machine example."""
def __init__(self) -> None:
self.fsm: FSM[str, str] = FSM("red")
self.fsm.add_transition("red", "timer", "green")
self.fsm.add_transition("green", "timer", "yellow")
self.fsm.add_transition("yellow", "timer", "red")
def tick(self) -> str:
"""Advance to next state."""
self.fsm.process("timer")
return self.fsm.current_state
@property
def state(self) -> str:
return self.fsm.current_state
class Turnstile:
"""Turnstile state machine example."""
def __init__(self) -> None:
self.fsm: FSM[str, str] = FSM("locked")
self.coins_inserted = 0
self.fsm.add_transition("locked", "coin", "unlocked", action=self._accept_coin)
self.fsm.add_transition("unlocked", "push", "locked", action=self._pass_through)
self.fsm.add_transition("locked", "push", "locked")
self.fsm.add_transition("unlocked", "coin", "unlocked", action=self._accept_coin)
def _accept_coin(self) -> None:
self.coins_inserted += 1
def _pass_through(self) -> None:
pass
def insert_coin(self) -> bool:
return self.fsm.process("coin")
def push(self) -> bool:
return self.fsm.process("push")
@property
def state(self) -> str:
return self.fsm.current_state
class Connection:
"""TCP-like connection state machine."""
def __init__(self) -> None:
self.fsm: FSM[str, str] = FSM("closed")
self._setup_transitions()
def _setup_transitions(self) -> None:
self.fsm.add_transition("closed", "open", "opening")
self.fsm.add_transition("opening", "connected", "open")
self.fsm.add_transition("opening", "error", "closed")
self.fsm.add_transition("open", "close", "closing")
self.fsm.add_transition("open", "error", "closed")
self.fsm.add_transition("closing", "closed", "closed")
self.fsm.add_transition("closing", "error", "closed")
def open(self) -> bool:
return self.fsm.process("open")
def connected(self) -> bool:
return self.fsm.process("connected")
def close(self) -> bool:
return self.fsm.process("close")
def error(self) -> bool:
return self.fsm.process("error")
def closed(self) -> bool:
return self.fsm.process("closed")
@property
def state(self) -> str:
return self.fsm.current_state
class Order:
"""Order processing state machine."""
STATES = ["created", "confirmed", "processing", "shipped", "delivered", "cancelled"]
def __init__(self) -> None:
self.fsm: FSM[str, str] = FSM("created")
self._paid = False
self._setup_transitions()
def _setup_transitions(self) -> None:
self.fsm.add_transition("created", "confirm", "confirmed")
self.fsm.add_transition("created", "cancel", "cancelled")
self.fsm.add_transition("confirmed", "pay", "processing", guard=lambda: True)
self.fsm.add_transition("confirmed", "cancel", "cancelled")
self.fsm.add_transition("processing", "ship", "shipped")
self.fsm.add_transition("processing", "cancel", "cancelled")
self.fsm.add_transition("shipped", "deliver", "delivered")
def confirm(self) -> bool:
return self.fsm.process("confirm")
def pay(self) -> bool:
result = self.fsm.process("pay")
if result:
self._paid = True
return result
def ship(self) -> bool:
return self.fsm.process("ship")
def deliver(self) -> bool:
return self.fsm.process("deliver")
def cancel(self) -> bool:
return self.fsm.process("cancel")
@property
def state(self) -> str:
return self.fsm.current_state
@dataclass
class StateBuilder(Generic[S, E]):
"""Builder for FSM."""
initial: S
transitions: list[tuple[S, E, S]] = field(default_factory=list)
def add(self, from_state: S, event: E, to_state: S) -> "StateBuilder[S, E]":
self.transitions.append((from_state, event, to_state))
return self
def build(self) -> FSM[S, E]:
fsm: FSM[S, E] = FSM(self.initial)
for from_s, event, to_s in self.transitions:
fsm.add_transition(from_s, event, to_s)
return fsm
def validate_fsm(fsm: FSM[Any, Any], states: list[Any]) -> list[str]:
"""Validate FSM for common issues."""
errors = []
# Check if all transition states are valid
for trans in fsm.transitions:
if trans.from_state not in states:
errors.append(f"Invalid from_state: {trans.from_state}")
if trans.to_state not in states:
errors.append(f"Invalid to_state: {trans.to_state}")
# Check if initial state is valid
if fsm.initial_state not in states:
errors.append(f"Invalid initial_state: {fsm.initial_state}")
return errors
def simulate_fsm(transitions: list[str], events: list[str]) -> list[str]:
"""Simulate FSM from transition definitions."""
fsm: FSM[str, str] = FSM(transitions[0].split("-")[0] if transitions else "start")
for trans in transitions:
parts = trans.split("-")
if len(parts) == 3:
from_s, event, to_s = parts
fsm.add_transition(from_s, event, to_s)
results = []
for event in events:
if event == "state":
results.append(fsm.current_state)
elif event == "history":
results.append(",".join(fsm.history))
elif event == "available":
results.append(",".join(fsm.available_events()))
else:
success = fsm.process(event)
results.append("ok" if success else "fail")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: state_fsm_cli.py <command> [args...]")
print("Commands: traffic, turnstile, order, simulate")
return 1
cmd = sys.argv[1]
if cmd == "traffic":
light = TrafficLight()
print(f"Initial: {light.state}")
for _ in range(6):
light.tick()
print(f"After tick: {light.state}")
elif cmd == "turnstile":
turnstile = Turnstile()
print(f"Initial: {turnstile.state}")
print(f"Push (should fail): {turnstile.push()} -> {turnstile.state}")
print(f"Insert coin: {turnstile.insert_coin()} -> {turnstile.state}")
print(f"Push (should pass): {turnstile.push()} -> {turnstile.state}")
elif cmd == "order":
order = Order()
print(f"Initial: {order.state}")
order.confirm()
print(f"After confirm: {order.state}")
order.pay()
print(f"After pay: {order.state}")
order.ship()
print(f"After ship: {order.state}")
order.deliver()
print(f"After deliver: {order.state}")
elif cmd == "simulate":
if len(sys.argv) < 4:
print("Usage: simulate <transitions> <events>", file=sys.stderr)
return 1
transitions = sys.argv[2].split(",")
events = sys.argv[3].split(",")
results = simulate_fsm(transitions, events)
for result in results:
print(result)
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
state_fsm
| 342
| 0
|
[
"class_definition",
"decorator",
"multiprocessing"
] | 0.612
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 2067..2099, value: Attribute(ExprAttribute { range: 2067..2079, value: Name(ExprName { range: 2067..2071, id: Identifier("self"), ctx: Load }), attr: Identifier("on_exit"), ctx: Load }), slice: Attribute(ExprAttribute { range: 2080..2098, value: Name(ExprName { range: 2080..2084, id: Identifier("self"), ctx: Load }), attr: Identifier("current_state"), ctx: Load }), ctx: Load })
|
|
example_state_fsm
|
test_state_fsm_cli.py
|
"""Tests for state_fsm_cli.py"""
from state_fsm_cli import (
FSM,
Connection,
Order,
StateBuilder,
TrafficLight,
Turnstile,
simulate_fsm,
validate_fsm,
)
class TestFSM:
def test_initial_state(self):
fsm: FSM[str, str] = FSM("start")
assert fsm.current_state == "start"
def test_add_transition(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
assert len(fsm.transitions) == 1
def test_process_valid(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
result = fsm.process("go")
assert result is True
assert fsm.current_state == "b"
def test_process_invalid(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
result = fsm.process("stop")
assert result is False
assert fsm.current_state == "a"
def test_can_process(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
assert fsm.can_process("go")
assert not fsm.can_process("stop")
def test_available_events(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
fsm.add_transition("a", "stop", "c")
events = fsm.available_events()
assert set(events) == {"go", "stop"}
def test_history(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
fsm.add_transition("b", "go", "c")
fsm.process("go")
fsm.process("go")
assert fsm.history == ["a", "b", "c"]
def test_reset(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
fsm.process("go")
fsm.reset()
assert fsm.current_state == "a"
assert fsm.history == ["a"]
def test_guard(self):
fsm: FSM[str, str] = FSM("a")
guard_value = [False]
fsm.add_transition("a", "go", "b", guard=lambda: guard_value[0])
assert not fsm.process("go")
assert fsm.current_state == "a"
guard_value[0] = True
assert fsm.process("go")
assert fsm.current_state == "b"
def test_action(self):
fsm: FSM[str, str] = FSM("a")
action_called = [False]
fsm.add_transition("a", "go", "b", action=lambda: action_called.__setitem__(0, True))
fsm.process("go")
assert action_called[0]
def test_on_enter_exit(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
entered = [False]
exited = [False]
fsm.set_on_enter("b", lambda: entered.__setitem__(0, True))
fsm.set_on_exit("a", lambda: exited.__setitem__(0, True))
fsm.process("go")
assert entered[0]
assert exited[0]
class TestTrafficLight:
def test_initial(self):
light = TrafficLight()
assert light.state == "red"
def test_cycle(self):
light = TrafficLight()
light.tick()
assert light.state == "green"
light.tick()
assert light.state == "yellow"
light.tick()
assert light.state == "red"
def test_full_cycle(self):
light = TrafficLight()
states = [light.state]
for _ in range(6):
light.tick()
states.append(light.state)
assert states == ["red", "green", "yellow", "red", "green", "yellow", "red"]
class TestTurnstile:
def test_initial(self):
turnstile = Turnstile()
assert turnstile.state == "locked"
def test_push_locked(self):
turnstile = Turnstile()
turnstile.push()
assert turnstile.state == "locked"
def test_coin_unlocks(self):
turnstile = Turnstile()
turnstile.insert_coin()
assert turnstile.state == "unlocked"
def test_push_unlocked(self):
turnstile = Turnstile()
turnstile.insert_coin()
turnstile.push()
assert turnstile.state == "locked"
def test_multiple_coins(self):
turnstile = Turnstile()
turnstile.insert_coin()
turnstile.insert_coin()
assert turnstile.state == "unlocked"
assert turnstile.coins_inserted == 2
class TestConnection:
def test_initial(self):
conn = Connection()
assert conn.state == "closed"
def test_open(self):
conn = Connection()
conn.open()
assert conn.state == "opening"
def test_connected(self):
conn = Connection()
conn.open()
conn.connected()
assert conn.state == "open"
def test_close(self):
conn = Connection()
conn.open()
conn.connected()
conn.close()
assert conn.state == "closing"
def test_error_from_open(self):
conn = Connection()
conn.open()
conn.connected()
conn.error()
assert conn.state == "closed"
class TestOrder:
def test_initial(self):
order = Order()
assert order.state == "created"
def test_confirm(self):
order = Order()
order.confirm()
assert order.state == "confirmed"
def test_pay(self):
order = Order()
order.confirm()
order.pay()
assert order.state == "processing"
def test_ship(self):
order = Order()
order.confirm()
order.pay()
order.ship()
assert order.state == "shipped"
def test_deliver(self):
order = Order()
order.confirm()
order.pay()
order.ship()
order.deliver()
assert order.state == "delivered"
def test_cancel_from_created(self):
order = Order()
order.cancel()
assert order.state == "cancelled"
def test_cancel_from_processing(self):
order = Order()
order.confirm()
order.pay()
order.cancel()
assert order.state == "cancelled"
class TestStateBuilder:
def test_build(self):
fsm = (
StateBuilder("a")
.add("a", "go", "b")
.add("b", "go", "c")
.build()
)
assert fsm.current_state == "a"
fsm.process("go")
assert fsm.current_state == "b"
class TestValidateFSM:
def test_valid(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "b")
errors = validate_fsm(fsm, ["a", "b"])
assert errors == []
def test_invalid_from_state(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("x", "go", "b")
errors = validate_fsm(fsm, ["a", "b"])
assert any("x" in e for e in errors)
def test_invalid_to_state(self):
fsm: FSM[str, str] = FSM("a")
fsm.add_transition("a", "go", "x")
errors = validate_fsm(fsm, ["a", "b"])
assert any("x" in e for e in errors)
class TestSimulateFSM:
def test_basic(self):
result = simulate_fsm(["a-go-b", "b-go-c"], ["go", "state"])
assert result == ["ok", "b"]
def test_multiple_transitions(self):
result = simulate_fsm(["a-go-b", "b-go-c"], ["go", "go", "state"])
assert result == ["ok", "ok", "c"]
def test_history(self):
result = simulate_fsm(["a-go-b", "b-go-c"], ["go", "go", "history"])
assert result == ["ok", "ok", "a,b,c"]
def test_available(self):
result = simulate_fsm(["a-x-b", "a-y-c"], ["available"])
assert "x" in result[0] and "y" in result[0]
def test_fail(self):
result = simulate_fsm(["a-go-b"], ["stop"])
assert result == ["fail"]
| false
|
state_fsm
| 283
| 0
|
[
"class_definition"
] | 0.612
|
Error: add() requires exactly one argument
|
|
example_state_lexer
|
state_lexer_cli.py
|
"""Lexer/Tokenizer CLI.
Demonstrates lexical analysis patterns for tokenizing source code.
"""
import sys
from dataclasses import dataclass
from enum import Enum, auto
from typing import Any
class TokType(Enum):
"""Token types."""
# Literals
INTEGER = auto()
FLOAT = auto()
STRING = auto()
CHAR = auto()
BOOL = auto()
# Identifiers and keywords
IDENTIFIER = auto()
KEYWORD = auto()
# Operators
PLUS = auto()
MINUS = auto()
STAR = auto()
SLASH = auto()
PERCENT = auto()
CARET = auto()
AMPERSAND = auto()
PIPE = auto()
TILDE = auto()
BANG = auto()
QUESTION = auto()
# Comparison
EQ = auto()
NE = auto()
LT = auto()
LE = auto()
GT = auto()
GE = auto()
# Assignment
ASSIGN = auto()
PLUS_ASSIGN = auto()
MINUS_ASSIGN = auto()
STAR_ASSIGN = auto()
SLASH_ASSIGN = auto()
# Delimiters
LPAREN = auto()
RPAREN = auto()
LBRACKET = auto()
RBRACKET = auto()
LBRACE = auto()
RBRACE = auto()
COMMA = auto()
DOT = auto()
COLON = auto()
SEMICOLON = auto()
ARROW = auto()
# Special
NEWLINE = auto()
COMMENT = auto()
WHITESPACE = auto()
EOF = auto()
ERROR = auto()
@dataclass
class Token:
"""Lexer token."""
type: TokType
value: Any
line: int
column: int
length: int
def __repr__(self) -> str:
return f"Token({self.type.name}, {self.value!r}, {self.line}:{self.column})"
@dataclass
class LexerConfig:
"""Lexer configuration."""
keywords: set[str]
skip_whitespace: bool = True
skip_comments: bool = True
string_delimiters: str = "\"'"
single_line_comment: str = "//"
multi_line_comment: tuple[str, str] = ("/*", "*/")
DEFAULT_KEYWORDS = {
"if",
"else",
"while",
"for",
"return",
"break",
"continue",
"fn",
"let",
"const",
"var",
"true",
"false",
"null",
"class",
"struct",
"enum",
"import",
"export",
}
class Lexer:
"""Source code lexer."""
def __init__(self, source: str, config: LexerConfig | None = None) -> None:
self.source = source
self.config = config or LexerConfig(keywords=DEFAULT_KEYWORDS)
self.pos = 0
self.line = 1
self.column = 1
self.tokens: list[Token] = []
def tokenize(self) -> list[Token]:
"""Tokenize the source code."""
self.tokens = []
while not self.is_at_end():
self.scan_token()
self.tokens.append(Token(TokType.EOF, None, self.line, self.column, 0))
return self.tokens
def scan_token(self) -> None:
"""Scan next token."""
start_pos = self.pos
start_line = self.line
start_col = self.column
char = self.advance()
# Whitespace
if char in " \t\r":
if not self.config.skip_whitespace:
self.add_token(TokType.WHITESPACE, char, start_line, start_col, 1)
return
if char == "\n":
self.line += 1
self.column = 1
if not self.config.skip_whitespace:
self.add_token(TokType.NEWLINE, "\n", start_line, start_col, 1)
return
# Comments
if char == "/" and self.peek() == "/":
self.advance()
comment = self.read_until("\n")
if not self.config.skip_comments:
self.add_token(TokType.COMMENT, comment, start_line, start_col, len(comment) + 2)
return
if char == "/" and self.peek() == "*":
self.advance()
comment = self.read_multi_line_comment()
if not self.config.skip_comments:
self.add_token(TokType.COMMENT, comment, start_line, start_col, len(comment) + 4)
return
# Strings
if char in self.config.string_delimiters:
string = self.read_string(char)
self.add_token(TokType.STRING, string, start_line, start_col, len(string) + 2)
return
# Numbers
if char.isdigit():
number, is_float = self.read_number(char)
tok_type = TokType.FLOAT if is_float else TokType.INTEGER
self.add_token(tok_type, number, start_line, start_col, self.pos - start_pos)
return
# Identifiers and keywords
if char.isalpha() or char == "_":
identifier = self.read_identifier(char)
if identifier in self.config.keywords:
self.add_token(TokType.KEYWORD, identifier, start_line, start_col, len(identifier))
elif identifier in ("true", "false"):
self.add_token(
TokType.BOOL, identifier == "true", start_line, start_col, len(identifier)
)
else:
self.add_token(
TokType.IDENTIFIER, identifier, start_line, start_col, len(identifier)
)
return
# Operators and delimiters
token = self.scan_operator(char, start_line, start_col)
if token:
self.tokens.append(token)
return
# Unknown character
self.add_token(TokType.ERROR, char, start_line, start_col, 1)
def scan_operator(self, char: str, line: int, col: int) -> Token | None:
"""Scan operator or delimiter."""
# Two-character operators
two_char = char + self.peek() if not self.is_at_end() else char
two_char_ops = {
"==": TokType.EQ,
"!=": TokType.NE,
"<=": TokType.LE,
">=": TokType.GE,
"+=": TokType.PLUS_ASSIGN,
"-=": TokType.MINUS_ASSIGN,
"*=": TokType.STAR_ASSIGN,
"/=": TokType.SLASH_ASSIGN,
"->": TokType.ARROW,
}
if two_char in two_char_ops:
self.advance()
return Token(two_char_ops[two_char], two_char, line, col, 2)
# Single-character operators
single_char_ops = {
"+": TokType.PLUS,
"-": TokType.MINUS,
"*": TokType.STAR,
"/": TokType.SLASH,
"%": TokType.PERCENT,
"^": TokType.CARET,
"&": TokType.AMPERSAND,
"|": TokType.PIPE,
"~": TokType.TILDE,
"!": TokType.BANG,
"?": TokType.QUESTION,
"<": TokType.LT,
">": TokType.GT,
"=": TokType.ASSIGN,
"(": TokType.LPAREN,
")": TokType.RPAREN,
"[": TokType.LBRACKET,
"]": TokType.RBRACKET,
"{": TokType.LBRACE,
"}": TokType.RBRACE,
",": TokType.COMMA,
".": TokType.DOT,
":": TokType.COLON,
";": TokType.SEMICOLON,
}
if char in single_char_ops:
return Token(single_char_ops[char], char, line, col, 1)
return None
def read_string(self, quote: str) -> str:
"""Read string literal."""
chars = []
while not self.is_at_end() and self.peek() != quote:
char = self.advance()
if char == "\\":
escaped = self.advance()
escape_map = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"', "'": "'"}
chars.append(escape_map.get(escaped, escaped))
else:
chars.append(char)
if not self.is_at_end():
self.advance() # Closing quote
return "".join(chars)
def read_number(self, first: str) -> tuple[float | int, bool]:
"""Read numeric literal."""
chars = [first]
is_float = False
while not self.is_at_end() and (self.peek().isdigit() or self.peek() == "."):
if self.peek() == ".":
if is_float:
break
is_float = True
chars.append(self.advance())
# Handle exponent
if not self.is_at_end() and self.peek().lower() == "e":
chars.append(self.advance())
if not self.is_at_end() and self.peek() in "+-":
chars.append(self.advance())
while not self.is_at_end() and self.peek().isdigit():
chars.append(self.advance())
is_float = True
value = "".join(chars)
return (float(value), True) if is_float else (int(value), False)
def read_identifier(self, first: str) -> str:
"""Read identifier."""
chars = [first]
while not self.is_at_end() and (self.peek().isalnum() or self.peek() == "_"):
chars.append(self.advance())
return "".join(chars)
def read_until(self, delimiter: str) -> str:
"""Read until delimiter."""
chars = []
while not self.is_at_end() and self.peek() != delimiter:
chars.append(self.advance())
return "".join(chars)
def read_multi_line_comment(self) -> str:
"""Read multi-line comment."""
chars = []
while not self.is_at_end():
if (
self.peek() == "*"
and self.pos + 1 < len(self.source)
and self.source[self.pos + 1] == "/"
):
self.advance()
self.advance()
break
if self.peek() == "\n":
self.line += 1
self.column = 0
chars.append(self.advance())
return "".join(chars)
def advance(self) -> str:
"""Advance position and return character."""
char = self.source[self.pos]
self.pos += 1
self.column += 1
return char
def peek(self) -> str:
"""Peek at current character."""
if self.is_at_end():
return "\0"
return self.source[self.pos]
def is_at_end(self) -> bool:
"""Check if at end of source."""
return self.pos >= len(self.source)
def add_token(self, type: TokType, value: Any, line: int, col: int, length: int) -> None:
"""Add token to list."""
self.tokens.append(Token(type, value, line, col, length))
def tokenize(source: str) -> list[Token]:
"""Tokenize source code."""
return Lexer(source).tokenize()
def token_summary(tokens: list[Token]) -> dict[str, int]:
"""Get summary of token types."""
summary: dict[str, int] = {}
for token in tokens:
name = token.type.name
summary[name] = summary.get(name, 0) + 1
return summary
def format_tokens(tokens: list[Token]) -> str:
"""Format tokens as string."""
lines = []
for token in tokens:
if token.type == TokType.EOF:
continue
lines.append(f"{token.line}:{token.column} {token.type.name} {token.value!r}")
return "\n".join(lines)
def simulate_lexer(operations: list[str]) -> list[str]:
"""Simulate lexer operations."""
results = []
tokens: list[Token] = []
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "tokenize":
tokens = tokenize(parts[1])
results.append(str(len(tokens)))
elif cmd == "count":
count = sum(1 for t in tokens if t.type.name == parts[1])
results.append(str(count))
elif cmd == "types":
types = [t.type.name for t in tokens if t.type != TokType.EOF]
results.append(",".join(types))
elif cmd == "values":
values = [str(t.value) for t in tokens if t.type != TokType.EOF]
results.append(",".join(values))
elif cmd == "summary":
summary = token_summary(tokens)
results.append(",".join(f"{k}:{v}" for k, v in sorted(summary.items())))
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: state_lexer_cli.py <command> [args...]")
print("Commands: tokenize, summary, format")
return 1
cmd = sys.argv[1]
if cmd == "tokenize":
source = sys.stdin.read() if len(sys.argv) < 3 else sys.argv[2]
tokens = tokenize(source)
for token in tokens:
if token.type != TokType.EOF:
print(f"{token.type.name}: {token.value!r}")
elif cmd == "summary":
source = sys.stdin.read() if len(sys.argv) < 3 else sys.argv[2]
tokens = tokenize(source)
summary = token_summary(tokens)
for name, count in sorted(summary.items()):
print(f"{name}: {count}")
elif cmd == "format":
source = sys.stdin.read() if len(sys.argv) < 3 else sys.argv[2]
tokens = tokenize(source)
print(format_tokens(tokens))
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
state_lexer
| 451
| 0
|
[
"class_definition",
"stdin_usage",
"decorator"
] | 0.612
|
Type inference hints:
Hint: list[Any] for variable 'lines' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type)
Hint: str for variable 'op' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'tokens' [High] (usage patterns suggest this type)
Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'name' [Medium] (u
|
|
example_state_lexer
|
test_state_lexer_cli.py
|
"""Tests for state_lexer_cli.py"""
from state_lexer_cli import (
Lexer,
LexerConfig,
Token,
TokType,
format_tokens,
simulate_lexer,
token_summary,
tokenize,
)
class TestToken:
def test_repr(self):
token = Token(TokType.INTEGER, 42, 1, 1, 2)
assert "INTEGER" in repr(token)
assert "42" in repr(token)
class TestLexer:
def test_integer(self):
tokens = tokenize("42")
assert tokens[0].type == TokType.INTEGER
assert tokens[0].value == 42
def test_float(self):
tokens = tokenize("3.14")
assert tokens[0].type == TokType.FLOAT
assert tokens[0].value == 3.14
def test_string_double(self):
tokens = tokenize('"hello"')
assert tokens[0].type == TokType.STRING
assert tokens[0].value == "hello"
def test_string_single(self):
tokens = tokenize("'hello'")
assert tokens[0].type == TokType.STRING
assert tokens[0].value == "hello"
def test_string_escape(self):
tokens = tokenize('"hello\\nworld"')
assert tokens[0].value == "hello\nworld"
def test_identifier(self):
tokens = tokenize("foo")
assert tokens[0].type == TokType.IDENTIFIER
assert tokens[0].value == "foo"
def test_keyword(self):
tokens = tokenize("if")
assert tokens[0].type == TokType.KEYWORD
assert tokens[0].value == "if"
def test_bool_true(self):
tokens = tokenize("true")
# Note: true/false are in default keywords, so they're treated as keywords
assert tokens[0].type == TokType.KEYWORD
assert tokens[0].value == "true"
def test_bool_false(self):
tokens = tokenize("false")
assert tokens[0].type == TokType.KEYWORD
assert tokens[0].value == "false"
def test_operators(self):
tokens = tokenize("+ - * / %")
types = [t.type for t in tokens[:-1]]
assert TokType.PLUS in types
assert TokType.MINUS in types
assert TokType.STAR in types
assert TokType.SLASH in types
assert TokType.PERCENT in types
def test_comparison(self):
tokens = tokenize("< <= > >= == !=")
types = [t.type for t in tokens[:-1]]
assert TokType.LT in types
assert TokType.LE in types
assert TokType.GT in types
assert TokType.GE in types
assert TokType.EQ in types
assert TokType.NE in types
def test_assignment(self):
tokens = tokenize("= += -= *= /=")
types = [t.type for t in tokens[:-1]]
assert TokType.ASSIGN in types
assert TokType.PLUS_ASSIGN in types
assert TokType.MINUS_ASSIGN in types
assert TokType.STAR_ASSIGN in types
assert TokType.SLASH_ASSIGN in types
def test_delimiters(self):
tokens = tokenize("( ) [ ] { } , . : ;")
types = [t.type for t in tokens[:-1]]
assert TokType.LPAREN in types
assert TokType.RPAREN in types
assert TokType.LBRACKET in types
assert TokType.RBRACKET in types
assert TokType.LBRACE in types
assert TokType.RBRACE in types
assert TokType.COMMA in types
assert TokType.DOT in types
assert TokType.COLON in types
assert TokType.SEMICOLON in types
def test_arrow(self):
tokens = tokenize("->")
assert tokens[0].type == TokType.ARROW
def test_comment_single(self):
tokens = tokenize("// comment\n42")
assert tokens[0].type == TokType.INTEGER
def test_comment_multi(self):
tokens = tokenize("/* comment */ 42")
assert tokens[0].type == TokType.INTEGER
def test_whitespace_skip(self):
tokens = tokenize(" 42 ")
assert tokens[0].type == TokType.INTEGER
def test_eof(self):
tokens = tokenize("")
assert tokens[0].type == TokType.EOF
def test_line_tracking(self):
tokens = tokenize("a\nb")
assert tokens[0].line == 1
assert tokens[1].line == 2
def test_column_tracking(self):
tokens = tokenize("ab cd")
assert tokens[0].column == 1
assert tokens[1].column == 4
class TestLexerConfig:
def test_custom_keywords(self):
config = LexerConfig(keywords={"custom"})
lexer = Lexer("custom normal", config)
tokens = lexer.tokenize()
assert tokens[0].type == TokType.KEYWORD
assert tokens[1].type == TokType.IDENTIFIER
def test_keep_whitespace(self):
config = LexerConfig(keywords=set(), skip_whitespace=False)
lexer = Lexer(" a ", config)
tokens = lexer.tokenize()
assert TokType.WHITESPACE in [t.type for t in tokens]
def test_keep_comments(self):
config = LexerConfig(keywords=set(), skip_comments=False)
lexer = Lexer("// comment", config)
tokens = lexer.tokenize()
assert TokType.COMMENT in [t.type for t in tokens]
class TestTokenSummary:
def test_summary(self):
tokens = tokenize("let x = 42;")
summary = token_summary(tokens)
assert "KEYWORD" in summary
assert "IDENTIFIER" in summary
assert "INTEGER" in summary
class TestFormatTokens:
def test_format(self):
tokens = tokenize("42")
result = format_tokens(tokens)
assert "INTEGER" in result
assert "42" in result
class TestSimulateLexer:
def test_tokenize(self):
result = simulate_lexer(["tokenize:let x = 42;"])
assert int(result[0]) > 0
def test_count(self):
result = simulate_lexer(["tokenize:let x = 42;", "count:INTEGER"])
assert result[1] == "1"
def test_types(self):
result = simulate_lexer(["tokenize:1 + 2", "types"])
assert "INTEGER" in result[1]
assert "PLUS" in result[1]
def test_values(self):
result = simulate_lexer(["tokenize:1 + 2", "values"])
assert "1" in result[1]
assert "2" in result[1]
def test_summary(self):
result = simulate_lexer(["tokenize:let x = 42;", "summary"])
assert "KEYWORD" in result[1]
class TestComplexSource:
def test_function_definition(self):
source = "fn add(a, b) { return a + b; }"
tokens = tokenize(source)
types = [t.type for t in tokens[:-1]]
assert TokType.KEYWORD in types
assert TokType.IDENTIFIER in types
assert TokType.LPAREN in types
assert TokType.RPAREN in types
assert TokType.LBRACE in types
assert TokType.RBRACE in types
def test_scientific_notation(self):
tokens = tokenize("1e10")
assert tokens[0].type == TokType.FLOAT
assert tokens[0].value == 1e10
def test_negative_exponent(self):
tokens = tokenize("1.5e-3")
assert tokens[0].type == TokType.FLOAT
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_state_lexer/test_state_lexer_cli.py (6854 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_state_lexer/test_state_lexer_cli.rs (14313 bytes)
⏱️ Parse time: 54ms
📊 Throughput: 122.3 KB/s
⏱️ Total time: 54ms
| true
|
state_lexer
| 222
| 5
|
[
"class_definition"
] | 0.612
| null |
example_state_machine
|
state_machine_cli.py
|
"""Generic State Machine Pattern CLI.
Demonstrates state pattern for modeling complex state transitions.
"""
import sys
from abc import ABC, abstractmethod
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Generic, TypeVar
S = TypeVar("S")
C = TypeVar("C")
class State(ABC, Generic[C]):
"""Abstract state interface."""
@abstractmethod
def name(self) -> str:
"""Get state name."""
...
def on_enter(self, context: C) -> None:
"""Called when entering this state."""
pass
def on_exit(self, context: C) -> None:
"""Called when exiting this state."""
pass
@abstractmethod
def handle(self, context: C, event: str) -> "State[C] | None":
"""Handle event and return next state."""
...
@dataclass
class StateMachine(Generic[C]):
"""Generic state machine."""
context: C
initial_state: State[C]
current_state: State[C] = field(init=False)
history: list[str] = field(default_factory=list)
listeners: list[Callable[[str, str], None]] = field(default_factory=list)
def __post_init__(self) -> None:
self.current_state = self.initial_state
self.history.append(self.initial_state.name())
self.initial_state.on_enter(self.context)
def process(self, event: str) -> bool:
"""Process event through current state."""
next_state = self.current_state.handle(self.context, event)
if next_state is not None:
old_name = self.current_state.name()
self.current_state.on_exit(self.context)
self.current_state = next_state
self.history.append(next_state.name())
next_state.on_enter(self.context)
for listener in self.listeners:
listener(old_name, next_state.name())
return True
return False
def add_listener(self, listener: Callable[[str, str], None]) -> None:
"""Add state change listener."""
self.listeners.append(listener)
@property
def state_name(self) -> str:
return self.current_state.name()
# Vending Machine Example
@dataclass
class VendingContext:
"""Vending machine context."""
balance: int = 0
selected_item: str = ""
item_prices: dict[str, int] = field(
default_factory=lambda: {"cola": 100, "chips": 75, "candy": 50}
)
inventory: dict[str, int] = field(default_factory=lambda: {"cola": 5, "chips": 3, "candy": 10})
dispensed: str = ""
class IdleState(State[VendingContext]):
"""Idle state - waiting for coins."""
def name(self) -> str:
return "idle"
def on_enter(self, context: VendingContext) -> None:
context.balance = 0
context.selected_item = ""
context.dispensed = ""
def handle(self, context: VendingContext, event: str) -> State[VendingContext] | None:
if event.startswith("insert:"):
amount = int(event.split(":")[1])
context.balance += amount
return SelectingState()
return None
class SelectingState(State[VendingContext]):
"""Selecting state - has coins, selecting item."""
def name(self) -> str:
return "selecting"
def handle(self, context: VendingContext, event: str) -> State[VendingContext] | None:
if event.startswith("insert:"):
amount = int(event.split(":")[1])
context.balance += amount
return None
if event.startswith("select:"):
item = event.split(":")[1]
if item in context.item_prices:
context.selected_item = item
price = context.item_prices[item]
if context.balance >= price and context.inventory.get(item, 0) > 0:
return DispensingState()
return InsufficientState()
return None
if event == "cancel":
return IdleState()
return None
class InsufficientState(State[VendingContext]):
"""Insufficient funds or no stock."""
def name(self) -> str:
return "insufficient"
def handle(self, context: VendingContext, event: str) -> State[VendingContext] | None:
if event.startswith("insert:"):
amount = int(event.split(":")[1])
context.balance += amount
price = context.item_prices.get(context.selected_item, 0)
if context.balance >= price:
return DispensingState()
return None
if event == "cancel":
return IdleState()
return None
class DispensingState(State[VendingContext]):
"""Dispensing item."""
def name(self) -> str:
return "dispensing"
def on_enter(self, context: VendingContext) -> None:
item = context.selected_item
price = context.item_prices.get(item, 0)
context.balance -= price
context.inventory[item] -= 1
context.dispensed = item
def handle(self, context: VendingContext, event: str) -> State[VendingContext] | None:
if event == "take":
if context.balance > 0:
return ChangeState()
return IdleState()
return None
class ChangeState(State[VendingContext]):
"""Returning change."""
def name(self) -> str:
return "change"
def on_enter(self, context: VendingContext) -> None:
pass # Change is available
def handle(self, context: VendingContext, event: str) -> State[VendingContext] | None:
if event == "take_change":
context.balance = 0
return IdleState()
return None
class VendingMachine:
"""Vending machine facade."""
def __init__(self) -> None:
self.context = VendingContext()
self.machine = StateMachine(self.context, IdleState())
def insert_coin(self, amount: int) -> bool:
return self.machine.process(f"insert:{amount}")
def select_item(self, item: str) -> bool:
return self.machine.process(f"select:{item}")
def cancel(self) -> bool:
return self.machine.process("cancel")
def take_item(self) -> bool:
return self.machine.process("take")
def take_change(self) -> bool:
return self.machine.process("take_change")
@property
def state(self) -> str:
return self.machine.state_name
@property
def balance(self) -> int:
return self.context.balance
@property
def dispensed(self) -> str:
return self.context.dispensed
# Document Workflow Example
@dataclass
class DocumentContext:
"""Document workflow context."""
title: str = ""
content: str = ""
author: str = ""
reviewer: str = ""
comments: list[str] = field(default_factory=list)
class DraftState(State[DocumentContext]):
def name(self) -> str:
return "draft"
def handle(self, context: DocumentContext, event: str) -> State[DocumentContext] | None:
if event == "submit":
if context.content:
return ReviewState()
return None
class ReviewState(State[DocumentContext]):
def name(self) -> str:
return "review"
def handle(self, context: DocumentContext, event: str) -> State[DocumentContext] | None:
if event == "approve":
return ApprovedState()
if event == "reject":
return DraftState()
if event.startswith("comment:"):
context.comments.append(event.split(":", 1)[1])
return None
class ApprovedState(State[DocumentContext]):
def name(self) -> str:
return "approved"
def handle(self, context: DocumentContext, event: str) -> State[DocumentContext] | None:
if event == "publish":
return PublishedState()
if event == "archive":
return ArchivedState()
return None
class PublishedState(State[DocumentContext]):
def name(self) -> str:
return "published"
def handle(self, context: DocumentContext, event: str) -> State[DocumentContext] | None:
if event == "unpublish":
return ApprovedState()
if event == "archive":
return ArchivedState()
return None
class ArchivedState(State[DocumentContext]):
def name(self) -> str:
return "archived"
def handle(self, context: DocumentContext, event: str) -> State[DocumentContext] | None:
if event == "restore":
return DraftState()
return None
class DocumentWorkflow:
"""Document workflow facade."""
def __init__(self, title: str, author: str) -> None:
self.context = DocumentContext(title=title, author=author)
self.machine = StateMachine(self.context, DraftState())
def edit(self, content: str) -> None:
self.context.content = content
def submit(self) -> bool:
return self.machine.process("submit")
def approve(self) -> bool:
return self.machine.process("approve")
def reject(self) -> bool:
return self.machine.process("reject")
def publish(self) -> bool:
return self.machine.process("publish")
def archive(self) -> bool:
return self.machine.process("archive")
@property
def state(self) -> str:
return self.machine.state_name
def simulate_machine(machine_type: str, events: list[str]) -> list[str]:
"""Simulate state machine operations."""
results = []
if machine_type == "vending":
vm = VendingMachine()
for event in events:
if event == "state":
results.append(vm.state)
elif event == "balance":
results.append(str(vm.balance))
elif event == "dispensed":
results.append(vm.dispensed or "none")
elif event.startswith("insert:"):
vm.insert_coin(int(event.split(":")[1]))
results.append("ok")
elif event.startswith("select:"):
vm.select_item(event.split(":")[1])
results.append("ok")
elif event == "take":
vm.take_item()
results.append("ok")
elif event == "take_change":
vm.take_change()
results.append("ok")
elif event == "cancel":
vm.cancel()
results.append("ok")
elif machine_type == "document":
doc = DocumentWorkflow("Test", "Author")
for event in events:
if event == "state":
results.append(doc.state)
elif event.startswith("edit:"):
doc.edit(event.split(":", 1)[1])
results.append("ok")
elif event == "submit":
results.append("ok" if doc.submit() else "fail")
elif event == "approve":
results.append("ok" if doc.approve() else "fail")
elif event == "reject":
results.append("ok" if doc.reject() else "fail")
elif event == "publish":
results.append("ok" if doc.publish() else "fail")
elif event == "archive":
results.append("ok" if doc.archive() else "fail")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: state_machine_cli.py <command> [args...]")
print("Commands: vending, document")
return 1
cmd = sys.argv[1]
if cmd == "vending":
vm = VendingMachine()
print(f"Initial state: {vm.state}")
vm.insert_coin(50)
print(f"After insert 50: state={vm.state}, balance={vm.balance}")
vm.insert_coin(50)
print(f"After insert 50: state={vm.state}, balance={vm.balance}")
vm.select_item("cola")
print(f"After select cola: state={vm.state}, dispensed={vm.dispensed}")
vm.take_item()
print(f"After take: state={vm.state}")
elif cmd == "document":
doc = DocumentWorkflow("My Document", "Alice")
print(f"Initial state: {doc.state}")
doc.edit("Hello World")
doc.submit()
print(f"After submit: {doc.state}")
doc.approve()
print(f"After approve: {doc.state}")
doc.publish()
print(f"After publish: {doc.state}")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
state_machine
| 435
| 0
|
[
"class_definition",
"decorator",
"multiprocessing"
] | 0.612
|
Error: Unsupported constant type
|
|
example_state_machine
|
test_state_machine_cli.py
|
"""Tests for state_machine_cli.py"""
from state_machine_cli import (
ApprovedState,
ArchivedState,
ChangeState,
DispensingState,
DocumentWorkflow,
DraftState,
IdleState,
InsufficientState,
PublishedState,
ReviewState,
SelectingState,
State,
StateMachine,
VendingMachine,
simulate_machine,
)
class TestStateMachine:
def test_initial_state(self):
context = {}
class StartState(State):
def name(self) -> str:
return "start"
def handle(self, context, event):
return None
sm = StateMachine(context, StartState())
assert sm.state_name == "start"
def test_transition(self):
context = {}
class StateA(State):
def name(self) -> str:
return "a"
def handle(self, context, event):
if event == "go":
return StateB()
return None
class StateB(State):
def name(self) -> str:
return "b"
def handle(self, context, event):
return None
sm = StateMachine(context, StateA())
assert sm.process("go")
assert sm.state_name == "b"
def test_history(self):
context = {}
class StateA(State):
def name(self) -> str:
return "a"
def handle(self, context, event):
if event == "go":
return StateB()
return None
class StateB(State):
def name(self) -> str:
return "b"
def handle(self, context, event):
return None
sm = StateMachine(context, StateA())
sm.process("go")
assert sm.history == ["a", "b"]
def test_listener(self):
context = {}
transitions = []
class StateA(State):
def name(self) -> str:
return "a"
def handle(self, context, event):
if event == "go":
return StateB()
return None
class StateB(State):
def name(self) -> str:
return "b"
def handle(self, context, event):
return None
sm = StateMachine(context, StateA())
sm.add_listener(lambda old, new: transitions.append((old, new)))
sm.process("go")
assert transitions == [("a", "b")]
class TestVendingMachine:
def test_initial_state(self):
vm = VendingMachine()
assert vm.state == "idle"
def test_insert_coin(self):
vm = VendingMachine()
vm.insert_coin(50)
assert vm.state == "selecting"
assert vm.balance == 50
def test_multiple_coins(self):
vm = VendingMachine()
vm.insert_coin(25)
vm.insert_coin(25)
assert vm.balance == 50
def test_select_insufficient(self):
vm = VendingMachine()
vm.insert_coin(50)
vm.select_item("cola") # costs 100
assert vm.state == "insufficient"
def test_select_sufficient(self):
vm = VendingMachine()
vm.insert_coin(100)
vm.select_item("cola")
assert vm.state == "dispensing"
assert vm.dispensed == "cola"
def test_take_item(self):
vm = VendingMachine()
vm.insert_coin(100)
vm.select_item("cola")
vm.take_item()
assert vm.state == "idle"
def test_change(self):
vm = VendingMachine()
vm.insert_coin(100)
vm.insert_coin(50)
vm.select_item("cola") # costs 100
vm.take_item()
assert vm.state == "change"
assert vm.balance == 50
def test_take_change(self):
vm = VendingMachine()
vm.insert_coin(150)
vm.select_item("cola")
vm.take_item()
vm.take_change()
assert vm.state == "idle"
assert vm.balance == 0
def test_cancel(self):
vm = VendingMachine()
vm.insert_coin(50)
vm.cancel()
assert vm.state == "idle"
class TestDocumentWorkflow:
def test_initial_state(self):
doc = DocumentWorkflow("Test", "Author")
assert doc.state == "draft"
def test_submit_empty(self):
doc = DocumentWorkflow("Test", "Author")
result = doc.submit()
assert not result
assert doc.state == "draft"
def test_submit_with_content(self):
doc = DocumentWorkflow("Test", "Author")
doc.edit("Content")
result = doc.submit()
assert result
assert doc.state == "review"
def test_approve(self):
doc = DocumentWorkflow("Test", "Author")
doc.edit("Content")
doc.submit()
doc.approve()
assert doc.state == "approved"
def test_reject(self):
doc = DocumentWorkflow("Test", "Author")
doc.edit("Content")
doc.submit()
doc.reject()
assert doc.state == "draft"
def test_publish(self):
doc = DocumentWorkflow("Test", "Author")
doc.edit("Content")
doc.submit()
doc.approve()
doc.publish()
assert doc.state == "published"
def test_archive(self):
doc = DocumentWorkflow("Test", "Author")
doc.edit("Content")
doc.submit()
doc.approve()
doc.archive()
assert doc.state == "archived"
class TestVendingStates:
def test_idle_state(self):
state = IdleState()
assert state.name() == "idle"
def test_selecting_state(self):
state = SelectingState()
assert state.name() == "selecting"
def test_insufficient_state(self):
state = InsufficientState()
assert state.name() == "insufficient"
def test_dispensing_state(self):
state = DispensingState()
assert state.name() == "dispensing"
def test_change_state(self):
state = ChangeState()
assert state.name() == "change"
class TestDocumentStates:
def test_draft_state(self):
state = DraftState()
assert state.name() == "draft"
def test_review_state(self):
state = ReviewState()
assert state.name() == "review"
def test_approved_state(self):
state = ApprovedState()
assert state.name() == "approved"
def test_published_state(self):
state = PublishedState()
assert state.name() == "published"
def test_archived_state(self):
state = ArchivedState()
assert state.name() == "archived"
class TestSimulateMachine:
def test_vending_insert(self):
result = simulate_machine("vending", ["insert:50", "state", "balance"])
assert result == ["ok", "selecting", "50"]
def test_vending_purchase(self):
result = simulate_machine("vending", ["insert:100", "select:cola", "state", "dispensed"])
assert result == ["ok", "ok", "dispensing", "cola"]
def test_document_workflow(self):
result = simulate_machine("document", ["edit:content", "submit", "state"])
assert result == ["ok", "ok", "review"]
def test_document_approve(self):
result = simulate_machine("document", ["edit:content", "submit", "approve", "state"])
assert result == ["ok", "ok", "ok", "approved"]
| false
|
state_machine
| 278
| 0
|
[
"lambda",
"class_definition"
] | 0.783
|
Error: Statement type not yet supported: ClassDef (classes)
|
|
example_state_parser
|
state_parser_cli.py
|
"""Pratt Parser CLI.
Demonstrates Pratt parsing technique for expression parsing with operator precedence.
"""
import sys
from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum, auto
from typing import Any
class TokenType(Enum):
"""Token types for expression parser."""
NUMBER = auto()
PLUS = auto()
MINUS = auto()
STAR = auto()
SLASH = auto()
CARET = auto()
LPAREN = auto()
RPAREN = auto()
IDENTIFIER = auto()
COMMA = auto()
EOF = auto()
@dataclass
class Token:
"""Parser token."""
type: TokenType
value: Any
pos: int
class Lexer:
"""Tokenize expression strings."""
def __init__(self, text: str) -> None:
self.text = text
self.pos = 0
def tokenize(self) -> list[Token]:
"""Tokenize the input text."""
tokens = []
while self.pos < len(self.text):
self._skip_whitespace()
if self.pos >= len(self.text):
break
char = self.text[self.pos]
start_pos = self.pos
if char.isdigit() or (char == "." and self._peek_digit()):
tokens.append(self._read_number(start_pos))
elif char.isalpha() or char == "_":
tokens.append(self._read_identifier(start_pos))
elif char == "+":
tokens.append(Token(TokenType.PLUS, "+", start_pos))
self.pos += 1
elif char == "-":
tokens.append(Token(TokenType.MINUS, "-", start_pos))
self.pos += 1
elif char == "*":
tokens.append(Token(TokenType.STAR, "*", start_pos))
self.pos += 1
elif char == "/":
tokens.append(Token(TokenType.SLASH, "/", start_pos))
self.pos += 1
elif char == "^":
tokens.append(Token(TokenType.CARET, "^", start_pos))
self.pos += 1
elif char == "(":
tokens.append(Token(TokenType.LPAREN, "(", start_pos))
self.pos += 1
elif char == ")":
tokens.append(Token(TokenType.RPAREN, ")", start_pos))
self.pos += 1
elif char == ",":
tokens.append(Token(TokenType.COMMA, ",", start_pos))
self.pos += 1
else:
self.pos += 1
tokens.append(Token(TokenType.EOF, None, self.pos))
return tokens
def _skip_whitespace(self) -> None:
while self.pos < len(self.text) and self.text[self.pos].isspace():
self.pos += 1
def _peek_digit(self) -> bool:
return self.pos + 1 < len(self.text) and self.text[self.pos + 1].isdigit()
def _read_number(self, start_pos: int) -> Token:
has_dot = False
while self.pos < len(self.text):
char = self.text[self.pos]
if char.isdigit():
self.pos += 1
elif char == "." and not has_dot:
has_dot = True
self.pos += 1
else:
break
value = self.text[start_pos : self.pos]
return Token(TokenType.NUMBER, float(value), start_pos)
def _read_identifier(self, start_pos: int) -> Token:
while self.pos < len(self.text):
char = self.text[self.pos]
if char.isalnum() or char == "_":
self.pos += 1
else:
break
value = self.text[start_pos : self.pos]
return Token(TokenType.IDENTIFIER, value, start_pos)
@dataclass
class Expr:
"""Base expression node."""
pass
@dataclass
class NumberExpr(Expr):
"""Number literal."""
value: float
@dataclass
class IdentifierExpr(Expr):
"""Variable or function name."""
name: str
@dataclass
class BinaryExpr(Expr):
"""Binary operation."""
left: Expr
op: str
right: Expr
@dataclass
class UnaryExpr(Expr):
"""Unary operation."""
op: str
operand: Expr
@dataclass
class CallExpr(Expr):
"""Function call."""
name: str
args: list[Expr]
@dataclass
class GroupExpr(Expr):
"""Grouped expression (parentheses)."""
expr: Expr
class Precedence(Enum):
"""Operator precedence levels."""
NONE = 0
ASSIGNMENT = 1
OR = 2
AND = 3
EQUALITY = 4
COMPARISON = 5
TERM = 6
FACTOR = 7
UNARY = 8
CALL = 9
PRIMARY = 10
class PrattParser:
"""Pratt parser for expressions."""
def __init__(self, tokens: list[Token]) -> None:
self.tokens = tokens
self.pos = 0
def parse(self) -> Expr:
"""Parse tokens into expression tree."""
return self.parse_precedence(Precedence.NONE)
def parse_precedence(self, precedence: Precedence) -> Expr:
"""Parse expression with given precedence."""
token = self.advance()
left = self.prefix(token)
if left is None:
raise ValueError(f"Unexpected token: {token}")
while precedence.value < self.get_precedence(self.current()).value:
token = self.advance()
left = self.infix(token, left)
return left
def prefix(self, token: Token) -> Expr | None:
"""Handle prefix expressions."""
if token.type == TokenType.NUMBER:
return NumberExpr(token.value)
if token.type == TokenType.IDENTIFIER:
if self.check(TokenType.LPAREN):
return self.call_expr(token.value)
return IdentifierExpr(token.value)
if token.type == TokenType.LPAREN:
expr = self.parse_precedence(Precedence.NONE)
self.consume(TokenType.RPAREN)
return GroupExpr(expr)
if token.type == TokenType.MINUS:
operand = self.parse_precedence(Precedence.UNARY)
return UnaryExpr("-", operand)
return None
def infix(self, token: Token, left: Expr) -> Expr:
"""Handle infix expressions."""
if token.type in (TokenType.PLUS, TokenType.MINUS, TokenType.STAR, TokenType.SLASH):
precedence = self.get_precedence(token)
right = self.parse_precedence(precedence)
return BinaryExpr(left, token.value, right)
if token.type == TokenType.CARET:
# Right associative
right = self.parse_precedence(Precedence(self.get_precedence(token).value - 1))
return BinaryExpr(left, "^", right)
return left
def call_expr(self, name: str) -> CallExpr:
"""Parse function call."""
self.consume(TokenType.LPAREN)
args: list[Expr] = []
if not self.check(TokenType.RPAREN):
args.append(self.parse_precedence(Precedence.NONE))
while self.match(TokenType.COMMA):
args.append(self.parse_precedence(Precedence.NONE))
self.consume(TokenType.RPAREN)
return CallExpr(name, args)
def get_precedence(self, token: Token) -> Precedence:
"""Get precedence for token."""
precedences = {
TokenType.PLUS: Precedence.TERM,
TokenType.MINUS: Precedence.TERM,
TokenType.STAR: Precedence.FACTOR,
TokenType.SLASH: Precedence.FACTOR,
TokenType.CARET: Precedence.UNARY,
TokenType.LPAREN: Precedence.CALL,
}
return precedences.get(token.type, Precedence.NONE)
def current(self) -> Token:
"""Get current token."""
return self.tokens[self.pos]
def advance(self) -> Token:
"""Advance to next token."""
token = self.tokens[self.pos]
if self.pos < len(self.tokens) - 1:
self.pos += 1
return token
def check(self, type: TokenType) -> bool:
"""Check if current token is of given type."""
return self.current().type == type
def match(self, type: TokenType) -> bool:
"""Match and consume token if it matches."""
if self.check(type):
self.advance()
return True
return False
def consume(self, type: TokenType) -> Token:
"""Consume token of expected type."""
if not self.check(type):
raise ValueError(f"Expected {type}, got {self.current().type}")
return self.advance()
class Evaluator:
"""Evaluate parsed expressions."""
def __init__(self, env: dict[str, float] | None = None) -> None:
self.env = env or {}
self.functions: dict[str, Callable[..., float]] = {
"abs": abs,
"min": min,
"max": max,
"sqrt": lambda x: x**0.5,
"pow": pow,
"sin": lambda x: __import__("math").sin(x),
"cos": lambda x: __import__("math").cos(x),
}
def evaluate(self, expr: Expr) -> float:
"""Evaluate expression."""
if isinstance(expr, NumberExpr):
return expr.value
if isinstance(expr, IdentifierExpr):
if expr.name not in self.env:
raise ValueError(f"Undefined variable: {expr.name}")
return self.env[expr.name]
if isinstance(expr, BinaryExpr):
left = self.evaluate(expr.left)
right = self.evaluate(expr.right)
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b if b != 0 else float("inf"),
"^": lambda a, b: a**b,
}
return ops[expr.op](left, right)
if isinstance(expr, UnaryExpr):
operand = self.evaluate(expr.operand)
if expr.op == "-":
return -operand
return operand
if isinstance(expr, CallExpr):
if expr.name not in self.functions:
raise ValueError(f"Undefined function: {expr.name}")
args = [self.evaluate(arg) for arg in expr.args]
return self.functions[expr.name](*args)
if isinstance(expr, GroupExpr):
return self.evaluate(expr.expr)
raise ValueError(f"Unknown expression type: {type(expr)}")
class Printer:
"""Print expressions in different formats."""
def to_string(self, expr: Expr) -> str:
"""Convert expression to string."""
if isinstance(expr, NumberExpr):
if expr.value == int(expr.value):
return str(int(expr.value))
return str(expr.value)
if isinstance(expr, IdentifierExpr):
return expr.name
if isinstance(expr, BinaryExpr):
left = self.to_string(expr.left)
right = self.to_string(expr.right)
return f"({left} {expr.op} {right})"
if isinstance(expr, UnaryExpr):
operand = self.to_string(expr.operand)
return f"({expr.op}{operand})"
if isinstance(expr, CallExpr):
args = ", ".join(self.to_string(arg) for arg in expr.args)
return f"{expr.name}({args})"
if isinstance(expr, GroupExpr):
return self.to_string(expr.expr)
return str(expr)
def to_rpn(self, expr: Expr) -> str:
"""Convert expression to reverse polish notation."""
if isinstance(expr, NumberExpr):
if expr.value == int(expr.value):
return str(int(expr.value))
return str(expr.value)
if isinstance(expr, IdentifierExpr):
return expr.name
if isinstance(expr, BinaryExpr):
left = self.to_rpn(expr.left)
right = self.to_rpn(expr.right)
return f"{left} {right} {expr.op}"
if isinstance(expr, UnaryExpr):
operand = self.to_rpn(expr.operand)
return f"{operand} {expr.op}"
if isinstance(expr, GroupExpr):
return self.to_rpn(expr.expr)
return str(expr)
def parse(text: str) -> Expr:
"""Parse expression string."""
lexer = Lexer(text)
tokens = lexer.tokenize()
parser = PrattParser(tokens)
return parser.parse()
def evaluate(text: str, env: dict[str, float] | None = None) -> float:
"""Parse and evaluate expression."""
expr = parse(text)
return Evaluator(env).evaluate(expr)
def to_string(text: str) -> str:
"""Parse and convert to string."""
expr = parse(text)
return Printer().to_string(expr)
def to_rpn(text: str) -> str:
"""Parse and convert to RPN."""
expr = parse(text)
return Printer().to_rpn(expr)
def simulate_parser(operations: list[str]) -> list[str]:
"""Simulate parser operations."""
results = []
env: dict[str, float] = {}
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "eval":
try:
value = evaluate(parts[1], env)
results.append(str(value))
except ValueError as e:
results.append(f"error:{e}")
elif cmd == "set":
name_val = parts[1].split("=")
env[name_val[0]] = float(name_val[1])
results.append("ok")
elif cmd == "string":
try:
results.append(to_string(parts[1]))
except ValueError as e:
results.append(f"error:{e}")
elif cmd == "rpn":
try:
results.append(to_rpn(parts[1]))
except ValueError as e:
results.append(f"error:{e}")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 3:
print("Usage: state_parser_cli.py <command> <expr>")
print("Commands: eval, string, rpn")
return 1
cmd = sys.argv[1]
expr = sys.argv[2]
if cmd == "eval":
result = evaluate(expr)
print(result)
elif cmd == "string":
result = to_string(expr)
print(result)
elif cmd == "rpn":
result = to_rpn(expr)
print(result)
else:
print(f"Unknown command: {cmd}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
state_parser
| 506
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 8530..8533, value: Ellipsis, kind: None })
|
|
example_state_parser
|
test_state_parser_cli.py
|
"""Tests for state_parser_cli.py"""
import pytest
from state_parser_cli import (
BinaryExpr,
CallExpr,
GroupExpr,
Lexer,
NumberExpr,
TokenType,
UnaryExpr,
evaluate,
parse,
simulate_parser,
to_rpn,
to_string,
)
class TestLexer:
def test_number(self):
lexer = Lexer("42")
tokens = lexer.tokenize()
assert tokens[0].type == TokenType.NUMBER
assert tokens[0].value == 42
def test_float(self):
lexer = Lexer("3.14")
tokens = lexer.tokenize()
assert tokens[0].type == TokenType.NUMBER
assert tokens[0].value == 3.14
def test_operators(self):
lexer = Lexer("+ - * / ^")
tokens = lexer.tokenize()
types = [t.type for t in tokens[:-1]]
assert TokenType.PLUS in types
assert TokenType.MINUS in types
assert TokenType.STAR in types
assert TokenType.SLASH in types
assert TokenType.CARET in types
def test_parens(self):
lexer = Lexer("()")
tokens = lexer.tokenize()
assert tokens[0].type == TokenType.LPAREN
assert tokens[1].type == TokenType.RPAREN
def test_identifier(self):
lexer = Lexer("foo")
tokens = lexer.tokenize()
assert tokens[0].type == TokenType.IDENTIFIER
assert tokens[0].value == "foo"
def test_expression(self):
lexer = Lexer("2 + 3 * 4")
tokens = lexer.tokenize()
assert len(tokens) == 6 # 2, +, 3, *, 4, EOF
class TestParser:
def test_number(self):
expr = parse("42")
assert isinstance(expr, NumberExpr)
assert expr.value == 42
def test_addition(self):
expr = parse("1 + 2")
assert isinstance(expr, BinaryExpr)
assert expr.op == "+"
def test_multiplication(self):
expr = parse("3 * 4")
assert isinstance(expr, BinaryExpr)
assert expr.op == "*"
def test_precedence(self):
expr = parse("2 + 3 * 4")
assert isinstance(expr, BinaryExpr)
assert expr.op == "+"
assert isinstance(expr.right, BinaryExpr)
assert expr.right.op == "*"
def test_parentheses(self):
expr = parse("(2 + 3) * 4")
assert isinstance(expr, BinaryExpr)
assert expr.op == "*"
assert isinstance(expr.left, GroupExpr)
def test_unary_minus(self):
expr = parse("-5")
assert isinstance(expr, UnaryExpr)
assert expr.op == "-"
def test_function_call(self):
expr = parse("sqrt(16)")
assert isinstance(expr, CallExpr)
assert expr.name == "sqrt"
assert len(expr.args) == 1
def test_function_multiple_args(self):
expr = parse("max(1, 2, 3)")
assert isinstance(expr, CallExpr)
assert len(expr.args) == 3
def test_power_right_associative(self):
expr = parse("2 ^ 3 ^ 4")
assert isinstance(expr, BinaryExpr)
assert expr.op == "^"
assert isinstance(expr.right, BinaryExpr)
class TestEvaluator:
def test_number(self):
result = evaluate("42")
assert result == 42
def test_addition(self):
result = evaluate("2 + 3")
assert result == 5
def test_subtraction(self):
result = evaluate("5 - 3")
assert result == 2
def test_multiplication(self):
result = evaluate("4 * 5")
assert result == 20
def test_division(self):
result = evaluate("10 / 2")
assert result == 5
def test_power(self):
result = evaluate("2 ^ 3")
assert result == 8
def test_precedence(self):
result = evaluate("2 + 3 * 4")
assert result == 14
def test_parentheses(self):
result = evaluate("(2 + 3) * 4")
assert result == 20
def test_unary_minus(self):
result = evaluate("-5")
assert result == -5
def test_nested_expression(self):
result = evaluate("((1 + 2) * (3 + 4))")
assert result == 21
def test_function_sqrt(self):
result = evaluate("sqrt(16)")
assert result == 4
def test_function_abs(self):
result = evaluate("abs(-5)")
assert result == 5
def test_function_min(self):
result = evaluate("min(3, 1, 2)")
assert result == 1
def test_function_max(self):
result = evaluate("max(3, 1, 2)")
assert result == 3
def test_variable(self):
result = evaluate("x + 1", {"x": 5})
assert result == 6
def test_undefined_variable(self):
with pytest.raises(ValueError):
evaluate("x + 1")
class TestPrinter:
def test_number(self):
result = to_string("42")
assert result == "42"
def test_binary(self):
result = to_string("1 + 2")
assert "1" in result and "+" in result and "2" in result
def test_nested(self):
result = to_string("(1 + 2) * 3")
assert "*" in result
class TestRPN:
def test_number(self):
result = to_rpn("42")
assert result == "42"
def test_addition(self):
result = to_rpn("1 + 2")
assert result == "1 2 +"
def test_complex(self):
result = to_rpn("2 + 3 * 4")
assert "2" in result and "3" in result and "4" in result
assert "+" in result and "*" in result
class TestSimulateParser:
def test_eval(self):
result = simulate_parser(["eval:2 + 3"])
assert result == ["5.0"]
def test_set_and_eval(self):
result = simulate_parser(["set:x=5", "eval:x + 1"])
assert result == ["ok", "6.0"]
def test_string(self):
result = simulate_parser(["string:1 + 2"])
assert result[0] != ""
def test_rpn(self):
result = simulate_parser(["rpn:1 + 2"])
assert result == ["1 2 +"]
def test_error(self):
result = simulate_parser(["eval:undefined_var"])
assert "error" in result[0]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_state_parser/test_state_parser_cli.py (5954 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_state_parser/test_state_parser_cli.rs (12353 bytes)
⏱️ Parse time: 56ms
📊 Throughput: 103.4 KB/s
⏱️ Total time: 56ms
| true
|
state_parser
| 227
| 5
|
[
"context_manager",
"class_definition",
"eval_exec"
] | 0.652
| null |
example_state_regex
|
state_regex_cli.py
|
"""Simple Regex Engine CLI.
Demonstrates regex pattern matching using NFA (Non-deterministic Finite Automaton).
"""
import sys
from dataclasses import dataclass, field
@dataclass(eq=False)
class NFAState:
"""NFA state."""
id: int
is_accept: bool = False
epsilon_transitions: list["NFAState"] = field(default_factory=list)
char_transitions: dict[str, list["NFAState"]] = field(default_factory=dict)
def __hash__(self) -> int:
"""Make hashable by id."""
return hash(self.id)
def __eq__(self, other: object) -> bool:
"""Compare by id."""
if not isinstance(other, NFAState):
return False
return self.id == other.id
def add_epsilon(self, state: "NFAState") -> None:
"""Add epsilon transition."""
self.epsilon_transitions.append(state)
def add_char(self, char: str, state: "NFAState") -> None:
"""Add character transition."""
if char not in self.char_transitions:
self.char_transitions[char] = []
self.char_transitions[char].append(state)
@dataclass
class NFA:
"""Non-deterministic Finite Automaton."""
start: NFAState
accept: NFAState
class RegexCompiler:
"""Compile regex pattern to NFA."""
def __init__(self) -> None:
self.state_id = 0
def new_state(self, is_accept: bool = False) -> NFAState:
"""Create new state."""
state = NFAState(self.state_id, is_accept)
self.state_id += 1
return state
def compile(self, pattern: str) -> NFA:
"""Compile regex pattern to NFA."""
self.state_id = 0
nfa, pos = self._parse_expr(pattern, 0)
return nfa
def _parse_expr(self, pattern: str, pos: int) -> tuple[NFA, int]:
"""Parse expression (handles alternation)."""
nfa, pos = self._parse_concat(pattern, pos)
while pos < len(pattern) and pattern[pos] == "|":
pos += 1
right_nfa, pos = self._parse_concat(pattern, pos)
nfa = self._alternation(nfa, right_nfa)
return nfa, pos
def _parse_concat(self, pattern: str, pos: int) -> tuple[NFA, int]:
"""Parse concatenation."""
nfa = None
while pos < len(pattern) and pattern[pos] not in "|)":
atom_nfa, pos = self._parse_atom(pattern, pos)
# Check for quantifiers
if pos < len(pattern) and pattern[pos] in "*+?":
quantifier = pattern[pos]
pos += 1
if quantifier == "*":
atom_nfa = self._star(atom_nfa)
elif quantifier == "+":
atom_nfa = self._plus(atom_nfa)
elif quantifier == "?":
atom_nfa = self._question(atom_nfa)
if nfa is None:
nfa = atom_nfa
else:
nfa = self._concatenation(nfa, atom_nfa)
if nfa is None:
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(accept)
nfa = NFA(start, accept)
return nfa, pos
def _parse_atom(self, pattern: str, pos: int) -> tuple[NFA, int]:
"""Parse single atom (char, group, or character class)."""
if pos >= len(pattern):
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(accept)
return NFA(start, accept), pos
char = pattern[pos]
if char == "(":
pos += 1
nfa, pos = self._parse_expr(pattern, pos)
if pos < len(pattern) and pattern[pos] == ")":
pos += 1
return nfa, pos
if char == "[":
pos += 1
chars = []
negated = False
if pos < len(pattern) and pattern[pos] == "^":
negated = True
pos += 1
while pos < len(pattern) and pattern[pos] != "]":
if pos + 2 < len(pattern) and pattern[pos + 1] == "-":
start_char = pattern[pos]
end_char = pattern[pos + 2]
for c in range(ord(start_char), ord(end_char) + 1):
chars.append(chr(c))
pos += 3
else:
chars.append(pattern[pos])
pos += 1
if pos < len(pattern):
pos += 1
return self._char_class(chars, negated), pos
if char == ".":
pos += 1
return self._dot(), pos
if char == "\\":
pos += 1
if pos < len(pattern):
escaped = pattern[pos]
pos += 1
return self._char(escaped), pos
pos += 1
return self._char(char), pos
def _char(self, c: str) -> NFA:
"""Create NFA for single character."""
start = self.new_state()
accept = self.new_state(True)
start.add_char(c, accept)
return NFA(start, accept)
def _dot(self) -> NFA:
"""Create NFA for any character (.)."""
start = self.new_state()
accept = self.new_state(True)
start.add_char(".", accept)
return NFA(start, accept)
def _char_class(self, chars: list[str], negated: bool = False) -> NFA:
"""Create NFA for character class."""
start = self.new_state()
accept = self.new_state(True)
if negated:
start.add_char(f"^{''.join(chars)}", accept)
else:
for c in chars:
start.add_char(c, accept)
return NFA(start, accept)
def _concatenation(self, nfa1: NFA, nfa2: NFA) -> NFA:
"""Concatenate two NFAs."""
nfa1.accept.is_accept = False
nfa1.accept.add_epsilon(nfa2.start)
return NFA(nfa1.start, nfa2.accept)
def _alternation(self, nfa1: NFA, nfa2: NFA) -> NFA:
"""Create alternation of two NFAs."""
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(nfa1.start)
start.add_epsilon(nfa2.start)
nfa1.accept.is_accept = False
nfa1.accept.add_epsilon(accept)
nfa2.accept.is_accept = False
nfa2.accept.add_epsilon(accept)
return NFA(start, accept)
def _star(self, nfa: NFA) -> NFA:
"""Create Kleene star (zero or more)."""
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(nfa.start)
start.add_epsilon(accept)
nfa.accept.is_accept = False
nfa.accept.add_epsilon(nfa.start)
nfa.accept.add_epsilon(accept)
return NFA(start, accept)
def _plus(self, nfa: NFA) -> NFA:
"""Create one or more."""
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(nfa.start)
nfa.accept.is_accept = False
nfa.accept.add_epsilon(nfa.start)
nfa.accept.add_epsilon(accept)
return NFA(start, accept)
def _question(self, nfa: NFA) -> NFA:
"""Create zero or one."""
start = self.new_state()
accept = self.new_state(True)
start.add_epsilon(nfa.start)
start.add_epsilon(accept)
nfa.accept.is_accept = False
nfa.accept.add_epsilon(accept)
return NFA(start, accept)
class RegexMatcher:
"""Match strings against compiled NFA."""
def __init__(self, nfa: NFA) -> None:
self.nfa = nfa
def match(self, text: str) -> bool:
"""Check if text matches the pattern."""
current_states = self._epsilon_closure({self.nfa.start})
for char in text:
next_states: set[NFAState] = set()
for state in current_states:
for trans_char, targets in state.char_transitions.items():
if trans_char == char or trans_char == ".":
next_states.update(targets)
elif trans_char.startswith("^"):
if char not in trans_char[1:]:
next_states.update(targets)
current_states = self._epsilon_closure(next_states)
return any(state.is_accept for state in current_states)
def _epsilon_closure(self, states: set[NFAState]) -> set[NFAState]:
"""Compute epsilon closure of state set."""
closure = set(states)
stack = list(states)
while stack:
state = stack.pop()
for target in state.epsilon_transitions:
if target not in closure:
closure.add(target)
stack.append(target)
return closure
class Regex:
"""High-level regex interface."""
def __init__(self, pattern: str) -> None:
self.pattern = pattern
compiler = RegexCompiler()
self.nfa = compiler.compile(pattern)
self.matcher = RegexMatcher(self.nfa)
def match(self, text: str) -> bool:
"""Check if text matches pattern exactly."""
return self.matcher.match(text)
def search(self, text: str) -> tuple[int, int] | None:
"""Find first match in text."""
for start in range(len(text)):
for end in range(start + 1, len(text) + 1):
if self.matcher.match(text[start:end]):
return start, end
return None
def find_all(self, text: str) -> list[str]:
"""Find all non-overlapping matches."""
matches = []
pos = 0
while pos < len(text):
best_match = None
for end in range(pos + 1, len(text) + 1):
if self.matcher.match(text[pos:end]):
best_match = text[pos:end]
if best_match:
matches.append(best_match)
pos += len(best_match)
else:
pos += 1
return matches
def regex_match(pattern: str, text: str) -> bool:
"""Check if text matches regex pattern."""
return Regex(pattern).match(text)
def regex_search(pattern: str, text: str) -> tuple[int, int] | None:
"""Search for pattern in text."""
return Regex(pattern).search(text)
def regex_find_all(pattern: str, text: str) -> list[str]:
"""Find all matches of pattern in text."""
return Regex(pattern).find_all(text)
def simulate_regex(operations: list[str]) -> list[str]:
"""Simulate regex operations."""
results = []
current_regex: Regex | None = None
for op in operations:
parts = op.split(":", 1)
cmd = parts[0]
if cmd == "compile":
current_regex = Regex(parts[1])
results.append("ok")
elif cmd == "match" and current_regex:
results.append("1" if current_regex.match(parts[1]) else "0")
elif cmd == "search" and current_regex:
result = current_regex.search(parts[1])
if result:
results.append(f"{result[0]},{result[1]}")
else:
results.append("none")
elif cmd == "find_all" and current_regex:
matches = current_regex.find_all(parts[1])
results.append(",".join(matches) if matches else "none")
return results
def main() -> int:
"""CLI entry point."""
if len(sys.argv) < 3:
print("Usage: state_regex_cli.py <pattern> <text>")
print(" or: state_regex_cli.py match <pattern> <text>")
print(" or: state_regex_cli.py search <pattern> <text>")
return 1
cmd = sys.argv[1]
if cmd == "match":
pattern, text = sys.argv[2], sys.argv[3]
result = regex_match(pattern, text)
print("Match" if result else "No match")
elif cmd == "search":
pattern, text = sys.argv[2], sys.argv[3]
result = regex_search(pattern, text)
if result:
print(f"Found at {result[0]}-{result[1]}: {text[result[0] : result[1]]}")
else:
print("No match")
elif cmd == "find":
pattern, text = sys.argv[2], sys.argv[3]
matches = regex_find_all(pattern, text)
print(f"Found {len(matches)} matches: {matches}")
else:
pattern, text = cmd, sys.argv[2]
result = regex_match(pattern, text)
print("Match" if result else "No match")
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
state_regex
| 405
| 0
|
[
"class_definition",
"decorator"
] | 0.612
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 301..311, value: Str("NFAState"), kind: None })
|
|
example_state_regex
|
test_state_regex_cli.py
|
"""Tests for state_regex_cli.py"""
from state_regex_cli import (
NFAState,
Regex,
RegexCompiler,
RegexMatcher,
regex_find_all,
regex_match,
regex_search,
simulate_regex,
)
class TestNFAState:
def test_add_epsilon(self):
s1 = NFAState(0)
s2 = NFAState(1)
s1.add_epsilon(s2)
assert s2 in s1.epsilon_transitions
def test_add_char(self):
s1 = NFAState(0)
s2 = NFAState(1)
s1.add_char("a", s2)
assert s2 in s1.char_transitions["a"]
class TestRegexCompiler:
def test_single_char(self):
compiler = RegexCompiler()
nfa = compiler.compile("a")
matcher = RegexMatcher(nfa)
assert matcher.match("a")
assert not matcher.match("b")
def test_concatenation(self):
compiler = RegexCompiler()
nfa = compiler.compile("ab")
matcher = RegexMatcher(nfa)
assert matcher.match("ab")
assert not matcher.match("a")
assert not matcher.match("b")
def test_alternation(self):
compiler = RegexCompiler()
nfa = compiler.compile("a|b")
matcher = RegexMatcher(nfa)
assert matcher.match("a")
assert matcher.match("b")
assert not matcher.match("c")
def test_star(self):
compiler = RegexCompiler()
nfa = compiler.compile("a*")
matcher = RegexMatcher(nfa)
assert matcher.match("")
assert matcher.match("a")
assert matcher.match("aaa")
def test_plus(self):
compiler = RegexCompiler()
nfa = compiler.compile("a+")
matcher = RegexMatcher(nfa)
assert not matcher.match("")
assert matcher.match("a")
assert matcher.match("aaa")
def test_question(self):
compiler = RegexCompiler()
nfa = compiler.compile("a?")
matcher = RegexMatcher(nfa)
assert matcher.match("")
assert matcher.match("a")
assert not matcher.match("aa")
def test_group(self):
compiler = RegexCompiler()
nfa = compiler.compile("(ab)+")
matcher = RegexMatcher(nfa)
assert not matcher.match("")
assert matcher.match("ab")
assert matcher.match("abab")
def test_dot(self):
compiler = RegexCompiler()
nfa = compiler.compile("a.c")
matcher = RegexMatcher(nfa)
assert matcher.match("abc")
assert matcher.match("axc")
assert not matcher.match("ac")
class TestRegex:
def test_match_simple(self):
regex = Regex("hello")
assert regex.match("hello")
assert not regex.match("world")
def test_match_star(self):
regex = Regex("ab*c")
assert regex.match("ac")
assert regex.match("abc")
assert regex.match("abbc")
def test_match_alternation(self):
regex = Regex("cat|dog")
assert regex.match("cat")
assert regex.match("dog")
assert not regex.match("bird")
def test_search(self):
regex = Regex("test")
result = regex.search("this is a test string")
assert result is not None
assert result == (10, 14)
def test_search_not_found(self):
regex = Regex("xyz")
result = regex.search("hello world")
assert result is None
def test_find_all(self):
regex = Regex("ab")
matches = regex.find_all("ab ab ab")
assert len(matches) == 3
class TestRegexMatch:
def test_match(self):
assert regex_match("a", "a")
assert not regex_match("a", "b")
def test_star(self):
assert regex_match("a*", "")
assert regex_match("a*", "aaa")
def test_plus(self):
assert not regex_match("a+", "")
assert regex_match("a+", "a")
def test_concat(self):
assert regex_match("abc", "abc")
assert not regex_match("abc", "ab")
class TestRegexSearch:
def test_found(self):
result = regex_search("world", "hello world")
assert result == (6, 11)
def test_not_found(self):
result = regex_search("xyz", "hello")
assert result is None
class TestRegexFindAll:
def test_multiple(self):
matches = regex_find_all("a", "ababa")
assert len(matches) >= 2
class TestSimulateRegex:
def test_compile_match(self):
result = simulate_regex(["compile:abc", "match:abc"])
assert result == ["ok", "1"]
def test_no_match(self):
result = simulate_regex(["compile:abc", "match:xyz"])
assert result == ["ok", "0"]
def test_search(self):
result = simulate_regex(["compile:test", "search:this is a test"])
assert result[0] == "ok"
assert result[1] != "none"
def test_find_all(self):
result = simulate_regex(["compile:a", "find_all:ababa"])
assert result[0] == "ok"
assert result[1] != "none"
class TestComplexPatterns:
def test_email_like(self):
regex = Regex("a+@b+")
assert regex.match("a@b")
assert regex.match("aaa@bbb")
def test_nested_groups(self):
regex = Regex("(a(b))+")
assert regex.match("ab")
assert regex.match("abab")
def test_alternation_with_star(self):
regex = Regex("(a|b)*")
assert regex.match("")
assert regex.match("a")
assert regex.match("ab")
assert regex.match("abba")
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_state_regex/test_state_regex_cli.py (5407 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_state_regex/test_state_regex_cli.rs (10572 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 107.1 KB/s
⏱️ Total time: 49ms
| true
|
state_regex
| 199
| 5
|
[
"class_definition",
"decorator"
] | 0.612
| null |
example_statistics
|
stats_tool.py
|
#!/usr/bin/env python3
"""Statistics Example - Statistical calculations CLI."""
import argparse
import statistics
def cmd_mean(args):
"""Calculate mean. Depyler: proven to terminate"""
nums = [float(n) for n in args.numbers]
print(f"Mean: {statistics.mean(nums)}")
def cmd_median(args):
"""Calculate median. Depyler: proven to terminate"""
nums = [float(n) for n in args.numbers]
print(f"Median: {statistics.median(nums)}")
def cmd_stdev(args):
"""Calculate standard deviation. Depyler: proven to terminate"""
nums = [float(n) for n in args.numbers]
print(f"Stdev: {statistics.stdev(nums):.4f}")
def cmd_mode(args):
"""Calculate mode. Depyler: proven to terminate"""
nums = [float(n) for n in args.numbers]
print(f"Mode: {statistics.mode(nums)}")
def main():
parser = argparse.ArgumentParser(description="Statistics tool")
subparsers = parser.add_subparsers(dest="command", required=True)
for cmd in ["mean", "median", "stdev", "mode"]:
p = subparsers.add_parser(cmd)
p.add_argument("numbers", nargs="+")
args = parser.parse_args()
{"mean": cmd_mean, "median": cmd_median, "stdev": cmd_stdev, "mode": cmd_mode}[args.command](
args
)
if __name__ == "__main__":
main()
| false
|
statistics
| 47
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1129..1221, value: Dict(ExprDict { range: 1129..1207, keys: [Some(Constant(ExprConstant { range: 1130..1136, value: Str("mean"), kind: None })), Some(Constant(ExprConstant { range: 1148..1156, value: Str("median"), kind: None })), Some(Constant(ExprConstant { range: 1170..1177, value: Str("stdev"), kind: None })), Some(Constant(ExprConstant { range: 1190..1196, value: Str("mode"), kind: None }))], values: [Name(ExprName { ra
|
|
example_statistics
|
test_stats_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for statistics CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "stats_tool.py"
SCRIPT = "stats_tool.py"
def run(args):
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
cwd=__file__.rsplit("/", 1)[0])
class TestMean:
def test_mean(self):
result = run(["mean", "1", "2", "3", "4", "5"])
assert result.returncode == 0
assert "3" in result.stdout
class TestMedian:
def test_median_odd(self):
result = run(["median", "1", "2", "3"])
assert result.returncode == 0
assert "2" in result.stdout
def test_median_even(self):
result = run(["median", "1", "2", "3", "4"])
assert result.returncode == 0
assert "2.5" in result.stdout
class TestStdev:
def test_stdev(self):
result = run(["stdev", "2", "4", "4", "4", "5", "5", "7", "9"])
assert result.returncode == 0
class TestMode:
def test_mode(self):
result = run(["mode", "1", "2", "2", "3"])
assert result.returncode == 0
assert "2" 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_statistics/test_stats_tool.py (1287 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_statistics/test_stats_tool.rs (3641 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_statistics/Cargo.toml (2 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 25.6 KB/s
⏱️ Total time: 49ms
| true
|
statistics
| 45
| 6
|
[
"class_definition"
] | 0.612
| null |
example_statistics_calc
|
stats_cli.py
|
#!/usr/bin/env python3
"""Statistics Calculator CLI.
Pure Python statistical functions without external dependencies.
"""
import argparse
import math
import sys
def mean(data: list[float]) -> float:
"""Calculate arithmetic mean."""
if not data:
raise ValueError("Cannot calculate mean of empty list")
return sum(data) / len(data)
def geometric_mean(data: list[float]) -> float:
"""Calculate geometric mean."""
if not data:
raise ValueError("Cannot calculate mean of empty list")
if any(x <= 0 for x in data):
raise ValueError("Geometric mean requires positive values")
product = 1.0
for x in data:
product *= x
return product ** (1.0 / len(data))
def harmonic_mean(data: list[float]) -> float:
"""Calculate harmonic mean."""
if not data:
raise ValueError("Cannot calculate mean of empty list")
if any(x <= 0 for x in data):
raise ValueError("Harmonic mean requires positive values")
return len(data) / sum(1.0 / x for x in data)
def median(data: list[float]) -> float:
"""Calculate median."""
if not data:
raise ValueError("Cannot calculate median of empty list")
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
return sorted_data[n // 2]
def mode(data: list[float]) -> list[float]:
"""Calculate mode(s) - most frequent values."""
if not data:
raise ValueError("Cannot calculate mode of empty list")
counts: dict[float, int] = {}
for x in data:
counts[x] = counts.get(x, 0) + 1
max_count = max(counts.values())
modes = [x for x, count in counts.items() if count == max_count]
return sorted(modes)
def variance(data: list[float], population: bool = False) -> float:
"""Calculate variance."""
if not data:
raise ValueError("Cannot calculate variance of empty list")
n = len(data)
if n == 1 and not population:
return 0.0
m = mean(data)
ss = sum((x - m) ** 2 for x in data)
if population:
return ss / n
return ss / (n - 1)
def std_dev(data: list[float], population: bool = False) -> float:
"""Calculate standard deviation."""
return variance(data, population) ** 0.5
def covariance(x: list[float], y: list[float], population: bool = False) -> float:
"""Calculate covariance between two variables."""
if len(x) != len(y):
raise ValueError("Lists must have same length")
if not x:
raise ValueError("Cannot calculate covariance of empty lists")
n = len(x)
mean_x = mean(x)
mean_y = mean(y)
cov = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n))
if population:
return cov / n
return cov / (n - 1)
def correlation(x: list[float], y: list[float]) -> float:
"""Calculate Pearson correlation coefficient."""
if len(x) != len(y):
raise ValueError("Lists must have same length")
std_x = std_dev(x)
std_y = std_dev(y)
if std_x == 0 or std_y == 0:
return 0.0
return covariance(x, y) / (std_x * std_y)
def percentile(data: list[float], p: float) -> float:
"""Calculate p-th percentile (0-100)."""
if not data:
raise ValueError("Cannot calculate percentile of empty list")
if not 0 <= p <= 100:
raise ValueError("Percentile must be between 0 and 100")
sorted_data = sorted(data)
n = len(sorted_data)
k = (n - 1) * (p / 100)
f = int(k)
c = f + 1 if f < n - 1 else f
return sorted_data[f] + (sorted_data[c] - sorted_data[f]) * (k - f)
def quartiles(data: list[float]) -> tuple[float, float, float]:
"""Calculate Q1, Q2 (median), Q3."""
q1 = percentile(data, 25)
q2 = percentile(data, 50)
q3 = percentile(data, 75)
return q1, q2, q3
def iqr(data: list[float]) -> float:
"""Calculate interquartile range."""
q1, _, q3 = quartiles(data)
return q3 - q1
def range_stat(data: list[float]) -> float:
"""Calculate range (max - min)."""
if not data:
raise ValueError("Cannot calculate range of empty list")
return max(data) - min(data)
def skewness(data: list[float]) -> float:
"""Calculate skewness (Fisher's)."""
if len(data) < 3:
raise ValueError("Need at least 3 values for skewness")
n = len(data)
m = mean(data)
s = std_dev(data)
if s == 0:
return 0.0
m3 = sum((x - m) ** 3 for x in data) / n
return m3 / (s**3)
def kurtosis(data: list[float]) -> float:
"""Calculate excess kurtosis (Fisher's)."""
if len(data) < 4:
raise ValueError("Need at least 4 values for kurtosis")
n = len(data)
m = mean(data)
s = std_dev(data, population=True)
if s == 0:
return 0.0
m4 = sum((x - m) ** 4 for x in data) / n
return (m4 / (s**4)) - 3
def zscore(data: list[float]) -> list[float]:
"""Calculate z-scores for data."""
m = mean(data)
s = std_dev(data)
if s == 0:
return [0.0] * len(data)
return [(x - m) / s for x in data]
def sem(data: list[float]) -> float:
"""Calculate standard error of the mean."""
return std_dev(data) / (len(data) ** 0.5)
def coefficient_of_variation(data: list[float]) -> float:
"""Calculate coefficient of variation (CV)."""
m = mean(data)
if m == 0:
raise ValueError("Mean is zero, CV undefined")
return std_dev(data) / m
def moving_average(data: list[float], window: int) -> list[float]:
"""Calculate simple moving average."""
if window < 1:
raise ValueError("Window must be at least 1")
if window > len(data):
raise ValueError("Window larger than data")
result = []
for i in range(len(data) - window + 1):
result.append(mean(data[i : i + window]))
return result
def weighted_mean(data: list[float], weights: list[float]) -> float:
"""Calculate weighted arithmetic mean."""
if len(data) != len(weights):
raise ValueError("Data and weights must have same length")
if not data:
raise ValueError("Cannot calculate mean of empty list")
total_weight = sum(weights)
if total_weight == 0:
raise ValueError("Total weight is zero")
return sum(d * w for d, w in zip(data, weights, strict=False)) / total_weight
def trimmed_mean(data: list[float], proportion: float) -> float:
"""Calculate trimmed mean."""
if not 0 <= proportion < 0.5:
raise ValueError("Proportion must be between 0 and 0.5")
sorted_data = sorted(data)
n = len(sorted_data)
k = int(n * proportion)
trimmed = sorted_data[k : n - k] if k > 0 else sorted_data
return mean(trimmed)
def describe(data: list[float]) -> dict[str, float]:
"""Generate summary statistics."""
n = len(data)
q1, q2, q3 = quartiles(data)
return {
"count": float(n),
"mean": mean(data),
"std": std_dev(data),
"min": min(data),
"25%": q1,
"50%": q2,
"75%": q3,
"max": max(data),
"range": range_stat(data),
"iqr": q3 - q1,
"variance": variance(data),
"skewness": skewness(data) if n >= 3 else float("nan"),
"kurtosis": kurtosis(data) if n >= 4 else float("nan"),
}
def linear_regression(x: list[float], y: list[float]) -> tuple[float, float, float]:
"""Simple linear regression. Returns (slope, intercept, r_squared)."""
if len(x) != len(y):
raise ValueError("Lists must have same length")
n = len(x)
mean_x = mean(x)
mean_y = mean(y)
ss_xx = sum((xi - mean_x) ** 2 for xi in x)
ss_xy = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n))
ss_yy = sum((yi - mean_y) ** 2 for yi in y)
if ss_xx == 0:
raise ValueError("Variance of x is zero")
slope = ss_xy / ss_xx
intercept = mean_y - slope * mean_x
r_squared = (ss_xy**2) / (ss_xx * ss_yy) if ss_yy != 0 else 0
return slope, intercept, r_squared
def main() -> int:
parser = argparse.ArgumentParser(description="Statistical calculations")
parser.add_argument("values", nargs="*", type=float, help="Data values")
parser.add_argument(
"--mode",
choices=[
"describe",
"mean",
"median",
"std",
"var",
"corr",
"zscore",
"percentile",
"regression",
],
default="describe",
help="Calculation mode",
)
parser.add_argument("--y", nargs="*", type=float, help="Y values for correlation/regression")
parser.add_argument("-p", type=float, default=50, help="Percentile value (0-100)")
args = parser.parse_args()
if not args.values:
values = [float(x) for x in sys.stdin.read().split()]
else:
values = args.values
if args.mode == "describe":
stats = describe(values)
print("Summary Statistics:")
print("-" * 30)
for key, val in stats.items():
if math.isnan(val):
print(f"{key:>12}: N/A")
else:
print(f"{key:>12}: {val:.4f}")
elif args.mode == "mean":
print(f"Mean: {mean(values):.6f}")
print(f"Geometric Mean: {geometric_mean([x for x in values if x > 0]):.6f}")
print(f"Harmonic Mean: {harmonic_mean([x for x in values if x > 0]):.6f}")
elif args.mode == "median":
print(f"Median: {median(values):.6f}")
modes = mode(values)
print(f"Mode(s): {', '.join(f'{m:.6f}' for m in modes)}")
elif args.mode == "std":
print(f"Std Dev (sample): {std_dev(values):.6f}")
print(f"Std Dev (population): {std_dev(values, population=True):.6f}")
print(f"SEM: {sem(values):.6f}")
elif args.mode == "var":
print(f"Variance (sample): {variance(values):.6f}")
print(f"Variance (population): {variance(values, population=True):.6f}")
elif args.mode == "corr" and args.y:
r = correlation(values, args.y)
cov = covariance(values, args.y)
print(f"Correlation: {r:.6f}")
print(f"Covariance: {cov:.6f}")
elif args.mode == "zscore":
z = zscore(values)
print("Z-scores:")
for _i, (v, zs) in enumerate(zip(values, z, strict=False)):
print(f" {v:.2f} -> {zs:.4f}")
elif args.mode == "percentile":
p = percentile(values, args.p)
print(f"{args.p}th percentile: {p:.6f}")
q1, q2, q3 = quartiles(values)
print(f"Q1 (25%): {q1:.6f}")
print(f"Q2 (50%): {q2:.6f}")
print(f"Q3 (75%): {q3:.6f}")
print(f"IQR: {iqr(values):.6f}")
elif args.mode == "regression" and args.y:
slope, intercept, r2 = linear_regression(values, args.y)
print(f"y = {slope:.6f}x + {intercept:.6f}")
print(f"R-squared: {r2:.6f}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_statistics_calc/stats_cli.py (10961 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_statistics_calc/stats_cli.rs (31760 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_statistics_calc/Cargo.toml (1 dependencies)
⏱️ Parse time: 68ms
📊 Throughput: 157.4 KB/s
⏱️ Total time: 68ms
| true
|
statistics_calc
| 395
| 6
|
[
"exception_handling",
"stdin_usage"
] | 0.577
| null |
example_statistics_calc
|
test_stats_cli.py
|
"""Tests for stats_cli.py"""
import pytest
from stats_cli import (
coefficient_of_variation,
correlation,
covariance,
describe,
geometric_mean,
harmonic_mean,
iqr,
kurtosis,
linear_regression,
mean,
median,
mode,
moving_average,
percentile,
quartiles,
range_stat,
sem,
skewness,
std_dev,
trimmed_mean,
variance,
weighted_mean,
zscore,
)
class TestMean:
def test_basic(self):
assert mean([1, 2, 3, 4, 5]) == 3.0
def test_single(self):
assert mean([5]) == 5.0
def test_empty(self):
with pytest.raises(ValueError):
mean([])
def test_negative(self):
assert mean([-1, 0, 1]) == 0.0
class TestGeometricMean:
def test_basic(self):
result = geometric_mean([1, 2, 4, 8])
assert result == pytest.approx(2.83, rel=0.01)
def test_equal_values(self):
assert geometric_mean([5, 5, 5]) == pytest.approx(5.0)
def test_negative(self):
with pytest.raises(ValueError):
geometric_mean([-1, 2, 3])
class TestHarmonicMean:
def test_basic(self):
result = harmonic_mean([1, 2, 4])
assert result == pytest.approx(12 / 7, rel=0.01)
def test_equal_values(self):
assert harmonic_mean([5, 5, 5]) == pytest.approx(5.0)
class TestMedian:
def test_odd(self):
assert median([1, 3, 5, 7, 9]) == 5.0
def test_even(self):
assert median([1, 2, 3, 4]) == 2.5
def test_single(self):
assert median([5]) == 5.0
def test_unsorted(self):
assert median([3, 1, 4, 1, 5]) == 3.0
class TestMode:
def test_single_mode(self):
assert mode([1, 2, 2, 3, 3, 3]) == [3]
def test_multiple_modes(self):
assert mode([1, 1, 2, 2]) == [1, 2]
def test_all_same(self):
assert mode([5, 5, 5]) == [5]
class TestVariance:
def test_sample(self):
data = [2, 4, 4, 4, 5, 5, 7, 9]
result = variance(data, population=False)
assert result == pytest.approx(4.57, rel=0.01)
def test_population(self):
data = [2, 4, 4, 4, 5, 5, 7, 9]
result = variance(data, population=True)
assert result == pytest.approx(4.0)
def test_single_value(self):
assert variance([5]) == 0.0
class TestStdDev:
def test_basic(self):
data = [2, 4, 4, 4, 5, 5, 7, 9]
result = std_dev(data, population=True)
assert result == pytest.approx(2.0)
class TestCovariance:
def test_basic(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
result = covariance(x, y)
assert result == pytest.approx(5.0)
def test_negative(self):
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
result = covariance(x, y)
assert result < 0
class TestCorrelation:
def test_perfect_positive(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
assert correlation(x, y) == pytest.approx(1.0)
def test_perfect_negative(self):
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
assert correlation(x, y) == pytest.approx(-1.0)
def test_no_correlation(self):
x = [1, 2, 3, 4, 5]
y = [3, 3, 3, 3, 3] # Constant
assert correlation(x, y) == pytest.approx(0.0)
class TestPercentile:
def test_median(self):
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert percentile(data, 50) == pytest.approx(5.5, rel=0.1)
def test_quartiles(self):
data = list(range(1, 101))
assert percentile(data, 25) == pytest.approx(25.75, rel=0.1)
assert percentile(data, 75) == pytest.approx(75.25, rel=0.1)
def test_extremes(self):
data = [1, 2, 3, 4, 5]
assert percentile(data, 0) == pytest.approx(1.0)
assert percentile(data, 100) == pytest.approx(5.0)
class TestQuartiles:
def test_basic(self):
data = list(range(1, 13))
q1, q2, q3 = quartiles(data)
assert q2 == pytest.approx(6.5, rel=0.1)
class TestIQR:
def test_basic(self):
data = list(range(1, 13))
result = iqr(data)
q1, _, q3 = quartiles(data)
assert result == pytest.approx(q3 - q1)
class TestRangeStat:
def test_basic(self):
assert range_stat([1, 5, 3, 9, 2]) == 8
def test_single(self):
assert range_stat([5]) == 0
class TestSkewness:
def test_symmetric(self):
# Normal-ish distribution centered at 0
data = [-2, -1, -1, 0, 0, 0, 1, 1, 2]
result = skewness(data)
assert abs(result) < 0.5
def test_right_skewed(self):
data = [1, 1, 1, 2, 2, 3, 10]
result = skewness(data)
assert result > 0
class TestKurtosis:
def test_basic(self):
# Normal distribution has kurtosis near 0
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = kurtosis(data)
# Just check it's computed without error
assert isinstance(result, float)
class TestZscore:
def test_basic(self):
data = [1, 2, 3, 4, 5]
z = zscore(data)
assert len(z) == 5
assert z[2] == pytest.approx(0.0) # Mean value
def test_constant(self):
data = [5, 5, 5]
z = zscore(data)
assert all(zi == 0.0 for zi in z)
class TestSEM:
def test_basic(self):
data = [1, 2, 3, 4, 5]
result = sem(data)
expected = std_dev(data) / (5**0.5)
assert result == pytest.approx(expected)
class TestCoefficientOfVariation:
def test_basic(self):
data = [10, 20, 30, 40, 50]
result = coefficient_of_variation(data)
assert result == pytest.approx(std_dev(data) / mean(data))
class TestMovingAverage:
def test_basic(self):
data = [1, 2, 3, 4, 5]
result = moving_average(data, 3)
assert result == [2.0, 3.0, 4.0]
def test_window_1(self):
data = [1, 2, 3]
result = moving_average(data, 1)
assert result == [1.0, 2.0, 3.0]
class TestWeightedMean:
def test_equal_weights(self):
data = [1, 2, 3, 4, 5]
weights = [1, 1, 1, 1, 1]
result = weighted_mean(data, weights)
assert result == pytest.approx(mean(data))
def test_unequal_weights(self):
data = [1, 2, 3]
weights = [1, 2, 3] # Weight 3 more heavily
result = weighted_mean(data, weights)
expected = (1 * 1 + 2 * 2 + 3 * 3) / 6
assert result == pytest.approx(expected)
class TestTrimmedMean:
def test_no_trim(self):
data = [1, 2, 3, 4, 5]
result = trimmed_mean(data, 0)
assert result == pytest.approx(mean(data))
def test_with_trim(self):
data = [1, 2, 3, 4, 5, 100] # Outlier
result = trimmed_mean(data, 0.2) # Remove 20% from each end
# Should remove 1 and 100
assert result < mean(data)
class TestDescribe:
def test_basic(self):
data = [1, 2, 3, 4, 5]
stats = describe(data)
assert stats["count"] == 5
assert stats["mean"] == pytest.approx(3.0)
assert stats["min"] == 1
assert stats["max"] == 5
class TestLinearRegression:
def test_perfect_fit(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10] # y = 2x
slope, intercept, r2 = linear_regression(x, y)
assert slope == pytest.approx(2.0)
assert intercept == pytest.approx(0.0)
assert r2 == pytest.approx(1.0)
def test_with_intercept(self):
x = [0, 1, 2, 3, 4]
y = [1, 3, 5, 7, 9] # y = 2x + 1
slope, intercept, r2 = linear_regression(x, y)
assert slope == pytest.approx(2.0)
assert intercept == pytest.approx(1.0)
def test_negative_slope(self):
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2] # y = -2x + 12
slope, intercept, r2 = linear_regression(x, y)
assert slope == pytest.approx(-2.0)
assert r2 == pytest.approx(1.0)
| false
|
statistics_calc
| 310
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Var("zi"), right: Literal(Float(0.0)) }, generators: [HirComprehension { target: "zi", iter: Var("z"), conditions: [] }] }
|
|
example_stdlib
|
stdlib_integration.py
|
#!/usr/bin/env python3
"""
Standard Library Integration Example (stdlib_integration.py)
This CLI tool demonstrates integration of multiple Python standard library modules:
- argparse: Command-line argument parsing
- json: JSON serialization/deserialization
- pathlib: Path operations and file metadata
- datetime: Timestamp formatting
- hashlib: File hashing (MD5, SHA256)
The tool provides detailed file information including size, timestamps,
hashes, and outputs in various formats (text, JSON, compact).
"""
import argparse
import datetime
import hashlib
import json
import sys
from pathlib import Path
def calculate_hash(file_path, algorithm):
"""Calculate file hash using specified algorithm."""
if algorithm not in ["md5", "sha256"]:
raise ValueError(f"Unsupported hash algorithm: {algorithm}")
hasher = hashlib.md5() if algorithm == "md5" else hashlib.sha256()
try:
with open(file_path, "rb") as f:
# Read file in chunks for efficiency
while chunk := f.read(8192):
hasher.update(chunk)
return hasher.hexdigest()
except PermissionError:
raise
except Exception as e:
raise RuntimeError(f"Failed to calculate hash: {e}") from e
def format_timestamp(timestamp, time_format):
"""Format timestamp according to specified format."""
dt = datetime.datetime.fromtimestamp(timestamp)
if time_format == "iso":
return dt.isoformat()
elif time_format == "human":
return dt.strftime("%b %d, %Y %I:%M:%S %p")
else:
return dt.isoformat()
def get_file_info(file_path, hash_algorithm=None, time_format="iso"):
"""Gather comprehensive file information using pathlib, datetime, hashlib."""
path = Path(file_path)
# Check if file exists
if not path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if not path.is_file():
raise ValueError(f"Not a file: {file_path}")
# Get file stats
stats = path.stat()
# Build file info dictionary
info = {
"path": str(path.absolute()),
"filename": path.name,
"extension": path.suffix,
"size": stats.st_size,
"modified": format_timestamp(stats.st_mtime, time_format),
}
# Add hash if requested
if hash_algorithm:
try:
info["hash"] = calculate_hash(path, hash_algorithm)
info["hash_algorithm"] = hash_algorithm
except PermissionError:
# Let permission errors propagate
raise
except Exception as e:
info["hash_error"] = str(e)
return info
def format_output_text(info, include_hash):
"""Format file info as human-readable text."""
lines = []
lines.append(f"Path: {info['path']}")
lines.append(f"Filename: {info['filename']}")
if info["extension"]:
lines.append(f"Extension: {info['extension']}")
lines.append(f"Size: {info['size']} bytes")
lines.append(f"Modified: {info['modified']}")
if include_hash and "hash" in info:
lines.append(f"Hash ({info['hash_algorithm'].upper()}): {info['hash']}")
return "\n".join(lines)
def format_output_json(info):
"""Format file info as JSON."""
return json.dumps(info, indent=2)
def format_output_compact(info, include_hash):
"""Format file info as compact single-line output."""
parts = [
info["filename"],
f"{info['size']}B",
info["modified"],
]
if include_hash and "hash" in info:
parts.append(f"{info['hash_algorithm']}:{info['hash'][:16]}...")
return " | ".join(parts)
def main():
"""Main entry point for the stdlib integration CLI."""
parser = argparse.ArgumentParser(
description="File information tool demonstrating Python stdlib integration",
prog="stdlib_integration.py",
epilog="Example: %(prog)s --file data.txt --format json --hash sha256",
)
# Version
parser.add_argument(
"--version",
action="version",
version="1.0.0",
)
# Required file argument
parser.add_argument(
"--file",
"-f",
required=True,
help="File path to analyze (required)",
)
# Output format
parser.add_argument(
"--format",
choices=["text", "json", "compact"],
default="text",
help="Output format (default: text)",
)
# Hash algorithm
parser.add_argument(
"--hash",
choices=["md5", "sha256"],
help="Hash algorithm (optional)",
)
# Output destination
parser.add_argument(
"--output",
"-o",
help="Output file path (default: stdout)",
)
# Time format
parser.add_argument(
"--time-format",
choices=["iso", "human"],
default="iso",
help="Timestamp format (default: iso)",
)
# Parse arguments
args = parser.parse_args()
try:
# Get file information
info = get_file_info(args.file, args.hash, args.time_format)
# Format output
if args.format == "json":
output = format_output_json(info)
elif args.format == "compact":
output = format_output_compact(info, args.hash is not None)
else: # text
output = format_output_text(info, args.hash is not None)
# Write output
if args.output:
output_path = Path(args.output)
with open(output_path, "w") as f:
f.write(output)
if args.format != "compact":
f.write("\n")
else:
print(output)
except FileNotFoundError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
except PermissionError:
print("Error: Permission denied", file=sys.stderr)
sys.exit(1)
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_stdlib/stdlib_integration.py (6078 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_stdlib/stdlib_integration.rs (13108 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_stdlib/Cargo.toml (8 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 111.8 KB/s
⏱️ Total time: 53ms
| true
|
stdlib
| 220
| 6
|
[
"context_manager",
"exception_handling",
"walrus_operator"
] | 0.85
| null |
example_stdlib
|
test_stdlib_integration.py
|
#!/usr/bin/env python3
"""
Test suite for stdlib_integration.py
This test suite validates a CLI tool that integrates multiple Python stdlib modules:
- argparse: Command-line argument parsing
- json: JSON serialization/deserialization
- pathlib: Path operations and file metadata
- datetime: Timestamp formatting
- hashlib: File hashing (MD5, SHA256)
Test coverage goals: 100%
Test-driven development: RED phase (tests written before implementation)
"""
import json
import os
import subprocess
import tempfile
from pathlib import Path
# Path to the script being tested
SCRIPT_PATH = Path(__file__).parent / "stdlib_integration.py"
def run_cli(*args, env=None):
"""Helper function to run the CLI with given arguments and optional environment."""
full_env = os.environ.copy()
if env:
full_env.update(env)
result = subprocess.run(
["python3", str(SCRIPT_PATH)] + list(args),
capture_output=True,
text=True,
env=full_env,
)
return result
class TestHelpAndVersion:
"""Test help and version output."""
def test_help_flag(self):
"""Test --help flag."""
result = run_cli("--help")
assert result.returncode == 0
assert "stdlib_integration.py" in result.stdout
assert "usage:" in result.stdout.lower()
assert "--file" in result.stdout
assert "--hash" in result.stdout
def test_version_flag(self):
"""Test --version flag."""
result = run_cli("--version")
assert result.returncode == 0
assert "1.0.0" in result.stdout
class TestBasicFileInfo:
"""Test basic file information retrieval."""
def test_file_info_text_output(self):
"""Test file info with text output format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
f.write("Hello World")
temp_path = f.name
try:
result = run_cli("--file", temp_path)
assert result.returncode == 0
assert "Path:" in result.stdout
assert temp_path in result.stdout
assert "Size:" in result.stdout
assert "11" in result.stdout # len("Hello World")
finally:
Path(temp_path).unlink()
def test_file_info_json_output(self):
"""Test file info with JSON output format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
f.write("Test content")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
# Parse JSON output
data = json.loads(result.stdout)
assert "path" in data
assert "size" in data
assert "modified" in data
assert data["size"] == 12 # len("Test content")
finally:
Path(temp_path).unlink()
def test_file_not_found(self):
"""Test error handling for non-existent file."""
result = run_cli("--file", "/nonexistent/file.txt")
assert result.returncode != 0
assert "error" in result.stderr.lower() or "not found" in result.stderr.lower()
def test_missing_required_argument(self):
"""Test error when --file is missing."""
result = run_cli()
assert result.returncode != 0
assert "required" in result.stderr.lower() or "error" in result.stderr.lower()
class TestHashingFeatures:
"""Test file hashing with different algorithms."""
def test_md5_hash(self):
"""Test MD5 hash calculation."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--hash", "md5")
assert result.returncode == 0
assert "Hash:" in result.stdout or "hash" in result.stdout.lower()
# MD5 of "Hello" is 8b1a9953c4611296a827abf8c47804d7
assert "8b1a9953c4611296a827abf8c47804d7" in result.stdout.lower()
finally:
Path(temp_path).unlink()
def test_sha256_hash(self):
"""Test SHA256 hash calculation."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--hash", "sha256")
assert result.returncode == 0
assert "Hash:" in result.stdout or "hash" in result.stdout.lower()
# SHA256 of "Hello" starts with 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
assert "185f8db32271fe25f561a6fc938b2e26" in result.stdout.lower()
finally:
Path(temp_path).unlink()
def test_no_hash_by_default(self):
"""Test that hash is not computed by default."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path)
assert result.returncode == 0
# Should not contain hash in output
assert "Hash:" not in result.stdout or "hash" not in result.stdout.lower()
finally:
Path(temp_path).unlink()
def test_json_output_with_hash(self):
"""Test JSON output includes hash when requested."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json", "--hash", "md5")
assert result.returncode == 0
data = json.loads(result.stdout)
assert "hash" in data
assert "hash_algorithm" in data
assert data["hash_algorithm"] == "md5"
finally:
Path(temp_path).unlink()
class TestOutputFormats:
"""Test different output formats."""
def test_text_format_default(self):
"""Test text format is default."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Content")
temp_path = f.name
try:
result = run_cli("--file", temp_path)
assert result.returncode == 0
# Text format has labels
assert "Path:" in result.stdout
assert "Size:" in result.stdout
finally:
Path(temp_path).unlink()
def test_json_format_explicit(self):
"""Test explicit JSON format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Content")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
# Should be valid JSON
data = json.loads(result.stdout)
assert isinstance(data, dict)
finally:
Path(temp_path).unlink()
def test_compact_format(self):
"""Test compact output format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Data")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "compact")
assert result.returncode == 0
# Compact format should be single line
lines = result.stdout.strip().split("\n")
assert len(lines) == 1
finally:
Path(temp_path).unlink()
class TestOutputDestination:
"""Test output to different destinations."""
def test_output_to_stdout(self):
"""Test output to stdout (default)."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Content")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
assert result.stdout.strip() # Has output
finally:
Path(temp_path).unlink()
def test_output_to_file(self):
"""Test output to file."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Content")
input_path = f.name
with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as out:
output_path = out.name
try:
result = run_cli("--file", input_path, "--format", "json", "--output", output_path)
assert result.returncode == 0
# Check output file exists and has content
output_file = Path(output_path)
assert output_file.exists()
with open(output_path) as f:
data = json.load(f)
assert "path" in data
assert "size" in data
finally:
Path(input_path).unlink()
if Path(output_path).exists():
Path(output_path).unlink()
class TestDateTimeFormatting:
"""Test datetime formatting options."""
def test_iso_format_default(self):
"""Test ISO format is default for timestamps."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
# ISO format has T and possibly Z or timezone
assert "T" in data["modified"]
finally:
Path(temp_path).unlink()
def test_human_readable_format(self):
"""Test human-readable timestamp format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--time-format", "human")
assert result.returncode == 0
# Human format has month names or more readable format
assert any(
month in result.stdout
for month in [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
)
finally:
Path(temp_path).unlink()
class TestPathlibIntegration:
"""Test pathlib integration for file operations."""
def test_absolute_path_in_output(self):
"""Test that absolute path is shown in output."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
# Path should be absolute
assert Path(data["path"]).is_absolute()
finally:
Path(temp_path).unlink()
def test_file_extension(self):
"""Test file extension extraction."""
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
assert "extension" in data
assert data["extension"] == ".txt"
finally:
Path(temp_path).unlink()
def test_filename_extraction(self):
"""Test filename extraction."""
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".log") as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
assert "filename" in data
assert data["filename"] == Path(temp_path).name
finally:
Path(temp_path).unlink()
class TestCombinedFeatures:
"""Test combinations of features."""
def test_all_features_combined(self):
"""Test all features together: JSON output, hash, custom time format, file output."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test data")
input_path = f.name
with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as out:
output_path = out.name
try:
result = run_cli(
"--file",
input_path,
"--format",
"json",
"--hash",
"sha256",
"--output",
output_path,
)
assert result.returncode == 0
# Verify output file
with open(output_path) as f:
data = json.load(f)
assert "path" in data
assert "size" in data
assert "hash" in data
assert "hash_algorithm" in data
assert data["hash_algorithm"] == "sha256"
finally:
Path(input_path).unlink()
if Path(output_path).exists():
Path(output_path).unlink()
def test_text_output_with_all_info(self):
"""Test text output with hash and custom formatting."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Sample")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--hash", "md5", "--time-format", "human")
assert result.returncode == 0
assert "Path:" in result.stdout
assert "Size:" in result.stdout
assert "Hash:" in result.stdout or "hash" in result.stdout.lower()
assert "Modified:" in result.stdout or "modified" in result.stdout.lower()
finally:
Path(temp_path).unlink()
class TestEdgeCases:
"""Test edge cases and boundary conditions."""
def test_empty_file(self):
"""Test info for empty file."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
# Empty file
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
assert data["size"] == 0
finally:
Path(temp_path).unlink()
def test_large_file(self):
"""Test info for large file."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
# Write 1MB of data
f.write("x" * 1024 * 1024)
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "json")
assert result.returncode == 0
data = json.loads(result.stdout)
assert data["size"] == 1024 * 1024
finally:
Path(temp_path).unlink()
def test_file_with_spaces_in_name(self):
"""Test file with spaces in filename."""
with tempfile.NamedTemporaryFile(
mode="w", delete=False, prefix="test file ", suffix=".txt"
) as f:
f.write("Content")
temp_path = f.name
try:
result = run_cli("--file", temp_path)
assert result.returncode == 0
assert "Path:" in result.stdout
finally:
Path(temp_path).unlink()
def test_file_with_unicode_content(self):
"""Test file with unicode content."""
with tempfile.NamedTemporaryFile(mode="w", delete=False, encoding="utf-8") as f:
f.write("Hello 世界 🌍")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--hash", "md5")
assert result.returncode == 0
# Should handle unicode content
assert result.returncode == 0
finally:
Path(temp_path).unlink()
class TestErrorHandling:
"""Test error handling and validation."""
def test_invalid_hash_algorithm(self):
"""Test error for invalid hash algorithm."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--hash", "invalid")
assert result.returncode != 0
assert "invalid" in result.stderr.lower() or "error" in result.stderr.lower()
finally:
Path(temp_path).unlink()
def test_invalid_format(self):
"""Test error for invalid output format."""
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Test")
temp_path = f.name
try:
result = run_cli("--file", temp_path, "--format", "invalid")
assert result.returncode != 0
finally:
Path(temp_path).unlink()
def test_permission_denied(self):
"""Test handling of permission denied errors."""
# This test is platform-dependent and may not work on all systems
# Skip if we can't create a file with restricted permissions
try:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
temp_path = f.name
# Remove read permissions
os.chmod(temp_path, 0o000)
result = run_cli("--file", temp_path)
# Should handle permission error gracefully
assert (
result.returncode != 0
or "permission" in result.stderr.lower()
or result.returncode == 0
)
finally:
# Restore permissions and clean up
try:
os.chmod(temp_path, 0o644)
Path(temp_path).unlink()
except Exception:
pass
| false
|
stdlib
| 541
| 0
|
[
"context_manager",
"class_definition",
"exception_handling"
] | 0.652
|
Performance Warnings
══════════════════════════════════════════════════
[1] [Medium] Large value 'args' passed by copy
Location: run_cli, line 0
Impact: Complexity: O(n), Scales: Yes, Hot path: No
Why: Passing large values by copy is inefficient
Fix: Consider passing by reference (&) or using Box/Arc for large types
Summary: Found 1 warnings (0 critical, 0 high severity)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions:
|
|
example_stdlib_math
|
math_cli.py
|
#!/usr/bin/env python3
"""Standard Library Math CLI.
Mathematical functions using Python's math module.
"""
import argparse
import math
import sys
def sqrt(x: float) -> float:
"""Square root."""
return math.sqrt(x)
def power(base: float, exp: float) -> float:
"""Power function."""
return math.pow(base, exp)
def log_natural(x: float) -> float:
"""Natural logarithm."""
return math.log(x)
def log_base(x: float, base: float) -> float:
"""Logarithm with custom base."""
return math.log(x, base)
def log10(x: float) -> float:
"""Base 10 logarithm."""
return math.log10(x)
def log2(x: float) -> float:
"""Base 2 logarithm."""
return math.log2(x)
def exp(x: float) -> float:
"""Exponential function e^x."""
return math.exp(x)
def sin(x: float) -> float:
"""Sine function."""
return math.sin(x)
def cos(x: float) -> float:
"""Cosine function."""
return math.cos(x)
def tan(x: float) -> float:
"""Tangent function."""
return math.tan(x)
def asin(x: float) -> float:
"""Arc sine."""
return math.asin(x)
def acos(x: float) -> float:
"""Arc cosine."""
return math.acos(x)
def atan(x: float) -> float:
"""Arc tangent."""
return math.atan(x)
def atan2(y: float, x: float) -> float:
"""Arc tangent of y/x."""
return math.atan2(y, x)
def sinh(x: float) -> float:
"""Hyperbolic sine."""
return math.sinh(x)
def cosh(x: float) -> float:
"""Hyperbolic cosine."""
return math.cosh(x)
def tanh(x: float) -> float:
"""Hyperbolic tangent."""
return math.tanh(x)
def floor(x: float) -> int:
"""Floor function."""
return math.floor(x)
def ceil(x: float) -> int:
"""Ceiling function."""
return math.ceil(x)
def trunc(x: float) -> int:
"""Truncate to integer."""
return math.trunc(x)
def fabs(x: float) -> float:
"""Absolute value (float)."""
return math.fabs(x)
def factorial(n: int) -> int:
"""Factorial."""
return math.factorial(n)
def gcd(a: int, b: int) -> int:
"""Greatest common divisor."""
return math.gcd(a, b)
def lcm(a: int, b: int) -> int:
"""Least common multiple."""
return math.lcm(a, b)
def isqrt(n: int) -> int:
"""Integer square root."""
return math.isqrt(n)
def is_close(a: float, b: float, rel_tol: float = 1e-9, abs_tol: float = 0.0) -> bool:
"""Check if two floats are close."""
return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
def is_finite(x: float) -> bool:
"""Check if finite."""
return math.isfinite(x)
def is_inf(x: float) -> bool:
"""Check if infinite."""
return math.isinf(x)
def is_nan(x: float) -> bool:
"""Check if NaN."""
return math.isnan(x)
def fmod(x: float, y: float) -> float:
"""Floating point modulo."""
return math.fmod(x, y)
def remainder(x: float, y: float) -> float:
"""IEEE 754 remainder."""
return math.remainder(x, y)
def modf(x: float) -> tuple[float, float]:
"""Return fractional and integer parts."""
return math.modf(x)
def frexp(x: float) -> tuple[float, int]:
"""Return mantissa and exponent."""
return math.frexp(x)
def ldexp(x: float, i: int) -> float:
"""Return x * 2^i."""
return math.ldexp(x, i)
def copysign(x: float, y: float) -> float:
"""Copy sign of y to x."""
return math.copysign(x, y)
def solve_quadratic(a: float, b: float, c: float) -> list[float]:
"""Solve quadratic equation ax^2 + bx + c = 0."""
discriminant = b * b - 4 * a * c
if discriminant < 0:
return []
if discriminant == 0:
return [-b / (2 * a)]
sqrt_d = math.sqrt(discriminant)
return [(-b + sqrt_d) / (2 * a), (-b - sqrt_d) / (2 * a)]
def distance_2d(x1: float, y1: float, x2: float, y2: float) -> float:
"""Euclidean distance in 2D."""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def distance_3d(x1: float, y1: float, z1: float, x2: float, y2: float, z2: float) -> float:
"""Euclidean distance in 3D."""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
def main() -> int:
parser = argparse.ArgumentParser(description="Math functions CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# sqrt
sqrt_p = subparsers.add_parser("sqrt", help="Square root")
sqrt_p.add_argument("x", type=float)
# pow
pow_p = subparsers.add_parser("pow", help="Power")
pow_p.add_argument("base", type=float)
pow_p.add_argument("exp", type=float)
# trig
sin_p = subparsers.add_parser("sin", help="Sine")
sin_p.add_argument("x", type=float)
cos_p = subparsers.add_parser("cos", help="Cosine")
cos_p.add_argument("x", type=float)
tan_p = subparsers.add_parser("tan", help="Tangent")
tan_p.add_argument("x", type=float)
# log
log_p = subparsers.add_parser("log", help="Natural log")
log_p.add_argument("x", type=float)
# exp
exp_p = subparsers.add_parser("exp", help="Exponential")
exp_p.add_argument("x", type=float)
# factorial
fact_p = subparsers.add_parser("factorial", help="Factorial")
fact_p.add_argument("n", type=int)
# gcd
gcd_p = subparsers.add_parser("gcd", help="GCD")
gcd_p.add_argument("a", type=int)
gcd_p.add_argument("b", type=int)
# quadratic
quad_p = subparsers.add_parser("quadratic", help="Solve quadratic")
quad_p.add_argument("a", type=float)
quad_p.add_argument("b", type=float)
quad_p.add_argument("c", type=float)
# distance
dist_p = subparsers.add_parser("distance", help="2D distance")
dist_p.add_argument("x1", type=float)
dist_p.add_argument("y1", type=float)
dist_p.add_argument("x2", type=float)
dist_p.add_argument("y2", type=float)
args = parser.parse_args()
if args.command == "sqrt":
print(sqrt(args.x))
elif args.command == "pow":
print(power(args.base, args.exp))
elif args.command == "sin":
print(sin(args.x))
elif args.command == "cos":
print(cos(args.x))
elif args.command == "tan":
print(tan(args.x))
elif args.command == "log":
print(log_natural(args.x))
elif args.command == "exp":
print(exp(args.x))
elif args.command == "factorial":
print(factorial(args.n))
elif args.command == "gcd":
print(gcd(args.a, args.b))
elif args.command == "quadratic":
roots = solve_quadratic(args.a, args.b, args.c)
if roots:
print(f"Roots: {roots}")
else:
print("No real roots")
elif args.command == "distance":
print(distance_2d(args.x1, args.y1, args.x2, args.y2))
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
stdlib_math
| 296
| 0
|
[
"context_manager"
] | 0.652
|
Type inference hints:
Hint: int for variable 'b' [Medium] (usage patterns suggest this type)
Hint: int for variable 'c' [Medium] (usage patterns suggest this type)
Hint: int for variable 'a' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'x2' [Medium] (usage patterns suggest this type)
Hint: int for variable 'x1' [Medium] (usage patterns suggest this type)
Hint: int for variable 'y2' [Medium] (usage patterns suggest this type)
Hint: int for variable 'y1
|
|
example_stdlib_math
|
test_math_cli.py
|
"""Tests for math_cli.py"""
import math
from math_cli import (
acos,
asin,
atan,
atan2,
ceil,
copysign,
cos,
cosh,
distance_2d,
distance_3d,
exp,
fabs,
factorial,
floor,
fmod,
frexp,
gcd,
is_close,
is_finite,
is_inf,
is_nan,
isqrt,
lcm,
ldexp,
log2,
log10,
log_base,
log_natural,
modf,
power,
remainder,
sin,
sinh,
solve_quadratic,
sqrt,
tan,
tanh,
trunc,
)
class TestBasicMath:
def test_sqrt(self):
assert sqrt(4) == 2.0
assert sqrt(9) == 3.0
assert abs(sqrt(2) - 1.41421356) < 0.0001
def test_power(self):
assert power(2, 3) == 8.0
assert power(10, 2) == 100.0
assert power(2, 0.5) == sqrt(2)
def test_fabs(self):
assert fabs(-5.5) == 5.5
assert fabs(5.5) == 5.5
assert fabs(0) == 0.0
class TestLogarithms:
def test_log_natural(self):
assert abs(log_natural(math.e) - 1.0) < 0.0001
assert abs(log_natural(1) - 0.0) < 0.0001
def test_log_base(self):
assert abs(log_base(8, 2) - 3.0) < 0.0001
assert abs(log_base(100, 10) - 2.0) < 0.0001
def test_log10(self):
assert abs(log10(100) - 2.0) < 0.0001
assert abs(log10(1000) - 3.0) < 0.0001
def test_log2(self):
assert abs(log2(8) - 3.0) < 0.0001
assert abs(log2(16) - 4.0) < 0.0001
class TestExponential:
def test_exp(self):
assert abs(exp(0) - 1.0) < 0.0001
assert abs(exp(1) - math.e) < 0.0001
assert abs(exp(2) - math.e**2) < 0.0001
class TestTrigonometric:
def test_sin(self):
assert abs(sin(0) - 0.0) < 0.0001
assert abs(sin(math.pi / 2) - 1.0) < 0.0001
assert abs(sin(math.pi) - 0.0) < 0.0001
def test_cos(self):
assert abs(cos(0) - 1.0) < 0.0001
assert abs(cos(math.pi / 2) - 0.0) < 0.0001
assert abs(cos(math.pi) - (-1.0)) < 0.0001
def test_tan(self):
assert abs(tan(0) - 0.0) < 0.0001
assert abs(tan(math.pi / 4) - 1.0) < 0.0001
def test_asin(self):
assert abs(asin(0) - 0.0) < 0.0001
assert abs(asin(1) - math.pi / 2) < 0.0001
def test_acos(self):
assert abs(acos(1) - 0.0) < 0.0001
assert abs(acos(0) - math.pi / 2) < 0.0001
def test_atan(self):
assert abs(atan(0) - 0.0) < 0.0001
assert abs(atan(1) - math.pi / 4) < 0.0001
def test_atan2(self):
assert abs(atan2(1, 1) - math.pi / 4) < 0.0001
assert abs(atan2(0, 1) - 0.0) < 0.0001
class TestHyperbolic:
def test_sinh(self):
assert abs(sinh(0) - 0.0) < 0.0001
def test_cosh(self):
assert abs(cosh(0) - 1.0) < 0.0001
def test_tanh(self):
assert abs(tanh(0) - 0.0) < 0.0001
class TestRounding:
def test_floor(self):
assert floor(3.7) == 3
assert floor(-3.7) == -4
assert floor(3.0) == 3
def test_ceil(self):
assert ceil(3.2) == 4
assert ceil(-3.2) == -3
assert ceil(3.0) == 3
def test_trunc(self):
assert trunc(3.7) == 3
assert trunc(-3.7) == -3
class TestIntegerMath:
def test_factorial(self):
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120
assert factorial(10) == 3628800
def test_gcd(self):
assert gcd(12, 8) == 4
assert gcd(17, 13) == 1
assert gcd(100, 25) == 25
def test_lcm(self):
assert lcm(4, 6) == 12
assert lcm(3, 5) == 15
assert lcm(12, 8) == 24
def test_isqrt(self):
assert isqrt(16) == 4
assert isqrt(17) == 4
assert isqrt(100) == 10
class TestFloatOps:
def test_fmod(self):
assert abs(fmod(5.5, 2.0) - 1.5) < 0.0001
assert abs(fmod(-5.5, 2.0) - (-1.5)) < 0.0001
def test_remainder(self):
assert abs(remainder(5.5, 2.0) - (-0.5)) < 0.0001
def test_modf(self):
frac, integer = modf(3.5)
assert abs(frac - 0.5) < 0.0001
assert abs(integer - 3.0) < 0.0001
def test_frexp(self):
mantissa, exp_val = frexp(8.0)
assert abs(mantissa - 0.5) < 0.0001
assert exp_val == 4
def test_ldexp(self):
assert abs(ldexp(0.5, 4) - 8.0) < 0.0001
def test_copysign(self):
assert copysign(1.0, -1.0) == -1.0
assert copysign(-1.0, 1.0) == 1.0
class TestFloatChecks:
def test_is_close(self):
assert is_close(1.0, 1.0000000001) is True
assert is_close(1.0, 1.1) is False
assert is_close(1.0, 1.01, abs_tol=0.1) is True
def test_is_finite(self):
assert is_finite(1.0) is True
assert is_finite(float("inf")) is False
assert is_finite(float("nan")) is False
def test_is_inf(self):
assert is_inf(float("inf")) is True
assert is_inf(float("-inf")) is True
assert is_inf(1.0) is False
def test_is_nan(self):
assert is_nan(float("nan")) is True
assert is_nan(1.0) is False
class TestQuadratic:
def test_two_roots(self):
roots = solve_quadratic(1, -5, 6) # x^2 - 5x + 6 = 0
assert len(roots) == 2
assert 3.0 in roots or abs(roots[0] - 3.0) < 0.0001 or abs(roots[1] - 3.0) < 0.0001
assert 2.0 in roots or abs(roots[0] - 2.0) < 0.0001 or abs(roots[1] - 2.0) < 0.0001
def test_one_root(self):
roots = solve_quadratic(1, -2, 1) # x^2 - 2x + 1 = 0
assert len(roots) == 1
assert abs(roots[0] - 1.0) < 0.0001
def test_no_roots(self):
roots = solve_quadratic(1, 0, 1) # x^2 + 1 = 0
assert len(roots) == 0
class TestDistance:
def test_distance_2d_origin(self):
assert abs(distance_2d(0, 0, 3, 4) - 5.0) < 0.0001
def test_distance_2d_same_point(self):
assert distance_2d(5, 5, 5, 5) == 0.0
def test_distance_2d_horizontal(self):
assert abs(distance_2d(0, 0, 10, 0) - 10.0) < 0.0001
def test_distance_3d(self):
assert abs(distance_3d(0, 0, 0, 1, 2, 2) - 3.0) < 0.0001
def test_distance_3d_same_point(self):
assert distance_3d(1, 2, 3, 1, 2, 3) == 0.0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_stdlib_math/test_math_cli.py (6214 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_stdlib_math/test_math_cli.rs (17866 bytes)
⏱️ Parse time: 54ms
📊 Throughput: 110.9 KB/s
⏱️ Total time: 54ms
| true
|
stdlib_math
| 249
| 5
|
[
"class_definition"
] | 0.612
| null |
example_stdlib_random
|
random_cli.py
|
#!/usr/bin/env python3
"""Standard Library Random CLI.
Random number generation using Python's random module.
"""
import argparse
import random
import sys
def random_float() -> float:
"""Random float in [0.0, 1.0)."""
return random.random()
def random_uniform(a: float, b: float) -> float:
"""Random float in [a, b]."""
return random.uniform(a, b)
def random_int(a: int, b: int) -> int:
"""Random integer in [a, b] inclusive."""
return random.randint(a, b)
def random_range(start: int, stop: int, step: int = 1) -> int:
"""Random from range(start, stop, step)."""
return random.randrange(start, stop, step)
def random_choice(items: list) -> any:
"""Random choice from sequence."""
return random.choice(items)
def random_choices(items: list, k: int) -> list:
"""Random choices with replacement."""
return random.choices(items, k=k)
def random_sample(items: list, k: int) -> list:
"""Random sample without replacement."""
return random.sample(items, k)
def shuffle_list(items: list) -> list:
"""Shuffle list in place and return."""
result = items.copy()
random.shuffle(result)
return result
def random_gauss(mu: float, sigma: float) -> float:
"""Gaussian distribution."""
return random.gauss(mu, sigma)
def random_normalvariate(mu: float, sigma: float) -> float:
"""Normal distribution."""
return random.normalvariate(mu, sigma)
def random_triangular(low: float, high: float, mode: float) -> float:
"""Triangular distribution."""
return random.triangular(low, high, mode)
def random_expovariate(lambd: float) -> float:
"""Exponential distribution."""
return random.expovariate(lambd)
def random_betavariate(alpha: float, beta: float) -> float:
"""Beta distribution."""
return random.betavariate(alpha, beta)
def random_gammavariate(alpha: float, beta: float) -> float:
"""Gamma distribution."""
return random.gammavariate(alpha, beta)
def random_paretovariate(alpha: float) -> float:
"""Pareto distribution."""
return random.paretovariate(alpha)
def random_weibullvariate(alpha: float, beta: float) -> float:
"""Weibull distribution."""
return random.weibullvariate(alpha, beta)
def set_seed(seed: int) -> None:
"""Set random seed for reproducibility."""
random.seed(seed)
def get_state() -> tuple:
"""Get random state."""
return random.getstate()
def set_state(state: tuple) -> None:
"""Set random state."""
random.setstate(state)
def generate_password(
length: int, use_upper: bool = True, use_digits: bool = True, use_special: bool = False
) -> str:
"""Generate random password."""
chars = "abcdefghijklmnopqrstuvwxyz"
if use_upper:
chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if use_digits:
chars += "0123456789"
if use_special:
chars += "!@#$%^&*"
return "".join(random.choices(chars, k=length))
def generate_uuid_like() -> str:
"""Generate UUID-like string."""
hex_chars = "0123456789abcdef"
parts = [
"".join(random.choices(hex_chars, k=8)),
"".join(random.choices(hex_chars, k=4)),
"".join(random.choices(hex_chars, k=4)),
"".join(random.choices(hex_chars, k=4)),
"".join(random.choices(hex_chars, k=12)),
]
return "-".join(parts)
def weighted_choice(items: list, weights: list[float]) -> any:
"""Weighted random choice."""
return random.choices(items, weights=weights, k=1)[0]
def reservoir_sample(items: list, k: int) -> list:
"""Reservoir sampling for streaming data."""
result = []
for i, item in enumerate(items):
if i < k:
result.append(item)
else:
j = random.randint(0, i)
if j < k:
result[j] = item
return result
def dice_roll(num_dice: int, sides: int) -> list[int]:
"""Roll dice."""
return [random.randint(1, sides) for _ in range(num_dice)]
def coin_flips(n: int) -> list[str]:
"""Flip coins."""
return [random.choice(["H", "T"]) for _ in range(n)]
def main() -> int:
parser = argparse.ArgumentParser(description="Random number CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# float
subparsers.add_parser("float", help="Random float [0,1)")
# uniform
uniform_p = subparsers.add_parser("uniform", help="Uniform distribution")
uniform_p.add_argument("a", type=float)
uniform_p.add_argument("b", type=float)
# int
int_p = subparsers.add_parser("int", help="Random integer")
int_p.add_argument("a", type=int)
int_p.add_argument("b", type=int)
# choice
choice_p = subparsers.add_parser("choice", help="Random choice")
choice_p.add_argument("items", nargs="+")
# sample
sample_p = subparsers.add_parser("sample", help="Random sample")
sample_p.add_argument("items", nargs="+")
sample_p.add_argument("-k", type=int, default=1)
# shuffle
shuffle_p = subparsers.add_parser("shuffle", help="Shuffle items")
shuffle_p.add_argument("items", nargs="+")
# password
pwd_p = subparsers.add_parser("password", help="Generate password")
pwd_p.add_argument("-l", "--length", type=int, default=12)
pwd_p.add_argument("--no-upper", action="store_true")
pwd_p.add_argument("--no-digits", action="store_true")
pwd_p.add_argument("--special", action="store_true")
# dice
dice_p = subparsers.add_parser("dice", help="Roll dice")
dice_p.add_argument("-n", type=int, default=1, help="Number of dice")
dice_p.add_argument("-s", "--sides", type=int, default=6)
# coin
coin_p = subparsers.add_parser("coin", help="Flip coins")
coin_p.add_argument("-n", type=int, default=1)
# gauss
gauss_p = subparsers.add_parser("gauss", help="Gaussian distribution")
gauss_p.add_argument("--mu", type=float, default=0.0)
gauss_p.add_argument("--sigma", type=float, default=1.0)
# seed
seed_p = subparsers.add_parser("seed", help="Set seed")
seed_p.add_argument("seed", type=int)
args = parser.parse_args()
if args.command == "float":
print(random_float())
elif args.command == "uniform":
print(random_uniform(args.a, args.b))
elif args.command == "int":
print(random_int(args.a, args.b))
elif args.command == "choice":
print(random_choice(args.items))
elif args.command == "sample":
print(random_sample(args.items, args.k))
elif args.command == "shuffle":
print(shuffle_list(args.items))
elif args.command == "password":
print(generate_password(args.length, not args.no_upper, not args.no_digits, args.special))
elif args.command == "dice":
rolls = dice_roll(args.n, args.sides)
print(f"Rolls: {rolls}, Sum: {sum(rolls)}")
elif args.command == "coin":
flips = coin_flips(args.n)
print(f"Flips: {flips}")
elif args.command == "gauss":
print(random_gauss(args.mu, args.sigma))
elif args.command == "seed":
set_seed(args.seed)
print(f"Seed set to {args.seed}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
stdlib_random
| 253
| 0
|
[
"context_manager",
"decorator"
] | 0.652
|
Type inference hints:
Hint: int for variable 'chars' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'result' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'flips' [Medium] (usage patterns suggest this type)
Hint: str for variable 'rolls' [Medium] (usage patterns suggest this type)
Migration Suggestions
══════════════════════════════════════════════════
[1] [Warning] Consider filter_map() for conditional t
|
|
example_stdlib_random
|
test_random_cli.py
|
"""Tests for random_cli.py"""
from random_cli import (
coin_flips,
dice_roll,
generate_password,
generate_uuid_like,
random_betavariate,
random_choice,
random_choices,
random_expovariate,
random_float,
random_gammavariate,
random_gauss,
random_int,
random_normalvariate,
random_paretovariate,
random_range,
random_sample,
random_triangular,
random_uniform,
random_weibullvariate,
reservoir_sample,
set_seed,
shuffle_list,
weighted_choice,
)
class TestBasicRandom:
def test_random_float_range(self):
set_seed(42)
for _ in range(100):
val = random_float()
assert 0.0 <= val < 1.0
def test_random_uniform_range(self):
set_seed(42)
for _ in range(100):
val = random_uniform(5.0, 10.0)
assert 5.0 <= val <= 10.0
def test_random_int_range(self):
set_seed(42)
for _ in range(100):
val = random_int(1, 10)
assert 1 <= val <= 10
def test_random_range(self):
set_seed(42)
for _ in range(100):
val = random_range(0, 100, 10)
assert val in [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
class TestChoice:
def test_random_choice(self):
set_seed(42)
items = ["a", "b", "c"]
for _ in range(100):
val = random_choice(items)
assert val in items
def test_random_choices(self):
set_seed(42)
items = ["a", "b", "c"]
result = random_choices(items, k=5)
assert len(result) == 5
assert all(x in items for x in result)
def test_random_sample(self):
set_seed(42)
items = [1, 2, 3, 4, 5]
result = random_sample(items, k=3)
assert len(result) == 3
assert len(set(result)) == 3 # No duplicates
assert all(x in items for x in result)
def test_shuffle_list(self):
set_seed(42)
items = [1, 2, 3, 4, 5]
result = shuffle_list(items)
assert sorted(result) == sorted(items)
assert items == [1, 2, 3, 4, 5] # Original unchanged
class TestDistributions:
def test_random_gauss(self):
set_seed(42)
samples = [random_gauss(0, 1) for _ in range(1000)]
mean = sum(samples) / len(samples)
assert abs(mean) < 0.2 # Should be close to 0
def test_random_normalvariate(self):
set_seed(42)
samples = [random_normalvariate(100, 10) for _ in range(1000)]
mean = sum(samples) / len(samples)
assert 95 < mean < 105 # Should be close to 100
def test_random_triangular(self):
set_seed(42)
for _ in range(100):
val = random_triangular(0, 10, 5)
assert 0 <= val <= 10
def test_random_expovariate(self):
set_seed(42)
for _ in range(100):
val = random_expovariate(1.0)
assert val >= 0
def test_random_betavariate(self):
set_seed(42)
for _ in range(100):
val = random_betavariate(2, 5)
assert 0 <= val <= 1
def test_random_gammavariate(self):
set_seed(42)
for _ in range(100):
val = random_gammavariate(2, 1)
assert val >= 0
def test_random_paretovariate(self):
set_seed(42)
for _ in range(100):
val = random_paretovariate(1)
assert val >= 1
def test_random_weibullvariate(self):
set_seed(42)
for _ in range(100):
val = random_weibullvariate(1, 1)
assert val >= 0
class TestSeed:
def test_reproducibility(self):
set_seed(42)
first = [random_int(1, 100) for _ in range(10)]
set_seed(42)
second = [random_int(1, 100) for _ in range(10)]
assert first == second
def test_different_seeds(self):
set_seed(42)
first = [random_int(1, 100) for _ in range(10)]
set_seed(43)
second = [random_int(1, 100) for _ in range(10)]
assert first != second
class TestPassword:
def test_length(self):
set_seed(42)
pwd = generate_password(16)
assert len(pwd) == 16
def test_lowercase_only(self):
set_seed(42)
pwd = generate_password(100, use_upper=False, use_digits=False)
assert pwd.islower()
def test_with_digits(self):
set_seed(42)
pwd = generate_password(100, use_upper=False, use_digits=True)
assert any(c.isdigit() for c in pwd)
def test_with_special(self):
set_seed(42)
pwd = generate_password(100, use_special=True)
special = "!@#$%^&*"
assert any(c in special for c in pwd)
class TestUUID:
def test_format(self):
set_seed(42)
uuid = generate_uuid_like()
parts = uuid.split("-")
assert len(parts) == 5
assert len(parts[0]) == 8
assert len(parts[1]) == 4
assert len(parts[2]) == 4
assert len(parts[3]) == 4
assert len(parts[4]) == 12
def test_uniqueness(self):
set_seed(42)
uuids = [generate_uuid_like() for _ in range(100)]
assert len(set(uuids)) == 100
class TestWeighted:
def test_weighted_choice(self):
set_seed(42)
items = ["a", "b", "c"]
weights = [0.9, 0.05, 0.05]
counts = {"a": 0, "b": 0, "c": 0}
for _ in range(1000):
choice = weighted_choice(items, weights)
counts[choice] += 1
assert counts["a"] > counts["b"]
assert counts["a"] > counts["c"]
class TestReservoir:
def test_sample_size(self):
set_seed(42)
items = list(range(100))
result = reservoir_sample(items, 10)
assert len(result) == 10
def test_sample_unique(self):
set_seed(42)
items = list(range(100))
result = reservoir_sample(items, 10)
assert len(set(result)) == 10
def test_sample_from_items(self):
set_seed(42)
items = list(range(100))
result = reservoir_sample(items, 10)
assert all(x in items for x in result)
class TestDice:
def test_dice_count(self):
set_seed(42)
rolls = dice_roll(5, 6)
assert len(rolls) == 5
def test_dice_range(self):
set_seed(42)
for _ in range(100):
rolls = dice_roll(3, 6)
assert all(1 <= r <= 6 for r in rolls)
def test_dice_d20(self):
set_seed(42)
for _ in range(100):
rolls = dice_roll(1, 20)
assert all(1 <= r <= 20 for r in rolls)
class TestCoin:
def test_coin_count(self):
set_seed(42)
flips = coin_flips(10)
assert len(flips) == 10
def test_coin_values(self):
set_seed(42)
flips = coin_flips(100)
assert all(f in ["H", "T"] for f in flips)
def test_coin_distribution(self):
set_seed(42)
flips = coin_flips(10000)
heads = flips.count("H")
tails = flips.count("T")
# Should be roughly 50/50
assert 4000 < heads < 6000
assert 4000 < tails < 6000
| false
|
stdlib_random
| 271
| 0
|
[
"class_definition",
"decorator"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: In, left: Var("x"), right: Var("items") }, generators: [HirComprehension { target: "x", iter: Var("result"), conditions: [] }] }
|
|
example_stdlib_statistics
|
stdlib_stats_cli.py
|
#!/usr/bin/env python3
"""Standard Library Statistics CLI.
Statistical functions using Python's statistics module.
"""
import argparse
import statistics
import sys
def mean(data: list[float]) -> float:
"""Arithmetic mean."""
return statistics.mean(data)
def fmean(data: list[float]) -> float:
"""Fast floating-point arithmetic mean."""
return statistics.fmean(data)
def geometric_mean(data: list[float]) -> float:
"""Geometric mean."""
return statistics.geometric_mean(data)
def harmonic_mean(data: list[float]) -> float:
"""Harmonic mean."""
return statistics.harmonic_mean(data)
def median(data: list[float]) -> float:
"""Median (middle value)."""
return statistics.median(data)
def median_low(data: list[float]) -> float:
"""Low median."""
return statistics.median_low(data)
def median_high(data: list[float]) -> float:
"""High median."""
return statistics.median_high(data)
def median_grouped(data: list[float], interval: float = 1.0) -> float:
"""Median of grouped data."""
return statistics.median_grouped(data, interval)
def mode(data: list) -> any:
"""Mode (most common value)."""
return statistics.mode(data)
def multimode(data: list) -> list:
"""All modes."""
return statistics.multimode(data)
def pstdev(data: list[float], mu: float | None = None) -> float:
"""Population standard deviation."""
if mu is not None:
return statistics.pstdev(data, mu)
return statistics.pstdev(data)
def pvariance(data: list[float], mu: float | None = None) -> float:
"""Population variance."""
if mu is not None:
return statistics.pvariance(data, mu)
return statistics.pvariance(data)
def stdev(data: list[float], xbar: float | None = None) -> float:
"""Sample standard deviation."""
if xbar is not None:
return statistics.stdev(data, xbar)
return statistics.stdev(data)
def variance(data: list[float], xbar: float | None = None) -> float:
"""Sample variance."""
if xbar is not None:
return statistics.variance(data, xbar)
return statistics.variance(data)
def quantiles(data: list[float], n: int = 4) -> list[float]:
"""Quantiles dividing data into n intervals."""
return statistics.quantiles(data, n=n)
def covariance(x: list[float], y: list[float]) -> float:
"""Covariance of two datasets."""
return statistics.covariance(x, y)
def correlation(x: list[float], y: list[float]) -> float:
"""Pearson correlation coefficient."""
return statistics.correlation(x, y)
def linear_regression(x: list[float], y: list[float]) -> tuple[float, float]:
"""Simple linear regression."""
result = statistics.linear_regression(x, y)
return (result.slope, result.intercept)
def z_score(value: float, data: list[float]) -> float:
"""Calculate z-score of a value relative to data."""
m = mean(data)
s = stdev(data)
return (value - m) / s
def percentile_rank(value: float, data: list[float]) -> float:
"""Calculate percentile rank of a value."""
sorted_data = sorted(data)
count_below = sum(1 for x in sorted_data if x < value)
count_equal = sum(1 for x in sorted_data if x == value)
return 100 * (count_below + 0.5 * count_equal) / len(data)
def interquartile_range(data: list[float]) -> float:
"""Calculate IQR (Q3 - Q1)."""
q = quantiles(data, n=4)
return q[2] - q[0]
def coefficient_of_variation(data: list[float]) -> float:
"""Coefficient of variation (CV)."""
return stdev(data) / mean(data)
def describe(data: list[float]) -> dict:
"""Descriptive statistics summary."""
return {
"count": len(data),
"mean": mean(data),
"median": median(data),
"mode": mode(data) if len(set(data)) < len(data) else None,
"stdev": stdev(data) if len(data) > 1 else 0,
"variance": variance(data) if len(data) > 1 else 0,
"min": min(data),
"max": max(data),
"range": max(data) - min(data),
}
def main() -> int:
parser = argparse.ArgumentParser(description="Statistics CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# mean
mean_p = subparsers.add_parser("mean", help="Arithmetic mean")
mean_p.add_argument("values", type=float, nargs="+")
# median
median_p = subparsers.add_parser("median", help="Median")
median_p.add_argument("values", type=float, nargs="+")
# mode
mode_p = subparsers.add_parser("mode", help="Mode")
mode_p.add_argument("values", type=float, nargs="+")
# stdev
stdev_p = subparsers.add_parser("stdev", help="Standard deviation")
stdev_p.add_argument("values", type=float, nargs="+")
# variance
var_p = subparsers.add_parser("variance", help="Variance")
var_p.add_argument("values", type=float, nargs="+")
# quantiles
quant_p = subparsers.add_parser("quantiles", help="Quantiles")
quant_p.add_argument("values", type=float, nargs="+")
quant_p.add_argument("-n", type=int, default=4)
# describe
desc_p = subparsers.add_parser("describe", help="Descriptive statistics")
desc_p.add_argument("values", type=float, nargs="+")
# correlation
corr_p = subparsers.add_parser("correlation", help="Correlation")
corr_p.add_argument("--x", type=float, nargs="+", required=True)
corr_p.add_argument("--y", type=float, nargs="+", required=True)
# regression
reg_p = subparsers.add_parser("regression", help="Linear regression")
reg_p.add_argument("--x", type=float, nargs="+", required=True)
reg_p.add_argument("--y", type=float, nargs="+", required=True)
args = parser.parse_args()
if args.command == "mean":
print(mean(args.values))
elif args.command == "median":
print(median(args.values))
elif args.command == "mode":
print(mode(args.values))
elif args.command == "stdev":
print(stdev(args.values))
elif args.command == "variance":
print(variance(args.values))
elif args.command == "quantiles":
print(quantiles(args.values, n=args.n))
elif args.command == "describe":
stats = describe(args.values)
for key, value in stats.items():
print(f"{key}: {value}")
elif args.command == "correlation":
print(correlation(args.x, args.y))
elif args.command == "regression":
slope, intercept = linear_regression(args.x, args.y)
print(f"y = {slope:.4f}x + {intercept:.4f}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
stdlib_statistics
| 225
| 0
|
[] | 0
|
Type inference hints:
Hint: int for variable 'value' [Medium] (usage patterns suggest this type)
Hint: int for variable 's' [Medium] (usage patterns suggest this type)
Hint: int for variable 'm' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'data' [High] (usage patterns suggest this type)
Hint: int for variable 'count_below' [Medium] (usage patterns suggest this type)
Hint: int for variable 'count_equal' [Medium] (usage patterns suggest this type
|
|
example_stdlib_statistics
|
test_stdlib_stats_cli.py
|
"""Tests for stdlib_stats_cli.py"""
from stdlib_stats_cli import (
coefficient_of_variation,
correlation,
covariance,
describe,
fmean,
geometric_mean,
harmonic_mean,
interquartile_range,
linear_regression,
mean,
median,
median_grouped,
median_high,
median_low,
mode,
multimode,
percentile_rank,
pstdev,
pvariance,
quantiles,
stdev,
variance,
z_score,
)
class TestMeans:
def test_mean(self):
assert mean([1, 2, 3, 4, 5]) == 3.0
assert mean([10, 20, 30]) == 20.0
def test_fmean(self):
assert fmean([1, 2, 3, 4, 5]) == 3.0
assert abs(fmean([1.5, 2.5, 3.5]) - 2.5) < 0.0001
def test_geometric_mean(self):
assert abs(geometric_mean([1, 2, 4, 8]) - 2.828427) < 0.001
assert geometric_mean([1, 1, 1]) == 1.0
def test_harmonic_mean(self):
assert abs(harmonic_mean([40, 60]) - 48.0) < 0.0001
assert harmonic_mean([1, 1, 1]) == 1.0
class TestMedian:
def test_median_odd(self):
assert median([1, 2, 3, 4, 5]) == 3
assert median([1, 3, 5]) == 3
def test_median_even(self):
assert median([1, 2, 3, 4]) == 2.5
assert median([1, 2]) == 1.5
def test_median_low(self):
assert median_low([1, 2, 3, 4]) == 2
assert median_low([1, 2, 3]) == 2
def test_median_high(self):
assert median_high([1, 2, 3, 4]) == 3
assert median_high([1, 2, 3]) == 2
def test_median_grouped(self):
result = median_grouped([1, 2, 3, 4, 5], interval=1)
assert 2.5 <= result <= 3.5
class TestMode:
def test_mode_single(self):
assert mode([1, 2, 2, 3]) == 2
assert mode(["a", "b", "b", "c"]) == "b"
def test_multimode(self):
result = multimode([1, 1, 2, 2, 3])
assert 1 in result
assert 2 in result
assert len(result) == 2
class TestVariance:
def test_pvariance(self):
assert abs(pvariance([1, 2, 3, 4, 5]) - 2.0) < 0.0001
def test_variance(self):
assert abs(variance([1, 2, 3, 4, 5]) - 2.5) < 0.0001
def test_pstdev(self):
assert abs(pstdev([1, 2, 3, 4, 5]) - 1.4142135) < 0.0001
def test_stdev(self):
assert abs(stdev([1, 2, 3, 4, 5]) - 1.5811388) < 0.0001
class TestQuantiles:
def test_quartiles(self):
data = list(range(1, 101))
q = quantiles(data, n=4)
assert len(q) == 3
assert abs(q[0] - 25.5) < 1
assert abs(q[1] - 50.5) < 1
assert abs(q[2] - 75.5) < 1
def test_deciles(self):
data = list(range(1, 101))
q = quantiles(data, n=10)
assert len(q) == 9
class TestCorrelation:
def test_perfect_positive(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
assert abs(correlation(x, y) - 1.0) < 0.0001
def test_perfect_negative(self):
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
assert abs(correlation(x, y) - (-1.0)) < 0.0001
def test_no_correlation(self):
x = [1, 2, 3, 4, 5]
y = [3, 1, 4, 1, 5]
corr = correlation(x, y)
assert abs(corr) < 0.5
class TestCovariance:
def test_positive(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cov = covariance(x, y)
assert cov > 0
def test_negative(self):
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
cov = covariance(x, y)
assert cov < 0
class TestLinearRegression:
def test_perfect_fit(self):
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10] # y = 2x
slope, intercept = linear_regression(x, y)
assert abs(slope - 2.0) < 0.0001
assert abs(intercept - 0.0) < 0.0001
def test_with_intercept(self):
x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 9, 11] # y = 2x + 1
slope, intercept = linear_regression(x, y)
assert abs(slope - 2.0) < 0.0001
assert abs(intercept - 1.0) < 0.0001
class TestZScore:
def test_mean_value(self):
data = [1, 2, 3, 4, 5]
z = z_score(3, data) # Mean is 3
assert abs(z) < 0.0001
def test_above_mean(self):
data = [1, 2, 3, 4, 5]
z = z_score(5, data)
assert z > 0
def test_below_mean(self):
data = [1, 2, 3, 4, 5]
z = z_score(1, data)
assert z < 0
class TestPercentileRank:
def test_minimum(self):
data = [1, 2, 3, 4, 5]
rank = percentile_rank(1, data)
assert rank < 20
def test_maximum(self):
data = [1, 2, 3, 4, 5]
rank = percentile_rank(5, data)
assert rank > 80
def test_median_value(self):
data = [1, 2, 3, 4, 5]
rank = percentile_rank(3, data)
assert 40 < rank < 60
class TestIQR:
def test_iqr(self):
data = list(range(1, 101))
iqr = interquartile_range(data)
assert 45 < iqr < 55
class TestCV:
def test_cv(self):
data = [10, 20, 30, 40, 50]
cv = coefficient_of_variation(data)
assert cv > 0
assert cv < 1
class TestDescribe:
def test_describe(self):
data = [1, 2, 2, 3, 4, 5]
stats = describe(data)
assert stats["count"] == 6
assert abs(stats["mean"] - 2.833) < 0.01
assert stats["median"] == 2.5
assert stats["mode"] == 2
assert stats["min"] == 1
assert stats["max"] == 5
assert stats["range"] == 4
assert stats["stdev"] > 0
assert stats["variance"] > 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_stdlib_statistics/test_stdlib_stats_cli.py (5529 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_stdlib_statistics/test_stdlib_stats_cli.rs (13627 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 110.9 KB/s
⏱️ Total time: 48ms
| true
|
stdlib_statistics
| 221
| 5
|
[
"class_definition"
] | 0.612
| null |
example_string
|
string_tool.py
|
#!/usr/bin/env python3
"""String Example - String operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="String operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
u = subs.add_parser("upper")
u.add_argument("text")
lp = subs.add_parser("lower")
lp.add_argument("text")
t = subs.add_parser("title")
t.add_argument("text")
le = subs.add_parser("length")
le.add_argument("text")
args = parser.parse_args()
if args.cmd == "upper":
print(args.text.upper())
elif args.cmd == "lower":
print(args.text.lower())
elif args.cmd == "title":
print(args.text.title())
elif args.cmd == "length":
print(len(args.text))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_string/string_tool.py (801 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_string/string_tool.rs (1487 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_string/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 16.9 KB/s
⏱️ Total time: 46ms
| true
|
string
| 32
| 6
|
[] | 0
| null |
example_string
|
test_string_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for string CLI."""
import subprocess
SCRIPT = "string_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCase:
def test_upper(self): assert "HELLO" in run(["upper", "hello"]).stdout
def test_lower(self): assert "hello" in run(["lower", "HELLO"]).stdout
def test_title(self): assert "Hello" in run(["title", "hello"]).stdout
def test_length(self): assert "5" in run(["length", "hello"]).stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_string/test_string_tool.py (634 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_string/test_string_tool.rs (2020 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 12.8 KB/s
⏱️ Total time: 48ms
| true
|
string
| 15
| 5
|
[
"class_definition"
] | 0.612
| null |
example_string_format
|
string_format_cli.py
|
#!/usr/bin/env python3
"""String Format CLI.
String formatting operations.
"""
import argparse
import sys
def format_basic(template: str, *args: str) -> str:
"""Format string with positional arguments."""
return template.format(*args)
def format_named(template: str, **kwargs: str) -> str:
"""Format string with named arguments."""
return template.format(**kwargs)
def format_dict(template: str, data: dict[str, str]) -> str:
"""Format string with dictionary."""
return template.format(**data)
def f_string_style(name: str, value: int) -> str:
"""Demonstrate f-string style formatting."""
return f"Name: {name}, Value: {value}"
def percent_format(template: str, *args: str) -> str:
"""Old-style % formatting."""
return template % args
def format_number(n: float, decimals: int = 2) -> str:
"""Format number with decimal places."""
return f"{n:.{decimals}f}"
def format_currency(amount: float, symbol: str = "$") -> str:
"""Format number as currency."""
return f"{symbol}{amount:,.2f}"
def format_percent(value: float) -> str:
"""Format number as percentage."""
return f"{value:.1%}"
def format_scientific(n: float) -> str:
"""Format number in scientific notation."""
return f"{n:.2e}"
def format_binary(n: int) -> str:
"""Format integer as binary."""
return f"{n:b}"
def format_hex(n: int) -> str:
"""Format integer as hexadecimal."""
return f"{n:x}"
def format_octal(n: int) -> str:
"""Format integer as octal."""
return f"{n:o}"
def pad_left(s: str, width: int, char: str = " ") -> str:
"""Pad string on left to width."""
return s.rjust(width, char)
def pad_right(s: str, width: int, char: str = " ") -> str:
"""Pad string on right to width."""
return s.ljust(width, char)
def pad_center(s: str, width: int, char: str = " ") -> str:
"""Center string to width."""
return s.center(width, char)
def zfill(s: str, width: int) -> str:
"""Pad string with zeros on left."""
return s.zfill(width)
def truncate(s: str, max_len: int, suffix: str = "...") -> str:
"""Truncate string to max length with suffix."""
if len(s) <= max_len:
return s
return s[: max_len - len(suffix)] + suffix
def wrap_text(s: str, width: int) -> str:
"""Wrap text to width."""
words = s.split()
lines: list[str] = []
current_line: list[str] = []
current_len = 0
for word in words:
if current_len + len(word) + len(current_line) <= width:
current_line.append(word)
current_len += len(word)
else:
if current_line:
lines.append(" ".join(current_line))
current_line = [word]
current_len = len(word)
if current_line:
lines.append(" ".join(current_line))
return "\n".join(lines)
def format_list(items: list[str], separator: str = ", ", last_separator: str = " and ") -> str:
"""Format list with separators."""
if not items:
return ""
if len(items) == 1:
return items[0]
return separator.join(items[:-1]) + last_separator + items[-1]
def format_table(rows: list[list[str]], headers: list[str] | None = None) -> str:
"""Format data as ASCII table."""
if not rows:
return ""
all_rows = [headers] + rows if headers else rows
col_widths = [
max(len(str(row[i])) for row in all_rows if i < len(row)) for i in range(len(all_rows[0]))
]
def format_row(row: list[str]) -> str:
return "| " + " | ".join(str(row[i]).ljust(col_widths[i]) for i in range(len(row))) + " |"
def separator() -> str:
return "+-" + "-+-".join("-" * w for w in col_widths) + "-+"
lines = [separator()]
if headers:
lines.append(format_row(headers))
lines.append(separator())
for row in rows:
lines.append(format_row(row))
lines.append(separator())
return "\n".join(lines)
def format_key_value(data: dict[str, str], separator: str = ": ") -> str:
"""Format dictionary as key-value pairs."""
max_key_len = max(len(k) for k in data.keys()) if data else 0
lines = [f"{k.ljust(max_key_len)}{separator}{v}" for k, v in data.items()]
return "\n".join(lines)
def format_bytes(n: int) -> str:
"""Format byte count as human-readable."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if abs(n) < 1024.0:
return f"{n:.1f} {unit}"
n //= 1024
return f"{n:.1f} PB"
def format_duration(seconds: int) -> str:
"""Format seconds as duration string."""
if seconds < 60:
return f"{seconds}s"
elif seconds < 3600:
mins = seconds // 60
secs = seconds % 60
return f"{mins}m {secs}s" if secs else f"{mins}m"
else:
hours = seconds // 3600
mins = (seconds % 3600) // 60
return f"{hours}h {mins}m" if mins else f"{hours}h"
def format_ordinal(n: int) -> str:
"""Format number with ordinal suffix."""
if 11 <= n % 100 <= 13:
suffix = "th"
elif n % 10 == 1:
suffix = "st"
elif n % 10 == 2:
suffix = "nd"
elif n % 10 == 3:
suffix = "rd"
else:
suffix = "th"
return f"{n}{suffix}"
def format_plural(n: int, singular: str, plural: str | None = None) -> str:
"""Format count with appropriate plural form."""
if plural is None:
plural = singular + "s"
return f"{n} {singular if n == 1 else plural}"
def template_replace(
template: str, replacements: dict[str, str], prefix: str = "{{", suffix: str = "}}"
) -> str:
"""Replace template placeholders."""
result = template
for key, value in replacements.items():
result = result.replace(f"{prefix}{key}{suffix}", value)
return result
def quote(s: str, char: str = '"') -> str:
"""Quote string."""
return f"{char}{s}{char}"
def unquote(s: str) -> str:
"""Remove surrounding quotes."""
if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
return s[1:-1]
return s
def main() -> int:
parser = argparse.ArgumentParser(description="String format CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# format
format_p = subparsers.add_parser("format", help="Format string")
format_p.add_argument("template", help="Template string")
format_p.add_argument("args", nargs="*", help="Arguments")
# number
number_p = subparsers.add_parser("number", help="Format number")
number_p.add_argument("value", type=float, help="Number")
number_p.add_argument("--decimals", type=int, default=2, help="Decimal places")
number_p.add_argument("--currency", action="store_true", help="Format as currency")
number_p.add_argument("--percent", action="store_true", help="Format as percent")
# pad
pad_p = subparsers.add_parser("pad", help="Pad string")
pad_p.add_argument("text", help="Text to pad")
pad_p.add_argument("width", type=int, help="Target width")
pad_p.add_argument("--side", choices=["left", "right", "center"], default="left")
pad_p.add_argument("--char", default=" ", help="Padding character")
# bytes
bytes_p = subparsers.add_parser("bytes", help="Format bytes")
bytes_p.add_argument("value", type=int, help="Byte count")
# duration
duration_p = subparsers.add_parser("duration", help="Format duration")
duration_p.add_argument("seconds", type=int, help="Seconds")
args = parser.parse_args()
if args.command == "format":
result = format_basic(args.template, *args.args)
print(result)
elif args.command == "number":
if args.currency:
print(format_currency(args.value))
elif args.percent:
print(format_percent(args.value))
else:
print(format_number(args.value, args.decimals))
elif args.command == "pad":
if args.side == "left":
print(pad_left(args.text, args.width, args.char))
elif args.side == "right":
print(pad_right(args.text, args.width, args.char))
else:
print(pad_center(args.text, args.width, args.char))
elif args.command == "bytes":
print(format_bytes(args.value))
elif args.command == "duration":
print(format_duration(args.seconds))
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
string_format
| 295
| 0
|
[
"context_manager"
] | 0.652
|
Type inference hints:
Hint: str for variable 'name' [Medium] (usage patterns suggest this type)
Hint: str for variable 'value' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'n' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'symbol' [Medium] (usage patterns suggest this type)
Hint: str for variable 'amount' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'value' [Mediu
|
|
example_string_format
|
test_string_format_cli.py
|
"""Tests for string_format_cli.py"""
from string_format_cli import (
f_string_style,
format_basic,
format_binary,
format_bytes,
format_currency,
format_dict,
format_duration,
format_hex,
format_key_value,
format_list,
format_named,
format_number,
format_octal,
format_ordinal,
format_percent,
format_plural,
format_scientific,
format_table,
pad_center,
pad_left,
pad_right,
percent_format,
quote,
template_replace,
truncate,
unquote,
wrap_text,
zfill,
)
class TestFormatBasic:
def test_format_basic(self):
result = format_basic("Hello, {}!", "World")
assert result == "Hello, World!"
def test_format_basic_multiple(self):
result = format_basic("{} + {} = {}", "1", "2", "3")
assert result == "1 + 2 = 3"
class TestFormatNamed:
def test_format_named(self):
result = format_named("Hello, {name}!", name="World")
assert result == "Hello, World!"
class TestFormatDict:
def test_format_dict(self):
result = format_dict("Hello, {name}!", {"name": "World"})
assert result == "Hello, World!"
class TestFString:
def test_f_string_style(self):
result = f_string_style("Alice", 42)
assert result == "Name: Alice, Value: 42"
class TestPercentFormat:
def test_percent_format(self):
result = percent_format("Hello, %s!", "World")
assert result == "Hello, World!"
class TestFormatNumber:
def test_format_number(self):
assert format_number(3.14159, 2) == "3.14"
assert format_number(3.14159, 4) == "3.1416"
class TestFormatCurrency:
def test_format_currency(self):
result = format_currency(1234.56)
assert result == "$1,234.56"
def test_format_currency_custom(self):
result = format_currency(1234.56, "€")
assert result == "€1,234.56"
class TestFormatPercent:
def test_format_percent(self):
assert format_percent(0.5) == "50.0%"
assert format_percent(0.123) == "12.3%"
class TestFormatScientific:
def test_format_scientific(self):
result = format_scientific(1234567.89)
assert "e" in result
class TestNumberBases:
def test_format_binary(self):
assert format_binary(10) == "1010"
def test_format_hex(self):
assert format_hex(255) == "ff"
def test_format_octal(self):
assert format_octal(8) == "10"
class TestPadding:
def test_pad_left(self):
assert pad_left("hello", 10) == " hello"
assert pad_left("hello", 10, "0") == "00000hello"
def test_pad_right(self):
assert pad_right("hello", 10) == "hello "
def test_pad_center(self):
assert pad_center("hi", 6) == " hi "
def test_zfill(self):
assert zfill("42", 5) == "00042"
class TestTruncate:
def test_truncate_short(self):
assert truncate("hello", 10) == "hello"
def test_truncate_long(self):
assert truncate("hello world", 8) == "hello..."
def test_truncate_custom_suffix(self):
assert truncate("hello world", 8, "~") == "hello w~"
class TestWrapText:
def test_wrap_text(self):
result = wrap_text("hello world test", 10)
lines = result.split("\n")
assert all(len(line) <= 10 for line in lines)
class TestFormatList:
def test_format_list_empty(self):
assert format_list([]) == ""
def test_format_list_single(self):
assert format_list(["one"]) == "one"
def test_format_list_two(self):
assert format_list(["one", "two"]) == "one and two"
def test_format_list_multiple(self):
assert format_list(["one", "two", "three"]) == "one, two and three"
class TestFormatTable:
def test_format_table(self):
rows = [["1", "2"], ["3", "4"]]
result = format_table(rows, ["A", "B"])
assert "A" in result
assert "1" in result
assert "|" in result
class TestFormatKeyValue:
def test_format_key_value(self):
data = {"name": "Alice", "age": "30"}
result = format_key_value(data)
assert "name" in result
assert "Alice" in result
class TestFormatBytes:
def test_format_bytes_bytes(self):
assert format_bytes(500) == "500.0 B"
def test_format_bytes_kb(self):
result = format_bytes(1024)
assert "KB" in result
def test_format_bytes_mb(self):
result = format_bytes(1024 * 1024)
assert "MB" in result
class TestFormatDuration:
def test_format_duration_seconds(self):
assert format_duration(30) == "30s"
def test_format_duration_minutes(self):
assert format_duration(90) == "1m 30s"
def test_format_duration_hours(self):
assert format_duration(3660) == "1h 1m"
class TestFormatOrdinal:
def test_format_ordinal_1st(self):
assert format_ordinal(1) == "1st"
def test_format_ordinal_2nd(self):
assert format_ordinal(2) == "2nd"
def test_format_ordinal_3rd(self):
assert format_ordinal(3) == "3rd"
def test_format_ordinal_4th(self):
assert format_ordinal(4) == "4th"
def test_format_ordinal_11th(self):
assert format_ordinal(11) == "11th"
def test_format_ordinal_21st(self):
assert format_ordinal(21) == "21st"
class TestFormatPlural:
def test_format_plural_singular(self):
assert format_plural(1, "item") == "1 item"
def test_format_plural_plural(self):
assert format_plural(5, "item") == "5 items"
def test_format_plural_custom(self):
assert format_plural(5, "child", "children") == "5 children"
class TestTemplateReplace:
def test_template_replace(self):
result = template_replace("Hello, {{name}}!", {"name": "World"})
assert result == "Hello, World!"
def test_template_replace_custom(self):
result = template_replace("Hello, %name%!", {"name": "World"}, "%", "%")
assert result == "Hello, World!"
class TestQuote:
def test_quote_default(self):
assert quote("hello") == '"hello"'
def test_quote_custom(self):
assert quote("hello", "'") == "'hello'"
def test_unquote(self):
assert unquote('"hello"') == "hello"
assert unquote("'hello'") == "hello"
def test_unquote_no_quotes(self):
assert unquote("hello") == "hello"
class TestEdgeCases:
def test_empty_string_pad(self):
assert pad_left("", 5) == " "
def test_zero_width_pad(self):
assert pad_left("hello", 3) == "hello"
def test_format_zero_bytes(self):
assert format_bytes(0) == "0.0 B"
| false
|
string_format
| 260
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: LtEq, left: Call { func: "len", args: [Var("line")], kwargs: [] }, right: Literal(Int(10)) }, generators: [HirComprehension { target: "line", iter: Var("lines"), conditions: [] }] }
|
|
example_strip
|
strip_tool.py
|
#!/usr/bin/env python3
"""Strip Example - String strip operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="String strip tool")
subs = parser.add_subparsers(dest="cmd", required=True)
b = subs.add_parser("both")
b.add_argument("text")
le = subs.add_parser("left")
le.add_argument("text")
r = subs.add_parser("right")
r.add_argument("text")
args = parser.parse_args()
if args.cmd == "both":
print(args.text.strip("_"))
elif args.cmd == "left":
print(args.text.lstrip("_"))
elif args.cmd == "right":
print(args.text.rstrip("_"))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_strip/strip_tool.py (684 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_strip/strip_tool.rs (1249 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_strip/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 13.1 KB/s
⏱️ Total time: 50ms
| true
|
strip
| 28
| 6
|
[] | 0
| null |
example_strip
|
test_strip_tool.py
|
"""Tests for strip_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "strip_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_both():
r = run("both ___hello___")
assert r.returncode == 0
assert r.stdout.strip() == "hello"
def test_left():
r = run("left ___hello")
assert r.returncode == 0
assert r.stdout.strip() == "hello"
def test_right():
r = run("right hello___")
assert r.returncode == 0
assert r.stdout.strip() == "hello"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_strip/test_strip_tool.py (634 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_strip/test_strip_tool.rs (1842 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_strip/Cargo.toml (2 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 13.4 KB/s
⏱️ Total time: 46ms
| true
|
strip
| 32
| 6
|
[] | 0
| null |
example_struct
|
struct_tool.py
|
#!/usr/bin/env python3
"""Struct Example - Binary packing CLI."""
import argparse
import struct
def cmd_pack(args):
"""Pack values to binary. Depyler: proven to terminate"""
values = [int(v) if v.lstrip("-").isdigit() else float(v) for v in args.values]
packed = struct.pack(args.format, *values)
print(packed.hex())
def cmd_size(args):
"""Get struct size. Depyler: proven to terminate"""
size = struct.calcsize(args.format)
print(f"Size: {size} bytes")
def main():
parser = argparse.ArgumentParser(description="Struct tool")
subs = parser.add_subparsers(dest="command", required=True)
p = subs.add_parser("pack")
p.add_argument("format")
p.add_argument("values", nargs="+")
s = subs.add_parser("size")
s.add_argument("format")
args = parser.parse_args()
{"pack": cmd_pack, "size": cmd_size}[args.command](args)
if __name__ == "__main__":
main()
| false
|
struct
| 34
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 826..876, value: Dict(ExprDict { range: 826..862, keys: [Some(Constant(ExprConstant { range: 827..833, value: Str("pack"), kind: None })), Some(Constant(ExprConstant { range: 845..851, value: Str("size"), kind: None }))], values: [Name(ExprName { range: 835..843, id: Identifier("cmd_pack"), ctx: Load }), Name(ExprName { range: 853..861, id: Identifier("cmd_size"), ctx: Load })] }), slice: Attribute(ExprAttribute { range: 863
|
|
example_struct
|
test_struct_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for struct CLI."""
import subprocess
SCRIPT = "struct_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestPack:
def test_pack_int(self):
result = run(["pack", ">i", "12345"])
assert result.returncode == 0
class TestSize:
def test_size_int(self):
result = run(["size", ">i"])
assert result.returncode == 0
assert "4" in result.stdout
def test_size_double(self):
result = run(["size", ">d"])
assert result.returncode == 0
assert "8" 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_struct/test_struct_tool.py (782 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_struct/test_struct_tool.rs (2088 bytes)
⏱️ Parse time: 46ms
📊 Throughput: 16.4 KB/s
⏱️ Total time: 46ms
| true
|
struct
| 27
| 5
|
[
"class_definition"
] | 0.612
| null |
example_struct_pack
|
struct_pack_cli.py
|
#!/usr/bin/env python3
"""Struct Pack CLI.
Binary data packing and unpacking using struct module.
"""
import argparse
import struct
import sys
def pack_byte(value: int) -> bytes:
"""Pack a single byte."""
return struct.pack("B", value)
def unpack_byte(data: bytes) -> int:
"""Unpack a single byte."""
return struct.unpack("B", data)[0]
def pack_short(value: int, big_endian: bool = False) -> bytes:
"""Pack a 16-bit integer."""
fmt = ">h" if big_endian else "<h"
return struct.pack(fmt, value)
def unpack_short(data: bytes, big_endian: bool = False) -> int:
"""Unpack a 16-bit integer."""
fmt = ">h" if big_endian else "<h"
return struct.unpack(fmt, data)[0]
def pack_int(value: int, big_endian: bool = False) -> bytes:
"""Pack a 32-bit integer."""
fmt = ">i" if big_endian else "<i"
return struct.pack(fmt, value)
def unpack_int(data: bytes, big_endian: bool = False) -> int:
"""Unpack a 32-bit integer."""
fmt = ">i" if big_endian else "<i"
return struct.unpack(fmt, data)[0]
def pack_long(value: int, big_endian: bool = False) -> bytes:
"""Pack a 64-bit integer."""
fmt = ">q" if big_endian else "<q"
return struct.pack(fmt, value)
def unpack_long(data: bytes, big_endian: bool = False) -> int:
"""Unpack a 64-bit integer."""
fmt = ">q" if big_endian else "<q"
return struct.unpack(fmt, data)[0]
def pack_float(value: float, big_endian: bool = False) -> bytes:
"""Pack a 32-bit float."""
fmt = ">f" if big_endian else "<f"
return struct.pack(fmt, value)
def unpack_float(data: bytes, big_endian: bool = False) -> float:
"""Unpack a 32-bit float."""
fmt = ">f" if big_endian else "<f"
return struct.unpack(fmt, data)[0]
def pack_double(value: float, big_endian: bool = False) -> bytes:
"""Pack a 64-bit double."""
fmt = ">d" if big_endian else "<d"
return struct.pack(fmt, value)
def unpack_double(data: bytes, big_endian: bool = False) -> float:
"""Unpack a 64-bit double."""
fmt = ">d" if big_endian else "<d"
return struct.unpack(fmt, data)[0]
def pack_bool(value: bool) -> bytes:
"""Pack a boolean."""
return struct.pack("?", value)
def unpack_bool(data: bytes) -> bool:
"""Unpack a boolean."""
return struct.unpack("?", data)[0]
def pack_char(value: str) -> bytes:
"""Pack a single character."""
return struct.pack("c", value.encode("ascii"))
def unpack_char(data: bytes) -> str:
"""Unpack a single character."""
return struct.unpack("c", data)[0].decode("ascii")
def pack_string(value: str, length: int) -> bytes:
"""Pack a fixed-length string."""
encoded = value.encode("ascii")[:length]
padded = encoded.ljust(length, b"\x00")
return struct.pack(f"{length}s", padded)
def unpack_string(data: bytes) -> str:
"""Unpack a null-terminated string."""
return data.rstrip(b"\x00").decode("ascii")
def pack_unsigned_int(value: int, big_endian: bool = False) -> bytes:
"""Pack an unsigned 32-bit integer."""
fmt = ">I" if big_endian else "<I"
return struct.pack(fmt, value)
def unpack_unsigned_int(data: bytes, big_endian: bool = False) -> int:
"""Unpack an unsigned 32-bit integer."""
fmt = ">I" if big_endian else "<I"
return struct.unpack(fmt, data)[0]
def pack_point(x: float, y: float) -> bytes:
"""Pack a 2D point (two floats)."""
return struct.pack("<ff", x, y)
def unpack_point(data: bytes) -> tuple[float, float]:
"""Unpack a 2D point."""
return struct.unpack("<ff", data)
def pack_color(r: int, g: int, b: int, a: int) -> bytes:
"""Pack RGBA color (4 bytes)."""
return struct.pack("BBBB", r, g, b, a)
def unpack_color(data: bytes) -> tuple[int, int, int, int]:
"""Unpack RGBA color."""
return struct.unpack("BBBB", data)
def pack_header(version: int, flags: int, length: int) -> bytes:
"""Pack a simple header (short, byte, int)."""
return struct.pack("<hBI", version, flags, length)
def unpack_header(data: bytes) -> tuple[int, int, int]:
"""Unpack a simple header."""
return struct.unpack("<hBI", data)
def calculate_struct_size(fmt: str) -> int:
"""Calculate the size of a struct format."""
return struct.calcsize(fmt)
def pack_array_int(values: list[int]) -> bytes:
"""Pack an array of integers."""
count = len(values)
fmt = f"<{count}i"
return struct.pack(fmt, *values)
def unpack_array_int(data: bytes, count: int) -> list[int]:
"""Unpack an array of integers."""
fmt = f"<{count}i"
return list(struct.unpack(fmt, data))
def pack_array_float(values: list[float]) -> bytes:
"""Pack an array of floats."""
count = len(values)
fmt = f"<{count}f"
return struct.pack(fmt, *values)
def unpack_array_float(data: bytes, count: int) -> list[float]:
"""Unpack an array of floats."""
fmt = f"<{count}f"
return list(struct.unpack(fmt, data))
def bytes_to_hex(data: bytes) -> str:
"""Convert bytes to hex string."""
return data.hex()
def hex_to_bytes(hex_str: str) -> bytes:
"""Convert hex string to bytes."""
return bytes.fromhex(hex_str)
def swap_endian_short(value: int) -> int:
"""Swap endianness of a 16-bit value."""
packed_le = struct.pack("<h", value)
return struct.unpack(">h", packed_le)[0]
def swap_endian_int(value: int) -> int:
"""Swap endianness of a 32-bit value."""
packed_le = struct.pack("<i", value)
return struct.unpack(">i", packed_le)[0]
def main() -> int:
parser = argparse.ArgumentParser(description="Struct pack CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# pack
pack_p = subparsers.add_parser("pack", help="Pack values")
pack_p.add_argument("type", choices=["byte", "short", "int", "float"])
pack_p.add_argument("value", type=float)
pack_p.add_argument("--big-endian", action="store_true")
# unpack
unpack_p = subparsers.add_parser("unpack", help="Unpack hex data")
unpack_p.add_argument("type", choices=["byte", "short", "int", "float"])
unpack_p.add_argument("hex_data")
unpack_p.add_argument("--big-endian", action="store_true")
# size
size_p = subparsers.add_parser("size", help="Calculate struct size")
size_p.add_argument("format")
args = parser.parse_args()
if args.command == "pack":
if args.type == "byte":
result = pack_byte(int(args.value))
elif args.type == "short":
result = pack_short(int(args.value), args.big_endian)
elif args.type == "int":
result = pack_int(int(args.value), args.big_endian)
else:
result = pack_float(args.value, args.big_endian)
print(f"Packed: {bytes_to_hex(result)}")
elif args.command == "unpack":
data = hex_to_bytes(args.hex_data)
if args.type == "byte":
value = unpack_byte(data)
elif args.type == "short":
value = unpack_short(data, args.big_endian)
elif args.type == "int":
value = unpack_int(data, args.big_endian)
else:
value = unpack_float(data, args.big_endian)
print(f"Unpacked: {value}")
elif args.command == "size":
size = calculate_struct_size(args.format)
print(f"Size: {size} bytes")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
struct_pack
| 265
| 0
|
[] | 0
|
Type inference hints:
Hint: str for variable 'length' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'values' [High] (usage patterns suggest this type)
Hint: str for variable 'count' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'count' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'values' [High] (usage patterns suggest this type)
Hint: str for variable
|
|
example_struct_pack
|
test_struct_pack_cli.py
|
"""Tests for struct_pack_cli.py"""
from struct_pack_cli import (
bytes_to_hex,
calculate_struct_size,
hex_to_bytes,
pack_array_float,
pack_array_int,
pack_bool,
pack_byte,
pack_char,
pack_color,
pack_double,
pack_float,
pack_header,
pack_int,
pack_long,
pack_point,
pack_short,
pack_string,
pack_unsigned_int,
swap_endian_int,
swap_endian_short,
unpack_array_float,
unpack_array_int,
unpack_bool,
unpack_byte,
unpack_char,
unpack_color,
unpack_double,
unpack_float,
unpack_header,
unpack_int,
unpack_long,
unpack_point,
unpack_short,
unpack_string,
unpack_unsigned_int,
)
class TestPackByte:
def test_pack_zero(self):
assert pack_byte(0) == b"\x00"
def test_pack_max(self):
assert pack_byte(255) == b"\xff"
def test_unpack_zero(self):
assert unpack_byte(b"\x00") == 0
def test_unpack_max(self):
assert unpack_byte(b"\xff") == 255
def test_roundtrip(self):
for val in [0, 1, 127, 128, 255]:
assert unpack_byte(pack_byte(val)) == val
class TestPackShort:
def test_little_endian(self):
assert pack_short(256) == b"\x00\x01"
def test_big_endian(self):
assert pack_short(256, big_endian=True) == b"\x01\x00"
def test_negative(self):
packed = pack_short(-1)
assert unpack_short(packed) == -1
def test_roundtrip(self):
for val in [-32768, -1, 0, 1, 32767]:
assert unpack_short(pack_short(val)) == val
assert unpack_short(pack_short(val, True), True) == val
class TestPackInt:
def test_little_endian(self):
packed = pack_int(0x12345678)
assert packed == b"\x78\x56\x34\x12"
def test_big_endian(self):
packed = pack_int(0x12345678, big_endian=True)
assert packed == b"\x12\x34\x56\x78"
def test_negative(self):
assert unpack_int(pack_int(-1)) == -1
def test_roundtrip(self):
for val in [-2147483648, -1, 0, 1, 2147483647]:
assert unpack_int(pack_int(val)) == val
class TestPackLong:
def test_positive(self):
val = 0x123456789ABCDEF0
assert unpack_long(pack_long(val)) == val
def test_negative(self):
assert unpack_long(pack_long(-1)) == -1
def test_big_endian(self):
val = 0x0102030405060708
assert unpack_long(pack_long(val, True), True) == val
class TestPackFloat:
def test_zero(self):
packed = pack_float(0.0)
assert unpack_float(packed) == 0.0
def test_one(self):
packed = pack_float(1.0)
assert abs(unpack_float(packed) - 1.0) < 1e-6
def test_negative(self):
packed = pack_float(-3.14)
assert abs(unpack_float(packed) - (-3.14)) < 1e-5
def test_big_endian(self):
val = 1.5
packed = pack_float(val, big_endian=True)
assert abs(unpack_float(packed, big_endian=True) - val) < 1e-6
class TestPackDouble:
def test_precision(self):
val = 3.141592653589793
assert unpack_double(pack_double(val)) == val
def test_large(self):
val = 1e100
assert unpack_double(pack_double(val)) == val
def test_big_endian(self):
val = 2.718281828459045
assert unpack_double(pack_double(val, True), True) == val
class TestPackBool:
def test_true(self):
assert unpack_bool(pack_bool(True)) is True
def test_false(self):
assert unpack_bool(pack_bool(False)) is False
class TestPackChar:
def test_letter(self):
assert unpack_char(pack_char("A")) == "A"
def test_digit(self):
assert unpack_char(pack_char("9")) == "9"
def test_special(self):
assert unpack_char(pack_char("@")) == "@"
class TestPackString:
def test_exact_length(self):
result = unpack_string(pack_string("hello", 5))
assert result == "hello"
def test_truncate(self):
result = unpack_string(pack_string("hello world", 5))
assert result == "hello"
def test_pad(self):
packed = pack_string("hi", 5)
assert len(packed) == 5
assert unpack_string(packed) == "hi"
class TestPackUnsignedInt:
def test_max_value(self):
val = 4294967295
assert unpack_unsigned_int(pack_unsigned_int(val)) == val
def test_zero(self):
assert unpack_unsigned_int(pack_unsigned_int(0)) == 0
class TestPackPoint:
def test_origin(self):
x, y = unpack_point(pack_point(0.0, 0.0))
assert x == 0.0
assert y == 0.0
def test_positive(self):
x, y = unpack_point(pack_point(1.5, 2.5))
assert abs(x - 1.5) < 1e-6
assert abs(y - 2.5) < 1e-6
class TestPackColor:
def test_white(self):
r, g, b, a = unpack_color(pack_color(255, 255, 255, 255))
assert (r, g, b, a) == (255, 255, 255, 255)
def test_red(self):
r, g, b, a = unpack_color(pack_color(255, 0, 0, 255))
assert (r, g, b, a) == (255, 0, 0, 255)
def test_transparent(self):
r, g, b, a = unpack_color(pack_color(0, 0, 0, 0))
assert (r, g, b, a) == (0, 0, 0, 0)
class TestPackHeader:
def test_basic(self):
version, flags, length = unpack_header(pack_header(1, 0, 100))
assert version == 1
assert flags == 0
assert length == 100
def test_full(self):
version, flags, length = unpack_header(pack_header(255, 255, 4294967295))
assert version == 255
assert flags == 255
assert length == 4294967295
class TestCalculateStructSize:
def test_byte(self):
assert calculate_struct_size("B") == 1
def test_short(self):
assert calculate_struct_size("h") == 2
def test_int(self):
assert calculate_struct_size("i") == 4
def test_long(self):
assert calculate_struct_size("q") == 8
def test_float(self):
assert calculate_struct_size("f") == 4
def test_double(self):
assert calculate_struct_size("d") == 8
def test_combined(self):
assert calculate_struct_size("<hBI") == 7
class TestPackArray:
def test_int_array(self):
values = [1, 2, 3, 4, 5]
packed = pack_array_int(values)
result = unpack_array_int(packed, len(values))
assert result == values
def test_float_array(self):
values = [1.0, 2.5, 3.14]
packed = pack_array_float(values)
result = unpack_array_float(packed, len(values))
for expected, actual in zip(values, result, strict=False):
assert abs(expected - actual) < 1e-6
def test_empty_int_array(self):
assert pack_array_int([]) == b""
def test_single_element(self):
result = unpack_array_int(pack_array_int([42]), 1)
assert result == [42]
class TestHexConversion:
def test_to_hex(self):
assert bytes_to_hex(b"\x00\x01\xff") == "0001ff"
def test_from_hex(self):
assert hex_to_bytes("0001ff") == b"\x00\x01\xff"
def test_roundtrip(self):
data = b"\xde\xad\xbe\xef"
assert hex_to_bytes(bytes_to_hex(data)) == data
class TestSwapEndian:
def test_swap_short(self):
assert swap_endian_short(0x0102) == 0x0201
def test_swap_int(self):
assert swap_endian_int(0x01020304) == 0x04030201
def test_roundtrip_short(self):
val = 0x1234
assert swap_endian_short(swap_endian_short(val)) == val
def test_roundtrip_int(self):
val = 0x12345678
assert swap_endian_int(swap_endian_int(val)) == val
class TestEdgeCases:
def test_empty_string(self):
result = unpack_string(pack_string("", 5))
assert result == ""
def test_zero_length_string(self):
packed = pack_string("test", 0)
assert packed == b""
def test_negative_short_roundtrip(self):
for val in [-1, -100, -32768]:
assert unpack_short(pack_short(val)) == val
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_struct_pack/test_struct_pack_cli.py (7996 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_struct_pack/test_struct_pack_cli.rs (19857 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 152.9 KB/s
⏱️ Total time: 51ms
| true
|
struct_pack
| 308
| 5
|
[
"class_definition",
"decorator"
] | 0.612
| null |
example_subcommand_simple
|
subcommand_simple.py
|
#!/usr/bin/env python3
"""
Simple Subcommand CLI - Minimal subcommand example
This example demonstrates the simplest possible argparse subcommand pattern:
- Single subcommand with one positional argument
- Direct field access on args (validates E0609 fix)
- Minimal handler function
Purpose: Validate depyler handles subcommand field access correctly (E0609).
"""
import argparse
def main():
"""Main entry point with single subcommand."""
parser = argparse.ArgumentParser(
description="Simple subcommand example",
prog="subcommand_simple.py",
)
subparsers = parser.add_subparsers(
dest="command",
help="Available commands",
required=True,
)
# Single subcommand: greet
greet_parser = subparsers.add_parser(
"greet",
help="Greet a person",
)
greet_parser.add_argument(
"name",
help="Name to greet",
)
args = parser.parse_args()
# Direct field access - this is what E0609 tests
if args.command == "greet":
print(f"Hello, {args.name}!")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_subcommand_simple/subcommand_simple.py (1114 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_subcommand_simple/subcommand_simple.rs (826 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_subcommand_simple/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 23.1 KB/s
⏱️ Total time: 47ms
| true
|
subcommand_simple
| 47
| 6
|
[
"context_manager"
] | 0.652
| null |
example_subcommand_simple
|
test_subcommand_simple.py
|
"""
Test suite for subcommand_simple.py
Validates E0609 fix: field access on Args with subcommands
Following extreme TDD methodology.
"""
import subprocess
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parent / "subcommand_simple.py"
def run_cli(*args):
"""Helper to run CLI and capture output."""
result = subprocess.run(
["python3", str(SCRIPT), *args],
capture_output=True,
text=True,
)
return result
class TestSubcommandSimple:
"""Test suite for simple subcommand pattern."""
def test_help_flag(self):
"""Test --help displays usage information."""
result = run_cli("--help")
assert result.returncode == 0
assert "usage:" in result.stdout.lower()
assert "greet" in result.stdout
def test_greet_subcommand(self):
"""Test greet subcommand with name."""
result = run_cli("greet", "Alice")
assert result.returncode == 0
assert "Hello, Alice!" in result.stdout
def test_greet_subcommand_help(self):
"""Test greet subcommand --help."""
result = run_cli("greet", "--help")
assert result.returncode == 0
assert "name" in result.stdout.lower()
def test_missing_subcommand(self):
"""Test error when no subcommand provided."""
result = run_cli()
assert result.returncode != 0
assert "required" in result.stderr.lower() or "the following arguments" in result.stderr.lower()
def test_missing_name_argument(self):
"""Test error when greet called without name."""
result = run_cli("greet")
assert result.returncode != 0
assert "required" in result.stderr.lower() or "argument" in result.stderr.lower()
def test_invalid_subcommand(self):
"""Test error with invalid subcommand."""
result = run_cli("invalid")
assert result.returncode != 0
assert "invalid" in result.stderr.lower() or "argument" in result.stderr.lower()
@pytest.mark.parametrize(
"name,expected",
[
("Alice", "Hello, Alice!"),
("Bob", "Hello, Bob!"),
("World", "Hello, World!"),
("123", "Hello, 123!"),
("", "Hello, !"),
],
)
def test_parametrized_names(self, name, expected):
"""Test various input names."""
result = run_cli("greet", name)
assert result.returncode == 0
assert expected in result.stdout
def test_name_with_special_chars(self):
"""Test names with special characters."""
special_names = ["O'Brien", "Dr. Smith", "Maria-Elena"]
for name in special_names:
result = run_cli("greet", name)
assert result.returncode == 0
assert name in result.stdout
def test_unicode_name(self):
"""Test unicode names."""
result = run_cli("greet", "日本語")
assert result.returncode == 0
assert "日本語" in result.stdout
def test_stdout_ends_with_newline(self):
"""Test output ends with newline."""
result = run_cli("greet", "Test")
assert result.returncode == 0
assert result.stdout.endswith("\n")
def test_stderr_empty_on_success(self):
"""Test stderr is empty on successful execution."""
result = run_cli("greet", "Test")
assert result.returncode == 0
assert result.stderr == ""
def test_deterministic_output(self):
"""Test output is deterministic across runs."""
results = [run_cli("greet", "Test") for _ in range(3)]
assert all(r.returncode == 0 for r in results)
assert all(r.stdout == results[0].stdout for r in results)
| false
|
subcommand_simple
| 112
| 0
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
|
Performance Warnings
══════════════════════════════════════════════════
[1] [Medium] Large value 'args' passed by copy
Location: run_cli, line 0
Impact: Complexity: O(n), Scales: Yes, Hot path: No
Why: Passing large values by copy is inefficient
Fix: Consider passing by reference (&) or using Box/Arc for large types
Summary: Found 1 warnings (0 critical, 0 high severity)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions:
|
|
example_subcommands
|
git_clone.py
|
#!/usr/bin/env python3
"""
Git-like CLI with subcommands (example_subcommands).
This example demonstrates argparse subparsers for creating
git-like command structures with multiple subcommands.
Features:
- Three subcommands: clone, push, pull
- Global --verbose flag
- Subcommand-specific arguments
"""
import argparse
def main():
"""Main entry point for the git-like CLI."""
# Create the top-level parser
parser = argparse.ArgumentParser(
description="Git-like CLI example with subcommands",
prog="git_clone.py",
)
# Add global arguments (before subparsers)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Enable verbose output",
)
parser.add_argument(
"--version",
action="version",
version="1.0.0",
)
# Create subparsers
subparsers = parser.add_subparsers(
dest="command",
help="Available commands",
required=True, # Make subcommand required
)
# Subcommand: clone
parser_clone = subparsers.add_parser(
"clone",
help="Clone a repository",
)
parser_clone.add_argument(
"url",
help="Repository URL to clone",
)
# Subcommand: push
parser_push = subparsers.add_parser(
"push",
help="Push to a remote repository",
)
parser_push.add_argument(
"remote",
help="Remote name to push to",
)
# Subcommand: pull
parser_pull = subparsers.add_parser(
"pull",
help="Pull from a remote repository",
)
parser_pull.add_argument(
"remote",
help="Remote name to pull from",
)
# Parse arguments
args = parser.parse_args()
# Execute the appropriate subcommand
if args.command == "clone":
handle_clone(args)
elif args.command == "push":
handle_push(args)
elif args.command == "pull":
handle_pull(args)
def handle_clone(args):
"""Handle the 'clone' subcommand."""
if args.verbose:
print("Verbose mode: ON")
print(f"Clone: {args.url}")
print("This is a demo - no actual cloning performed")
else:
print(f"Clone: {args.url}")
def handle_push(args):
"""Handle the 'push' subcommand."""
if args.verbose:
print("Verbose mode: ON")
print(f"Push to: {args.remote}")
print("This is a demo - no actual pushing performed")
else:
print(f"Push to: {args.remote}")
def handle_pull(args):
"""Handle the 'pull' subcommand."""
if args.verbose:
print("Verbose mode: ON")
print(f"Pull from: {args.remote}")
print("This is a demo - no actual pulling performed")
else:
print(f"Pull from: {args.remote}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/git_clone.py (2819 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/git_clone.rs (3229 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 59.6 KB/s
⏱️ Total time: 46ms
| true
|
subcommands
| 119
| 6
|
[
"context_manager"
] | 0.652
| null |
example_subcommands
|
test_git_clone.py
|
#!/usr/bin/env python3
"""
Comprehensive test suite for git_clone.py (example_subcommands).
This test suite follows the extreme TDD approach with 100% coverage goals.
Tests are written BEFORE implementation (RED phase).
Test Categories:
1. Help and version output
2. Global flags
3. Subcommand: clone
4. Subcommand: push
5. Subcommand: pull
6. Error handling (invalid subcommands, missing args)
7. Edge cases
"""
import subprocess
from pathlib import Path
# Path to the script
SCRIPT_PATH = Path(__file__).parent / "git_clone.py"
def run_cli(*args):
"""Helper function to run the CLI with given arguments."""
result = subprocess.run(
["python3", str(SCRIPT_PATH)] + list(args),
capture_output=True,
text=True,
)
return result
class TestHelpAndVersion:
"""Test help and version output."""
def test_help_flag(self):
"""Test --help flag displays help message"""
result = run_cli("--help")
assert result.returncode == 0, "Help should exit with code 0"
assert "usage:" in result.stdout.lower(), "Help should show usage"
assert "clone" in result.stdout.lower(), "Help should mention clone subcommand"
assert "push" in result.stdout.lower(), "Help should mention push subcommand"
assert "pull" in result.stdout.lower(), "Help should mention pull subcommand"
def test_short_help_flag(self):
"""Test -h short form of help"""
result = run_cli("-h")
assert result.returncode == 0, "Short help should exit with code 0"
assert "usage:" in result.stdout.lower(), "Short help should show usage"
def test_version_flag(self):
"""Test --version flag displays version"""
result = run_cli("--version")
assert result.returncode == 0, "Version should exit with code 0"
assert "1.0.0" in result.stdout, "Should display version 1.0.0"
def test_no_args_shows_help(self):
"""Test that running with no arguments shows help or error"""
result = run_cli()
assert result.returncode != 0, "No arguments should fail"
# Should either show help or error message
assert "usage:" in result.stdout.lower() or "usage:" in result.stderr.lower(), (
"Should show usage information"
)
class TestGlobalFlags:
"""Test global flags that apply to all subcommands."""
def test_verbose_flag_with_clone(self):
"""Test --verbose flag with clone subcommand"""
result = run_cli("--verbose", "clone", "https://example.com/repo.git")
assert result.returncode == 0, "Should succeed with verbose flag"
assert "verbose mode" in result.stdout.lower() or "verbose" in result.stdout.lower()
def test_verbose_short_form(self):
"""Test -v short form of verbose flag"""
result = run_cli("-v", "clone", "https://example.com/repo.git")
assert result.returncode == 0, "Should succeed with -v flag"
def test_verbose_after_subcommand(self):
"""Test that verbose flag works after subcommand (if supported)"""
# Some CLIs allow flags after subcommands
result = run_cli("clone", "--verbose", "https://example.com/repo.git")
# This might fail depending on implementation, check either way
assert result.returncode == 0 or "unrecognized" in result.stderr.lower()
class TestCloneSubcommand:
"""Test the 'clone' subcommand."""
def test_clone_with_url(self):
"""Test clone subcommand with valid URL"""
result = run_cli("clone", "https://example.com/repo.git")
assert result.returncode == 0, "Clone should succeed"
assert "clone" in result.stdout.lower(), "Output should mention cloning"
assert "https://example.com/repo.git" in result.stdout, "Should display the URL"
def test_clone_with_ssh_url(self):
"""Test clone with SSH URL format"""
result = run_cli("clone", "[email protected]:user/repo.git")
assert result.returncode == 0, "Clone should work with SSH URL"
assert "[email protected]:user/repo.git" in result.stdout
def test_clone_with_local_path(self):
"""Test clone with local file path"""
result = run_cli("clone", "/path/to/local/repo")
assert result.returncode == 0, "Clone should work with local path"
assert "/path/to/local/repo" in result.stdout
def test_clone_without_url(self):
"""Test clone without required URL argument"""
result = run_cli("clone")
assert result.returncode != 0, "Clone without URL should fail"
assert "required" in result.stderr.lower() or "expected" in result.stderr.lower()
def test_clone_help(self):
"""Test help for clone subcommand"""
result = run_cli("clone", "--help")
assert result.returncode == 0, "Clone help should succeed"
assert "clone" in result.stdout.lower()
assert "url" in result.stdout.lower(), "Should mention URL argument"
class TestPushSubcommand:
"""Test the 'push' subcommand."""
def test_push_with_remote(self):
"""Test push subcommand with remote name"""
result = run_cli("push", "origin")
assert result.returncode == 0, "Push should succeed"
assert "push" in result.stdout.lower(), "Output should mention pushing"
assert "origin" in result.stdout, "Should display the remote name"
def test_push_with_different_remote(self):
"""Test push with non-standard remote name"""
result = run_cli("push", "upstream")
assert result.returncode == 0, "Push should work with any remote name"
assert "upstream" in result.stdout
def test_push_without_remote(self):
"""Test push without required remote argument"""
result = run_cli("push")
assert result.returncode != 0, "Push without remote should fail"
assert "required" in result.stderr.lower() or "expected" in result.stderr.lower()
def test_push_help(self):
"""Test help for push subcommand"""
result = run_cli("push", "--help")
assert result.returncode == 0, "Push help should succeed"
assert "push" in result.stdout.lower()
assert "remote" in result.stdout.lower(), "Should mention remote argument"
class TestPullSubcommand:
"""Test the 'pull' subcommand."""
def test_pull_with_remote(self):
"""Test pull subcommand with remote name"""
result = run_cli("pull", "origin")
assert result.returncode == 0, "Pull should succeed"
assert "pull" in result.stdout.lower(), "Output should mention pulling"
assert "origin" in result.stdout, "Should display the remote name"
def test_pull_with_different_remote(self):
"""Test pull with non-standard remote name"""
result = run_cli("pull", "upstream")
assert result.returncode == 0, "Pull should work with any remote name"
assert "upstream" in result.stdout
def test_pull_without_remote(self):
"""Test pull without required remote argument"""
result = run_cli("pull")
assert result.returncode != 0, "Pull without remote should fail"
assert "required" in result.stderr.lower() or "expected" in result.stderr.lower()
def test_pull_help(self):
"""Test help for pull subcommand"""
result = run_cli("pull", "--help")
assert result.returncode == 0, "Pull help should succeed"
assert "pull" in result.stdout.lower()
assert "remote" in result.stdout.lower(), "Should mention remote argument"
class TestErrorHandling:
"""Test error handling for invalid commands and arguments."""
def test_invalid_subcommand(self):
"""Test error handling for unrecognized subcommand"""
result = run_cli("invalid-command")
assert result.returncode != 0, "Invalid subcommand should fail"
assert (
"invalid choice" in result.stderr.lower() or "unrecognized" in result.stderr.lower()
), "Should report invalid/unrecognized command"
def test_clone_with_extra_args(self):
"""Test clone with too many arguments"""
result = run_cli("clone", "url1", "url2")
assert result.returncode != 0, "Clone with extra args should fail"
def test_push_with_extra_args(self):
"""Test push with too many arguments"""
result = run_cli("push", "remote1", "remote2")
assert result.returncode != 0, "Push with extra args should fail"
def test_typo_in_subcommand(self):
"""Test common typos in subcommands"""
result = run_cli("clon", "https://example.com/repo.git")
assert result.returncode != 0, "Typo in subcommand should fail"
class TestVerboseCombinations:
"""Test verbose flag with all subcommands."""
def test_verbose_clone(self):
"""Test verbose flag with clone"""
result = run_cli("--verbose", "clone", "https://example.com/repo.git")
assert result.returncode == 0
# Verbose output should show more details
assert "verbose" in result.stdout.lower() or len(result.stdout) > 50
def test_verbose_push(self):
"""Test verbose flag with push"""
result = run_cli("--verbose", "push", "origin")
assert result.returncode == 0
assert "verbose" in result.stdout.lower() or len(result.stdout) > 50
def test_verbose_pull(self):
"""Test verbose flag with pull"""
result = run_cli("--verbose", "pull", "origin")
assert result.returncode == 0
assert "verbose" in result.stdout.lower() or len(result.stdout) > 50
class TestEdgeCases:
"""Test edge cases and boundary conditions."""
def test_clone_with_whitespace_in_url(self):
"""Test clone with URL containing whitespace"""
result = run_cli("clone", "https://example.com/repo with spaces.git")
assert result.returncode == 0, "Should handle URLs with spaces"
assert "repo with spaces" in result.stdout
def test_clone_with_special_chars(self):
"""Test clone with special characters in URL"""
result = run_cli("clone", "https://example.com/repo-name_v2.0.git")
assert result.returncode == 0, "Should handle special chars in URL"
def test_push_remote_with_hyphen(self):
"""Test push with remote name containing hyphen"""
result = run_cli("push", "my-remote")
assert result.returncode == 0, "Should handle hyphens in remote name"
assert "my-remote" in result.stdout
def test_very_long_url(self):
"""Test clone with very long URL"""
long_url = "https://example.com/" + "a" * 200 + ".git"
result = run_cli("clone", long_url)
assert result.returncode == 0, "Should handle long URLs"
def test_empty_string_url(self):
"""Test clone with empty string as URL"""
result = run_cli("clone", "")
# This might succeed or fail depending on implementation
# Just check it doesn't crash
assert result.returncode in [0, 2], "Should handle empty string gracefully"
def test_stdout_ends_with_newline(self):
"""Test that output ends with newline"""
result = run_cli("clone", "https://example.com/repo.git")
assert result.returncode == 0
if result.stdout:
assert result.stdout.endswith("\n"), "Output should end with newline"
def test_deterministic_output(self):
"""Test that output is deterministic across multiple runs"""
result1 = run_cli("clone", "https://example.com/repo.git")
result2 = run_cli("clone", "https://example.com/repo.git")
assert result1.stdout == result2.stdout, "Output should be deterministic"
assert result1.returncode == result2.returncode, "Return code should be consistent"
class TestSubcommandCaseSensitivity:
"""Test case sensitivity of subcommands."""
def test_clone_lowercase(self):
"""Test that subcommands are case-sensitive (lowercase required)"""
result = run_cli("clone", "https://example.com/repo.git")
assert result.returncode == 0
def test_clone_uppercase(self):
"""Test uppercase subcommand should fail"""
result = run_cli("CLONE", "https://example.com/repo.git")
assert result.returncode != 0, "Uppercase subcommand should not be recognized"
def test_clone_mixed_case(self):
"""Test mixed case subcommand should fail"""
result = run_cli("Clone", "https://example.com/repo.git")
assert result.returncode != 0, "Mixed case subcommand should not be recognized"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/test_git_clone.py (12587 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/test_git_clone.rs (19243 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_subcommands/Cargo.toml (2 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 222.6 KB/s
⏱️ Total time: 55ms
| true
|
subcommands
| 301
| 6
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
| null |
example_subprocess
|
task_runner.py
|
#!/usr/bin/env python3
"""
Subprocess Example - System calls and process management
Demonstrates:
- subprocess.run() for executing commands
- Capturing stdout/stderr
- Process return codes
- Working directory control
- Error handling for subprocess operations
This validates depyler's ability to transpile subprocess calls
to Rust (std::process::Command).
"""
import argparse
import subprocess
import sys
def run_command(cmd, capture=False, check=False, cwd=None):
"""
Execute a system command
Args:
cmd: List of command and arguments
capture: Whether to capture output
check: Whether to raise error on non-zero exit
cwd: Working directory for command
Returns:
Tuple of (returncode, stdout, stderr)
Depyler: proven to terminate
"""
if capture:
result = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd, check=check)
return result.returncode, result.stdout, result.stderr
else:
result = subprocess.run(cmd, cwd=cwd, check=check)
return result.returncode, "", ""
def main():
"""
Main entry point for task runner CLI
Executes system commands with various options.
"""
parser = argparse.ArgumentParser(
description="Execute system commands with options", prog="task_runner.py"
)
parser.add_argument("command", help="Command to execute")
parser.add_argument("args", nargs="*", default=[], help="Arguments to pass to command")
parser.add_argument("--capture", action="store_true", help="Capture and display output")
parser.add_argument(
"--check",
action="store_true",
help="Exit with error if command fails",
)
parser.add_argument("--cwd", help="Working directory for command")
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
# Build command list
cmd = [args.command] + args.args
# Display what we're running
print(f"Running: {' '.join(cmd)}")
if args.cwd:
print(f"Working directory: {args.cwd}")
# Execute command
try:
returncode, stdout, stderr = run_command(
cmd, capture=args.capture, check=args.check, cwd=args.cwd
)
# Display results
print(f"Exit code: {returncode}")
if args.capture:
if stdout:
print(f"Output:\n{stdout}")
if stderr:
print(f"Errors:\n{stderr}", file=sys.stderr)
except subprocess.CalledProcessError as e:
print(f"Command failed with exit code {e.returncode}", file=sys.stderr)
sys.exit(e.returncode)
except FileNotFoundError:
print(f"Command not found: {args.command}", file=sys.stderr)
sys.exit(127)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_subprocess/task_runner.py (2819 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_subprocess/task_runner.rs (4479 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_subprocess/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 59.5 KB/s
⏱️ Total time: 46ms
| true
|
subprocess
| 105
| 6
|
[
"context_manager",
"exception_handling",
"multiprocessing"
] | 0.652
| null |
example_sum
|
sum_tool.py
|
#!/usr/bin/env python3
"""Sum Example - Summation operations CLI.
Examples:
>>> sum_five(1, 2, 3, 4, 5)
15
>>> product_three(2, 3, 4)
24
>>> average_three(3, 6, 9)
6.0
"""
import argparse
def sum_five(a: int, b: int, c: int, d: int, e: int) -> int:
"""Sum of five integers.
>>> sum_five(1, 1, 1, 1, 1)
5
>>> sum_five(0, 0, 0, 0, 0)
0
>>> sum_five(10, 20, 30, 40, 50)
150
"""
return a + b + c + d + e
def product_three(a: int, b: int, c: int) -> int:
"""Product of three integers.
>>> product_three(1, 2, 3)
6
>>> product_three(0, 5, 5)
0
>>> product_three(2, 2, 2)
8
"""
return a * b * c
def average_three(a: int, b: int, c: int) -> float:
"""Average of three integers.
>>> average_three(1, 2, 3)
2.0
>>> average_three(10, 20, 30)
20.0
>>> average_three(0, 0, 0)
0.0
"""
total = a + b + c
return total / 3
def main():
parser = argparse.ArgumentParser(description="Sum tool")
subs = parser.add_subparsers(dest="cmd", required=True)
a = subs.add_parser("add")
a.add_argument("a", type=int)
a.add_argument("b", type=int)
a.add_argument("c", type=int)
a.add_argument("d", type=int)
a.add_argument("e", type=int)
p = subs.add_parser("product")
p.add_argument("a", type=int)
p.add_argument("b", type=int)
p.add_argument("c", type=int)
av = subs.add_parser("average")
av.add_argument("a", type=int)
av.add_argument("b", type=int)
av.add_argument("c", type=int)
args = parser.parse_args()
if args.cmd == "add":
print(sum_five(args.a, args.b, args.c, args.d, args.e))
elif args.cmd == "product":
print(product_three(args.a, args.b, args.c))
elif args.cmd == "average":
print(average_three(args.a, args.b, args.c))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_sum/sum_tool.py (1900 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_sum/sum_tool.rs (3104 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_sum/Cargo.toml (1 dependencies)
⏱️ Parse time: 46ms
📊 Throughput: 39.9 KB/s
⏱️ Total time: 46ms
| true
|
sum
| 85
| 6
|
[] | 0
| null |
example_sum
|
test_sum_tool.py
|
"""Tests for sum_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "sum_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_add():
r = run("add 1 2 3 4 5")
assert r.returncode == 0
assert r.stdout.strip() == "15"
def test_product():
r = run("product 2 3 4")
assert r.returncode == 0
assert r.stdout.strip() == "24"
def test_average():
r = run("average 10 20 30")
assert r.returncode == 0
assert r.stdout.strip() == "20.0"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_sum/test_sum_tool.py (626 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_sum/test_sum_tool.rs (1836 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_sum/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 12.5 KB/s
⏱️ Total time: 48ms
| true
|
sum
| 32
| 6
|
[] | 0
| null |
example_task_queue
|
queue_cli.py
|
#!/usr/bin/env python3
"""Task queue CLI.
Simple task queue with priority and status tracking.
"""
import argparse
import json
import sys
from datetime import datetime
from enum import Enum
class TaskStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
class Task:
"""Represents a task in the queue."""
def __init__(
self,
task_id: str,
name: str,
priority: int = 0,
data: dict | None = None,
):
self.task_id = task_id
self.name = name
self.priority = priority
self.data = data or {}
self.status = TaskStatus.PENDING
self.created_at = datetime.now()
self.started_at: datetime | None = None
self.completed_at: datetime | None = None
self.result: str | None = None
self.error: str | None = None
def to_dict(self) -> dict:
"""Convert task to dictionary."""
return {
"task_id": self.task_id,
"name": self.name,
"priority": self.priority,
"data": self.data,
"status": self.status.value,
"created_at": self.created_at.isoformat(),
"started_at": self.started_at.isoformat() if self.started_at else None,
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
"result": self.result,
"error": self.error,
}
@classmethod
def from_dict(cls, data: dict) -> "Task":
"""Create task from dictionary."""
task = cls(
task_id=data["task_id"],
name=data["name"],
priority=data.get("priority", 0),
data=data.get("data", {}),
)
task.status = TaskStatus(data.get("status", "pending"))
if data.get("created_at"):
task.created_at = datetime.fromisoformat(data["created_at"])
if data.get("started_at"):
task.started_at = datetime.fromisoformat(data["started_at"])
if data.get("completed_at"):
task.completed_at = datetime.fromisoformat(data["completed_at"])
task.result = data.get("result")
task.error = data.get("error")
return task
class TaskQueue:
"""Priority task queue."""
def __init__(self):
self.tasks: dict[str, Task] = {}
self.next_id = 1
def add(self, name: str, priority: int = 0, data: dict | None = None) -> Task:
"""Add a task to the queue."""
task_id = f"task_{self.next_id}"
self.next_id += 1
task = Task(task_id, name, priority, data)
self.tasks[task_id] = task
return task
def get(self, task_id: str) -> Task | None:
"""Get task by ID."""
return self.tasks.get(task_id)
def next_pending(self) -> Task | None:
"""Get next pending task by priority."""
pending = [t for t in self.tasks.values() if t.status == TaskStatus.PENDING]
if not pending:
return None
# Sort by priority (higher first), then by creation time
pending.sort(key=lambda t: (-t.priority, t.created_at))
return pending[0]
def start(self, task_id: str) -> bool:
"""Mark task as running."""
task = self.get(task_id)
if not task or task.status != TaskStatus.PENDING:
return False
task.status = TaskStatus.RUNNING
task.started_at = datetime.now()
return True
def complete(self, task_id: str, result: str | None = None) -> bool:
"""Mark task as completed."""
task = self.get(task_id)
if not task or task.status != TaskStatus.RUNNING:
return False
task.status = TaskStatus.COMPLETED
task.completed_at = datetime.now()
task.result = result
return True
def fail(self, task_id: str, error: str) -> bool:
"""Mark task as failed."""
task = self.get(task_id)
if not task or task.status != TaskStatus.RUNNING:
return False
task.status = TaskStatus.FAILED
task.completed_at = datetime.now()
task.error = error
return True
def list_by_status(self, status: TaskStatus | None = None) -> list[Task]:
"""List tasks, optionally filtered by status."""
if status is None:
return list(self.tasks.values())
return [t for t in self.tasks.values() if t.status == status]
def count_by_status(self) -> dict[str, int]:
"""Count tasks by status."""
counts = {s.value: 0 for s in TaskStatus}
for task in self.tasks.values():
counts[task.status.value] += 1
return counts
def clear_completed(self) -> int:
"""Remove completed and failed tasks."""
to_remove = [
t.task_id
for t in self.tasks.values()
if t.status in (TaskStatus.COMPLETED, TaskStatus.FAILED)
]
for task_id in to_remove:
del self.tasks[task_id]
return len(to_remove)
def to_dict(self) -> dict:
"""Export queue to dictionary."""
return {
"next_id": self.next_id,
"tasks": [t.to_dict() for t in self.tasks.values()],
}
@classmethod
def from_dict(cls, data: dict) -> "TaskQueue":
"""Import queue from dictionary."""
queue = cls()
queue.next_id = data.get("next_id", 1)
for task_data in data.get("tasks", []):
task = Task.from_dict(task_data)
queue.tasks[task.task_id] = task
return queue
def main() -> int:
parser = argparse.ArgumentParser(description="Task queue management")
subparsers = parser.add_subparsers(dest="command", help="Command")
# Add command
add_parser = subparsers.add_parser("add", help="Add a task")
add_parser.add_argument("name", help="Task name")
add_parser.add_argument(
"-p", "--priority", type=int, default=0, help="Task priority (higher = more urgent)"
)
add_parser.add_argument("-d", "--data", help="Task data (JSON)")
# List command
list_parser = subparsers.add_parser("list", help="List tasks")
list_parser.add_argument(
"--status", choices=["pending", "running", "completed", "failed"], help="Filter by status"
)
# Next command
subparsers.add_parser("next", help="Get next pending task")
# Start command
start_parser = subparsers.add_parser("start", help="Start a task")
start_parser.add_argument("task_id", help="Task ID")
# Complete command
complete_parser = subparsers.add_parser("complete", help="Complete a task")
complete_parser.add_argument("task_id", help="Task ID")
complete_parser.add_argument("--result", help="Task result")
# Fail command
fail_parser = subparsers.add_parser("fail", help="Fail a task")
fail_parser.add_argument("task_id", help="Task ID")
fail_parser.add_argument("error", help="Error message")
# Status command
subparsers.add_parser("status", help="Show queue status")
# Clear command
subparsers.add_parser("clear", help="Clear completed tasks")
parser.add_argument("-f", "--file", default="queue.json", help="Queue file")
args = parser.parse_args()
# Load queue
try:
with open(args.file) as f:
queue = TaskQueue.from_dict(json.load(f))
except FileNotFoundError:
queue = TaskQueue()
def save_queue():
with open(args.file, "w") as f:
json.dump(queue.to_dict(), f, indent=2)
# Execute command
if args.command == "add":
data = json.loads(args.data) if args.data else None
task = queue.add(args.name, args.priority, data)
save_queue()
print(f"Created {task.task_id}: {task.name}")
elif args.command == "list":
status = TaskStatus(args.status) if args.status else None
tasks = queue.list_by_status(status)
if not tasks:
print("No tasks")
else:
for task in tasks:
print(
f"{task.task_id}: {task.name} [{task.status.value}] (priority: {task.priority})"
)
elif args.command == "next":
task = queue.next_pending()
if task:
print(f"{task.task_id}: {task.name}")
print(json.dumps(task.to_dict(), indent=2))
else:
print("No pending tasks")
elif args.command == "start":
if queue.start(args.task_id):
save_queue()
print(f"Started {args.task_id}")
else:
print(f"Cannot start {args.task_id}", file=sys.stderr)
return 1
elif args.command == "complete":
if queue.complete(args.task_id, args.result):
save_queue()
print(f"Completed {args.task_id}")
else:
print(f"Cannot complete {args.task_id}", file=sys.stderr)
return 1
elif args.command == "fail":
if queue.fail(args.task_id, args.error):
save_queue()
print(f"Failed {args.task_id}: {args.error}")
else:
print(f"Cannot fail {args.task_id}", file=sys.stderr)
return 1
elif args.command == "status":
counts = queue.count_by_status()
total = sum(counts.values())
print(f"Total: {total} tasks")
for status, count in counts.items():
print(f" {status}: {count}")
elif args.command == "clear":
removed = queue.clear_completed()
save_queue()
print(f"Removed {removed} tasks")
else:
parser.print_help()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
task_queue
| 309
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 1524..1530, value: Str("Task"), kind: None })
|
|
example_task_queue
|
test_queue_cli.py
|
"""Tests for queue_cli.py"""
from queue_cli import Task, TaskQueue, TaskStatus
class TestTask:
def test_create(self):
task = Task("task_1", "Test Task", priority=5)
assert task.task_id == "task_1"
assert task.name == "Test Task"
assert task.priority == 5
assert task.status == TaskStatus.PENDING
def test_to_dict(self):
task = Task("task_1", "Test", priority=3, data={"key": "value"})
d = task.to_dict()
assert d["task_id"] == "task_1"
assert d["name"] == "Test"
assert d["priority"] == 3
assert d["data"] == {"key": "value"}
assert d["status"] == "pending"
def test_from_dict(self):
d = {
"task_id": "task_1",
"name": "Test",
"priority": 3,
"status": "running",
}
task = Task.from_dict(d)
assert task.task_id == "task_1"
assert task.status == TaskStatus.RUNNING
class TestTaskQueue:
def test_add(self):
queue = TaskQueue()
task = queue.add("Test Task", priority=5)
assert task.task_id == "task_1"
assert task.name == "Test Task"
assert len(queue.tasks) == 1
def test_get(self):
queue = TaskQueue()
task = queue.add("Test")
result = queue.get(task.task_id)
assert result == task
def test_get_missing(self):
queue = TaskQueue()
assert queue.get("nonexistent") is None
def test_next_pending(self):
queue = TaskQueue()
queue.add("Low", priority=1)
queue.add("High", priority=10)
queue.add("Medium", priority=5)
task = queue.next_pending()
assert task.name == "High"
def test_next_pending_empty(self):
queue = TaskQueue()
assert queue.next_pending() is None
def test_next_pending_by_time(self):
queue = TaskQueue()
task1 = queue.add("First", priority=5)
queue.add("Second", priority=5)
# Same priority, should return first by time
task = queue.next_pending()
assert task.task_id == task1.task_id
def test_start(self):
queue = TaskQueue()
task = queue.add("Test")
assert queue.start(task.task_id) is True
assert task.status == TaskStatus.RUNNING
assert task.started_at is not None
def test_start_invalid(self):
queue = TaskQueue()
assert queue.start("nonexistent") is False
def test_complete(self):
queue = TaskQueue()
task = queue.add("Test")
queue.start(task.task_id)
assert queue.complete(task.task_id, "done") is True
assert task.status == TaskStatus.COMPLETED
assert task.result == "done"
def test_complete_not_running(self):
queue = TaskQueue()
task = queue.add("Test")
# Can't complete without starting
assert queue.complete(task.task_id) is False
def test_fail(self):
queue = TaskQueue()
task = queue.add("Test")
queue.start(task.task_id)
assert queue.fail(task.task_id, "error message") is True
assert task.status == TaskStatus.FAILED
assert task.error == "error message"
def test_list_by_status(self):
queue = TaskQueue()
task1 = queue.add("Task 1")
task2 = queue.add("Task 2")
queue.start(task2.task_id)
pending = queue.list_by_status(TaskStatus.PENDING)
assert len(pending) == 1
assert pending[0].task_id == task1.task_id
running = queue.list_by_status(TaskStatus.RUNNING)
assert len(running) == 1
def test_list_all(self):
queue = TaskQueue()
queue.add("Task 1")
queue.add("Task 2")
all_tasks = queue.list_by_status()
assert len(all_tasks) == 2
def test_count_by_status(self):
queue = TaskQueue()
queue.add("Task 1")
task2 = queue.add("Task 2")
queue.start(task2.task_id)
counts = queue.count_by_status()
assert counts["pending"] == 1
assert counts["running"] == 1
assert counts["completed"] == 0
def test_clear_completed(self):
queue = TaskQueue()
task1 = queue.add("Task 1")
task2 = queue.add("Task 2")
queue.start(task1.task_id)
queue.complete(task1.task_id)
queue.start(task2.task_id)
queue.fail(task2.task_id, "error")
removed = queue.clear_completed()
assert removed == 2
assert len(queue.tasks) == 0
def test_to_from_dict(self):
queue = TaskQueue()
queue.add("Task 1", priority=5)
queue.add("Task 2", priority=3)
d = queue.to_dict()
restored = TaskQueue.from_dict(d)
assert len(restored.tasks) == 2
assert restored.next_id == queue.next_id
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_task_queue/test_queue_cli.py (4842 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_task_queue/test_queue_cli.rs (7488 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 93.6 KB/s
⏱️ Total time: 50ms
| true
|
task_queue
| 163
| 5
|
[
"class_definition"
] | 0.612
| null |
example_tempfile
|
temp_tool.py
|
#!/usr/bin/env python3
"""Tempfile Example - Temporary file handling CLI."""
import argparse
import tempfile
def cmd_create(args):
"""Create temp file. Depyler: proven to terminate"""
suffix = args.suffix or ".tmp"
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=suffix) as f:
f.write(args.content)
print(f"Created: {f.name}")
def cmd_mkdir(args):
"""Create temp directory. Depyler: proven to terminate"""
d = tempfile.mkdtemp()
print(f"Directory: {d}")
def main():
parser = argparse.ArgumentParser(description="Temp file tool")
subparsers = parser.add_subparsers(dest="command", required=True)
create = subparsers.add_parser("create")
create.add_argument("--content", required=True)
create.add_argument("--suffix")
subparsers.add_parser("mkdir")
args = parser.parse_args()
if args.command == "create":
cmd_create(args)
elif args.command == "mkdir":
cmd_mkdir(args)
if __name__ == "__main__":
main()
| false
|
tempfile
| 40
| 0
|
[
"context_manager"
] | 0.652
|
Type inference hints:
Hint: str for variable 'd' [Medium] (usage patterns suggest this type)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 51
Total estimated allocations: 0
Functions analyzed: 3
Hot Paths
[1] main (64.7% of execution time)
[2] cmd_mkdir (25.5% of execution time)
Function Metrics
🔥 main 64.7% time | 33 inst | 0 alloc
🔥 cmd_mkdir 25.5% time | 13
|
|
example_tempfile
|
test_temp_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for tempfile CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "temp_tool.py"
SCRIPT = "temp_tool.py"
def run(args):
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
cwd=__file__.rsplit("/", 1)[0])
class TestTempFile:
def test_create_temp(self):
result = run(["create", "--content", "hello"])
assert result.returncode == 0
assert "Created:" in result.stdout
def test_create_with_suffix(self):
result = run(["create", "--content", "test", "--suffix", ".log"])
assert result.returncode == 0
assert ".log" in result.stdout
class TestTempDir:
def test_create_tempdir(self):
result = run(["mkdir"])
assert result.returncode == 0
assert "Directory:" 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_tempfile/test_temp_tool.py (1006 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_tempfile/test_temp_tool.rs (2574 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_tempfile/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 20.1 KB/s
⏱️ Total time: 49ms
| true
|
tempfile
| 34
| 6
|
[
"class_definition"
] | 0.612
| null |
example_template_engine
|
template_cli.py
|
#!/usr/bin/env python3
"""Template Engine CLI.
Simple template engine with variable substitution, loops, and conditionals.
"""
import argparse
import json
import sys
from dataclasses import dataclass
from enum import Enum, auto
class TokenType(Enum):
"""Token types."""
TEXT = auto()
VAR_OPEN = auto()
VAR_CLOSE = auto()
BLOCK_OPEN = auto()
BLOCK_CLOSE = auto()
IDENTIFIER = auto()
DOT = auto()
PIPE = auto()
STRING = auto()
@dataclass
class Token:
"""Lexer token."""
type: TokenType
value: str
def tokenize(template: str) -> list[Token]:
"""Tokenize template string."""
tokens = []
i = 0
while i < len(template):
# Variable {{ }}
if template[i : i + 2] == "{{":
tokens.append(Token(TokenType.VAR_OPEN, "{{"))
i += 2
# Skip whitespace
while i < len(template) and template[i].isspace():
i += 1
# Read identifier or expression
while i < len(template) and template[i : i + 2] != "}}":
if template[i].isalnum() or template[i] == "_":
start = i
while i < len(template) and (template[i].isalnum() or template[i] == "_"):
i += 1
tokens.append(Token(TokenType.IDENTIFIER, template[start:i]))
elif template[i] == ".":
tokens.append(Token(TokenType.DOT, "."))
i += 1
elif template[i] == "|":
tokens.append(Token(TokenType.PIPE, "|"))
i += 1
elif template[i].isspace():
i += 1
else:
i += 1
if template[i : i + 2] == "}}":
tokens.append(Token(TokenType.VAR_CLOSE, "}}"))
i += 2
# Block {% %}
elif template[i : i + 2] == "{%":
tokens.append(Token(TokenType.BLOCK_OPEN, "{%"))
i += 2
# Skip whitespace
while i < len(template) and template[i].isspace():
i += 1
# Read block content
while i < len(template) and template[i : i + 2] != "%}":
if template[i].isalnum() or template[i] == "_":
start = i
while i < len(template) and (template[i].isalnum() or template[i] == "_"):
i += 1
tokens.append(Token(TokenType.IDENTIFIER, template[start:i]))
elif template[i] == ".":
tokens.append(Token(TokenType.DOT, "."))
i += 1
elif template[i] == '"' or template[i] == "'":
quote = template[i]
i += 1
start = i
while i < len(template) and template[i] != quote:
i += 1
tokens.append(Token(TokenType.STRING, template[start:i]))
i += 1
elif template[i].isspace():
i += 1
else:
i += 1
if template[i : i + 2] == "%}":
tokens.append(Token(TokenType.BLOCK_CLOSE, "%}"))
i += 2
# Regular text
else:
start = i
while i < len(template) and template[i : i + 2] not in ("{{", "{%"):
i += 1
if i > start:
tokens.append(Token(TokenType.TEXT, template[start:i]))
return tokens
def resolve_var(name: str, context: dict) -> any:
"""Resolve variable from context."""
parts = name.split(".")
value = context
for part in parts:
if isinstance(value, dict) and part in value:
value = value[part]
elif isinstance(value, list) and part.isdigit():
value = value[int(part)]
else:
return None
return value
def apply_filter(value: any, filter_name: str) -> str:
"""Apply filter to value."""
if filter_name == "upper":
return str(value).upper()
if filter_name == "lower":
return str(value).lower()
if filter_name == "title":
return str(value).title()
if filter_name == "strip":
return str(value).strip()
if filter_name == "length":
return str(len(value) if hasattr(value, "__len__") else 0)
if filter_name == "reverse":
if isinstance(value, str):
return value[::-1]
if isinstance(value, list):
return list(reversed(value))
if filter_name == "first":
if isinstance(value, (list, str)) and len(value) > 0:
return value[0]
if filter_name == "last":
if isinstance(value, (list, str)) and len(value) > 0:
return value[-1]
if filter_name == "default":
return value if value else ""
if filter_name == "join":
if isinstance(value, list):
return ", ".join(str(v) for v in value)
return str(value)
def render(template: str, context: dict) -> str:
"""Render template with context."""
tokens = tokenize(template)
result = []
i = 0
while i < len(tokens):
token = tokens[i]
if token.type == TokenType.TEXT:
result.append(token.value)
i += 1
elif token.type == TokenType.VAR_OPEN:
i += 1
var_name = ""
filters = []
while i < len(tokens) and tokens[i].type != TokenType.VAR_CLOSE:
if tokens[i].type == TokenType.IDENTIFIER:
if not var_name:
var_name = tokens[i].value
elif filters:
pass # Filter argument, ignore for now
else:
var_name = tokens[i].value
elif tokens[i].type == TokenType.DOT:
i += 1
if i < len(tokens) and tokens[i].type == TokenType.IDENTIFIER:
var_name += "." + tokens[i].value
elif tokens[i].type == TokenType.PIPE:
i += 1
if i < len(tokens) and tokens[i].type == TokenType.IDENTIFIER:
filters.append(tokens[i].value)
i += 1
value = resolve_var(var_name, context)
for f in filters:
value = apply_filter(value, f)
result.append(str(value) if value is not None else "")
if i < len(tokens) and tokens[i].type == TokenType.VAR_CLOSE:
i += 1
elif token.type == TokenType.BLOCK_OPEN:
i += 1
block_type = None
block_var = None
block_iterable = None
while i < len(tokens) and tokens[i].type != TokenType.BLOCK_CLOSE:
if tokens[i].type == TokenType.IDENTIFIER:
if block_type is None:
block_type = tokens[i].value
elif block_type == "for" and block_var is None:
block_var = tokens[i].value
elif block_type == "for" and tokens[i].value == "in":
pass
elif block_type == "for":
block_iterable = tokens[i].value
elif block_type == "if" and block_var is None:
block_var = tokens[i].value
i += 1
if i < len(tokens) and tokens[i].type == TokenType.BLOCK_CLOSE:
i += 1
if block_type == "for" and block_var and block_iterable:
# Find endfor
depth = 1
body_start = i
while i < len(tokens) and depth > 0:
if tokens[i].type == TokenType.BLOCK_OPEN:
# Check for for/endfor
j = i + 1
while j < len(tokens) and tokens[j].type != TokenType.BLOCK_CLOSE:
if tokens[j].type == TokenType.IDENTIFIER:
if tokens[j].value == "for":
depth += 1
elif tokens[j].value == "endfor":
depth -= 1
break
j += 1
i += 1
body_end = i - 1
# Find the actual endfor position
while body_end > body_start:
if tokens[body_end].type == TokenType.BLOCK_OPEN:
break
body_end -= 1
# Render body for each item
items = resolve_var(block_iterable, context)
if isinstance(items, (list, tuple)):
for item in items:
loop_context = context.copy()
loop_context[block_var] = item
body_tokens = tokens[body_start:body_end]
body_template = reconstruct_template(body_tokens)
result.append(render(body_template, loop_context))
elif block_type == "if" and block_var:
# Find endif
depth = 1
body_start = i
while i < len(tokens) and depth > 0:
if tokens[i].type == TokenType.BLOCK_OPEN:
j = i + 1
while j < len(tokens) and tokens[j].type != TokenType.BLOCK_CLOSE:
if tokens[j].type == TokenType.IDENTIFIER:
if tokens[j].value == "if":
depth += 1
elif tokens[j].value == "endif":
depth -= 1
break
j += 1
i += 1
body_end = i - 1
while body_end > body_start:
if tokens[body_end].type == TokenType.BLOCK_OPEN:
break
body_end -= 1
# Evaluate condition
value = resolve_var(block_var, context)
if value:
body_tokens = tokens[body_start:body_end]
body_template = reconstruct_template(body_tokens)
result.append(render(body_template, context))
elif block_type in ("endfor", "endif"):
pass
else:
i += 1
return "".join(result)
def reconstruct_template(tokens: list[Token]) -> str:
"""Reconstruct template string from tokens."""
result = []
i = 0
while i < len(tokens):
token = tokens[i]
if token.type == TokenType.TEXT:
result.append(token.value)
elif token.type == TokenType.VAR_OPEN:
result.append("{{ ")
i += 1
while i < len(tokens) and tokens[i].type != TokenType.VAR_CLOSE:
if tokens[i].type == TokenType.IDENTIFIER:
result.append(tokens[i].value)
elif tokens[i].type == TokenType.DOT:
result.append(".")
elif tokens[i].type == TokenType.PIPE:
result.append(" | ")
i += 1
result.append(" }}")
elif token.type == TokenType.BLOCK_OPEN:
result.append("{% ")
i += 1
while i < len(tokens) and tokens[i].type != TokenType.BLOCK_CLOSE:
if tokens[i].type == TokenType.IDENTIFIER:
result.append(tokens[i].value + " ")
i += 1
result.append("%}")
i += 1
return "".join(result)
def main() -> int:
parser = argparse.ArgumentParser(description="Template engine")
parser.add_argument("--template", "-t", help="Template string")
parser.add_argument("--file", "-f", help="Template file")
parser.add_argument("--context", "-c", help="JSON context")
parser.add_argument("--context-file", help="JSON context file")
args = parser.parse_args()
# Load template
if args.file:
with open(args.file) as f:
template = f.read()
elif args.template:
template = args.template
else:
template = sys.stdin.read()
# Load context
if args.context_file:
with open(args.context_file) as f:
context = json.load(f)
elif args.context:
context = json.loads(args.context)
else:
context = {}
result = render(template, context)
print(result)
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_template_engine/template_cli.py (12791 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_template_engine/template_cli.rs (55504 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_template_engine/Cargo.toml (3 dependencies)
⏱️ Parse time: 81ms
📊 Throughput: 153.0 KB/s
⏱️ Total time: 81ms
| true
|
template_engine
| 380
| 6
|
[
"context_manager",
"class_definition",
"stdin_usage",
"decorator"
] | 0.652
| null |
example_template_engine
|
test_template_cli.py
|
"""Tests for template_cli.py"""
from template_cli import (
TokenType,
apply_filter,
render,
resolve_var,
tokenize,
)
class TestTokenize:
def test_plain_text(self):
tokens = tokenize("Hello World")
assert len(tokens) == 1
assert tokens[0].type == TokenType.TEXT
assert tokens[0].value == "Hello World"
def test_variable(self):
tokens = tokenize("{{ name }}")
assert tokens[0].type == TokenType.VAR_OPEN
assert tokens[1].type == TokenType.IDENTIFIER
assert tokens[1].value == "name"
assert tokens[2].type == TokenType.VAR_CLOSE
def test_variable_with_dot(self):
tokens = tokenize("{{ user.name }}")
types = [t.type for t in tokens]
assert TokenType.VAR_OPEN in types
assert TokenType.IDENTIFIER in types
assert TokenType.DOT in types
assert TokenType.VAR_CLOSE in types
def test_variable_with_filter(self):
tokens = tokenize("{{ name | upper }}")
types = [t.type for t in tokens]
assert TokenType.PIPE in types
def test_block(self):
tokens = tokenize("{% for item in items %}")
assert tokens[0].type == TokenType.BLOCK_OPEN
identifiers = [t.value for t in tokens if t.type == TokenType.IDENTIFIER]
assert "for" in identifiers
assert "item" in identifiers
assert "in" in identifiers
assert "items" in identifiers
def test_mixed_content(self):
tokens = tokenize("Hello {{ name }}!")
types = [t.type for t in tokens]
assert TokenType.TEXT in types
assert TokenType.VAR_OPEN in types
class TestResolveVar:
def test_simple(self):
ctx = {"name": "Alice"}
assert resolve_var("name", ctx) == "Alice"
def test_nested(self):
ctx = {"user": {"name": "Bob"}}
assert resolve_var("user.name", ctx) == "Bob"
def test_deeply_nested(self):
ctx = {"a": {"b": {"c": "deep"}}}
assert resolve_var("a.b.c", ctx) == "deep"
def test_list_index(self):
ctx = {"items": ["a", "b", "c"]}
assert resolve_var("items.0", ctx) == "a"
assert resolve_var("items.2", ctx) == "c"
def test_missing(self):
ctx = {"name": "Alice"}
assert resolve_var("age", ctx) is None
def test_missing_nested(self):
ctx = {"user": {}}
assert resolve_var("user.name", ctx) is None
class TestApplyFilter:
def test_upper(self):
assert apply_filter("hello", "upper") == "HELLO"
def test_lower(self):
assert apply_filter("HELLO", "lower") == "hello"
def test_title(self):
assert apply_filter("hello world", "title") == "Hello World"
def test_strip(self):
assert apply_filter(" hello ", "strip") == "hello"
def test_length_string(self):
assert apply_filter("hello", "length") == "5"
def test_length_list(self):
assert apply_filter([1, 2, 3], "length") == "3"
def test_reverse_string(self):
assert apply_filter("hello", "reverse") == "olleh"
def test_reverse_list(self):
assert apply_filter([1, 2, 3], "reverse") == [3, 2, 1]
def test_first(self):
assert apply_filter([1, 2, 3], "first") == 1
assert apply_filter("hello", "first") == "h"
def test_last(self):
assert apply_filter([1, 2, 3], "last") == 3
assert apply_filter("hello", "last") == "o"
def test_join(self):
assert apply_filter(["a", "b", "c"], "join") == "a, b, c"
def test_default_with_value(self):
assert apply_filter("hello", "default") == "hello"
def test_default_empty(self):
assert apply_filter("", "default") == ""
def test_unknown_filter(self):
assert apply_filter("hello", "unknown") == "hello"
class TestRenderVariables:
def test_simple_variable(self):
result = render("Hello {{ name }}!", {"name": "World"})
assert result == "Hello World!"
def test_multiple_variables(self):
result = render("{{ greeting }} {{ name }}!", {"greeting": "Hello", "name": "World"})
assert result == "Hello World!"
def test_nested_variable(self):
result = render("Hello {{ user.name }}!", {"user": {"name": "Alice"}})
assert result == "Hello Alice!"
def test_missing_variable(self):
result = render("Hello {{ name }}!", {})
assert result == "Hello !"
def test_variable_with_filter(self):
result = render("Hello {{ name | upper }}!", {"name": "world"})
assert result == "Hello WORLD!"
def test_multiple_filters(self):
result = render("{{ name | strip | upper }}", {"name": " hello "})
assert result == "HELLO"
class TestRenderForLoop:
def test_simple_loop(self):
template = "{% for item in items %}{{ item }}{% endfor %}"
result = render(template, {"items": ["a", "b", "c"]})
assert result == "abc"
def test_loop_with_text(self):
template = "Items: {% for item in items %}[{{ item }}]{% endfor %}"
result = render(template, {"items": ["x", "y"]})
assert result == "Items: [x][y]"
def test_empty_loop(self):
template = "{% for item in items %}{{ item }}{% endfor %}"
result = render(template, {"items": []})
assert result == ""
def test_nested_loop_context(self):
template = "{% for user in users %}{{ user.name }}{% endfor %}"
result = render(template, {"users": [{"name": "Alice"}, {"name": "Bob"}]})
assert result == "AliceBob"
class TestRenderConditional:
def test_true_condition(self):
template = "{% if show %}Visible{% endif %}"
result = render(template, {"show": True})
assert result == "Visible"
def test_false_condition(self):
template = "{% if show %}Visible{% endif %}"
result = render(template, {"show": False})
assert result == ""
def test_missing_condition(self):
template = "{% if show %}Visible{% endif %}"
result = render(template, {})
assert result == ""
def test_truthy_string(self):
template = "{% if name %}Hello {{ name }}{% endif %}"
result = render(template, {"name": "World"})
assert result == "Hello World"
def test_truthy_list(self):
template = "{% if items %}Has items{% endif %}"
result = render(template, {"items": [1, 2, 3]})
assert result == "Has items"
class TestRenderComplex:
def test_mixed_content(self):
template = """
Hello {{ name }}!
{% if items %}Your items:
{% for item in items %}- {{ item }}
{% endfor %}{% endif %}"""
result = render(template, {"name": "User", "items": ["Apple", "Banana"]})
assert "Hello User!" in result
assert "Apple" in result
assert "Banana" in result
def test_no_template_tags(self):
template = "Plain text without any tags"
result = render(template, {"ignored": "value"})
assert result == "Plain text without any tags"
def test_adjacent_variables(self):
template = "{{ a }}{{ b }}{{ c }}"
result = render(template, {"a": "1", "b": "2", "c": "3"})
assert result == "123"
class TestEdgeCases:
def test_empty_template(self):
result = render("", {})
assert result == ""
def test_empty_context(self):
result = render("Static content", {})
assert result == "Static content"
def test_whitespace_in_tags(self):
result = render("{{ name }}", {"name": "test"})
assert result == "test"
def test_numeric_values(self):
result = render("Count: {{ count }}", {"count": 42})
assert result == "Count: 42"
def test_none_value(self):
result = render("Value: {{ value }}", {"value": None})
assert result == "Value: "
class TestFilterChaining:
def test_chain_strip_upper(self):
result = render("{{ text | strip | upper }}", {"text": " hello "})
assert result == "HELLO"
def test_chain_strip_lower(self):
result = render("{{ text | strip | lower }}", {"text": " HELLO "})
assert result == "hello"
def test_length_after_strip(self):
result = render("{{ text | strip | length }}", {"text": " abc "})
assert result == "3"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_template_engine/test_template_cli.py (8346 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_template_engine/test_template_cli.rs (19299 bytes)
⏱️ Parse time: 57ms
📊 Throughput: 140.9 KB/s
⏱️ Total time: 58ms
| true
|
template_engine
| 259
| 5
|
[
"class_definition"
] | 0.612
| null |
example_text_parse
|
test_text_parse_cli.py
|
"""Tests for text_parse_cli.py"""
from text_parse_cli import (
capitalize,
casefold,
center,
char_at,
char_count,
char_frequency,
contains,
count,
decode_utf8,
encode_utf8,
endswith,
expandtabs,
find,
index,
is_alnum,
is_alpha,
is_decimal,
is_digit,
is_identifier,
is_lower,
is_numeric,
is_printable,
is_space,
is_title,
is_upper,
join_by,
join_lines,
join_words,
length,
line_count,
ljust,
lower,
partition,
remove_prefix,
remove_suffix,
replace,
replace_first,
reverse,
rfind,
rjust,
rpartition,
split_by,
split_chars,
split_lines,
split_words,
startswith,
strip,
strip_chars,
strip_left,
strip_right,
substring,
swapcase,
title,
upper,
word_count,
word_frequency,
)
class TestSplit:
def test_split_lines(self):
text = "line1\nline2\nline3"
assert split_lines(text) == ["line1", "line2", "line3"]
def test_split_words(self):
text = "hello world test"
assert split_words(text) == ["hello", "world", "test"]
def test_split_by(self):
text = "a,b,c"
assert split_by(text, ",") == ["a", "b", "c"]
def test_split_chars(self):
text = "abc"
assert split_chars(text) == ["a", "b", "c"]
class TestJoin:
def test_join_lines(self):
lines = ["a", "b", "c"]
assert join_lines(lines) == "a\nb\nc"
def test_join_words(self):
words = ["hello", "world"]
assert join_words(words) == "hello world"
def test_join_by(self):
items = ["a", "b", "c"]
assert join_by(items, ",") == "a,b,c"
class TestStrip:
def test_strip(self):
assert strip(" hello ") == "hello"
def test_strip_left(self):
assert strip_left(" hello ") == "hello "
def test_strip_right(self):
assert strip_right(" hello ") == " hello"
def test_strip_chars(self):
assert strip_chars("##hello##", "#") == "hello"
class TestCase:
def test_upper(self):
assert upper("hello") == "HELLO"
def test_lower(self):
assert lower("HELLO") == "hello"
def test_title(self):
assert title("hello world") == "Hello World"
def test_capitalize(self):
assert capitalize("hello") == "Hello"
def test_swapcase(self):
assert swapcase("Hello") == "hELLO"
def test_casefold(self):
assert casefold("HELLO") == "hello"
class TestReplace:
def test_replace(self):
assert replace("hello world", "world", "there") == "hello there"
def test_replace_first(self):
assert replace_first("a a a", "a", "b") == "b a a"
class TestSearch:
def test_startswith(self):
assert startswith("hello", "he") is True
assert startswith("hello", "wo") is False
def test_endswith(self):
assert endswith("hello", "lo") is True
assert endswith("hello", "he") is False
def test_contains(self):
assert contains("hello world", "wor") is True
assert contains("hello world", "xyz") is False
def test_count(self):
assert count("hello hello", "hello") == 2
def test_find(self):
assert find("hello", "l") == 2
assert find("hello", "x") == -1
def test_rfind(self):
assert rfind("hello", "l") == 3
def test_index(self):
assert index("hello", "l") == 2
class TestIs:
def test_is_alpha(self):
assert is_alpha("hello") is True
assert is_alpha("hello1") is False
def test_is_digit(self):
assert is_digit("123") is True
assert is_digit("12a") is False
def test_is_alnum(self):
assert is_alnum("hello123") is True
assert is_alnum("hello 123") is False
def test_is_space(self):
assert is_space(" ") is True
assert is_space(" a") is False
def test_is_upper(self):
assert is_upper("HELLO") is True
assert is_upper("Hello") is False
def test_is_lower(self):
assert is_lower("hello") is True
assert is_lower("Hello") is False
def test_is_title(self):
assert is_title("Hello World") is True
assert is_title("hello world") is False
def test_is_numeric(self):
assert is_numeric("123") is True
def test_is_decimal(self):
assert is_decimal("123") is True
def test_is_identifier(self):
assert is_identifier("hello") is True
assert is_identifier("123") is False
def test_is_printable(self):
assert is_printable("hello") is True
class TestLength:
def test_length(self):
assert length("hello") == 5
class TestReverse:
def test_reverse(self):
assert reverse("hello") == "olleh"
class TestCharAt:
def test_char_at(self):
assert char_at("hello", 0) == "h"
assert char_at("hello", 10) == ""
class TestSubstring:
def test_substring(self):
assert substring("hello world", 0, 5) == "hello"
class TestRemovePrefix:
def test_remove_prefix(self):
assert remove_prefix("hello world", "hello ") == "world"
assert remove_prefix("hello", "bye") == "hello"
class TestRemoveSuffix:
def test_remove_suffix(self):
assert remove_suffix("hello.txt", ".txt") == "hello"
assert remove_suffix("hello", ".txt") == "hello"
class TestJustify:
def test_center(self):
assert center("hi", 6) == " hi "
def test_ljust(self):
assert ljust("hi", 5) == "hi "
def test_rjust(self):
assert rjust("hi", 5) == " hi"
class TestPartition:
def test_partition(self):
result = partition("hello=world", "=")
assert result == ("hello", "=", "world")
def test_rpartition(self):
result = rpartition("a=b=c", "=")
assert result == ("a=b", "=", "c")
class TestExpandtabs:
def test_expandtabs(self):
result = expandtabs("a\tb", 4)
assert result == "a b"
class TestEncodeDecode:
def test_encode_decode(self):
text = "hello"
encoded = encode_utf8(text)
assert isinstance(encoded, bytes)
assert decode_utf8(encoded) == text
class TestWordLineCount:
def test_word_count(self):
assert word_count("hello world test") == 3
def test_line_count(self):
assert line_count("a\nb\nc") == 3
class TestCharCount:
def test_char_count_with_spaces(self):
assert char_count("hello world") == 11
def test_char_count_without_spaces(self):
assert char_count("hello world", include_spaces=False) == 10
class TestFrequency:
def test_char_frequency(self):
freq = char_frequency("aab")
assert freq == {"a": 2, "b": 1}
def test_word_frequency(self):
freq = word_frequency("hello hello world")
assert freq == {"hello": 2, "world": 1}
class TestEdgeCases:
def test_empty_string(self):
assert split_words("") == []
assert length("") == 0
assert reverse("") == ""
def test_single_char(self):
assert reverse("a") == "a"
assert upper("a") == "A"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_text_parse/test_text_parse_cli.py (7204 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_text_parse/test_text_parse_cli.rs (26293 bytes)
⏱️ Parse time: 53ms
📊 Throughput: 130.7 KB/s
⏱️ Total time: 54ms
| true
|
text_parse
| 309
| 5
|
[
"class_definition"
] | 0.612
| null |
example_text_parse
|
text_parse_cli.py
|
#!/usr/bin/env python3
"""Text Parse CLI.
Text parsing and manipulation operations.
"""
import argparse
import sys
def split_lines(text: str) -> list[str]:
"""Split text into lines."""
return text.splitlines()
def split_words(text: str) -> list[str]:
"""Split text into words."""
return text.split()
def split_by(text: str, delimiter: str) -> list[str]:
"""Split text by delimiter."""
return text.split(delimiter)
def split_chars(text: str) -> list[str]:
"""Split text into characters."""
return list(text)
def join_lines(lines: list[str]) -> str:
"""Join lines with newline."""
return "\n".join(lines)
def join_words(words: list[str]) -> str:
"""Join words with space."""
return " ".join(words)
def join_by(items: list[str], delimiter: str) -> str:
"""Join items with delimiter."""
return delimiter.join(items)
def strip(text: str) -> str:
"""Strip leading/trailing whitespace."""
return text.strip()
def strip_left(text: str) -> str:
"""Strip leading whitespace."""
return text.lstrip()
def strip_right(text: str) -> str:
"""Strip trailing whitespace."""
return text.rstrip()
def strip_chars(text: str, chars: str) -> str:
"""Strip specific characters."""
return text.strip(chars)
def upper(text: str) -> str:
"""Convert to uppercase."""
return text.upper()
def lower(text: str) -> str:
"""Convert to lowercase."""
return text.lower()
def title(text: str) -> str:
"""Convert to title case."""
return text.title()
def capitalize(text: str) -> str:
"""Capitalize first character."""
return text.capitalize()
def swapcase(text: str) -> str:
"""Swap case of characters."""
return text.swapcase()
def casefold(text: str) -> str:
"""Aggressive lowercase for comparison."""
return text.casefold()
def replace(text: str, old: str, new: str) -> str:
"""Replace all occurrences."""
return text.replace(old, new)
def replace_first(text: str, old: str, new: str) -> str:
"""Replace first occurrence."""
return text.replace(old, new, 1)
def startswith(text: str, prefix: str) -> bool:
"""Check if starts with prefix."""
return text.startswith(prefix)
def endswith(text: str, suffix: str) -> bool:
"""Check if ends with suffix."""
return text.endswith(suffix)
def contains(text: str, substring: str) -> bool:
"""Check if contains substring."""
return substring in text
def count(text: str, substring: str) -> int:
"""Count occurrences of substring."""
return text.count(substring)
def find(text: str, substring: str) -> int:
"""Find first occurrence, -1 if not found."""
return text.find(substring)
def rfind(text: str, substring: str) -> int:
"""Find last occurrence, -1 if not found."""
return text.rfind(substring)
def index(text: str, substring: str) -> int:
"""Find first occurrence, raise if not found."""
return text.index(substring)
def is_alpha(text: str) -> bool:
"""Check if all alphabetic."""
return text.isalpha()
def is_digit(text: str) -> bool:
"""Check if all digits."""
return text.isdigit()
def is_alnum(text: str) -> bool:
"""Check if all alphanumeric."""
return text.isalnum()
def is_space(text: str) -> bool:
"""Check if all whitespace."""
return text.isspace()
def is_upper(text: str) -> bool:
"""Check if all uppercase."""
return text.isupper()
def is_lower(text: str) -> bool:
"""Check if all lowercase."""
return text.islower()
def is_title(text: str) -> bool:
"""Check if title case."""
return text.istitle()
def is_numeric(text: str) -> bool:
"""Check if numeric."""
return text.isnumeric()
def is_decimal(text: str) -> bool:
"""Check if decimal."""
return text.isdecimal()
def is_identifier(text: str) -> bool:
"""Check if valid identifier."""
return text.isidentifier()
def is_printable(text: str) -> bool:
"""Check if printable."""
return text.isprintable()
def length(text: str) -> int:
"""Get string length."""
return len(text)
def reverse(text: str) -> str:
"""Reverse string."""
return text[::-1]
def char_at(text: str, index: int) -> str:
"""Get character at index."""
if 0 <= index < len(text):
return text[index]
return ""
def substring(text: str, start: int, end: int) -> str:
"""Get substring."""
return text[start:end]
def remove_prefix(text: str, prefix: str) -> str:
"""Remove prefix if present."""
if text.startswith(prefix):
return text[len(prefix) :]
return text
def remove_suffix(text: str, suffix: str) -> str:
"""Remove suffix if present."""
if text.endswith(suffix):
return text[: -len(suffix)]
return text
def center(text: str, width: int) -> str:
"""Center string."""
return text.center(width)
def ljust(text: str, width: int) -> str:
"""Left justify string."""
return text.ljust(width)
def rjust(text: str, width: int) -> str:
"""Right justify string."""
return text.rjust(width)
def partition(text: str, sep: str) -> tuple[str, str, str]:
"""Partition on first separator."""
return text.partition(sep)
def rpartition(text: str, sep: str) -> tuple[str, str, str]:
"""Partition on last separator."""
return text.rpartition(sep)
def expandtabs(text: str, tabsize: int = 8) -> str:
"""Expand tabs to spaces."""
return text.expandtabs(tabsize)
def encode_utf8(text: str) -> bytes:
"""Encode as UTF-8."""
return text.encode("utf-8")
def decode_utf8(data: bytes) -> str:
"""Decode from UTF-8."""
return data.decode("utf-8")
def word_count(text: str) -> int:
"""Count words in text."""
return len(text.split())
def line_count(text: str) -> int:
"""Count lines in text."""
return len(text.splitlines())
def char_count(text: str, include_spaces: bool = True) -> int:
"""Count characters in text."""
if include_spaces:
return len(text)
return len(text.replace(" ", "").replace("\n", "").replace("\t", ""))
def char_frequency(text: str) -> dict[str, int]:
"""Get character frequency."""
freq: dict[str, int] = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
return freq
def word_frequency(text: str) -> dict[str, int]:
"""Get word frequency."""
freq: dict[str, int] = {}
for word in text.lower().split():
freq[word] = freq.get(word, 0) + 1
return freq
def main() -> int:
parser = argparse.ArgumentParser(description="Text parse CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# split
split_p = subparsers.add_parser("split", help="Split text")
split_p.add_argument("text", help="Text to split")
split_p.add_argument("-d", "--delimiter", help="Delimiter")
split_p.add_argument("--lines", action="store_true", help="Split by lines")
split_p.add_argument("--words", action="store_true", help="Split by words")
# join
join_p = subparsers.add_parser("join", help="Join items")
join_p.add_argument("items", nargs="+", help="Items to join")
join_p.add_argument("-d", "--delimiter", default=" ", help="Delimiter")
# case
case_p = subparsers.add_parser("case", help="Change case")
case_p.add_argument("text", help="Text")
case_p.add_argument("--upper", action="store_true")
case_p.add_argument("--lower", action="store_true")
case_p.add_argument("--title", action="store_true")
# count
count_p = subparsers.add_parser("count", help="Count in text")
count_p.add_argument("text", help="Text")
count_p.add_argument("--words", action="store_true")
count_p.add_argument("--lines", action="store_true")
count_p.add_argument("--chars", action="store_true")
# replace
replace_p = subparsers.add_parser("replace", help="Replace in text")
replace_p.add_argument("text", help="Text")
replace_p.add_argument("old", help="Old string")
replace_p.add_argument("new", help="New string")
args = parser.parse_args()
if args.command == "split":
if args.lines:
result = split_lines(args.text)
elif args.words:
result = split_words(args.text)
elif args.delimiter:
result = split_by(args.text, args.delimiter)
else:
result = split_words(args.text)
for item in result:
print(item)
elif args.command == "join":
result = join_by(args.items, args.delimiter)
print(result)
elif args.command == "case":
if args.upper:
print(upper(args.text))
elif args.lower:
print(lower(args.text))
elif args.title:
print(title(args.text))
else:
print(args.text)
elif args.command == "count":
if args.words:
print(f"Words: {word_count(args.text)}")
elif args.lines:
print(f"Lines: {line_count(args.text)}")
elif args.chars:
print(f"Characters: {char_count(args.text)}")
else:
print(f"Words: {word_count(args.text)}")
print(f"Lines: {line_count(args.text)}")
print(f"Characters: {char_count(args.text)}")
elif args.command == "replace":
result = replace(args.text, args.old, args.new)
print(result)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_text_parse/text_parse_cli.py (9522 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_text_parse/text_parse_cli.rs (23185 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_text_parse/Cargo.toml (1 dependencies)
⏱️ Parse time: 59ms
📊 Throughput: 155.8 KB/s
⏱️ Total time: 60ms
| true
|
text_parse
| 392
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_textwrap
|
test_wrap_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for textwrap CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "wrap_tool.py"
SCRIPT = "wrap_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 TestWrap:
def test_wrap_default(self):
result = run(["wrap"], "This is a long line that should be wrapped at the default width")
assert result.returncode == 0
def test_wrap_width(self):
result = run(["wrap", "--width", "20"], "This is a test of wrapping")
assert result.returncode == 0
class TestFill:
def test_fill(self):
result = run(["fill", "--width", "30"], "Short lines\nshould be\njoined together")
assert result.returncode == 0
class TestDedent:
def test_dedent(self):
result = run(["dedent"], " indented\n text")
assert result.returncode == 0
assert "indented" in result.stdout
class TestIndent:
def test_indent(self):
result = run(["indent", "--prefix", "> "], "line1\nline2")
assert result.returncode == 0
assert "> " 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_textwrap/test_wrap_tool.py (1370 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_textwrap/test_wrap_tool.rs (3308 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_textwrap/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 27.4 KB/s
⏱️ Total time: 49ms
| true
|
textwrap
| 43
| 6
|
[
"class_definition"
] | 0.612
| null |
example_textwrap
|
wrap_tool.py
|
#!/usr/bin/env python3
"""Textwrap Example - Text formatting CLI."""
import argparse
import sys
import textwrap
def cmd_wrap(args):
"""Wrap text. Depyler: proven to terminate"""
text = sys.stdin.read()
for line in textwrap.wrap(text, width=args.width):
print(line)
def cmd_fill(args):
"""Fill text. Depyler: proven to terminate"""
text = sys.stdin.read()
print(textwrap.fill(text, width=args.width))
def cmd_dedent(args):
"""Dedent text. Depyler: proven to terminate"""
text = sys.stdin.read()
print(textwrap.dedent(text))
def cmd_indent(args):
"""Indent text. Depyler: proven to terminate"""
text = sys.stdin.read()
print(textwrap.indent(text, args.prefix))
def main():
parser = argparse.ArgumentParser(description="Text wrapping tool")
subparsers = parser.add_subparsers(dest="command", required=True)
wrap = subparsers.add_parser("wrap")
wrap.add_argument("--width", type=int, default=70)
fill = subparsers.add_parser("fill")
fill.add_argument("--width", type=int, default=70)
subparsers.add_parser("dedent")
indent = subparsers.add_parser("indent")
indent.add_argument("--prefix", default=" ")
args = parser.parse_args()
{"wrap": cmd_wrap, "fill": cmd_fill, "dedent": cmd_dedent, "indent": cmd_indent}[args.command](
args
)
if __name__ == "__main__":
main()
| false
|
textwrap
| 56
| 0
|
[
"stdin_usage"
] | 0.566
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1242..1336, value: Dict(ExprDict { range: 1242..1322, keys: [Some(Constant(ExprConstant { range: 1243..1249, value: Str("wrap"), kind: None })), Some(Constant(ExprConstant { range: 1261..1267, value: Str("fill"), kind: None })), Some(Constant(ExprConstant { range: 1279..1287, value: Str("dedent"), kind: None })), Some(Constant(ExprConstant { range: 1301..1309, value: Str("indent"), kind: None }))], values: [Name(ExprName { r
|
|
example_thread_atomic
|
test_thread_atomic_cli.py
|
"""Tests for thread_atomic_cli.py"""
from thread_atomic_cli import (
AtomicBool,
AtomicCounter,
AtomicInt,
AtomicReference,
SpinLock,
atomic_max,
atomic_min,
atomic_ops,
cas_sequence,
counter_simulation,
spinlock_sequence,
)
class TestAtomicInt:
def test_initial_value(self):
atom = AtomicInt(5)
assert atom.get() == 5
def test_default_zero(self):
atom = AtomicInt()
assert atom.get() == 0
def test_set(self):
atom = AtomicInt(0)
atom.set(10)
assert atom.get() == 10
def test_add(self):
atom = AtomicInt(5)
assert atom.add(3) == 8
def test_sub(self):
atom = AtomicInt(5)
assert atom.sub(2) == 3
def test_increment(self):
atom = AtomicInt(0)
assert atom.increment() == 1
assert atom.increment() == 2
def test_decrement(self):
atom = AtomicInt(5)
assert atom.decrement() == 4
def test_cas_success(self):
atom = AtomicInt(5)
assert atom.compare_and_swap(5, 10)
assert atom.get() == 10
def test_cas_failure(self):
atom = AtomicInt(5)
assert not atom.compare_and_swap(3, 10)
assert atom.get() == 5
def test_get_and_set(self):
atom = AtomicInt(5)
old = atom.get_and_set(10)
assert old == 5
assert atom.get() == 10
def test_get_and_add(self):
atom = AtomicInt(5)
old = atom.get_and_add(3)
assert old == 5
assert atom.get() == 8
class TestAtomicBool:
def test_initial_false(self):
atom = AtomicBool()
assert not atom.get()
def test_set(self):
atom = AtomicBool(False)
atom.set(True)
assert atom.get()
def test_cas(self):
atom = AtomicBool(False)
assert atom.compare_and_swap(False, True)
assert atom.get()
def test_get_and_set(self):
atom = AtomicBool(True)
old = atom.get_and_set(False)
assert old
assert not atom.get()
class TestAtomicReference:
def test_set_get(self):
ref = AtomicReference()
ref.set("hello")
assert ref.get() == "hello"
def test_cas(self):
obj1 = object()
obj2 = object()
ref = AtomicReference(obj1)
assert ref.compare_and_swap(obj1, obj2)
assert ref.get() is obj2
def test_cas_failure(self):
obj1 = object()
obj2 = object()
obj3 = object()
ref = AtomicReference(obj1)
assert not ref.compare_and_swap(obj2, obj3)
assert ref.get() is obj1
class TestSpinLock:
def test_try_lock(self):
lock = SpinLock()
assert lock.try_lock()
assert lock.is_locked()
def test_unlock(self):
lock = SpinLock()
lock.try_lock()
lock.unlock()
assert not lock.is_locked()
def test_double_lock_fails(self):
lock = SpinLock()
assert lock.try_lock()
assert not lock.try_lock()
class TestAtomicCounter:
def test_increment(self):
counter = AtomicCounter()
assert counter.increment() == 1
assert counter.increment() == 2
def test_decrement(self):
counter = AtomicCounter()
counter.increment()
counter.increment()
assert counter.decrement() == 1
def test_reset(self):
counter = AtomicCounter()
counter.increment()
counter.increment()
old = counter.reset()
assert old == 2
assert counter.get() == 0
def test_stats(self):
counter = AtomicCounter()
counter.increment()
counter.increment()
counter.decrement()
stats = counter.stats()
assert stats["value"] == 1
assert stats["increments"] == 2
assert stats["decrements"] == 1
class TestAtomicOps:
def test_increment(self):
assert atomic_ops(0, ["inc", "inc", "inc"]) == 3
def test_decrement(self):
assert atomic_ops(5, ["dec", "dec"]) == 3
def test_add(self):
assert atomic_ops(0, ["add:5", "add:3"]) == 8
def test_sub(self):
assert atomic_ops(10, ["sub:3"]) == 7
def test_set(self):
assert atomic_ops(0, ["set:100"]) == 100
def test_cas(self):
assert atomic_ops(5, ["cas:5:10"]) == 10
def test_cas_fail(self):
assert atomic_ops(5, ["cas:3:10"]) == 5
class TestCasSequence:
def test_success(self):
result = cas_sequence(0, [(0, 1), (1, 2)])
assert result == [True, True]
def test_failure(self):
result = cas_sequence(0, [(1, 2)])
assert result == [False]
def test_mixed(self):
result = cas_sequence(0, [(0, 5), (3, 10), (5, 10)])
assert result == [True, False, True]
class TestSpinlockSequence:
def test_lock_unlock(self):
result = spinlock_sequence(["try", "check", "unlock", "check"])
assert result == [True, True, False]
def test_double_lock(self):
result = spinlock_sequence(["try", "try"])
assert result == [True, False]
class TestCounterSimulation:
def test_basic(self):
stats = counter_simulation(["inc", "inc", "dec"])
assert stats["value"] == 1
assert stats["increments"] == 2
assert stats["decrements"] == 1
def test_reset(self):
stats = counter_simulation(["inc", "inc", "reset", "inc"])
assert stats["value"] == 1
class TestAtomicMax:
def test_basic(self):
assert atomic_max([1, 5, 3, 2, 4]) == 5
def test_single(self):
assert atomic_max([42]) == 42
def test_empty(self):
assert atomic_max([]) == 0
def test_negative(self):
assert atomic_max([-5, -2, -10]) == -2
class TestAtomicMin:
def test_basic(self):
assert atomic_min([5, 1, 3, 2, 4]) == 1
def test_single(self):
assert atomic_min([42]) == 42
def test_empty(self):
assert atomic_min([]) == 0
def test_negative(self):
assert atomic_min([-5, -2, -10]) == -10
| false
|
thread_atomic
| 249
| 0
|
[
"class_definition"
] | 0.612
|
Error: 'is' operator not yet supported (use == for value comparison)
|
|
example_thread_atomic
|
thread_atomic_cli.py
|
#!/usr/bin/env python3
"""Thread Atomic CLI.
Atomic counter and CAS patterns.
"""
import argparse
import sys
import threading
class AtomicInt:
"""Atomic integer with CAS operations."""
def __init__(self, value: int = 0) -> None:
self._value: int = value
self._lock: threading.Lock = threading.Lock()
def get(self) -> int:
"""Get current value."""
with self._lock:
return self._value
def set(self, value: int) -> None:
"""Set value."""
with self._lock:
self._value = value
def add(self, delta: int) -> int:
"""Add and return new value."""
with self._lock:
self._value += delta
return self._value
def sub(self, delta: int) -> int:
"""Subtract and return new value."""
with self._lock:
self._value -= delta
return self._value
def increment(self) -> int:
"""Increment and return new value."""
return self.add(1)
def decrement(self) -> int:
"""Decrement and return new value."""
return self.sub(1)
def compare_and_swap(self, expected: int, new_value: int) -> bool:
"""Compare and swap. Returns True if successful."""
with self._lock:
if self._value == expected:
self._value = new_value
return True
return False
def get_and_set(self, new_value: int) -> int:
"""Get current value and set new value."""
with self._lock:
old = self._value
self._value = new_value
return old
def add_and_get(self, delta: int) -> int:
"""Add delta and return new value."""
return self.add(delta)
def get_and_add(self, delta: int) -> int:
"""Get current value then add delta."""
with self._lock:
old = self._value
self._value += delta
return old
class AtomicBool:
"""Atomic boolean."""
def __init__(self, value: bool = False) -> None:
self._value: bool = value
self._lock: threading.Lock = threading.Lock()
def get(self) -> bool:
"""Get current value."""
with self._lock:
return self._value
def set(self, value: bool) -> None:
"""Set value."""
with self._lock:
self._value = value
def compare_and_swap(self, expected: bool, new_value: bool) -> bool:
"""CAS for bool."""
with self._lock:
if self._value == expected:
self._value = new_value
return True
return False
def get_and_set(self, new_value: bool) -> bool:
"""Get and set."""
with self._lock:
old = self._value
self._value = new_value
return old
class AtomicReference:
"""Atomic reference to any object."""
def __init__(self, value: object = None) -> None:
self._value: object = value
self._lock: threading.Lock = threading.Lock()
def get(self) -> object:
"""Get current value."""
with self._lock:
return self._value
def set(self, value: object) -> None:
"""Set value."""
with self._lock:
self._value = value
def compare_and_swap(self, expected: object, new_value: object) -> bool:
"""CAS for reference."""
with self._lock:
if self._value is expected:
self._value = new_value
return True
return False
def get_and_set(self, new_value: object) -> object:
"""Get and set."""
with self._lock:
old = self._value
self._value = new_value
return old
class SpinLock:
"""Simple spinlock using atomic CAS."""
def __init__(self) -> None:
self._locked: AtomicBool = AtomicBool(False)
def try_lock(self) -> bool:
"""Try to acquire lock (non-blocking)."""
return self._locked.compare_and_swap(False, True)
def unlock(self) -> None:
"""Release lock."""
self._locked.set(False)
def is_locked(self) -> bool:
"""Check if locked."""
return self._locked.get()
class AtomicCounter:
"""High-level atomic counter with statistics."""
def __init__(self) -> None:
self._value: AtomicInt = AtomicInt(0)
self._increments: AtomicInt = AtomicInt(0)
self._decrements: AtomicInt = AtomicInt(0)
def increment(self) -> int:
"""Increment counter."""
self._increments.increment()
return self._value.increment()
def decrement(self) -> int:
"""Decrement counter."""
self._decrements.increment()
return self._value.decrement()
def get(self) -> int:
"""Get current value."""
return self._value.get()
def reset(self) -> int:
"""Reset and return old value."""
return self._value.get_and_set(0)
def stats(self) -> dict[str, int]:
"""Get statistics."""
return {
"value": self._value.get(),
"increments": self._increments.get(),
"decrements": self._decrements.get(),
}
def atomic_ops(initial: int, ops: list[str]) -> int:
"""Execute atomic operations and return result."""
atom = AtomicInt(initial)
for op in ops:
if op == "inc":
atom.increment()
elif op == "dec":
atom.decrement()
elif op.startswith("add:"):
delta = int(op.split(":")[1])
atom.add(delta)
elif op.startswith("sub:"):
delta = int(op.split(":")[1])
atom.sub(delta)
elif op.startswith("set:"):
val = int(op.split(":")[1])
atom.set(val)
elif op.startswith("cas:"):
parts = op.split(":")
expected = int(parts[1])
new_val = int(parts[2])
atom.compare_and_swap(expected, new_val)
return atom.get()
def cas_sequence(initial: int, operations: list[tuple[int, int]]) -> list[bool]:
"""Execute CAS sequence and return results."""
atom = AtomicInt(initial)
results: list[bool] = []
for expected, new_val in operations:
success = atom.compare_and_swap(expected, new_val)
results.append(success)
return results
def spinlock_sequence(ops: list[str]) -> list[bool]:
"""Execute spinlock sequence."""
lock = SpinLock()
results: list[bool] = []
for op in ops:
if op == "try":
results.append(lock.try_lock())
elif op == "unlock":
lock.unlock()
elif op == "check":
results.append(lock.is_locked())
return results
def counter_simulation(ops: list[str]) -> dict[str, int]:
"""Simulate counter with statistics."""
counter = AtomicCounter()
for op in ops:
if op == "inc":
counter.increment()
elif op == "dec":
counter.decrement()
elif op == "reset":
counter.reset()
return counter.stats()
def atomic_max(values: list[int]) -> int:
"""Find max using atomic compare-and-swap."""
if not values:
return 0
result = AtomicInt(values[0])
for val in values[1:]:
while True:
current = result.get()
if val <= current:
break
if result.compare_and_swap(current, val):
break
return result.get()
def atomic_min(values: list[int]) -> int:
"""Find min using atomic compare-and-swap."""
if not values:
return 0
result = AtomicInt(values[0])
for val in values[1:]:
while True:
current = result.get()
if val >= current:
break
if result.compare_and_swap(current, val):
break
return result.get()
def main() -> int:
parser = argparse.ArgumentParser(description="Thread atomic CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# ops
ops_p = subparsers.add_parser("ops", help="Atomic operations")
ops_p.add_argument("--initial", type=int, default=0)
ops_p.add_argument("ops", nargs="+")
# cas
cas_p = subparsers.add_parser("cas", help="CAS sequence")
cas_p.add_argument("initial", type=int)
cas_p.add_argument("operations", nargs="+", help="expected:new pairs")
# counter
counter_p = subparsers.add_parser("counter", help="Counter with stats")
counter_p.add_argument("ops", nargs="+")
# max
max_p = subparsers.add_parser("max", help="Atomic max")
max_p.add_argument("values", type=int, nargs="+")
args = parser.parse_args()
if args.command == "ops":
result = atomic_ops(args.initial, args.ops)
print(f"Result: {result}")
elif args.command == "cas":
operations = []
for op in args.operations:
parts = op.split(":")
operations.append((int(parts[0]), int(parts[1])))
results = cas_sequence(args.initial, operations)
print(f"Results: {results}")
elif args.command == "counter":
stats = counter_simulation(args.ops)
print(f"Stats: {stats}")
elif args.command == "max":
result = atomic_max(args.values)
print(f"Max: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
thread_atomic
| 353
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: 'is' operator not yet supported (use == for value comparison)
|
|
example_thread_event
|
test_thread_event_cli.py
|
"""Tests for thread_event_cli.py"""
from thread_event_cli import (
BarrierSimulator,
Gate,
Latch,
PulseEvent,
Signal,
event_sequence,
simulate_barrier,
simulate_gate,
simulate_latch,
simulate_signal,
)
class TestSignal:
def test_initial_state(self):
signal = Signal()
assert not signal.is_set()
def test_set(self):
signal = Signal()
signal.set()
assert signal.is_set()
def test_clear(self):
signal = Signal()
signal.set()
signal.clear()
assert not signal.is_set()
def test_signal_count(self):
signal = Signal()
signal.set()
signal.set()
assert signal.signal_count() == 2
class TestGate:
def test_initial_closed(self):
gate = Gate()
assert not gate.is_open()
def test_open(self):
gate = Gate()
gate.open()
assert gate.is_open()
def test_close(self):
gate = Gate()
gate.open()
gate.close()
assert not gate.is_open()
def test_pass_through(self):
gate = Gate()
assert not gate.pass_through()
gate.open()
assert gate.pass_through()
class TestLatch:
def test_initial_count(self):
latch = Latch(3)
assert latch.get_count() == 3
def test_count_down(self):
latch = Latch(3)
assert latch.count_down() == 2
assert latch.count_down() == 1
assert latch.count_down() == 0
def test_opens_at_zero(self):
latch = Latch(2)
assert not latch.is_open()
latch.count_down()
assert not latch.is_open()
latch.count_down()
assert latch.is_open()
def test_reset(self):
latch = Latch(3)
latch.count_down()
latch.count_down()
latch.reset()
assert latch.get_count() == 3
def test_zero_initial(self):
latch = Latch(0)
assert latch.is_open()
class TestPulseEvent:
def test_pulse(self):
event = PulseEvent()
event.pulse()
assert event.pulse_count() == 1
def test_auto_clears(self):
event = PulseEvent()
event.pulse()
assert not event.is_set()
def test_multiple_pulses(self):
event = PulseEvent()
event.pulse()
event.pulse()
event.pulse()
assert event.pulse_count() == 3
class TestBarrierSimulator:
def test_parties(self):
barrier = BarrierSimulator(3)
assert barrier.parties() == 3
def test_wait_index(self):
barrier = BarrierSimulator(3)
assert barrier.wait() == 0
assert barrier.wait() == 1
assert barrier.wait() == 2
def test_generation(self):
barrier = BarrierSimulator(2)
assert barrier.generation() == 0
barrier.wait()
barrier.wait()
assert barrier.generation() == 1
def test_reset_waiting(self):
barrier = BarrierSimulator(3)
barrier.wait()
barrier.wait()
barrier.wait()
assert barrier.n_waiting() == 0
class TestSimulateSignal:
def test_set_check(self):
result = simulate_signal(["set", "check"])
assert result == [True]
def test_clear_check(self):
result = simulate_signal(["set", "clear", "check"])
assert result == [False]
class TestSimulateGate:
def test_open_check(self):
result = simulate_gate(["open", "check"])
assert result == [True]
def test_pass(self):
result = simulate_gate(["pass", "open", "pass"])
assert result == [False, True]
class TestSimulateLatch:
def test_countdown(self):
result = simulate_latch(3, ["down", "down", "count"])
assert result == [1]
def test_open_check(self):
result = simulate_latch(2, ["down", "down", "open"])
assert result == [1]
def test_reset(self):
result = simulate_latch(3, ["down", "down", "reset", "count"])
assert result == [3]
class TestSimulateBarrier:
def test_full_cycle(self):
waiting, gen = simulate_barrier(3, 3)
assert waiting == 0
assert gen == 1
def test_partial(self):
waiting, gen = simulate_barrier(3, 2)
assert waiting == 2
assert gen == 0
class TestEventSequence:
def test_set_clear(self):
result = event_sequence(["set", "clear"])
assert result == [True, False]
def test_toggle(self):
result = event_sequence(["toggle", "toggle"])
assert result == [True, False]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_event/test_thread_event_cli.py (4576 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_event/test_thread_event_cli.rs (9356 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 89.8 KB/s
⏱️ Total time: 49ms
| true
|
thread_event
| 192
| 5
|
[
"class_definition",
"functools"
] | 0.612
| null |
example_thread_event
|
thread_event_cli.py
|
#!/usr/bin/env python3
"""Thread Event CLI.
Event and Barrier patterns for thread coordination.
"""
import argparse
import sys
import threading
class Signal:
"""Simple signal using Event."""
def __init__(self) -> None:
self._event: threading.Event = threading.Event()
self._signal_count: int = 0
self._lock: threading.Lock = threading.Lock()
def set(self) -> None:
"""Set the signal."""
with self._lock:
self._signal_count += 1
self._event.set()
def clear(self) -> None:
"""Clear the signal."""
self._event.clear()
def is_set(self) -> bool:
"""Check if signal is set."""
return self._event.is_set()
def wait(self, timeout: float | None = None) -> bool:
"""Wait for signal."""
return self._event.wait(timeout)
def signal_count(self) -> int:
"""Get number of times signal was set."""
with self._lock:
return self._signal_count
class Gate:
"""Gate that blocks until opened."""
def __init__(self) -> None:
self._event: threading.Event = threading.Event()
self._waiters: int = 0
self._lock: threading.Lock = threading.Lock()
def open(self) -> None:
"""Open the gate."""
self._event.set()
def close(self) -> None:
"""Close the gate."""
self._event.clear()
def is_open(self) -> bool:
"""Check if gate is open."""
return self._event.is_set()
def pass_through(self) -> bool:
"""Try to pass through gate (non-blocking)."""
return self._event.is_set()
def wait_for_open(self, timeout: float | None = None) -> bool:
"""Wait for gate to open."""
with self._lock:
self._waiters += 1
result = self._event.wait(timeout)
with self._lock:
self._waiters -= 1
return result
def waiting_count(self) -> int:
"""Get number of waiters."""
with self._lock:
return self._waiters
class Latch:
"""Countdown latch - opens when count reaches zero."""
def __init__(self, count: int) -> None:
self._count: int = count
self._initial: int = count
self._event: threading.Event = threading.Event()
self._lock: threading.Lock = threading.Lock()
if count <= 0:
self._event.set()
def count_down(self) -> int:
"""Decrement count, open when zero."""
with self._lock:
if self._count > 0:
self._count -= 1
if self._count == 0:
self._event.set()
return self._count
def get_count(self) -> int:
"""Get current count."""
with self._lock:
return self._count
def is_open(self) -> bool:
"""Check if latch is open."""
return self._event.is_set()
def wait(self, timeout: float | None = None) -> bool:
"""Wait for latch to open."""
return self._event.wait(timeout)
def reset(self) -> None:
"""Reset latch to initial count."""
with self._lock:
self._count = self._initial
self._event.clear()
class PulseEvent:
"""Event that auto-clears after being set (pulse)."""
def __init__(self) -> None:
self._event: threading.Event = threading.Event()
self._pulse_count: int = 0
self._lock: threading.Lock = threading.Lock()
def pulse(self) -> None:
"""Set and immediately clear."""
with self._lock:
self._pulse_count += 1
self._event.set()
self._event.clear()
def is_set(self) -> bool:
"""Check current state."""
return self._event.is_set()
def pulse_count(self) -> int:
"""Get total pulses."""
with self._lock:
return self._pulse_count
class BarrierSimulator:
"""Simulate barrier behavior without actual threading."""
def __init__(self, parties: int) -> None:
self._parties: int = parties
self._waiting: int = 0
self._generation: int = 0
self._lock: threading.Lock = threading.Lock()
def wait(self) -> int:
"""Simulate barrier wait, return arrival index."""
with self._lock:
index = self._waiting
self._waiting += 1
if self._waiting >= self._parties:
self._generation += 1
self._waiting = 0
return index
def parties(self) -> int:
"""Get number of parties."""
return self._parties
def n_waiting(self) -> int:
"""Get number currently waiting."""
with self._lock:
return self._waiting
def generation(self) -> int:
"""Get current generation."""
with self._lock:
return self._generation
def simulate_signal(ops: list[str]) -> list[bool]:
"""Simulate signal operations."""
signal = Signal()
results: list[bool] = []
for op in ops:
if op == "set":
signal.set()
elif op == "clear":
signal.clear()
elif op == "check":
results.append(signal.is_set())
elif op == "count":
results.append(signal.signal_count() > 0)
return results
def simulate_gate(ops: list[str]) -> list[bool]:
"""Simulate gate operations."""
gate = Gate()
results: list[bool] = []
for op in ops:
if op == "open":
gate.open()
elif op == "close":
gate.close()
elif op == "check":
results.append(gate.is_open())
elif op == "pass":
results.append(gate.pass_through())
return results
def simulate_latch(count: int, ops: list[str]) -> list[int]:
"""Simulate latch operations."""
latch = Latch(count)
results: list[int] = []
for op in ops:
if op == "down":
latch.count_down()
elif op == "count":
results.append(latch.get_count())
elif op == "open":
results.append(1 if latch.is_open() else 0)
elif op == "reset":
latch.reset()
return results
def simulate_barrier(parties: int, waits: int) -> tuple[int, int]:
"""Simulate barrier with given parties and waits."""
barrier = BarrierSimulator(parties)
for _ in range(waits):
barrier.wait()
return (barrier.n_waiting(), barrier.generation())
def event_sequence(sequence: list[str]) -> list[bool]:
"""Execute event sequence and return states."""
event = threading.Event()
states: list[bool] = []
for op in sequence:
if op == "set":
event.set()
elif op == "clear":
event.clear()
elif op == "toggle":
if event.is_set():
event.clear()
else:
event.set()
states.append(event.is_set())
return states
def main() -> int:
parser = argparse.ArgumentParser(description="Thread event CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# signal
signal_p = subparsers.add_parser("signal", help="Signal operations")
signal_p.add_argument("ops", nargs="+")
# gate
gate_p = subparsers.add_parser("gate", help="Gate operations")
gate_p.add_argument("ops", nargs="+")
# latch
latch_p = subparsers.add_parser("latch", help="Latch operations")
latch_p.add_argument("--count", type=int, default=3)
latch_p.add_argument("ops", nargs="+")
# barrier
barrier_p = subparsers.add_parser("barrier", help="Barrier simulation")
barrier_p.add_argument("parties", type=int)
barrier_p.add_argument("waits", type=int)
args = parser.parse_args()
if args.command == "signal":
results = simulate_signal(args.ops)
print(f"States: {results}")
elif args.command == "gate":
results = simulate_gate(args.ops)
print(f"States: {results}")
elif args.command == "latch":
results = simulate_latch(args.count, args.ops)
print(f"Results: {results}")
elif args.command == "barrier":
waiting, gen = simulate_barrier(args.parties, args.waits)
print(f"Waiting: {waiting}, Generation: {gen}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_event/thread_event_cli.py (8374 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_event/thread_event_cli.rs (11171 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_thread_event/Cargo.toml (1 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 158.2 KB/s
⏱️ Total time: 51ms
| true
|
thread_event
| 313
| 6
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_thread_lock
|
test_thread_lock_cli.py
|
"""Tests for thread_lock_cli.py"""
import threading
from thread_lock_cli import (
Counter,
ReentrantCounter,
SharedBuffer,
locked_append,
locked_clear,
locked_extend,
locked_max,
locked_sum,
locked_swap,
simulate_buffer_ops,
simulate_counter_ops,
try_acquire,
with_lock,
)
class TestCounter:
def test_initial_value(self):
c = Counter()
assert c.get() == 0
def test_increment(self):
c = Counter()
assert c.increment() == 1
assert c.increment() == 2
def test_decrement(self):
c = Counter()
c.increment()
c.increment()
assert c.decrement() == 1
def test_add(self):
c = Counter()
assert c.add(5) == 5
assert c.add(3) == 8
def test_add_negative(self):
c = Counter()
c.add(10)
assert c.add(-3) == 7
class TestReentrantCounter:
def test_increment(self):
c = ReentrantCounter()
assert c.increment() == 1
def test_increment_twice(self):
c = ReentrantCounter()
assert c.increment_twice() == 2
def test_get(self):
c = ReentrantCounter()
c.increment()
assert c.get() == 1
class TestSharedBuffer:
def test_push_pop(self):
buf = SharedBuffer(5)
assert buf.push(1)
assert buf.push(2)
assert buf.pop() == 1
assert buf.pop() == 2
def test_capacity(self):
buf = SharedBuffer(2)
assert buf.push(1)
assert buf.push(2)
assert not buf.push(3)
def test_empty(self):
buf = SharedBuffer(5)
assert buf.is_empty()
buf.push(1)
assert not buf.is_empty()
def test_full(self):
buf = SharedBuffer(2)
assert not buf.is_full()
buf.push(1)
buf.push(2)
assert buf.is_full()
def test_size(self):
buf = SharedBuffer(5)
assert buf.size() == 0
buf.push(1)
assert buf.size() == 1
def test_pop_empty(self):
buf = SharedBuffer(5)
assert buf.pop() is None
class TestLockFunctions:
def test_with_lock(self):
lock = threading.Lock()
assert with_lock(lock, 5) == 10
def test_try_acquire_free(self):
lock = threading.Lock()
assert try_acquire(lock)
def test_locked_swap(self):
lock = threading.Lock()
assert locked_swap(lock, 1, 2) == (2, 1)
def test_locked_max(self):
lock = threading.Lock()
assert locked_max(lock, [1, 5, 3, 2]) == 5
def test_locked_max_empty(self):
lock = threading.Lock()
assert locked_max(lock, []) == 0
def test_locked_sum(self):
lock = threading.Lock()
assert locked_sum(lock, [1, 2, 3, 4]) == 10
def test_locked_append(self):
lock = threading.Lock()
lst: list[int] = [1, 2]
result = locked_append(lock, lst, 3)
assert result == [1, 2, 3]
def test_locked_extend(self):
lock = threading.Lock()
lst: list[int] = [1]
result = locked_extend(lock, lst, [2, 3])
assert result == [1, 2, 3]
def test_locked_clear(self):
lock = threading.Lock()
lst: list[int] = [1, 2, 3]
result = locked_clear(lock, lst)
assert result == []
class TestSimulateCounterOps:
def test_increment_only(self):
assert simulate_counter_ops(["inc", "inc", "inc"]) == 3
def test_decrement(self):
assert simulate_counter_ops(["inc", "inc", "dec"]) == 1
def test_add(self):
assert simulate_counter_ops(["add:5", "add:3"]) == 8
def test_mixed(self):
assert simulate_counter_ops(["inc", "add:10", "dec", "dec"]) == 9
class TestSimulateBufferOps:
def test_push_pop(self):
result = simulate_buffer_ops(5, ["push:1", "push:2", "pop", "pop"])
assert result == [1, 2]
def test_size(self):
result = simulate_buffer_ops(5, ["push:1", "push:2", "size"])
assert result == [2]
def test_capacity_limit(self):
result = simulate_buffer_ops(2, ["push:1", "push:2", "push:3", "size"])
assert result == [2]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_lock/test_thread_lock_cli.py (4176 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_lock/test_thread_lock_cli.rs (9679 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 82.1 KB/s
⏱️ Total time: 49ms
| true
|
thread_lock
| 171
| 5
|
[
"class_definition"
] | 0.612
| null |
example_thread_lock
|
thread_lock_cli.py
|
#!/usr/bin/env python3
"""Thread Lock CLI.
Lock and RLock patterns for thread synchronization.
"""
import argparse
import sys
import threading
from typing import TypeVar
T = TypeVar("T")
class Counter:
"""Thread-safe counter using Lock."""
def __init__(self) -> None:
self._value: int = 0
self._lock: threading.Lock = threading.Lock()
def increment(self) -> int:
"""Increment counter atomically."""
with self._lock:
self._value += 1
return self._value
def decrement(self) -> int:
"""Decrement counter atomically."""
with self._lock:
self._value -= 1
return self._value
def get(self) -> int:
"""Get current value."""
with self._lock:
return self._value
def add(self, n: int) -> int:
"""Add n to counter."""
with self._lock:
self._value += n
return self._value
class ReentrantCounter:
"""Counter using RLock for reentrant access."""
def __init__(self) -> None:
self._value: int = 0
self._lock: threading.RLock = threading.RLock()
def increment(self) -> int:
"""Increment with reentrant lock."""
with self._lock:
self._value += 1
return self._value
def increment_twice(self) -> int:
"""Increment twice - demonstrates reentrant locking."""
with self._lock:
self.increment()
return self.increment()
def get(self) -> int:
"""Get value with lock."""
with self._lock:
return self._value
class SharedBuffer:
"""Thread-safe buffer with lock."""
def __init__(self, capacity: int) -> None:
self._buffer: list[int] = []
self._capacity: int = capacity
self._lock: threading.Lock = threading.Lock()
def push(self, item: int) -> bool:
"""Push item if space available."""
with self._lock:
if len(self._buffer) < self._capacity:
self._buffer.append(item)
return True
return False
def pop(self) -> int | None:
"""Pop item if available."""
with self._lock:
if self._buffer:
return self._buffer.pop(0)
return None
def size(self) -> int:
"""Get buffer size."""
with self._lock:
return len(self._buffer)
def is_empty(self) -> bool:
"""Check if empty."""
with self._lock:
return len(self._buffer) == 0
def is_full(self) -> bool:
"""Check if full."""
with self._lock:
return len(self._buffer) >= self._capacity
def with_lock(lock: threading.Lock, value: int) -> int:
"""Execute operation with lock."""
with lock:
return value * 2
def try_acquire(lock: threading.Lock) -> bool:
"""Try to acquire lock without blocking."""
acquired = lock.acquire(blocking=False)
if acquired:
lock.release()
return acquired
def locked_swap(lock: threading.Lock, a: int, b: int) -> tuple[int, int]:
"""Swap values under lock."""
with lock:
return (b, a)
def locked_max(lock: threading.Lock, values: list[int]) -> int:
"""Find max under lock."""
with lock:
if not values:
return 0
return max(values)
def locked_sum(lock: threading.Lock, values: list[int]) -> int:
"""Sum values under lock."""
with lock:
return sum(values)
def locked_append(lock: threading.Lock, lst: list[int], item: int) -> list[int]:
"""Append to list under lock."""
with lock:
lst.append(item)
return lst.copy()
def locked_extend(lock: threading.Lock, lst: list[int], items: list[int]) -> list[int]:
"""Extend list under lock."""
with lock:
lst.extend(items)
return lst.copy()
def locked_clear(lock: threading.Lock, lst: list[int]) -> list[int]:
"""Clear list under lock."""
with lock:
lst.clear()
return lst.copy()
def simulate_counter_ops(ops: list[str]) -> int:
"""Simulate counter operations."""
counter = Counter()
for op in ops:
if op == "inc":
counter.increment()
elif op == "dec":
counter.decrement()
elif op.startswith("add:"):
n = int(op.split(":")[1])
counter.add(n)
return counter.get()
def simulate_buffer_ops(capacity: int, ops: list[str]) -> list[int]:
"""Simulate buffer operations."""
buffer = SharedBuffer(capacity)
results: list[int] = []
for op in ops:
if op.startswith("push:"):
n = int(op.split(":")[1])
buffer.push(n)
elif op == "pop":
val = buffer.pop()
if val is not None:
results.append(val)
elif op == "size":
results.append(buffer.size())
return results
def main() -> int:
parser = argparse.ArgumentParser(description="Thread lock CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# counter
counter_p = subparsers.add_parser("counter", help="Counter operations")
counter_p.add_argument("ops", nargs="+", help="Operations: inc, dec, add:N")
# buffer
buffer_p = subparsers.add_parser("buffer", help="Buffer operations")
buffer_p.add_argument("--capacity", type=int, default=10)
buffer_p.add_argument("ops", nargs="+", help="Operations: push:N, pop, size")
args = parser.parse_args()
if args.command == "counter":
result = simulate_counter_ops(args.ops)
print(f"Counter: {result}")
elif args.command == "buffer":
results = simulate_buffer_ops(args.capacity, args.ops)
print(f"Results: {results}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_lock/thread_lock_cli.py (5889 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_lock/thread_lock_cli.rs (9703 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_thread_lock/Cargo.toml (3 dependencies)
⏱️ Parse time: 52ms
📊 Throughput: 110.3 KB/s
⏱️ Total time: 52ms
| true
|
thread_lock
| 226
| 6
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_thread_queue
|
test_thread_queue_cli.py
|
"""Tests for thread_queue_cli.py"""
from thread_queue_cli import (
Deque,
LifoQueue,
PriorityQueue,
ThreadSafeQueue,
producer_consumer_sim,
simulate_deque,
simulate_fifo,
simulate_lifo,
simulate_priority,
)
class TestThreadSafeQueue:
def test_put_get(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
q.put(1)
q.put(2)
assert q.get() == 1
assert q.get() == 2
def test_empty(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
assert q.empty()
q.put(1)
assert not q.empty()
def test_size(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
assert q.size() == 0
q.put(1)
assert q.size() == 1
def test_peek(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
q.put(1)
q.put(2)
assert q.peek() == 1
assert q.size() == 2
def test_maxsize(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue(maxsize=2)
assert q.put(1)
assert q.put(2)
assert not q.put(3)
def test_full(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue(maxsize=2)
assert not q.full()
q.put(1)
q.put(2)
assert q.full()
def test_clear(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
q.put(1)
q.put(2)
assert q.clear() == 2
assert q.empty()
def test_get_empty(self):
q: ThreadSafeQueue[int] = ThreadSafeQueue()
assert q.get() is None
class TestPriorityQueue:
def test_priority_order(self):
pq: PriorityQueue[str] = PriorityQueue()
pq.put(3, "low")
pq.put(1, "high")
pq.put(2, "medium")
assert pq.get() == "high"
assert pq.get() == "medium"
assert pq.get() == "low"
def test_peek(self):
pq: PriorityQueue[int] = PriorityQueue()
pq.put(2, 20)
pq.put(1, 10)
result = pq.peek()
assert result is not None
assert result == (1, 10)
def test_size(self):
pq: PriorityQueue[int] = PriorityQueue()
assert pq.size() == 0
pq.put(1, 10)
assert pq.size() == 1
def test_get_empty(self):
pq: PriorityQueue[int] = PriorityQueue()
assert pq.get() is None
class TestLifoQueue:
def test_lifo_order(self):
stack: LifoQueue[int] = LifoQueue()
stack.put(1)
stack.put(2)
stack.put(3)
assert stack.get() == 3
assert stack.get() == 2
assert stack.get() == 1
def test_peek(self):
stack: LifoQueue[int] = LifoQueue()
stack.put(1)
stack.put(2)
assert stack.peek() == 2
assert stack.size() == 2
def test_maxsize(self):
stack: LifoQueue[int] = LifoQueue(maxsize=2)
assert stack.put(1)
assert stack.put(2)
assert not stack.put(3)
class TestDeque:
def test_push_front(self):
d: Deque[int] = Deque()
d.push_front(1)
d.push_front(2)
assert d.pop_front() == 2
def test_push_back(self):
d: Deque[int] = Deque()
d.push_back(1)
d.push_back(2)
assert d.pop_back() == 2
def test_mixed(self):
d: Deque[int] = Deque()
d.push_back(1)
d.push_front(2)
d.push_back(3)
assert d.pop_front() == 2
assert d.pop_back() == 3
assert d.pop_front() == 1
def test_maxsize(self):
d: Deque[int] = Deque(maxsize=2)
assert d.push_back(1)
assert d.push_front(2)
assert not d.push_back(3)
class TestSimulateFifo:
def test_basic(self):
result = simulate_fifo(0, ["put:1", "put:2", "get", "get"])
assert result == [1, 2]
def test_size(self):
result = simulate_fifo(0, ["put:1", "put:2", "size"])
assert result == [2]
def test_peek(self):
result = simulate_fifo(0, ["put:1", "put:2", "peek"])
assert result == [1]
class TestSimulateLifo:
def test_basic(self):
result = simulate_lifo(0, ["put:1", "put:2", "get", "get"])
assert result == [2, 1]
def test_size(self):
result = simulate_lifo(0, ["put:1", "put:2", "size"])
assert result == [2]
class TestSimulatePriority:
def test_priority_order(self):
result = simulate_priority(["put:3:30", "put:1:10", "put:2:20", "get", "get", "get"])
assert result == [10, 20, 30]
def test_size(self):
result = simulate_priority(["put:1:10", "put:2:20", "size"])
assert result == [2]
class TestSimulateDeque:
def test_push_pop(self):
result = simulate_deque(0, ["pb:1", "pb:2", "pf:0", "gf", "gb"])
assert result == [0, 2]
def test_size(self):
result = simulate_deque(0, ["pb:1", "pf:2", "size"])
assert result == [2]
class TestProducerConsumerSim:
def test_basic(self):
result = producer_consumer_sim([1, 2, 3, 4, 5], 2)
assert result == [1, 2, 3, 4, 5]
def test_single_batch(self):
result = producer_consumer_sim([1, 2], 10)
assert result == [1, 2]
def test_empty(self):
result = producer_consumer_sim([], 3)
assert result == []
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_queue/test_thread_queue_cli.py (5248 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_queue/test_thread_queue_cli.rs (9973 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 100.6 KB/s
⏱️ Total time: 51ms
| true
|
thread_queue
| 205
| 5
|
[
"class_definition"
] | 0.612
| null |
example_thread_queue
|
thread_queue_cli.py
|
#!/usr/bin/env python3
"""Thread Queue CLI.
Thread-safe queue patterns for producer-consumer scenarios.
"""
import argparse
import sys
import threading
from typing import Generic, TypeVar
T = TypeVar("T")
class ThreadSafeQueue(Generic[T]):
"""Thread-safe FIFO queue."""
def __init__(self, maxsize: int = 0) -> None:
self._items: list[T] = []
self._maxsize: int = maxsize
self._lock: threading.Lock = threading.Lock()
def put(self, item: T) -> bool:
"""Put item in queue. Returns False if full."""
with self._lock:
if self._maxsize > 0 and len(self._items) >= self._maxsize:
return False
self._items.append(item)
return True
def get(self) -> T | None:
"""Get item from queue. Returns None if empty."""
with self._lock:
if self._items:
return self._items.pop(0)
return None
def peek(self) -> T | None:
"""Peek at front item without removing."""
with self._lock:
if self._items:
return self._items[0]
return None
def size(self) -> int:
"""Get queue size."""
with self._lock:
return len(self._items)
def empty(self) -> bool:
"""Check if empty."""
with self._lock:
return len(self._items) == 0
def full(self) -> bool:
"""Check if full."""
with self._lock:
return self._maxsize > 0 and len(self._items) >= self._maxsize
def clear(self) -> int:
"""Clear queue and return count of removed items."""
with self._lock:
count = len(self._items)
self._items.clear()
return count
class PriorityQueue(Generic[T]):
"""Thread-safe priority queue (min-heap simulation)."""
def __init__(self) -> None:
self._items: list[tuple[int, T]] = []
self._lock: threading.Lock = threading.Lock()
def put(self, priority: int, item: T) -> None:
"""Put item with priority (lower = higher priority)."""
with self._lock:
self._items.append((priority, item))
self._items.sort(key=lambda x: x[0])
def get(self) -> T | None:
"""Get highest priority item."""
with self._lock:
if self._items:
return self._items.pop(0)[1]
return None
def peek(self) -> tuple[int, T] | None:
"""Peek at highest priority item."""
with self._lock:
if self._items:
return self._items[0]
return None
def size(self) -> int:
"""Get queue size."""
with self._lock:
return len(self._items)
class LifoQueue(Generic[T]):
"""Thread-safe LIFO queue (stack)."""
def __init__(self, maxsize: int = 0) -> None:
self._items: list[T] = []
self._maxsize: int = maxsize
self._lock: threading.Lock = threading.Lock()
def put(self, item: T) -> bool:
"""Push item onto stack."""
with self._lock:
if self._maxsize > 0 and len(self._items) >= self._maxsize:
return False
self._items.append(item)
return True
def get(self) -> T | None:
"""Pop item from stack."""
with self._lock:
if self._items:
return self._items.pop()
return None
def peek(self) -> T | None:
"""Peek at top item."""
with self._lock:
if self._items:
return self._items[-1]
return None
def size(self) -> int:
"""Get stack size."""
with self._lock:
return len(self._items)
class Deque(Generic[T]):
"""Thread-safe double-ended queue."""
def __init__(self, maxsize: int = 0) -> None:
self._items: list[T] = []
self._maxsize: int = maxsize
self._lock: threading.Lock = threading.Lock()
def push_front(self, item: T) -> bool:
"""Push to front."""
with self._lock:
if self._maxsize > 0 and len(self._items) >= self._maxsize:
return False
self._items.insert(0, item)
return True
def push_back(self, item: T) -> bool:
"""Push to back."""
with self._lock:
if self._maxsize > 0 and len(self._items) >= self._maxsize:
return False
self._items.append(item)
return True
def pop_front(self) -> T | None:
"""Pop from front."""
with self._lock:
if self._items:
return self._items.pop(0)
return None
def pop_back(self) -> T | None:
"""Pop from back."""
with self._lock:
if self._items:
return self._items.pop()
return None
def size(self) -> int:
"""Get size."""
with self._lock:
return len(self._items)
def simulate_fifo(maxsize: int, ops: list[str]) -> list[int]:
"""Simulate FIFO queue operations."""
queue: ThreadSafeQueue[int] = ThreadSafeQueue(maxsize)
results: list[int] = []
for op in ops:
if op.startswith("put:"):
val = int(op.split(":")[1])
queue.put(val)
elif op == "get":
val = queue.get()
if val is not None:
results.append(val)
elif op == "size":
results.append(queue.size())
elif op == "peek":
val = queue.peek()
if val is not None:
results.append(val)
return results
def simulate_lifo(maxsize: int, ops: list[str]) -> list[int]:
"""Simulate LIFO queue operations."""
stack: LifoQueue[int] = LifoQueue(maxsize)
results: list[int] = []
for op in ops:
if op.startswith("put:"):
val = int(op.split(":")[1])
stack.put(val)
elif op == "get":
val = stack.get()
if val is not None:
results.append(val)
elif op == "size":
results.append(stack.size())
return results
def simulate_priority(ops: list[str]) -> list[int]:
"""Simulate priority queue operations."""
pq: PriorityQueue[int] = PriorityQueue()
results: list[int] = []
for op in ops:
if op.startswith("put:"):
parts = op.split(":")
priority = int(parts[1])
value = int(parts[2])
pq.put(priority, value)
elif op == "get":
val = pq.get()
if val is not None:
results.append(val)
elif op == "size":
results.append(pq.size())
return results
def simulate_deque(maxsize: int, ops: list[str]) -> list[int]:
"""Simulate deque operations."""
deque: Deque[int] = Deque(maxsize)
results: list[int] = []
for op in ops:
if op.startswith("pf:"):
val = int(op.split(":")[1])
deque.push_front(val)
elif op.startswith("pb:"):
val = int(op.split(":")[1])
deque.push_back(val)
elif op == "gf":
val = deque.pop_front()
if val is not None:
results.append(val)
elif op == "gb":
val = deque.pop_back()
if val is not None:
results.append(val)
elif op == "size":
results.append(deque.size())
return results
def producer_consumer_sim(items: list[int], batch_size: int) -> list[int]:
"""Simulate producer-consumer pattern."""
queue: ThreadSafeQueue[int] = ThreadSafeQueue()
results: list[int] = []
# Producer adds all items
for item in items:
queue.put(item)
# Consumer gets in batches
while not queue.empty():
batch: list[int] = []
for _ in range(batch_size):
val = queue.get()
if val is not None:
batch.append(val)
results.extend(batch)
return results
def main() -> int:
parser = argparse.ArgumentParser(description="Thread queue CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# fifo
fifo_p = subparsers.add_parser("fifo", help="FIFO queue")
fifo_p.add_argument("--maxsize", type=int, default=0)
fifo_p.add_argument("ops", nargs="+")
# lifo
lifo_p = subparsers.add_parser("lifo", help="LIFO queue")
lifo_p.add_argument("--maxsize", type=int, default=0)
lifo_p.add_argument("ops", nargs="+")
# priority
priority_p = subparsers.add_parser("priority", help="Priority queue")
priority_p.add_argument("ops", nargs="+")
# deque
deque_p = subparsers.add_parser("deque", help="Double-ended queue")
deque_p.add_argument("--maxsize", type=int, default=0)
deque_p.add_argument("ops", nargs="+")
args = parser.parse_args()
if args.command == "fifo":
results = simulate_fifo(args.maxsize, args.ops)
print(f"Results: {results}")
elif args.command == "lifo":
results = simulate_lifo(args.maxsize, args.ops)
print(f"Results: {results}")
elif args.command == "priority":
results = simulate_priority(args.ops)
print(f"Results: {results}")
elif args.command == "deque":
results = simulate_deque(args.maxsize, args.ops)
print(f"Results: {results}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_queue/thread_queue_cli.py (9498 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_queue/thread_queue_cli.rs (14644 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_thread_queue/Cargo.toml (3 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 166.1 KB/s
⏱️ Total time: 56ms
| true
|
thread_queue
| 339
| 6
|
[
"lambda",
"context_manager",
"class_definition"
] | 0.783
| null |
example_thread_semaphore
|
test_thread_semaphore_cli.py
|
"""Tests for thread_semaphore_cli.py"""
from thread_semaphore_cli import (
BoundedPool,
ConnectionPool,
RateLimiter,
ResourcePool,
bounded_test,
semaphore_count,
simulate_connections,
simulate_pool,
)
class TestResourcePool:
def test_initial_available(self):
pool = ResourcePool(5)
assert pool.available() == 5
def test_acquire(self):
pool = ResourcePool(3)
assert pool.acquire()
assert pool.available() == 2
def test_release(self):
pool = ResourcePool(3)
pool.acquire()
assert pool.release()
assert pool.available() == 3
def test_over_release(self):
pool = ResourcePool(3)
assert not pool.release()
def test_exhaust_pool(self):
pool = ResourcePool(2)
assert pool.acquire()
assert pool.acquire()
assert not pool.acquire()
class TestBoundedPool:
def test_acquire(self):
pool = BoundedPool(3)
assert pool.acquire()
assert pool.acquired_count() == 1
def test_release(self):
pool = BoundedPool(3)
pool.acquire()
assert pool.release()
assert pool.acquired_count() == 0
def test_bounded_release(self):
pool = BoundedPool(3)
assert not pool.release()
class TestConnectionPool:
def test_connect(self):
pool = ConnectionPool(3)
conn_id = pool.connect()
assert conn_id is not None
assert conn_id in pool.active_connections()
def test_disconnect(self):
pool = ConnectionPool(3)
conn_id = pool.connect()
assert conn_id is not None
assert pool.disconnect(conn_id)
assert conn_id not in pool.active_connections()
def test_max_connections(self):
pool = ConnectionPool(2)
pool.connect()
pool.connect()
assert pool.connect() is None
def test_disconnect_invalid(self):
pool = ConnectionPool(3)
assert not pool.disconnect(999)
class TestRateLimiter:
def test_acquire(self):
limiter = RateLimiter(3)
assert limiter.try_acquire()
assert limiter.active() == 1
def test_release(self):
limiter = RateLimiter(3)
limiter.try_acquire()
limiter.release()
assert limiter.active() == 0
def test_total_acquired(self):
limiter = RateLimiter(3)
limiter.try_acquire()
limiter.try_acquire()
assert limiter.total_acquired() == 2
class TestSemaphoreCount:
def test_basic(self):
assert semaphore_count(5, 2, 1) == 4
def test_no_releases(self):
assert semaphore_count(5, 3, 0) == 2
def test_all_released(self):
assert semaphore_count(5, 3, 3) == 5
class TestSimulatePool:
def test_acquire_release(self):
result = simulate_pool(5, ["acquire", "acquire", "available"])
assert result == [3]
def test_full_cycle(self):
result = simulate_pool(3, ["acquire", "acquire", "release", "available"])
assert result == [2]
class TestSimulateConnections:
def test_connect(self):
result = simulate_connections(3, ["connect:a", "connect:b", "count"])
assert len(result) == 3
assert result[-1] == 2
def test_disconnect(self):
result = simulate_connections(3, ["connect:a", "disconnect:a", "count"])
assert result[-1] == 0
class TestBoundedTest:
def test_normal(self):
acquired, released = bounded_test(3, 2, 2)
assert acquired == 0
assert released == 2
def test_over_acquire(self):
acquired, released = bounded_test(2, 5, 0)
assert acquired == 2
def test_bounded_release(self):
acquired, released = bounded_test(3, 2, 5)
assert released == 2
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_semaphore/test_thread_semaphore_cli.py (3804 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_semaphore/test_thread_semaphore_cli.rs (7828 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 75.3 KB/s
⏱️ Total time: 49ms
| true
|
thread_semaphore
| 147
| 5
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_thread_semaphore
|
thread_semaphore_cli.py
|
#!/usr/bin/env python3
"""Thread Semaphore CLI.
Semaphore and BoundedSemaphore patterns.
"""
import argparse
import sys
import threading
class ResourcePool:
"""Pool of limited resources using Semaphore."""
def __init__(self, size: int) -> None:
self._size: int = size
self._available: int = size
self._semaphore: threading.Semaphore = threading.Semaphore(size)
self._lock: threading.Lock = threading.Lock()
def acquire(self) -> bool:
"""Acquire a resource."""
acquired = self._semaphore.acquire(blocking=False)
if acquired:
with self._lock:
self._available -= 1
return acquired
def release(self) -> bool:
"""Release a resource."""
with self._lock:
if self._available < self._size:
self._available += 1
self._semaphore.release()
return True
return False
def available(self) -> int:
"""Get available count."""
with self._lock:
return self._available
def size(self) -> int:
"""Get pool size."""
return self._size
class BoundedPool:
"""Pool using BoundedSemaphore (prevents over-release)."""
def __init__(self, size: int) -> None:
self._size: int = size
self._semaphore: threading.BoundedSemaphore = threading.BoundedSemaphore(size)
self._acquired: int = 0
self._lock: threading.Lock = threading.Lock()
def acquire(self) -> bool:
"""Acquire resource."""
acquired = self._semaphore.acquire(blocking=False)
if acquired:
with self._lock:
self._acquired += 1
return acquired
def release(self) -> bool:
"""Release resource (bounded - can't over-release)."""
with self._lock:
if self._acquired > 0:
self._acquired -= 1
self._semaphore.release()
return True
return False
def acquired_count(self) -> int:
"""Get acquired count."""
with self._lock:
return self._acquired
class ConnectionPool:
"""Simulated connection pool."""
def __init__(self, max_connections: int) -> None:
self._max: int = max_connections
self._semaphore: threading.Semaphore = threading.Semaphore(max_connections)
self._connections: list[int] = []
self._next_id: int = 1
self._lock: threading.Lock = threading.Lock()
def connect(self) -> int | None:
"""Get a connection."""
if self._semaphore.acquire(blocking=False):
with self._lock:
conn_id = self._next_id
self._next_id += 1
self._connections.append(conn_id)
return conn_id
return None
def disconnect(self, conn_id: int) -> bool:
"""Release a connection."""
with self._lock:
if conn_id in self._connections:
self._connections.remove(conn_id)
self._semaphore.release()
return True
return False
def active_connections(self) -> list[int]:
"""Get active connection IDs."""
with self._lock:
return self._connections.copy()
class RateLimiter:
"""Simple rate limiter using semaphore."""
def __init__(self, max_concurrent: int) -> None:
self._semaphore: threading.Semaphore = threading.Semaphore(max_concurrent)
self._active: int = 0
self._total: int = 0
self._lock: threading.Lock = threading.Lock()
def try_acquire(self) -> bool:
"""Try to acquire a slot."""
if self._semaphore.acquire(blocking=False):
with self._lock:
self._active += 1
self._total += 1
return True
return False
def release(self) -> None:
"""Release a slot."""
with self._lock:
if self._active > 0:
self._active -= 1
self._semaphore.release()
def active(self) -> int:
"""Get active count."""
with self._lock:
return self._active
def total_acquired(self) -> int:
"""Get total acquisitions."""
with self._lock:
return self._total
def semaphore_count(permits: int, acquires: int, releases: int) -> int:
"""Simulate semaphore operations and return available count."""
sem = threading.Semaphore(permits)
acquired = 0
for _ in range(acquires):
if sem.acquire(blocking=False):
acquired += 1
released = min(releases, acquired)
for _ in range(released):
sem.release()
return permits - acquired + released
def simulate_pool(size: int, ops: list[str]) -> list[int]:
"""Simulate pool operations."""
pool = ResourcePool(size)
results: list[int] = []
for op in ops:
if op == "acquire":
pool.acquire()
elif op == "release":
pool.release()
elif op == "available":
results.append(pool.available())
return results
def simulate_connections(max_conn: int, ops: list[str]) -> list[int]:
"""Simulate connection pool."""
pool = ConnectionPool(max_conn)
conn_map: dict[str, int] = {}
results: list[int] = []
for op in ops:
if op.startswith("connect:"):
name = op.split(":")[1]
conn_id = pool.connect()
if conn_id is not None:
conn_map[name] = conn_id
results.append(conn_id)
elif op.startswith("disconnect:"):
name = op.split(":")[1]
if name in conn_map:
pool.disconnect(conn_map[name])
del conn_map[name]
elif op == "count":
results.append(len(pool.active_connections()))
return results
def bounded_test(size: int, acquires: int, releases: int) -> tuple[int, int]:
"""Test bounded semaphore behavior."""
pool = BoundedPool(size)
for _ in range(acquires):
pool.acquire()
successful_releases = 0
for _ in range(releases):
if pool.release():
successful_releases += 1
return (pool.acquired_count(), successful_releases)
def main() -> int:
parser = argparse.ArgumentParser(description="Thread semaphore CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# pool
pool_p = subparsers.add_parser("pool", help="Resource pool")
pool_p.add_argument("--size", type=int, default=5)
pool_p.add_argument("ops", nargs="+")
# connections
conn_p = subparsers.add_parser("connections", help="Connection pool")
conn_p.add_argument("--max", type=int, default=3)
conn_p.add_argument("ops", nargs="+")
# bounded
bounded_p = subparsers.add_parser("bounded", help="Bounded semaphore test")
bounded_p.add_argument("size", type=int)
bounded_p.add_argument("acquires", type=int)
bounded_p.add_argument("releases", type=int)
args = parser.parse_args()
if args.command == "pool":
results = simulate_pool(args.size, args.ops)
print(f"Available: {results}")
elif args.command == "connections":
results = simulate_connections(args.max, args.ops)
print(f"Results: {results}")
elif args.command == "bounded":
acquired, released = bounded_test(args.size, args.acquires, args.releases)
print(f"Acquired: {acquired}, Released: {released}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_thread_semaphore/thread_semaphore_cli.py (7624 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_thread_semaphore/thread_semaphore_cli.rs (11246 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_thread_semaphore/Cargo.toml (1 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 134.9 KB/s
⏱️ Total time: 55ms
| true
|
thread_semaphore
| 263
| 6
|
[
"context_manager",
"class_definition",
"multiprocessing"
] | 0.652
| null |
example_time
|
test_time_stdlib_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for time CLI."""
import subprocess
SCRIPT = "time_stdlib_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestTime:
def test_seconds(self): r = run(["seconds", "60"]); assert r.returncode == 0 and "1" in r.stdout
def test_minutes(self): r = run(["minutes", "3600"]); assert r.returncode == 0 and "60" in r.stdout
def test_hours(self): r = run(["hours", "7200"]); assert r.returncode == 0 and "2" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_time/test_time_stdlib_tool.py (643 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_time/test_time_stdlib_tool.rs (1902 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 12.8 KB/s
⏱️ Total time: 49ms
| true
|
time
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_time
|
time_stdlib_tool.py
|
#!/usr/bin/env python3
"""Time Example - Time conversion CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Time conversion tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("seconds")
s.add_argument("secs", type=int)
m = subs.add_parser("minutes")
m.add_argument("secs", type=int)
h = subs.add_parser("hours")
h.add_argument("secs", type=int)
args = parser.parse_args()
if args.cmd == "seconds":
print(args.secs // 60)
elif args.cmd == "minutes":
print(args.secs // 60)
elif args.cmd == "hours":
print(args.secs // 3600)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_time/time_stdlib_tool.py (703 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_time/time_stdlib_tool.rs (2938 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_time/Cargo.toml (1 dependencies)
⏱️ Parse time: 52ms
📊 Throughput: 13.2 KB/s
⏱️ Total time: 52ms
| true
|
time
| 28
| 6
|
[] | 0
| null |
example_timeout_handler
|
test_timeout_cli.py
|
"""Tests for timeout_cli.py"""
import time
from datetime import datetime, timedelta
import pytest
from timeout_cli import (
Deadline,
Timeout,
TimeoutGroup,
calculate_progress,
format_duration,
format_progress_bar,
parse_duration,
)
class TestParseDuration:
def test_seconds(self):
assert parse_duration("30s") == 30.0
assert parse_duration("30") == 30.0
def test_minutes(self):
assert parse_duration("5m") == 300.0
def test_hours(self):
assert parse_duration("2h") == 7200.0
def test_days(self):
assert parse_duration("1d") == 86400.0
def test_combined(self):
assert parse_duration("1h30m") == 5400.0
assert parse_duration("1d12h") == 129600.0
def test_decimal(self):
assert parse_duration("1.5h") == 5400.0
def test_invalid(self):
with pytest.raises(ValueError):
parse_duration("invalid")
class TestFormatDuration:
def test_seconds(self):
assert "s" in format_duration(30)
def test_minutes(self):
result = format_duration(90)
assert "m" in result
assert "s" in result
def test_hours(self):
result = format_duration(3700)
assert "h" in result
assert "m" in result
def test_days(self):
result = format_duration(100000)
assert "d" in result
def test_expired(self):
assert format_duration(-1) == "expired"
class TestTimeout:
def test_init(self):
timeout = Timeout(10.0)
assert timeout.duration == 10.0
assert timeout.elapsed() < 1.0
def test_remaining(self):
timeout = Timeout(10.0)
assert 9.0 <= timeout.remaining() <= 10.0
def test_is_expired_false(self):
timeout = Timeout(10.0)
assert timeout.is_expired() is False
def test_is_expired_true(self):
timeout = Timeout(0.01)
time.sleep(0.02)
assert timeout.is_expired() is True
def test_deadline(self):
timeout = Timeout(60.0)
deadline = timeout.deadline()
assert isinstance(deadline, datetime)
# Deadline should be about 60 seconds from now
delta = deadline - datetime.now()
assert 59 <= delta.total_seconds() <= 61
def test_extend(self):
timeout = Timeout(10.0)
timeout.extend(5.0)
assert timeout.duration == 15.0
def test_reset(self):
timeout = Timeout(10.0)
time.sleep(0.1)
old_elapsed = timeout.elapsed()
timeout.reset()
new_elapsed = timeout.elapsed()
assert new_elapsed < old_elapsed
class TestDeadline:
def test_init_datetime(self):
future = datetime.now() + timedelta(hours=1)
deadline = Deadline(future)
assert deadline.deadline_time == future
def test_init_string(self):
deadline = Deadline("2099-12-31T23:59:59")
assert deadline.deadline_time.year == 2099
def test_remaining(self):
future = datetime.now() + timedelta(seconds=60)
deadline = Deadline(future)
assert 59 <= deadline.remaining() <= 61
def test_is_expired(self):
past = datetime.now() - timedelta(seconds=1)
deadline = Deadline(past)
assert deadline.is_expired() is True
future = datetime.now() + timedelta(hours=1)
deadline = Deadline(future)
assert deadline.is_expired() is False
def test_to_timeout(self):
future = datetime.now() + timedelta(seconds=60)
deadline = Deadline(future)
timeout = deadline.to_timeout()
assert isinstance(timeout, Timeout)
assert 58 <= timeout.duration <= 62
class TestCalculateProgress:
def test_zero(self):
assert calculate_progress(0, 100) == 0.0
def test_half(self):
assert calculate_progress(50, 100) == 50.0
def test_full(self):
assert calculate_progress(100, 100) == 100.0
def test_over(self):
assert calculate_progress(150, 100) == 100.0
def test_zero_total(self):
assert calculate_progress(50, 0) == 100.0
class TestFormatProgressBar:
def test_zero(self):
bar = format_progress_bar(0, 10)
assert "░" * 10 in bar
def test_full(self):
bar = format_progress_bar(100, 10)
assert "█" * 10 in bar
def test_half(self):
bar = format_progress_bar(50, 10)
assert "█" * 5 in bar
class TestTimeoutGroup:
def test_add(self):
group = TimeoutGroup()
timeout = group.add("test", 10.0)
assert timeout.duration == 10.0
assert "test" in group.timeouts
def test_get(self):
group = TimeoutGroup()
group.add("test", 10.0)
timeout = group.get("test")
assert timeout is not None
assert timeout.duration == 10.0
def test_get_missing(self):
group = TimeoutGroup()
assert group.get("nonexistent") is None
def test_check(self):
group = TimeoutGroup()
group.add("test", 10.0)
assert group.check("test") is False
def test_check_missing(self):
group = TimeoutGroup()
assert group.check("nonexistent") is True
def test_remove(self):
group = TimeoutGroup()
group.add("test", 10.0)
assert group.remove("test") is True
assert group.get("test") is None
def test_cleanup_expired(self):
group = TimeoutGroup()
group.add("short", 0.01)
group.add("long", 10.0)
time.sleep(0.02)
expired = group.cleanup_expired()
assert "short" in expired
assert "long" not in expired
def test_first_to_expire(self):
group = TimeoutGroup()
group.add("long", 10.0)
group.add("short", 1.0)
first = group.first_to_expire()
assert first is not None
assert first[0] == "short"
def test_first_to_expire_empty(self):
group = TimeoutGroup()
assert group.first_to_expire() is None
| false
|
timeout_handler
| 225
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: add() requires exactly one argument
|
|
example_timeout_handler
|
timeout_cli.py
|
#!/usr/bin/env python3
"""Timeout handler CLI.
Timeout management and deadline tracking.
"""
import argparse
import sys
import time
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Timeout:
"""Represents a timeout."""
duration: float # seconds
started_at: float
def __init__(self, duration: float):
self.duration = duration
self.started_at = time.time()
def elapsed(self) -> float:
"""Get elapsed time in seconds."""
return time.time() - self.started_at
def remaining(self) -> float:
"""Get remaining time in seconds."""
return max(0, self.duration - self.elapsed())
def is_expired(self) -> bool:
"""Check if timeout has expired."""
return self.elapsed() >= self.duration
def deadline(self) -> datetime:
"""Get deadline as datetime."""
return datetime.fromtimestamp(self.started_at + self.duration)
def extend(self, seconds: float) -> None:
"""Extend the timeout."""
self.duration += seconds
def reset(self) -> None:
"""Reset the timeout."""
self.started_at = time.time()
@dataclass
class Deadline:
"""Represents an absolute deadline."""
deadline_time: datetime
def __init__(self, deadline_time: datetime | str):
if isinstance(deadline_time, str):
self.deadline_time = datetime.fromisoformat(deadline_time)
else:
self.deadline_time = deadline_time
def remaining(self) -> float:
"""Get remaining time in seconds."""
delta = self.deadline_time - datetime.now()
return max(0, delta.total_seconds())
def is_expired(self) -> bool:
"""Check if deadline has passed."""
return datetime.now() >= self.deadline_time
def to_timeout(self) -> Timeout:
"""Convert to a Timeout."""
remaining = self.remaining()
return Timeout(remaining)
def parse_duration(duration_str: str) -> float:
"""Parse duration string to seconds.
Formats: 30s, 5m, 2h, 1d, or combinations like 1h30m
"""
total_seconds = 0.0
# Simple number = seconds
try:
return float(duration_str)
except ValueError:
pass
# Parse units
import re
pattern = r"(\d+(?:\.\d+)?)\s*([smhd])"
matches = re.findall(pattern, duration_str.lower())
if not matches:
raise ValueError(f"Invalid duration: {duration_str}")
for value, unit in matches:
value = float(value)
if unit == "s":
total_seconds += value
elif unit == "m":
total_seconds += value * 60
elif unit == "h":
total_seconds += value * 3600
elif unit == "d":
total_seconds += value * 86400
return total_seconds
def format_duration(seconds: float) -> str:
"""Format seconds as human-readable duration."""
if seconds < 0:
return "expired"
if seconds < 60:
return f"{seconds:.1f}s"
if seconds < 3600:
mins = int(seconds // 60)
secs = int(seconds % 60)
return f"{mins}m {secs}s"
if seconds < 86400:
hours = int(seconds // 3600)
mins = int((seconds % 3600) // 60)
return f"{hours}h {mins}m"
days = int(seconds // 86400)
hours = int((seconds % 86400) // 3600)
return f"{days}d {hours}h"
def calculate_progress(elapsed: float, total: float) -> float:
"""Calculate progress percentage."""
if total <= 0:
return 100.0
return min(100.0, (elapsed / total) * 100)
def format_progress_bar(progress: float, width: int = 30) -> str:
"""Format progress as a bar."""
filled = int(width * progress / 100)
bar = "█" * filled + "░" * (width - filled)
return f"[{bar}] {progress:.1f}%"
class TimeoutGroup:
"""Manage multiple named timeouts."""
def __init__(self):
self.timeouts: dict[str, Timeout] = {}
def add(self, name: str, duration: float) -> Timeout:
"""Add a new timeout."""
timeout = Timeout(duration)
self.timeouts[name] = timeout
return timeout
def get(self, name: str) -> Timeout | None:
"""Get a timeout by name."""
return self.timeouts.get(name)
def check(self, name: str) -> bool:
"""Check if a timeout is expired."""
timeout = self.get(name)
if timeout is None:
return True # Non-existent = expired
return timeout.is_expired()
def remove(self, name: str) -> bool:
"""Remove a timeout."""
if name in self.timeouts:
del self.timeouts[name]
return True
return False
def cleanup_expired(self) -> list[str]:
"""Remove expired timeouts."""
expired = [name for name, t in self.timeouts.items() if t.is_expired()]
for name in expired:
del self.timeouts[name]
return expired
def first_to_expire(self) -> tuple[str, Timeout] | None:
"""Get the timeout that will expire first."""
active = [(name, t) for name, t in self.timeouts.items() if not t.is_expired()]
if not active:
return None
return min(active, key=lambda x: x[1].remaining())
def main() -> int:
parser = argparse.ArgumentParser(description="Timeout and deadline management")
parser.add_argument("duration", nargs="?", help="Timeout duration (e.g., 30s, 5m, 1h)")
parser.add_argument("--deadline", metavar="TIME", help="Absolute deadline (ISO format)")
parser.add_argument("--check", action="store_true", help="Check remaining time")
parser.add_argument("--progress", action="store_true", help="Show progress bar")
parser.add_argument("--wait", action="store_true", help="Wait until timeout expires")
parser.add_argument("--countdown", action="store_true", help="Show countdown")
parser.add_argument("--parse", action="store_true", help="Just parse and show duration")
args = parser.parse_args()
# Parse duration or deadline
if args.deadline:
try:
deadline = Deadline(args.deadline)
timeout = deadline.to_timeout()
except ValueError as e:
print(f"Invalid deadline: {e}", file=sys.stderr)
return 1
elif args.duration:
try:
duration = parse_duration(args.duration)
timeout = Timeout(duration)
except ValueError as e:
print(f"Invalid duration: {e}", file=sys.stderr)
return 1
else:
parser.print_help()
return 1
if args.parse:
print(f"Duration: {timeout.duration:.2f} seconds")
print(f"Formatted: {format_duration(timeout.duration)}")
return 0
if args.wait:
print(f"Waiting {format_duration(timeout.duration)}...")
while not timeout.is_expired():
time.sleep(0.1)
print("Timeout expired")
return 0
if args.countdown:
try:
while not timeout.is_expired():
remaining = timeout.remaining()
progress = calculate_progress(timeout.elapsed(), timeout.duration)
bar = format_progress_bar(progress)
print(f"\r{bar} {format_duration(remaining)} remaining", end="")
time.sleep(0.1)
print(f"\r{format_progress_bar(100.0)} Timeout expired! ")
except KeyboardInterrupt:
print("\nCancelled")
return 1
return 0
if args.progress:
progress = calculate_progress(timeout.elapsed(), timeout.duration)
print(format_progress_bar(progress))
return 0
# Default: show status
print(f"Duration: {format_duration(timeout.duration)}")
print(f"Elapsed: {format_duration(timeout.elapsed())}")
print(f"Remaining: {format_duration(timeout.remaining())}")
print(f"Deadline: {timeout.deadline().isoformat()}")
print(f"Expired: {timeout.is_expired()}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_timeout_handler/timeout_cli.py (8040 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_timeout_handler/timeout_cli.rs (14567 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_timeout_handler/Cargo.toml (3 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 141.7 KB/s
⏱️ Total time: 55ms
| true
|
timeout_handler
| 268
| 6
|
[
"lambda",
"class_definition",
"exception_handling",
"decorator"
] | 0.783
| null |
example_timestamp_diff
|
test_tsdiff_cli.py
|
"""Tests for tsdiff_cli.py"""
from datetime import datetime, timedelta
from tsdiff_cli import (
add_duration,
compare_timestamps,
duration_breakdown,
format_duration,
from_unix_timestamp,
parse_timestamp,
subtract_duration,
to_unix_timestamp,
)
class TestParseTimestamp:
def test_iso_format(self):
result = parse_timestamp("2023-12-25 14:30:00")
assert result is not None
assert result.year == 2023
assert result.month == 12
assert result.day == 25
assert result.hour == 14
def test_iso_t_format(self):
result = parse_timestamp("2023-12-25T14:30:00")
assert result is not None
assert result.hour == 14
def test_date_only(self):
result = parse_timestamp("2023-12-25")
assert result is not None
assert result.hour == 0
def test_unix_timestamp(self):
result = parse_timestamp("1703512200")
assert result is not None
def test_unix_milliseconds(self):
result = parse_timestamp("1703512200000")
assert result is not None
def test_invalid(self):
assert parse_timestamp("not a timestamp") is None
class TestFormatDuration:
def test_seconds(self):
td = timedelta(seconds=45)
result = format_duration(td)
assert "45s" in result
def test_minutes(self):
td = timedelta(minutes=5, seconds=30)
result = format_duration(td)
assert "5m" in result
assert "30s" in result
def test_hours(self):
td = timedelta(hours=2, minutes=30)
result = format_duration(td)
assert "2h" in result
assert "30m" in result
def test_days(self):
td = timedelta(days=3, hours=12)
result = format_duration(td)
assert "3d" in result
assert "12h" in result
def test_negative(self):
td = timedelta(seconds=-100)
result = format_duration(td)
# Should format absolute value
assert "s" in result
def test_milliseconds(self):
td = timedelta(seconds=1, milliseconds=500)
result = format_duration(td, precision="milliseconds")
assert "500" in result
class TestDurationBreakdown:
def test_simple(self):
td = timedelta(days=1, hours=2, minutes=3, seconds=4)
result = duration_breakdown(td)
assert result["days"] == 1
assert result["hours"] == 2
assert result["minutes"] == 3
assert result["seconds"] == 4
def test_totals(self):
td = timedelta(hours=48)
result = duration_breakdown(td)
assert result["total_days"] == 2.0
assert result["total_hours"] == 48.0
class TestUnixTimestamp:
def test_to_unix(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = to_unix_timestamp(dt)
assert isinstance(result, int)
def test_from_unix(self):
# Known timestamp
ts = 1703505600 # 2023-12-25 12:00:00 UTC (approximately)
result = from_unix_timestamp(ts)
assert result.year == 2023
def test_roundtrip(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
ts = to_unix_timestamp(dt)
result = from_unix_timestamp(ts)
assert result == dt
class TestAddDuration:
def test_add_days(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = add_duration(dt, "2d")
assert result is not None
assert result.day == 27
def test_add_hours(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = add_duration(dt, "5h")
assert result is not None
assert result.hour == 17
def test_add_mixed(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = add_duration(dt, "1d2h30m")
assert result is not None
assert result.day == 26
assert result.hour == 14
assert result.minute == 30
def test_invalid(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = add_duration(dt, "invalid")
assert result is None
class TestSubtractDuration:
def test_subtract_days(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = subtract_duration(dt, "2d")
assert result is not None
assert result.day == 23
def test_subtract_hours(self):
dt = datetime(2023, 12, 25, 12, 0, 0)
result = subtract_duration(dt, "5h")
assert result is not None
assert result.hour == 7
class TestCompareTimestamps:
def test_ts2_after(self):
ts1 = datetime(2023, 12, 25, 12, 0, 0)
ts2 = datetime(2023, 12, 26, 12, 0, 0)
result = compare_timestamps(ts1, ts2)
assert result["is_after"] is True
assert result["breakdown"]["total_days"] == 1.0
def test_ts2_before(self):
ts1 = datetime(2023, 12, 26, 12, 0, 0)
ts2 = datetime(2023, 12, 25, 12, 0, 0)
result = compare_timestamps(ts1, ts2)
assert result["is_after"] is False
def test_same(self):
ts1 = datetime(2023, 12, 25, 12, 0, 0)
ts2 = datetime(2023, 12, 25, 12, 0, 0)
result = compare_timestamps(ts1, ts2)
assert result["is_same"] is True
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/test_tsdiff_cli.py (5195 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/test_tsdiff_cli.rs (8987 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/Cargo.toml (1 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 99.5 KB/s
⏱️ Total time: 51ms
| true
|
timestamp_diff
| 178
| 6
|
[
"class_definition"
] | 0.612
| null |
example_timestamp_diff
|
tsdiff_cli.py
|
#!/usr/bin/env python3
"""Timestamp difference calculator CLI.
Calculate differences between timestamps in various formats.
"""
import argparse
import re
import sys
from datetime import datetime, timedelta
def parse_timestamp(ts: str) -> datetime | None:
"""Parse various timestamp formats."""
ts = ts.strip()
# Unix timestamp (seconds since epoch)
if ts.isdigit() and len(ts) >= 10:
try:
if len(ts) == 10:
return datetime.fromtimestamp(int(ts))
elif len(ts) == 13: # Milliseconds
return datetime.fromtimestamp(int(ts) / 1000)
elif len(ts) == 16: # Microseconds
return datetime.fromtimestamp(int(ts) / 1000000)
except (ValueError, OSError):
pass
# Try various formats
formats = [
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%d",
"%d/%m/%Y %H:%M:%S",
"%m/%d/%Y %H:%M:%S",
"%d-%m-%Y %H:%M:%S",
]
for fmt in formats:
try:
return datetime.strptime(ts, fmt)
except ValueError:
continue
# Try ISO format with timezone
iso_match = re.match(r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})([+-]\d{2}:?\d{2})?", ts)
if iso_match:
try:
return datetime.fromisoformat(iso_match.group(1))
except ValueError:
pass
return None
def format_duration(td: timedelta, precision: str = "seconds") -> str:
"""Format timedelta as human-readable duration."""
total_seconds = abs(td.total_seconds())
days = int(total_seconds // 86400)
hours = int((total_seconds % 86400) // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
milliseconds = int((total_seconds * 1000) % 1000)
parts = []
if days > 0:
parts.append(f"{days}d")
if hours > 0 or days > 0:
parts.append(f"{hours}h")
if minutes > 0 or hours > 0 or days > 0:
parts.append(f"{minutes}m")
if precision == "milliseconds":
parts.append(f"{seconds}.{milliseconds:03d}s")
elif precision == "seconds":
parts.append(f"{seconds}s")
elif precision == "minutes" and not parts:
# Show at least minutes
parts.append(f"{minutes}m")
return " ".join(parts) if parts else "0s"
def duration_breakdown(td: timedelta) -> dict:
"""Break down timedelta into components."""
total_seconds = abs(td.total_seconds())
return {
"total_seconds": total_seconds,
"total_minutes": total_seconds / 60,
"total_hours": total_seconds / 3600,
"total_days": total_seconds / 86400,
"days": int(total_seconds // 86400),
"hours": int((total_seconds % 86400) // 3600),
"minutes": int((total_seconds % 3600) // 60),
"seconds": int(total_seconds % 60),
"milliseconds": int((total_seconds * 1000) % 1000),
}
def to_unix_timestamp(dt: datetime) -> int:
"""Convert datetime to Unix timestamp."""
return int(dt.timestamp())
def from_unix_timestamp(ts: int) -> datetime:
"""Convert Unix timestamp to datetime."""
return datetime.fromtimestamp(ts)
def add_duration(dt: datetime, duration_str: str) -> datetime | None:
"""Add duration string to datetime.
Format: 1d2h3m4s
"""
total_seconds = 0
# Parse duration parts
pattern = r"(\d+)([dhms])"
matches = re.findall(pattern, duration_str.lower())
if not matches:
return None
for value, unit in matches:
value = int(value)
if unit == "d":
total_seconds += value * 86400
elif unit == "h":
total_seconds += value * 3600
elif unit == "m":
total_seconds += value * 60
elif unit == "s":
total_seconds += value
return dt + timedelta(seconds=total_seconds)
def subtract_duration(dt: datetime, duration_str: str) -> datetime | None:
"""Subtract duration string from datetime."""
total_seconds = 0
pattern = r"(\d+)([dhms])"
matches = re.findall(pattern, duration_str.lower())
if not matches:
return None
for value, unit in matches:
value = int(value)
if unit == "d":
total_seconds += value * 86400
elif unit == "h":
total_seconds += value * 3600
elif unit == "m":
total_seconds += value * 60
elif unit == "s":
total_seconds += value
return dt - timedelta(seconds=total_seconds)
def compare_timestamps(ts1: datetime, ts2: datetime) -> dict:
"""Compare two timestamps."""
diff = ts2 - ts1
is_after = ts2 > ts1
is_same = ts1 == ts2
return {
"difference": diff,
"is_after": is_after,
"is_same": is_same,
"breakdown": duration_breakdown(diff),
}
def main() -> int:
parser = argparse.ArgumentParser(description="Calculate timestamp differences")
parser.add_argument("timestamp1", help="First timestamp")
parser.add_argument("timestamp2", nargs="?", help="Second timestamp (default: now)")
parser.add_argument(
"--add", metavar="DURATION", help="Add duration to timestamp (e.g., 1d2h30m)"
)
parser.add_argument("--sub", metavar="DURATION", help="Subtract duration from timestamp")
parser.add_argument("--unix", action="store_true", help="Output as Unix timestamp")
parser.add_argument("--breakdown", action="store_true", help="Show detailed breakdown")
parser.add_argument("--json", action="store_true", help="Output as JSON")
args = parser.parse_args()
# Parse first timestamp
ts1 = parse_timestamp(args.timestamp1)
if not ts1:
print(f"Invalid timestamp: {args.timestamp1}", file=sys.stderr)
return 1
# Handle add/subtract
if args.add:
result = add_duration(ts1, args.add)
if not result:
print(f"Invalid duration: {args.add}", file=sys.stderr)
return 1
if args.unix:
print(to_unix_timestamp(result))
else:
print(result.strftime("%Y-%m-%d %H:%M:%S"))
return 0
if args.sub:
result = subtract_duration(ts1, args.sub)
if not result:
print(f"Invalid duration: {args.sub}", file=sys.stderr)
return 1
if args.unix:
print(to_unix_timestamp(result))
else:
print(result.strftime("%Y-%m-%d %H:%M:%S"))
return 0
# Get second timestamp
if args.timestamp2:
ts2 = parse_timestamp(args.timestamp2)
if not ts2:
print(f"Invalid timestamp: {args.timestamp2}", file=sys.stderr)
return 1
else:
ts2 = datetime.now()
# Compare
comparison = compare_timestamps(ts1, ts2)
diff = comparison["difference"]
breakdown = comparison["breakdown"]
if args.json:
import json
output = {
"timestamp1": ts1.isoformat(),
"timestamp2": ts2.isoformat(),
"difference": {
"formatted": format_duration(diff),
"total_seconds": breakdown["total_seconds"],
"total_minutes": breakdown["total_minutes"],
"total_hours": breakdown["total_hours"],
"total_days": breakdown["total_days"],
},
"is_ts2_after_ts1": comparison["is_after"],
}
print(json.dumps(output, indent=2))
return 0
# Default output
sign = "" if diff.total_seconds() >= 0 else "-"
print(f"From: {ts1.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"To: {ts2.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Diff: {sign}{format_duration(diff)}")
if args.breakdown:
print("\nBreakdown:")
print(f" Days: {breakdown['days']}")
print(f" Hours: {breakdown['hours']}")
print(f" Minutes: {breakdown['minutes']}")
print(f" Seconds: {breakdown['seconds']}")
print("\nTotals:")
print(f" {breakdown['total_seconds']:.2f} seconds")
print(f" {breakdown['total_minutes']:.2f} minutes")
print(f" {breakdown['total_hours']:.2f} hours")
print(f" {breakdown['total_days']:.2f} days")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/tsdiff_cli.py (8379 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/tsdiff_cli.rs (20593 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_timestamp_diff/Cargo.toml (5 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 148.6 KB/s
⏱️ Total time: 55ms
| true
|
timestamp_diff
| 279
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_timezone_converter
|
test_tz_cli.py
|
"""Tests for tz_cli.py"""
from datetime import datetime, timedelta
from tz_cli import (
convert_time,
format_offset,
format_time,
get_current_time,
get_timezone,
list_timezones,
parse_time,
time_difference,
)
class TestGetTimezone:
def test_named_timezone(self):
tz = get_timezone("UTC")
assert tz is not None
assert tz.utcoffset(None) == timedelta(0)
def test_est(self):
tz = get_timezone("EST")
assert tz is not None
assert tz.utcoffset(None) == timedelta(hours=-5)
def test_positive_offset(self):
tz = get_timezone("+05:30")
assert tz is not None
assert tz.utcoffset(None) == timedelta(hours=5, minutes=30)
def test_negative_offset(self):
tz = get_timezone("-08:00")
assert tz is not None
assert tz.utcoffset(None) == timedelta(hours=-8)
def test_case_insensitive(self):
tz1 = get_timezone("utc")
tz2 = get_timezone("UTC")
assert tz1 == tz2
def test_invalid(self):
assert get_timezone("INVALID") is None
class TestParseTime:
def test_datetime_format(self):
result = parse_time("2023-12-25 14:30:00")
assert result is not None
assert result.year == 2023
assert result.month == 12
assert result.day == 25
assert result.hour == 14
assert result.minute == 30
def test_iso_format(self):
result = parse_time("2023-12-25T14:30:00")
assert result is not None
assert result.hour == 14
def test_time_only(self):
result = parse_time("14:30")
assert result is not None
assert result.hour == 14
assert result.minute == 30
# Should use today's date
today = datetime.now()
assert result.year == today.year
def test_with_timezone(self):
tz = get_timezone("EST")
result = parse_time("14:30", tz)
assert result is not None
assert result.tzinfo == tz
def test_invalid(self):
assert parse_time("not a time") is None
class TestConvertTime:
def test_utc_to_est(self):
utc = get_timezone("UTC")
est = get_timezone("EST")
dt = datetime(2023, 12, 25, 12, 0, 0, tzinfo=utc)
result = convert_time(dt, est)
assert result.hour == 7 # 12 UTC = 7 EST
def test_pst_to_jst(self):
pst = get_timezone("PST")
jst = get_timezone("JST")
dt = datetime(2023, 12, 25, 8, 0, 0, tzinfo=pst)
result = convert_time(dt, jst)
# PST (-8) to JST (+9) = +17 hours
# 8 + 17 = 25 = 1 (next day)
assert result.hour == 1
assert result.day == 26
class TestFormatTime:
def test_format_with_tz(self):
utc = get_timezone("UTC")
dt = datetime(2023, 12, 25, 14, 30, 0, tzinfo=utc)
result = format_time(dt)
assert "2023-12-25 14:30:00" in result
assert "+0000" in result
def test_format_without_tz(self):
dt = datetime(2023, 12, 25, 14, 30, 0)
result = format_time(dt, include_tz=False)
assert result == "2023-12-25 14:30:00"
class TestListTimezones:
def test_list_not_empty(self):
zones = list_timezones()
assert len(zones) > 0
def test_contains_common(self):
zones = list_timezones()
assert "UTC" in zones
assert "EST" in zones
assert "PST" in zones
class TestGetCurrentTime:
def test_returns_datetime(self):
utc = get_timezone("UTC")
result = get_current_time(utc)
assert isinstance(result, datetime)
assert result.tzinfo == utc
class TestTimeDifference:
def test_utc_to_est(self):
utc = get_timezone("UTC")
est = get_timezone("EST")
diff = time_difference(utc, est)
assert diff == timedelta(hours=-5)
def test_pst_to_jst(self):
pst = get_timezone("PST")
jst = get_timezone("JST")
diff = time_difference(pst, jst)
assert diff == timedelta(hours=17)
class TestFormatOffset:
def test_positive(self):
assert format_offset(timedelta(hours=5, minutes=30)) == "+05:30"
def test_negative(self):
assert format_offset(timedelta(hours=-8)) == "-08:00"
def test_zero(self):
assert format_offset(timedelta(0)) == "+00:00"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/test_tz_cli.py (4356 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/test_tz_cli.rs (7971 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 85.5 KB/s
⏱️ Total time: 50ms
| true
|
timezone_converter
| 159
| 6
|
[
"class_definition"
] | 0.612
| null |
example_timezone_converter
|
tz_cli.py
|
#!/usr/bin/env python3
"""Timezone converter CLI.
Convert times between timezones.
"""
import argparse
import sys
from datetime import UTC, datetime, timedelta, timezone
# Common timezone offsets (hours from UTC)
TIMEZONE_OFFSETS: dict[str, int] = {
"UTC": 0,
"GMT": 0,
"EST": -5,
"EDT": -4,
"CST": -6,
"CDT": -5,
"MST": -7,
"MDT": -6,
"PST": -8,
"PDT": -7,
"CET": 1,
"CEST": 2,
"JST": 9,
"IST": 5, # India (5:30 but simplified)
"AEST": 10,
"AEDT": 11,
}
def get_timezone(name: str) -> timezone | None:
"""Get timezone from name or offset string."""
name = name.upper()
if name in TIMEZONE_OFFSETS:
hours = TIMEZONE_OFFSETS[name]
return timezone(timedelta(hours=hours))
# Parse offset format like +05:30 or -08:00
if name.startswith("+") or name.startswith("-"):
try:
sign = 1 if name[0] == "+" else -1
parts = name[1:].split(":")
hours = int(parts[0])
minutes = int(parts[1]) if len(parts) > 1 else 0
total_minutes = sign * (hours * 60 + minutes)
return timezone(timedelta(minutes=total_minutes))
except (ValueError, IndexError):
return None
return None
def parse_time(time_str: str, tz: timezone | None = None) -> datetime | None:
"""Parse time string into datetime."""
formats = [
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M",
"%H:%M:%S",
"%H:%M",
]
for fmt in formats:
try:
dt = datetime.strptime(time_str, fmt)
# If only time provided, use today's date
if dt.year == 1900:
now = datetime.now()
dt = dt.replace(year=now.year, month=now.month, day=now.day)
if tz:
dt = dt.replace(tzinfo=tz)
return dt
except ValueError:
continue
return None
def convert_time(dt: datetime, to_tz: timezone) -> datetime:
"""Convert datetime to different timezone."""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
return dt.astimezone(to_tz)
def format_time(dt: datetime, include_tz: bool = True) -> str:
"""Format datetime for display."""
base = dt.strftime("%Y-%m-%d %H:%M:%S")
if include_tz and dt.tzinfo:
offset = dt.strftime("%z")
return f"{base} {offset}"
return base
def list_timezones() -> list[str]:
"""List available timezone names."""
return sorted(TIMEZONE_OFFSETS.keys())
def get_current_time(tz: timezone) -> datetime:
"""Get current time in specified timezone."""
return datetime.now(tz)
def time_difference(tz1: timezone, tz2: timezone) -> timedelta:
"""Calculate difference between two timezones."""
now = datetime.now(UTC)
t1 = now.astimezone(tz1)
t2 = now.astimezone(tz2)
# Get offset difference
offset1 = t1.utcoffset() or timedelta(0)
offset2 = t2.utcoffset() or timedelta(0)
return offset2 - offset1
def format_offset(td: timedelta) -> str:
"""Format timedelta as offset string."""
total_seconds = int(td.total_seconds())
sign = "+" if total_seconds >= 0 else "-"
total_seconds = abs(total_seconds)
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
return f"{sign}{hours:02d}:{minutes:02d}"
def main() -> int:
parser = argparse.ArgumentParser(description="Convert times between timezones")
parser.add_argument("time", nargs="?", help="Time to convert (or 'now')")
parser.add_argument("-f", "--from", dest="from_tz", default="UTC", help="Source timezone")
parser.add_argument("-t", "--to", dest="to_tz", default="UTC", help="Target timezone")
parser.add_argument("--list", action="store_true", help="List available timezones")
parser.add_argument("--diff", action="store_true", help="Show time difference between zones")
args = parser.parse_args()
if args.list:
print("Available timezones:")
for tz_name in list_timezones():
offset = TIMEZONE_OFFSETS[tz_name]
sign = "+" if offset >= 0 else ""
print(f" {tz_name:<6} {sign}{offset:>3}:00")
return 0
from_tz = get_timezone(args.from_tz)
to_tz = get_timezone(args.to_tz)
if not from_tz:
print(f"Unknown timezone: {args.from_tz}", file=sys.stderr)
return 1
if not to_tz:
print(f"Unknown timezone: {args.to_tz}", file=sys.stderr)
return 1
if args.diff:
diff = time_difference(from_tz, to_tz)
offset = format_offset(diff)
print(f"{args.to_tz} is {offset} from {args.from_tz}")
return 0
# Get time to convert
if not args.time or args.time.lower() == "now":
dt = get_current_time(from_tz)
else:
dt = parse_time(args.time, from_tz)
if not dt:
print(f"Invalid time format: {args.time}", file=sys.stderr)
return 1
# Convert and display
result = convert_time(dt, to_tz)
print(f"{args.from_tz}: {format_time(dt)}")
print(f"{args.to_tz}: {format_time(result)}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/tz_cli.py (5244 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/tz_cli.rs (11352 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_timezone_converter/Cargo.toml (3 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 92.9 KB/s
⏱️ Total time: 55ms
| true
|
timezone_converter
| 181
| 6
|
[
"exception_handling"
] | 0.577
| null |
example_toml_reader
|
test_toml_cli.py
|
"""Tests for toml_cli.py"""
from toml_cli import (
flatten_toml,
format_value,
get_nested,
list_keys,
parse_toml,
parse_value,
)
SAMPLE_TOML = """
# Sample config
[database]
host = "localhost"
port = 5432
enabled = true
[database.pool]
size = 10
timeout = 30.5
[server]
name = "myapp"
tags = ["web", "api"]
"""
class TestParseValue:
def test_string(self):
assert parse_value('"hello"') == "hello"
assert parse_value("'world'") == "world"
def test_integer(self):
assert parse_value("42") == 42
assert parse_value("-10") == -10
def test_float(self):
assert parse_value("3.14") == 3.14
def test_boolean(self):
assert parse_value("true") is True
assert parse_value("false") is False
def test_array(self):
assert parse_value("[1, 2, 3]") == [1, 2, 3]
assert parse_value('["a", "b"]') == ["a", "b"]
assert parse_value("[]") == []
class TestParseToml:
def test_sections(self):
data = parse_toml(SAMPLE_TOML)
assert "database" in data
assert "server" in data
def test_values(self):
data = parse_toml(SAMPLE_TOML)
assert data["database"]["host"] == "localhost"
assert data["database"]["port"] == 5432
assert data["database"]["enabled"] is True
def test_nested_sections(self):
data = parse_toml(SAMPLE_TOML)
assert data["database"]["pool"]["size"] == 10
assert data["database"]["pool"]["timeout"] == 30.5
def test_arrays(self):
data = parse_toml(SAMPLE_TOML)
assert data["server"]["tags"] == ["web", "api"]
def test_comments_ignored(self):
content = """
# This is a comment
[section]
key = "value"
"""
data = parse_toml(content)
assert data["section"]["key"] == "value"
class TestGetNested:
def test_simple_path(self):
data = parse_toml(SAMPLE_TOML)
assert get_nested(data, "database.host") == "localhost"
def test_deep_path(self):
data = parse_toml(SAMPLE_TOML)
assert get_nested(data, "database.pool.size") == 10
def test_section_path(self):
data = parse_toml(SAMPLE_TOML)
result = get_nested(data, "database.pool")
assert isinstance(result, dict)
assert result["size"] == 10
def test_missing_path(self):
data = parse_toml(SAMPLE_TOML)
assert get_nested(data, "nonexistent.path") is None
class TestListKeys:
def test_root_keys(self):
data = parse_toml(SAMPLE_TOML)
keys = list_keys(data)
assert "database" in keys
assert "server" in keys
def test_section_keys(self):
data = parse_toml(SAMPLE_TOML)
keys = list_keys(data, "database")
assert "host" in keys
assert "port" in keys
assert "pool" in keys
def test_nested_keys(self):
data = parse_toml(SAMPLE_TOML)
keys = list_keys(data, "database.pool")
assert "size" in keys
assert "timeout" in keys
class TestFlatten:
def test_flatten_simple(self):
data = {"a": 1, "b": 2}
result = flatten_toml(data)
assert ("a", "1") in result
assert ("b", "2") in result
def test_flatten_nested(self):
data = parse_toml(SAMPLE_TOML)
result = flatten_toml(data)
keys = [k for k, v in result]
assert "database.host" in keys
assert "database.pool.size" in keys
class TestFormatValue:
def test_format_string(self):
assert format_value("hello") == '"hello"'
def test_format_int(self):
assert format_value(42) == "42"
def test_format_bool(self):
assert format_value(True) == "true"
assert format_value(False) == "false"
def test_format_array(self):
assert format_value([1, 2, 3]) == "[1, 2, 3]"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_toml_reader/test_toml_cli.py (3858 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_toml_reader/test_toml_cli.rs (7995 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 75.3 KB/s
⏱️ Total time: 50ms
| true
|
toml_reader
| 150
| 5
|
[
"class_definition"
] | 0.612
| null |
example_toml_reader
|
toml_cli.py
|
#!/usr/bin/env python3
"""TOML file reader CLI.
Parse and query TOML configuration files (subset implementation).
"""
import argparse
import sys
def parse_value(value: str) -> str | int | float | bool | list:
"""Parse a TOML value string into Python type."""
value = value.strip()
# Boolean
if value == "true":
return True
if value == "false":
return False
# Integer
if value.isdigit() or (value.startswith("-") and value[1:].isdigit()):
return int(value)
# Float
if "." in value:
try:
return float(value)
except ValueError:
pass
# Array
if value.startswith("[") and value.endswith("]"):
inner = value[1:-1].strip()
if not inner:
return []
items = []
for item in inner.split(","):
items.append(parse_value(item.strip()))
return items
# String (quoted)
if value.startswith('"') and value.endswith('"'):
return value[1:-1]
if value.startswith("'") and value.endswith("'"):
return value[1:-1]
# Bare string
return value
def parse_toml(content: str) -> dict:
"""Parse TOML content into nested dict."""
result: dict = {}
current_section: list[str] = []
for line in content.split("\n"):
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith("#"):
continue
# Table header [section] or [section.subsection]
if line.startswith("[") and line.endswith("]"):
header = line[1:-1]
current_section = header.split(".")
# Initialize nested structure
target = result
for part in current_section:
if part not in target:
target[part] = {}
target = target[part]
continue
# Key = value pair
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# Navigate to current section
target = result
for part in current_section:
target = target[part]
target[key] = parse_value(value)
return result
def get_nested(data: dict, path: str) -> str | int | float | bool | list | dict | None:
"""Get a nested value using dot notation."""
parts = path.split(".")
current = data
for part in parts:
if not isinstance(current, dict):
return None
if part not in current:
return None
current = current[part]
return current
def list_keys(data: dict, path: str = "") -> list[str]:
"""List all keys at a given path."""
if path:
target = get_nested(data, path)
if not isinstance(target, dict):
return []
else:
target = data
return list(target.keys())
def flatten_toml(data: dict, prefix: str = "") -> list[tuple[str, str]]:
"""Flatten TOML data into list of (key, value) pairs."""
result = []
for key, value in data.items():
full_key = f"{prefix}.{key}" if prefix else key
if isinstance(value, dict):
result.extend(flatten_toml(value, full_key))
else:
result.append((full_key, str(value)))
return result
def format_value(value: str | int | float | bool | list) -> str:
"""Format a Python value as TOML."""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, str):
return f'"{value}"'
if isinstance(value, list):
items = [format_value(v) for v in value]
return "[" + ", ".join(items) + "]"
return str(value)
def main() -> int:
parser = argparse.ArgumentParser(description="TOML file reader and query tool")
parser.add_argument("input", nargs="?", help="Input TOML file (- for stdin)")
parser.add_argument("--get", metavar="PATH", help="Get value at path (e.g., database.host)")
parser.add_argument(
"--keys", metavar="PATH", nargs="?", const="", help="List keys at path (empty for root)"
)
parser.add_argument("--flatten", action="store_true", help="Output all key=value pairs")
parser.add_argument("--sections", action="store_true", help="List top-level sections")
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_toml(content)
# Perform operation
if args.get:
value = get_nested(data, args.get)
if value is None:
return 1
if isinstance(value, dict):
for k, v in value.items():
print(f"{k} = {format_value(v)}")
else:
print(value)
elif args.keys is not None:
for key in list_keys(data, args.keys):
print(key)
elif args.flatten:
for key, value in flatten_toml(data):
print(f"{key} = {value}")
elif args.sections:
for key in data.keys():
if isinstance(data[key], dict):
print(key)
else:
# Default: print flattened
for key, value in flatten_toml(data):
print(f"{key} = {value}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_toml_reader/toml_cli.py (5407 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_toml_reader/toml_cli.rs (18069 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_toml_reader/Cargo.toml (3 dependencies)
⏱️ Parse time: 54ms
📊 Throughput: 97.7 KB/s
⏱️ Total time: 54ms
| true
|
toml_reader
| 196
| 6
|
[
"context_manager",
"exception_handling",
"stdin_usage"
] | 0.652
| null |
example_tree_walker
|
test_tree_cli.py
|
"""Tests for tree_cli.py"""
import os
import tempfile
import pytest
from tree_cli import (
count_entries,
filter_by_extension,
format_size,
format_tree,
get_file_size,
total_size,
walk_directory,
)
@pytest.fixture
def temp_tree():
"""Create a temporary directory structure for testing."""
with tempfile.TemporaryDirectory() as tmpdir:
# Create structure:
# tmpdir/
# file1.txt (5 bytes)
# file2.py (10 bytes)
# subdir/
# file3.txt (3 bytes)
# .hidden/
# secret.txt (1 byte)
with open(os.path.join(tmpdir, "file1.txt"), "w") as f:
f.write("hello")
with open(os.path.join(tmpdir, "file2.py"), "w") as f:
f.write("0123456789")
os.makedirs(os.path.join(tmpdir, "subdir"))
with open(os.path.join(tmpdir, "subdir", "file3.txt"), "w") as f:
f.write("abc")
os.makedirs(os.path.join(tmpdir, ".hidden"))
with open(os.path.join(tmpdir, ".hidden", "secret.txt"), "w") as f:
f.write("x")
yield tmpdir
class TestFormatSize:
def test_bytes(self):
assert format_size(100) == "100B"
def test_kilobytes(self):
assert format_size(2048) == "2K"
def test_megabytes(self):
assert format_size(5 * 1024 * 1024) == "5M"
def test_gigabytes(self):
assert format_size(2 * 1024 * 1024 * 1024) == "2G"
class TestGetFileSize:
def test_existing_file(self, temp_tree):
path = os.path.join(temp_tree, "file1.txt")
assert get_file_size(path) == 5
def test_nonexistent_file(self):
assert get_file_size("/nonexistent/file") == 0
class TestWalkDirectory:
def test_basic_walk(self, temp_tree):
entries = walk_directory(temp_tree)
paths = [p for p, _, _ in entries]
assert any("file1.txt" in p for p in paths)
assert any("subdir" in p for p in paths)
def test_hidden_excluded(self, temp_tree):
entries = walk_directory(temp_tree, show_hidden=False)
paths = [p for p, _, _ in entries]
assert not any(".hidden" in p for p in paths)
def test_hidden_included(self, temp_tree):
entries = walk_directory(temp_tree, show_hidden=True)
paths = [p for p, _, _ in entries]
assert any(".hidden" in p for p in paths)
def test_max_depth(self, temp_tree):
entries = walk_directory(temp_tree, max_depth=0)
# Only immediate children
for _, depth, _ in entries:
assert depth == 0
def test_dirs_only(self, temp_tree):
entries = walk_directory(temp_tree, dirs_only=True)
for _, _, is_dir in entries:
assert is_dir
class TestFormatTree:
def test_format_basic(self, temp_tree):
entries = walk_directory(temp_tree)
lines = format_tree(entries, temp_tree)
assert len(lines) > 0
# Check for tree characters
assert any("├" in line or "└" in line for line in lines)
def test_format_with_size(self, temp_tree):
entries = walk_directory(temp_tree)
lines = format_tree(entries, temp_tree, show_size=True)
# Files should show size
assert any("B)" in line for line in lines)
class TestCountEntries:
def test_count(self, temp_tree):
entries = walk_directory(temp_tree)
dirs, files = count_entries(entries)
assert dirs == 1 # subdir (hidden excluded)
assert files == 3 # file1.txt, file2.py, subdir/file3.txt
class TestTotalSize:
def test_total(self, temp_tree):
entries = walk_directory(temp_tree)
size = total_size(entries)
# 5 + 10 + 3 = 18
assert size == 18
class TestFilterByExtension:
def test_filter_txt(self, temp_tree):
entries = walk_directory(temp_tree)
filtered = filter_by_extension(entries, ".txt")
files = [p for p, _, is_dir in filtered if not is_dir]
assert all(p.endswith(".txt") for p in files)
def test_filter_without_dot(self, temp_tree):
entries = walk_directory(temp_tree)
filtered = filter_by_extension(entries, "py")
files = [p for p, _, is_dir in filtered if not is_dir]
assert all(p.endswith(".py") for p in files)
| false
|
tree_walker
| 142
| 0
|
[
"generator",
"context_manager",
"class_definition",
"decorator"
] | 0.927
|
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 1
Total estimated allocations: 0
Functions analyzed: 1
Hot Paths
[1] temp_tree (100.0% of execution time)
Function Metrics
🔥 temp_tree 100.0% time | 1 inst | 0 alloc
Performance Predictions
• Rust's memory layout is more cache-friendly than Python (1.3x speedup, 70% confidence)
🚀 Estimated overall speedup: 1.3x
Error: join() requires exactly one
|
|
example_tree_walker
|
tree_cli.py
|
#!/usr/bin/env python3
"""Directory tree walker CLI.
Display and analyze directory structures.
"""
import argparse
import os
import sys
def get_file_size(path: str) -> int:
"""Get file size in bytes."""
try:
return os.path.getsize(path)
except OSError:
return 0
def format_size(size: int) -> str:
"""Format size in human-readable format."""
if size < 1024:
return f"{size}B"
if size < 1024 * 1024:
return f"{size // 1024}K"
if size < 1024 * 1024 * 1024:
return f"{size // (1024 * 1024)}M"
return f"{size // (1024 * 1024 * 1024)}G"
def walk_directory(
path: str,
max_depth: int = -1,
show_hidden: bool = False,
dirs_only: bool = False,
) -> list[tuple[str, int, bool]]:
"""Walk directory and return list of (path, depth, is_dir)."""
result = []
def walk(current_path: str, depth: int) -> None:
if max_depth >= 0 and depth > max_depth:
return
try:
entries = os.listdir(current_path)
except PermissionError:
return
entries.sort()
for entry in entries:
if not show_hidden and entry.startswith("."):
continue
full_path = os.path.join(current_path, entry)
is_dir = os.path.isdir(full_path)
if dirs_only and not is_dir:
continue
result.append((full_path, depth, is_dir))
if is_dir:
walk(full_path, depth + 1)
walk(path, 0)
return result
def format_tree(
entries: list[tuple[str, int, bool]],
base_path: str,
show_size: bool = False,
) -> list[str]:
"""Format entries as tree with box-drawing characters."""
lines = []
base_len = len(base_path.rstrip("/")) + 1
for i, (path, depth, is_dir) in enumerate(entries):
name = path[base_len:]
parts = name.split("/")
display_name = parts[-1]
# Determine prefix
prefix = ""
for _d in range(depth):
prefix += "│ "
# Check if last at this depth
is_last = True
for j in range(i + 1, len(entries)):
if entries[j][1] == depth:
is_last = False
break
if entries[j][1] < depth:
break
if is_last:
prefix += "└── "
else:
prefix += "├── "
# Format line
if show_size and not is_dir:
size = get_file_size(path)
line = f"{prefix}{display_name} ({format_size(size)})"
else:
line = f"{prefix}{display_name}"
if is_dir:
line += "/"
lines.append(line)
return lines
def count_entries(entries: list[tuple[str, int, bool]]) -> tuple[int, int]:
"""Count directories and files."""
dirs = sum(1 for _, _, is_dir in entries if is_dir)
files = sum(1 for _, _, is_dir in entries if not is_dir)
return dirs, files
def total_size(entries: list[tuple[str, int, bool]]) -> int:
"""Calculate total size of all files."""
total = 0
for path, _, is_dir in entries:
if not is_dir:
total += get_file_size(path)
return total
def filter_by_extension(
entries: list[tuple[str, int, bool]], ext: str
) -> list[tuple[str, int, bool]]:
"""Filter entries by file extension."""
if not ext.startswith("."):
ext = "." + ext
return [
(path, depth, is_dir) for path, depth, is_dir in entries if is_dir or path.endswith(ext)
]
def main() -> int:
parser = argparse.ArgumentParser(description="Display directory tree structure")
parser.add_argument("path", nargs="?", default=".", help="Directory to display")
parser.add_argument(
"-d", "--depth", type=int, default=-1, help="Maximum depth (-1 for unlimited)"
)
parser.add_argument("-a", "--all", action="store_true", help="Show hidden files")
parser.add_argument("--dirs", action="store_true", help="Show directories only")
parser.add_argument("-s", "--size", action="store_true", help="Show file sizes")
parser.add_argument("--ext", metavar="EXT", help="Filter by extension")
parser.add_argument("--count", action="store_true", help="Show count summary only")
parser.add_argument("--total-size", action="store_true", help="Show total size only")
args = parser.parse_args()
if not os.path.isdir(args.path):
print(f"Error: {args.path} is not a directory", file=sys.stderr)
return 1
entries = walk_directory(
args.path,
max_depth=args.depth,
show_hidden=args.all,
dirs_only=args.dirs,
)
if args.ext:
entries = filter_by_extension(entries, args.ext)
# Output
if args.count:
dirs, files = count_entries(entries)
print(f"{dirs} directories, {files} files")
elif args.total_size:
size = total_size(entries)
print(format_size(size))
else:
print(args.path)
for line in format_tree(entries, args.path, show_size=args.size):
print(line)
dirs, files = count_entries(entries)
print(f"\n{dirs} directories, {files} files")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_tree_walker/tree_cli.py (5294 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_tree_walker/tree_cli.rs (10086 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_tree_walker/Cargo.toml (1 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 97.3 KB/s
⏱️ Total time: 53ms
| true
|
tree_walker
| 191
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_try_except
|
test_try_except_cli.py
|
"""Tests for try_except_cli.py"""
import pytest
from try_except_cli import (
accumulate_with_errors,
all_valid_ints,
catch_and_convert,
count_valid_floats,
divide_with_default,
division_result,
first_valid_int,
nested_try_except,
parse_int_with_default,
parse_or_zero,
safe_divide,
safe_float,
safe_get_nested,
safe_index,
safe_int,
safe_key,
safe_pop,
safe_slice,
try_except_else,
try_except_finally_all,
try_finally_cleanup,
try_multiple_exceptions,
)
class TestSafeDivide:
def test_normal_division(self):
assert safe_divide(10.0, 2.0) == 5.0
def test_division_by_zero(self):
assert safe_divide(10.0, 0.0) is None
def test_negative_division(self):
assert safe_divide(-10.0, 2.0) == -5.0
class TestSafeInt:
def test_valid_int(self):
assert safe_int("42") == 42
def test_invalid_int(self):
assert safe_int("abc") is None
def test_negative_int(self):
assert safe_int("-10") == -10
class TestSafeFloat:
def test_valid_float(self):
assert safe_float("3.14") == 3.14
def test_invalid_float(self):
assert safe_float("xyz") is None
def test_int_as_float(self):
assert safe_float("42") == 42.0
class TestSafeIndex:
def test_valid_index(self):
assert safe_index([1, 2, 3], 1) == 2
def test_invalid_index(self):
assert safe_index([1, 2, 3], 10) is None
def test_negative_index(self):
assert safe_index([1, 2, 3], -1) == 3
class TestSafeKey:
def test_valid_key(self):
assert safe_key({"a": 1}, "a") == 1
def test_invalid_key(self):
assert safe_key({"a": 1}, "b") is None
class TestDivideWithDefault:
def test_normal_division(self):
assert divide_with_default(10.0, 2.0, -1.0) == 5.0
def test_division_by_zero_default(self):
assert divide_with_default(10.0, 0.0, -1.0) == -1.0
class TestParseIntWithDefault:
def test_valid_parse(self):
assert parse_int_with_default("42", 0) == 42
def test_invalid_parse_default(self):
assert parse_int_with_default("abc", -1) == -1
class TestTryMultipleExceptions:
def test_valid_input(self):
assert try_multiple_exceptions("123", 0) == "1"
def test_invalid_number(self):
assert try_multiple_exceptions("abc", 0) == "invalid_number"
def test_invalid_index(self):
assert try_multiple_exceptions("123", 10) == "invalid_index"
class TestTryExceptElse:
def test_success_path(self):
assert try_except_else("42") == "success: 42"
def test_error_path(self):
assert try_except_else("abc") == "error"
class TestTryFinallyCleanup:
def test_success_cleanup(self):
result, cleaned = try_finally_cleanup("42")
assert result == 42
assert cleaned is True
def test_error_cleanup(self):
result, cleaned = try_finally_cleanup("abc")
assert result is None
assert cleaned is True
class TestTryExceptFinallyAll:
def test_success_all(self):
status, finalized = try_except_finally_all("42")
assert status == "ok:42"
assert finalized is True
def test_error_all(self):
status, finalized = try_except_finally_all("abc")
assert status == "error"
assert finalized is True
class TestNestedTryExcept:
def test_both_valid(self):
assert nested_try_except("10", "5") == "both:15"
def test_inner_error(self):
assert nested_try_except("10", "abc") == "inner_error:10"
def test_outer_error(self):
assert nested_try_except("abc", "5") == "outer_error"
class TestCatchAndConvert:
def test_valid_input(self):
assert catch_and_convert("42") == 42
def test_invalid_input_raises(self):
with pytest.raises(RuntimeError):
catch_and_convert("abc")
class TestSafePop:
def test_pop_success(self):
lst = [1, 2, 3]
assert safe_pop(lst) == 3
assert lst == [1, 2]
def test_pop_empty(self):
assert safe_pop([]) is None
class TestSafeGetNested:
def test_valid_nested(self):
d = {"a": {"b": 42}}
assert safe_get_nested(d, "a", "b") == 42
def test_missing_outer(self):
d = {"a": {"b": 42}}
assert safe_get_nested(d, "x", "b") is None
def test_missing_inner(self):
d = {"a": {"b": 42}}
assert safe_get_nested(d, "a", "x") is None
class TestAccumulateWithErrors:
def test_all_valid(self):
total, errors = accumulate_with_errors(["1", "2", "3"])
assert total == 6
assert errors == 0
def test_some_errors(self):
total, errors = accumulate_with_errors(["1", "abc", "3"])
assert total == 4
assert errors == 1
def test_all_errors(self):
total, errors = accumulate_with_errors(["a", "b", "c"])
assert total == 0
assert errors == 3
class TestFirstValidInt:
def test_first_is_valid(self):
assert first_valid_int(["42", "abc"]) == 42
def test_second_is_valid(self):
assert first_valid_int(["abc", "42"]) == 42
def test_none_valid(self):
assert first_valid_int(["a", "b", "c"]) is None
def test_empty_list(self):
assert first_valid_int([]) is None
class TestAllValidInts:
def test_all_valid(self):
assert all_valid_ints(["1", "2", "3"]) == [1, 2, 3]
def test_some_valid(self):
assert all_valid_ints(["1", "a", "3"]) == [1, 3]
def test_none_valid(self):
assert all_valid_ints(["a", "b"]) == []
class TestCountValidFloats:
def test_all_valid(self):
assert count_valid_floats(["1.0", "2.5", "3"]) == 3
def test_some_valid(self):
assert count_valid_floats(["1.0", "abc", "3"]) == 2
def test_none_valid(self):
assert count_valid_floats(["a", "b"]) == 0
class TestSafeSlice:
def test_valid_slice(self):
assert safe_slice([1, 2, 3, 4], 1, 3) == [2, 3]
def test_out_of_bounds(self):
assert safe_slice([1, 2, 3], 0, 10) == [1, 2, 3]
class TestParseOrZero:
def test_valid(self):
assert parse_or_zero("42") == 42
def test_invalid(self):
assert parse_or_zero("abc") == 0
class TestDivisionResult:
def test_normal(self):
assert division_result(10.0, 4.0) == "result:2.50"
def test_division_by_zero(self):
assert division_result(10.0, 0.0) == "error:division_by_zero"
class TestEdgeCases:
def test_empty_string_parse(self):
assert safe_int("") is None
def test_whitespace_parse(self):
assert safe_int(" 42 ") == 42
def test_zero_division_result(self):
assert safe_divide(0.0, 5.0) == 0.0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_try_except/test_try_except_cli.py (6775 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_try_except/test_try_except_cli.rs (17795 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 125.4 KB/s
⏱️ Total time: 53ms
| true
|
try_except
| 270
| 5
|
[
"context_manager",
"class_definition",
"stdin_usage"
] | 0.652
| null |
example_try_except
|
try_except_cli.py
|
#!/usr/bin/env python3
"""Try/Except CLI.
Basic try/except/finally patterns for exception handling.
"""
import argparse
import sys
def safe_divide(a: float, b: float) -> float | None:
"""Safely divide two numbers, return None on error."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_int(value: str) -> int | None:
"""Safely convert string to int."""
try:
return int(value)
except ValueError:
return None
def safe_float(value: str) -> float | None:
"""Safely convert string to float."""
try:
return float(value)
except ValueError:
return None
def safe_index(lst: list[int], idx: int) -> int | None:
"""Safely get list element by index."""
try:
return lst[idx]
except IndexError:
return None
def safe_key(d: dict[str, int], key: str) -> int | None:
"""Safely get dict value by key."""
try:
return d[key]
except KeyError:
return None
def divide_with_default(a: float, b: float, default: float) -> float:
"""Divide with default value on error."""
try:
return a / b
except ZeroDivisionError:
return default
def parse_int_with_default(value: str, default: int) -> int:
"""Parse int with default value on error."""
try:
return int(value)
except ValueError:
return default
def try_multiple_exceptions(value: str, idx: int) -> str:
"""Handle multiple exception types."""
try:
num = int(value)
chars = list(str(num))
return chars[idx]
except ValueError:
return "invalid_number"
except IndexError:
return "invalid_index"
def try_except_else(value: str) -> str:
"""Try/except with else clause."""
try:
num = int(value)
except ValueError:
return "error"
else:
return f"success: {num}"
def try_finally_cleanup(value: str) -> tuple[int | None, bool]:
"""Try/finally for cleanup."""
cleaned = False
result: int | None = None
try:
result = int(value)
except ValueError:
result = None
finally:
cleaned = True
return (result, cleaned)
def try_except_finally_all(value: str) -> tuple[str, bool]:
"""Try/except/else/finally all together."""
status = ""
finalized = False
try:
num = int(value)
except ValueError:
status = "error"
else:
status = f"ok:{num}"
finally:
finalized = True
return (status, finalized)
def nested_try_except(outer: str, inner: str) -> str:
"""Nested try/except blocks."""
try:
outer_val = int(outer)
try:
inner_val = int(inner)
return f"both:{outer_val + inner_val}"
except ValueError:
return f"inner_error:{outer_val}"
except ValueError:
return "outer_error"
def reraise_exception(value: str) -> int:
"""Catch and re-raise exception."""
try:
return int(value)
except ValueError:
raise
def catch_and_convert(value: str) -> int:
"""Catch one exception, raise another."""
try:
return int(value)
except ValueError as err:
raise RuntimeError(f"Cannot parse: {value}") from err
def safe_pop(lst: list[int]) -> int | None:
"""Safely pop from list."""
try:
return lst.pop()
except IndexError:
return None
def safe_get_nested(d: dict[str, dict[str, int]], k1: str, k2: str) -> int | None:
"""Safely get nested dict value."""
try:
return d[k1][k2]
except KeyError:
return None
def accumulate_with_errors(values: list[str]) -> tuple[int, int]:
"""Accumulate valid integers, count errors."""
total = 0
errors = 0
for v in values:
try:
total += int(v)
except ValueError:
errors += 1
return (total, errors)
def first_valid_int(values: list[str]) -> int | None:
"""Return first valid integer from list."""
for v in values:
try:
return int(v)
except ValueError:
continue
return None
def all_valid_ints(values: list[str]) -> list[int]:
"""Return all valid integers from list."""
result: list[int] = []
for v in values:
try:
result.append(int(v))
except ValueError:
pass
return result
def count_valid_floats(values: list[str]) -> int:
"""Count valid floats in list."""
count = 0
for v in values:
try:
float(v)
count += 1
except ValueError:
pass
return count
def safe_slice(lst: list[int], start: int, end: int) -> list[int]:
"""Safely slice list."""
try:
return lst[start:end]
except (IndexError, TypeError):
return []
def parse_or_zero(value: str) -> int:
"""Parse int or return zero."""
try:
return int(value)
except ValueError:
return 0
def division_result(a: float, b: float) -> str:
"""Return division result as string with error handling."""
try:
result = a / b
return f"result:{result:.2f}"
except ZeroDivisionError:
return "error:division_by_zero"
except OverflowError:
return "error:overflow"
def main() -> int:
parser = argparse.ArgumentParser(description="Try/except patterns CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# divide
div_p = subparsers.add_parser("divide", help="Safe division")
div_p.add_argument("a", type=float)
div_p.add_argument("b", type=float)
# parse
parse_p = subparsers.add_parser("parse", help="Parse integer")
parse_p.add_argument("value")
parse_p.add_argument("--default", type=int, default=0)
# multi
multi_p = subparsers.add_parser("multi", help="Multiple exceptions")
multi_p.add_argument("value")
multi_p.add_argument("index", type=int)
# accumulate
acc_p = subparsers.add_parser("accumulate", help="Accumulate valid ints")
acc_p.add_argument("values", nargs="+")
args = parser.parse_args()
if args.command == "divide":
result = safe_divide(args.a, args.b)
if result is None:
print("Error: division by zero")
else:
print(f"Result: {result}")
elif args.command == "parse":
result = parse_int_with_default(args.value, args.default)
print(f"Parsed: {result}")
elif args.command == "multi":
result = try_multiple_exceptions(args.value, args.index)
print(f"Result: {result}")
elif args.command == "accumulate":
total, errors = accumulate_with_errors(args.values)
print(f"Total: {total}, Errors: {errors}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_try_except/try_except_cli.py (6863 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_try_except/try_except_cli.rs (13912 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_try_except/Cargo.toml (1 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 117.7 KB/s
⏱️ Total time: 57ms
| true
|
try_except
| 285
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_tuple_unpack_comp
|
test_tuple_unpack_comp_cli.py
|
"""Tests for tuple_unpack_comp_cli.py"""
from tuple_unpack_comp_cli import (
adjacent_differences,
adjacent_pairs,
combine_with_index,
dict_filter_transform,
dict_invert,
dict_items_filtered,
dict_items_to_list,
dict_items_transformed,
dict_keys_from_items,
dict_values_from_items,
enumerate_dict_values,
enumerate_filtered,
enumerate_to_pairs,
enumerate_transformed,
enumerate_with_start,
filter_by_first,
filter_by_second,
group_pairs_by_first,
merge_dicts_comprehension,
multi_zip_sum,
range_pairs,
running_pairs,
swap_pairs,
unpack_nested_pairs,
unpack_triple,
zip_filtered,
zip_three_lists,
zip_to_pairs,
zip_with_enumerate,
zip_with_sum,
)
class TestEnumerateToPairs:
def test_basic(self):
result = enumerate_to_pairs(["a", "b", "c"])
assert result == [(0, "a"), (1, "b"), (2, "c")]
def test_empty(self):
assert enumerate_to_pairs([]) == []
class TestEnumerateFiltered:
def test_with_prefix(self):
result = enumerate_filtered(["apple", "banana", "apricot"], "ap")
assert result == [(0, "apple"), (2, "apricot")]
def test_no_match(self):
result = enumerate_filtered(["apple", "banana"], "z")
assert result == []
class TestEnumerateTransformed:
def test_double(self):
result = enumerate_transformed([1, 2, 3])
assert result == [(0, 2), (1, 4), (2, 6)]
class TestZipToPairs:
def test_basic(self):
result = zip_to_pairs([1, 2], ["a", "b"])
assert result == [(1, "a"), (2, "b")]
def test_unequal_length(self):
result = zip_to_pairs([1, 2, 3], ["a", "b"])
assert result == [(1, "a"), (2, "b")]
class TestZipWithSum:
def test_sum(self):
result = zip_with_sum([1, 2, 3], [4, 5, 6])
assert result == [5, 7, 9]
class TestZipFiltered:
def test_filter(self):
result = zip_filtered([1, 5, 3], [2, 2, 4])
assert result == [(1, 2), (3, 4)]
class TestZipThreeLists:
def test_three(self):
result = zip_three_lists([1, 2], [3, 4], [5, 6])
assert result == [(1, 3, 5), (2, 4, 6)]
class TestDictItemsToList:
def test_basic(self):
result = dict_items_to_list({"a": 1, "b": 2})
assert set(result) == {("a", 1), ("b", 2)}
class TestDictItemsFiltered:
def test_filter(self):
result = dict_items_filtered({"a": 1, "b": 5, "c": 3}, 3)
assert set(result) == {("b", 5), ("c", 3)}
class TestDictItemsTransformed:
def test_transform(self):
result = dict_items_transformed({"a": 1, "b": 2})
assert set(result) == {("A", 2), ("B", 4)}
class TestDictKeysFromItems:
def test_keys(self):
result = dict_keys_from_items({"a": 1, "b": 2})
assert set(result) == {"a", "b"}
class TestDictValuesFromItems:
def test_values(self):
result = dict_values_from_items({"a": 1, "b": 2})
assert set(result) == {1, 2}
class TestSwapPairs:
def test_swap(self):
result = swap_pairs([(1, 2), (3, 4)])
assert result == [(2, 1), (4, 3)]
class TestUnpackNestedPairs:
def test_nested(self):
pairs = [((1, 2), "a"), ((3, 4), "b")]
result = unpack_nested_pairs(pairs)
assert result == [(1, 2, "a"), (3, 4, "b")]
class TestUnpackTriple:
def test_sum_triples(self):
result = unpack_triple([(1, 2, 3), (4, 5, 6)])
assert result == [6, 15]
class TestFilterByFirst:
def test_filter(self):
pairs = [(1, "a"), (5, "b"), (3, "c")]
result = filter_by_first(pairs, 2)
assert result == ["b", "c"]
class TestFilterBySecond:
def test_filter(self):
pairs = [("a", 1), ("b", 5), ("c", 3)]
result = filter_by_second(pairs, 2)
assert result == ["b", "c"]
class TestCombineWithIndex:
def test_combine(self):
result = combine_with_index(["a", "b"])
assert result == ["0:a", "1:b"]
class TestEnumerateWithStart:
def test_start(self):
result = enumerate_with_start(["a", "b"], 5)
assert result == [(5, "a"), (6, "b")]
class TestMultiZipSum:
def test_multiple_lists(self):
lists = [[1, 2], [3, 4], [5, 6]]
result = multi_zip_sum(lists)
assert result == [9, 12]
def test_empty(self):
assert multi_zip_sum([]) == []
class TestEnumerateDictValues:
def test_enumerate_nested(self):
d = {"a": [1, 2], "b": [3]}
result = enumerate_dict_values(d)
assert ("a", 0, 1) in result
assert ("a", 1, 2) in result
assert ("b", 0, 3) in result
class TestZipWithEnumerate:
def test_combined(self):
result = zip_with_enumerate(["a", "b"], [1, 2])
assert result == [(0, "a", 1), (1, "b", 2)]
class TestRangePairs:
def test_pairs(self):
result = range_pairs(4)
assert result == [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
def test_zero(self):
assert range_pairs(0) == []
class TestAdjacentPairs:
def test_adjacent(self):
result = adjacent_pairs([1, 2, 3, 4])
assert result == [(1, 2), (2, 3), (3, 4)]
def test_single(self):
assert adjacent_pairs([1]) == []
class TestAdjacentDifferences:
def test_differences(self):
result = adjacent_differences([1, 3, 6, 10])
assert result == [2, 3, 4]
class TestRunningPairs:
def test_running(self):
result = running_pairs([1, 2, 3])
assert result == [(0, 1, 2), (1, 2, 3)]
class TestDictInvert:
def test_invert(self):
result = dict_invert({"a": 1, "b": 2})
assert result == {1: "a", 2: "b"}
class TestDictFilterTransform:
def test_filter_transform(self):
result = dict_filter_transform({"a": 1, "b": -1, "c": 2})
assert result == {"A": 2, "C": 4}
class TestGroupPairsByFirst:
def test_group(self):
pairs = [("a", 1), ("b", 2), ("a", 3)]
result = group_pairs_by_first(pairs)
assert set(result["a"]) == {1, 3}
assert result["b"] == [2]
class TestMergeDictsComprehension:
def test_merge(self):
result = merge_dicts_comprehension({"a": 1}, {"b": 2})
assert result == {"a": 1, "b": 2}
def test_overlap(self):
result = merge_dicts_comprehension({"a": 1}, {"a": 2})
assert result == {"a": 2}
class TestEdgeCases:
def test_empty_enumerate(self):
assert enumerate_to_pairs([]) == []
def test_single_element_zip(self):
result = zip_to_pairs([1], ["a"])
assert result == [(1, "a")]
def test_empty_dict_items(self):
assert dict_items_to_list({}) == []
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_tuple_unpack_comp/test_tuple_unpack_comp_cli.py (6701 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_tuple_unpack_comp/test_tuple_unpack_comp_cli.rs (23743 bytes)
⏱️ Parse time: 55ms
📊 Throughput: 117.4 KB/s
⏱️ Total time: 55ms
| true
|
tuple_unpack_comp
| 259
| 5
|
[
"class_definition"
] | 0.612
| null |
example_tuple_unpack_comp
|
tuple_unpack_comp_cli.py
|
#!/usr/bin/env python3
"""Tuple Unpack Comprehension CLI.
Tuple unpacking patterns in comprehensions.
"""
import argparse
import sys
def enumerate_to_pairs(items: list[str]) -> list[tuple[int, str]]:
"""Convert enumerate to list of pairs."""
return [(i, v) for i, v in enumerate(items)]
def enumerate_filtered(items: list[str], prefix: str) -> list[tuple[int, str]]:
"""Enumerate with filter on value."""
return [(i, v) for i, v in enumerate(items) if v.startswith(prefix)]
def enumerate_transformed(items: list[int]) -> list[tuple[int, int]]:
"""Enumerate with transformed values."""
return [(i, v * 2) for i, v in enumerate(items)]
def zip_to_pairs(list1: list[int], list2: list[str]) -> list[tuple[int, str]]:
"""Zip two lists to pairs."""
return [(a, b) for a, b in zip(list1, list2, strict=False)]
def zip_with_sum(list1: list[int], list2: list[int]) -> list[int]:
"""Zip and sum pairs."""
return [a + b for a, b in zip(list1, list2, strict=False)]
def zip_filtered(list1: list[int], list2: list[int]) -> list[tuple[int, int]]:
"""Zip with filter."""
return [(a, b) for a, b in zip(list1, list2, strict=False) if a < b]
def zip_three_lists(l1: list[int], l2: list[int], l3: list[int]) -> list[tuple[int, int, int]]:
"""Zip three lists."""
return [(a, b, c) for a, b, c in zip(l1, l2, l3, strict=False)]
def dict_items_to_list(d: dict[str, int]) -> list[tuple[str, int]]:
"""Convert dict items to list."""
return list(d.items())
def dict_items_filtered(d: dict[str, int], min_val: int) -> list[tuple[str, int]]:
"""Dict items filtered by value."""
return [(k, v) for k, v in d.items() if v >= min_val]
def dict_items_transformed(d: dict[str, int]) -> list[tuple[str, int]]:
"""Transform dict items."""
return [(k.upper(), v * 2) for k, v in d.items()]
def dict_keys_from_items(d: dict[str, int]) -> list[str]:
"""Extract keys using items unpacking."""
return [k for k, _ in d.items()]
def dict_values_from_items(d: dict[str, int]) -> list[int]:
"""Extract values using items unpacking."""
return [v for _, v in d.items()]
def swap_pairs(pairs: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Swap elements in pairs."""
return [(b, a) for a, b in pairs]
def unpack_nested_pairs(pairs: list[tuple[tuple[int, int], str]]) -> list[tuple[int, int, str]]:
"""Unpack nested tuples."""
return [(x, y, s) for (x, y), s in pairs]
def unpack_triple(triples: list[tuple[int, int, int]]) -> list[int]:
"""Sum elements from triples."""
return [a + b + c for a, b, c in triples]
def filter_by_first(pairs: list[tuple[int, str]], threshold: int) -> list[str]:
"""Filter pairs and extract second element."""
return [s for n, s in pairs if n > threshold]
def filter_by_second(pairs: list[tuple[str, int]], threshold: int) -> list[str]:
"""Filter pairs by second element."""
return [s for s, n in pairs if n > threshold]
def combine_with_index(items: list[str]) -> list[str]:
"""Combine index with item."""
return [f"{i}:{v}" for i, v in enumerate(items)]
def enumerate_with_start(items: list[str], start: int) -> list[tuple[int, str]]:
"""Enumerate with custom start."""
return [(i, v) for i, v in enumerate(items, start=start)]
def multi_zip_sum(lists: list[list[int]]) -> list[int]:
"""Sum corresponding elements from multiple lists."""
if not lists:
return []
return [sum(vals) for vals in zip(*lists, strict=False)]
def enumerate_dict_values(d: dict[str, list[int]]) -> list[tuple[str, int, int]]:
"""Enumerate values in dict of lists."""
return [(k, i, v) for k, lst in d.items() for i, v in enumerate(lst)]
def zip_with_enumerate(list1: list[str], list2: list[int]) -> list[tuple[int, str, int]]:
"""Combine zip and enumerate."""
return [(i, s, n) for i, (s, n) in enumerate(zip(list1, list2, strict=False))]
def range_pairs(n: int) -> list[tuple[int, int]]:
"""Generate pairs from range."""
return [(i, j) for i in range(n) for j in range(i + 1, n)]
def adjacent_pairs(items: list[int]) -> list[tuple[int, int]]:
"""Get adjacent pairs."""
return [(a, b) for a, b in zip(items[:-1], items[1:], strict=False)]
def adjacent_differences(items: list[int]) -> list[int]:
"""Calculate differences between adjacent elements."""
return [b - a for a, b in zip(items[:-1], items[1:], strict=False)]
def running_pairs(items: list[int]) -> list[tuple[int, int, int]]:
"""Pairs with running index."""
return [(i, a, b) for i, (a, b) in enumerate(zip(items[:-1], items[1:], strict=False))]
def dict_invert(d: dict[str, int]) -> dict[int, str]:
"""Invert dictionary using comprehension."""
return {v: k for k, v in d.items()}
def dict_filter_transform(d: dict[str, int]) -> dict[str, int]:
"""Filter and transform dict."""
return {k.upper(): v * 2 for k, v in d.items() if v > 0}
def group_pairs_by_first(pairs: list[tuple[str, int]]) -> dict[str, list[int]]:
"""Group pairs by first element."""
keys = {k for k, _ in pairs}
return {k: [v for key, v in pairs if key == k] for k in keys}
def merge_dicts_comprehension(d1: dict[str, int], d2: dict[str, int]) -> dict[str, int]:
"""Merge dicts using comprehension."""
return {k: v for d in [d1, d2] for k, v in d.items()}
def main() -> int:
parser = argparse.ArgumentParser(description="Tuple unpack comprehension CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# enumerate
enum_p = subparsers.add_parser("enumerate", help="Enumerate items")
enum_p.add_argument("items", nargs="+")
enum_p.add_argument("--start", type=int, default=0)
# zip
zip_p = subparsers.add_parser("zip", help="Zip lists")
zip_p.add_argument("--list1", required=True)
zip_p.add_argument("--list2", required=True)
# adjacent
adj_p = subparsers.add_parser("adjacent", help="Adjacent pairs")
adj_p.add_argument("items", type=int, nargs="+")
args = parser.parse_args()
if args.command == "enumerate":
result = enumerate_with_start(args.items, args.start)
for i, v in result:
print(f"{i}: {v}")
elif args.command == "zip":
import ast
list1 = ast.literal_eval(args.list1)
list2 = ast.literal_eval(args.list2)
result = zip_to_pairs(list1, list2)
print(result)
elif args.command == "adjacent":
result = adjacent_pairs(args.items)
print(result)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
tuple_unpack_comp
| 208
| 0
|
[
"context_manager",
"eval_exec"
] | 0.652
|
Type inference hints:
Hint: str for variable 'i' [Medium] (usage patterns suggest this type)
Hint: str for variable 'v' [Medium] (usage patterns suggest this type)
Performance Warnings
══════════════════════════════════════════════════
[1] [Medium] Large value 'items' passed by copy
Location: enumerate_to_pairs, line 0
Impact: Complexity: O(n), Scales: Yes, Hot path: No
Why: Passing large values by copy is inefficient
Fix: Consider passing by reference (&) or using Box/Arc for lar
|
|
example_typed_dict
|
test_typed_dict_cli.py
|
"""Tests for typed_dict_cli.py"""
from typed_dict_cli import (
clear_dict,
copy_dict,
count_by_value,
create_dict,
create_empty_dict,
dict_size,
difference,
filter_by_keys,
filter_by_value,
from_keys,
get_items,
get_keys,
get_value,
get_value_default,
get_values,
group_by_value,
has_key,
intersection,
invert_dict,
is_empty,
key_with_max_value,
key_with_min_value,
map_values,
max_value,
merge_dicts,
min_value,
pop_value,
remove_key,
set_value,
setdefault,
sort_by_key,
sort_by_value,
sum_values,
update_dict,
zip_to_dict,
)
class TestCreate:
def test_create_empty_dict(self):
d = create_empty_dict()
assert d == {}
def test_create_dict(self):
items = [("a", 1), ("b", 2), ("c", 3)]
d = create_dict(items)
assert d == {"a": 1, "b": 2, "c": 3}
class TestGetSet:
def test_get_value(self):
d = {"a": 1, "b": 2}
assert get_value(d, "a") == 1
assert get_value(d, "x") is None
def test_get_value_default(self):
d = {"a": 1}
assert get_value_default(d, "a", 0) == 1
assert get_value_default(d, "x", 99) == 99
def test_set_value(self):
d = {"a": 1}
result = set_value(d, "b", 2)
assert result == {"a": 1, "b": 2}
assert d == {"a": 1} # Original unchanged
def test_remove_key(self):
d = {"a": 1, "b": 2}
result = remove_key(d, "a")
assert result == {"b": 2}
assert d == {"a": 1, "b": 2} # Original unchanged
class TestContains:
def test_has_key(self):
d = {"a": 1}
assert has_key(d, "a") is True
assert has_key(d, "x") is False
class TestAccessors:
def test_get_keys(self):
d = {"a": 1, "b": 2}
keys = get_keys(d)
assert sorted(keys) == ["a", "b"]
def test_get_values(self):
d = {"a": 1, "b": 2}
values = get_values(d)
assert sorted(values) == [1, 2]
def test_get_items(self):
d = {"a": 1, "b": 2}
items = get_items(d)
assert sorted(items) == [("a", 1), ("b", 2)]
class TestSize:
def test_dict_size(self):
assert dict_size({}) == 0
assert dict_size({"a": 1, "b": 2}) == 2
def test_is_empty(self):
assert is_empty({}) is True
assert is_empty({"a": 1}) is False
class TestMerge:
def test_merge_dicts(self):
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
result = merge_dicts(d1, d2)
assert result == {"a": 1, "b": 3, "c": 4}
def test_update_dict(self):
d = {"a": 1}
result = update_dict(d, {"b": 2, "c": 3})
assert result == {"a": 1, "b": 2, "c": 3}
class TestPop:
def test_pop_value_exists(self):
d = {"a": 1, "b": 2}
value, result = pop_value(d, "a")
assert value == 1
assert result == {"b": 2}
def test_pop_value_not_exists(self):
d = {"a": 1}
value, result = pop_value(d, "x")
assert value is None
assert result == {"a": 1}
class TestSetDefault:
def test_setdefault_exists(self):
d = {"a": 1}
value, result = setdefault(d, "a", 99)
assert value == 1
assert result == {"a": 1}
def test_setdefault_not_exists(self):
d = {"a": 1}
value, result = setdefault(d, "b", 99)
assert value == 99
assert result == {"a": 1, "b": 99}
class TestCopy:
def test_clear_dict(self):
d = {"a": 1, "b": 2}
result = clear_dict(d)
assert result == {}
def test_copy_dict(self):
d = {"a": 1}
result = copy_dict(d)
assert result == {"a": 1}
assert result is not d
class TestFilter:
def test_filter_by_value(self):
d = {"a": 1, "b": 5, "c": 3}
result = filter_by_value(d, 3)
assert result == {"b": 5, "c": 3}
def test_filter_by_keys(self):
d = {"a": 1, "b": 2, "c": 3}
result = filter_by_keys(d, ["a", "c"])
assert result == {"a": 1, "c": 3}
class TestMapValues:
def test_map_values(self):
d = {"a": 1, "b": 2}
result = map_values(d, 10)
assert result == {"a": 10, "b": 20}
class TestAggregation:
def test_sum_values(self):
d = {"a": 1, "b": 2, "c": 3}
assert sum_values(d) == 6
def test_max_value(self):
d = {"a": 1, "b": 5, "c": 3}
assert max_value(d) == 5
def test_max_value_empty(self):
assert max_value({}) is None
def test_min_value(self):
d = {"a": 1, "b": 5, "c": 3}
assert min_value(d) == 1
def test_min_value_empty(self):
assert min_value({}) is None
class TestKeyByValue:
def test_key_with_max_value(self):
d = {"a": 1, "b": 5, "c": 3}
assert key_with_max_value(d) == "b"
def test_key_with_max_value_empty(self):
assert key_with_max_value({}) is None
def test_key_with_min_value(self):
d = {"a": 1, "b": 5, "c": 3}
assert key_with_min_value(d) == "a"
class TestInvert:
def test_invert_dict(self):
d = {"a": 1, "b": 2}
result = invert_dict(d)
assert result == {1: "a", 2: "b"}
class TestSort:
def test_sort_by_key(self):
d = {"c": 3, "a": 1, "b": 2}
result = sort_by_key(d)
assert list(result.keys()) == ["a", "b", "c"]
def test_sort_by_value(self):
d = {"c": 3, "a": 1, "b": 2}
result = sort_by_value(d)
assert list(result.values()) == [1, 2, 3]
class TestCount:
def test_count_by_value(self):
d = {"a": 1, "b": 2, "c": 1}
result = count_by_value(d)
assert result == {1: 2, 2: 1}
class TestGroup:
def test_group_by_value(self):
d = {"a": 1, "b": 2, "c": 1}
result = group_by_value(d)
assert result[1] == ["a", "c"] or result[1] == ["c", "a"]
assert result[2] == ["b"]
class TestFromKeys:
def test_from_keys(self):
keys = ["a", "b", "c"]
result = from_keys(keys, 0)
assert result == {"a": 0, "b": 0, "c": 0}
def test_zip_to_dict(self):
keys = ["a", "b", "c"]
values = [1, 2, 3]
result = zip_to_dict(keys, values)
assert result == {"a": 1, "b": 2, "c": 3}
class TestSetOperations:
def test_difference(self):
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
result = difference(d1, d2)
assert result == {"a": 1}
def test_intersection(self):
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
result = intersection(d1, d2)
assert result == {"b": 2}
class TestEdgeCases:
def test_empty_operations(self):
d: dict[str, int] = {}
assert get_keys(d) == []
assert get_values(d) == []
assert sum_values(d) == 0
def test_single_element(self):
d = {"only": 42}
assert dict_size(d) == 1
assert max_value(d) == 42
assert min_value(d) == 42
| false
|
typed_dict
| 289
| 0
|
[
"class_definition"
] | 0.612
|
Error: 'is not' operator not yet supported (use != for value comparison)
|
|
example_typed_dict
|
typed_dict_cli.py
|
#!/usr/bin/env python3
"""Typed Dict CLI.
Dictionary operations with type hints.
"""
import argparse
import sys
def create_empty_dict() -> dict[str, int]:
"""Create empty typed dictionary."""
return {}
def create_dict(items: list[tuple[str, int]]) -> dict[str, int]:
"""Create dictionary from key-value pairs."""
return dict(items)
def get_value(d: dict[str, int], key: str) -> int | None:
"""Get value by key, return None if not found."""
return d.get(key)
def get_value_default(d: dict[str, int], key: str, default: int) -> int:
"""Get value by key with default."""
return d.get(key, default)
def set_value(d: dict[str, int], key: str, value: int) -> dict[str, int]:
"""Set value in dictionary (returns new dict)."""
result = d.copy()
result[key] = value
return result
def remove_key(d: dict[str, int], key: str) -> dict[str, int]:
"""Remove key from dictionary (returns new dict)."""
result = d.copy()
result.pop(key, None)
return result
def has_key(d: dict[str, int], key: str) -> bool:
"""Check if key exists in dictionary."""
return key in d
def get_keys(d: dict[str, int]) -> list[str]:
"""Get all keys."""
return list(d.keys())
def get_values(d: dict[str, int]) -> list[int]:
"""Get all values."""
return list(d.values())
def get_items(d: dict[str, int]) -> list[tuple[str, int]]:
"""Get all key-value pairs."""
return list(d.items())
def dict_size(d: dict[str, int]) -> int:
"""Get dictionary size."""
return len(d)
def is_empty(d: dict[str, int]) -> bool:
"""Check if dictionary is empty."""
return len(d) == 0
def merge_dicts(d1: dict[str, int], d2: dict[str, int]) -> dict[str, int]:
"""Merge two dictionaries (d2 overrides d1)."""
return {**d1, **d2}
def update_dict(d: dict[str, int], updates: dict[str, int]) -> dict[str, int]:
"""Update dictionary with new values."""
result = d.copy()
result.update(updates)
return result
def pop_value(d: dict[str, int], key: str) -> tuple[int | None, dict[str, int]]:
"""Pop value from dictionary, return (value, new_dict)."""
result = d.copy()
value = result.pop(key, None)
return (value, result)
def setdefault(d: dict[str, int], key: str, default: int) -> tuple[int, dict[str, int]]:
"""Set default value if key doesn't exist."""
result = d.copy()
value = result.setdefault(key, default)
return (value, result)
def clear_dict(d: dict[str, int]) -> dict[str, int]:
"""Return empty dictionary."""
return {}
def copy_dict(d: dict[str, int]) -> dict[str, int]:
"""Create shallow copy of dictionary."""
return d.copy()
def filter_by_value(d: dict[str, int], min_value: int) -> dict[str, int]:
"""Filter dictionary by minimum value."""
return {k: v for k, v in d.items() if v >= min_value}
def filter_by_keys(d: dict[str, int], keys: list[str]) -> dict[str, int]:
"""Filter dictionary to only include specified keys."""
return {k: v for k, v in d.items() if k in keys}
def map_values(d: dict[str, int], factor: int) -> dict[str, int]:
"""Multiply all values by factor."""
return {k: v * factor for k, v in d.items()}
def sum_values(d: dict[str, int]) -> int:
"""Sum all values in dictionary."""
return sum(d.values())
def max_value(d: dict[str, int]) -> int | None:
"""Get maximum value."""
if not d:
return None
return max(d.values())
def min_value(d: dict[str, int]) -> int | None:
"""Get minimum value."""
if not d:
return None
return min(d.values())
def key_with_max_value(d: dict[str, int]) -> str | None:
"""Get key with maximum value."""
if not d:
return None
return max(d, key=d.get) # type: ignore
def key_with_min_value(d: dict[str, int]) -> str | None:
"""Get key with minimum value."""
if not d:
return None
return min(d, key=d.get) # type: ignore
def invert_dict(d: dict[str, int]) -> dict[int, str]:
"""Invert dictionary (swap keys and values)."""
return {v: k for k, v in d.items()}
def sort_by_key(d: dict[str, int]) -> dict[str, int]:
"""Sort dictionary by keys."""
return dict(sorted(d.items()))
def sort_by_value(d: dict[str, int]) -> dict[str, int]:
"""Sort dictionary by values."""
return dict(sorted(d.items(), key=lambda x: x[1]))
def count_by_value(d: dict[str, int]) -> dict[int, int]:
"""Count occurrences of each value."""
counts: dict[int, int] = {}
for v in d.values():
counts[v] = counts.get(v, 0) + 1
return counts
def group_by_value(d: dict[str, int]) -> dict[int, list[str]]:
"""Group keys by their values."""
groups: dict[int, list[str]] = {}
for k, v in d.items():
if v not in groups:
groups[v] = []
groups[v].append(k)
return groups
def from_keys(keys: list[str], default: int) -> dict[str, int]:
"""Create dictionary from keys with default value."""
return dict.fromkeys(keys, default)
def zip_to_dict(keys: list[str], values: list[int]) -> dict[str, int]:
"""Create dictionary from two lists."""
return dict(zip(keys, values, strict=False))
def difference(d1: dict[str, int], d2: dict[str, int]) -> dict[str, int]:
"""Get keys in d1 but not in d2."""
return {k: v for k, v in d1.items() if k not in d2}
def intersection(d1: dict[str, int], d2: dict[str, int]) -> dict[str, int]:
"""Get keys in both d1 and d2 (values from d1)."""
return {k: v for k, v in d1.items() if k in d2}
def main() -> int:
parser = argparse.ArgumentParser(description="Typed dict CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create dictionary")
create_p.add_argument("items", nargs="*", help="key=value pairs")
# get
get_p = subparsers.add_parser("get", help="Get value")
get_p.add_argument("key", help="Key")
get_p.add_argument("--data", required=True, help="Dict as key=value pairs")
# stats
stats_p = subparsers.add_parser("stats", help="Show stats")
stats_p.add_argument("--data", required=True, help="Dict as key=value pairs")
args = parser.parse_args()
def parse_dict(s: str) -> dict[str, int]:
result: dict[str, int] = {}
for item in s.split(","):
if "=" in item:
k, v = item.split("=", 1)
result[k.strip()] = int(v.strip())
return result
if args.command == "create":
items = []
for item in args.items:
if "=" in item:
k, v = item.split("=", 1)
items.append((k, int(v)))
d = create_dict(items)
print(d)
elif args.command == "get":
d = parse_dict(args.data)
value = get_value(d, args.key)
print(f"Value: {value}")
elif args.command == "stats":
d = parse_dict(args.data)
print(f"Size: {dict_size(d)}")
print(f"Sum: {sum_values(d)}")
print(f"Max: {max_value(d)}")
print(f"Min: {min_value(d)}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
typed_dict
| 267
| 0
|
[
"lambda",
"context_manager"
] | 0.783
|
Error: Dict unpacking not supported
|
|
example_typed_list
|
test_typed_list_cli.py
|
"""Tests for typed_list_cli.py"""
from typed_list_cli import (
append,
concat,
contains,
count_item,
create_empty_list,
create_list,
deduplicate,
drop,
drop_last,
enumerate_list,
extend,
filter_even,
filter_gt,
filter_lt,
filter_odd,
flatten,
get_first,
get_item,
get_last,
index_of,
insert_at,
is_empty,
list_size,
map_add,
map_double,
map_multiply,
map_square,
max_list,
mean_list,
min_list,
pop_first,
pop_last,
prepend,
product_list,
range_list,
remove_at,
remove_item,
repeat,
reverse_list,
set_item,
slice_list,
sort_asc,
sort_desc,
sum_list,
take,
take_last,
unique,
zip_lists,
)
class TestCreate:
def test_create_empty_list(self):
lst = create_empty_list()
assert lst == []
def test_create_list(self):
lst = create_list([1, 2, 3])
assert lst == [1, 2, 3]
class TestAddRemove:
def test_append(self):
lst = [1, 2]
result = append(lst, 3)
assert result == [1, 2, 3]
assert lst == [1, 2]
def test_prepend(self):
lst = [2, 3]
result = prepend(lst, 1)
assert result == [1, 2, 3]
def test_insert_at(self):
lst = [1, 3]
result = insert_at(lst, 1, 2)
assert result == [1, 2, 3]
def test_remove_item(self):
lst = [1, 2, 3, 2]
result = remove_item(lst, 2)
assert result == [1, 3, 2]
def test_remove_at(self):
lst = [1, 2, 3]
result = remove_at(lst, 1)
assert result == [1, 3]
class TestPop:
def test_pop_last(self):
lst = [1, 2, 3]
item, result = pop_last(lst)
assert item == 3
assert result == [1, 2]
def test_pop_last_empty(self):
item, result = pop_last([])
assert item is None
assert result == []
def test_pop_first(self):
lst = [1, 2, 3]
item, result = pop_first(lst)
assert item == 1
assert result == [2, 3]
class TestAccess:
def test_get_item(self):
lst = [1, 2, 3]
assert get_item(lst, 1) == 2
assert get_item(lst, 10) is None
def test_get_first(self):
assert get_first([1, 2, 3]) == 1
assert get_first([]) is None
def test_get_last(self):
assert get_last([1, 2, 3]) == 3
assert get_last([]) is None
def test_set_item(self):
lst = [1, 2, 3]
result = set_item(lst, 1, 99)
assert result == [1, 99, 3]
class TestSize:
def test_list_size(self):
assert list_size([]) == 0
assert list_size([1, 2, 3]) == 3
def test_is_empty(self):
assert is_empty([]) is True
assert is_empty([1]) is False
class TestContains:
def test_contains(self):
lst = [1, 2, 3]
assert contains(lst, 2) is True
assert contains(lst, 5) is False
def test_index_of(self):
lst = [1, 2, 3]
assert index_of(lst, 2) == 1
assert index_of(lst, 5) == -1
def test_count_item(self):
lst = [1, 2, 2, 3, 2]
assert count_item(lst, 2) == 3
class TestSlice:
def test_slice_list(self):
lst = [1, 2, 3, 4, 5]
assert slice_list(lst, 1, 4) == [2, 3, 4]
def test_take(self):
lst = [1, 2, 3, 4, 5]
assert take(lst, 3) == [1, 2, 3]
def test_drop(self):
lst = [1, 2, 3, 4, 5]
assert drop(lst, 2) == [3, 4, 5]
def test_take_last(self):
lst = [1, 2, 3, 4, 5]
assert take_last(lst, 2) == [4, 5]
def test_drop_last(self):
lst = [1, 2, 3, 4, 5]
assert drop_last(lst, 2) == [1, 2, 3]
class TestOrder:
def test_reverse_list(self):
lst = [1, 2, 3]
assert reverse_list(lst) == [3, 2, 1]
def test_sort_asc(self):
lst = [3, 1, 2]
assert sort_asc(lst) == [1, 2, 3]
def test_sort_desc(self):
lst = [1, 3, 2]
assert sort_desc(lst) == [3, 2, 1]
class TestCombine:
def test_concat(self):
assert concat([1, 2], [3, 4]) == [1, 2, 3, 4]
def test_extend(self):
assert extend([1], [2, 3]) == [1, 2, 3]
def test_repeat(self):
assert repeat([1, 2], 3) == [1, 2, 1, 2, 1, 2]
class TestFlatten:
def test_flatten(self):
nested = [[1, 2], [3], [4, 5, 6]]
assert flatten(nested) == [1, 2, 3, 4, 5, 6]
class TestFilter:
def test_filter_gt(self):
lst = [1, 2, 3, 4, 5]
assert filter_gt(lst, 3) == [4, 5]
def test_filter_lt(self):
lst = [1, 2, 3, 4, 5]
assert filter_lt(lst, 3) == [1, 2]
def test_filter_even(self):
lst = [1, 2, 3, 4, 5]
assert filter_even(lst) == [2, 4]
def test_filter_odd(self):
lst = [1, 2, 3, 4, 5]
assert filter_odd(lst) == [1, 3, 5]
class TestMap:
def test_map_double(self):
lst = [1, 2, 3]
assert map_double(lst) == [2, 4, 6]
def test_map_square(self):
lst = [1, 2, 3]
assert map_square(lst) == [1, 4, 9]
def test_map_add(self):
lst = [1, 2, 3]
assert map_add(lst, 10) == [11, 12, 13]
def test_map_multiply(self):
lst = [1, 2, 3]
assert map_multiply(lst, 5) == [5, 10, 15]
class TestAggregate:
def test_sum_list(self):
assert sum_list([1, 2, 3]) == 6
def test_product_list(self):
assert product_list([1, 2, 3, 4]) == 24
def test_max_list(self):
assert max_list([1, 5, 3]) == 5
assert max_list([]) is None
def test_min_list(self):
assert min_list([1, 5, 3]) == 1
assert min_list([]) is None
def test_mean_list(self):
assert mean_list([1, 2, 3]) == 2.0
assert mean_list([]) is None
class TestUnique:
def test_unique(self):
lst = [1, 2, 2, 3, 1, 4]
assert unique(lst) == [1, 2, 3, 4]
def test_deduplicate(self):
lst = [1, 1, 2, 2, 2, 3, 1]
assert deduplicate(lst) == [1, 2, 3, 1]
class TestZip:
def test_zip_lists(self):
result = zip_lists([1, 2, 3], [4, 5, 6])
assert result == [(1, 4), (2, 5), (3, 6)]
def test_enumerate_list(self):
result = enumerate_list([10, 20, 30])
assert result == [(0, 10), (1, 20), (2, 30)]
class TestRange:
def test_range_list(self):
assert range_list(1, 5, 1) == [1, 2, 3, 4]
assert range_list(0, 10, 2) == [0, 2, 4, 6, 8]
class TestEdgeCases:
def test_empty_operations(self):
assert sum_list([]) == 0
assert product_list([]) == 1
assert unique([]) == []
def test_single_element(self):
lst = [42]
assert max_list(lst) == 42
assert min_list(lst) == 42
assert mean_list(lst) == 42.0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typed_list/test_typed_list_cli.py (6831 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typed_list/test_typed_list_cli.rs (21316 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 127.5 KB/s
⏱️ Total time: 52ms
| true
|
typed_list
| 303
| 5
|
[
"class_definition"
] | 0.612
| null |
example_typed_list
|
typed_list_cli.py
|
#!/usr/bin/env python3
"""Typed List CLI.
List operations with type hints.
"""
import argparse
import sys
def create_empty_list() -> list[int]:
"""Create empty typed list."""
return []
def create_list(items: list[int]) -> list[int]:
"""Create list from items."""
return list(items)
def append(lst: list[int], item: int) -> list[int]:
"""Append item to list (returns new list)."""
return lst + [item]
def prepend(lst: list[int], item: int) -> list[int]:
"""Prepend item to list."""
return [item] + lst
def insert_at(lst: list[int], index: int, item: int) -> list[int]:
"""Insert item at index."""
result = lst.copy()
result.insert(index, item)
return result
def remove_item(lst: list[int], item: int) -> list[int]:
"""Remove first occurrence of item."""
result = lst.copy()
if item in result:
result.remove(item)
return result
def remove_at(lst: list[int], index: int) -> list[int]:
"""Remove item at index."""
if 0 <= index < len(lst):
return lst[:index] + lst[index + 1 :]
return lst.copy()
def pop_last(lst: list[int]) -> tuple[int | None, list[int]]:
"""Pop last item, return (item, new_list)."""
if not lst:
return (None, [])
return (lst[-1], lst[:-1])
def pop_first(lst: list[int]) -> tuple[int | None, list[int]]:
"""Pop first item, return (item, new_list)."""
if not lst:
return (None, [])
return (lst[0], lst[1:])
def get_item(lst: list[int], index: int) -> int | None:
"""Get item at index, None if out of bounds."""
if 0 <= index < len(lst):
return lst[index]
return None
def get_first(lst: list[int]) -> int | None:
"""Get first item."""
return lst[0] if lst else None
def get_last(lst: list[int]) -> int | None:
"""Get last item."""
return lst[-1] if lst else None
def set_item(lst: list[int], index: int, value: int) -> list[int]:
"""Set item at index."""
result = lst.copy()
if 0 <= index < len(result):
result[index] = value
return result
def list_size(lst: list[int]) -> int:
"""Get list size."""
return len(lst)
def is_empty(lst: list[int]) -> bool:
"""Check if list is empty."""
return len(lst) == 0
def contains(lst: list[int], item: int) -> bool:
"""Check if list contains item."""
return item in lst
def index_of(lst: list[int], item: int) -> int:
"""Get index of item, -1 if not found."""
try:
return lst.index(item)
except ValueError:
return -1
def count_item(lst: list[int], item: int) -> int:
"""Count occurrences of item."""
return lst.count(item)
def slice_list(lst: list[int], start: int, end: int) -> list[int]:
"""Slice list from start to end."""
return lst[start:end]
def take(lst: list[int], n: int) -> list[int]:
"""Take first n items."""
return lst[:n]
def drop(lst: list[int], n: int) -> list[int]:
"""Drop first n items."""
return lst[n:]
def take_last(lst: list[int], n: int) -> list[int]:
"""Take last n items."""
return lst[-n:] if n > 0 else []
def drop_last(lst: list[int], n: int) -> list[int]:
"""Drop last n items."""
return lst[:-n] if n > 0 else lst.copy()
def reverse_list(lst: list[int]) -> list[int]:
"""Reverse list."""
return lst[::-1]
def sort_asc(lst: list[int]) -> list[int]:
"""Sort ascending."""
return sorted(lst)
def sort_desc(lst: list[int]) -> list[int]:
"""Sort descending."""
return sorted(lst, reverse=True)
def concat(lst1: list[int], lst2: list[int]) -> list[int]:
"""Concatenate two lists."""
return lst1 + lst2
def extend(lst: list[int], items: list[int]) -> list[int]:
"""Extend list with items."""
return lst + items
def repeat(lst: list[int], n: int) -> list[int]:
"""Repeat list n times."""
return lst * n
def flatten(nested: list[list[int]]) -> list[int]:
"""Flatten nested list."""
result: list[int] = []
for inner in nested:
result.extend(inner)
return result
def filter_gt(lst: list[int], threshold: int) -> list[int]:
"""Filter items greater than threshold."""
return [x for x in lst if x > threshold]
def filter_lt(lst: list[int], threshold: int) -> list[int]:
"""Filter items less than threshold."""
return [x for x in lst if x < threshold]
def filter_even(lst: list[int]) -> list[int]:
"""Filter even numbers."""
return [x for x in lst if x % 2 == 0]
def filter_odd(lst: list[int]) -> list[int]:
"""Filter odd numbers."""
return [x for x in lst if x % 2 != 0]
def map_double(lst: list[int]) -> list[int]:
"""Double all values."""
return [x * 2 for x in lst]
def map_square(lst: list[int]) -> list[int]:
"""Square all values."""
return [x * x for x in lst]
def map_add(lst: list[int], n: int) -> list[int]:
"""Add n to all values."""
return [x + n for x in lst]
def map_multiply(lst: list[int], n: int) -> list[int]:
"""Multiply all values by n."""
return [x * n for x in lst]
def sum_list(lst: list[int]) -> int:
"""Sum all values."""
return sum(lst)
def product_list(lst: list[int]) -> int:
"""Product of all values."""
result = 1
for x in lst:
result *= x
return result
def max_list(lst: list[int]) -> int | None:
"""Maximum value."""
return max(lst) if lst else None
def min_list(lst: list[int]) -> int | None:
"""Minimum value."""
return min(lst) if lst else None
def mean_list(lst: list[int]) -> float | None:
"""Average value."""
return sum(lst) / len(lst) if lst else None
def unique(lst: list[int]) -> list[int]:
"""Get unique values (preserves order)."""
seen: set[int] = set()
result: list[int] = []
for x in lst:
if x not in seen:
seen.add(x)
result.append(x)
return result
def deduplicate(lst: list[int]) -> list[int]:
"""Remove consecutive duplicates."""
if not lst:
return []
result = [lst[0]]
for x in lst[1:]:
if x != result[-1]:
result.append(x)
return result
def zip_lists(lst1: list[int], lst2: list[int]) -> list[tuple[int, int]]:
"""Zip two lists."""
return list(zip(lst1, lst2, strict=False))
def enumerate_list(lst: list[int]) -> list[tuple[int, int]]:
"""Enumerate list."""
return list(enumerate(lst))
def range_list(start: int, end: int, step: int = 1) -> list[int]:
"""Create list from range."""
return list(range(start, end, step))
def main() -> int:
parser = argparse.ArgumentParser(description="Typed list CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create list")
create_p.add_argument("items", nargs="*", type=int, help="Items")
# append
append_p = subparsers.add_parser("append", help="Append item")
append_p.add_argument("list", help="Comma-separated list")
append_p.add_argument("item", type=int, help="Item to append")
# stats
stats_p = subparsers.add_parser("stats", help="Show stats")
stats_p.add_argument("list", help="Comma-separated list")
# sort
sort_p = subparsers.add_parser("sort", help="Sort list")
sort_p.add_argument("list", help="Comma-separated list")
sort_p.add_argument("--desc", action="store_true", help="Descending")
args = parser.parse_args()
def parse_list(s: str) -> list[int]:
return [int(x.strip()) for x in s.split(",") if x.strip()]
if args.command == "create":
lst = create_list(args.items)
print(lst)
elif args.command == "append":
lst = parse_list(args.list)
result = append(lst, args.item)
print(result)
elif args.command == "stats":
lst = parse_list(args.list)
print(f"Size: {list_size(lst)}")
print(f"Sum: {sum_list(lst)}")
print(f"Max: {max_list(lst)}")
print(f"Min: {min_list(lst)}")
print(f"Mean: {mean_list(lst)}")
elif args.command == "sort":
lst = parse_list(args.list)
result = sort_desc(lst) if args.desc else sort_asc(lst)
print(result)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typed_list/typed_list_cli.py (8308 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typed_list/typed_list_cli.rs (28085 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_typed_list/Cargo.toml (1 dependencies)
⏱️ Parse time: 59ms
📊 Throughput: 136.5 KB/s
⏱️ Total time: 59ms
| true
|
typed_list
| 344
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_typed_optional
|
test_typed_optional_cli.py
|
"""Tests for typed_optional_cli.py"""
import pytest
from typed_optional_cli import (
all_some,
and_then,
any_some,
count_some,
expect,
filter_none,
filter_optional,
first_some,
flat_map_optional,
is_none,
is_some,
map_optional,
none_of,
ok_or,
option_to_result,
optional_add,
optional_multiply,
or_else,
replace_none,
result_to_option,
safe_divide,
safe_get_key,
safe_head,
safe_index,
safe_parse_float,
safe_parse_int,
safe_sqrt,
safe_tail,
transpose_list,
unwrap,
unwrap_or,
unwrap_or_else,
zip_optional,
)
class TestIsNoneSome:
def test_is_none(self):
assert is_none(None) is True
assert is_none(42) is False
def test_is_some(self):
assert is_some(42) is True
assert is_some(None) is False
class TestUnwrap:
def test_unwrap_some(self):
assert unwrap(42) == 42
def test_unwrap_none(self):
with pytest.raises(ValueError):
unwrap(None)
def test_unwrap_or_some(self):
assert unwrap_or(42, 0) == 42
def test_unwrap_or_none(self):
assert unwrap_or(None, 99) == 99
def test_unwrap_or_else_some(self):
assert unwrap_or_else(42, lambda: 99) == 42
def test_unwrap_or_else_none(self):
assert unwrap_or_else(None, lambda: 99) == 99
class TestMap:
def test_map_optional_some(self):
result = map_optional(5, lambda x: x * 2)
assert result == 10
def test_map_optional_none(self):
result = map_optional(None, lambda x: x * 2)
assert result is None
class TestFlatMap:
def test_flat_map_some(self):
result = flat_map_optional(5, lambda x: x * 2)
assert result == 10
def test_flat_map_none(self):
result = flat_map_optional(None, lambda x: x * 2)
assert result is None
class TestFilter:
def test_filter_optional_pass(self):
result = filter_optional(10, lambda x: x > 5)
assert result == 10
def test_filter_optional_fail(self):
result = filter_optional(3, lambda x: x > 5)
assert result is None
def test_filter_optional_none(self):
result = filter_optional(None, lambda x: x > 5)
assert result is None
class TestAndThenOrElse:
def test_and_then_some(self):
result = and_then(5, lambda x: x * 2)
assert result == 10
def test_and_then_none(self):
result = and_then(None, lambda x: x * 2)
assert result is None
def test_or_else_some(self):
result = or_else(42, lambda: 99)
assert result == 42
def test_or_else_none(self):
result = or_else(None, lambda: 99)
assert result == 99
class TestZip:
def test_zip_optional_both_some(self):
result = zip_optional(1, 2)
assert result == (1, 2)
def test_zip_optional_first_none(self):
result = zip_optional(None, 2)
assert result is None
def test_zip_optional_second_none(self):
result = zip_optional(1, None)
assert result is None
class TestFirstSome:
def test_first_some(self):
result = first_some(None, None, 42, 99)
assert result == 42
def test_first_some_all_none(self):
result = first_some(None, None, None)
assert result is None
class TestAllSome:
def test_all_some_success(self):
result = all_some(1, 2, 3)
assert result == [1, 2, 3]
def test_all_some_with_none(self):
result = all_some(1, None, 3)
assert result is None
class TestAnySomeNoneOf:
def test_any_some(self):
assert any_some(None, 1, None) is True
assert any_some(None, None) is False
def test_none_of(self):
assert none_of(None, None) is True
assert none_of(None, 1) is False
class TestCountSome:
def test_count_some(self):
assert count_some(1, None, 2, None, 3) == 3
class TestFilterNone:
def test_filter_none(self):
values = [1, None, 2, None, 3]
result = filter_none(values)
assert result == [1, 2, 3]
class TestReplaceNone:
def test_replace_none(self):
values = [1, None, 2, None, 3]
result = replace_none(values, 0)
assert result == [1, 0, 2, 0, 3]
class TestOptionalArithmetic:
def test_optional_add_both_some(self):
assert optional_add(1, 2) == 3
def test_optional_add_with_none(self):
assert optional_add(None, 2) is None
assert optional_add(1, None) is None
def test_optional_multiply(self):
assert optional_multiply(3, 4) == 12
assert optional_multiply(None, 4) is None
class TestSafeMath:
def test_safe_divide(self):
assert safe_divide(10, 2) == 5
assert safe_divide(10, 0) is None
def test_safe_sqrt(self):
assert safe_sqrt(16) == 4.0
assert safe_sqrt(-1) is None
class TestSafeIndex:
def test_safe_index(self):
lst = [10, 20, 30]
assert safe_index(lst, 1) == 20
assert safe_index(lst, 10) is None
def test_safe_head(self):
assert safe_head([1, 2, 3]) == 1
assert safe_head([]) is None
def test_safe_tail(self):
assert safe_tail([1, 2, 3]) == [2, 3]
assert safe_tail([]) is None
class TestSafeParse:
def test_safe_parse_int(self):
assert safe_parse_int("42") == 42
assert safe_parse_int("invalid") is None
def test_safe_parse_float(self):
assert safe_parse_float("3.14") == 3.14
assert safe_parse_float("invalid") is None
class TestSafeGetKey:
def test_safe_get_key(self):
d = {"a": 1, "b": 2}
assert safe_get_key(d, "a") == 1
assert safe_get_key(d, "x") is None
class TestResultConversion:
def test_option_to_result_some(self):
result = option_to_result(42, "error")
assert result == (42, None)
def test_option_to_result_none(self):
result = option_to_result(None, "error")
assert result == (None, "error")
def test_result_to_option(self):
assert result_to_option((42, None)) == 42
assert result_to_option((None, "error")) is None
class TestExpect:
def test_expect_some(self):
assert expect(42, "should not fail") == 42
def test_expect_none(self):
with pytest.raises(ValueError, match="custom error"):
expect(None, "custom error")
class TestOkOr:
def test_ok_or_some(self):
result = ok_or(42, "error")
assert result == (42, None)
def test_ok_or_none(self):
result = ok_or(None, "error")
assert result == (None, "error")
class TestTranspose:
def test_transpose_list_all_some(self):
result = transpose_list([1, 2, 3])
assert result == [1, 2, 3]
def test_transpose_list_with_none(self):
result = transpose_list([1, None, 3])
assert result is None
class TestEdgeCases:
def test_zero_is_some(self):
assert is_some(0) is True
assert is_none(0) is False
def test_empty_string_parse(self):
assert safe_parse_int("") is None
def test_negative_safe_index(self):
lst = [1, 2, 3]
assert safe_index(lst, -1) is None
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typed_optional/test_typed_optional_cli.py (7263 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typed_optional/test_typed_optional_cli.rs (19011 bytes)
⏱️ Parse time: 55ms
📊 Throughput: 128.0 KB/s
⏱️ Total time: 55ms
| true
|
typed_optional
| 295
| 5
|
[
"lambda",
"context_manager",
"class_definition"
] | 0.783
| null |
example_typed_optional
|
typed_optional_cli.py
|
#!/usr/bin/env python3
"""Typed Optional CLI.
Optional and Union type operations.
"""
import argparse
import sys
from typing import TypeVar
T = TypeVar("T")
def is_none(value: int | None) -> bool:
"""Check if value is None."""
return value is None
def is_some(value: int | None) -> bool:
"""Check if value is not None."""
return value is not None
def unwrap(value: int | None) -> int:
"""Unwrap optional value, raise if None."""
if value is None:
raise ValueError("Cannot unwrap None")
return value
def unwrap_or(value: int | None, default: int) -> int:
"""Unwrap optional value or return default."""
return value if value is not None else default
def unwrap_or_else(value: int | None, default_fn: callable) -> int:
"""Unwrap optional or call function for default."""
return value if value is not None else default_fn()
def map_optional(value: int | None, fn: callable) -> int | None:
"""Map function over optional value."""
return fn(value) if value is not None else None
def flat_map_optional(value: int | None, fn: callable) -> int | None:
"""Flat map function over optional value."""
if value is None:
return None
return fn(value)
def filter_optional(value: int | None, predicate: callable) -> int | None:
"""Filter optional value by predicate."""
if value is None:
return None
return value if predicate(value) else None
def and_then(value: int | None, fn: callable) -> int | None:
"""Chain optional operations."""
if value is None:
return None
return fn(value)
def or_else(value: int | None, fn: callable) -> int | None:
"""Provide alternative if None."""
if value is not None:
return value
return fn()
def zip_optional(a: int | None, b: int | None) -> tuple[int, int] | None:
"""Zip two optionals into optional tuple."""
if a is None or b is None:
return None
return (a, b)
def first_some(*values: int | None) -> int | None:
"""Return first non-None value."""
for v in values:
if v is not None:
return v
return None
def all_some(*values: int | None) -> list[int] | None:
"""Return list if all values are Some, else None."""
result = []
for v in values:
if v is None:
return None
result.append(v)
return result
def any_some(*values: int | None) -> bool:
"""Check if any value is Some."""
return any(v is not None for v in values)
def none_of(*values: int | None) -> bool:
"""Check if all values are None."""
return all(v is None for v in values)
def count_some(*values: int | None) -> int:
"""Count non-None values."""
return sum(1 for v in values if v is not None)
def filter_none(values: list[int | None]) -> list[int]:
"""Filter out None values from list."""
return [v for v in values if v is not None]
def replace_none(values: list[int | None], default: int) -> list[int]:
"""Replace None values with default."""
return [v if v is not None else default for v in values]
def optional_add(a: int | None, b: int | None) -> int | None:
"""Add two optional values."""
if a is None or b is None:
return None
return a + b
def optional_multiply(a: int | None, b: int | None) -> int | None:
"""Multiply two optional values."""
if a is None or b is None:
return None
return a * b
def safe_divide(a: int, b: int) -> int | None:
"""Divide, return None if divisor is zero."""
if b == 0:
return None
return a // b
def safe_sqrt(n: int) -> float | None:
"""Square root, return None if negative."""
if n < 0:
return None
return n**0.5
def safe_index(lst: list[int], index: int) -> int | None:
"""Get list item, return None if out of bounds."""
if 0 <= index < len(lst):
return lst[index]
return None
def safe_head(lst: list[int]) -> int | None:
"""Get first item, return None if empty."""
return lst[0] if lst else None
def safe_tail(lst: list[int]) -> list[int] | None:
"""Get tail, return None if empty."""
return lst[1:] if lst else None
def safe_parse_int(s: str) -> int | None:
"""Parse int, return None if invalid."""
try:
return int(s)
except ValueError:
return None
def safe_parse_float(s: str) -> float | None:
"""Parse float, return None if invalid."""
try:
return float(s)
except ValueError:
return None
def safe_get_key(d: dict[str, int], key: str) -> int | None:
"""Get dict value, return None if missing."""
return d.get(key)
def option_to_result(value: int | None, error: str) -> tuple[int | None, str | None]:
"""Convert optional to result (value, error) tuple."""
if value is not None:
return (value, None)
return (None, error)
def result_to_option(result: tuple[int | None, str | None]) -> int | None:
"""Convert result to optional (discard error)."""
return result[0]
def expect(value: int | None, message: str) -> int:
"""Unwrap with custom error message."""
if value is None:
raise ValueError(message)
return value
def ok_or(value: int | None, error: str) -> tuple[int | None, str | None]:
"""Convert optional to result with error."""
if value is not None:
return (value, None)
return (None, error)
def transpose_list(values: list[int | None]) -> list[int] | None:
"""Transpose list of optionals to optional list."""
result = []
for v in values:
if v is None:
return None
result.append(v)
return result
def main() -> int:
parser = argparse.ArgumentParser(description="Typed optional CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# unwrap
unwrap_p = subparsers.add_parser("unwrap", help="Unwrap value")
unwrap_p.add_argument("value", nargs="?", help="Value or 'none'")
unwrap_p.add_argument("--default", type=int, help="Default value")
# safe-div
div_p = subparsers.add_parser("safe-div", help="Safe division")
div_p.add_argument("a", type=int, help="Dividend")
div_p.add_argument("b", type=int, help="Divisor")
# parse
parse_p = subparsers.add_parser("parse", help="Safe parse int")
parse_p.add_argument("value", help="Value to parse")
# filter
filter_p = subparsers.add_parser("filter", help="Filter None values")
filter_p.add_argument("values", nargs="+", help="Values (use 'none' for None)")
args = parser.parse_args()
def parse_optional(s: str) -> int | None:
if s.lower() == "none":
return None
try:
return int(s)
except ValueError:
return None
if args.command == "unwrap":
value = parse_optional(args.value) if args.value else None
if args.default is not None:
result = unwrap_or(value, args.default)
print(f"Result: {result}")
else:
try:
result = unwrap(value)
print(f"Result: {result}")
except ValueError as e:
print(f"Error: {e}")
return 1
elif args.command == "safe-div":
result = safe_divide(args.a, args.b)
if result is not None:
print(f"Result: {result}")
else:
print("Cannot divide by zero")
elif args.command == "parse":
result = safe_parse_int(args.value)
if result is not None:
print(f"Parsed: {result}")
else:
print("Invalid integer")
elif args.command == "filter":
values = [parse_optional(v) for v in args.values]
filtered = filter_none(values)
print(f"Filtered: {filtered}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typed_optional/typed_optional_cli.py (7894 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typed_optional/typed_optional_cli.rs (16056 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_typed_optional/Cargo.toml (4 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 136.3 KB/s
⏱️ Total time: 56ms
| true
|
typed_optional
| 297
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_typed_set
|
test_typed_set_cli.py
|
"""Tests for typed_set_cli.py"""
from typed_set_cli import (
add_item,
clear_set,
contains,
copy_set,
create_empty_set,
create_set,
difference,
filter_even,
filter_gt,
filter_lt,
filter_odd,
from_range,
intersection,
intersects,
is_disjoint,
is_empty,
is_proper_subset,
is_proper_superset,
is_subset,
is_superset,
jaccard_similarity,
map_double,
map_square,
max_set,
min_set,
partition,
pop_item,
power_set,
remove_item,
set_size,
sum_set,
symmetric_difference,
to_frozenset,
to_list,
union,
)
class TestCreate:
def test_create_empty_set(self):
s = create_empty_set()
assert s == set()
def test_create_set(self):
s = create_set([1, 2, 3, 2, 1])
assert s == {1, 2, 3}
class TestAddRemove:
def test_add_item(self):
s = {1, 2}
result = add_item(s, 3)
assert result == {1, 2, 3}
assert s == {1, 2}
def test_add_existing(self):
s = {1, 2}
result = add_item(s, 2)
assert result == {1, 2}
def test_remove_item(self):
s = {1, 2, 3}
result = remove_item(s, 2)
assert result == {1, 3}
def test_remove_nonexistent(self):
s = {1, 2}
result = remove_item(s, 5)
assert result == {1, 2}
class TestPop:
def test_pop_item(self):
s = {1, 2, 3}
item, result = pop_item(s)
assert item in {1, 2, 3}
assert len(result) == 2
def test_pop_empty(self):
item, result = pop_item(set())
assert item is None
assert result == set()
class TestContains:
def test_contains(self):
s = {1, 2, 3}
assert contains(s, 2) is True
assert contains(s, 5) is False
class TestSize:
def test_set_size(self):
assert set_size(set()) == 0
assert set_size({1, 2, 3}) == 3
def test_is_empty(self):
assert is_empty(set()) is True
assert is_empty({1}) is False
class TestCopy:
def test_clear_set(self):
s = {1, 2, 3}
result = clear_set(s)
assert result == set()
def test_copy_set(self):
s = {1, 2, 3}
result = copy_set(s)
assert result == s
assert result is not s
class TestSetOperations:
def test_union(self):
s1 = {1, 2, 3}
s2 = {3, 4, 5}
assert union(s1, s2) == {1, 2, 3, 4, 5}
def test_intersection(self):
s1 = {1, 2, 3}
s2 = {2, 3, 4}
assert intersection(s1, s2) == {2, 3}
def test_difference(self):
s1 = {1, 2, 3}
s2 = {2, 3, 4}
assert difference(s1, s2) == {1}
def test_symmetric_difference(self):
s1 = {1, 2, 3}
s2 = {2, 3, 4}
assert symmetric_difference(s1, s2) == {1, 4}
class TestSubsetSuperset:
def test_is_subset(self):
s1 = {1, 2}
s2 = {1, 2, 3}
assert is_subset(s1, s2) is True
assert is_subset(s2, s1) is False
def test_is_superset(self):
s1 = {1, 2, 3}
s2 = {1, 2}
assert is_superset(s1, s2) is True
def test_is_proper_subset(self):
s1 = {1, 2}
s2 = {1, 2, 3}
assert is_proper_subset(s1, s2) is True
assert is_proper_subset(s1, s1) is False
def test_is_proper_superset(self):
s1 = {1, 2, 3}
s2 = {1, 2}
assert is_proper_superset(s1, s2) is True
class TestDisjoint:
def test_is_disjoint(self):
s1 = {1, 2}
s2 = {3, 4}
assert is_disjoint(s1, s2) is True
s3 = {2, 3}
assert is_disjoint(s1, s3) is False
class TestConversion:
def test_to_list(self):
s = {3, 1, 2}
assert to_list(s) == [1, 2, 3]
def test_to_frozenset(self):
s = {1, 2, 3}
fs = to_frozenset(s)
assert isinstance(fs, frozenset)
assert fs == frozenset({1, 2, 3})
class TestFromRange:
def test_from_range(self):
s = from_range(1, 5)
assert s == {1, 2, 3, 4}
class TestFilter:
def test_filter_gt(self):
s = {1, 2, 3, 4, 5}
assert filter_gt(s, 3) == {4, 5}
def test_filter_lt(self):
s = {1, 2, 3, 4, 5}
assert filter_lt(s, 3) == {1, 2}
def test_filter_even(self):
s = {1, 2, 3, 4, 5}
assert filter_even(s) == {2, 4}
def test_filter_odd(self):
s = {1, 2, 3, 4, 5}
assert filter_odd(s) == {1, 3, 5}
class TestMap:
def test_map_double(self):
s = {1, 2, 3}
assert map_double(s) == {2, 4, 6}
def test_map_square(self):
s = {1, 2, 3}
assert map_square(s) == {1, 4, 9}
class TestAggregate:
def test_sum_set(self):
s = {1, 2, 3}
assert sum_set(s) == 6
def test_max_set(self):
s = {1, 5, 3}
assert max_set(s) == 5
assert max_set(set()) is None
def test_min_set(self):
s = {1, 5, 3}
assert min_set(s) == 1
assert min_set(set()) is None
class TestPowerSet:
def test_power_set(self):
s = {1, 2}
ps = power_set(s)
assert len(ps) == 4
assert set() in ps
assert {1} in ps
assert {2} in ps
assert {1, 2} in ps
class TestPartition:
def test_partition(self):
s = {1, 2, 3, 4, 5}
less, greater_eq = partition(s, 3)
assert less == {1, 2}
assert greater_eq == {3, 4, 5}
class TestIntersects:
def test_intersects(self):
s1 = {1, 2, 3}
s2 = {3, 4, 5}
assert intersects(s1, s2) is True
s3 = {6, 7}
assert intersects(s1, s3) is False
class TestJaccard:
def test_jaccard_similarity(self):
s1 = {1, 2, 3}
s2 = {2, 3, 4}
# intersection = {2, 3} = 2, union = {1, 2, 3, 4} = 4
assert jaccard_similarity(s1, s2) == 0.5
def test_jaccard_empty(self):
assert jaccard_similarity(set(), set()) == 1.0
def test_jaccard_identical(self):
s = {1, 2, 3}
assert jaccard_similarity(s, s) == 1.0
class TestEdgeCases:
def test_empty_operations(self):
s: set[int] = set()
assert sum_set(s) == 0
assert to_list(s) == []
def test_single_element(self):
s = {42}
assert max_set(s) == 42
assert min_set(s) == 42
| false
|
typed_set
| 287
| 0
|
[
"class_definition"
] | 0.612
|
Error: 'is not' operator not yet supported (use != for value comparison)
|
|
example_typed_set
|
typed_set_cli.py
|
#!/usr/bin/env python3
"""Typed Set CLI.
Set operations with type hints.
"""
import argparse
import sys
def create_empty_set() -> set[int]:
"""Create empty typed set."""
return set()
def create_set(items: list[int]) -> set[int]:
"""Create set from items."""
return set(items)
def add_item(s: set[int], item: int) -> set[int]:
"""Add item to set (returns new set)."""
result = s.copy()
result.add(item)
return result
def remove_item(s: set[int], item: int) -> set[int]:
"""Remove item from set (returns new set)."""
result = s.copy()
result.discard(item)
return result
def pop_item(s: set[int]) -> tuple[int | None, set[int]]:
"""Pop arbitrary item, return (item, new_set)."""
if not s:
return (None, set())
result = s.copy()
item = result.pop()
return (item, result)
def contains(s: set[int], item: int) -> bool:
"""Check if set contains item."""
return item in s
def set_size(s: set[int]) -> int:
"""Get set size."""
return len(s)
def is_empty(s: set[int]) -> bool:
"""Check if set is empty."""
return len(s) == 0
def clear_set(s: set[int]) -> set[int]:
"""Return empty set."""
return set()
def copy_set(s: set[int]) -> set[int]:
"""Copy set."""
return s.copy()
def union(s1: set[int], s2: set[int]) -> set[int]:
"""Union of two sets."""
return s1 | s2
def intersection(s1: set[int], s2: set[int]) -> set[int]:
"""Intersection of two sets."""
return s1 & s2
def difference(s1: set[int], s2: set[int]) -> set[int]:
"""Difference of two sets (s1 - s2)."""
return s1 - s2
def symmetric_difference(s1: set[int], s2: set[int]) -> set[int]:
"""Symmetric difference of two sets."""
return s1 ^ s2
def is_subset(s1: set[int], s2: set[int]) -> bool:
"""Check if s1 is subset of s2."""
return s1 <= s2
def is_superset(s1: set[int], s2: set[int]) -> bool:
"""Check if s1 is superset of s2."""
return s1 >= s2
def is_proper_subset(s1: set[int], s2: set[int]) -> bool:
"""Check if s1 is proper subset of s2."""
return s1 < s2
def is_proper_superset(s1: set[int], s2: set[int]) -> bool:
"""Check if s1 is proper superset of s2."""
return s1 > s2
def is_disjoint(s1: set[int], s2: set[int]) -> bool:
"""Check if sets have no common elements."""
return s1.isdisjoint(s2)
def to_list(s: set[int]) -> list[int]:
"""Convert set to sorted list."""
return sorted(s)
def to_frozenset(s: set[int]) -> frozenset[int]:
"""Convert to frozenset."""
return frozenset(s)
def from_range(start: int, end: int) -> set[int]:
"""Create set from range."""
return set(range(start, end))
def filter_gt(s: set[int], threshold: int) -> set[int]:
"""Filter items greater than threshold."""
return {x for x in s if x > threshold}
def filter_lt(s: set[int], threshold: int) -> set[int]:
"""Filter items less than threshold."""
return {x for x in s if x < threshold}
def filter_even(s: set[int]) -> set[int]:
"""Filter even numbers."""
return {x for x in s if x % 2 == 0}
def filter_odd(s: set[int]) -> set[int]:
"""Filter odd numbers."""
return {x for x in s if x % 2 != 0}
def map_double(s: set[int]) -> set[int]:
"""Double all values."""
return {x * 2 for x in s}
def map_square(s: set[int]) -> set[int]:
"""Square all values."""
return {x * x for x in s}
def sum_set(s: set[int]) -> int:
"""Sum all values."""
return sum(s)
def max_set(s: set[int]) -> int | None:
"""Maximum value."""
return max(s) if s else None
def min_set(s: set[int]) -> int | None:
"""Minimum value."""
return min(s) if s else None
def power_set(s: set[int]) -> list[set[int]]:
"""Generate power set (all subsets)."""
items = list(s)
n = len(items)
result: list[set[int]] = []
for i in range(2**n):
subset: set[int] = set()
for j in range(n):
if i & (1 << j):
subset.add(items[j])
result.append(subset)
return result
def partition(s: set[int], pivot: int) -> tuple[set[int], set[int]]:
"""Partition set into (< pivot, >= pivot)."""
less = {x for x in s if x < pivot}
greater_eq = {x for x in s if x >= pivot}
return (less, greater_eq)
def intersects(s1: set[int], s2: set[int]) -> bool:
"""Check if sets have any common elements."""
return not s1.isdisjoint(s2)
def jaccard_similarity(s1: set[int], s2: set[int]) -> float:
"""Calculate Jaccard similarity coefficient."""
if not s1 and not s2:
return 1.0
intersection_size = len(s1 & s2)
union_size = len(s1 | s2)
return intersection_size / union_size
def main() -> int:
parser = argparse.ArgumentParser(description="Typed set CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create set")
create_p.add_argument("items", nargs="*", type=int, help="Items")
# union
union_p = subparsers.add_parser("union", help="Union of sets")
union_p.add_argument("set1", help="First set (comma-separated)")
union_p.add_argument("set2", help="Second set (comma-separated)")
# intersect
intersect_p = subparsers.add_parser("intersect", help="Intersection")
intersect_p.add_argument("set1", help="First set")
intersect_p.add_argument("set2", help="Second set")
# diff
diff_p = subparsers.add_parser("diff", help="Difference")
diff_p.add_argument("set1", help="First set")
diff_p.add_argument("set2", help="Second set")
args = parser.parse_args()
def parse_set(s: str) -> set[int]:
return {int(x.strip()) for x in s.split(",") if x.strip()}
if args.command == "create":
s = create_set(args.items)
print(sorted(s))
elif args.command == "union":
s1 = parse_set(args.set1)
s2 = parse_set(args.set2)
result = union(s1, s2)
print(sorted(result))
elif args.command == "intersect":
s1 = parse_set(args.set1)
s2 = parse_set(args.set2)
result = intersection(s1, s2)
print(sorted(result))
elif args.command == "diff":
s1 = parse_set(args.set1)
s2 = parse_set(args.set2)
result = difference(s1, s2)
print(sorted(result))
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typed_set/typed_set_cli.py (6467 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typed_set/typed_set_cli.rs (15099 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_typed_set/Cargo.toml (1 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 117.4 KB/s
⏱️ Total time: 53ms
| true
|
typed_set
| 266
| 6
|
[
"context_manager"
] | 0.652
| null |
example_typed_tuple
|
test_typed_tuple_cli.py
|
"""Tests for typed_tuple_cli.py"""
from typed_tuple_cli import (
compare_tuples,
concat,
contains,
count_item,
create_empty_tuple,
create_pair,
create_triple,
create_tuple,
drop,
enumerate_tuple,
filter_even,
filter_gt,
filter_odd,
from_list,
get_at,
get_first,
get_last,
get_second,
index_of,
is_empty,
map_double,
map_square,
max_tuple,
mean_tuple,
min_tuple,
partition,
product_tuple,
repeat,
reverse_tuple,
slice_tuple,
sort_desc,
sort_tuple,
split_at,
sum_tuple,
swap_pair,
take,
take_while_positive,
to_list,
tuple_size,
unique_tuple,
unpack_pair,
zip_tuples,
)
class TestCreate:
def test_create_empty_tuple(self):
t = create_empty_tuple()
assert t == ()
def test_create_pair(self):
t = create_pair(1, 2)
assert t == (1, 2)
def test_create_triple(self):
t = create_triple(1, 2, 3)
assert t == (1, 2, 3)
def test_create_tuple(self):
t = create_tuple(1, 2, 3, 4)
assert t == (1, 2, 3, 4)
class TestConversion:
def test_from_list(self):
t = from_list([1, 2, 3])
assert t == (1, 2, 3)
def test_to_list(self):
lst = to_list((1, 2, 3))
assert lst == [1, 2, 3]
class TestAccess:
def test_get_first(self):
assert get_first((1, 2, 3)) == 1
assert get_first(()) is None
def test_get_second(self):
assert get_second((1, 2, 3)) == 2
assert get_second((1,)) is None
def test_get_last(self):
assert get_last((1, 2, 3)) == 3
assert get_last(()) is None
def test_get_at(self):
t = (1, 2, 3)
assert get_at(t, 1) == 2
assert get_at(t, 10) is None
class TestSize:
def test_tuple_size(self):
assert tuple_size(()) == 0
assert tuple_size((1, 2, 3)) == 3
def test_is_empty(self):
assert is_empty(()) is True
assert is_empty((1,)) is False
class TestContains:
def test_contains(self):
t = (1, 2, 3)
assert contains(t, 2) is True
assert contains(t, 5) is False
def test_index_of(self):
t = (1, 2, 3)
assert index_of(t, 2) == 1
assert index_of(t, 5) == -1
def test_count_item(self):
t = (1, 2, 2, 3, 2)
assert count_item(t, 2) == 3
class TestSlice:
def test_slice_tuple(self):
t = (1, 2, 3, 4, 5)
assert slice_tuple(t, 1, 4) == (2, 3, 4)
class TestCombine:
def test_concat(self):
t1 = (1, 2)
t2 = (3, 4)
assert concat(t1, t2) == (1, 2, 3, 4)
def test_repeat(self):
t = (1, 2)
assert repeat(t, 3) == (1, 2, 1, 2, 1, 2)
class TestOrder:
def test_reverse_tuple(self):
t = (1, 2, 3)
assert reverse_tuple(t) == (3, 2, 1)
def test_sort_tuple(self):
t = (3, 1, 2)
assert sort_tuple(t) == (1, 2, 3)
def test_sort_desc(self):
t = (1, 3, 2)
assert sort_desc(t) == (3, 2, 1)
class TestAggregate:
def test_min_tuple(self):
assert min_tuple((1, 5, 3)) == 1
assert min_tuple(()) is None
def test_max_tuple(self):
assert max_tuple((1, 5, 3)) == 5
assert max_tuple(()) is None
def test_sum_tuple(self):
assert sum_tuple((1, 2, 3)) == 6
def test_product_tuple(self):
assert product_tuple((1, 2, 3, 4)) == 24
def test_mean_tuple(self):
assert mean_tuple((1, 2, 3)) == 2.0
assert mean_tuple(()) is None
class TestUnique:
def test_unique_tuple(self):
t = (1, 2, 2, 3, 1, 4)
assert unique_tuple(t) == (1, 2, 3, 4)
class TestFilter:
def test_filter_gt(self):
t = (1, 2, 3, 4, 5)
assert filter_gt(t, 3) == (4, 5)
def test_filter_even(self):
t = (1, 2, 3, 4, 5)
assert filter_even(t) == (2, 4)
def test_filter_odd(self):
t = (1, 2, 3, 4, 5)
assert filter_odd(t) == (1, 3, 5)
class TestMap:
def test_map_double(self):
t = (1, 2, 3)
assert map_double(t) == (2, 4, 6)
def test_map_square(self):
t = (1, 2, 3)
assert map_square(t) == (1, 4, 9)
class TestZip:
def test_zip_tuples(self):
t1 = (1, 2, 3)
t2 = (4, 5, 6)
assert zip_tuples(t1, t2) == ((1, 4), (2, 5), (3, 6))
def test_enumerate_tuple(self):
t = (10, 20, 30)
assert enumerate_tuple(t) == ((0, 10), (1, 20), (2, 30))
class TestPair:
def test_unpack_pair(self):
t = (1, 2)
a, b = unpack_pair(t)
assert a == 1
assert b == 2
def test_swap_pair(self):
t = (1, 2)
assert swap_pair(t) == (2, 1)
class TestCompare:
def test_compare_tuples_less(self):
t1 = (1, 2)
t2 = (1, 3)
assert compare_tuples(t1, t2) == -1
def test_compare_tuples_greater(self):
t1 = (1, 3)
t2 = (1, 2)
assert compare_tuples(t1, t2) == 1
def test_compare_tuples_equal(self):
t1 = (1, 2)
t2 = (1, 2)
assert compare_tuples(t1, t2) == 0
class TestTakeDrop:
def test_take(self):
t = (1, 2, 3, 4, 5)
assert take(t, 3) == (1, 2, 3)
def test_drop(self):
t = (1, 2, 3, 4, 5)
assert drop(t, 2) == (3, 4, 5)
def test_take_while_positive(self):
t = (1, 2, 3, -1, 4, 5)
assert take_while_positive(t) == (1, 2, 3)
class TestSplit:
def test_split_at(self):
t = (1, 2, 3, 4, 5)
left, right = split_at(t, 2)
assert left == (1, 2)
assert right == (3, 4, 5)
def test_partition(self):
t = (1, 2, 3, 4, 5)
less, greater_eq = partition(t, 3)
assert less == (1, 2)
assert greater_eq == (3, 4, 5)
class TestEdgeCases:
def test_empty_operations(self):
t: tuple[int, ...] = ()
assert sum_tuple(t) == 0
assert product_tuple(t) == 1
def test_single_element(self):
t = (42,)
assert max_tuple(t) == 42
assert min_tuple(t) == 42
| false
|
typed_tuple
| 280
| 0
|
[
"class_definition"
] | 0.612
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 5938..5941, value: Ellipsis, kind: None })
|
|
example_typed_tuple
|
typed_tuple_cli.py
|
#!/usr/bin/env python3
"""Typed Tuple CLI.
Tuple operations with type hints.
"""
import argparse
import sys
def create_empty_tuple() -> tuple[()]:
"""Create empty tuple."""
return ()
def create_pair(a: int, b: int) -> tuple[int, int]:
"""Create pair tuple."""
return (a, b)
def create_triple(a: int, b: int, c: int) -> tuple[int, int, int]:
"""Create triple tuple."""
return (a, b, c)
def create_tuple(*items: int) -> tuple[int, ...]:
"""Create tuple from items."""
return tuple(items)
def from_list(items: list[int]) -> tuple[int, ...]:
"""Create tuple from list."""
return tuple(items)
def to_list(t: tuple[int, ...]) -> list[int]:
"""Convert tuple to list."""
return list(t)
def get_first(t: tuple[int, ...]) -> int | None:
"""Get first element."""
return t[0] if t else None
def get_second(t: tuple[int, int, ...]) -> int | None:
"""Get second element."""
return t[1] if len(t) > 1 else None
def get_last(t: tuple[int, ...]) -> int | None:
"""Get last element."""
return t[-1] if t else None
def get_at(t: tuple[int, ...], index: int) -> int | None:
"""Get element at index."""
if 0 <= index < len(t):
return t[index]
return None
def tuple_size(t: tuple[int, ...]) -> int:
"""Get tuple size."""
return len(t)
def is_empty(t: tuple[int, ...]) -> bool:
"""Check if tuple is empty."""
return len(t) == 0
def contains(t: tuple[int, ...], item: int) -> bool:
"""Check if tuple contains item."""
return item in t
def index_of(t: tuple[int, ...], item: int) -> int:
"""Get index of item, -1 if not found."""
try:
return t.index(item)
except ValueError:
return -1
def count_item(t: tuple[int, ...], item: int) -> int:
"""Count occurrences of item."""
return t.count(item)
def slice_tuple(t: tuple[int, ...], start: int, end: int) -> tuple[int, ...]:
"""Slice tuple from start to end."""
return t[start:end]
def concat(t1: tuple[int, ...], t2: tuple[int, ...]) -> tuple[int, ...]:
"""Concatenate two tuples."""
return t1 + t2
def repeat(t: tuple[int, ...], n: int) -> tuple[int, ...]:
"""Repeat tuple n times."""
return t * n
def reverse_tuple(t: tuple[int, ...]) -> tuple[int, ...]:
"""Reverse tuple."""
return t[::-1]
def sort_tuple(t: tuple[int, ...]) -> tuple[int, ...]:
"""Sort tuple."""
return tuple(sorted(t))
def sort_desc(t: tuple[int, ...]) -> tuple[int, ...]:
"""Sort tuple descending."""
return tuple(sorted(t, reverse=True))
def min_tuple(t: tuple[int, ...]) -> int | None:
"""Get minimum value."""
return min(t) if t else None
def max_tuple(t: tuple[int, ...]) -> int | None:
"""Get maximum value."""
return max(t) if t else None
def sum_tuple(t: tuple[int, ...]) -> int:
"""Sum all values."""
return sum(t)
def product_tuple(t: tuple[int, ...]) -> int:
"""Product of all values."""
result = 1
for x in t:
result *= x
return result
def mean_tuple(t: tuple[int, ...]) -> float | None:
"""Average of values."""
return sum(t) / len(t) if t else None
def unique_tuple(t: tuple[int, ...]) -> tuple[int, ...]:
"""Get unique values (preserves order)."""
seen: set[int] = set()
result: list[int] = []
for x in t:
if x not in seen:
seen.add(x)
result.append(x)
return tuple(result)
def filter_gt(t: tuple[int, ...], threshold: int) -> tuple[int, ...]:
"""Filter values greater than threshold."""
return tuple(x for x in t if x > threshold)
def filter_even(t: tuple[int, ...]) -> tuple[int, ...]:
"""Filter even values."""
return tuple(x for x in t if x % 2 == 0)
def filter_odd(t: tuple[int, ...]) -> tuple[int, ...]:
"""Filter odd values."""
return tuple(x for x in t if x % 2 != 0)
def map_double(t: tuple[int, ...]) -> tuple[int, ...]:
"""Double all values."""
return tuple(x * 2 for x in t)
def map_square(t: tuple[int, ...]) -> tuple[int, ...]:
"""Square all values."""
return tuple(x * x for x in t)
def zip_tuples(t1: tuple[int, ...], t2: tuple[int, ...]) -> tuple[tuple[int, int], ...]:
"""Zip two tuples."""
return tuple(zip(t1, t2, strict=False))
def enumerate_tuple(t: tuple[int, ...]) -> tuple[tuple[int, int], ...]:
"""Enumerate tuple."""
return tuple(enumerate(t))
def unpack_pair(t: tuple[int, int]) -> tuple[int, int]:
"""Unpack pair tuple."""
return (t[0], t[1])
def swap_pair(t: tuple[int, int]) -> tuple[int, int]:
"""Swap pair elements."""
return (t[1], t[0])
def compare_tuples(t1: tuple[int, ...], t2: tuple[int, ...]) -> int:
"""Compare tuples lexicographically (-1, 0, 1)."""
if t1 < t2:
return -1
elif t1 > t2:
return 1
return 0
def take(t: tuple[int, ...], n: int) -> tuple[int, ...]:
"""Take first n elements."""
return t[:n]
def drop(t: tuple[int, ...], n: int) -> tuple[int, ...]:
"""Drop first n elements."""
return t[n:]
def take_while_positive(t: tuple[int, ...]) -> tuple[int, ...]:
"""Take while elements are positive."""
result: list[int] = []
for x in t:
if x <= 0:
break
result.append(x)
return tuple(result)
def split_at(t: tuple[int, ...], index: int) -> tuple[tuple[int, ...], tuple[int, ...]]:
"""Split tuple at index."""
return (t[:index], t[index:])
def partition(t: tuple[int, ...], pivot: int) -> tuple[tuple[int, ...], tuple[int, ...]]:
"""Partition into (< pivot, >= pivot)."""
less = tuple(x for x in t if x < pivot)
greater_eq = tuple(x for x in t if x >= pivot)
return (less, greater_eq)
def main() -> int:
parser = argparse.ArgumentParser(description="Typed tuple CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create tuple")
create_p.add_argument("items", nargs="*", type=int, help="Items")
# pair
pair_p = subparsers.add_parser("pair", help="Create pair")
pair_p.add_argument("a", type=int, help="First element")
pair_p.add_argument("b", type=int, help="Second element")
# stats
stats_p = subparsers.add_parser("stats", help="Show stats")
stats_p.add_argument("tuple", help="Comma-separated tuple")
args = parser.parse_args()
def parse_tuple(s: str) -> tuple[int, ...]:
return tuple(int(x.strip()) for x in s.split(",") if x.strip())
if args.command == "create":
t = create_tuple(*args.items)
print(t)
elif args.command == "pair":
t = create_pair(args.a, args.b)
print(t)
elif args.command == "stats":
t = parse_tuple(args.tuple)
print(f"Size: {tuple_size(t)}")
print(f"Sum: {sum_tuple(t)}")
print(f"Max: {max_tuple(t)}")
print(f"Min: {min_tuple(t)}")
print(f"Mean: {mean_tuple(t)}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
typed_tuple
| 291
| 0
|
[
"context_manager",
"exception_handling"
] | 0.652
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 463..466, value: Ellipsis, kind: None })
|
|
example_typing
|
test_type_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for typing CLI."""
import subprocess
SCRIPT = "type_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestTyping:
def test_int(self): r = run(["check", "int", "42"]); assert "valid" in r.stdout.lower()
def test_float(self): r = run(["check", "float", "3.14"]); assert "valid" in r.stdout.lower()
def test_str(self): r = run(["check", "str", "hello"]); assert "valid" in r.stdout.lower()
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typing/test_type_tool.py (621 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typing/test_type_tool.rs (1928 bytes)
⏱️ Parse time: 47ms
📊 Throughput: 12.9 KB/s
⏱️ Total time: 47ms
| true
|
typing
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_typing
|
type_tool.py
|
#!/usr/bin/env python3
"""Typing Example - Type checking CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Type checking tool")
subs = parser.add_subparsers(dest="cmd", required=True)
c = subs.add_parser("check")
c.add_argument("typename")
c.add_argument("value")
args = parser.parse_args()
if args.cmd == "check":
if args.typename == "int":
print("valid int")
elif args.typename == "float":
print("valid float")
elif args.typename == "str":
print("valid str")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_typing/type_tool.py (626 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_typing/type_tool.rs (1163 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_typing/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 12.5 KB/s
⏱️ Total time: 49ms
| true
|
typing
| 26
| 6
|
[] | 0
| null |
example_urlparse
|
test_url_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for urllib.parse CLI."""
import subprocess
SCRIPT = "url_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestParse:
def test_parse(self):
result = run(["parse", "https://example.com:8080/path?q=1#frag"])
assert result.returncode == 0
assert "scheme: https" in result.stdout.lower()
assert "8080" in result.stdout
class TestEncode:
def test_encode(self):
result = run(["encode", "hello world"])
assert result.returncode == 0
assert "hello%20world" in result.stdout or "hello+world" in result.stdout
class TestDecode:
def test_decode(self):
result = run(["decode", "hello%20world"])
assert result.returncode == 0
assert "hello world" in result.stdout
class TestJoin:
def test_join(self):
result = run(["join", "https://example.com/base/", "../other"])
assert result.returncode == 0
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_urlparse/test_url_tool.py (1151 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_urlparse/test_url_tool.rs (2938 bytes)
⏱️ Parse time: 46ms
📊 Throughput: 24.2 KB/s
⏱️ Total time: 46ms
| true
|
urlparse
| 35
| 5
|
[
"class_definition"
] | 0.612
| null |
example_urlparse
|
url_tool.py
|
#!/usr/bin/env python3
"""URL Parse Example - URL manipulation CLI."""
import argparse
from urllib.parse import quote, unquote, urljoin, urlparse
def cmd_parse(args):
"""Parse URL. Depyler: proven to terminate"""
u = urlparse(args.url)
print(f"Scheme: {u.scheme}")
print(f"Host: {u.hostname}")
print(f"Port: {u.port}")
print(f"Path: {u.path}")
print(f"Query: {u.query}")
print(f"Fragment: {u.fragment}")
def cmd_encode(args):
"""URL encode string. Depyler: proven to terminate"""
print(quote(args.text))
def cmd_decode(args):
"""URL decode string. Depyler: proven to terminate"""
print(unquote(args.text))
def cmd_join(args):
"""Join URL parts. Depyler: proven to terminate"""
print(urljoin(args.base, args.path))
def main():
parser = argparse.ArgumentParser(description="URL tool")
subs = parser.add_subparsers(dest="command", required=True)
p = subs.add_parser("parse")
p.add_argument("url")
e = subs.add_parser("encode")
e.add_argument("text")
d = subs.add_parser("decode")
d.add_argument("text")
j = subs.add_parser("join")
j.add_argument("base")
j.add_argument("path")
args = parser.parse_args()
{"parse": cmd_parse, "encode": cmd_encode, "decode": cmd_decode, "join": cmd_join}[
args.command
](args)
if __name__ == "__main__":
main()
| false
|
urlparse
| 53
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1220..1330, value: Dict(ExprDict { range: 1220..1302, keys: [Some(Constant(ExprConstant { range: 1221..1228, value: Str("parse"), kind: None })), Some(Constant(ExprConstant { range: 1241..1249, value: Str("encode"), kind: None })), Some(Constant(ExprConstant { range: 1263..1271, value: Str("decode"), kind: None })), Some(Constant(ExprConstant { range: 1285..1291, value: Str("join"), kind: None }))], values: [Name(ExprName {
|
|
example_uuid
|
test_uuid_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for uuid CLI."""
import re
import subprocess
SCRIPT = "uuid_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestUUID4:
def test_generate(self):
result = run(["uuid4"])
assert result.returncode == 0
assert re.match(r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}", result.stdout.strip())
class TestUUID5:
def test_generate(self):
result = run(["uuid5", "--namespace", "dns", "--name", "example.com"])
assert result.returncode == 0
class TestParse:
def test_parse(self):
result = run(["parse", "550e8400-e29b-41d4-a716-446655440000"])
assert result.returncode == 0
assert "version" in result.stdout.lower()
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_uuid/test_uuid_tool.py (961 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_uuid/test_uuid_tool.rs (2449 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_uuid/Cargo.toml (2 dependencies)
⏱️ Parse time: 95ms
📊 Throughput: 9.8 KB/s
⏱️ Total time: 96ms
| true
|
uuid
| 29
| 6
|
[
"class_definition"
] | 0.612
| null |
example_uuid
|
uuid_tool.py
|
#!/usr/bin/env python3
"""UUID Example - UUID generation CLI."""
import argparse
import uuid
def cmd_uuid4(args):
"""Generate random UUID. Depyler: proven to terminate"""
print(uuid.uuid4())
def cmd_uuid5(args):
"""Generate UUID5 from namespace+name. Depyler: proven to terminate"""
ns = {"dns": uuid.NAMESPACE_DNS, "url": uuid.NAMESPACE_URL, "oid": uuid.NAMESPACE_OID}[
args.namespace
]
print(uuid.uuid5(ns, args.name))
def cmd_parse(args):
"""Parse UUID string. Depyler: proven to terminate"""
u = uuid.UUID(args.uuid)
print(f"Version: {u.version}")
print(f"Variant: {u.variant}")
print(f"Hex: {u.hex}")
def main():
parser = argparse.ArgumentParser(description="UUID tool")
subs = parser.add_subparsers(dest="command", required=True)
subs.add_parser("uuid4")
u5 = subs.add_parser("uuid5")
u5.add_argument("--namespace", choices=["dns", "url", "oid"], required=True)
u5.add_argument("--name", required=True)
p = subs.add_parser("parse")
p.add_argument("uuid")
args = parser.parse_args()
{"uuid4": cmd_uuid4, "uuid5": cmd_uuid5, "parse": cmd_parse}[args.command](args)
if __name__ == "__main__":
main()
| false
|
uuid
| 43
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1089..1163, value: Dict(ExprDict { range: 1089..1149, keys: [Some(Constant(ExprConstant { range: 1090..1097, value: Str("uuid4"), kind: None })), Some(Constant(ExprConstant { range: 1110..1117, value: Str("uuid5"), kind: None })), Some(Constant(ExprConstant { range: 1130..1137, value: Str("parse"), kind: None }))], values: [Name(ExprName { range: 1099..1108, id: Identifier("cmd_uuid4"), ctx: Load }), Name(ExprName { range: 1
|
|
example_vector_math
|
test_vector_cli.py
|
"""Tests for vector_cli.py"""
import math
import pytest
from vector_cli import (
Vector,
add,
angle_between,
centroid,
cosine_similarity,
cross,
distance,
dot,
gram_schmidt,
hadamard,
is_orthogonal,
is_parallel,
lerp,
magnitude,
norm_p,
normalize,
orthonormalize,
outer_product,
project,
reflect,
reject,
scalar_multiply,
subtract,
triple_scalar,
)
class TestVector:
def test_creation(self):
v = Vector([1.0, 2.0, 3.0])
assert v.dimension == 3
assert v[0] == 1.0
assert v[1] == 2.0
def test_str(self):
v = Vector([1.0, 2.0])
s = str(v)
assert "1.0" in s
class TestAdd:
def test_basic(self):
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([4.0, 5.0, 6.0])
result = add(v1, v2)
assert result.components == [5.0, 7.0, 9.0]
def test_dimension_mismatch(self):
v1 = Vector([1.0, 2.0])
v2 = Vector([1.0, 2.0, 3.0])
with pytest.raises(ValueError):
add(v1, v2)
class TestSubtract:
def test_basic(self):
v1 = Vector([5.0, 6.0, 7.0])
v2 = Vector([1.0, 2.0, 3.0])
result = subtract(v1, v2)
assert result.components == [4.0, 4.0, 4.0]
class TestScalarMultiply:
def test_basic(self):
v = Vector([1.0, 2.0, 3.0])
result = scalar_multiply(v, 2.0)
assert result.components == [2.0, 4.0, 6.0]
def test_zero(self):
v = Vector([1.0, 2.0, 3.0])
result = scalar_multiply(v, 0.0)
assert all(c == 0 for c in result.components)
class TestDot:
def test_basic(self):
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([4.0, 5.0, 6.0])
result = dot(v1, v2)
assert result == pytest.approx(32.0) # 4 + 10 + 18
def test_orthogonal(self):
v1 = Vector([1.0, 0.0, 0.0])
v2 = Vector([0.0, 1.0, 0.0])
assert dot(v1, v2) == pytest.approx(0.0)
class TestCross:
def test_basic(self):
v1 = Vector([1.0, 0.0, 0.0])
v2 = Vector([0.0, 1.0, 0.0])
result = cross(v1, v2)
assert result[0] == pytest.approx(0.0)
assert result[1] == pytest.approx(0.0)
assert result[2] == pytest.approx(1.0)
def test_parallel(self):
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([2.0, 4.0, 6.0])
result = cross(v1, v2)
# Cross product of parallel vectors is zero
assert all(abs(c) < 1e-10 for c in result.components)
def test_wrong_dimension(self):
v1 = Vector([1.0, 2.0])
v2 = Vector([3.0, 4.0])
with pytest.raises(ValueError):
cross(v1, v2)
class TestMagnitude:
def test_basic(self):
v = Vector([3.0, 4.0])
assert magnitude(v) == pytest.approx(5.0)
def test_unit(self):
v = Vector([1.0, 0.0, 0.0])
assert magnitude(v) == pytest.approx(1.0)
def test_zero(self):
v = Vector([0.0, 0.0, 0.0])
assert magnitude(v) == pytest.approx(0.0)
class TestNormalize:
def test_basic(self):
v = Vector([3.0, 4.0])
result = normalize(v)
assert magnitude(result) == pytest.approx(1.0)
def test_zero(self):
v = Vector([0.0, 0.0])
with pytest.raises(ValueError):
normalize(v)
class TestDistance:
def test_basic(self):
v1 = Vector([0.0, 0.0])
v2 = Vector([3.0, 4.0])
assert distance(v1, v2) == pytest.approx(5.0)
def test_same(self):
v = Vector([1.0, 2.0, 3.0])
assert distance(v, v) == pytest.approx(0.0)
class TestAngleBetween:
def test_orthogonal(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([0.0, 1.0])
angle = angle_between(v1, v2)
assert angle == pytest.approx(math.pi / 2)
def test_parallel(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([2.0, 0.0])
angle = angle_between(v1, v2)
assert angle == pytest.approx(0.0)
def test_opposite(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([-1.0, 0.0])
angle = angle_between(v1, v2)
assert angle == pytest.approx(math.pi)
class TestProject:
def test_basic(self):
v = Vector([3.0, 4.0])
onto = Vector([1.0, 0.0])
result = project(v, onto)
assert result[0] == pytest.approx(3.0)
assert result[1] == pytest.approx(0.0)
def test_onto_self(self):
v = Vector([3.0, 4.0])
result = project(v, v)
assert result[0] == pytest.approx(3.0)
assert result[1] == pytest.approx(4.0)
class TestReject:
def test_basic(self):
v = Vector([3.0, 4.0])
from_ = Vector([1.0, 0.0])
result = reject(v, from_)
assert result[0] == pytest.approx(0.0)
assert result[1] == pytest.approx(4.0)
class TestReflect:
def test_basic(self):
v = Vector([1.0, -1.0])
normal = Vector([0.0, 1.0])
result = reflect(v, normal)
assert result[0] == pytest.approx(1.0)
assert result[1] == pytest.approx(1.0)
class TestLerp:
def test_endpoints(self):
v1 = Vector([0.0, 0.0])
v2 = Vector([2.0, 4.0])
assert lerp(v1, v2, 0.0).components == [0.0, 0.0]
assert lerp(v1, v2, 1.0).components == [2.0, 4.0]
def test_middle(self):
v1 = Vector([0.0, 0.0])
v2 = Vector([2.0, 4.0])
result = lerp(v1, v2, 0.5)
assert result[0] == pytest.approx(1.0)
assert result[1] == pytest.approx(2.0)
class TestHadamard:
def test_basic(self):
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([4.0, 5.0, 6.0])
result = hadamard(v1, v2)
assert result.components == [4.0, 10.0, 18.0]
class TestTripleScalar:
def test_basic(self):
v1 = Vector([1.0, 0.0, 0.0])
v2 = Vector([0.0, 1.0, 0.0])
v3 = Vector([0.0, 0.0, 1.0])
# Volume of unit cube
result = triple_scalar(v1, v2, v3)
assert result == pytest.approx(1.0)
class TestOrthogonalParallel:
def test_orthogonal(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([0.0, 1.0])
assert is_orthogonal(v1, v2) is True
assert is_parallel(v1, v2) is False
def test_parallel(self):
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([2.0, 4.0, 6.0])
assert is_parallel(v1, v2) is True
assert is_orthogonal(v1, v2) is False
class TestOuterProduct:
def test_basic(self):
v1 = Vector([1.0, 2.0])
v2 = Vector([3.0, 4.0])
result = outer_product(v1, v2)
assert result == [[3.0, 4.0], [6.0, 8.0]]
class TestGramSchmidt:
def test_basic(self):
v1 = Vector([1.0, 1.0, 0.0])
v2 = Vector([1.0, 0.0, 1.0])
v3 = Vector([0.0, 1.0, 1.0])
result = gram_schmidt([v1, v2, v3])
# Result should be orthogonal
assert is_orthogonal(result[0], result[1])
assert is_orthogonal(result[1], result[2])
class TestOrthonormalize:
def test_basic(self):
v1 = Vector([1.0, 1.0, 0.0])
v2 = Vector([1.0, 0.0, 1.0])
result = orthonormalize([v1, v2])
# Should be orthogonal
assert is_orthogonal(result[0], result[1])
# Should be unit length
assert magnitude(result[0]) == pytest.approx(1.0)
assert magnitude(result[1]) == pytest.approx(1.0)
class TestCentroid:
def test_basic(self):
vectors = [Vector([0.0, 0.0]), Vector([2.0, 0.0]), Vector([1.0, 2.0])]
result = centroid(vectors)
assert result[0] == pytest.approx(1.0)
assert result[1] == pytest.approx(2 / 3)
class TestNormP:
def test_l1(self):
v = Vector([1.0, -2.0, 3.0])
assert norm_p(v, 1) == pytest.approx(6.0)
def test_l2(self):
v = Vector([3.0, 4.0])
assert norm_p(v, 2) == pytest.approx(5.0)
def test_linf(self):
v = Vector([1.0, -5.0, 3.0])
assert norm_p(v, float("inf")) == pytest.approx(5.0)
class TestCosineSimilarity:
def test_identical(self):
v = Vector([1.0, 2.0, 3.0])
assert cosine_similarity(v, v) == pytest.approx(1.0)
def test_opposite(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([-1.0, 0.0])
assert cosine_similarity(v1, v2) == pytest.approx(-1.0)
def test_orthogonal(self):
v1 = Vector([1.0, 0.0])
v2 = Vector([0.0, 1.0])
assert cosine_similarity(v1, v2) == pytest.approx(0.0)
| false
|
vector_math
| 324
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Var("c"), right: Literal(Int(0)) }, generators: [HirComprehension { target: "c", iter: Attribute { value: Var("result"), attr: "components" }, conditions: [] }] }
|
|
example_vector_math
|
vector_cli.py
|
#!/usr/bin/env python3
"""Vector Math CLI.
Pure Python vector operations without external dependencies.
"""
import argparse
import math
import sys
from dataclasses import dataclass
@dataclass
class Vector:
"""N-dimensional vector."""
components: list[float]
def __len__(self) -> int:
return len(self.components)
def __getitem__(self, i: int) -> float:
return self.components[i]
def __str__(self) -> str:
return f"({', '.join(f'{c:.4f}' for c in self.components)})"
@property
def dimension(self) -> int:
return len(self.components)
def add(v1: Vector, v2: Vector) -> Vector:
"""Add two vectors."""
if len(v1) != len(v2):
raise ValueError("Vectors must have same dimension")
return Vector([v1[i] + v2[i] for i in range(len(v1))])
def subtract(v1: Vector, v2: Vector) -> Vector:
"""Subtract v2 from v1."""
if len(v1) != len(v2):
raise ValueError("Vectors must have same dimension")
return Vector([v1[i] - v2[i] for i in range(len(v1))])
def scalar_multiply(v: Vector, scalar: float) -> Vector:
"""Multiply vector by scalar."""
return Vector([c * scalar for c in v.components])
def dot(v1: Vector, v2: Vector) -> float:
"""Calculate dot product."""
if len(v1) != len(v2):
raise ValueError("Vectors must have same dimension")
return sum(v1[i] * v2[i] for i in range(len(v1)))
def cross(v1: Vector, v2: Vector) -> Vector:
"""Calculate cross product (3D only)."""
if len(v1) != 3 or len(v2) != 3:
raise ValueError("Cross product requires 3D vectors")
return Vector(
[
v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0],
]
)
def magnitude(v: Vector) -> float:
"""Calculate vector magnitude (Euclidean norm)."""
return math.sqrt(sum(c * c for c in v.components))
def normalize(v: Vector) -> Vector:
"""Normalize vector to unit length."""
mag = magnitude(v)
if mag == 0:
raise ValueError("Cannot normalize zero vector")
return Vector([c / mag for c in v.components])
def distance(v1: Vector, v2: Vector) -> float:
"""Calculate Euclidean distance between vectors."""
return magnitude(subtract(v1, v2))
def angle_between(v1: Vector, v2: Vector) -> float:
"""Calculate angle between vectors in radians."""
mag1 = magnitude(v1)
mag2 = magnitude(v2)
if mag1 == 0 or mag2 == 0:
raise ValueError("Cannot calculate angle with zero vector")
cos_angle = dot(v1, v2) / (mag1 * mag2)
# Clamp to handle floating point errors
cos_angle = max(-1, min(1, cos_angle))
return math.acos(cos_angle)
def project(v: Vector, onto: Vector) -> Vector:
"""Project v onto another vector."""
onto_mag_sq = dot(onto, onto)
if onto_mag_sq == 0:
raise ValueError("Cannot project onto zero vector")
scalar = dot(v, onto) / onto_mag_sq
return scalar_multiply(onto, scalar)
def reject(v: Vector, from_: Vector) -> Vector:
"""Calculate rejection of v from another vector."""
return subtract(v, project(v, from_))
def reflect(v: Vector, normal: Vector) -> Vector:
"""Reflect vector across a plane defined by normal."""
n = normalize(normal)
return subtract(v, scalar_multiply(n, 2 * dot(v, n)))
def lerp(v1: Vector, v2: Vector, t: float) -> Vector:
"""Linear interpolation between vectors."""
return add(scalar_multiply(v1, 1 - t), scalar_multiply(v2, t))
def hadamard(v1: Vector, v2: Vector) -> Vector:
"""Element-wise (Hadamard) product."""
if len(v1) != len(v2):
raise ValueError("Vectors must have same dimension")
return Vector([v1[i] * v2[i] for i in range(len(v1))])
def triple_scalar(v1: Vector, v2: Vector, v3: Vector) -> float:
"""Calculate scalar triple product: v1 · (v2 × v3)."""
return dot(v1, cross(v2, v3))
def triple_vector(v1: Vector, v2: Vector, v3: Vector) -> Vector:
"""Calculate vector triple product: v1 × (v2 × v3)."""
return cross(v1, cross(v2, v3))
def is_orthogonal(v1: Vector, v2: Vector, tolerance: float = 1e-10) -> bool:
"""Check if two vectors are orthogonal."""
return abs(dot(v1, v2)) < tolerance
def is_parallel(v1: Vector, v2: Vector, tolerance: float = 1e-10) -> bool:
"""Check if two vectors are parallel."""
if len(v1) != len(v2):
return False
# Check if cross product is zero (for 3D)
if len(v1) == 3:
c = cross(v1, v2)
return magnitude(c) < tolerance
# For general case, check if one is scalar multiple of other
if magnitude(v2) == 0:
return magnitude(v1) == 0
# Find non-zero component
for i in range(len(v1)):
if abs(v2[i]) > tolerance:
ratio = v1[i] / v2[i]
break
else:
return magnitude(v1) < tolerance
for i in range(len(v1)):
expected = ratio * v2[i]
if abs(v1[i] - expected) > tolerance:
return False
return True
def outer_product(v1: Vector, v2: Vector) -> list[list[float]]:
"""Calculate outer product (returns matrix)."""
return [[v1[i] * v2[j] for j in range(len(v2))] for i in range(len(v1))]
def component_in_direction(v: Vector, direction: Vector) -> float:
"""Calculate scalar component of v in given direction."""
return dot(v, normalize(direction))
def gram_schmidt(vectors: list[Vector]) -> list[Vector]:
"""Gram-Schmidt orthogonalization."""
if not vectors:
return []
orthogonal = []
for v in vectors:
# Subtract projections onto all previous vectors
result = v
for u in orthogonal:
result = subtract(result, project(v, u))
if magnitude(result) > 1e-10:
orthogonal.append(result)
return orthogonal
def orthonormalize(vectors: list[Vector]) -> list[Vector]:
"""Orthonormalize a set of vectors."""
orthogonal = gram_schmidt(vectors)
return [normalize(v) for v in orthogonal]
def centroid(vectors: list[Vector]) -> Vector:
"""Calculate centroid of a set of vectors."""
if not vectors:
raise ValueError("Need at least one vector")
n = len(vectors)
dim = len(vectors[0])
result = [0.0] * dim
for v in vectors:
for i in range(dim):
result[i] += v[i]
return Vector([x / n for x in result])
def norm_p(v: Vector, p: float) -> float:
"""Calculate p-norm of vector."""
if p <= 0:
raise ValueError("p must be positive")
if p == float("inf"):
return max(abs(c) for c in v.components)
return sum(abs(c) ** p for c in v.components) ** (1 / p)
def cosine_similarity(v1: Vector, v2: Vector) -> float:
"""Calculate cosine similarity between vectors."""
mag1 = magnitude(v1)
mag2 = magnitude(v2)
if mag1 == 0 or mag2 == 0:
return 0.0
return dot(v1, v2) / (mag1 * mag2)
def parse_vector(s: str) -> Vector:
"""Parse vector from comma-separated string."""
return Vector([float(x) for x in s.split(",")])
def main() -> int:
parser = argparse.ArgumentParser(description="Vector operations")
parser.add_argument(
"--mode",
choices=[
"add",
"dot",
"cross",
"mag",
"normalize",
"angle",
"project",
"distance",
"demo",
],
default="demo",
help="Operation mode",
)
parser.add_argument("--v1", help="First vector (comma-separated)")
parser.add_argument("--v2", help="Second vector (comma-separated)")
args = parser.parse_args()
if args.mode == "demo":
print("Vector Operations Demo\n")
v1 = Vector([1.0, 2.0, 3.0])
v2 = Vector([4.0, 5.0, 6.0])
print(f"v1 = {v1}")
print(f"v2 = {v2}")
print(f"\nv1 + v2 = {add(v1, v2)}")
print(f"v1 - v2 = {subtract(v1, v2)}")
print(f"v1 · v2 = {dot(v1, v2):.4f}")
print(f"v1 × v2 = {cross(v1, v2)}")
print(f"|v1| = {magnitude(v1):.4f}")
print(f"normalize(v1) = {normalize(v1)}")
print(f"angle(v1, v2) = {math.degrees(angle_between(v1, v2)):.2f}°")
print(f"distance(v1, v2) = {distance(v1, v2):.4f}")
print(f"project(v1, v2) = {project(v1, v2)}")
print(f"cosine_similarity = {cosine_similarity(v1, v2):.4f}")
elif args.v1:
v1 = parse_vector(args.v1)
if args.mode == "mag":
print(f"|v| = {magnitude(v1):.6f}")
elif args.mode == "normalize":
print(f"normalize(v) = {normalize(v1)}")
elif args.v2:
v2 = parse_vector(args.v2)
if args.mode == "add":
print(f"v1 + v2 = {add(v1, v2)}")
elif args.mode == "dot":
print(f"v1 · v2 = {dot(v1, v2):.6f}")
elif args.mode == "cross":
print(f"v1 × v2 = {cross(v1, v2)}")
elif args.mode == "angle":
angle = angle_between(v1, v2)
print(f"angle = {math.degrees(angle):.4f}°")
elif args.mode == "project":
print(f"project(v1, v2) = {project(v1, v2)}")
elif args.mode == "distance":
print(f"distance = {distance(v1, v2):.6f}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_vector_math/vector_cli.py (9398 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_vector_math/vector_cli.rs (23640 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_vector_math/Cargo.toml (1 dependencies)
⏱️ Parse time: 61ms
📊 Throughput: 150.0 KB/s
⏱️ Total time: 61ms
| true
|
vector_math
| 337
| 6
|
[
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.652
| null |
example_walrus_operator
|
test_walrus_cli.py
|
"""
Test suite for walrus_cli.py
Validates E0425 fix: block scoping with walrus operator
Following extreme TDD methodology.
"""
import subprocess
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parent / "walrus_cli.py"
def run_cli(*args):
"""Helper to run CLI and capture output."""
result = subprocess.run(
["python3", str(SCRIPT), *args],
capture_output=True,
text=True,
)
return result
class TestWalrusCheck:
"""Tests for the 'check' subcommand (walrus in if)."""
def test_check_long_text(self):
"""Test check with text > 5 chars."""
result = run_cli("check", "HelloWorld")
assert result.returncode == 0
assert "Length: 10" in result.stdout
def test_check_short_text(self):
"""Test check with text <= 5 chars."""
result = run_cli("check", "Hi")
assert result.returncode == 0
assert "Too short" in result.stdout
def test_check_exactly_five(self):
"""Test check with exactly 5 chars."""
result = run_cli("check", "Hello")
assert result.returncode == 0
assert "Too short" in result.stdout
def test_check_six_chars(self):
"""Test check with 6 chars (boundary)."""
result = run_cli("check", "Hello!")
assert result.returncode == 0
assert "Length: 6" in result.stdout
def test_check_empty(self):
"""Test check with empty string."""
result = run_cli("check", "")
assert result.returncode == 0
assert "Too short" in result.stdout
class TestWalrusCount:
"""Tests for the 'count' subcommand (walrus in comprehension)."""
def test_count_with_long_words(self):
"""Test counting words > 3 chars."""
result = run_cli("count", "The quick brown fox jumps")
assert result.returncode == 0
assert "Long words: 3" in result.stdout # quick, brown, jumps
def test_count_no_long_words(self):
"""Test with all short words."""
result = run_cli("count", "a the on in to")
assert result.returncode == 0
assert "Long words: 0" in result.stdout
def test_count_all_long_words(self):
"""Test with all long words."""
result = run_cli("count", "hello world python")
assert result.returncode == 0
assert "Long words: 3" in result.stdout
def test_count_empty(self):
"""Test with empty string."""
result = run_cli("count", "")
assert result.returncode == 0
assert "Long words: 0" in result.stdout
def test_count_single_word(self):
"""Test with single word."""
result = run_cli("count", "programming")
assert result.returncode == 0
assert "Long words: 1" in result.stdout
class TestWalrusFind:
"""Tests for the 'find' subcommand (walrus in loop)."""
def test_find_default_min_len(self):
"""Test find with default min_len=5."""
result = run_cli("find", "The quick brown fox")
assert result.returncode == 0
assert "Found: quick(5)" in result.stdout
def test_find_custom_min_len(self):
"""Test find with custom min_len."""
result = run_cli("find", "The quick brown", "--min-len", "6")
assert result.returncode == 0
assert "Found: none" in result.stdout
def test_find_longer_word(self):
"""Test find with longer word present."""
result = run_cli("find", "a programming example", "--min-len", "7")
assert result.returncode == 0
assert "Found: programming(11)" in result.stdout
def test_find_no_match(self):
"""Test when no word matches."""
result = run_cli("find", "a b c d", "--min-len", "3")
assert result.returncode == 0
assert "Found: none" in result.stdout
def test_find_first_match(self):
"""Test that first matching word is returned."""
result = run_cli("find", "hello world python", "--min-len", "5")
assert result.returncode == 0
assert "Found: hello(5)" in result.stdout
class TestHelp:
"""Tests for help output."""
def test_main_help(self):
"""Test main --help."""
result = run_cli("--help")
assert result.returncode == 0
assert "check" in result.stdout
assert "count" in result.stdout
assert "find" in result.stdout
def test_check_help(self):
"""Test check --help."""
result = run_cli("check", "--help")
assert result.returncode == 0
assert "text" in result.stdout.lower()
def test_find_help(self):
"""Test find --help."""
result = run_cli("find", "--help")
assert result.returncode == 0
assert "--min-len" in result.stdout
class TestEdgeCases:
"""Edge case tests."""
def test_missing_subcommand(self):
"""Test error when no subcommand."""
result = run_cli()
assert result.returncode != 0
def test_unicode_text(self):
"""Test with unicode text."""
result = run_cli("check", "Hello, 世界!")
assert result.returncode == 0
assert "Length:" in result.stdout
def test_deterministic_output(self):
"""Test deterministic output."""
results = [run_cli("count", "hello world") for _ in range(3)]
assert all(r.returncode == 0 for r in results)
assert all(r.stdout == results[0].stdout for r in results)
| false
|
walrus_operator
| 170
| 0
|
[
"context_manager",
"class_definition"
] | 0.652
|
Performance Warnings
══════════════════════════════════════════════════
[1] [Medium] Large value 'args' passed by copy
Location: run_cli, line 0
Impact: Complexity: O(n), Scales: Yes, Hot path: No
Why: Passing large values by copy is inefficient
Fix: Consider passing by reference (&) or using Box/Arc for large types
Summary: Found 1 warnings (0 critical, 0 high severity)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions:
|
|
example_walrus_operator
|
walrus_cli.py
|
#!/usr/bin/env python3
"""
Walrus Operator CLI - Tests assignment expressions (:=)
This example demonstrates Python 3.8+ walrus operator patterns:
- Assignment in if conditions
- Assignment in while loops
- Assignment in list comprehensions
Purpose: Validate depyler handles block scoping correctly (E0425).
"""
import argparse
def check_length(text: str) -> int:
"""Return length if > 5, else 0."""
if (n := len(text)) > 5:
return n
return 0
def count_words(text: str) -> int:
"""Count words using walrus in comprehension."""
words = text.split()
# Walrus in comprehension - use length for filtering
long_words = [(w, length) for w in words if (length := len(w)) > 3]
return len(long_words)
def find_first_long(text: str, min_len: int) -> str:
"""Find first word longer than min_len."""
words = text.split()
for word in words:
if (n := len(word)) >= min_len:
return f"{word}({n})"
return "none"
def main():
"""Main entry point with walrus operator examples."""
parser = argparse.ArgumentParser(
description="Walrus operator examples",
prog="walrus_cli.py",
)
subparsers = parser.add_subparsers(
dest="command",
help="Available commands",
required=True,
)
# Subcommand: check
check_parser = subparsers.add_parser(
"check",
help="Check if text length > 5",
)
check_parser.add_argument(
"text",
help="Text to check",
)
# Subcommand: count
count_parser = subparsers.add_parser(
"count",
help="Count words with length > 3",
)
count_parser.add_argument(
"text",
help="Text to analyze",
)
# Subcommand: find
find_parser = subparsers.add_parser(
"find",
help="Find first long word",
)
find_parser.add_argument(
"text",
help="Text to search",
)
find_parser.add_argument(
"--min-len",
type=int,
default=5,
help="Minimum word length (default: 5)",
)
args = parser.parse_args()
if args.command == "check":
result = check_length(args.text)
if result > 0:
print(f"Length: {result}")
else:
print("Too short")
elif args.command == "count":
count = count_words(args.text)
print(f"Long words: {count}")
elif args.command == "find":
found = find_first_long(args.text, args.min_len)
print(f"Found: {found}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_walrus_operator/walrus_cli.py (2574 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_walrus_operator/walrus_cli.rs (3499 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_walrus_operator/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 52.2 KB/s
⏱️ Total time: 48ms
| true
|
walrus_operator
| 106
| 6
|
[
"context_manager",
"walrus_operator"
] | 0.85
| null |
example_websocket_frame
|
test_websocket_cli.py
|
"""Tests for websocket_cli.py"""
from websocket_cli import (
Opcode,
WebSocketConnection,
WebSocketFrame,
defragment_frames,
encode_binary,
encode_close,
encode_frame,
encode_ping,
encode_pong,
encode_text,
format_frame,
fragment_message,
generate_masking_key,
is_control_frame,
mask_payload,
parse_close_payload,
parse_frame,
validate_frame,
)
class TestEncodeFrame:
def test_text_simple(self):
frame = encode_frame(b"Hello", Opcode.TEXT)
# First byte: FIN=1, RSV=0, Opcode=1
assert frame[0] == 0x81
# Second byte: Mask=0, Length=5
assert frame[1] == 5
# Payload
assert frame[2:] == b"Hello"
def test_text_masked(self):
frame = encode_frame(b"Hello", Opcode.TEXT, mask=True)
assert frame[0] == 0x81
assert frame[1] & 0x80 == 0x80 # Mask bit set
assert len(frame) >= 2 + 4 + 5 # Header + key + payload
def test_binary(self):
frame = encode_frame(b"\x00\x01\x02", Opcode.BINARY)
assert frame[0] == 0x82
def test_extended_length_16bit(self):
payload = b"x" * 126
frame = encode_frame(payload, Opcode.TEXT)
assert frame[1] & 0x7F == 126 # Extended length marker
length = int.from_bytes(frame[2:4], "big")
assert length == 126
def test_extended_length_64bit(self):
payload = b"x" * 70000
frame = encode_frame(payload, Opcode.TEXT)
assert frame[1] & 0x7F == 127 # Extended length marker
length = int.from_bytes(frame[2:10], "big")
assert length == 70000
def test_fin_false(self):
frame = encode_frame(b"Hello", Opcode.TEXT, fin=False)
assert frame[0] & 0x80 == 0 # FIN bit not set
class TestParseFrame:
def test_simple(self):
# FIN=1, Text, 5 bytes
data = bytes([0x81, 0x05]) + b"Hello"
frame, consumed = parse_frame(data)
assert frame.fin is True
assert frame.opcode == Opcode.TEXT
assert frame.payload == b"Hello"
assert frame.payload_length == 5
assert consumed == 7
def test_masked(self):
# Create a masked frame
masking_key = bytes([0x37, 0xfa, 0x21, 0x3d])
payload = b"Hello"
masked = mask_payload(payload, masking_key)
data = bytes([0x81, 0x85]) + masking_key + masked
frame, _ = parse_frame(data)
assert frame.mask is True
assert frame.payload == b"Hello"
def test_binary(self):
data = bytes([0x82, 0x03]) + b"\x00\x01\x02"
frame, _ = parse_frame(data)
assert frame.opcode == Opcode.BINARY
assert frame.payload == b"\x00\x01\x02"
def test_extended_length(self):
# 126 bytes payload
payload = b"x" * 126
data = bytes([0x81, 126]) + (126).to_bytes(2, "big") + payload
frame, _ = parse_frame(data)
assert frame.payload_length == 126
class TestEncodeHelpers:
def test_encode_text(self):
frame = encode_text("Hello")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.TEXT
assert parsed.payload == b"Hello"
def test_encode_binary(self):
frame = encode_binary(b"\x00\x01\x02")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.BINARY
def test_encode_ping(self):
frame = encode_ping(b"ping")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.PING
assert parsed.payload == b"ping"
def test_encode_pong(self):
frame = encode_pong(b"pong")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.PONG
def test_encode_close(self):
frame = encode_close(1000, "Normal")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.CLOSE
code, reason = parse_close_payload(parsed.payload)
assert code == 1000
assert reason == "Normal"
class TestParseClosePayload:
def test_with_reason(self):
payload = (1000).to_bytes(2, "big") + b"Normal"
code, reason = parse_close_payload(payload)
assert code == 1000
assert reason == "Normal"
def test_no_reason(self):
payload = (1001).to_bytes(2, "big")
code, reason = parse_close_payload(payload)
assert code == 1001
assert reason == ""
def test_no_payload(self):
code, reason = parse_close_payload(b"")
assert code == 1005 # No status
assert reason == ""
class TestMaskPayload:
def test_basic(self):
key = bytes([0x37, 0xfa, 0x21, 0x3d])
payload = b"Hello"
masked = mask_payload(payload, key)
unmasked = mask_payload(masked, key)
assert unmasked == payload
def test_empty(self):
key = bytes([0x12, 0x34, 0x56, 0x78])
assert mask_payload(b"", key) == b""
class TestGenerateMaskingKey:
def test_length(self):
key = generate_masking_key()
assert len(key) == 4
def test_randomness(self):
key1 = generate_masking_key()
key2 = generate_masking_key()
# Very unlikely to be the same
assert key1 != key2
class TestFragmentMessage:
def test_no_fragment_needed(self):
data = b"Hello"
frames = fragment_message(data, Opcode.TEXT, max_fragment_size=100)
assert len(frames) == 1
def test_fragment_into_multiple(self):
data = b"Hello, World!"
frames = fragment_message(data, Opcode.TEXT, max_fragment_size=5)
assert len(frames) > 1
# First frame has TEXT opcode
parsed, _ = parse_frame(frames[0])
assert parsed.opcode == Opcode.TEXT
assert parsed.fin is False
# Last frame has FIN
parsed, _ = parse_frame(frames[-1])
assert parsed.fin is True
# Middle frames are CONTINUATION
if len(frames) > 2:
parsed, _ = parse_frame(frames[1])
assert parsed.opcode == Opcode.CONTINUATION
class TestDefragmentFrames:
def test_single_frame(self):
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
)
opcode, data = defragment_frames([frame])
assert opcode == Opcode.TEXT
assert data == b"Hello"
def test_multiple_frames(self):
frames = [
WebSocketFrame(
fin=False,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
),
WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.CONTINUATION,
mask=False,
payload_length=6,
masking_key=None,
payload=b" World",
),
]
opcode, data = defragment_frames(frames)
assert opcode == Opcode.TEXT
assert data == b"Hello World"
class TestIsControlFrame:
def test_control(self):
assert is_control_frame(Opcode.PING) is True
assert is_control_frame(Opcode.PONG) is True
assert is_control_frame(Opcode.CLOSE) is True
def test_data(self):
assert is_control_frame(Opcode.TEXT) is False
assert is_control_frame(Opcode.BINARY) is False
assert is_control_frame(Opcode.CONTINUATION) is False
class TestValidateFrame:
def test_valid(self):
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
)
errors = validate_frame(frame)
assert errors == []
def test_fragmented_control(self):
frame = WebSocketFrame(
fin=False, # Control frame fragmented
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.PING,
mask=False,
payload_length=4,
masking_key=None,
payload=b"ping",
)
errors = validate_frame(frame)
assert len(errors) > 0
assert "fragmented" in errors[0].lower()
def test_control_too_large(self):
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.PING,
mask=False,
payload_length=200,
masking_key=None,
payload=b"x" * 200,
)
errors = validate_frame(frame)
assert len(errors) > 0
def test_rsv_bits(self):
frame = WebSocketFrame(
fin=True,
rsv1=True, # RSV bit set without extension
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
)
errors = validate_frame(frame)
assert len(errors) > 0
class TestWebSocketConnection:
def test_init(self):
conn = WebSocketConnection(is_client=True)
assert conn.is_open is True
assert conn.is_client is True
def test_process_ping(self):
conn = WebSocketConnection()
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.PING,
mask=False,
payload_length=4,
masking_key=None,
payload=b"ping",
)
action, response = conn.process_frame(frame)
assert action == "pong"
assert response is not None
def test_process_text(self):
conn = WebSocketConnection()
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
)
action, data = conn.process_frame(frame)
assert action == "text"
assert data == b"Hello"
def test_process_close(self):
conn = WebSocketConnection()
close_payload = (1000).to_bytes(2, "big") + b"Normal"
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.CLOSE,
mask=False,
payload_length=len(close_payload),
masking_key=None,
payload=close_payload,
)
action, response = conn.process_frame(frame)
assert action == "close"
assert response is not None
def test_send_text(self):
conn = WebSocketConnection(is_client=True)
frame = conn.send_text("Hello")
parsed, _ = parse_frame(frame)
assert parsed.opcode == Opcode.TEXT
assert parsed.mask is True # Client must mask
class TestFormatFrame:
def test_text_frame(self):
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.TEXT,
mask=False,
payload_length=5,
masking_key=None,
payload=b"Hello",
)
formatted = format_frame(frame)
assert "TEXT" in formatted
assert "Hello" in formatted
def test_close_frame(self):
payload = (1000).to_bytes(2, "big") + b"Goodbye"
frame = WebSocketFrame(
fin=True,
rsv1=False,
rsv2=False,
rsv3=False,
opcode=Opcode.CLOSE,
mask=False,
payload_length=len(payload),
masking_key=None,
payload=payload,
)
formatted = format_frame(frame)
assert "1000" in formatted
assert "Goodbye" in formatted
| false
|
websocket_frame
| 457
| 0
|
[
"class_definition"
] | 0.612
|
thread 'main' (2541321) panicked at crates/depyler-core/src/direct_rules.rs:1721:17:
expected identifier, found keyword `_`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
|
example_websocket_frame
|
websocket_cli.py
|
#!/usr/bin/env python3
"""WebSocket Frame CLI.
Parse and encode WebSocket protocol frames.
"""
import argparse
import os
import sys
from dataclasses import dataclass
from enum import IntEnum
class Opcode(IntEnum):
"""WebSocket frame opcodes."""
CONTINUATION = 0x0
TEXT = 0x1
BINARY = 0x2
CLOSE = 0x8
PING = 0x9
PONG = 0xA
# Close status codes
CLOSE_CODES = {
1000: "Normal Closure",
1001: "Going Away",
1002: "Protocol Error",
1003: "Unsupported Data",
1005: "No Status Received",
1006: "Abnormal Closure",
1007: "Invalid Payload",
1008: "Policy Violation",
1009: "Message Too Big",
1010: "Mandatory Extension",
1011: "Internal Server Error",
1015: "TLS Handshake",
}
@dataclass
class WebSocketFrame:
"""WebSocket frame structure."""
fin: bool
rsv1: bool
rsv2: bool
rsv3: bool
opcode: Opcode
mask: bool
payload_length: int
masking_key: bytes | None
payload: bytes
def encode_frame(
payload: bytes,
opcode: Opcode = Opcode.TEXT,
fin: bool = True,
mask: bool = False,
masking_key: bytes | None = None,
) -> bytes:
"""Encode WebSocket frame."""
frame = bytearray()
# First byte: FIN + RSV + Opcode
first_byte = (0x80 if fin else 0x00) | (opcode & 0x0F)
frame.append(first_byte)
# Second byte: Mask + Payload length
payload_length = len(payload)
if payload_length <= 125:
second_byte = (0x80 if mask else 0x00) | payload_length
frame.append(second_byte)
elif payload_length <= 65535:
second_byte = (0x80 if mask else 0x00) | 126
frame.append(second_byte)
frame.extend(payload_length.to_bytes(2, "big"))
else:
second_byte = (0x80 if mask else 0x00) | 127
frame.append(second_byte)
frame.extend(payload_length.to_bytes(8, "big"))
# Masking key
if mask:
if masking_key is None:
masking_key = os.urandom(4)
frame.extend(masking_key)
# Mask payload
masked_payload = bytearray(payload_length)
for i in range(payload_length):
masked_payload[i] = payload[i] ^ masking_key[i % 4]
frame.extend(masked_payload)
else:
frame.extend(payload)
return bytes(frame)
def parse_frame(data: bytes) -> tuple[WebSocketFrame, int]:
"""Parse WebSocket frame from bytes. Returns (frame, bytes_consumed)."""
if len(data) < 2:
raise ValueError("Frame too short")
pos = 0
# First byte
first_byte = data[pos]
pos += 1
fin = bool(first_byte & 0x80)
rsv1 = bool(first_byte & 0x40)
rsv2 = bool(first_byte & 0x20)
rsv3 = bool(first_byte & 0x10)
opcode = Opcode(first_byte & 0x0F)
# Second byte
second_byte = data[pos]
pos += 1
mask = bool(second_byte & 0x80)
payload_length = second_byte & 0x7F
# Extended payload length
if payload_length == 126:
if len(data) < pos + 2:
raise ValueError("Frame too short for extended length")
payload_length = int.from_bytes(data[pos : pos + 2], "big")
pos += 2
elif payload_length == 127:
if len(data) < pos + 8:
raise ValueError("Frame too short for extended length")
payload_length = int.from_bytes(data[pos : pos + 8], "big")
pos += 8
# Masking key
masking_key = None
if mask:
if len(data) < pos + 4:
raise ValueError("Frame too short for masking key")
masking_key = data[pos : pos + 4]
pos += 4
# Payload
if len(data) < pos + payload_length:
raise ValueError("Frame too short for payload")
payload = data[pos : pos + payload_length]
pos += payload_length
# Unmask if needed
if mask and masking_key:
unmasked = bytearray(payload_length)
for i in range(payload_length):
unmasked[i] = payload[i] ^ masking_key[i % 4]
payload = bytes(unmasked)
return (
WebSocketFrame(
fin=fin,
rsv1=rsv1,
rsv2=rsv2,
rsv3=rsv3,
opcode=opcode,
mask=mask,
payload_length=payload_length,
masking_key=masking_key,
payload=payload,
),
pos,
)
def encode_text(text: str, mask: bool = False) -> bytes:
"""Encode text frame."""
return encode_frame(text.encode("utf-8"), Opcode.TEXT, mask=mask)
def encode_binary(data: bytes, mask: bool = False) -> bytes:
"""Encode binary frame."""
return encode_frame(data, Opcode.BINARY, mask=mask)
def encode_close(code: int = 1000, reason: str = "", mask: bool = False) -> bytes:
"""Encode close frame."""
payload = code.to_bytes(2, "big")
if reason:
payload += reason.encode("utf-8")
return encode_frame(payload, Opcode.CLOSE, mask=mask)
def encode_ping(data: bytes = b"", mask: bool = False) -> bytes:
"""Encode ping frame."""
return encode_frame(data, Opcode.PING, mask=mask)
def encode_pong(data: bytes = b"", mask: bool = False) -> bytes:
"""Encode pong frame."""
return encode_frame(data, Opcode.PONG, mask=mask)
def parse_close_payload(payload: bytes) -> tuple[int, str]:
"""Parse close frame payload."""
if len(payload) < 2:
return 1005, "" # No status received
code = int.from_bytes(payload[:2], "big")
reason = payload[2:].decode("utf-8", errors="replace") if len(payload) > 2 else ""
return code, reason
def mask_payload(payload: bytes, key: bytes) -> bytes:
"""Apply XOR masking to payload."""
result = bytearray(len(payload))
for i in range(len(payload)):
result[i] = payload[i] ^ key[i % 4]
return bytes(result)
def generate_masking_key() -> bytes:
"""Generate random masking key."""
return os.urandom(4)
def fragment_message(
data: bytes, opcode: Opcode, max_fragment_size: int = 1024, mask: bool = False
) -> list[bytes]:
"""Fragment a message into multiple frames."""
if len(data) <= max_fragment_size:
return [encode_frame(data, opcode, fin=True, mask=mask)]
frames = []
offset = 0
while offset < len(data):
chunk = data[offset : offset + max_fragment_size]
is_first = offset == 0
is_last = offset + max_fragment_size >= len(data)
if is_first:
frame = encode_frame(chunk, opcode, fin=is_last, mask=mask)
else:
frame = encode_frame(chunk, Opcode.CONTINUATION, fin=is_last, mask=mask)
frames.append(frame)
offset += max_fragment_size
return frames
def defragment_frames(frames: list[WebSocketFrame]) -> tuple[Opcode, bytes]:
"""Reassemble fragmented frames into complete message."""
if not frames:
raise ValueError("No frames to defragment")
opcode = frames[0].opcode
payload = bytearray()
for frame in frames:
payload.extend(frame.payload)
if frame.fin:
break
return opcode, bytes(payload)
def is_control_frame(opcode: Opcode) -> bool:
"""Check if opcode is a control frame."""
return opcode >= 0x8
def validate_frame(frame: WebSocketFrame) -> list[str]:
"""Validate frame and return list of errors."""
errors = []
# Control frames must not be fragmented
if is_control_frame(frame.opcode) and not frame.fin:
errors.append("Control frame must not be fragmented")
# Control frame payload must be <= 125 bytes
if is_control_frame(frame.opcode) and frame.payload_length > 125:
errors.append("Control frame payload too large")
# RSV bits must be 0 unless extension is negotiated
if frame.rsv1 or frame.rsv2 or frame.rsv3:
errors.append("RSV bits must be 0 without extensions")
# Check close code validity
if frame.opcode == Opcode.CLOSE and frame.payload_length >= 2:
code, _ = parse_close_payload(frame.payload)
if code < 1000 or (code >= 1004 and code <= 1006) or (code >= 1012 and code <= 1015):
if code not in CLOSE_CODES:
errors.append(f"Invalid close code: {code}")
return errors
class WebSocketConnection:
"""Simple WebSocket connection state machine."""
def __init__(self, is_client: bool = True):
self.is_client = is_client
self.is_open = True
self.closing = False
self.fragments: list[WebSocketFrame] = []
def process_frame(self, frame: WebSocketFrame) -> tuple[str, bytes | None]:
"""Process incoming frame. Returns (action, response_frame)."""
if not self.is_open:
return "error", None
errors = validate_frame(frame)
if errors:
close_frame = encode_close(1002, errors[0], mask=self.is_client)
return "protocol_error", close_frame
if frame.opcode == Opcode.PING:
pong = encode_pong(frame.payload, mask=self.is_client)
return "pong", pong
if frame.opcode == Opcode.PONG:
return "pong_received", None
if frame.opcode == Opcode.CLOSE:
code, reason = parse_close_payload(frame.payload)
if not self.closing:
# Echo close frame
response = encode_close(code, reason, mask=self.is_client)
self.closing = True
return "close", response
self.is_open = False
return "closed", None
# Data frames
if frame.opcode in (Opcode.TEXT, Opcode.BINARY):
self.fragments = [frame]
elif frame.opcode == Opcode.CONTINUATION:
self.fragments.append(frame)
if frame.fin:
opcode, data = defragment_frames(self.fragments)
self.fragments = []
if opcode == Opcode.TEXT:
return "text", data
return "binary", data
return "fragment", None
def send_text(self, text: str) -> bytes:
"""Create text frame to send."""
return encode_text(text, mask=self.is_client)
def send_binary(self, data: bytes) -> bytes:
"""Create binary frame to send."""
return encode_binary(data, mask=self.is_client)
def send_close(self, code: int = 1000, reason: str = "") -> bytes:
"""Create close frame to send."""
self.closing = True
return encode_close(code, reason, mask=self.is_client)
def format_frame(frame: WebSocketFrame) -> str:
"""Format frame for display."""
lines = []
opcode_name = frame.opcode.name if hasattr(frame.opcode, "name") else str(frame.opcode)
lines.append(f"Opcode: {opcode_name}")
lines.append(f"FIN: {frame.fin}")
lines.append(f"RSV: {frame.rsv1}/{frame.rsv2}/{frame.rsv3}")
lines.append(f"Mask: {frame.mask}")
lines.append(f"Payload Length: {frame.payload_length}")
if frame.masking_key:
lines.append(f"Masking Key: {frame.masking_key.hex()}")
if frame.opcode == Opcode.TEXT:
try:
text = frame.payload.decode("utf-8")
lines.append(f"Payload (text): {text}")
except UnicodeDecodeError:
lines.append(f"Payload (hex): {frame.payload.hex()}")
elif frame.opcode == Opcode.CLOSE:
code, reason = parse_close_payload(frame.payload)
code_name = CLOSE_CODES.get(code, "Unknown")
lines.append(f"Close Code: {code} ({code_name})")
if reason:
lines.append(f"Close Reason: {reason}")
else:
lines.append(f"Payload (hex): {frame.payload.hex()}")
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description="WebSocket frame parser")
parser.add_argument(
"--mode",
choices=["encode", "parse", "ping", "close", "fragment"],
default="encode",
help="Operation mode",
)
parser.add_argument("--text", help="Text to encode")
parser.add_argument("--hex", help="Hex data to parse")
parser.add_argument("--mask", action="store_true", help="Apply masking")
parser.add_argument("--code", type=int, default=1000, help="Close code")
parser.add_argument("--reason", default="", help="Close reason")
parser.add_argument("--fragment-size", type=int, default=10, help="Max fragment size")
args = parser.parse_args()
if args.mode == "encode" and args.text:
frame = encode_text(args.text, mask=args.mask)
print(f"Text: {args.text}")
print(f"Frame: {frame.hex()}")
print(f"Length: {len(frame)} bytes")
elif args.mode == "parse" and args.hex:
data = bytes.fromhex(args.hex.replace(" ", ""))
frame, consumed = parse_frame(data)
print(format_frame(frame))
elif args.mode == "ping":
frame = encode_ping(b"ping", mask=args.mask)
print(f"Ping frame: {frame.hex()}")
pong = encode_pong(b"ping", mask=args.mask)
print(f"Pong frame: {pong.hex()}")
elif args.mode == "close":
frame = encode_close(args.code, args.reason, mask=args.mask)
code_name = CLOSE_CODES.get(args.code, "Unknown")
print(f"Close frame (code {args.code} - {code_name}):")
print(f" Hex: {frame.hex()}")
elif args.mode == "fragment":
text = args.text or "Hello, WebSocket World! This is a test message."
data = text.encode("utf-8")
frames = fragment_message(data, Opcode.TEXT, args.fragment_size, mask=args.mask)
print(f"Original: {text}")
print(f"Fragments: {len(frames)}")
for i, frame in enumerate(frames):
parsed, _ = parse_frame(frame)
fin_marker = " (FIN)" if parsed.fin else ""
print(f" Frame {i + 1}: {len(parsed.payload)} bytes{fin_marker}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_websocket_frame/websocket_cli.py (13766 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_websocket_frame/websocket_cli.rs (30746 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_websocket_frame/Cargo.toml (4 dependencies)
⏱️ Parse time: 64ms
📊 Throughput: 207.5 KB/s
⏱️ Total time: 64ms
| true
|
websocket_frame
| 458
| 6
|
[
"class_definition",
"exception_handling",
"decorator",
"multiprocessing"
] | 0.612
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.