Check our Programming Sample Library

Check our code samples curated by our expert engineers at "DomyCodingHomework". Toggle between "Freshman" and "Senior" level logic to see how our engineers adapt their coding style to match your academic year.

Verified Code Repository / Sample Projects

"Browse our library of mid-to-complex code samples. You can use these code blocks to understand our logic, verify our coding style, or simply learn how to solve difficult problems." Toggle the switch to see how we adapt the code logic from "Freshman" (simple, explicit, readable) to "Senior" (optimized, safe, professional).

Parse 5GB Log File for Errors

Python File I/O Memory Management
The Challenge: Professor can ask to Parse a massive server log file to find "ERROR" lines without crashing the RAM (MemoryOverflow).
Mid-Complex Task: Efficient string handling and memory safety.

Note : Please use the code below only for academic research and learning purpose. DMCH never encourages students to do academic cheating.
# Student Level: Freshman / Sophomore # Logic: Reads the whole file into a list. Simple, but risky for large files. def find_errors(filename): # Open the file in read mode file = open(filename, "r") # Read ALL lines into memory at once (Risk: RAM Crash on 5GB file) all_lines = file.readlines() error_lines = [] # Loop through every line one by one for line in all_lines: # Check if the word "ERROR" is in the line if "ERROR" in line: error_lines.append(line) file.close() return error_lines # Running the function results = find_errors("server_logs.txt") print("Found errors:", len(results))
# Student Level: Senior / Expert # Logic: Uses Generators (yield) to stream the file line-by-line. # Memory Usage: Constant O(1), regardless of file size. import os def stream_error_logs(file_path): """Generator that yields error lines one by one to save memory.""" if not os.path.exists(file_path): raise FileNotFoundError(f"Log file not found: {file_path}") # Context Manager handles closing automatically with open(file_path, 'r', encoding='utf-8') as f: for line in f: # Optimized check & strip whitespace if 'ERROR' in line: yield line.strip() # Consumption of the generator try: error_count = 0 for err in stream_error_logs("server_logs.txt"): # Process logic here (e.g., send alert) error_count += 1 print(f"Processing complete. Total Errors: {error_count}") except Exception as e: print(f"Critical Failure: {e}")

Flatten Deeply Nested JSON

Python Recursion Algorithms
The Challenge: Convert a complex, multi-layered JSON object (nested dictionaries) into a flat key-value pair for CSV export.
Mid-Complex Task: Handling unknown depth recursion.
# Student Level: Freshman # Logic: Hardcoded loops. Logic breaks if JSON is deeper than 3 levels. # Risk: Not scalable. Will crash on deeper data. data = { "user": { "name": "Alex", "address": { "city": "New York", "geo": { "lat": 40.71, "long": -74.00 } } } } flat_data = {} # Manually looping through known layers for key, value in data.items(): if isinstance(value, dict): for k2, v2 in value.items(): if isinstance(v2, dict): for k3, v3 in v2.items(): # Hardcoded key combining flat_data[key + "_" + k2 + "_" + k3] = v3 else: flat_data[key + "_" + k2] = v2 else: flat_data[key] = value print(flat_data)
# Student Level: Senior / Expert # Logic: Recursive generator. Handles infinite depth. # Scalable: Works on any JSON structure. def flatten_json(y): out = {} def flatten(x, name=''): # Check if item is a dictionary if type(x) is dict: for a in x: # Recursively call flatten on the child flatten(x[a], name + a + '_') else: # Base case: It's a value, strip trailing underscore out[name[:-1]] = x flatten(y) return out # Usage print(flatten_json(data))

High-Speed Image Downloader

Python Threading Network I/O
The Challenge: Download 100 images from URLs. Doing it one-by-one is too slow.
Mid-Complex Task: Using ThreadPoolExecutor for parallel processing.
# Student Level: Freshman # Logic: Sequential Loop. # Speed: Slow. Waits for Image 1 to finish before starting Image 2. import requests import time urls = ["http://img1.jpg", "http://img2.jpg", "http://img3.jpg"] def download_image(url): print(f"Downloading {url}...") r = requests.get(url) # simulate saving file... time.sleep(1) # Single-Threaded Loop start = time.time() for url in urls: download_image(url) print(f"Finished in {time.time()-start} seconds")
# Student Level: Senior # Logic: ThreadPoolExecutor. # Speed: Fast. Downloads 5 images simultaneously. import concurrent.futures import requests def download_image(url): try: r = requests.get(url, timeout=5) return f"{url} Done" except Exception as e: return f"{url} Failed" # Multi-Threaded Execution with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: # Map the function to the list of URLs results = executor.map(download_image, urls) for result in results: print(result)

