shivakumar2005 commited on
Commit
0ece6cd
·
verified ·
1 Parent(s): 10e4698

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -323
app.py CHANGED
@@ -18,7 +18,8 @@ def default_progress_data():
18
  "total_hours_studied": 0,
19
  "last_study_date": datetime.now().isoformat(),
20
  "daily_goals": {},
21
- "achievements": []
 
22
  }
23
 
24
  def default_opportunities_data():
@@ -205,6 +206,534 @@ ROADMAPS = {
205
  }
206
  }
207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  # ---------------- Opportunities (H/I/S) ----------------
209
  HACKATHONS = [
210
  {"name":"Smart India Hackathon 2025","deadline":"2025-09-30","eligibility":"College Students (All Years)","prizes":"₹5 Lakhs + Incubation","skills":["Programming","Problem Solving"],"url":"https://sih.gov.in","category":"National","level":"B.Tech All Years"},
@@ -285,325 +814,4 @@ def mark_session_completed(level, session_title):
285
 
286
  def create_dashboard_stats(level):
287
  p = load_progress()
288
- sessions = ROADMAPS.get(level, {}).get("study_sessions", [])
289
- completed_sessions = sum(1 for s in sessions if p.get("study_sessions_completed", {}).get(f"{level}_{s['title']}", False))
290
- total_sessions = len(sessions)
291
- percent = (completed_sessions / total_sessions * 100) if total_sessions > 0 else 0
292
- last = p.get("last_study_date", datetime.now().isoformat())[:10]
293
- html_block = f"""
294
- <div style='background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;padding:16px;border-radius:10px;'>
295
- <h3>🎯 {level} Learning Dashboard</h3>
296
- <div style='display:flex;justify-content:space-around;flex-wrap:wrap;margin-top:10px;'>
297
- <div><h4>📚 {completed_sessions}/{total_sessions}</h4><small>Sessions</small></div>
298
- <div><h4>⏰ {p.get('total_hours_studied',0):.1f}</h4><small>Total Hours</small></div>
299
- <div><h4>📅 {last}</h4><small>Last Study</small></div>
300
- </div>
301
- <p style='margin-top:12px;'>Overall Progress: <strong>{percent:.1f}%</strong></p>
302
- <div style='background:#ddd;border-radius:8px;height:10px;'><div style='background:#28a745;height:100%;width:{percent}%;border-radius:8px;'></div></div>
303
- </div>
304
- """
305
- return html_block
306
-
307
- # ---------------- Opportunities & Reminders ----------------
308
- def get_upcoming_deadlines_html():
309
- today = datetime.now().date()
310
- items = HACKATHONS + INTERNSHIPS + SCHOLARSHIPS
311
- deadlines = []
312
- for it in items:
313
- dl = it.get("deadline")
314
- try:
315
- d = datetime.strptime(dl, "%Y-%m-%d").date()
316
- days = (d - today).days
317
- except:
318
- days = None
319
- deadlines.append({"name":it.get("name"), "deadline":dl, "days_left":days, "url":it.get("url","#")})
320
- deadlines = sorted([d for d in deadlines if d['days_left'] is None or d['days_left']>=0], key=lambda x: (x['days_left'] if x['days_left'] is not None else 999))
321
- if not deadlines:
322
- return "<div style='padding:12px;text-align:center;'><h4>No upcoming deadlines</h4></div>"
323
- html_block = "<div style='max-height:420px;overflow-y:auto;'>"
324
- for d in deadlines[:12]:
325
- left = f"{d['days_left']} days left" if d['days_left'] is not None else "N/A"
326
- html_block += f"<div style='padding:10px;margin:8px 0;background:white;border-radius:8px;'><h4>{html.escape(d['name'])}</h4><p>📅 {d['deadline']} | {left}</p><a href='{d['url']}' target='_blank'>More</a></div>"
327
- html_block += "</div>"
328
- return html_block
329
-
330
- def create_hackathon_interface_html():
331
- html_block = "<div style='max-height:420px;overflow-y:auto;'>"
332
- for h in HACKATHONS:
333
- try:
334
- days = (datetime.strptime(h['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
335
- except:
336
- days = "N/A"
337
- html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;border-radius:8px;'><h4>🏆 {h['name']}</h4><p>📅 {h['deadline']} | {days} days left</p><p>Eligibility: {h['eligibility']}</p><a href='{h['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
338
- html_block += "</div>"
339
- return html_block
340
-
341
- def create_internship_interface_html():
342
- html_block = "<div style='max-height:420px;overflow-y:auto;'>"
343
- for it in INTERNSHIPS:
344
- try:
345
- days = (datetime.strptime(it['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
346
- except:
347
- days = "N/A"
348
- html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#e6f4ff,#cfeeff);color:#0b3d91;border-radius:8px;'><h4>💼 {it['name']}</h4><p>📅 {it['deadline']} | {days} days left</p><p>Duration: {it.get('duration')}</p><a href='{it['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
349
- html_block += "</div>"
350
- return html_block
351
-
352
- def create_scholarship_interface_html():
353
- html_block = "<div style='max-height:420px;overflow-y:auto;'>"
354
- for s in SCHOLARSHIPS:
355
- try:
356
- days = (datetime.strptime(s['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
357
- except:
358
- days = "N/A"
359
- html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#e0f7ff,#cdeeff);color:#0b3d91;border-radius:8px;'><h4>🎓 {s['name']}</h4><p>📅 {s['deadline']} | {days} days left</p><p>Amount: {s.get('amount')}</p><a href='{s['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
360
- html_block += "</div>"
361
- return html_block
362
-
363
- def set_custom_reminder(reminder_type, reminder_name, reminder_date, reminder_notes):
364
- if not reminder_name or not reminder_date:
365
- return "❌ Name and date required."
366
- try:
367
- datetime.strptime(reminder_date, "%Y-%m-%d")
368
- except ValueError:
369
- return "❌ Invalid date format. Use YYYY-MM-DD."
370
- data = load_opportunities()
371
- data.setdefault("reminders", [])
372
- new = {
373
- "type": reminder_type or "Personal",
374
- "name": reminder_name,
375
- "date": reminder_date,
376
- "notes": reminder_notes or "",
377
- "set_date": datetime.now().isoformat(),
378
- "completed": False
379
- }
380
- data["reminders"].append(new)
381
- save_opportunities(data)
382
- return f"✅ Reminder set for {reminder_date}: {reminder_name}"
383
-
384
- def get_custom_reminders_html():
385
- data = load_opportunities()
386
- rems = data.get("reminders", [])
387
- if not rems:
388
- return "<div style='text-align:center;padding:12px;'><h4>No custom reminders.</h4></div>"
389
- html_block = "<div style='max-height:420px;overflow-y:auto;'>"
390
- for idx, r in enumerate(rems):
391
- try:
392
- d = datetime.strptime(r['date'], "%Y-%m-%d").date()
393
- days_left = (d - datetime.now().date()).days
394
- left_text = f"{days_left} days left"
395
- except:
396
- left_text = "N/A"
397
- color = "#28a745" if r.get("completed") else "#ff6b6b"
398
- status = "✅" if r.get("completed") else "⏳"
399
- html_block += f"""
400
- <div style='padding:10px;margin:8px 0;background:white;border-left:6px solid {color};border-radius:8px;'>
401
- <h4>{status} [{idx}] {html.escape(r['type'])}: {html.escape(r['name'])}</h4>
402
- <p>📅 {r['date']} | {left_text}</p>
403
- <p>📝 {html.escape(r.get('notes',''))}</p>
404
- <p style='font-size:12px;color:#666;'>Set on: {r['set_date'][:10]}</p>
405
- </div>
406
- """
407
- html_block += "</div>"
408
- return html_block
409
-
410
- def mark_reminder_completed(index):
411
- data = load_opportunities()
412
- rems = data.get("reminders", [])
413
- try:
414
- idx = int(index)
415
- if idx < 0 or idx >= len(rems):
416
- return "❌ Invalid index"
417
- except:
418
- return "❌ Invalid index"
419
- rems[idx]['completed'] = True
420
- save_opportunities(data)
421
- return "✅ Reminder marked completed."
422
-
423
- def delete_reminder(index):
424
- data = load_opportunities()
425
- rems = data.get("reminders", [])
426
- try:
427
- idx = int(index)
428
- if idx < 0 or idx >= len(rems):
429
- return "❌ Invalid index"
430
- except:
431
- return "❌ Invalid index"
432
- name = rems[idx].get("name","")
433
- rems.pop(idx)
434
- save_opportunities(data)
435
- return f"🗑️ Reminder '{name}' deleted."
436
-
437
- # ---------------- GRADIO UI ----------------
438
- custom_css = """
439
- /* Light blue background gradient for the whole app */
440
- .gradio-container {
441
- background: linear-gradient(135deg, #eaf6ff 0%, #d5efff 100%);
442
- min-height: 100vh;
443
- padding: 24px;
444
- color: #0b3d91;
445
- }
446
- /* Slightly transparent panels so the light-blue shows through */
447
- .gradio-container .container {
448
- background: rgba(255,255,255,0.04);
449
- border-radius: 12px;
450
- padding: 16px;
451
- }
452
- """
453
-
454
- with gr.Blocks(title="Road2Success — Learning Dashboard (light blue)", theme=gr.themes.Soft(), css=custom_css) as app:
455
- gr.Markdown("# 🚀 Road2Success — Learning Dashboard")
456
- gr.Markdown("*Professional roadmap, AI mentor, hackathon prep & leaderboard*")
457
-
458
- with gr.Tabs():
459
- # Learning Dashboard
460
- with gr.TabItem("🏠 Learning Dashboard"):
461
- with gr.Row():
462
- with gr.Column(scale=2):
463
- gr.Markdown("### Select Level")
464
- level_choice = gr.Radio(choices=list(ROADMAPS.keys()), value=list(ROADMAPS.keys())[0], label="Level")
465
- refresh_btn = gr.Button("🔄 Refresh")
466
- stats_display = gr.HTML()
467
- with gr.Column(scale=3):
468
- progress_plot = gr.Plot()
469
- gr.Markdown("### Study Materials")
470
- with gr.Row():
471
- with gr.Column(scale=2):
472
- materials_html = gr.HTML()
473
- with gr.Column(scale=1):
474
- gr.Markdown("### Quick Actions")
475
- session_dropdown = gr.Dropdown(label="Session", choices=[])
476
- mark_session_btn = gr.Button("Mark Session Complete")
477
- action_status = gr.Textbox(interactive=False, label="Action status")
478
- schedule_html = gr.HTML()
479
- # Reset button
480
- reset_status = gr.Textbox(interactive=False, label="Reset status")
481
- reset_btn = gr.Button("⚠️ Reset Dashboard", variant="danger")
482
-
483
- # Study Roadmaps
484
- with gr.TabItem("📚 Study Roadmaps"):
485
- gr.Markdown("## 🗺️ Study Roadmaps")
486
- roadmap_level = gr.Dropdown(choices=list(ROADMAPS.keys()), value=list(ROADMAPS.keys())[0], label="Select Level")
487
- show_roadmap_btn = gr.Button("Show Roadmap")
488
- roadmap_html = gr.HTML()
489
-
490
- # Opportunities & Reminders
491
- with gr.TabItem("🚀 Opportunities & Reminders"):
492
- gr.Markdown("## 🌟 Opportunities Hub")
493
- with gr.Row():
494
- with gr.Column(scale=2):
495
- opp_overview = gr.HTML()
496
- gr.Markdown("### Hackathons")
497
- hack_html = gr.HTML()
498
- gr.Markdown("### Internships")
499
- intern_html = gr.HTML()
500
- gr.Markdown("### Scholarships")
501
- schol_html = gr.HTML()
502
- with gr.Column(scale=1):
503
- gr.Markdown("### Set Custom Reminder")
504
- r_type = gr.Dropdown(["Hackathon","Internship","Scholarship","Exam","Project","Personal"], label="Type")
505
- r_name = gr.Textbox(label="Name")
506
- r_date = gr.Textbox(label="Date (YYYY-MM-DD)")
507
- r_notes = gr.Textbox(label="Notes", lines=2)
508
- set_reminder_btn = gr.Button("Set Reminder")
509
- set_out = gr.Textbox(interactive=False, label="Set status")
510
- gr.Markdown("### Your Reminders (0-based index shown)")
511
- reminders_html = gr.HTML()
512
- rem_index = gr.Textbox(label="Reminder index (0-based)")
513
- mark_done_btn = gr.Button("Mark Done")
514
- del_btn = gr.Button("Delete Reminder")
515
- rem_action_status = gr.Textbox(interactive=False, label="Reminder action status")
516
-
517
- # AI Mentor
518
- with gr.TabItem("🤖 AI Mentor"):
519
- gr.Markdown("## 💬 AI Mentor (simple fallback)")
520
- prompt = gr.Textbox(label="Ask a question", lines=3)
521
- short_toggle = gr.Checkbox(label="Short answer", value=True)
522
- eli5_toggle = gr.Checkbox(label="Explain simply", value=False)
523
- ask_btn = gr.Button("Ask Mentor")
524
- mentor_out = gr.Textbox(lines=6, label="Mentor output")
525
-
526
- # -- Core update function used by several handlers
527
- def update_dashboard(level):
528
- sessions = ROADMAPS.get(level, {}).get("study_sessions", [])
529
- session_titles = [s['title'] for s in sessions]
530
- stats = create_dashboard_stats(level)
531
- completed_sessions = sum(1 for s in sessions if load_progress().get("study_sessions_completed", {}).get(f"{level}_{s['title']}", False))
532
- fig = create_progress_chart(level, completed_sessions, len(sessions))
533
- schedule = "<div style='padding:12px;background:rgba(255,255,255,0.04);border-radius:8px;'><h4>Weekly Plan</h4>"
534
- schedule += f"<p>Target: {ROADMAPS.get(level,{}).get('weekly_hours', 'N/A')} hours per week</p>"
535
- schedule += f"<p>Focus: {', '.join(ROADMAPS.get(level,{}).get('subjects', []))}</p></div>"
536
- materials = get_study_materials_interface(level)
537
- opps = get_upcoming_deadlines_html()
538
- return gr.update(choices=session_titles, value=(session_titles[0] if session_titles else None)), stats, fig, schedule, materials, opps
539
-
540
- # Helper to refresh multiple UI parts (used after reset)
541
- def refresh_all(level):
542
- session_update, stats, fig, schedule, materials, opps = update_dashboard(level)
543
- reminders = get_custom_reminders_html()
544
- hack = create_hackathon_interface_html()
545
- intern = create_internship_interface_html()
546
- schol = create_scholarship_interface_html()
547
- return session_update, stats, fig, schedule, materials, opps, reminders, hack, intern, schol
548
-
549
- # Reset handler
550
- def reset_dashboard():
551
- save_progress(default_progress_data())
552
- save_opportunities(default_opportunities_data())
553
- reset_leaderboard()
554
- return "✅ Dashboard reset to defaults."
555
-
556
- # Wire events (use inputs rather than .value)
557
- level_choice.change(update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
558
- refresh_btn.click(update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
559
- app.load(lambda: update_dashboard(list(ROADMAPS.keys())[0]), outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
560
-
561
- mark_session_btn.click(mark_session_completed, inputs=[level_choice, session_dropdown], outputs=[action_status]).then(
562
- update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview]
563
- )
564
-
565
- # Reset button wiring: run reset_dashboard then refresh entire UI
566
- reset_btn.click(reset_dashboard, outputs=[reset_status]).then(
567
- refresh_all, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview, reminders_html, hack_html, intern_html, schol_html]
568
- )
569
-
570
- # Study roadmap
571
- def show_roadmap(level):
572
- r = ROADMAPS.get(level, {})
573
- html_block = f"<div style='padding:16px;background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;border-radius:10px;'><h2>{level} - Learning Path</h2>"
574
- html_block += f"<h4>Objective</h4><p>{r.get('objective','')}</p>"
575
- html_block += "<h4>Subjects</h4><ul>"
576
- for sub in r.get('subjects', []):
577
- html_block += f"<li>{sub}</li>"
578
- html_block += "</ul><h4>Projects</h4><ul>"
579
- for proj in r.get('projects', []):
580
- html_block += f"<li>{proj}</li>"
581
- html_block += "</ul>"
582
- html_block += f"<p><strong>Weekly hours:</strong> {r.get('weekly_hours','N/A')}</p></div>"
583
- return html_block
584
-
585
- show_roadmap_btn.click(show_roadmap, inputs=[roadmap_level], outputs=[roadmap_html])
586
-
587
- # Opportunities and reminders initial loads
588
- app.load(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
589
- app.load(lambda: create_hackathon_interface_html(), outputs=[hack_html])
590
- app.load(lambda: create_internship_interface_html(), outputs=[intern_html])
591
- app.load(lambda: create_scholarship_interface_html(), outputs=[schol_html])
592
- app.load(lambda: get_custom_reminders_html(), outputs=[reminders_html])
593
-
594
- set_reminder_btn.click(set_custom_reminder, inputs=[r_type, r_name, r_date, r_notes], outputs=[set_out]).then(
595
- lambda: get_custom_reminders_html(), outputs=[reminders_html]
596
- ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
597
-
598
- mark_done_btn.click(mark_reminder_completed, inputs=[rem_index], outputs=[rem_action_status]).then(
599
- lambda: get_custom_reminders_html(), outputs=[reminders_html]
600
- ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
601
-
602
- del_btn.click(delete_reminder, inputs=[rem_index], outputs=[rem_action_status]).then(
603
- lambda: get_custom_reminders_html(), outputs=[reminders_html]
604
- ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
605
-
606
- ask_btn.click(ai_mentor_query, inputs=[prompt, short_toggle, eli5_toggle], outputs=[mentor_out])
607
-
608
- # Launch Gradio app
609
- app.launch()
 
18
  "total_hours_studied": 0,
19
  "last_study_date": datetime.now().isoformat(),
20
  "daily_goals": {},
21
+ "achievements": [],
22
+ "code_snippets_completed": {}
23
  }
24
 
25
  def default_opportunities_data():
 
206
  }
207
  }
208
 
209
+ # ---------------- Code Snippets for B.Tech Students ----------------
210
+ CODE_SNIPPETS = {
211
+ "B.Tech 1st Year": [
212
+ {
213
+ "title": "Factorial Calculator",
214
+ "problem": "Write a C program to calculate factorial of a number using recursion",
215
+ "code": """#include <stdio.h>
216
+
217
+ long factorial(int n) {
218
+ if (n == 0 || n == 1)
219
+ return 1;
220
+ else
221
+ return n * factorial(n - 1);
222
+ }
223
+
224
+ int main() {
225
+ int num;
226
+ printf("Enter a positive integer: ");
227
+ scanf("%d", &num);
228
+
229
+ if (num < 0)
230
+ printf("Factorial is not defined for negative numbers.\\n");
231
+ else
232
+ printf("Factorial of %d = %ld\\n", num, factorial(num));
233
+
234
+ return 0;
235
+ }""",
236
+ "explanation": "This program uses recursion to calculate factorial. The base case is when n=0 or n=1, returning 1. Otherwise, it calls itself with n-1.",
237
+ "video_url": "https://www.youtube.com/embed/4agL-MQq05E"
238
+ },
239
+ {
240
+ "title": "Matrix Multiplication",
241
+ "problem": "Write a C program for matrix multiplication",
242
+ "code": """#include <stdio.h>
243
+
244
+ int main() {
245
+ int a[10][10], b[10][10], result[10][10];
246
+ int r1, c1, r2, c2;
247
+
248
+ printf("Enter rows and columns for first matrix: ");
249
+ scanf("%d %d", &r1, &c1);
250
+ printf("Enter rows and columns for second matrix: ");
251
+ scanf("%d %d", &r2, &c2);
252
+
253
+ if (c1 != r2) {
254
+ printf("Matrix multiplication not possible!\\n");
255
+ return 0;
256
+ }
257
+
258
+ printf("Enter elements of matrix 1:\\n");
259
+ for(int i=0; i<r1; i++)
260
+ for(int j=0; j<c1; j++)
261
+ scanf("%d", &a[i][j]);
262
+
263
+ printf("Enter elements of matrix 2:\\n");
264
+ for(int i=0; i<r2; i++)
265
+ for(int j=0; j<c2; j++)
266
+ scanf("%d", &b[i][j]);
267
+
268
+ // Multiply matrices
269
+ for(int i=0; i<r1; i++) {
270
+ for(int j=0; j<c2; j++) {
271
+ result[i][j] = 0;
272
+ for(int k=0; k<c1; k++)
273
+ result[i][j] += a[i][k] * b[k][j];
274
+ }
275
+ }
276
+
277
+ printf("Result matrix:\\n");
278
+ for(int i=0; i<r1; i++) {
279
+ for(int j=0; j<c2; j++)
280
+ printf("%d\\t", result[i][j]);
281
+ printf("\\n");
282
+ }
283
+
284
+ return 0;
285
+ }""",
286
+ "explanation": "Matrix multiplication requires that columns of first matrix equal rows of second matrix. Uses triple nested loops for calculation.",
287
+ "video_url": "https://www.youtube.com/embed/jzdQ-5hry98"
288
+ }
289
+ ],
290
+ "B.Tech 2nd Year": [
291
+ {
292
+ "title": "Linked List Implementation",
293
+ "problem": "Implement a singly linked list with insert, delete and display operations",
294
+ "code": """#include <stdio.h>
295
+ #include <stdlib.h>
296
+
297
+ struct Node {
298
+ int data;
299
+ struct Node* next;
300
+ };
301
+
302
+ struct Node* createNode(int data) {
303
+ struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
304
+ newNode->data = data;
305
+ newNode->next = NULL;
306
+ return newNode;
307
+ }
308
+
309
+ void insertAtEnd(struct Node** head, int data) {
310
+ struct Node* newNode = createNode(data);
311
+
312
+ if (*head == NULL) {
313
+ *head = newNode;
314
+ return;
315
+ }
316
+
317
+ struct Node* temp = *head;
318
+ while (temp->next != NULL)
319
+ temp = temp->next;
320
+
321
+ temp->next = newNode;
322
+ }
323
+
324
+ void deleteNode(struct Node** head, int key) {
325
+ struct Node *temp = *head, *prev = NULL;
326
+
327
+ if (temp != NULL && temp->data == key) {
328
+ *head = temp->next;
329
+ free(temp);
330
+ return;
331
+ }
332
+
333
+ while (temp != NULL && temp->data != key) {
334
+ prev = temp;
335
+ temp = temp->next;
336
+ }
337
+
338
+ if (temp == NULL) return;
339
+
340
+ prev->next = temp->next;
341
+ free(temp);
342
+ }
343
+
344
+ void displayList(struct Node* head) {
345
+ struct Node* temp = head;
346
+ while (temp != NULL) {
347
+ printf("%d -> ", temp->data);
348
+ temp = temp->next;
349
+ }
350
+ printf("NULL\\n");
351
+ }
352
+
353
+ int main() {
354
+ struct Node* head = NULL;
355
+
356
+ insertAtEnd(&head, 10);
357
+ insertAtEnd(&head, 20);
358
+ insertAtEnd(&head, 30);
359
+
360
+ printf("Linked list: ");
361
+ displayList(head);
362
+
363
+ deleteNode(&head, 20);
364
+ printf("After deleting 20: ");
365
+ displayList(head);
366
+
367
+ return 0;
368
+ }""",
369
+ "explanation": "Singly linked list implementation with dynamic memory allocation. Includes node creation, insertion at end, deletion by value, and display functions.",
370
+ "video_url": "https://www.youtube.com/embed/dq3F3e9o2DM"
371
+ },
372
+ {
373
+ "title": "Binary Search Tree",
374
+ "problem": "Implement BST with insert, search and inorder traversal",
375
+ "code": """#include <stdio.h>
376
+ #include <stdlib.h>
377
+
378
+ struct Node {
379
+ int data;
380
+ struct Node *left, *right;
381
+ };
382
+
383
+ struct Node* createNode(int data) {
384
+ struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
385
+ newNode->data = data;
386
+ newNode->left = newNode->right = NULL;
387
+ return newNode;
388
+ }
389
+
390
+ struct Node* insert(struct Node* root, int data) {
391
+ if (root == NULL)
392
+ return createNode(data);
393
+
394
+ if (data < root->data)
395
+ root->left = insert(root->left, data);
396
+ else if (data > root->data)
397
+ root->right = insert(root->right, data);
398
+
399
+ return root;
400
+ }
401
+
402
+ struct Node* search(struct Node* root, int key) {
403
+ if (root == NULL || root->data == key)
404
+ return root;
405
+
406
+ if (key < root->data)
407
+ return search(root->left, key);
408
+
409
+ return search(root->right, key);
410
+ }
411
+
412
+ void inorder(struct Node* root) {
413
+ if (root != NULL) {
414
+ inorder(root->left);
415
+ printf("%d ", root->data);
416
+ inorder(root->right);
417
+ }
418
+ }
419
+
420
+ int main() {
421
+ struct Node* root = NULL;
422
+
423
+ root = insert(root, 50);
424
+ insert(root, 30);
425
+ insert(root, 20);
426
+ insert(root, 40);
427
+ insert(root, 70);
428
+ insert(root, 60);
429
+ insert(root, 80);
430
+
431
+ printf("Inorder traversal: ");
432
+ inorder(root);
433
+ printf("\\n");
434
+
435
+ int key = 40;
436
+ if (search(root, key) != NULL)
437
+ printf("%d found in BST\\n", key);
438
+ else
439
+ printf("%d not found in BST\\n", key);
440
+
441
+ return 0;
442
+ }""",
443
+ "explanation": "Binary Search Tree implementation with recursive insert, search and inorder traversal. BST property: left < root < right.",
444
+ "video_url": "https://www.youtube.com/embed/cySVml6e_Fc"
445
+ }
446
+ ],
447
+ "B.Tech 3rd Year": [
448
+ {
449
+ "title": "Dijkstra's Algorithm",
450
+ "problem": "Implement Dijkstra's algorithm for shortest path finding",
451
+ "code": """#include <stdio.h>
452
+ #include <limits.h>
453
+
454
+ #define V 6
455
+
456
+ int minDistance(int dist[], int sptSet[]) {
457
+ int min = INT_MAX, min_index;
458
+
459
+ for (int v = 0; v < V; v++)
460
+ if (sptSet[v] == 0 && dist[v] <= min)
461
+ min = dist[v], min_index = v;
462
+
463
+ return min_index;
464
+ }
465
+
466
+ void printSolution(int dist[]) {
467
+ printf("Vertex \\t Distance from Source\\n");
468
+ for (int i = 0; i < V; i++)
469
+ printf("%d \\t %d\\n", i, dist[i]);
470
+ }
471
+
472
+ void dijkstra(int graph[V][V], int src) {
473
+ int dist[V];
474
+ int sptSet[V];
475
+
476
+ for (int i = 0; i < V; i++)
477
+ dist[i] = INT_MAX, sptSet[i] = 0;
478
+
479
+ dist[src] = 0;
480
+
481
+ for (int count = 0; count < V - 1; count++) {
482
+ int u = minDistance(dist, sptSet);
483
+ sptSet[u] = 1;
484
+
485
+ for (int v = 0; v < V; v++)
486
+ if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
487
+ && dist[u] + graph[u][v] < dist[v])
488
+ dist[v] = dist[u] + graph[u][v];
489
+ }
490
+
491
+ printSolution(dist);
492
+ }
493
+
494
+ int main() {
495
+ int graph[V][V] = {
496
+ {0, 4, 0, 0, 0, 0},
497
+ {4, 0, 8, 0, 0, 0},
498
+ {0, 8, 0, 7, 0, 4},
499
+ {0, 0, 7, 0, 9, 14},
500
+ {0, 0, 0, 9, 0, 10},
501
+ {0, 0, 4, 14, 10, 0}
502
+ };
503
+
504
+ dijkstra(graph, 0);
505
+ return 0;
506
+ }""",
507
+ "explanation": "Dijkstra's algorithm finds shortest paths from source to all vertices in a weighted graph. Uses greedy approach with priority queue.",
508
+ "video_url": "https://www.youtube.com/embed/GazC3A4OQTE"
509
+ },
510
+ {
511
+ "title": "Producer-Consumer Problem",
512
+ "problem": "Implement producer-consumer problem using semaphores",
513
+ "code": """#include <stdio.h>
514
+ #include <stdlib.h>
515
+ #include <pthread.h>
516
+ #include <semaphore.h>
517
+
518
+ #define BUFFER_SIZE 5
519
+
520
+ int buffer[BUFFER_SIZE];
521
+ int in = 0, out = 0;
522
+
523
+ sem_t empty, full;
524
+ pthread_mutex_t mutex;
525
+
526
+ void* producer(void* arg) {
527
+ int item;
528
+ for (int i = 0; i < 10; i++) {
529
+ item = rand() % 100;
530
+
531
+ sem_wait(&empty);
532
+ pthread_mutex_lock(&mutex);
533
+
534
+ buffer[in] = item;
535
+ printf("Producer produced: %d\\n", item);
536
+ in = (in + 1) % BUFFER_SIZE;
537
+
538
+ pthread_mutex_unlock(&mutex);
539
+ sem_post(&full);
540
+ }
541
+ return NULL;
542
+ }
543
+
544
+ void* consumer(void* arg) {
545
+ int item;
546
+ for (int i = 0; i < 10; i++) {
547
+ sem_wait(&full);
548
+ pthread_mutex_lock(&mutex);
549
+
550
+ item = buffer[out];
551
+ printf("Consumer consumed: %d\\n", item);
552
+ out = (out + 1) % BUFFER_SIZE;
553
+
554
+ pthread_mutex_unlock(&mutex);
555
+ sem_post(&empty);
556
+ }
557
+ return NULL;
558
+ }
559
+
560
+ int main() {
561
+ pthread_t prod_thread, cons_thread;
562
+
563
+ sem_init(&empty, 0, BUFFER_SIZE);
564
+ sem_init(&full, 0, 0);
565
+ pthread_mutex_init(&mutex, NULL);
566
+
567
+ pthread_create(&prod_thread, NULL, producer, NULL);
568
+ pthread_create(&cons_thread, NULL, consumer, NULL);
569
+
570
+ pthread_join(prod_thread, NULL);
571
+ pthread_join(cons_thread, NULL);
572
+
573
+ sem_destroy(&empty);
574
+ sem_destroy(&full);
575
+ pthread_mutex_destroy(&mutex);
576
+
577
+ return 0;
578
+ }""",
579
+ "explanation": "Producer-Consumer problem solution using semaphores for synchronization. Empty semaphore tracks empty slots, full semaphore tracks filled slots.",
580
+ "video_url": "https://www.youtube.com/embed/ltXjAtncKeo"
581
+ }
582
+ ],
583
+ "B.Tech Final Year": [
584
+ {
585
+ "title": "Machine Learning - Linear Regression",
586
+ "problem": "Implement linear regression from scratch in Python",
587
+ "code": """import numpy as np
588
+ import matplotlib.pyplot as plt
589
+
590
+ class LinearRegression:
591
+ def __init__(self, learning_rate=0.01, iterations=1000):
592
+ self.learning_rate = learning_rate
593
+ self.iterations = iterations
594
+ self.weights = None
595
+ self.bias = None
596
+ self.loss_history = []
597
+
598
+ def fit(self, X, y):
599
+ n_samples, n_features = X.shape
600
+ self.weights = np.zeros(n_features)
601
+ self.bias = 0
602
+
603
+ for i in range(self.iterations):
604
+ y_pred = np.dot(X, self.weights) + self.bias
605
+
606
+ # Calculate gradients
607
+ dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
608
+ db = (1/n_samples) * np.sum(y_pred - y)
609
+
610
+ # Update parameters
611
+ self.weights -= self.learning_rate * dw
612
+ self.bias -= self.learning_rate * db
613
+
614
+ # Calculate loss
615
+ loss = np.mean((y_pred - y) ** 2)
616
+ self.loss_history.append(loss)
617
+
618
+ if i % 100 == 0:
619
+ print(f"Iteration {i}, Loss: {loss:.4f}")
620
+
621
+ def predict(self, X):
622
+ return np.dot(X, self.weights) + self.bias
623
+
624
+ # Example usage
625
+ if __name__ == "__main__":
626
+ # Generate sample data
627
+ np.random.seed(42)
628
+ X = 2 * np.random.rand(100, 1)
629
+ y = 4 + 3 * X + np.random.randn(100, 1)
630
+
631
+ # Create and train model
632
+ model = LinearRegression(learning_rate=0.1, iterations=1000)
633
+ model.fit(X, y.ravel())
634
+
635
+ # Make predictions
636
+ X_new = np.array([[0], [2]])
637
+ y_pred = model.predict(X_new)
638
+
639
+ print(f"Predicted for x=0: {y_pred[0]:.2f}")
640
+ print(f"Predicted for x=2: {y_pred[1]:.2f}")
641
+
642
+ # Plot results
643
+ plt.scatter(X, y)
644
+ plt.plot(X_new, y_pred, 'r-')
645
+ plt.title('Linear Regression')
646
+ plt.xlabel('X')
647
+ plt.ylabel('y')
648
+ plt.show()""",
649
+ "explanation": "Linear regression implementation from scratch using gradient descent. Updates weights and bias to minimize mean squared error.",
650
+ "video_url": "https://www.youtube.com/embed/4b4MUYve_U8"
651
+ },
652
+ {
653
+ "title": "Blockchain Implementation",
654
+ "problem": "Simple blockchain implementation in Python",
655
+ "code": """import hashlib
656
+ import time
657
+ import json
658
+
659
+ class Block:
660
+ def __init__(self, index, transactions, timestamp, previous_hash):
661
+ self.index = index
662
+ self.transactions = transactions
663
+ self.timestamp = timestamp
664
+ self.previous_hash = previous_hash
665
+ self.nonce = 0
666
+ self.hash = self.calculate_hash()
667
+
668
+ def calculate_hash(self):
669
+ block_string = json.dumps({
670
+ "index": self.index,
671
+ "transactions": self.transactions,
672
+ "timestamp": self.timestamp,
673
+ "previous_hash": self.previous_hash,
674
+ "nonce": self.nonce
675
+ }, sort_keys=True)
676
+ return hashlib.sha256(block_string.encode()).hexdigest()
677
+
678
+ def mine_block(self, difficulty):
679
+ target = "0" * difficulty
680
+ while self.hash[:difficulty] != target:
681
+ self.nonce += 1
682
+ self.hash = self.calculate_hash()
683
+ print(f"Block mined: {self.hash}")
684
+
685
+ class Blockchain:
686
+ def __init__(self):
687
+ self.chain = [self.create_genesis_block()]
688
+ self.difficulty = 2
689
+ self.pending_transactions = []
690
+
691
+ def create_genesis_block(self):
692
+ return Block(0, ["Genesis Block"], time.time(), "0")
693
+
694
+ def get_latest_block(self):
695
+ return self.chain[-1]
696
+
697
+ def add_transaction(self, transaction):
698
+ self.pending_transactions.append(transaction)
699
+
700
+ def mine_pending_transactions(self):
701
+ block = Block(len(self.chain), self.pending_transactions, time.time(), self.get_latest_block().hash)
702
+ block.mine_block(self.difficulty)
703
+ self.chain.append(block)
704
+ self.pending_transactions = []
705
+
706
+ def is_chain_valid(self):
707
+ for i in range(1, len(self.chain)):
708
+ current_block = self.chain[i]
709
+ previous_block = self.chain[i-1]
710
+
711
+ if current_block.hash != current_block.calculate_hash():
712
+ return False
713
+ if current_block.previous_hash != previous_block.hash:
714
+ return False
715
+ return True
716
+
717
+ # Example usage
718
+ if __name__ == "__main__":
719
+ blockchain = Blockchain()
720
+
721
+ print("Mining block 1...")
722
+ blockchain.add_transaction("Transaction 1")
723
+ blockchain.mine_pending_transactions()
724
+
725
+ print("Mining block 2...")
726
+ blockchain.add_transaction("Transaction 2")
727
+ blockchain.mine_pending_transactions()
728
+
729
+ print(f"Blockchain valid: {blockchain.is_chain_valid()}")
730
+ print(f"Blockchain length: {len(blockchain.chain)}")""",
731
+ "explanation": "Simple blockchain implementation with mining, transaction adding, and chain validation. Uses SHA-256 hashing and proof-of-work.",
732
+ "video_url": "https://www.youtube.com/embed/zVqczFZr124"
733
+ }
734
+ ]
735
+ }
736
+
737
  # ---------------- Opportunities (H/I/S) ----------------
738
  HACKATHONS = [
739
  {"name":"Smart India Hackathon 2025","deadline":"2025-09-30","eligibility":"College Students (All Years)","prizes":"₹5 Lakhs + Incubation","skills":["Programming","Problem Solving"],"url":"https://sih.gov.in","category":"National","level":"B.Tech All Years"},
 
814
 
815
  def create_dashboard_stats(level):
816
  p = load_progress()
817
+ sessions = ROADMAPS.get(