id,label,modality,language,content,source,generator code_human_000,human,code,python,"def parse_csv(fname): # quick and dirty, assumes first row is header rows = [] with open(fname) as f: headers = f.readline().strip().split(',') for line in f: vals = line.strip().split(',') if len(vals) != len(headers): continue # skip malformed rows, happens more than you'd think rows.append(dict(zip(headers, vals))) return rows # TODO: handle quoted fields with commas inside them # TODO: maybe just use pandas lol",human_written,human code_human_001,human,code,python,"class Node: def __init__(self, val): self.val = val self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, val): if not self.root: self.root = Node(val) return cur = self.root while True: if val < cur.val: if cur.left is None: cur.left = Node(val) break cur = cur.left else: if cur.right is None: cur.right = Node(val) break cur = cur.right def search(self, val): cur = self.root while cur: if val == cur.val: return True cur = cur.left if val < cur.val else cur.right return False",human_written,human code_human_002,human,code,javascript,"// lifted this from stackoverflow and tweaked it function debounce(fn, wait) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), wait); } } // usage: const handleResize = debounce(() => doThing(), 200) // window.addEventListener('resize', handleResize)",human_written,human code_human_003,human,code,python,"import re # regex I've tested against like 50 addresses, probably not perfect EMAIL_RE = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') def valid_email(s): return bool(EMAIL_RE.match(s.strip())) if __name__ == '__main__': tests = ['user@example.com', 'bad@', 'also.bad', 'ok+filter@sub.domain.org'] for t in tests: print(t, '->', valid_email(t))",human_written,human code_human_004,human,code,python,"from collections import OrderedDict class LRUCache: def __init__(self, cap): self.cap = cap self.cache = OrderedDict() def get(self, key): if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key, val): if key in self.cache: self.cache.move_to_end(key) self.cache[key] = val if len(self.cache) > self.cap: self.cache.popitem(last=False) # evict oldest",human_written,human code_ai_000,ai,code,python,"import pandas as pd import numpy as np import os def compute_summary_statistics(file_path: str) -> dict: """""" Reads a CSV file and computes summary statistics for each numeric column. Args: file_path: Path to the CSV file Returns: Dictionary containing summary statistics for each numeric column """""" if not os.path.exists(file_path): raise FileNotFoundError(f""File not found: {file_path}"") df = pd.read_csv(file_path) numeric_df = df.select_dtypes(include=[np.number]) if numeric_df.empty: return {""message"": ""No numeric columns found in the CSV file""} summary = {} for column in numeric_df.columns: col_data = numeric_df[column] summary[column] = { ""count"": int(col_data.count()), ""missing_values"": int(col_data.isna().sum()), ""mean"": round(float(col_data.mean()), 4), ""median"": round(float(col_data.median()), 4), ""mode"": round(float(col_data.mode()[0]), 4) if not col_data.mode().empty else None, ""std_dev"": round(float(col_data.std()), 4), ""variance"": round(float(col_data.var()), 4), ""min"": round(float(col_data.min()), 4), ""max"": round(float(col_data.max()), 4), ""range"": round(float(col_data.max() - col_data.min()), 4), ""25th_percentile"": round(float(col_data.quantile(0.25)), 4), ""50th_percentile"": round(float(col_data.quantile(0.50)), 4), ""75th_percentile"": round(float(col_data.quantile(0.75)), 4), ""iqr"": round(float(col_data.quantile(0.75) - col_data.quantile(0.25)), 4), ""skewness"": round(float(col_data.skew()), 4), ""kurtosis"": round(float(col_data.kurtosis()), 4), ""sum"":",claude-sonnet-4-6,claude code_ai_001,ai,code,python,"class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: return None if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: # Node to delete found if node.left is None: return node.right elif node.right is None: return node.left # Node has two children: find in-order successor (smallest in right subtree) successor = self._find_min(node.right) node.value = successor.value node.right = self._delete_recursive(node.right, successor.value) return node def _find_min(self, node): current = node while current.left is not None: current = current.left return current def inorder_traversal(self): result = [] self._inorder_recursive(self.root, result)",claude-sonnet-4-6,claude code_ai_002,ai,code,python,"import requests from bs4 import BeautifulSoup from datetime import datetime import json import re def scrape_news_articles(url=None): """""" Scrapes article titles and dates from a news website. Default target: BBC News """""" if url is None: url = ""https://www.bbc.com/news"" headers = { ""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "" ""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"", ""Accept"": ""text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"", ""Accept-Language"": ""en-US,en;q=0.5"", ""Accept-Encoding"": ""gzip, deflate, br"", ""Connection"": ""keep-alive"", } articles = [] try: print(f""Fetching articles from: {url}"") response = requests.get(url, headers=headers, timeout=15) response.raise_for_status() soup = BeautifulSoup(response.text, ""html.parser"") # Try multiple selectors for different news sites scrapers = [ scrape_bbc, scrape_generic_time_tags, scrape_generic_article_tags, ] for scraper in scrapers: articles = scraper(soup, url) if articles: break if not articles: print(""No articles found with standard selectors. Trying fallback method..."") articles = scrape_fallback(soup) except requests.exceptions.RequestException as e: print(f""Error fetching URL: {e}"") return [] return articles def scrape_bbc(soup, url): """"""Scrape BBC News articles."""""" articles = [] if ""bbc"" not in url.lower(): return articles # BBC News selectors article_selectors = [ ""h3[data-testid='card-headline']"", ""h1[data-testid='headline']"", "".gs-c-promo-heading__title"", """,claude-sonnet-4-6,claude code_ai_003,ai,code,javascript,"function debounce(callback, n) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => { callback.apply(this, args); }, n); }; } // Example usage: const handleInput = debounce((value) => { console.log(""Input value:"", value); }, 500); handleInput(""H""); handleInput(""He""); handleInput(""Hel""); handleInput(""Hell""); handleInput(""Hello""); // Only logs ""Input value: Hello"" after 500ms",claude-sonnet-4-6,claude code_ai_004,ai,code,javascript,"class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter(l => l !== listener); if (this.events[event].length === 0) { delete this.events[event]; } return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach(listener => { listener(...args); }); return true; } } // Example usage const emitter = new EventEmitter(); const greet = (name) => console.log(`Hello, ${name}!`); const farewell = (name) => console.log(`Goodbye, ${name}!`); emitter.on('greet', greet); emitter.on('greet', farewell); console.log('Emitting greet event:'); emitter.emit('greet', 'Alice'); console.log('\nRemoving farewell listener:'); emitter.off('greet', farewell); emitter.emit('greet', 'Bob'); console.log('\nEmitting unknown event:'); const result = emitter.emit('unknown', 'Charlie'); console.log('Event emitted:', result);",claude-sonnet-4-6,claude code_ai_005,ai,code,python,"import re def is_valid_email(email: str) -> bool: pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) if __name__ == ""__main__"": test_emails = [ ""user@example.com"", ""user.name+tag@example.co.uk"", ""user@subdomain.example.com"", ""invalid-email"", ""missing@domain"", ""@nodomain.com"", ""spaces in@email.com"", ""user@.com"", ""user@domain."", ""user123@example.org"" ] for email in test_emails: result = is_valid_email(email) print(f""{email}: {'Valid' if result else 'Invalid'}"")",claude-sonnet-4-6,claude code_ai_006,ai,code,python,"from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) if __name__ == ""__main__"": cache = LRUCache(2) cache.put(1, 1) print(f""Put (1, 1): cache = {dict(cache.cache)}"") cache.put(2, 2) print(f""Put (2, 2): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") cache.put(3, 3) print(f""Put (3, 3): cache = {dict(cache.cache)}"") print(f""Get 2 (evicted): {cache.get(2)}"") cache.put(4, 4) print(f""Put (4, 4): cache = {dict(cache.cache)}"") print(f""Get 1 (evicted): {cache.get(1)}"") print(f""Get 3: {cache.get(3)}"") print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude code_ai_007,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) { // Handle null, undefined, and primitive types if (obj === null || obj === undefined) { return obj; } if (typeof obj !== ""object"" && typeof obj !== ""function"") { return obj; } // Handle circular references if (visited.has(obj)) { return visited.get(obj); } // Handle Date if (obj instanceof Date) { return new Date(obj.getTime()); } // Handle RegExp if (obj instanceof RegExp) { return new RegExp(obj.source, obj.flags); } // Handle Map if (obj instanceof Map) { const clonedMap = new Map(); visited.set(obj, clonedMap); obj.forEach((value, key) => { clonedMap.set(deepClone(key, visited), deepClone(value, visited)); }); return clonedMap; } // Handle Set if (obj instanceof Set) { const clonedSet = new Set(); visited.set(obj, clonedSet); obj.forEach((value) => { clonedSet.add(deepClone(value, visited)); }); return clonedSet; } // Handle Array if (Array.isArray(obj)) { const clonedArray = []; visited.set(obj, clonedArray); obj.forEach((item, index) => { clonedArray[index] = deepClone(item, visited); }); return clonedArray; } // Handle Function if (typeof obj === ""function"") { return obj; } // Handle Symbol keys const clonedObj = Object.create(Object.getPrototypeOf(obj)); visited.set(obj, clonedObj); // Clone regular keys for (const key of Object.keys(obj)) { clonedObj[key] = deepClone(obj[key], visited); } // Clone Symbol keys for (const sym of Object.getOwnPropertySymbols(obj)) { clonedObj[sym] = deepClone(obj[sym], visited); } return clonedObj; } // Test the function const original = { name: """,claude-sonnet-4-6,claude code_ai_008,ai,code,python,"def generate_permutations(lst): if len(lst) <= 1: return [lst] permutations = [] for i, element in enumerate(lst): remaining = lst[:i] + lst[i+1:] for perm in generate_permutations(remaining): permutations.append([element] + perm) return permutations if __name__ == ""__main__"": sample_list = [1, 2, 3] result = generate_permutations(sample_list) print(f""All permutations of {sample_list}:"") for perm in result: print(perm) print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude code_ai_009,ai,code,python,"import time import logging from contextlib import contextmanager logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) @contextmanager def timer(name=""Code block""): start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() elapsed_time = end_time - start_time logger.info(f""{name} executed in {elapsed_time:.6f} seconds"") if __name__ == ""__main__"": with timer(""Sleep example""): time.sleep(1.5) with timer(""List comprehension""): result = [x ** 2 for x in range(100000)] with timer(""String concatenation""): text = """" for i in range(10000): text += str(i)",claude-sonnet-4-6,claude code_ai_010,ai,code,python,"import pandas as pd import numpy as np import csv import os def compute_summary_statistics(file_path: str) -> dict: """""" Reads a CSV file and computes summary statistics for each numeric column. Args: file_path: Path to the CSV file Returns: Dictionary with column names as keys and statistics as values """""" if not os.path.exists(file_path): raise FileNotFoundError(f""File not found: {file_path}"") df = pd.read_csv(file_path) numeric_columns = df.select_dtypes(include=[np.number]).columns if len(numeric_columns) == 0: return {""message"": ""No numeric columns found in the CSV file""} summary = {} for col in numeric_columns: col_data = df[col].dropna() summary[col] = { ""count"": int(col_data.count()), ""missing_values"": int(df[col].isnull().sum()), ""mean"": round(float(col_data.mean()), 4), ""median"": round(float(col_data.median()), 4), ""mode"": round(float(col_data.mode()[0]), 4) if not col_data.mode().empty else None, ""std_dev"": round(float(col_data.std()), 4), ""variance"": round(float(col_data.var()), 4), ""min"": round(float(col_data.min()), 4), ""max"": round(float(col_data.max()), 4), ""range"": round(float(col_data.max() - col_data.min()), 4), ""25th_percentile"": round(float(col_data.quantile(0.25)), 4), ""75th_percentile"": round(float(col_data.quantile(0.75)), 4), ""iqr"": round(float(col_data.quantile(0.75) - col_data.quantile(0.25)), 4), ""skewness"": round(float(col_data.skew()), 4), ""kurtosis"": round(float(col_data.kurtosis()), 4), ""sum"": round(float(col_data.sum()), 4), }",claude-sonnet-4-6,claude code_ai_011,ai,code,python,"class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: return None if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: # Node with only one child or no child if node.left is None: return node.right elif node.right is None: return node.left # Node with two children: get inorder successor (smallest in right subtree) min_larger_node = self._get_min(node.right) node.value = min_larger_node.value node.right = self._delete_recursive(node.right, min_larger_node.value) return node def _get_min(self, node): current = node while current.left is not None: current = current.left return current def inorder_traversal(self): result = []",claude-sonnet-4-6,claude code_ai_012,ai,code,python,"import requests from bs4 import BeautifulSoup from datetime import datetime import json import re def scrape_news_articles(url=None): """""" Scrapes article titles and dates from a news website. Uses BBC News as the default example. """""" if url is None: url = ""https://www.bbc.com/news"" headers = { ""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "" ""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"", ""Accept-Language"": ""en-US,en;q=0.9"", ""Accept-Encoding"": ""gzip, deflate, br"", ""Accept"": ""text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"", ""Connection"": ""keep-alive"", } articles = [] try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.content, ""html.parser"") # Strategy 1: Look for time elements with article titles time_elements = soup.find_all(""time"") for time_el in time_elements: date_text = ( time_el.get(""datetime"") or time_el.get(""data-datetime"") or time_el.get_text(strip=True) ) # Try to find associated title by traversing parent elements parent = time_el.parent title = None for _ in range(5): # Look up to 5 levels up if parent is None: break heading = parent.find([""h1"", ""h2"", ""h3"", ""h4""]) if heading: title = heading.get_text(strip=True) break parent = parent.parent if title and date_text: articles.append({ ""title"": title, ""date"": date_text, ""source"": url }) # Strategy 2: Look for article tags if not articles: article_tags = soup.find_all(""article",claude-sonnet-4-6,claude code_ai_013,ai,code,javascript,"function debounce(callback, n) { let timeoutId; return function (...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { callback.apply(this, args); }, n); }; } // Example usage const debouncedFn = debounce((message) => { console.log(`Called with: ${message}`); }, 500); debouncedFn(""first""); debouncedFn(""second""); debouncedFn(""third""); // Only ""Called with: third"" will be logged after 500ms",claude-sonnet-4-6,claude code_ai_014,ai,code,javascript,"class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter((l) => l !== listener); if (this.events[event].length === 0) { delete this.events[event]; } return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach((listener) => { listener(...args); }); return true; } } // Example usage const emitter = new EventEmitter(); const greet = (name) => console.log(`Hello, ${name}!`); const farewell = (name) => console.log(`Goodbye, ${name}!`); emitter.on(""greeting"", greet); emitter.on(""greeting"", farewell); console.log(""Emitting greeting event:""); emitter.emit(""greeting"", ""Alice""); console.log(""\nRemoving farewell listener:""); emitter.off(""greeting"", farewell); console.log(""Emitting greeting event again:""); emitter.emit(""greeting"", ""Bob""); console.log(""\nEmitting non-existent event:""); console.log(emitter.emit(""nonExistent""));",claude-sonnet-4-6,claude code_ai_015,ai,code,python,"import re def is_valid_email(email): pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) # Test the function test_emails = [ ""user@example.com"", ""user.name+tag@example.co.uk"", ""user@subdomain.example.com"", ""invalid-email"", ""missing@domain"", ""@nodomain.com"", ""user@.com"", ""user@domain.c"", ""user name@domain.com"", ""user@domain..com"" ] for email in test_emails: print(f""{email}: {'Valid' if is_valid_email(email) else 'Invalid'}"")",claude-sonnet-4-6,claude code_ai_016,ai,code,python,"from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) if __name__ == ""__main__"": cache = LRUCache(2) cache.put(1, 1) print(f""Put (1, 1): cache = {dict(cache.cache)}"") cache.put(2, 2) print(f""Put (2, 2): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") cache.put(3, 3) print(f""Put (3, 3): cache = {dict(cache.cache)}"") print(f""Get 2: {cache.get(2)}"") cache.put(4, 4) print(f""Put (4, 4): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") print(f""Get 3: {cache.get(3)}"") print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude code_ai_017,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) { // Handle null and non-object types if (obj === null || typeof obj !== ""object"") { return obj; } // Handle circular references if (visited.has(obj)) { return visited.get(obj); } // Handle Date if (obj instanceof Date) { return new Date(obj.getTime()); } // Handle RegExp if (obj instanceof RegExp) { return new RegExp(obj.source, obj.flags); } // Handle Map if (obj instanceof Map) { const clonedMap = new Map(); visited.set(obj, clonedMap); obj.forEach((value, key) => { clonedMap.set(deepClone(key, visited), deepClone(value, visited)); }); return clonedMap; } // Handle Set if (obj instanceof Set) { const clonedSet = new Set(); visited.set(obj, clonedSet); obj.forEach((value) => { clonedSet.add(deepClone(value, visited)); }); return clonedSet; } // Handle Array if (Array.isArray(obj)) { const clonedArray = []; visited.set(obj, clonedArray); obj.forEach((item, index) => { clonedArray[index] = deepClone(item, visited); }); return clonedArray; } // Handle ArrayBuffer if (obj instanceof ArrayBuffer) { return obj.slice(0); } // Handle TypedArrays if (ArrayBuffer.isView(obj)) { return new obj.constructor(obj); } // Handle plain objects const clonedObj = Object.create(Object.getPrototypeOf(obj)); visited.set(obj, clonedObj); // Copy all own properties (including non-enumerable) for (const key of Reflect.ownKeys(obj)) { const descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor.value !== undefined) { descriptor.value = deepClone(descriptor.value, visited); } Object.defineProperty(clonedObj, key, descriptor); } return cloned",claude-sonnet-4-6,claude code_ai_018,ai,code,python,"def generate_permutations(lst): if len(lst) <= 1: return [lst] permutations = [] for i, element in enumerate(lst): remaining = lst[:i] + lst[i+1:] for perm in generate_permutations(remaining): permutations.append([element] + perm) return permutations if __name__ == ""__main__"": sample_list = [1, 2, 3] result = generate_permutations(sample_list) print(f""All permutations of {sample_list}:"") for perm in result: print(perm) print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude code_ai_019,ai,code,python,"import time import logging from contextlib import contextmanager logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) @contextmanager def timer(name: str = ""Code block""): start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() elapsed_time = end_time - start_time logger.info(f""{name} executed in {elapsed_time:.4f} seconds"") if __name__ == ""__main__"": with timer(""Sleep test""): time.sleep(1.5) with timer(""List comprehension""): result = [x ** 2 for x in range(1000000)] with timer(""String concatenation""): text = """" for i in range(10000): text += str(i)",claude-sonnet-4-6,claude code_ai_020,ai,code,python,"import pandas as pd import numpy as np import csv import os def compute_summary_statistics(file_path: str) -> dict: """""" Reads a CSV file and computes summary statistics for each numeric column. Args: file_path: Path to the CSV file Returns: Dictionary containing summary statistics for each numeric column """""" if not os.path.exists(file_path): raise FileNotFoundError(f""File not found: {file_path}"") df = pd.read_csv(file_path) numeric_df = df.select_dtypes(include=[np.number]) if numeric_df.empty: return {""message"": ""No numeric columns found in the CSV file""} summary = {} for column in numeric_df.columns: col_data = numeric_df[column].dropna() if len(col_data) == 0: summary[column] = {""message"": ""Column contains no valid numeric data""} continue q1 = col_data.quantile(0.25) q3 = col_data.quantile(0.75) iqr = q3 - q1 summary[column] = { ""count"": len(col_data), ""missing_values"": numeric_df[column].isna().sum(), ""mean"": round(col_data.mean(), 4), ""median"": round(col_data.median(), 4), ""mode"": round(col_data.mode()[0], 4) if not col_data.mode().empty else None, ""std_dev"": round(col_data.std(), 4), ""variance"": round(col_data.var(), 4), ""min"": round(col_data.min(), 4), ""max"": round(col_data.max(), 4), ""range"": round(col_data.max() - col_data.min(), 4), ""q1"": round(q1, 4), ""q3"": round(q3, 4), ""iqr"": round(iqr, 4), ""skewness"": round(col_data.skew(), 4), ""kurtosis"": round(col_data.kurtosis(), 4), ""sum"": round(col_data.sum(), 4), }",claude-sonnet-4-6,claude code_ai_021,ai,code,python,"class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) else: print(f""Value {value} already exists in the tree."") def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: print(f""Value {value} not found in the tree."") return node if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: # Node with only one child or no child if node.left is None: return node.right elif node.right is None: return node.left # Node with two children # Get the inorder successor (smallest in the right subtree) min_larger_node = self._get_min(node.right) node.value = min_larger_node.value node.right = self._delete_recursive(node.right, min_larger_node.value) return node def _get_min(self, node): current",claude-sonnet-4-6,claude code_ai_022,ai,code,python,"import requests from bs4 import BeautifulSoup from datetime import datetime import json import re def scrape_news_articles(url: str, headers: dict = None) -> list[dict]: """""" Scrape article titles and dates from a news website. Args: url: The URL of the news website to scrape headers: Optional HTTP headers for the request Returns: List of dictionaries containing article titles and dates """""" if headers is None: headers = { ""User-Agent"": ( ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) "" ""AppleWebKit/537.36 (KHTML, like Gecko) "" ""Chrome/91.0.4472.124 Safari/537.36"" ) } articles = [] try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, ""html.parser"") # Try multiple common HTML patterns for news articles articles = ( extract_schema_articles(soup) or extract_article_tags(soup) or extract_common_class_patterns(soup) ) if not articles: print(""No articles found with standard patterns. Trying generic extraction..."") articles = extract_generic_content(soup) except requests.exceptions.RequestException as e: print(f""Error fetching URL: {e}"") return articles def extract_schema_articles(soup: BeautifulSoup) -> list[dict]: """"""Extract articles using JSON-LD schema markup."""""" articles = [] for script in soup.find_all(""script"", type=""application/ld+json""): try: data = json.loads(script.string) if isinstance(data, list): items = data elif isinstance(data, dict): items = data.get(""@graph"", [data]) else: continue for item in items: if isinstance(item, dict) and item.get(""@type"") in [""NewsArticle"", ""Article"", ""BlogPosting""]: title = item.get(""headline"", """") date = item.get(""datePublished"", """") or item.get(""dateCreated"", """")",claude-sonnet-4-6,claude code_ai_023,ai,code,javascript,"function debounce(callback, n) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { callback.apply(this, args); }, n); }; }",claude-sonnet-4-6,claude code_ai_024,ai,code,javascript,"class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter((l) => l !== listener); if (this.events[event].length === 0) { delete this.events[event]; } return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach((listener) => { listener(...args); }); return true; } } // Example usage const emitter = new EventEmitter(); const greet = (name) => console.log(`Hello, ${name}!`); const farewell = (name) => console.log(`Goodbye, ${name}!`); emitter.on(""greet"", greet); emitter.on(""greet"", farewell); console.log(""Emitting 'greet' event:""); emitter.emit(""greet"", ""Alice""); console.log(""\nRemoving 'farewell' listener:""); emitter.off(""greet"", farewell); console.log(""Emitting 'greet' event again:""); emitter.emit(""greet"", ""Bob""); console.log(""\nEmitting non-existent event:""); const result = emitter.emit(""nonExistent""); console.log(`Event emitted: ${result}`);",claude-sonnet-4-6,claude code_ai_025,ai,code,python,"import re def is_valid_email(email: str) -> bool: pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) if __name__ == ""__main__"": test_emails = [ ""user@example.com"", ""user.name+tag@domain.co.uk"", ""user@subdomain.domain.com"", ""invalid-email"", ""missing@domain"", ""@nodomain.com"", ""spaces in@email.com"", ""user@.com"", ""user@domain."", ""valid_email123@company.org"" ] for email in test_emails: result = is_valid_email(email) print(f""{email}: {'Valid' if result else 'Invalid'}"")",claude-sonnet-4-6,claude code_ai_026,ai,code,python,"from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) if __name__ == ""__main__"": cache = LRUCache(2) cache.put(1, 1) print(f""Put (1, 1): cache = {dict(cache.cache)}"") cache.put(2, 2) print(f""Put (2, 2): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") cache.put(3, 3) print(f""Put (3, 3): cache = {dict(cache.cache)}"") print(f""Get 2: {cache.get(2)}"") cache.put(4, 4) print(f""Put (4, 4): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") print(f""Get 3: {cache.get(3)}"") print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude code_ai_027,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) { // Handle null and non-object types if (obj === null || typeof obj !== 'object') { return obj; } // Handle circular references if (visited.has(obj)) { return visited.get(obj); } // Handle Date if (obj instanceof Date) { return new Date(obj.getTime()); } // Handle RegExp if (obj instanceof RegExp) { return new RegExp(obj.source, obj.flags); } // Handle Map if (obj instanceof Map) { const mapClone = new Map(); visited.set(obj, mapClone); obj.forEach((value, key) => { mapClone.set(deepClone(key, visited), deepClone(value, visited)); }); return mapClone; } // Handle Set if (obj instanceof Set) { const setClone = new Set(); visited.set(obj, setClone); obj.forEach((value) => { setClone.add(deepClone(value, visited)); }); return setClone; } // Handle Array if (Array.isArray(obj)) { const arrayClone = []; visited.set(obj, arrayClone); obj.forEach((item, index) => { arrayClone[index] = deepClone(item, visited); }); return arrayClone; } // Handle ArrayBuffer if (obj instanceof ArrayBuffer) { return obj.slice(0); } // Handle TypedArrays if (ArrayBuffer.isView(obj)) { return new obj.constructor(obj); } // Handle Symbol keys const clone = Object.create(Object.getPrototypeOf(obj)); visited.set(obj, clone); // Clone regular string keys for (const key of Object.keys(obj)) { clone[key] = deepClone(obj[key], visited); } // Clone symbol keys for (const sym of Object.getOwnPropertySymbols(obj)) { clone[sym] = deepClone(obj[sym], visited); } return clone; } // Example usage: const original = { name: 'John', age: 30,",claude-sonnet-4-6,claude code_ai_028,ai,code,python,"def generate_permutations(lst): if len(lst) <= 1: return [lst] permutations = [] for i, element in enumerate(lst): remaining = lst[:i] + lst[i+1:] for perm in generate_permutations(remaining): permutations.append([element] + perm) return permutations if __name__ == ""__main__"": sample_list = [1, 2, 3] result = generate_permutations(sample_list) print(f""All permutations of {sample_list}:"") for perm in result: print(perm) print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude code_ai_029,ai,code,python,"import time import logging from contextlib import contextmanager logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) @contextmanager def timer(label=""Code block""): start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() elapsed_time = end_time - start_time logger.info(f""{label} executed in {elapsed_time:.6f} seconds"") if __name__ == ""__main__"": with timer(""Sleep example""): time.sleep(1.5) with timer(""List comprehension""): result = [x ** 2 for x in range(100000)] with timer(""String concatenation""): text = """" for i in range(10000): text += str(i)",claude-sonnet-4-6,claude code_ai_030,ai,code,python,"import pandas as pd import numpy as np import csv import os def compute_summary_statistics(file_path: str) -> dict: """""" Reads a CSV file and computes summary statistics for each numeric column. Args: file_path: Path to the CSV file Returns: A dictionary with column names as keys and statistics as values """""" if not os.path.exists(file_path): raise FileNotFoundError(f""File not found: {file_path}"") df = pd.read_csv(file_path) numeric_columns = df.select_dtypes(include=[np.number]).columns if len(numeric_columns) == 0: print(""No numeric columns found in the CSV file."") return {} summary = {} for col in numeric_columns: col_data = df[col].dropna() summary[col] = { ""count"": len(col_data), ""missing_values"": df[col].isna().sum(), ""mean"": col_data.mean(), ""median"": col_data.median(), ""mode"": col_data.mode()[0] if not col_data.mode().empty else None, ""std"": col_data.std(), ""variance"": col_data.var(), ""min"": col_data.min(), ""max"": col_data.max(), ""range"": col_data.max() - col_data.min(), ""25th_percentile"": col_data.quantile(0.25), ""75th_percentile"": col_data.quantile(0.75), ""iqr"": col_data.quantile(0.75) - col_data.quantile(0.25), ""skewness"": col_data.skew(), ""kurtosis"": col_data.kurt(), ""sum"": col_data.sum() } return summary def print_summary_statistics(file_path: str) -> None: """""" Prints formatted summary statistics for each numeric column in a CSV file. Args: file_path: Path to the CSV file """""" summary = compute_summary_statistics(file_path) if not summary: return print(f""\n{'='*60}"") print(f""Summary Statistics for: {os.path",claude-sonnet-4-6,claude code_ai_031,ai,code,python,"class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: return None if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: # Node with only one child or no child if node.left is None: return node.right elif node.right is None: return node.left # Node with two children: get inorder successor (smallest in right subtree) min_larger_node = self._get_min(node.right) node.value = min_larger_node.value node.right = self._delete_recursive(node.right, min_larger_node.value) return node def _get_min(self, node): current = node while current.left is not None: current = current.left return current def inorder_traversal(self): result = []",claude-sonnet-4-6,claude code_ai_032,ai,code,python,"import requests from bs4 import BeautifulSoup from datetime import datetime import json import re def scrape_news_articles(url: str, headers: dict = None) -> list[dict]: """""" Scrape article titles and dates from a news website. Args: url: The URL of the news website to scrape headers: Optional HTTP headers for the request Returns: List of dictionaries containing article titles and dates """""" if headers is None: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() except requests.RequestException as e: print(f""Error fetching URL: {e}"") return [] soup = BeautifulSoup(response.content, 'html.parser') articles = [] # Common patterns for article titles and dates title_selectors = [ 'h1', 'h2', 'h3', 'article h1', 'article h2', 'article h3', '.article-title', '.post-title', '.entry-title', '.headline', '.news-title', '.story-title', '[class*=""title""]', '[class*=""headline""]', 'a[href*=""/article""]', 'a[href*=""/news""]', 'a[href*=""/story""]', 'a[href*=""/post""]' ] date_selectors = [ 'time', '.date', '.published', '.post-date', '.article-date', '.entry-date', '.timestamp', '[class*=""date""]', '[class*=""time""]', '[class*=""published""]', '[datetime]', 'span[class*=""date""]', 'p[class*=""date""]' ] # Try to find article containers first article_containers = soup.find_all(['article', 'div'], class_=re.compile(r'article|post|news|story|card', re.I)) if article_containers: for",claude-sonnet-4-6,claude code_ai_033,ai,code,javascript,"function debounce(callback, n) { let timeoutId; return function (...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { callback.apply(this, args); }, n); }; } // Example usage const debouncedFunction = debounce((message) => { console.log(`Called with: ${message}`); }, 500); debouncedFunction(""Hello""); debouncedFunction(""Hello again""); debouncedFunction(""Final call""); // Only this will execute after 500ms",claude-sonnet-4-6,claude code_ai_034,ai,code,javascript,"class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter(l => l !== listener); if (this.events[event].length === 0) { delete this.events[event]; } return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach(listener => listener(...args)); return true; } } // Example usage const emitter = new EventEmitter(); const greet = (name) => console.log(`Hello, ${name}!`); const farewell = (name) => console.log(`Goodbye, ${name}!`); emitter.on('greet', greet); emitter.on('greet', farewell); emitter.emit('greet', 'Alice'); // Output: // Hello, Alice! // Goodbye, Alice! emitter.off('greet', farewell); emitter.emit('greet', 'Bob'); // Output: // Hello, Bob!",claude-sonnet-4-6,claude code_ai_035,ai,code,python,"import re def is_valid_email(email): pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) # Test examples test_emails = [ ""user@example.com"", ""user.name+tag@domain.co.uk"", ""invalid-email"", ""missing@domain"", ""@nodomain.com"", ""user@.com"", ""user@domain.c"", ""user123@sub.domain.com"" ] for email in test_emails: print(f""{email}: {is_valid_email(email)}"")",claude-sonnet-4-6,claude code_ai_036,ai,code,python,"from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) if __name__ == ""__main__"": cache = LRUCache(2) cache.put(1, 1) print(f""Put (1, 1): cache = {dict(cache.cache)}"") cache.put(2, 2) print(f""Put (2, 2): cache = {dict(cache.cache)}"") print(f""Get 1: {cache.get(1)}"") cache.put(3, 3) print(f""Put (3, 3): cache = {dict(cache.cache)}"") print(f""Get 2 (evicted): {cache.get(2)}"") cache.put(4, 4) print(f""Put (4, 4): cache = {dict(cache.cache)}"") print(f""Get 1 (evicted): {cache.get(1)}"") print(f""Get 3: {cache.get(3)}"") print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude code_ai_037,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) { // Handle null and non-object types if (obj === null || typeof obj !== 'object') { return obj; } // Handle circular references if (visited.has(obj)) { return visited.get(obj); } // Handle Date if (obj instanceof Date) { return new Date(obj.getTime()); } // Handle RegExp if (obj instanceof RegExp) { return new RegExp(obj.source, obj.flags); } // Handle Map if (obj instanceof Map) { const mapClone = new Map(); visited.set(obj, mapClone); obj.forEach((value, key) => { mapClone.set(deepClone(key, visited), deepClone(value, visited)); }); return mapClone; } // Handle Set if (obj instanceof Set) { const setClone = new Set(); visited.set(obj, setClone); obj.forEach((value) => { setClone.add(deepClone(value, visited)); }); return setClone; } // Handle Array if (Array.isArray(obj)) { const arrClone = []; visited.set(obj, arrClone); obj.forEach((item, index) => { arrClone[index] = deepClone(item, visited); }); return arrClone; } // Handle ArrayBuffer if (obj instanceof ArrayBuffer) { return obj.slice(0); } // Handle TypedArrays if (ArrayBuffer.isView(obj)) { return new obj.constructor(obj.buffer.slice(0)); } // Handle plain objects const objClone = Object.create(Object.getPrototypeOf(obj)); visited.set(obj, objClone); // Copy all own properties including non-enumerable ones [...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)].forEach((key) => { const descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor.value !== undefined) { descriptor.value = deepClone(descriptor.value, visited); } Object.defineProperty(objClone, key, descriptor);",claude-sonnet-4-6,claude code_ai_038,ai,code,python,"def get_permutations(lst): if len(lst) <= 1: return [lst] permutations = [] for i, element in enumerate(lst): remaining = lst[:i] + lst[i+1:] for perm in get_permutations(remaining): permutations.append([element] + perm) return permutations if __name__ == ""__main__"": sample_list = [1, 2, 3] result = get_permutations(sample_list) print(f""All permutations of {sample_list}:"") for perm in result: print(perm) print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude code_ai_039,ai,code,python,"import time import logging from contextlib import contextmanager logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) @contextmanager def timer(name: str = ""Code block""): start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() elapsed_time = end_time - start_time logger.info(f""{name} executed in {elapsed_time:.4f} seconds"") # Example usage if __name__ == ""__main__"": with timer(""Sleep example""): time.sleep(1.5) with timer(""List comprehension""): result = [x ** 2 for x in range(1000000)] with timer(""String concatenation""): text = """" for i in range(10000): text += str(i)",claude-sonnet-4-6,claude code_ai_040,ai,code,python,"import pandas as pd import numpy as np import csv import os def compute_summary_statistics(file_path: str) -> dict: """""" Reads a CSV file and computes summary statistics for each numeric column. Args: file_path: Path to the CSV file Returns: Dictionary with column names as keys and statistics as values """""" if not os.path.exists(file_path): raise FileNotFoundError(f""File not found: {file_path}"") df = pd.read_csv(file_path) numeric_columns = df.select_dtypes(include=[np.number]).columns if len(numeric_columns) == 0: print(""No numeric columns found in the CSV file."") return {} summary = {} for col in numeric_columns: col_data = df[col].dropna() summary[col] = { ""count"": len(col_data), ""missing_values"": df[col].isna().sum(), ""mean"": col_data.mean(), ""median"": col_data.median(), ""mode"": col_data.mode()[0] if not col_data.mode().empty else None, ""std_dev"": col_data.std(), ""variance"": col_data.var(), ""min"": col_data.min(), ""max"": col_data.max(), ""range"": col_data.max() - col_data.min(), ""25th_percentile"": col_data.quantile(0.25), ""75th_percentile"": col_data.quantile(0.75), ""iqr"": col_data.quantile(0.75) - col_data.quantile(0.25), ""skewness"": col_data.skew(), ""kurtosis"": col_data.kurt(), ""sum"": col_data.sum() } return summary def print_summary_statistics(summary: dict) -> None: """""" Prints the summary statistics in a formatted way. Args: summary: Dictionary containing summary statistics per column """""" if not summary: print(""No statistics to display."") return for col, stats in summary.items(): print(f""\n{'='*50}"") print(f""Column: {col}"") print(f",claude-sonnet-4-6,claude code_ai_041,ai,code,python,"class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: return None if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: # Node with only one child or no child if node.left is None: return node.right elif node.right is None: return node.left # Node with two children: get inorder successor (smallest in right subtree) min_larger_node = self._get_min(node.right) node.value = min_larger_node.value node.right = self._delete_recursive(node.right, min_larger_node.value) return node def _get_min(self, node): current = node while current.left is not None: current = current.left return current def inorder_traversal(self): result = []",claude-sonnet-4-6,claude code_ai_042,ai,code,python,"import requests from bs4 import BeautifulSoup from datetime import datetime import json import time import re def scrape_news_articles(url: str, headers: dict = None) -> list[dict]: """""" Scrape article titles and dates from a news website. Args: url: The URL of the news website to scrape headers: Optional HTTP headers to use for the request Returns: List of dictionaries containing article titles and dates """""" if headers is None: headers = { ""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "" ""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"" } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() except requests.RequestException as e: print(f""Error fetching URL: {e}"") return [] soup = BeautifulSoup(response.text, ""html.parser"") articles = [] # Try multiple common patterns for news articles articles = ( _extract_from_article_tags(soup) or _extract_from_common_classes(soup) or _extract_from_headings(soup) ) return articles def _extract_from_article_tags(soup: BeautifulSoup) -> list[dict]: """"""Extract articles from
HTML tags."""""" articles = [] article_tags = soup.find_all(""article"") for article in article_tags: title = _extract_title(article) date = _extract_date(article) if title: articles.append({ ""title"": title, ""date"": date or ""Date not found"", ""url"": _extract_url(article) }) return articles def _extract_from_common_classes(soup: BeautifulSoup) -> list[dict]: """"""Extract articles using common CSS class patterns."""""" articles = [] # Common class patterns used by news websites class_patterns = [ ""article"", ""post"", ""news-item"", ""story"", ""entry"", ""card"", ""list-item"", ""news-article"", ""article-item"" ]",claude-sonnet-4-6,claude code_ai_043,ai,code,javascript,"function debounce(callback, n) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { callback.apply(this, args); }, n); }; } // Example usage: const debouncedFn = debounce((value) => { console.log(""Debounced value:"", value); }, 500); debouncedFn(""first""); debouncedFn(""second""); debouncedFn(""third""); // Only ""third"" will be logged after 500ms",claude-sonnet-4-6,claude code_ai_044,ai,code,javascript,"class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter(l => l !== listener); if (this.events[event].length === 0) { delete this.events[event]; } return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach(listener => listener(...args)); return true; } } // Example usage const emitter = new EventEmitter(); const greet = (name) => console.log(`Hello, ${name}!`); const farewell = (name) => console.log(`Goodbye, ${name}!`); emitter.on('greet', greet); emitter.on('greet', farewell); emitter.emit('greet', 'Alice'); // Output: // Hello, Alice! // Goodbye, Alice! emitter.off('greet', farewell); emitter.emit('greet', 'Bob'); // Output: // Hello, Bob!",claude-sonnet-4-6,claude code_ai_045,ai,code,python,"import re def is_valid_email(email): pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email)) # Test the function test_emails = [ ""user@example.com"", ""user.name+tag@domain.co.uk"", ""invalid-email"", ""missing@domain"", ""@nodomain.com"", ""user@.com"", ""user@domain."", ""user name@domain.com"", ""user@domain.c"", ""test.email@subdomain.domain.com"" ] for email in test_emails: print(f""{email}: {'Valid' if is_valid_email(email) else 'Invalid'}"")",claude-sonnet-4-6,claude code_ai_046,ai,code,python,"class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} # key -> (value, node) # Doubly linked list with dummy head and tail self.head = Node(0, 0) # Most recently used end self.tail = Node(0, 0) # Least recently used end self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self._remove(node) self._insert_front(node) return node.value return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self._remove(self.cache[key]) node = Node(key, value) self.cache[key] = node self._insert_front(node) if len(self.cache) > self.capacity: # Remove least recently used (node before tail) lru_node = self.tail.prev self._remove(lru_node) del self.cache[lru_node.key] def _remove(self, node): node.prev.next = node.next node.next.prev = node.prev def _insert_front(self, node): node.next = self.head.next node.prev = self.head self.head.next.prev = node self.head.next = node class Node: def __init__(self, key: int, value: int): self.key = key self.value = value self.prev = None self.next = None # Example usage if __name__ == ""__main__"": cache = LRUCache(2) cache.put(1, 1) print(f""Put (1, 1)"") cache.put(2, 2) print(f""Put (2, 2)"") print(f""Get 1: {cache.get(1)}"") # returns 1 cache.put(3, 3) # evicts key 2 print(f""Put (3, 3) - evicts key 2"")",claude-sonnet-4-6,claude code_ai_047,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) { // Handle null, undefined, and primitive types if (obj === null || obj === undefined) { return obj; } if (typeof obj !== ""object"" && typeof obj !== ""function"") { return obj; } // Handle circular references if (visited.has(obj)) { return visited.get(obj); } // Handle Date if (obj instanceof Date) { return new Date(obj.getTime()); } // Handle RegExp if (obj instanceof RegExp) { return new RegExp(obj.source, obj.flags); } // Handle Map if (obj instanceof Map) { const mapClone = new Map(); visited.set(obj, mapClone); obj.forEach((value, key) => { mapClone.set(deepClone(key, visited), deepClone(value, visited)); }); return mapClone; } // Handle Set if (obj instanceof Set) { const setClone = new Set(); visited.set(obj, setClone); obj.forEach((value) => { setClone.add(deepClone(value, visited)); }); return setClone; } // Handle Array if (Array.isArray(obj)) { const arrayClone = []; visited.set(obj, arrayClone); obj.forEach((item, index) => { arrayClone[index] = deepClone(item, visited); }); return arrayClone; } // Handle Function if (typeof obj === ""function"") { return obj; } // Handle ArrayBuffer if (obj instanceof ArrayBuffer) { return obj.slice(0); } // Handle TypedArray (e.g., Int8Array, Uint8Array, Float32Array, etc.) if (ArrayBuffer.isView(obj)) { return new obj.constructor(obj.buffer.slice(0)); } // Handle Error if (obj instanceof Error) { const errorClone = new obj.constructor(obj.message); errorClone.stack = obj.stack; return errorClone; } // Handle Symbol keys const symbolKeys = Object.getOwnPropertySymbols(obj); // Handle plain objects",claude-sonnet-4-6,claude code_ai_048,ai,code,python,"def get_permutations(lst): if len(lst) <= 1: return [lst] permutations = [] for i, element in enumerate(lst): remaining = lst[:i] + lst[i+1:] for perm in get_permutations(remaining): permutations.append([element] + perm) return permutations if __name__ == ""__main__"": sample_list = [1, 2, 3] result = get_permutations(sample_list) print(f""All permutations of {sample_list}:"") for perm in result: print(perm) print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude code_ai_049,ai,code,python,"import time import logging from contextlib import contextmanager logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) @contextmanager def timer(name=""Code block""): start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() elapsed_time = end_time - start_time logger.info(f""{name} executed in {elapsed_time:.4f} seconds"") if __name__ == ""__main__"": with timer(""Sleep example""): time.sleep(1.5) with timer(""List comprehension""): result = [x ** 2 for x in range(100000)] with timer(""String concatenation""): text = """" for i in range(10000): text += str(i)",claude-sonnet-4-6,claude code_human_ext_000,human,code,python,"# wrote this in like 20 min, probably not the cleanest def merge_sort(arr): if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 left, lc = merge_sort(arr[:mid]) right, rc = merge_sort(arr[mid:]) merged = [] comparisons = lc + rc i = j = 0 while i < len(left) and j < len(right): comparisons += 1 if left[i] <= right[j]: merged.append(left[i]); i += 1 else: merged.append(right[j]); j += 1 merged += left[i:] + right[j:] return merged, comparisons",human_written_extended,human code_human_ext_001,human,code,python,"import time from functools import wraps def ttl_cache(seconds=60): cache = {} def decorator(fn): @wraps(fn) def wrapper(*args): now = time.time() if args in cache: result, ts = cache[args] if now - ts < seconds: return result result = fn(*args) cache[args] = (result, now) return result wrapper.cache = cache # expose for testing return wrapper return decorator # usage: @ttl_cache(seconds=300)",human_written_extended,human code_human_ext_002,human,code,javascript,"// exponential backoff retry - learned this pattern from a blog post // doubles wait time each attempt, adds jitter to avoid thundering herd async function retry(fn, maxAttempts = 3, baseDelay = 1000) { let lastErr; for (let attempt = 0; attempt < maxAttempts; attempt++) { try { return await fn(); } catch (err) { lastErr = err; if (attempt === maxAttempts - 1) break; const delay = baseDelay * Math.pow(2, attempt) + Math.random() * 100; await new Promise(r => setTimeout(r, delay)); } } throw lastErr; }",human_written_extended,human code_human_ext_003,human,code,python,"# simple rate limiter using a sliding window import time from collections import deque class RateLimiter: def __init__(self, max_calls, period): self.max_calls = max_calls self.period = period self.calls = deque() def allow(self): now = time.time() # drop old calls outside window while self.calls and now - self.calls[0] > self.period: self.calls.popleft() if len(self.calls) < self.max_calls: self.calls.append(now) return True return False",human_written_extended,human code_human_ext_004,human,code,javascript,"function flatten(arr, depth = Infinity) { // could use arr.flat(depth) but writing it out for clarity if (depth === 0) return arr.slice(); return arr.reduce((acc, val) => { if (Array.isArray(val)) { acc.push(...flatten(val, depth - 1)); } else { acc.push(val); } return acc; }, []); } // flatten([1,[2,[3,[4]]]], 1) => [1,2,[3,[4]]] // flatten([1,[2,[3,[4]]]]) => [1,2,3,4]",human_written_extended,human code_ai_ext_000,ai,code,python,"def merge_sort(arr): comparisons = [0] def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): comparisons[0] += 1 if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result def sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = sort(arr[:mid]) right = sort(arr[mid:]) return merge(left, right) sorted_arr = sort(arr) return sorted_arr, comparisons[0] if __name__ == ""__main__"": test_cases = [ [64, 34, 25, 12, 22, 11, 90], [1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [1], [], [3, 3, 3, 1, 1], ] for test in test_cases: sorted_list, num_comparisons = merge_sort(test) print(f""Original: {test}"") print(f""Sorted: {sorted_list}"") print(f""Number of comparisons: {num_comparisons}"") print(""-"" * 40)",claude-sonnet-4-6,claude code_ai_ext_001,ai,code,python,"from collections import defaultdict, deque import heapq from typing import Optional class DirectedGraph: def __init__(self): self.graph = defaultdict(list) self.vertices = set() self.weights = {} def add_vertex(self, vertex): """"""Add a vertex to the graph."""""" self.vertices.add(vertex) if vertex not in self.graph: self.graph[vertex] = [] def add_edge(self, source, destination, weight=1): """"""Add a directed edge from source to destination with optional weight."""""" self.vertices.add(source) self.vertices.add(destination) if destination not in self.graph[source]: self.graph[source].append(destination) if destination not in self.graph: self.graph[destination] = [] self.weights[(source, destination)] = weight def remove_edge(self, source, destination): """"""Remove a directed edge from source to destination."""""" if source in self.graph and destination in self.graph[source]: self.graph[source].remove(destination) self.weights.pop((source, destination), None) def remove_vertex(self, vertex): """"""Remove a vertex and all its associated edges."""""" if vertex in self.graph: del self.graph[vertex] for v in self.graph: if vertex in self.graph[v]: self.graph[v].remove(vertex) self.vertices.discard(vertex) keys_to_remove = [key for key in self.weights if vertex in key] for key in keys_to_remove: del self.weights[key] def has_cycle(self): """""" Detect if the directed graph contains a cycle using DFS. Returns True if a cycle exists, False otherwise. """""" WHITE, GRAY, BLACK = 0, 1, 2 color = {v: WHITE for v in self.vertices} def dfs(vertex): color[vertex] = GRAY for neighbor in self.graph[vertex]: if color[neighbor] == GRAY: return True if color[neighbor] == WHITE and dfs(neighbor): return True color[vertex] = BLACK return False for vertex in self.vertices: if color[vertex] == WHITE: if dfs(vertex): return True return False def find_cycle(self): """""" Find and return a cycle in the graph if one exists. Returns the cycle as a list of vertices, or None if no cycle exists. """""" WHITE, GRAY, BLACK = 0, 1, 2 color",claude-sonnet-4-6,claude code_ai_ext_002,ai,code,python,"import time import functools from typing import Any, Callable, Optional from collections import OrderedDict def ttl_cache(ttl: float = 60.0, maxsize: Optional[int] = None): """""" A decorator that caches function results with a configurable TTL expiration. Args: ttl: Time-to-live in seconds for cached results (default: 60 seconds) maxsize: Maximum number of entries in cache (default: None = unlimited) """""" def decorator(func: Callable) -> Callable: cache: OrderedDict = OrderedDict() cache_times: dict = {} @functools.wraps(func) def wrapper(*args, **kwargs) -> Any: # Create a hashable cache key from arguments key = _make_cache_key(args, kwargs) current_time = time.time() # Check if result is in cache and not expired if key in cache: if current_time - cache_times[key] < ttl: # Move to end to maintain LRU order cache.move_to_end(key) return cache[key] else: # Entry has expired, remove it del cache[key] del cache_times[key] # Call the function and cache the result result = func(*args, **kwargs) # If maxsize is set and cache is full, remove oldest entry if maxsize is not None and len(cache) >= maxsize: oldest_key = next(iter(cache)) del cache[oldest_key] del cache_times[oldest_key] cache[key] = result cache_times[key] = current_time return result def _make_cache_key(args, kwargs): """"""Create a hashable key from function arguments."""""" try: key_parts = [args] if kwargs: key_parts.append(tuple(sorted(kwargs.items()))) return hash(tuple(key_parts)) except TypeError: # Fallback for unhashable types return hash(str(args) + str(sorted(kwargs.items()) if kwargs else """")) def cache_info() -> dict: """"""Return information about the cache."""""" current_time = time.time() valid_entries = sum( 1 for key in cache if current_time - cache_times[key] < ttl ) return { ""total_entries"": len(cache), ""valid_entries"": valid_entries, ""expired_entries"": len(cache) - valid_entries, ""maxsize"": maxsize, ""ttl"": ttl } def cache_clear() -> None:",claude-sonnet-4-6,claude code_ai_ext_003,ai,code,python,"import re from dataclasses import dataclass from enum import Enum from typing import List class TokenType(Enum): SENTENCE = ""SENTENCE"" WORD = ""WORD"" PUNCTUATION = ""PUNCTUATION"" WHITESPACE = ""WHITESPACE"" NUMBER = ""NUMBER"" @dataclass class Token: type: TokenType value: str position: int def __repr__(self): return f""Token(type={self.type.value}, value={self.value!r}, position={self.position})"" class Tokenizer: def __init__(self): self.sentence_endings = re.compile(r'(?<=[.!?])\s+(?=[A-Z])|(?<=[.!?])\s*$') self.word_pattern = re.compile(r""[a-zA-Z]+(?:'[a-zA-Z]+)*"") self.number_pattern = re.compile(r'\d+(?:\.\d+)?') self.punctuation_pattern = re.compile(r'[^\w\s]') self.whitespace_pattern = re.compile(r'\s+') def tokenize_into_sentences(self, text: str) -> List[str]: """"""Split text into sentences."""""" sentence_pattern = re.compile(r'(?<=[.!?])\s+') sentences = sentence_pattern.split(text.strip()) return [s.strip() for s in sentences if s.strip()] def tokenize_into_words(self, text: str) -> List[Token]: """"""Split text into word tokens."""""" tokens = [] for match in self.word_pattern.finditer(text): tokens.append(Token( type=TokenType.WORD, value=match.group(), position=match.start() )) return tokens def tokenize(self, text: str) -> dict: """""" Full tokenization returning sentences, words, and punctuation tokens. """""" result = { 'sentences': [], 'tokens': [] } sentences = self.tokenize_into_sentences(text) result['sentences'] = sentences position = 0 i = 0 while i < len(text): char = text[i] word_match = self.word_pattern.match(text, i) if word_match: result['tokens'].append(Token( type=TokenType.WORD, value=word_match.group(), position=i )) i = word_match.end() continue number_match = self.number_pattern.match(text, i) if number_match: result['tokens'].append(Token( type=TokenType.NUMBER,",claude-sonnet-4-6,claude code_ai_ext_004,ai,code,javascript,"function retry(asyncOperation, maxAttempts = 3, baseDelay = 1000) { return new Promise((resolve, reject) => { const attempt = (attemptNumber) => { asyncOperation() .then(resolve) .catch((error) => { if (attemptNumber >= maxAttempts) { reject( new Error( `Operation failed after ${maxAttempts} attempts. Last error: ${error.message}` ) ); return; } const delay = baseDelay * Math.pow(2, attemptNumber - 1); console.log( `Attempt ${attemptNumber} failed. Retrying in ${delay}ms...` ); setTimeout(() => { attempt(attemptNumber + 1); }, delay); }); }; attempt(1); }); } // ==================== USAGE EXAMPLES ==================== // Example 1: Simulating a flaky API call function createFlakyOperation(failTimes = 2) { let callCount = 0; return function flakyOperation() { callCount++; return new Promise((resolve, reject) => { if (callCount <= failTimes) { reject(new Error(`Simulated failure on attempt ${callCount}`)); } else { resolve(`Success on attempt ${callCount}`); } }); }; } // Example 2: With jitter (randomized delay to prevent thundering herd) function retryWithJitter( asyncOperation, maxAttempts = 3, baseDelay = 1000, jitterFactor = 0.1 ) { return new Promise((resolve, reject) => { const attempt = (attemptNumber) => { asyncOperation() .then(resolve) .catch((error) => { if (attemptNumber >= maxAttempts) { reject( new Error( `Operation failed after ${maxAttempts} attempts. Last error: ${error.message}` ) ); return; } const exponentialDelay = baseDelay * Math.pow(2, attemptNumber - 1); const jitter = exponentialDelay * jitterFactor * Math.random(); const delay = exponentialDelay + jitter; console.log( `Attempt ${attemptNumber} failed. Retrying in ${Math.round(delay)}ms (with jitter)...` ); setTimeout(() => { attempt(attemptNumber + 1); }, delay); }); }; attempt(1); }); } // Example 3: With abort signal support function retryWithAbort( asyncOperation, maxAttempts = 3, baseDe",claude-sonnet-4-6,claude code_ai_ext_005,ai,code,javascript,"class Observable { constructor() { this.subscribers = {}; } subscribe(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); // Return unsubscribe function return { unsubscribe: () => { this.subscribers[event] = this.subscribers[event].filter( (cb) => cb !== callback ); }, }; } publish(event, data) { if (!this.subscribers[event]) { return; } this.subscribers[event].forEach((callback) => { callback(data); }); } unsubscribeAll(event) { if (event) { delete this.subscribers[event]; } else { this.subscribers = {}; } } } // Example usage const observable = new Observable(); // Subscribe to events const subscription1 = observable.subscribe(""userLoggedIn"", (data) => { console.log(`Subscriber 1: User logged in - ${data.username}`); }); const subscription2 = observable.subscribe(""userLoggedIn"", (data) => { console.log(`Subscriber 2: Welcome, ${data.username}!`); }); const subscription3 = observable.subscribe(""dataUpdated"", (data) => { console.log(`Data updated: ${JSON.stringify(data)}`); }); // Publish events console.log(""--- Publishing userLoggedIn event ---""); observable.publish(""userLoggedIn"", { username: ""JohnDoe"" }); console.log(""\n--- Publishing dataUpdated event ---""); observable.publish(""dataUpdated"", { id: 1, value: ""new value"" }); // Unsubscribe subscriber 1 console.log(""\n--- Unsubscribing subscriber 1 ---""); subscription1.unsubscribe(); console.log(""\n--- Publishing userLoggedIn event after unsubscribe ---""); observable.publish(""userLoggedIn"", { username: ""JaneDoe"" }); // Unsubscribe all from userLoggedIn console.log(""\n--- Unsubscribing all from userLoggedIn ---""); observable.unsubscribeAll(""userLoggedIn""); console.log(""\n--- Publishing userLoggedIn event after unsubscribeAll ---""); observable.publish(""userLoggedIn"", { username: ""TestUser"" }); console.log(""\n--- Publishing dataUpdated event (should still work) ---""); observable.publish(""dataUpdated"", { id: 2, value: ""another value"" });",claude-sonnet-4-6,claude code_ai_ext_006,ai,code,python,"def parse_and_evaluate(expression: str) -> float: """""" Parses and evaluates a simple arithmetic expression string without using eval(). Supports: +, -, *, /, parentheses, and floating point numbers. """""" tokens = tokenize(expression) pos = 0 def peek(): nonlocal pos if pos < len(tokens): return tokens[pos] return None def consume(): nonlocal pos token = tokens[pos] pos += 1 return token def parse_expression(): """"""Handle + and - (lowest precedence)"""""" left = parse_term() while peek() in ('+', '-'): op = consume() right = parse_term() if op == '+': left += right else: left -= right return left def parse_term(): """"""Handle * and / (higher precedence)"""""" left = parse_factor() while peek() in ('*', '/'): op = consume() right = parse_factor() if op == '*': left *= right else: if right == 0: raise ZeroDivisionError(""Division by zero"") left /= right return left def parse_factor(): """"""Handle numbers, parentheses, and unary operators"""""" token = peek() if token is None: raise ValueError(""Unexpected end of expression"") # Handle unary minus and plus if token == '-': consume() return -parse_factor() if token == '+': consume() return parse_factor() # Handle parentheses if token == '(': consume() # consume '(' result = parse_expression() if peek() != ')': raise ValueError(""Missing closing parenthesis"") consume() # consume ')' return result # Handle numbers try: consume() return float(token) except ValueError: raise ValueError(f""Unexpected token: {token}"") result = parse_expression() if pos < len(tokens): raise ValueError(f""Unexpected token: {tokens[pos]}"") return result def tokenize(expression: str) -> list: """""" Converts expression string into list of tokens (numbers and operators). """""" tokens = [] i = 0 expression = expression.replace(' ', '') # Remove spaces while i < len(expression): char = expression[i] # Handle numbers (including decimals) if char.isdigit() or (char == '.' and i + 1 < len(expression)",claude-sonnet-4-6,claude code_ai_ext_007,ai,code,python,"import threading from typing import Any, Optional class ThreadSafeQueue: def __init__(self, maxsize: int = 0): self._queue = [] self._maxsize = maxsize self._mutex = threading.Lock() self._not_empty = threading.Condition(self._mutex) self._not_full = threading.Condition(self._mutex) self._size = 0 def put(self, item: Any, block: bool = True, timeout: Optional[float] = None) -> None: with self._not_full: if self._maxsize > 0: if not block: if self._size >= self._maxsize: raise QueueFull(""Queue is full"") elif timeout is None: while self._size >= self._maxsize: self._not_full.wait() elif timeout < 0: raise ValueError(""'timeout' must be a non-negative number"") else: end_time = threading.Event() remaining = timeout while self._size >= self._maxsize: if not self._not_full.wait(remaining): raise QueueFull(""Queue is full"") remaining = timeout - remaining self._queue.append(item) self._size += 1 self._not_empty.notify() def get(self, block: bool = True, timeout: Optional[float] = None) -> Any: with self._not_empty: if not block: if self._size == 0: raise QueueEmpty(""Queue is empty"") elif timeout is None: while self._size == 0: self._not_empty.wait() elif timeout < 0: raise ValueError(""'timeout' must be a non-negative number"") else: import time end_time = time.monotonic() + timeout while self._size == 0: remaining = end_time - time.monotonic() if remaining <= 0: raise QueueEmpty(""Queue is empty"") self._not_empty.wait(remaining) item = self._queue.pop(0) self._size -= 1 self._not_full.notify() return item def put_nowait(self, item: Any) -> None: self.put(item, block=False) def get_nowait(self) -> Any: return self.get(block=False) def empty(self) -> bool: with self._mutex: return self._size == 0 def full(self) -> bool: with self._mutex: if self._maxsize <= 0: return False return self._size >= self._maxsize def qsize(self) -> int:",claude-sonnet-4-6,claude code_ai_ext_008,ai,code,javascript,"function flattenArray(arr, depth = Infinity) { if (depth === 0) { return arr.slice(); } return arr.reduce((result, item) => { if (Array.isArray(item) && depth > 0) { result.push(...flattenArray(item, depth - 1)); } else { result.push(item); } return result; }, []); } // Test examples const nestedArray = [1, [2, [3, [4, [5]]]]]; console.log(""Original array:"", JSON.stringify(nestedArray)); console.log(""Flatten depth 1:"", JSON.stringify(flattenArray(nestedArray, 1))); console.log(""Flatten depth 2:"", JSON.stringify(flattenArray(nestedArray, 2))); console.log(""Flatten depth 3:"", JSON.stringify(flattenArray(nestedArray, 3))); console.log(""Flatten fully (Infinity):"", JSON.stringify(flattenArray(nestedArray))); const complexArray = [1, [2, 3], [4, [5, 6]], [7, [8, [9, [10]]]]]; console.log(""\nComplex array:"", JSON.stringify(complexArray)); console.log(""Flatten depth 1:"", JSON.stringify(flattenArray(complexArray, 1))); console.log(""Flatten depth 2:"", JSON.stringify(flattenArray(complexArray, 2))); console.log(""Flatten fully:"", JSON.stringify(flattenArray(complexArray))); // Alternative using built-in Array.flat() for comparison console.log(""\nUsing built-in Array.flat():""); console.log(""Flatten depth 1:"", JSON.stringify(nestedArray.flat(1))); console.log(""Flatten fully:"", JSON.stringify(nestedArray.flat(Infinity)));",claude-sonnet-4-6,claude code_ai_ext_009,ai,code,python,"import time from collections import deque from threading import Lock class RateLimiter: """"""A simple rate limiter that allows n calls per time window."""""" def __init__(self, max_calls: int, time_window: float): """""" Initialize the rate limiter. Args: max_calls: Maximum number of calls allowed per time window time_window: Time window in seconds """""" self.max_calls = max_calls self.time_window = time_window self.calls = deque() self.lock = Lock() def is_allowed(self) -> bool: """""" Check if a call is allowed based on the rate limit. Returns: True if the call is allowed, False otherwise """""" with self.lock: now = time.time() # Remove calls outside the time window while self.calls and self.calls[0] <= now - self.time_window: self.calls.popleft() # Check if we're within the rate limit if len(self.calls) < self.max_calls: self.calls.append(now) return True return False def wait_and_call(self) -> float: """""" Wait until a call is allowed and record it. Returns: The time waited in seconds """""" start_time = time.time() while not self.is_allowed(): with self.lock: if self.calls: # Calculate how long to wait wait_time = self.calls[0] + self.time_window - time.time() if wait_time > 0: time.sleep(wait_time) else: time.sleep(0.001) return time.time() - start_time def remaining_calls(self) -> int: """""" Get the number of remaining calls allowed in the current window. Returns: Number of remaining calls """""" with self.lock: now = time.time() # Remove calls outside the time window while self.calls and self.calls[0] <= now - self.time_window: self.calls.popleft() return self.max_calls - len(self.calls) def reset(self): """"""Reset the rate limiter by clearing all recorded calls."""""" with self.lock: self.calls.clear() def __repr__(self) -> str: return f""RateLimiter(max_calls={self.max_calls}, time_window={self.time_window}s)"" def rate_limited(max_calls: int, time_window: float): """""" Decorator that",claude-sonnet-4-6,claude code_human_v2_000,human,code,python,"# min heap - wrote this for an interview prep session # probably not the cleanest but it works class MinHeap: def __init__(self): self.h = [] def insert(self, val): self.h.append(val) i = len(self.h) - 1 # bubble up while i > 0: parent = (i - 1) // 2 if self.h[parent] > self.h[i]: self.h[parent], self.h[i] = self.h[i], self.h[parent] i = parent else: break def extract_min(self): if not self.h: return None if len(self.h) == 1: return self.h.pop() min_val = self.h[0] self.h[0] = self.h.pop() self._sink(0) return min_val def _sink(self, i): n = len(self.h) while True: smallest = i l, r = 2*i+1, 2*i+2 if l < n and self.h[l] < self.h[smallest]: smallest = l if r < n and self.h[r] < self.h[smallest]: smallest = r if smallest == i: break self.h[i], self.h[smallest] = self.h[smallest], self.h[i] i = smallest",human_written_v2,human code_human_v2_001,human,code,python,"from collections import defaultdict import heapq # dijkstra - took me a while to get the visited set right def shortest_path(graph, start, end): dist = {start: 0} pq = [(0, start)] prev = {} visited = set() while pq: d, node = heapq.heappop(pq) if node in visited: continue visited.add(node) if node == end: # reconstruct path path = [] cur = end while cur in prev: path.append(cur) cur = prev[cur] path.append(start) return d, path[::-1] for neighbor, weight in graph[node]: new_dist = d + weight if neighbor not in dist or new_dist < dist[neighbor]: dist[neighbor] = new_dist prev[neighbor] = node heapq.heappush(pq, (new_dist, neighbor)) return float('inf'), [] # no path found",human_written_v2,human code_human_v2_002,human,code,javascript,"// LRU cache using Map (Maps preserve insertion order in JS) // O(1) get and put - the trick is moving accessed keys to end class LRUCache { constructor(capacity) { this.cap = capacity this.cache = new Map() } get(key) { if (!this.cache.has(key)) return -1 // move to end (most recently used) const val = this.cache.get(key) this.cache.delete(key) this.cache.set(key, val) return val } put(key, val) { if (this.cache.has(key)) this.cache.delete(key) else if (this.cache.size >= this.cap) { // delete least recently used (first item) this.cache.delete(this.cache.keys().next().value) } this.cache.set(key, val) } }",human_written_v2,human code_human_v2_003,human,code,python,"# bloom filter - built this for a distributed dedup project # false positive rate is approximate, real impl would tune m and k more carefully import math, hashlib class BloomFilter: def __init__(self, capacity, fp_rate=0.01): self.capacity = capacity self.fp_rate = fp_rate # standard formula for optimal m and k m = -capacity * math.log(fp_rate) / (math.log(2) ** 2) self.m = int(m) self.k = int((self.m / capacity) * math.log(2)) self.bits = bytearray(self.m) def _hashes(self, item): # use two hash functions to simulate k h1 = int(hashlib.md5(item.encode()).hexdigest(), 16) h2 = int(hashlib.sha1(item.encode()).hexdigest(), 16) return [(h1 + i * h2) % self.m for i in range(self.k)] def add(self, item): for pos in self._hashes(item): self.bits[pos] = 1 def __contains__(self, item): return all(self.bits[pos] for pos in self._hashes(item))",human_written_v2,human code_human_v2_004,human,code,javascript,"// deep merge - handles the annoying array edge cases // arrays are replaced not merged (change concat to ... if you want merge behavior) function deepMerge(target, source) { const result = { ...target } for (const key of Object.keys(source)) { if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) { if (target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) { result[key] = deepMerge(target[key], source[key]) } else { result[key] = deepMerge({}, source[key]) } } else { result[key] = source[key] } } return result } // test: deepMerge({a:{b:1},c:3}, {a:{d:2},e:4}) => {a:{b:1,d:2},c:3,e:4}",human_written_v2,human code_human_v2_005,human,code,python,"# run length encoding - simple but surprisingly useful for compression def rle_encode(s): if not s: return '' result = [] count = 1 for i in range(1, len(s)): if s[i] == s[i-1]: count += 1 else: result.append(f'{count}{s[i-1]}' if count > 1 else s[i-1]) count = 1 result.append(f'{count}{s[-1]}' if count > 1 else s[-1]) return ''.join(result) def rle_decode(s): result = [] i = 0 while i < len(s): if s[i].isdigit(): j = i while j < len(s) and s[j].isdigit(): j += 1 result.append(s[j] * int(s[i:j])) i = j + 1 else: result.append(s[i]) i += 1 return ''.join(result)",human_written_v2,human code_human_v2_006,human,code,javascript,"// simple event emitter - written from scratch, not using Node's EventEmitter // supports multiple handlers per event, returns unsubscribe function class EventEmitter { #handlers = new Map() // private field on(event, handler) { if (!this.#handlers.has(event)) { this.#handlers.set(event, new Set()) } this.#handlers.get(event).add(handler) // return cleanup fn return () => this.off(event, handler) } off(event, handler) { this.#handlers.get(event)?.delete(handler) } emit(event, ...args) { this.#handlers.get(event)?.forEach(h => h(...args)) } once(event, handler) { const wrapper = (...args) => { handler(...args) this.off(event, wrapper) } return this.on(event, wrapper) } }",human_written_v2,human code_human_v2_007,human,code,python,"# topological sort - Kahn's algorithm # used this in a build system dependency resolver from collections import deque, defaultdict def topo_sort(nodes, edges): """""" nodes: list of node ids edges: list of (from, to) tuples meaning 'from' must come before 'to' returns sorted list or raises ValueError on cycle """""" in_degree = defaultdict(int) adj = defaultdict(list) for u, v in edges: adj[u].append(v) in_degree[v] += 1 for n in nodes: in_degree.setdefault(n, 0) queue = deque(n for n in nodes if in_degree[n] == 0) result = [] while queue: node = queue.popleft() result.append(node) for neighbor in adj[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) if len(result) != len(nodes): raise ValueError(""Graph has a cycle"") return result",human_written_v2,human code_human_v2_008,human,code,python,"# flatten nested dict - useful for logging and config diffing def flatten_dict(d, prefix='', sep='.'): items = {} for k, v in d.items(): new_key = f""{prefix}{sep}{k}"" if prefix else k if isinstance(v, dict) and v: items.update(flatten_dict(v, new_key, sep)) else: items[new_key] = v return items def unflatten_dict(d, sep='.'): result = {} for key, val in d.items(): parts = key.split(sep) cur = result for part in parts[:-1]: cur = cur.setdefault(part, {}) cur[parts[-1]] = val return result",human_written_v2,human code_human_v2_009,human,code,javascript,"// priority queue backed by binary heap // used min-heap by default (smaller priority = higher priority) class PriorityQueue { #heap = [] #compare constructor(compare = (a, b) => a - b) { this.#compare = compare } get size() { return this.#heap.length } peek() { return this.#heap[0] } push(val) { this.#heap.push(val) this.#bubbleUp(this.#heap.length - 1) } pop() { const top = this.#heap[0] const last = this.#heap.pop() if (this.#heap.length > 0) { this.#heap[0] = last this.#sinkDown(0) } return top } #bubbleUp(i) { while (i > 0) { const parent = (i - 1) >> 1 if (this.#compare(this.#heap[i], this.#heap[parent]) < 0) { ;[this.#heap[i], this.#heap[parent]] = [this.#heap[parent], this.#heap[i]] i = parent } else break } } #sinkDown(i) { const n = this.#heap.length while (true) { let smallest = i const l = 2*i+1, r = 2*i+2 if (l < n && this.#compare(this.#heap[l], this.#heap[smallest]) < 0) smallest = l if (r < n && this.#compare(this.#heap[r], this.#heap[smallest]) < 0) smallest = r if (smallest === i) break ;[this.#heap[i], this.#heap[smallest]] = [this.#heap[smallest], this.#heap[i]] i = smallest } } }",human_written_v2,human