Group & Aggregate Sales Data

Python Pandas Big Data
The Challenge: Calculate the total sales revenue per region from a dataset of 1 million rows.
Mid-Complex Task: Vectorized Operations vs Loops.
# Student Level: Freshman # Logic: Iterating rows manually. # Performance: Very Slow (Minutes for 1M rows). sales_data = [ {"region": "North", "amount": 100}, {"region": "South", "amount": 150}, # ... imagine 1 million rows ] region_totals = {} for row in sales_data: r = row["region"] amt = row["amount"] if r in region_totals: region_totals[r] += amt else: region_totals[r] = amt print(region_totals)
# Student Level: Senior / Data Scientist # Logic: Pandas 'groupby' (C-optimized backend). # Performance: Instant (Milliseconds). import pandas as pd # Load data into DataFrame df = pd.DataFrame(sales_data) # One-liner to group and sum # Vectorization applies the math to the whole column at once totals = df.groupby('region')['amount'].sum() print(totals)

Secure Database Query (Login)

Python SQL Cybersecurity
The Challenge: Check user credentials against a database without getting hacked.
Mid-Complex Task: Preventing SQL Injection attacks.
# Student Level: Freshman # Logic: F-String formatting directly into query. # Risk: CRITICAL. Vulnerable to SQL Injection (e.g., user inputs "' OR 1=1 --") def check_login_unsafe(cursor, username, password): # Directly injecting input strings query = f"SELECT * FROM users WHERE user='{username}' AND pass='{password}'" cursor.execute(query) return cursor.fetchone()
# Student Level: Senior / Security Engineer # Logic: Parameterized Queries (Prepared Statements). # Safety: 100% Safe. The DB engine treats input as data, not code. def check_login_safe(cursor, username, password): # Use '?' placeholder (SQLite) or %s (Postgres) query = "SELECT * FROM users WHERE user=? AND pass=?" # Pass variables as a separate tuple cursor.execute(query, (username, password)) return cursor.fetchone()
```

Multi-Threaded Bank Transfer

Java Threading Concurrency
The Challenge: Transfer money between two bank accounts safely when multiple threads are accessing them (Deadlock Prevention).
Mid-Complex Task: Avoiding Race Conditions.
// Student Level: Freshman // Logic: Using basic 'synchronized' keyword on the method. // Risk: Low performance, potential deadlocks if A calls B and B calls A. public class BankAccount { private double balance; public BankAccount(double balance) { this.balance = balance; } // Synchronized prevents two people from withdrawing at once public synchronized void withdraw(double amount) { if (balance >= amount) { balance = balance - amount; } } public synchronized void deposit(double amount) { balance = balance + amount; } // Simple transfer method public void transfer(BankAccount to, double amount) { this.withdraw(amount); to.deposit(amount); } }
// Student Level: Senior / Systems Architect // Logic: Using ReentrantLock with tryLock() to prevent Deadlocks. // This allows threads to "give up" if the lock is busy, rather than freezing. import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.TimeUnit; public class SafeAccount { private double balance; private final Lock lock = new ReentrantLock(); public boolean transfer(SafeAccount to, double amount) throws InterruptedException { // Try to lock both accounts to ensure atomicity if (this.lock.tryLock(1, TimeUnit.SECONDS)) { try { if (to.lock.tryLock(1, TimeUnit.SECONDS)) { try { if (this.balance >= amount) { this.balance -= amount; to.balance += amount; return true; // Success } } finally { to.lock.unlock(); // Always release lock B } } } finally { this.lock.unlock(); // Always release lock A } } return false; // Failed to acquire locks } }

High-Speed User Lookup

Java Data Structures Big-O Analysis
The Challenge: Find a specific user by ID inside a database of 1 million users.
Mid-Complex Task: Optimizing Time Complexity from O(n) to O(1).
// Student Level: Freshman // Logic: Using an ArrayList and iterating through it. // Performance: O(n) - Slow. If user is at the end of 1M records, it loops 1M times. import java.util.ArrayList; public class UserSearch { public User findUserById(ArrayList<User> users, int targetId) { // Loop through every single user for (User u : users) { if (u.getId() == targetId) { return u; // Found it! } } return null; // Not found } }
// Student Level: Senior / Backend Eng // Logic: Using a HashMap for constant time lookup. // Performance: O(1) - Instant. Finds the user in 1 step, even with 10M records. import java.util.HashMap; import java.util.Map; public class UserSearchOptimized { // Pre-process list into a Map for fast access private Map<Integer, User> userMap = new HashMap<>(); public void loadUsers(List<User> users) { for (User u : users) { userMap.put(u.getId(), u); } } public User getUser(int id) { // Instant hash lookup return userMap.get(id); } }

Filter & Transform Data

Java 8+ Functional Streams
The Challenge: Take a list of Products, find the ones in stock, apply a 20% discount, and extract their names.
Mid-Complex Task: Declarative programming vs Imperative loops.
// Student Level: Freshman // Logic: Multiple nested IF statements inside a For-Loop. // Readability: Cluttered "Spaghetti Code". public List<String> getDiscountedItems(List<Product> items) { List<String> result = new ArrayList<>(); for (int i = 0; i < items.size(); i++) { Product p = items.get(i); // Check if in stock if (p.isInStock()) { // Apply logic double newPrice = p.getPrice() * 0.8; p.setPrice(newPrice); // Add name to list result.add(p.getName()); } } return result; }
// Student Level: Senior / Java Developer // Logic: Java Stream API (Functional Programming). // Readability: Clean, declarative, and easily parallelizable. public List<String> getDiscountedItems(List<Product> items) { return items.stream() .filter(Product::isInStock) // 1. Filter .peek(p -> p.setPrice(p.getPrice() * 0.8)) // 2. Apply logic .map(Product::getName) // 3. Transform to String .collect(Collectors.toList()); // 4. Collect results }

Thread-Safe Database Connector

Java Design Patterns Singleton
The Challenge: Ensure only ONE instance of the Database Connection exists across the entire application (Singleton Pattern).
Mid-Complex Task: Handling Multi-threaded initialization safely.
// Student Level: Freshman // Logic: Basic Lazy Initialization. // Risk: NOT Thread Safe. Two threads could create two instances at once. public class DBConnection { private static DBConnection instance; private DBConnection() { // Connect to DB... } public static DBConnection getInstance() { if (instance == null) { // If Thread A pauses here, Thread B enters and makes a duplicate. instance = new DBConnection(); } return instance; } }
// Student Level: Senior / Architect // Logic: "Double-Checked Locking" with volatile keyword. // Safety: 100% Thread Safe and Performant. public class DBConnection { // 'volatile' ensures atomic reads across CPU cores private static volatile DBConnection instance; private DBConnection() {} public static DBConnection getInstance() { if (instance == null) { // Lock ONLY the creation block synchronized (DBConnection.class) { // Double check inside the lock if (instance == null) { instance = new DBConnection(); } } } return instance; } }

Safe File Reading

Java I/O Clean Code
The Challenge: Read a text file and ensure the OS resource is closed even if the program crashes halfway through.
Mid-Complex Task: Try-With-Resources (AutoCloseable).
// Student Level: Freshman // Logic: Traditional try-catch-finally block. // Issue: Verbose, messy, and easy to forget the 'close()' call. public void readFileOldWay(String path) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } finally { // Must manually close logic in 'finally' block try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
// Student Level: Senior // Logic: Try-With-Resources syntax (Java 7+). // Safety: Automatically calls .close() when block exits. public void readFileSafe(String path) { // Resource declared inside parentheses is auto-managed try (BufferedReader br = new BufferedReader(new FileReader(path))) { System.out.println(br.readLine()); } catch (IOException e) { // No finally block needed! e.printStackTrace(); } }
```

Custom Smart Pointer Class

C++ Memory Management Templates
The Challenge: Manage heap memory manually without causing Memory Leaks (Segfaults).
Mid-Complex Task: Implementing RAII (Resource Acquisition Is Initialization).
// Student Level: Freshman // Logic: Using raw pointers and manually deleting them. // Risk: High. If an error occurs before 'delete', memory leaks forever. class MyClass { public: void sayHello() { cout << "Hello!" << endl; } }; void usePointer() { // Allocate memory on the heap MyClass* ptr = new MyClass(); ptr->sayHello(); // Must remember to delete! delete ptr; // DANGER: If we use 'ptr' again here, it's a "Dangling Pointer" }
// Student Level: Senior / Systems Eng // Logic: Implementing a custom Smart Pointer using Templates. // Uses Destructor logic to auto-delete memory when it goes out of scope. template <typename T> class SmartPtr { private: T* ptr; public: // Constructor: Takes ownership of the pointer explicit SmartPtr(T* p = nullptr) : ptr(p) {} // Destructor: Automatically cleans up memory ~SmartPtr() { if (ptr) { delete ptr; std::cout << "Auto-cleaned memory." << std::endl; } } // Overloading operators to act like a real pointer T& operator*() { return *ptr; } T* operator->() { return ptr; } }; void useSmartPointer() { // No 'delete' needed! It cleans itself up when function ends. SmartPtr sp(new MyClass()); sp->sayHello(); }

Power of 2 Checker

C++ Bit Manipulation Optimization
The Challenge: Check if a number is a Power of Two (2, 4, 8, 16...) instantly.
Mid-Complex Task: Replacing Loops with CPU Bitwise logic.
// Student Level: Freshman // Logic: Iterative Loop. // Performance: O(log n) - It has to divide repeatedly. Slower. bool isPowerOfTwo(int n) { if (n <= 0) return false; // Keep dividing by 2 until we hit 1 or an odd number while (n % 2 == 0) { n /= 2; } // If we reached 1, it was a power of 2 return n == 1; }
// Student Level: Senior / Embedded Systems // Logic: Bitwise AND. // Performance: O(1) - Executed in a single CPU cycle. bool isPowerOfTwo(int n) { // Powers of 2 have exactly one bit set (e.g., 1000). // Subtracting 1 flips bits (e.g., 0111). // ANDing them results in 0. return (n > 0) && ((n & (n - 1)) == 0); }

Thread-Safe Counter

C++11 Mutex Concurrency
The Challenge: Increment a global counter from 10 different threads without corrupting the value (Race Condition).
Mid-Complex Task: Using Locks effectively.
// Student Level: Freshman // Logic: No protection. // Risk: Data Race. The final count will be wrong/random. int counter = 0; void incrementCounter() { // If two threads read '0' at the same time, they both write '1'. // We lose counts! counter++; }
// Student Level: Senior // Logic: Using std::lock_guard (RAII pattern). // Safety: Automatically unlocks even if an error occurs. #include <mutex> int counter = 0; std::mutex mtx; // The lock void incrementCounter() { // Lock is acquired when 'guard' is created std::lock_guard<std::mutex> guard(mtx); counter++; // Lock is automatically released here when 'guard' is destroyed }

Vector Memory Pre-Allocation

C++ STL Heap Optimization
The Challenge: Fill a vector with 1 million integers.
Mid-Complex Task: Preventing expensive memory re-allocations.
// Student Level: Freshman // Logic: Just push_back in a loop. // Performance: Slow. Vector has to resize and copy data ~20 times. void fillVector() { std::vector<int> v; for (int i = 0; i < 1000000; i++) { // Every time capacity is exceeded, C++ copies the WHOLE array // to a new memory location. Expensive! v.push_back(i); } }
// Student Level: Senior // Logic: Using .reserve() to allocate memory once. // Performance: Fast. Zero resizing/copying occurs. void fillVector() { std::vector<int> v; // Request memory for 1M ints upfront v.reserve(1000000); for (int i = 0; i < 1000000; i++) { // Memory is already there, just filling it. v.push_back(i); } }

Safe String Copying

C / C++ Security Buffer Overflow
The Challenge: Copy user input into a fixed-size buffer.
Mid-Complex Task: Preventing "Buffer Overflow" exploits.
// Student Level: Freshman // Logic: Using strcpy (C-style). // Risk: CRITICAL. If input is longer than 10 chars, it corrupts memory. void copyInput(char* input) { char buffer[10]; // DANGER: Does not check size! // Hacker can overwrite adjacent memory (Stack Smashing) strcpy(buffer, input); }
// Student Level: Senior / Security Eng // Logic: Using strncpy or std::string. // Safety: Limits copy to buffer size. void copyInput(const char* input) { char buffer[10]; // Safe Copy: Only copy max 9 chars + null terminator // sizeof(buffer)-1 ensures we don't overflow strncpy(buffer, input, sizeof(buffer) - 1); // Manually ensure null termination buffer[sizeof(buffer) - 1] = '\0'; }
```

Async API Fetcher with Retry

JavaScript Promises Async/Await
The Challenge: Fetch data from an unstable API. If it fails, retry 3 times before giving up.
Mid-Complex Task: Handling asynchronous errors and exponential backoff.
// Student Level: Freshman // Logic: Basic fetch with .then(). No retry logic. // Risk: If the internet blips for 1ms, the whole app crashes. function getData() { // Simple fetch request fetch('https://api.example.com/data') .then(response => { if (response.ok) { return response.json(); } }) .then(data => { console.log("Got data:", data); }) .catch(error => { // We just log the error and give up console.error("It failed.", error); }); }
// Student Level: Senior / Full-Stack Dev // Logic: Async/Await with a recursive Retry pattern. // Robustness: Tries 3 times before throwing an error. async function fetchWithRetry(url, retries = 3) { try { // Await the fetch response const response = await fetch(url); if (!response.ok) throw new Error(`Server error: ${response.status}`); return await response.json(); } catch (error) { // Check if we have retries left if (retries > 0) { console.warn(`Failed. Retrying... (${retries} left)`); // Wait 1 second before retrying (Backoff) await new Promise(r => setTimeout(r, 1000)); // Recursively call function again return fetchWithRetry(url, retries - 1); } throw error; // Give up after 3 tries } }

React Global State (Theme Switcher)

React JS Context API Scalability
The Challenge: Pass a "Dark Mode" setting from the top App component down to a deeply nested Button.
Mid-Complex Task: Avoiding "Prop Drilling" hell.
// Student Level: Freshman // Logic: "Prop Drilling". Passing data through components that don't need it. // Issue: If we move the button, we have to rewrite 4 files. function App() { const [theme, setTheme] = useState("dark"); // Passing theme down... return <Layout theme={theme} />; } function Layout({ theme }) { // Passing theme down again... return <Header theme={theme} />; } function Header({ theme }) { // And again... return <UserInfo theme={theme} />; } function UserInfo({ theme }) { // Finally using it here return <div className={theme}>User Profile</div>; }
// Student Level: Senior / Frontend Lead // Logic: Context API. // Benefit: Data teleports directly to the component that needs it. // 1. Create Context const ThemeContext = createContext("light"); function App() { return ( <ThemeContext.Provider value="dark"> <Layout /> // No props passed here! </ThemeContext.Provider> ); } // ... skip intermediate components ... function UserInfo() { // 2. Consume Context directly const theme = useContext(ThemeContext); return <div className={theme}>User Profile</div>; }

Displaying User Comments

JavaScript DOM Security
The Challenge: Render a user's comment on a blog post.
Mid-Complex Task: Preventing Cross-Site Scripting (XSS) attacks.
// Student Level: Freshman // Logic: Using innerHTML. // Risk: CRITICAL. If user types "<script>stealCookies()</script>", it runs. function displayComment(userText) { const commentBox = document.getElementById('box'); // DANGER: Direct injection of HTML strings commentBox.innerHTML = "<p>" + userText + "</p>"; }
// Student Level: Senior / Security Eng // Logic: Using textContent or CreateElement. // Safety: Browser treats input as raw text, never as executable code. function displayComment(userText) { const commentBox = document.getElementById('box'); const p = document.createElement('p'); // Safe: This escapes special characters automatically p.textContent = userText; commentBox.appendChild(p); }

Saving User Passwords

Node.js Cryptography Auth
The Challenge: Store a password in the database.
Mid-Complex Task: Preventing "Rainbow Table" attacks on leaks.
// Student Level: Freshman // Logic: Plaintext or simple MD5/SHA. // Risk: Hackers can reverse this instantly using Rainbow Tables. const crypto = require('crypto'); function savePassword(password) { // Simple hashing is NOT secure anymore const hash = crypto.createHash('sha256').update(password).digest('hex'); db.save(hash); }
// Student Level: Senior // Logic: Bcrypt with Salt Rounds. // Safety: Salt makes hashes unique; Work factor slows down brute-force. const bcrypt = require('bcrypt'); async function savePassword(password) { // 10 = Salt Rounds (Work Factor) // Makes hashing slow enough to defeat brute-force attacks const hash = await bcrypt.hash(password, 10); await db.save(hash); }

Responsive 3-Column Grid

CSS 3 Grid Layout Responsive
The Challenge: Create a card layout that is 3-columns on Desktop but stacks 1-column on Mobile.
Mid-Complex Task: Doing it without 50 lines of `@media` queries.
/* Student Level: Freshman */ /* Logic: Floats and Percentages. */ /* Issue: Fragile. Requires clearing floats and explicit mobile breakpoints. */ .container { overflow: hidden; /* Clear floats */ } .card { float: left; width: 33.33%; /* Fixed width */ padding: 10px; } /* Mobile Media Query */ @media (max-width: 600px) { .card { width: 100%; float: none; } }
/* Student Level: Senior */ /* Logic: CSS Grid (Auto-Fit). */ /* Benefit: Zero media queries. Layout adapts fluidly to any screen size. */ .container { display: grid; gap: 20px; /* The Magic Line: */ /* "Fit as many 300px columns as possible, then wrap" */ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
```