Skip to content

Commit 832a422

Browse files
fix: submission handling
1 parent ab9104f commit 832a422

File tree

5 files changed

+124
-72
lines changed

5 files changed

+124
-72
lines changed

src/commands/daily.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
def daily(
66
lang: str = typer.Argument("py", help="Programming language to use."),
77
editor: str = typer.Option("vim", '--editor', '-e', help="Code editor to use."),
8+
full: bool = typer.Option(False, "--full", "-f", help="Show full problem description"),
89
save: bool = typer.Option(False, "--save", "-s", help="Save problem description to a file"),
910
no_editor: bool = typer.Option(False, "--no-editor", help="Skip opening editor"),
1011
):
@@ -26,7 +27,7 @@ def daily(
2627
question = result['data']['activeDailyCodingChallengeQuestion']
2728
typer.echo("\r" + " " * 30 + "\r", nl=False)
2829

29-
show(problem=question['question']['titleSlug'], save=save)
30+
show(problem=question['question']['titleSlug'], save=save, compact=not full)
3031
except Exception as e:
3132
typer.echo("\n" + typer.style(f"❌ Failed to fetch daily question: {str(e)}", fg=typer.colors.RED))
3233
raise typer.Exit(1)

src/commands/submit.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def submit(
3636
try:
3737
# Auto-detect language from file extension if not provided
3838
if not lang:
39-
extension = os.path.splitext(file)[1].lower()
39+
extension = os.path.splitext(file)[1].lower().replace(".", "")
4040
if extension in LANGUAGE_MAP:
4141
lang = LANGUAGE_MAP[extension]
4242
display_language_detection_message(lang)
@@ -55,6 +55,7 @@ def submit(
5555

5656
if not display_submission_details(problem, problem_name, lang, file):
5757
display_submission_canceled()
58+
return
5859

5960
if not lang:
6061
display_language_detection_error("")

src/lib/problem_ui.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def _format_markdown(self, content):
5151
md = re.sub(r'\*\*Input:\*\*', r'**Input:** ', md)
5252
md = re.sub(r'\*\*Output:\*\*', r'**Output:** ', md)
5353
md = re.sub(r'\*\*Explanation:\*\*', r'**Explanation:** ', md)
54-
md = re.sub(r'\n{3,}', '\n\n', md)
54+
md = re.sub(r'\n{2,}', '\n\n', md)
5555
return md
5656

5757
def _format_stats(self) -> str:
@@ -61,9 +61,9 @@ def _format_stats(self) -> str:
6161
'Total Submissions': self.stats.get('totalSubmission', 'N/A')
6262
}
6363

64-
formatted = [f"[{COLORS['section_title']}]Problem Statistics[/]"]
64+
formatted = [f"[{COLORS['section_title']}]Problem Statistics:[/]"]
6565
for label, value in stats.items():
66-
formatted.append(f"[{COLORS['stats_label']}]{label}:[/] {value}")
66+
formatted.append(f" - [{COLORS['stats_label']}]{label}:[/] {value}")
6767

6868
return "\n".join(formatted)
6969

@@ -81,13 +81,13 @@ def _format_topics(self) -> str:
8181
if not topic_names:
8282
return ""
8383

84-
return f"[{COLORS['section_title']}]Topics:[/] {', '.join(topic_names)}"
84+
return f"[{COLORS['section_title']}]Topics:[/] {', '.join(topic_names)}"
8585

8686
def _format_similar_questions(self) -> str:
8787
if not self.similar_questions:
8888
return ""
8989

90-
lines = [f"[{COLORS['section_title']}]Similar Questions:[/]"]
90+
lines = [f"[{COLORS['section_title']}]Similar Questions:[/]"]
9191
for q in self.similar_questions[:5]:
9292
title = q.get('title', '')
9393
difficulty = q.get('difficulty', '')
@@ -102,7 +102,7 @@ def _format_similar_questions(self) -> str:
102102
else:
103103
title_display = title
104104

105-
question_line = f"- [{COLORS['problem_number']}]#{question_id}[/] {title_display} {lock_symbol} ([{diff_color}]{difficulty}[/{diff_color}])"
105+
question_line = f" - [{COLORS['problem_number']}]#{question_id}[/] {title_display} {lock_symbol} ([{diff_color}]{difficulty}[/{diff_color}])"
106106
lines.append(question_line)
107107

108108
if len(lines) <= 1:

src/lib/submission_ui.py

Lines changed: 102 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from rich.console import Console
33
from rich.panel import Panel
44
from rich.progress import Progress, SpinnerColumn, TextColumn
5+
from ..server.config import STATUS_CODES
56
from rich import box
67
from rich.columns import Columns
78
import typer
@@ -54,7 +55,6 @@ def display_submission_details(problem, problem_name, lang, file):
5455
def display_submission_canceled():
5556
"""Display submission canceled message"""
5657
console.print("[yellow]Submission canceled[/]")
57-
raise typer.Exit(0)
5858

5959
def create_submission_progress():
6060
"""Create and return a submission progress context"""
@@ -67,89 +67,120 @@ def create_submission_progress():
6767
def display_submission_results(result: Dict[str, Any], is_test: bool = False):
6868
"""Display submission results with a cleaner layout"""
6969
status_code = result.get('status_code')
70-
status = result.get('status', result.get('status_msg', 'Unknown'))
70+
71+
# Use status code mapping if available
72+
if status_code in STATUS_CODES:
73+
status = STATUS_CODES[status_code]
74+
else:
75+
status = result.get('status', result.get('status_msg', 'Unknown'))
76+
7177
run_success = result.get('run_success', result.get('success', False))
7278

73-
if status == "Accepted" and run_success:
79+
# Determine status style and emoji
80+
if status_code == 10 or status == "Accepted" and run_success:
7481
status_style = "bold green"
7582
border_style = "green"
7683
emoji = "✅"
77-
elif status in ["Runtime Error", "Time Limit Exceeded"] or status_code in [14, 15]:
84+
elif status_code in [14, 15] or status in ["Runtime Error", "Time Limit Exceeded"]:
7885
status_style = "bold yellow"
7986
border_style = "yellow"
8087
emoji = "⚠️"
81-
elif status == "Compile Error" or status_code == 20:
88+
elif status_code in [12, 13]: # Memory Limit Exceeded, Output Limit Exceeded
89+
status_style = "bold yellow"
90+
border_style = "yellow"
91+
emoji = "⚠️"
92+
elif status_code == 20 or status == "Compile Error":
93+
status_style = "bold red"
94+
border_style = "red"
95+
emoji = "❌"
96+
elif status_code == 11: # Wrong Answer
8297
status_style = "bold red"
8398
border_style = "red"
8499
emoji = "❌"
100+
elif status_code in [16, 30]: # Internal Error, Timeout
101+
status_style = "bold red"
102+
border_style = "red"
103+
emoji = "⚠️"
85104
else:
86105
status_style = "bold red"
87106
border_style = "red"
88107
emoji = "❌"
89108

109+
# Format runtime and memory metrics
90110
runtime = result.get('status_runtime', result.get('runtime', 'N/A'))
91111
memory = result.get('status_memory', result.get('memory', 'N/A'))
92112

93113
if isinstance(memory, int):
94-
memory = f"{memory / 1000000:.1f} MB"
114+
memory = f"{memory / 1000000:.2f} MB"
95115

96116
memory_warning = None
97117
if isinstance(result.get('memory'), int):
98118
memory_value = result.get('memory', 0)
99119
if memory_value > 200000000:
100-
memory_warning = f"Your solution is using a large amount of memory ({memory_value/1000000:.1f} MB). Consider optimizing to reduce memory usage."
101-
102-
if memory_warning:
103-
memory = f"{memory} [bold yellow](!)[/]"
120+
memory_warning = f"Your solution is using a large amount of memory ({memory_value/1000000:.2f} MB). Consider optimizing to reduce memory usage."
104121

122+
# Calculate test case statistics
105123
passed = result.get('total_correct', 0)
106124
total = result.get('total_testcases', 0)
107125

108126
test_case_str = "N/A"
109127
if total and total > 0:
110128
percentage = (passed / total) * 100
111129
test_case_str = f"{passed}/{total} ({percentage:.1f}%)"
112-
113-
content_parts = []
114-
content_parts.append(f"[cyan]⏱️ Runtime:[/] {runtime}")
115-
content_parts.append(f"[cyan]💾 Memory:[/] {memory}")
130+
if percentage == 100:
131+
test_case_str = f"[bold green]{test_case_str}[/]"
132+
elif percentage >= 80:
133+
test_case_str = f"[bold yellow]{test_case_str}[/]"
134+
else:
135+
test_case_str = f"[bold red]{test_case_str}[/]"
136+
137+
content_parts = [
138+
f"📊 [bold cyan]Status:[/] [{status_style}]{status}[/]\n",
139+
f"[bold cyan]🕒 Runtime:[/] {runtime}",
140+
f"[bold cyan]📝 Memory:[/] {memory}" + (" [bold yellow](!)[/]" if memory_warning else ""),
141+
]
116142

117143
if result.get('elapsed_time'):
118-
content_parts.append(f"[cyan]⏲️ Elapsed Time:[/] {result.get('elapsed_time')} ms")
144+
content_parts.append(f"⌛ [bold cyan]Time:[/] {result.get('elapsed_time')} ms")
145+
146+
content_parts.append(f"🧪 [bold cyan]Tests:[/] {test_case_str}")
147+
148+
if status == "Accepted" and run_success:
149+
if "beats" in str(runtime).lower() or "percentile" in str(runtime).lower():
150+
content_parts.append(f"[bold green]🚀 Great performance![/]")
119151

120-
content_parts.append(f"[cyan]🧪 Test Cases:[/] {test_case_str}")
121152
content_string = "\n".join(content_parts)
122153

123-
title = f"{emoji} {'Test' if is_test else 'Submission'} Result: [{status_style}]{status}[/]"
154+
title = f"{emoji} {'Test' if is_test else 'Submission'} Result"
124155
console.print(Panel(
125156
content_string,
126157
title=title,
158+
title_align="center",
127159
border_style=border_style,
128160
box=box.ROUNDED,
129-
padding=(0, 10)
161+
padding=(1, 2)
130162
))
131163

132-
# Display specific error messages
133164
if status == "Compile Error" or status_code == 20:
134165
error_msg = result.get('compile_error', result.get('error', 'No details available'))
135166
full_error = result.get('full_compile_error', result.get('full_error', ''))
136167

137168
if error_msg:
138169
console.print(Panel(
139-
error_msg,
140-
title="Compilation Error",
170+
f"[red]{error_msg}[/]",
171+
title="Compilation Error",
141172
border_style="red",
142173
box=box.ROUNDED,
143-
padding=(0, 1)
174+
padding=(1, 1)
144175
))
145176

146-
if full_error:
177+
if full_error and full_error != error_msg:
147178
console.print(Panel(
148-
full_error,
179+
f"[dim]{full_error}[/]",
149180
title="Full Compilation Error",
150181
border_style="red",
151182
box=box.ROUNDED,
152-
padding=(0, 1)
183+
padding=(1, 1)
153184
))
154185

155186
elif status == "Runtime Error" or status_code == 15:
@@ -158,30 +189,29 @@ def display_submission_results(result: Dict[str, Any], is_test: bool = False):
158189

159190
if error_msg:
160191
console.print(Panel(
161-
error_msg,
162-
title="Runtime Error",
192+
f"[yellow]{error_msg}[/]",
193+
title="⚠️ Runtime Error",
163194
border_style="yellow",
164195
box=box.ROUNDED,
165-
padding=(0, 1)
196+
padding=(1, 1)
166197
))
167198

168-
if full_error:
199+
if full_error and full_error != error_msg:
169200
console.print(Panel(
170-
full_error,
201+
f"[dim]{full_error}[/]",
171202
title="Full Error Trace",
172203
border_style="yellow",
173204
box=box.ROUNDED,
174-
padding=(0, 1)
205+
padding=(1, 1)
175206
))
176207

177-
# Display memory warning if present
178208
if memory_warning:
179209
console.print(Panel(
180-
memory_warning,
210+
f"[yellow]{memory_warning}[/]",
181211
title="⚠️ Memory Usage Warning",
182212
border_style="yellow",
183213
box=box.ROUNDED,
184-
padding=(0, 1)
214+
padding=(1, 1)
185215
))
186216

187217
stdout_lines = []
@@ -203,15 +233,15 @@ def display_submission_results(result: Dict[str, Any], is_test: bool = False):
203233
title="📝 Standard Output",
204234
border_style="blue",
205235
box=box.ROUNDED,
206-
padding=(0, 1)
236+
padding=(1, 1)
207237
))
208238
elif result.get('stdout') and result.get('stdout', '').strip():
209239
console.print(Panel(
210240
result.get('stdout', '').strip(),
211241
title="📝 Standard Output",
212242
border_style="blue",
213243
box=box.ROUNDED,
214-
padding=(0, 1)
244+
padding=(1, 1)
215245
))
216246

