Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import random | |
| from typing import Dict, List | |
| PASS_POINTS = 13 | |
| NUM_EXAM_QUESTIONS = 8 | |
| MAX_QUESTION_SCORE = 3 | |
| class ExamPrepApp: | |
| def __init__(self): | |
| self.flashcards = self._parse_flashcards() | |
| self.all_topics = list(range(len(self.flashcards))) | |
| self.reset() | |
| def reset(self): | |
| random.shuffle(self.all_topics) | |
| self.exam_questions = self.all_topics[:NUM_EXAM_QUESTIONS] | |
| self.answered = {} # qidx: score (0-3) | |
| self.answered_yes = set() | |
| self.answered_no = set() | |
| self.current_index = 0 | |
| self.last_answer = "" | |
| def _parse_flashcards(self) -> List[Dict[str, str]]: | |
| return [ | |
| # 1 | |
| { | |
| "question": "Addresses in computer networks – structure, properties", | |
| "answer": """Addresses are used to identify communicating nodes or resources in a network. | |
| Typically this is some number (IP, MAC, port) or a string (URL, domain). | |
| Addresses should be unique within a network to be a proper ID, but there are exceptions (e.g private IP addresses are not unique, because they are used with port in a SNAT configuration)""" | |
| }, | |
| # 2 | |
| { | |
| "question": "Addressing features in different TCP/IP layers", | |
| "answer": """• Physical - MAC (“physical”) addresses - visible only in the network (Directly connected devices), used by switches | |
| • Internet - IP addresses, visible globally (except private IP addresses) | |
| • sometimes ICMP payload is used (e.g for NAT), used by routers | |
| • Transport - ports, used by operating system, or routers in case of NAT | |
| • Application - paths, URLs, application-specific""" | |
| }, | |
| # 3 | |
| { | |
| "question": "ARP protocol", | |
| "answer": """• Used to discover MAC addresses of devices in the network (IP to MAC mapping) | |
| • Works on OSI data link layer | |
| • Typical procedure: | |
| – One device broadcasts request for MAC address | |
| – Other devices respond with their IP+MAC addresses | |
| • Info is stored in “ARP table” and used when sending next packets""" | |
| }, | |
| # 4 | |
| { | |
| "question": "Basic transmission parameters", | |
| "answer": """• Bandwidth (mbps/gbps - mega/giga bits per second) - how much bits can be sent through a medium | |
| • Throughput - actual amount of data that can be sent, including control, errors, headers etc. | |
| • Propagation delay, RTT = latency | |
| • Jitter | |
| • Error coefficients (lost packet rate, bit error rate)""" | |
| }, | |
| # 5 | |
| { | |
| "question": "Client-server mode of transmission", | |
| "answer": """There is a single host (“server”) which processes “requests” from other hosts (“clients”), the server is typically some authority. | |
| Example: HTTP—server hosts a website, clients make requests. | |
| Advantages: | |
| • Important logic is in a single place (the server) | |
| • Server controls access, permissions, etc. | |
| Disadvantages: | |
| • If server goes down, nothing works | |
| • No privacy (server sees everything) | |
| Contrast with p2p (peer to peer) where every host can process requests from every other host.""" | |
| }, | |
| # 6 | |
| { | |
| "question": "Communication protocol", | |
| "answer": """Protocol specifies how two devices communicate. Defines messages, headers, algorithms, error handling, sessions, data formatting, etc. | |
| Each layer has its own protocols.""" | |
| }, | |
| # 7 | |
| { | |
| "question": "Connection oriented transmission", | |
| "answer": """The host needs to make a reliable “connection” first before it starts to communicate. This is a kind of “session”, lasting until a connection is closed (manually, one of hosts goes offline, etc.). | |
| This mode requires a “listener” socket which accepts connections—used for client-server comms. | |
| Implemented by TCP transport protocol.""" | |
| }, | |
| # 8 | |
| { | |
| "question": "Connectionless transmission mode", | |
| "answer": """No need to make a connection, just send the data to the destination (if a socket is created!). | |
| Natural for p2p communication but works with client-server too (e.g DNS). | |
| Implemented by UDP transport protocol.""" | |
| }, | |
| # 9 | |
| { | |
| "question": "DNS", | |
| "answer": """Domain Name System. The main purpose is to translate human-readable addresses (“domains”) into IP addresses (A/AAAA records) but also stores additional data (MX, TXT, SRV records). | |
| Typically works on UDP port 53. There is also DNS over TLS/HTTPS (for improved security). | |
| Records: | |
| • host IN A 1.1.1.1 — maps host to IPv4 address | |
| • host IN AAAA 2a00:: — maps host to IPv6 address | |
| • alias IN CNAME domain — alias to domain | |
| • IN MX — mail exchange (mail server) | |
| • NS — name server for this domain""" | |
| }, | |
| # 10 | |
| { | |
| "question": "Elements of communication system", | |
| "answer": """• Nodes - send and receive data | |
| • Medium - the “space” through which data is sent, e.g. cables/wires, EM field (radio waves for wireless) | |
| • Protocol - a way to encode data so it is efficiently transmitted and understood by all nodes""" | |
| }, | |
| # 11 | |
| { | |
| "question": "Ethernet", | |
| "answer": """Specifies physical and data-link layer for wired communication (IEEE 802.3). Uses 48-bit “MAC addresses” to identify interfaces. | |
| Variants wrt speed: 10BASE-T (first), 100BASE-T (“Fast Ethernet”), 1GBASE-T, 10GBASE-T, 25GBASE-T, 50GBASE-T, 100GBASE-X. | |
| Autoconfigures speed, duplex/half-duplex. | |
| Features collision detection (CSMA/CD) in half-duplex.""" | |
| }, | |
| # 12 | |
| { | |
| "question": "Functions of communication protocols", | |
| "answer": """• Data formatting | |
| • Error detection and correction | |
| • Flow control | |
| • Congestion control | |
| • Session/connection management | |
| • Addressing | |
| • Security | |
| • Interoperability""" | |
| }, | |
| # 13 | |
| { | |
| "question": "ICMP", | |
| "answer": """Internet Control Message Protocol, used to send status/control messages between hosts. | |
| Example messages: | |
| • Echo request/Echo reply - used for ping | |
| • Error codes: host unreachable, redirect, ttl exceeded, etc.""" | |
| }, | |
| # 14 | |
| { | |
| "question": "IEEE 802.11 standards", | |
| "answer": """WiFi | |
| • 802.11a/h/n: 5GHz | |
| • 802.11b/g/h/n: 2.4GHz | |
| • ac, ax are newer/faster standards""" | |
| }, | |
| # 15 | |
| { | |
| "question": "IPv4 address", | |
| "answer": """32-bit address used in network/Internet layer. Written in 4 decimal “octets”, e.g. 123.123.123.123. | |
| Netmasks, e.g. 1.1.1.0/24, are used for network ranges. First address (network) and last (broadcast) are special; usable IP range is in between (e.g. 254 hosts for /24). | |
| Classes: A (0.0.0.0-127.255.255.255), B (128.0.0.0-191.255.255.255), C (192.0.0.0-223.255.255.255) | |
| Special addresses: multicast, broadcast, 127.0.0.0/8 (loopback), 169.254.0.0/16 (link-local), 10.0.0.0/8 etc. (private)""" | |
| }, | |
| # 16 | |
| { | |
| "question": "IPv4 and IPv6 comparison", | |
| "answer": """IPv4: 32-bit address space, exhausted, more complex header, supports fragmentation, unicast/broadcast/multicast, assigned externally, notation: xxx.xxx.xxx.xxx | |
| IPv6: 128-bit address space, simpler header, never fragmented by routers, supports unicast/multicast/anycast, can be assigned automatically, notation: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx""" | |
| }, | |
| # 17 | |
| { | |
| "question": "IPv4 protocol", | |
| "answer": """Used to address hosts in the entire network. IPv4 packet contains (not in order): | |
| • source IP address | |
| • destination IP address | |
| • transport protocol ID | |
| • stuff for fragmentation | |
| • TTL | |
| • flags | |
| • checksum | |
| • data | |
| Supports fragmentation if packet doesn’t fit MTU. Sequence index is used.""" | |
| }, | |
| # 18 | |
| { | |
| "question": "IPv6 address", | |
| "answer": """128 bit address, successor to IPv4. | |
| Notation: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx (hexadecimal) | |
| • Zeros can be skipped using :: (only once) | |
| • Leading zeros can be skipped | |
| Assignment: split into network (64 bits) and host (64 bits); host part can be auto-assigned (SLAAC). | |
| Special addresses: | |
| • :: - indefinite | |
| • ::1 - loopback | |
| • ff00::/8 - multicast | |
| • fe80::/10 - link-local | |
| • fec0::/10 - site-local""" | |
| }, | |
| # 19 | |
| { | |
| "question": "IPv6 protocol", | |
| "answer": """Header is simpler than IPv4: | |
| • source address | |
| • destination address | |
| • priority | |
| • TTL | |
| • flags | |
| • next header | |
| • data | |
| No fragmentation, no checksum. Extensions use “next header” field.""" | |
| }, | |
| # 20 | |
| { | |
| "question": "LAN", | |
| "answer": """Local Area Network. Used within a single organization or household. Typically uses private IP addresses. Typical layer 2 protocols: Ethernet, Wi-Fi.""" | |
| }, | |
| # 21 | |
| { | |
| "question": "MAC address", | |
| "answer": """48 bit physical address. Used in data link layer (e.g. Ethernet). First 3 bytes identify manufacturer. Written as aa:bb:cc:dd:ee:ff | |
| Special: 00:00:00:00:00:00 (null), ff:ff:ff:ff:ff:ff (broadcast)""" | |
| }, | |
| # 22 | |
| { | |
| "question": "MAN", | |
| "answer": """Metropolitan Area Network. Typical range: a city. E.g. a research network connecting multiple LANs in a city.""" | |
| }, | |
| # 23 | |
| { | |
| "question": "Multilayer transmission in computer networks", | |
| "answer": """Layers separate responsibilities (abstraction), make protocol changes easier. Each layer serves a function and communicates only with adjacent layers. | |
| Changing a protocol in a layer (e.g. IPv6 vs IPv4) can cause compatibility issues. | |
| Protocols are stacked: Ethernet-IPv4-TCP-HTTP, WiFi-IPv6-UDP-DNS, etc.""" | |
| }, | |
| # 24 | |
| { | |
| "question": "NAT", | |
| "answer": """Network Address Translation. Used to translate addresses between networks. | |
| Allows Internet access for computers with private addresses. Improves security and conserves public IPs. | |
| • Source NAT - router translates private IPs into external address for outbound packets, uses TCP/UDP ports and a translation table | |
| • Destination NAT - router translates incoming messages to internal IP+port (port forwarding)""" | |
| }, | |
| # 25 | |
| { | |
| "question": "Network topology", | |
| "answer": """Defines how nodes are connected (logically) in a network. | |
| • Star - central node (switch), most common for LANs | |
| • Tree - nested star, for big LANs | |
| • Partial mesh - topology of public Internet (WAN), provides redundancy | |
| • Mesh - everyone connected to everyone (unusual for wired) | |
| • Bus - all devices connected to a single cable | |
| • Ring - computers connected in a ring""" | |
| }, | |
| # 26 | |
| { | |
| "question": "Networks classification (range of transmission)", | |
| "answer": """• BAN (bodynet), PAN (personal), NAN (near-me), LAN (local), CAN (campus), MAN (metropolitan), WAN (wide) | |
| Lower range networks use lower range mediums. | |
| LAN for resource sharing, MANs mostly research, WAN is large area (mostly routers).""" | |
| }, | |
| # 27 | |
| { | |
| "question": "Ports in transport layer", | |
| "answer": """Ports specify to which application the data should be sent on a host. | |
| Allows hosting multiple services on one server, or multiple clients. | |
| Ports are 16-bit numbers (1-65535) for both TCP and UDP. 1-1024 are “well known ports”. | |
| When sending, destination port is provided, source port is randomized by OS.""" | |
| }, | |
| # 28 | |
| { | |
| "question": "Router – functions, structure", | |
| "answer": """Routers select routes between networks (layer 3). Use routing tables (static/manual or dynamic). | |
| Main tasks: | |
| • Forwarding packets | |
| • Maintaining/generating routing tables (BGP, OSPF, RIP) | |
| Additional tasks: filtering (firewall), NAT, switching, DHCP, DNS, etc.""" | |
| }, | |
| # 29 | |
| { | |
| "question": "Routing protocols – examples", | |
| "answer": """Interior (internal to AS): RIP, OSPF, IS-IS | |
| Exterior (between AS): EGP (old), BGP (current)""" | |
| }, | |
| # 30 | |
| { | |
| "question": "Routing protocols – classification", | |
| "answer": """• Interior/Exterior | |
| • Algorithm: | |
| - Distance vector: each router shares routing table with neighbors (RIP) | |
| - Link-state: each router builds a connectivity map for the entire network (OSPF, IS-IS)""" | |
| }, | |
| # 31 | |
| { | |
| "question": "Socket – definition, applications", | |
| "answer": """Endpoint in operating systems for communication (send/receive data). Identified by IP + port. | |
| Stores protocol state (connected? listening? etc.). | |
| Examples: HTTP server socket 1.1.1.1:80; client creates a TCP socket at random port, connects to server. UDP: server binds 1.1.1.1:53, client sends from random port.""" | |
| }, | |
| # 32 | |
| { | |
| "question": "Switch – functions, applications, structure", | |
| "answer": """Physical device for extending IP networks without collisions (unlike hubs). Operates at data link layer. | |
| Remembers MAC addresses on its ports (MAC table), passes frames only to relevant ports. | |
| Professional switches: VLAN, STP, stacking, routing, etc.""" | |
| }, | |
| # 33 | |
| { | |
| "question": "TCP and UDP comparison", | |
| "answer": """TCP: | |
| • Requires connection | |
| • Ensures all data arrives in order | |
| • Streaming (app layer sees stream of data) | |
| • Complex header (retransmission) | |
| • Complex implementation (for reliability) | |
| UDP: | |
| • Connectionless | |
| • No guarantee of order or arrival | |
| • App layer sees discrete datagrams | |
| • Simple header | |
| Both: | |
| • Include a checksum (data arrives, it is correct)""" | |
| }, | |
| # 34 | |
| { | |
| "question": "TCP/IP layers and their functions", | |
| "answer": """• Physical: data encoding, communication within a network (Ethernet, WiFi, Bluetooth, USB) | |
| • Internet: routing, comm between networks, logical addressing (IPv4, IPv6) | |
| • Transport: data integrity/reliability, connection management (TCP, UDP) | |
| • Application: app-specific protocols (HTTP, FTP, SSH, etc)""" | |
| }, | |
| # 35 | |
| { | |
| "question": "TCP/IP stack of protocols – layers, exemplary protocols", | |
| "answer": """Physical: Ethernet, WiFi, Bluetooth, USB | |
| Internet: IPv4, IPv6 | |
| Transport: TCP, UDP | |
| Application: HTTP, FTP, SSH, many others""" | |
| }, | |
| # 36 | |
| { | |
| "question": "Wired media – types, features", | |
| "answer": """Cable structure: | |
| • Coaxial cables - single copper wire with insulation/shielding (old, still used) | |
| • Twisted pair cables - copper strands in pairs, 8P8C connectors, various shielding, used in LANs | |
| • Categories: 5e-1G, 6-10G, 7, 8-40Gbps | |
| • Optical fiber - uses light (infrared), low latency, no EM interference, long range (single/multi mode, various connectors)""" | |
| }, | |
| # 37 | |
| { | |
| "question": "Wireless and wired media comparison", | |
| "answer": """Wireless: | |
| • Easier and faster to deploy (no cables) | |
| • Good for ad-hoc networks | |
| • Low speed and reliability (interference) | |
| • High latency | |
| • Lower security | |
| Wired: | |
| • Requires cables | |
| • Good for permanent networks | |
| • Higher speed/reliability, low latency, higher security""" | |
| }, | |
| # 38 | |
| { | |
| "question": "Wireless media – applications, bands, features", | |
| "answer": """Applications: | |
| • Temporary networks (portable devices, personal area, public hotspots, satellite, IoT) | |
| Bands: | |
| • Wi-Fi has 11-14 channels around 2.4 GHz, more at 5 GHz | |
| • Also longer wavelength for satellite comms | |
| Features: | |
| • Short range (Wi-Fi), longer for satellite, prone to interference""" | |
| }, | |
| # 39 | |
| { | |
| "question": "Wireless transmission – exemplary protocols", | |
| "answer": """• WiFi (802.11) | |
| • Bluetooth | |
| • ZigBee | |
| • Mobile: GSM, LTE, 5G | |
| • Satellite: DVB-S""" | |
| }, | |
| # 40 | |
| { | |
| "question": "Wireless transmission characterization", | |
| "answer": """Range, bandwidth, interference, security.""" | |
| } | |
| ] | |
| def get_current_card(self) -> Dict[str, str]: | |
| qidx = self.exam_questions[self.current_index] | |
| return self.flashcards[qidx] | |
| def show_question(self): | |
| card = self.get_current_card() | |
| answer_to_show = self.last_answer if self.last_answer else "" | |
| return ( | |
| card["question"], | |
| answer_to_show, | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| self.get_stats(), | |
| gr.update(visible=False), | |
| self.get_pass_probability() | |
| ) | |
| def show_answer(self): | |
| card = self.get_current_card() | |
| return ( | |
| card["question"], | |
| card["answer"], | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=True), | |
| self.get_stats(), | |
| gr.update(visible=True), | |
| self.get_pass_probability() | |
| ) | |
| def handle_yes(self, score): | |
| qidx = self.exam_questions[self.current_index] | |
| self.answered_yes.add(qidx) | |
| self.answered[qidx] = int(score) | |
| self.last_answer = self.flashcards[qidx]["answer"] | |
| if qidx in self.answered_no: | |
| self.answered_no.remove(qidx) | |
| return self.goto_next() | |
| def handle_no(self, score): | |
| qidx = self.exam_questions[self.current_index] | |
| self.answered_no.add(qidx) | |
| self.answered[qidx] = int(score) | |
| self.last_answer = self.flashcards[qidx]["answer"] | |
| if qidx in self.answered_yes: | |
| self.answered_yes.remove(qidx) | |
| return self.goto_next() | |
| def goto_next(self): | |
| n = len(self.exam_questions) | |
| for _ in range(n): | |
| self.current_index = (self.current_index + 1) % n | |
| qidx = self.exam_questions[self.current_index] | |
| if qidx not in self.answered: | |
| return self.show_question() | |
| return self.show_summary() | |
| def show_summary(self): | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| correct = len(self.answered_yes) | |
| wrong = len(self.answered_no) | |
| details = "\n\n".join([ | |
| f"**Q{i+1}: {self.flashcards[q]['question']}**\n" | |
| f"**A:** {self.flashcards[q]['answer']}\n" | |
| f"**Score:** {self.answered.get(q,0)}/3" | |
| for i, q in enumerate(self.exam_questions) | |
| ]) | |
| status = "✅ You PASSED!" if total >= PASS_POINTS else "❌ You did NOT pass." | |
| summary = ( | |
| f"**Your Score:** {total}/24\n" | |
| f"**Result:** {status}\n" | |
| f"✅ Remembered: {correct} | ❌ Not remembered: {wrong}\n\n" | |
| f"**Full breakdown:**\n\n{details}" | |
| ) | |
| return ("Exam Finished!", summary, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), summary, gr.update(visible=False), self.get_pass_probability()) | |
| def get_stats(self): | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| correct = len(self.answered_yes) | |
| wrong = len(self.answered_no) | |
| return ( | |
| f"✅ Remembered: {correct} | ❌ Not remembered: {wrong} | " | |
| f"🎯 Your Score: {total}/24 | " | |
| f"Question {len(self.answered)+1} of {NUM_EXAM_QUESTIONS}" | |
| ) | |
| def get_pass_probability(self): | |
| if len(self.answered) == NUM_EXAM_QUESTIONS: | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| return f"🟢 Probability to pass: {'100%' if total >= PASS_POINTS else '0%'}" | |
| current_score = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| remaining = NUM_EXAM_QUESTIONS - len(self.answered) | |
| ways = 0 | |
| passing_ways = 0 | |
| def dfs(depth, acc): | |
| nonlocal ways, passing_ways | |
| if depth == 0: | |
| ways += 1 | |
| if acc + current_score >= PASS_POINTS: | |
| passing_ways += 1 | |
| return | |
| for s in range(0, MAX_QUESTION_SCORE + 1): | |
| dfs(depth-1, acc+s) | |
| dfs(remaining, 0) | |
| prob = (passing_ways / ways) * 100 if ways > 0 else 0 | |
| return f"🟢 Probability to pass (based on possible scores): {prob:.1f}%" | |
| def reset_exam(self): | |
| self.reset() | |
| return self.show_question() | |
| # Instantiate app | |
| app = ExamPrepApp() | |
| with gr.Blocks(title="Network Exam Simulator", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 📝 Computer Networks Final Exam Simulator") | |
| gr.Markdown(""" | |
| - **Pattern:** 8 open questions randomly drawn from the official list. | |
| - **Scoring:** 0-3 points per question. Passing = 13 points or more.<br> | |
| - Mark yourself for each answer and track your passing probability live! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| question = gr.Textbox(label="❓ Question", interactive=False, lines=3) | |
| answer = gr.Textbox(label="💡 Answer (for previous question)", interactive=False, visible=True, lines=8) | |
| with gr.Row(): | |
| show_answer_btn = gr.Button("👀 Show Answer", variant="primary") | |
| yes_btn = gr.Button("✅ I remember this", visible=False) | |
| no_btn = gr.Button("❌ I don't remember", visible=False) | |
| with gr.Row(): | |
| score_input = gr.Radio(choices=[0,1,2,3], value=0, label="How many points would you get for this question?", interactive=True, visible=False) | |
| with gr.Column(scale=1): | |
| stats = gr.Markdown(app.get_stats()) | |
| prob = gr.Markdown(app.get_pass_probability()) | |
| reset_btn = gr.Button("♻️ Start New Exam", variant="stop") | |
| show_answer_btn.click( | |
| fn=app.show_answer, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| yes_btn.click( | |
| fn=app.handle_yes, | |
| inputs=[score_input], | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| no_btn.click( | |
| fn=app.handle_no, | |
| inputs=[score_input], | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| reset_btn.click( | |
| fn=app.reset_exam, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| demo.load( | |
| fn=app.show_question, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |