Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
95 changes: 95 additions & 0 deletions Implement-Laptop-Allocation/implementLaptop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict


# Define possible operating systems
class OperatingSystem(Enum):
MACOS = "macOS"
ARCH = "Arch Linux"
UBUNTU = "Ubuntu"


# Define Person and Laptop
@dataclass
class Person:
name: str
age: int
preferred_operating_system: List[OperatingSystem]


@dataclass
class Laptop:
id: int
manufacturer: str
model: str
operating_system: OperatingSystem


# Function to calculate sadness
def sadness_for_person(person: Person, laptop: Laptop) -> int:
"""How sad a person is with this laptop."""
if laptop.operating_system in person.preferred_operating_system:
return person.preferred_operating_system.index(laptop.operating_system)
else:
return 100 # Very sad if OS not in their list


# Simple laptop allocation
def allocate_laptops(people: List[Person], laptops: List[Laptop]) -> Dict[str, Laptop]:
"""
Give each person one laptop.
Try to reduce sadness.
"""
allocated = {}
available_laptops = laptops.copy()

for person in people:
best_laptop = None
best_sadness = 999

# Try to find the best laptop for this person
for laptop in available_laptops:
s = sadness_for_person(person, laptop)
if s < best_sadness:
best_sadness = s
best_laptop = laptop

# Give them the best one we found
allocated[person.name] = best_laptop
available_laptops.remove(best_laptop)

return allocated


# Testing data
def main():
laptops = [
Laptop(1, "Dell", "XPS 13", OperatingSystem.ARCH),
Laptop(2, "Dell", "XPS 15", OperatingSystem.UBUNTU),
Laptop(3, "Apple", "MacBook Air", OperatingSystem.MACOS),
Laptop(4, "Dell", "Inspiron", OperatingSystem.UBUNTU),
]

people = [
Person("Imran", 22, [OperatingSystem.UBUNTU, OperatingSystem.ARCH, OperatingSystem.MACOS]),
Person("Eliza", 34, [OperatingSystem.ARCH, OperatingSystem.UBUNTU, OperatingSystem.MACOS]),
Person("Sam", 29, [OperatingSystem.MACOS, OperatingSystem.UBUNTU]),
Person("Tariq", 25, [OperatingSystem.ARCH]),
]

allocations = allocate_laptops(people, laptops)

print("=== Laptop Allocations ===")
total_sadness = 0
for name, laptop in allocations.items():
person = next(p for p in people if p.name == name)
sad = sadness_for_person(person, laptop)
total_sadness += sad
print(f"{name} gets {laptop.model} ({laptop.operating_system.value}) - sadness {sad}")

print(f"\nTotal sadness: {total_sadness}")


if __name__ == "__main__":
main()
56 changes: 56 additions & 0 deletions Middleware-custom/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware 1: Check username header
app.use((req, res, next) => {
req.username = req.headers['x-username'] || null;
next();
});

// Middleware 2: Parse JSON and check if body is string array
app.use((req, res, next) => {
if (req.method !== 'POST') return next();

let body = '';
req.on('data', chunk => {
body += chunk.toString();
});

req.on('end', () => {
try {
req.body = JSON.parse(body);
} catch (error) {
return res.status(400).send('Error: Invalid JSON');
}

// Simple array check
if (!Array.isArray(req.body)) {
return res.status(400).send('Error: Send a JSON array');
}

// Simple string check
for (let item of req.body) {
if (typeof item !== 'string') {
return res.status(400).send('Error: All items must be strings');
}
}

req.subjects = req.body;
next();
});
});

// POST endpoint
app.post('/', (req, res) => {
const name = req.username ? `authenticated as ${req.username}` : 'not authenticated';
const count = req.subjects.length;
const word = count === 1 ? 'subject' : 'subjects';
const list = req.subjects.join(', ');

res.send(`You are ${name}.\n\nYou asked about ${count} ${word}: ${list}.`);
});

app.listen(PORT, () => {
console.log('Custom server started on port 3000');
});
Loading