217247
if result.get('code_answer') and result.get('expected_code_answer'):
@@ -222,57 +252,77 @@ def display_submission_results(result: Dict[str, Any], is_test: bool = False):
222252
output = "\n".join(output_lines)
223253
expected = "\n".join(expected_lines)
224254

225-
is_wrong_answer = status == "Wrong Answer" or (not run_success and not (status in ["Compile Error", "Runtime Error", "Time Limit Exceeded"]))
255+
is_wrong_answer = status == "Wrong Answer" or (not run_success and
256+
not (status in ["Compile Error", "Runtime Error", "Time Limit Exceeded"]))
226257

227258
output_panel = Panel(
228259
output,
229-
title="Your Output",
260+
title="🔍 Your Output",
230261
border_style="red" if is_wrong_answer else "blue",
231-
padding=(0, 1)
262+
padding=(1, 1)
232263
)
233264
expected_panel = Panel(
234265
expected,
235-
title="Expected Output",
266+
title="Expected Output",
236267
border_style="green",
237-
padding=(0, 1)
268+
padding=(1, 1)
238269
)
270+
271+
if is_wrong_answer:
272+
console.print(Panel(
273+
"[bold red]Output does not match expected result[/]",
274+
title="❌ Wrong Answer",
275+
border_style="red",
276+
padding=(0, 1)
277+
))
278+
239279
console.print(Columns([output_panel, expected_panel]))
280+
240281
elif result.get('output') or result.get('expected'):
241282
output = (result.get('output', '') or '').strip()
242283
expected = (result.get('expected', '') or '').strip()
243284

244-
is_wrong_answer = status == "Wrong Answer" or (not run_success and not (status in ["Compile Error", "Runtime Error", "Time Limit Exceeded"]))
285+
is_wrong_answer = status == "Wrong Answer" or (not run_success and
286+
not (status in ["Compile Error", "Runtime Error", "Time Limit Exceeded"]))
287+
288+
if is_wrong_answer:
289+
console.print(Panel(
290+
"[bold red]Output does not match expected result[/]",
291+
title="❌ Wrong Answer",
292+
border_style="red",
293+
padding=(0, 1)
294+
))
245295

246296
output_panel = Panel(
247297
output,
248-
title="Your Output",
298+
title="🔍 Your Output",
249299
border_style="red" if is_wrong_answer else "blue",
250-
padding=(0, 1)
300+
padding=(1, 1)
251301
)
252302
expected_panel = Panel(
253303
expected,
254-
title="Expected Output",
304+
title="Expected Output",
255305
border_style="green",
256-
padding=(0, 1)
306+
padding=(1, 1)
257307
)
258308
console.print(Columns([output_panel, expected_panel]))
259309

260310
if not run_success and status not in ["Compile Error", "Runtime Error"] and result.get('error'):
261311
error_msg = result.get('error', 'No details available')
262312
console.print(Panel(
263-
error_msg,
264-
title="Error Details",
313+
f"[red]{error_msg}[/]",
314+
title="Error Details",
265315
border_style="red",
266-
padding=(0, 1)
316+
padding=(1, 1)
267317
))
268318

269-
if result.get('full_error'):
319+
if result.get('full_error') and result.get('full_error') != error_msg:
270320
console.print(Panel(
271-
result.get('full_error', ''),
321+
f"[dim]{result.get('full_error', '')}[/]",
272322
title="Full Error Trace",
273323
border_style="red",
274324
box=box.ROUNDED,
275-
padding=(0, 1)
325+
padding=(1, 1)
276326
))
277327

278328
def display_exception_error(e):

0 commit comments

Comments
 (0)