20 coding tasks scored by two neutral LLM judges. Click any row to see the code.
Brewmode runs locally at $0/call. Claude costs ~$0.03/call. Both judges are neutral third parties.
| Task | FR | BM | Base | FR | BM | Base | |
|---|---|---|---|---|---|---|---|
| GPT-5.4-mini | Gemini 3.1 Flash | ||||||
| Trie Autocomplete ▸ | 9 | 10 | 8 | 9 | 9 | 9 | |
|
CLAUDE SONNET 4.6 from typing import Dict, List, Optional
class TrieNode:
def __init__(self) -> None:
self.children: Dict[str, 'TrieNode'] = {}
self.is_end_of_word: bool = False
class Trie:
def __init__(self) -> None:
self.root: TrieNode = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word: str) -> bool:
node = self._find_node(word)
return node is not None and node.is_end_of_word
def _find_node(self, word: str) -> Optional[TrieNode]:
node = self.root
for char in word:
if char not in node.children:
return None
node = node.children[char]
return node
def autocomplete(self, prefix: str) -> List[str]:
node = self._find_node(prefix)
if node is None:
return []
results = []
self._dfs(node, prefix, results)
return results
def _dfs(self, node: TrieNode, current_word: str, results: List[str]) -> None:
if node.is_end_of_word:
results.append(current_word)
for char, child_node in node.children.items():
self._dfs(child_node, current_word + char, results)BREWMODE 8B from typing import Dict, Optional, List
class TrieNode:
def __init__(self) -> None:
self.children: Dict[str, TrieNode] = {}
self.is_end_of_word: bool = False
class Trie:
def __init__(self) -> None:
self.root: TrieNode = TrieNode()
def insert(self, word: str) -> None:
"""
Insert a word into the Trie.
Args:
word (str): The word to insert.
"""
node: TrieNode = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word: str) -> bool:
"""
Search for a word in the Trie.
Args:
word (str): The word to search for.
Returns:
bool: True if the word exists in the Trie, False otherwise.
"""
node: TrieNode = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
def starts_with(self, prefix: str) -> bool:
"""
Check if any word in the Trie starts with the given prefix.
Args:
prefix (str): The prefix to check.
Returns:
bool: True if there are words starting with the prefix, False otherwise.
"""
node: TrieNode = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def autocomplete(self, prefix: str) -> List[str]:
"""
Get all words that start with the given prefix.
Args:
prefix (str): The prefix to autocomplete.
Returns:
List[str]: A list of words that start with the given prefix.
"""
results: List[str] = []
node: TrieNode = self.root
for char in prefix:
if char not in node.children:
return results
node = node.children[char]
self._collect_words(node, prefix, results)
return results
def _collect_words(self, node: TrieNode, prefix: str, results: List[str]) -> None:
"""
Helper method to collect all words starting from the given node.
Args:
node (TrieNode): The current node in the Trie.
prefix (str): The current prefix being built.
results (List[str]): List to store the collected words.
"""
if node.is_end_of_word:
results.append(prefix)
for char, child_node in node.children.items():
self._collect_words(child_node, prefix + char, results)QWEN3-8B BASE from typing import Optional, List
class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.is_end: bool = False
class Trie:
def __init__(self):
self.root: TrieNode = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
def starts_with(self, prefix: str) -> bool:
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def autocomplete(self, prefix: str) -> List[str]:
prefix_node = self.root
for char in prefix:
if char not in prefix_node.children:
return []
prefix_node = prefix_node.children[char]
result: List[str] = []
self._collect_words(prefix_node, prefix, result)
return result
def _collect_words(self, node: TrieNode, prefix: str, result: List[str]) -> None:
if node.is_end:
result.append(prefix)
for char, child in node.children.items():
self._collect_words(child, prefix + char, result) | |||||||
| Interval Scheduling ▸ | 9 | 9 | 6 | 9 | 9 | 3 | |
|
CLAUDE SONNET 4.6 from typing import List, Tuple
def max_non_overlapping_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals by end time
sorted_intervals = sorted(intervals, key=lambda x: x[1])
result = [sorted_intervals[0]]
last_end = sorted_intervals[0][1]
for start, end in sorted_intervals[1:]:
if start >= last_end:
result.append((start, end))
last_end = end
return resultBREWMODE 8B from typing import List, Tuple
def maximum_non_overlapping_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals by their end times
sorted_intervals = sorted(intervals, key=lambda x: x[1])
selected = [sorted_intervals[0]]
last_end = sorted_intervals[0][1]
for interval in sorted_intervals[1:]:
if interval[0] >= last_end:
selected.append(interval)
last_end = interval[1]
return selectedQWEN3-8B BASE from typing import List, Tuple
def max_non_overlapping_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals by start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
selected = [sorted_intervals[0]]
for current in sorted_intervals[1:]:
last = selected[-1]
if current[0] >= last[1]:
selected.append(current)
return selected | |||||||
| Graph BFS Shortest Path ▸ | 9 | 8 | 7 | 8 | 6 | 7 | |
|
CLAUDE SONNET 4.6 from collections import deque
from typing import Dict, List, Optional, Set
def shortest_path_bfs(graph: Dict[str, List[str]], start: str, end: str) -> Optional[List[str]]:
if start == end:
return [start]
queue = deque([(start, [start])])
visited: Set[str] = {start}
while queue:
current, path = queue.popleft()
for neighbor in graph.get(current, []):
if neighbor == end:
return path + [neighbor]
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, path + [neighbor]))
return NoneBREWMODE 8B from collections import deque
from typing import Dict, List, Optional, Set, Union
def shortest_path_bfs(
graph: Dict[Union[str, int], List[Union[str, int]]],
start: Union[str, int],
end: Union[str, int]
) -> Optional[List[Union[str, int]]]:
"""
Find the shortest path in an unweighted graph using BFS.
Args:
graph: Adjacency list representation of the graph.
start: Starting node for the path.
end: Target node for the path.
Returns:
List of nodes representing the shortest path from start to end.
Returns None if no path exists.
"""
if start == end:
return []
visited: Set[Union[str, int]] = set()
queue: deque = deque([(start, [start])])
visited.add(start)
parent: Dict[Union[str, int], Union[str, int]] = {}
while queue:
current, path = queue.popleft()
for neighbor in graph[current]:
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = current
queue.append((neighbor, path + [neighbor]))
if neighbor == end:
return path + [end]
return NoneQWEN3-8B BASE from typing import List, Dict, Tuple, Optional
from collections import deque
def shortest_path_bfs(
graph: Dict[int, List[int]],
start: int,
end: int
) -> List[int]:
if start == end:
return [start]
visited = set()
parent = {}
queue = deque([start])
visited.add(start)
while queue:
current = queue.popleft()
for neighbor in graph[current]:
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = current
queue.append(neighbor)
if neighbor == end:
queue.clear()
break
# Reconstruct path
path = []
current = end
while current is not None:
path.append(current)
current = parent.get(current)
return path[::-1] | |||||||
| Binary Search Variants ▸ | 9 | 8 | 7 | 9 | 8 | 8 | |
|
CLAUDE SONNET 4.6 from typing import List, Optional
def binary_search(arr: List[int], target: int) -> int:
"""
Performs binary search on a sorted array.
Returns index of target if found, -1 otherwise.
"""
if not arr:
return -1
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def find_first_occurrence(arr: List[int], target: int) -> int:
"""
Finds the first occurrence of target in a sorted array with duplicates.
Returns index of first occurrence if found, -1 otherwise.
"""
if not arr:
return -1
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # Continue searching left for first occurrence
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
def find_last_occurrence(arr: List[int], target: int) -> int:
"""
Finds the last occurrence of target in a sorted array with duplicates.
Returns index of last occurrence if found, -1 otherwise.
"""
if not arr:
return -1
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
result = mid
left = mid + 1 # Continue searching right for last occurrence
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return resultBREWMODE 8B from typing import List, Optional
def binary_search(nums: List[int], target: int) -> int:
"""
Perform binary search on a sorted list to find the index of a target value.
Args:
nums: A sorted list of integers.
target: The integer value to search for.
Returns:
The index of the target if found, -1 otherwise.
Edge Cases:
- Empty list: returns -1
- Single element: returns 0 if matches target, -1 otherwise
- Target at beginning/end of list
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def find_first_occurrence(nums: List[int], target: int) -> Optional[int]:
"""
Find the first occurrence of a target in a sorted list.
Args:
nums: A sorted list of integers.
target: The integer value to search for.
Returns:
The index of the first occurrence of the target if found, None otherwise.
Edge Cases:
- Empty list: returns None
- Single element: returns 0 if matches target, None otherwise
- Target at beginning/end of list
"""
left, right = 0, len(nums) - 1
result = None
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
result = mid
right = mid - 1 # Continue searching left
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
def find_last_occurrence(nums: List[int], target: int) -> Optional[int]:
"""
Find the last occurrence of a target in a sorted list.
Args:
nums: A sorted list of integers.
target: The integer value to search for.
Returns:
The index of the last occurrence of the target if found, None otherwise.
Edge Cases:
- Empty list: returns None
- Single element: returns 0 if matches target, None otherwise
- Target at beginning/end of list
"""
left, right = 0, len(nums) - 1
result = None
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
result = mid
left = mid + 1 # Continue searching right
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return resultQWEN3-8B BASE from typing import List, Optional
def binary_search(arr: List[int], target: int) -> Optional[int]:
"""
Perform binary search on a sorted list to find the index of the target.
Returns the index if found, otherwise returns None.
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return None
def find_first_occurrence(arr: List[int], target: int) -> Optional[int]:
"""
Find the first occurrence of the target in a sorted list.
Returns the index if found, otherwise returns None.
"""
left, right = 0, len(arr) - 1
result = None
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # Look for earlier occurrences
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
def find_last_occurrence(arr: List[int], target: int) -> Optional[int]:
"""
Find the last occurrence of the target in a sorted list.
Returns the index if found, otherwise returns None.
"""
left, right = 0, len(arr) - 1
result = None
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
left = mid + 1 # Look for later occurrences
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result | |||||||
| Min Heap ▸ | 9 | 8 | 7 | 9 | 7 | 8 | |
|
CLAUDE SONNET 4.6 from typing import TypeVar, Generic, List, Optional
T = TypeVar('T')
class MinHeap(Generic[T]):
def __init__(self) -> None:
self._heap: List[T] = []
def __len__(self) -> int:
return len(self._heap)
def __bool__(self) -> bool:
return len(self._heap) > 0
def _parent(self, index: int) -> int:
return (index - 1) // 2
def _left_child(self, index: int) -> int:
return 2 * index + 1
def _right_child(self, index: int) -> int:
return 2 * index + 2
def _has_left_child(self, index: int) -> bool:
return self._left_child(index) < len(self._heap)
def _has_right_child(self, index: int) -> bool:
return self._right_child(index) < len(self._heap)
def _has_parent(self, index: int) -> bool:
return self._parent(index) >= 0
def _swap(self, i: int, j: int) -> None:
self._heap[i], self._heap[j] = self._heap[j], self._heap[i]
def _heapify_up(self, index: int) -> None:
while (self._has_parent(index) and
self._heap[self._parent(index)] > self._heap[index]):
self._swap(index, self._parent(index))
index = self._parent(index)
def _heapify_down(self, index: int) -> None:
while self._has_left_child(index):
smaller_child_index = self._left_child(index)
if (self._has_right_child(index) and
self._heap[self._right_child(index)] < self._heap[smaller_child_index]):
smaller_child_index = self._right_child(index)
if self._heap[index] <= self._heap[smaller_child_index]:
break
self._swap(index, smaller_child_index)
index = smaller_child_index
def push(self, item: T) -> None:
self._heap.append(item)
self._heapify_up(len(self._heap) - 1)
def pop(self) -> T:
if not self._heap:
raise IndexError("pop from empty heap")
if len(self._heap) == 1:
return self._heap.pop()
min_item = self._heap[0]
self._heap[0] = self._heap.pop()
self._heapify_down(0)
return min_item
def peek(self) -> T:
if not self._heap:
raise IndexError("peek from empty heap")
return self._heap[0]
def heapify(self, items: List[T]) -> None:
self._heap = items.copy()
for i in range(len(self._heap) // 2 - 1, -1, -1):
self._heapify_down(i)
@classmethod
def from_list(cls, items: List[T]) -> 'MinHeap[T]':
heap = cls()
heap.heapify(items)
return heapBREWMODE 8B from typing import List, Optional
class PriorityQueue:
def __init__(self, elements: Optional[List[int]] = None):
self.heap: List[int] = []
if elements is not None:
self.heap = elements.copy()
self.heapify()
def heapify(self):
"""Convert the list into a heap in-place."""
n = len(self.heap)
for i in range(n // 2 - 1, -1, -1):
self._sift_down(i, n)
def push(self, value: int):
"""Add a value to the heap and sift it up."""
self.heap.append(value)
self._sift_up(len(self.heap) - 1)
def pop(self) -> int:
"""Remove and return the smallest element."""
if not self.heap:
raise ValueError("Heap is empty")
value = self.heap[0]
self.heap[0] = self.heap[-1]
self.heap.pop()
self._sift_down(0, len(self.heap))
return value
def peek(self) -> int:
"""Return the smallest element without removing it."""
if not self.heap:
raise ValueError("Heap is empty")
return self.heap[0]
def _sift_up(self, index: int):
"""Sift a value up to maintain the heap property."""
while index > 0:
parent = (index - 1) // 2
if self.heap[index] < self.heap[parent]:
self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
index = parent
else:
break
def _sift_down(self, index: int, size: int):
"""Sift a value down to maintain the heap property."""
while True:
left = 2 * index + 1
right = 2 * index + 2
smallest = index
if left < size and self.heap[left] < self.heap[smallest]:
smallest = left
if right < size and self.heap[right] < self.heap[smallest]:
smallest = right
if smallest != index:
self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
index = smallest
else:
breakQWEN3-8B BASE from typing import Generic, TypeVar, List
T = TypeVar('T', bound=int)
class MinHeap(Generic[T]):
def __init__(self) -> None:
self.heap: List[T] = []
def push(self, value: T) -> None:
self.heap.append(value)
self._sift_up(len(self.heap) - 1)
def pop(self) -> T:
if not self.heap:
raise IndexError("Pop from empty heap")
self._swap(0, len(self.heap) - 1)
value = self.heap.pop()
self._sift_down(0)
return value
def peek(self) -> T:
if not self.heap:
raise IndexError("Peek from empty heap")
return self.heap[0]
def heapify(self, iterable: List[T]) -> None:
self.heap = iterable[:]
for i in range((len(self.heap) - 1) // 2, -1, -1):
self._sift_down(i)
def _sift_up(self, index: int) -> None:
parent = (index - 1) // 2
while index > 0 and self.heap[index] < self.heap[parent]:
self._swap(index, parent)
index = parent
parent = (index - 1) // 2
def _sift_down(self, index: int) -> None:
size = len(self.heap)
while True:
left = 2 * index + 1
right = 2 * index + 2
smallest = index
if left < size and self.heap[left] < self.heap[smallest]:
smallest = left
if right < size and self.heap[right] < self.heap[smallest]:
smallest = right
if smallest != index:
self._swap(index, smallest)
index = smallest
else:
break
def _swap(self, i: int, j: int) -> None:
self.heap[i], self.heap[j] = self.heap[j], self.heap[i] | |||||||
| Observable Pattern ▸ | 9 | 8 | 7 | 9 | 7 | 8 | |
|
CLAUDE SONNET 4.6 interface Observer<T> {
update(data: T): void;
}
interface Observable<T> {
subscribe(observer: Observer<T>): void;
unsubscribe(observer: Observer<T>): void;
notify(data: T): void;
}
class ConcreteObservable<T> implements Observable<T> {
private observers: Observer<T>[] = [];
subscribe(observer: Observer<T>): void {
this.observers.push(observer);
}
unsubscribe(observer: Observer<T>): void {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}
notify(data: T): void {
this.observers.forEach(observer => observer.update(data));
}
}
class ConcreteObserver<T> implements Observer<T> {
constructor(private callback: (data: T) => void) {}
update(data: T): void {
this.callback(data);
}
}BREWMODE 8B interface Observer<T> {
update(value: T): void;
}
class Observable<T> {
private observers: Observer<T>[];
constructor() {
this.observers = [];
}
subscribe(observer: Observer<T>): void {
this.observers.push(observer);
}
unsubscribe(observer: Observer<T>): void {
const index = this.observers.indexOf(observer);
if (index !== -1) {
this.observers.splice(index, 1);
}
}
notify(value: T): void {
for (const observer of this.observers) {
observer.update(value);
}
}
}QWEN3-8B BASE class Observable<T> {
private observers: ((value: T) => void)[] = [];
subscribe(observer: (value: T) => void): void {
this.observers.push(observer);
}
unsubscribe(observer: (value: T) => void): void {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(value: T): void {
this.observers.forEach(observer => observer(value));
}
}
// Example usage:
// const obs = new Observable<number>();
// obs.subscribe(value => console.log('Observer 1:', value));
// obs.subscribe(value => console.log('Observer 2:', value));
// obs.notify(42); | |||||||
| Data Table ▸ | 7 | 8 | 6 | 7 | 9 | 6 | |
|
CLAUDE SONNET 4.6 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sortable Table</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-8">
<div class="max-w-6xl mx-auto">
<h1 class="text-3xl font-bold text-gray-900 mb-6">Sortable Table</h1>
<!-- Search Filter -->
<div class="mb-4">
<input type="text" id="searchInput" placeholder="Search table..."
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
</div>
<!-- Table -->
<div class="overflow-x-auto bg-white rounded-lg shadow">
<table id="dataTable" class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="sortable px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-column="0">
Name <span class="sort-arrow">↕</span>
</th>
<th class="sortable px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-column="1">
Age <span class="sort-arrow">↕</span>
</th>
<th class="sortable px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-column="2">
Email <span class="sort-arrow">↕</span>
</th>
<th class="sortable px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-column="3">
Department <span class="sort-arrow">↕</span>
</th>
<th class="sortable px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-column="4">
Salary <span class="sort-arrow">↕</span>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr class="hover:bg-gray-50">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">John Doe</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">28</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">john@example.com</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">Engineering</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">$75,000</td>
</tr>
BREWMODE 8B <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sortable Table</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 text-gray-900">
<div class="container mx-auto px-4 py-8">
<h1 class="text-2xl font-bold mb-6">Sortable Table</h1>
<div class="mb-4">
<input type="text" id="searchInput" placeholder="Search..." class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" onclick="sortTable('age')">
Age <span id="ageSortArrow" class="inline-block w-4 h-4 ml-1 transform transition-transform duration-200"></span>
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" onclick="sortTable('city')">
City <span id="citySortArrow" class="inline-block w-4 h-4 ml-1 transform transition-transform duration-200"></span>
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" onclick="sortTable('email')">
Email <span id="emailSortArrow" class="inline-block w-4 h-4 ml-1 transform transition-transform duration-200"></span>
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" onclick="sortTable('role')">
Role <span id="roleSortArrow" class="inline-block w-4 h-4 ml-1 transform transition-transform duration-200"></span>
</th>
</tr>
</thead>
<tbody id="tableBody" class="bg-white divide-y divide-gray-200">
<!-- Rows will be populated here -->
</tbody>
</table>
</div>
</div>
<script>
const data = [
{ name: "Alice", age: 28, city: "New York", email: "alice@example.com", role: "Developer" },
{ name: "Bob", age: 34, city: "Los Angeles", email: "bob@example.com", role: "Designer" },
{ name: "Charlie", age: 25, city: "Chicago", email: "charlie@example.com", role: "Manager" },
{ name: "Diana", age: 31, city: "San Francisco", email: "diana@example.com", role: "Analyst" },
{ name: "Eve", age: 29, city: "Seattle", email: "eve@example.com", role: "Engineer" },
{ name: "Frank", age: 40, city: "Boston", email: "frank@example.com", role: "Consultant" },
{ name: "Grace", age: 27, city: "Austin", email: QWEN3-8B BASE <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sortable Table</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-6">
<div class="max-w-4xl mx-auto">
<h1 class="text-2xl font-bold mb-4">Sortable Table</h1>
<div class="mb-4">
<input type="text" id="searchInput" placeholder="Search..." class="w-full px-3 py-2 border border-gray-300 rounded" />
</div>
<table class="min-w-full bg-white shadow-md rounded-lg overflow-hidden">
<thead>
<tr class="bg-gray-200">
<th class="px-4 py-2 cursor-pointer" onclick="sortTable(0)">Name ▼</th>
<th class="px-4 py-2 cursor-pointer" onclick="sortTable(1)">Age ▼</th>
<th class="px-4 py-2 cursor-pointer" onclick="sortTable(2)">City ▼</th>
<th class="px-4 py-2 cursor-pointer" onclick="sortTable(3)">Occupation ▼</th>
<th class="px-4 py-2 cursor-pointer" onclick="sortTable(4)">Salary ▼</th>
</tr>
</thead>
<tbody id="tableBody">
<tr>
<td class="border px-4 py-2">John Doe</td>
<td class="border px-4 py-2">30</td>
<td class="border px-4 py-2">New York</td>
<td class="border px-4 py-2">Engineer</td>
<td class="border px-4 py-2">$75,000</td>
</tr>
<tr>
<td class="border px-4 py-2">Jane Smith</td>
<td class="border px-4 py-2">25</td>
<td class="border px-4 py-2">Los Angeles</td>
<td class="border px-4 py-2">Designer</td>
<td class="border px-4 py-2">$65,000</td>
</tr>
<tr>
<td class="border px-4 py-2">Mike Johnson</td>
<td class="border px-4 py-2">35</td>
<td class="border px-4 py-2">Chicago</td>
<td class="border px-4 py-2">Manager</td>
<td class="border px-4 py-2">$85,000</td>
</tr>
<tr>
<td class="border px-4 py-2">Sarah Williams</td>
<td class="border px-4 py-2">28</td>
<td class="border px-4 py-2">Houston</td>
<td class="border px-4 py-2">Teacher</td>
<td class="border px-4 py-2">$55,000</td>
</tr>
<tr>
<td class="border px-4 py-2">David Brown</td>
<td class="border px-4 py-2">40</td>
<td class="border px-4 py-2">San Francisco</td>
<td class="border px-4 py-2">Doctor</td>
<td class="border px-4 py-2">$120,000</td>
</tr>
<tr>
<td class="border px-4 py-2">Emily Davis</td>
<td class="border px-4 py-2">22</td>
<td class="border px-4 py-2">Seattle</td>
<td class="border px-4 py-2">Student</td>
<td class="border px-4 py-2">$25,000</td>
</tr>
<tr>
<td class="border px-4 py-2">Michael Wilson</td>
<td class="border px-4 py-2">32</td>
<td class="border px-4 | |||||||
| Retry with Backoff ▸ | 9 | 7 | 6 | 9 | 7 | 6 | |
|
CLAUDE SONNET 4.6 interface RetryOptions {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
jitter?: boolean;
retryCondition?: (error: any, attempt: number) => boolean | Promise<boolean>;
}
class RetryError extends Error {
constructor(
message: string,
public readonly attempts: number,
public readonly lastError: any
) {
super(message);
this.name = 'RetryError';
}
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function retry<T>(
fn: () => Promise<T>,
options: RetryOptions = {}
): Promise<T> {
const {
maxRetries = 3,
baseDelay = 1000,
maxDelay = 30000,
jitter = true,
retryCondition = () => true
} = options;
let lastError: any;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt === maxRetries) {
break;
}
const shouldRetry = await retryCondition(error, attempt + 1);
if (!shouldRetry) {
break;
}
let delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
if (jitter) {
delay = delay * (0.5 + Math.random() * 0.5);
}
await sleep(delay);
}
}
throw new RetryError(
`Failed after ${maxRetries + 1} attempts`,
maxRetries + 1,
lastError
);
}
export { retry, RetryError, RetryOptions };BREWMODE 8B /**
* Retry an async function with exponential backoff, jitter, and custom condition.
*
* @param fn - The async function to retry.
* @param options - Retry configuration.
* @param options.maxRetries - Maximum number of retry attempts (default: 3).
* @param options.minDelay - Minimum delay between retries in ms (default: 1000).
* @param options.maxDelay - Maximum delay between retries in ms (default: 10000).
* @param options.jitter - Whether to add jitter to the delay (default: true).
* @param options.condition - Custom retry condition function (default: always retry on error).
* @param options.onRetry - Callback called on each retry attempt (optional).
* @returns Promise that resolves to the result of the function or rejects on final failure.
*/
export async function retry<T>(
fn: () => Promise<T>,
options: {
maxRetries?: number;
minDelay?: number;
maxDelay?: number;
jitter?: boolean;
condition?: (error: unknown) => boolean;
onRetry?: (attempt: number, error: unknown) => void;
} = {}
): Promise<T> {
const { maxRetries = 3, minDelay = 1000, maxDelay = 10000, jitter = true, condition = (e) => !!e, onRetry } = options;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt >= maxRetries || !condition(error)) {
throw error;
}
const delay = jitter
? Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay
: minDelay * Math.pow(2, attempt);
if (onRetry) {
onRetry(attempt, error);
}
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw new Error('Retry failed after maximum attempts');
}QWEN3-8B BASE import { promises as fs } from 'fs';
async function asyncRetry<T>(
task: () => Promise<T>,
options: {
maxRetries: number;
retryDelay: number;
jitter?: number;
retryCondition?: (error: any) => boolean;
}
): Promise<T> {
let retries = 0;
let delay = options.retryDelay;
while (retries <= options.maxRetries) {
try {
return await task();
} catch (error) {
if (retries === options.maxRetries) {
throw error;
}
if (options.retryCondition && !options.retryCondition(error)) {
throw error;
}
// Add jitter
const jitter = options.jitter ? Math.floor(Math.random() * options.jitter) : 0;
await new Promise(resolve => setTimeout(resolve, delay + jitter));
retries++;
delay *= 2; // Exponential backoff
}
}
throw new Error('Max retries exceeded');
}
// Example usage
async function exampleUsage() {
try {
const result = await asyncRetry(() => fs.readFile('nonexistent.txt', 'utf-8'), {
maxRetries: 3,
retryDelay: 1000,
jitter: 500,
retryCondition: (error) => error.code === 'ENOENT'
});
console.log(result);
} catch (error) {
console.error('Failed after retries:', error);
}
} | |||||||
| Schema Validator ▸ | 9 | 7 | 5 | 9 | 7 | 5 | |
|
CLAUDE SONNET 4.6 type InferType<T extends Schema<any>> = T extends Schema<infer U> ? U : never;
abstract class Schema<T> {
abstract parse(value: unknown): T;
optional(): OptionalSchema<T> {
return new OptionalSchema(this);
}
}
class StringSchema extends Schema<string> {
parse(value: unknown): string {
if (typeof value !== 'string') {
throw new Error(`Expected string, got ${typeof value}`);
}
return value;
}
}
class NumberSchema extends Schema<number> {
parse(value: unknown): number {
if (typeof value !== 'number') {
throw new Error(`Expected number, got ${typeof value}`);
}
return value;
}
}
class ObjectSchema<T extends Record<string, Schema<any>>> extends Schema<{
[K in keyof T]: InferType<T[K]>
}> {
constructor(private shape: T) {
super();
}
parse(value: unknown): { [K in keyof T]: InferType<T[K]> } {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`Expected object, got ${typeof value}`);
}
const obj = value as Record<string, unknown>;
const result = {} as { [K in keyof T]: InferType<T[K]> };
for (const key in this.shape) {
result[key] = this.shape[key].parse(obj[key]);
}
return result;
}
}
class ArraySchema<T extends Schema<any>> extends Schema<InferType<T>[]> {
constructor(private element: T) {
super();
}
parse(value: unknown): InferType<T>[] {
if (!Array.isArray(value)) {
throw new Error(`Expected array, got ${typeof value}`);
}
return value.map((item, index) => {
try {
return this.element.parse(item);
} catch (error) {
throw new Error(`Array item at index ${index}: ${(error as Error).message}`);
}
});
}
}
class OptionalSchema<T> extends Schema<T | undefined> {
constructor(private inner: Schema<T>) {
super();
}
parse(value: unknown): T | undefined {
if (value === undefined) {
return undefined;
}
return this.inner.parse(value);
}
}
const z = {
string: () => new StringSchema(),
number: () => new NumberSchema(),
object: <T extends Record<string, Schema<any>>>(shape: T) => new ObjectSchema(shape),
array: <T extends Schema<any>>(element: T) => new ArraySchema(element),
};
export { z, Schema, InferType };BREWMODE 8B type SchemaType = 'string' | 'number' | 'object' | 'array' | 'optional';
interface Schema {
type: SchemaType;
[key: string]: unknown;
}
interface StringSchema {
type: 'string';
format?: string;
minLength?: number;
maxLength?: number;
}
interface NumberSchema {
type: 'number';
minimum?: number;
maximum?: number;
multipleOf?: number;
}
interface ObjectSchema {
type: 'object';
properties?: Record<string, Schema>;
required?: string[];
additionalProperties?: boolean;
}
interface ArraySchema {
type: 'array';
items?: Schema;
minItems?: number;
maxItems?: number;
}
interface OptionalSchema {
type: 'optional';
schema: Schema;
}
function validate(schema: Schema, value: unknown): boolean {
switch (schema.type) {
case 'string':
return validateString(schema as StringSchema, value);
case 'number':
return validateNumber(schema as NumberSchema, value);
case 'object':
return validateObject(schema as ObjectSchema, value);
case 'array':
return validateArray(schema as ArraySchema, value);
case 'optional':
return validateOptional(schema as OptionalSchema, value);
default:
return false;
}
}
function validateString(schema: StringSchema, value: unknown): boolean {
if (!isString(value)) return false;
if (schema.format && !isFormat(value, schema.format)) return false;
if (schema.minLength !== undefined && value.length < schema.minLength) return false;
if (schema.maxLength !== undefined && value.length > schema.maxLength) return false;
return true;
}
function isFormat(value: string, format: string): boolean {
switch (format) {
case 'email':
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
case 'url':
return /^https?:\/\/[^\s/$.?#]+\.[^\s]*$/.test(value);
case 'date':
return !isNaN(Date.parse(value));
default:
return true;
}
}
function validateNumber(schema: NumberSchema, value: unknown): boolean {
if (!isNumber(value)) return false;
if (schema.minimum !== undefined && value < schema.minimum) return false;
if (schema.maximum !== nil && value > schema.maximum) return false;
if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) return false;
return true;
}
function validateObject(schema: ObjectSchema, value: unknown): boolean {
if (!isObject(value)) return false;
if (schema.properties) {
for (const [key, propSchema] of Object.entries(schema.properties)) {
if (value[key] === undefined) continue;
if (!validate(propSchema, value[key])) return false;
}
}
if (schema.required) {
for (const key of schema.required) {
if (value[key] === undefined) return false;
}
}
if (schema.additionalProperties !== undefined) {
for (const key of Object.keys(value)) {
if (!schema.properties?.hasOwnProperty(key)) {
if (schema.additionalProperties) continue;
return false;
}
}
}
return true;
}
functioQWEN3-8B BASE type ValidationResult = {
success: boolean;
errors: string[];
};
type Schema<T> = {
parse(input: unknown): ValidationResult & { data: T | null };
};
const createSchema = <T,>(validator: (input: unknown) => ValidationResult & { data: T | null }): Schema<T> => validator;
const stringSchema = createSchema((input: unknown): ValidationResult & { data: string | null } => {
if (typeof input === 'string') {
return { success: true, errors: [], data: input };
}
return { success: false, errors: ['Expected string'], data: null };
});
const numberSchema = createSchema((input: unknown): ValidationResult & { data: number | null } => {
if (typeof input === 'number') {
return { success: true, errors: [], data: input };
}
return { success: false, errors: ['Expected number'], data: null };
});
const objectSchema = createSchema((input: unknown): ValidationResult & { data: Record<string, unknown> | null } => {
if (typeof input === 'object' && input !== null) {
return { success: true, errors: [], data: input };
}
return { success: false, errors: ['Expected object'], data: null };
});
const arraySchema = createSchema((input: unknown): ValidationResult & { data: unknown[] | null } => {
if (Array.isArray(input)) {
return { success: true, errors: [], data: input };
}
return { success: false, errors: ['Expected array'], data: null };
});
const optionalSchema = <T,>(schema: Schema<T>): Schema<T | null> => createSchema((input: unknown): ValidationResult & { data: T | null } => {
const result = schema.parse(input);
if (result.success) {
return { ...result, data: result.data };
}
return { success: true, errors: [], data: null };
});
// Example usage:
const emailSchema = objectSchema({
parse: (input: unknown): ValidationResult & { data: { email: string } | null } => {
const objResult = objectSchema.parse(input);
if (!objResult.success) return { success: false, errors: objResult.errors, data: null };
const emailResult = stringSchema.parse(objResult.data.email);
if (!emailResult.success) {
return { success: false, errors: [...objResult.errors, ...emailResult.errors], data: null };
}
return { success: true, errors: [], data: { email: emailResult.data } };
}
});
const result = emailSchema.parse({ email: 'test@example.com' });
console.log(result); // { success: true, errors: [], data: { email: 'test@example.com' } } | |||||||
| Todo App ▸ | 9 | 7 | 6 | 9 | 7 | 7 | |
|
CLAUDE SONNET 4.6 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen py-8">
<div class="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">
<h1 class="text-3xl font-bold text-center text-gray-800 mb-6">Todo App</h1>
<!-- Add Todo Form -->
<form id="todoForm" class="mb-6">
<div class="flex gap-2">
<input
type="text"
id="todoInput"
placeholder="Add a new todo..."
class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
>
<button
type="submit"
class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Add
</button>
</div>
</form>
<!-- Filter Buttons -->
<div class="flex justify-center gap-2 mb-6">
<button
id="filterAll"
class="px-3 py-1 rounded-md bg-blue-500 text-white text-sm"
>
All
</button>
<button
id="filterActive"
class="px-3 py-1 rounded-md bg-gray-200 text-gray-700 text-sm hover:bg-gray-300"
>
Active
</button>
<button
id="filterCompleted"
class="px-3 py-1 rounded-md bg-gray-200 text-gray-700 text-sm hover:bg-gray-300"
>
Completed
</button>
</div>
<!-- Todo List -->
<ul id="todoList" class="space-y-2"></ul>
<!-- Empty State -->
<div id="emptyState" class="text-center text-gray-500 py-8 hidden">
No todos yet. Add one above!
</div>
</div>
<script>
class TodoApp {
constructor() {
this.todos = JSON.parse(localStorage.getItem('todos')) || [];
this.currentFilter = 'all';
this.init();
}
init() {
this.bindEvents();
this.render();
}
bindEvents() {
document.getElementById('todoForm').addEventListener('submit', (e) => {
e.preventDefault();
this.addTodo();
});
document.getElementById('filterAll').addEventListener('click', () => {
this.setFilter('all');
});
document.getElementById('filterActive').addEventListener('click', () => {
this.setFilter('active');
});
BREWMODE 8B <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todo App</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 text-gray-900 font-sans">
<div class="max-w-md mx-auto p-6">
<h1 class="text-3xl font-bold mb-6">Todo App</h1>
<div class="flex mb-4">
<input type="text" id="newTodo" placeholder="Add a new todo..." class="flex-grow px-4 py-2 rounded-l-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<button onclick="addTodo()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-r-lg font-medium">Add</button>
</div>
<div class="mb-4">
<label class="flex items-center">
<input type="checkbox" id="toggleCompleted" onchange="toggleCompleted()" class="form-checkbox h-4 w-4 text-blue-600" />
<span class="ml-2 text-sm">Show completed</span>
</label>
</div>
<div class="mb-4">
<select id="filter" onchange="filterTodos()" class="px-3 py-2 rounded-lg border border-gray-300">
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
</div>
<ul id="todoList" class="space-y-2">
<!-- Todos will appear here -->
</ul>
<div class="mt-4">
<p class="text-sm">Todos saved to localStorage</p>
</div>
</div>
<script>
const todoList = document.getElementById('todoList');
const newTodoInput = document.getElementById('newTodo');
const toggleCompletedCheckbox = document.getElementById('toggleCompleted');
const filterSelect = document.getElementById('filter');
let todos = JSON.parse(localStorage.getItem('todos')) || [];
function saveTodos() {
localStorage.setItem('todos', JSON.stringify(todos));
}
function renderTodos() {
todoList.innerHTML = '';
const filtered = todos.filter(todo => {
if (filterSelect.value === 'all') return true;
if (filterSelect.value === 'active') return !todo.completed;
if (filterSelect.value === 'completed') return todo.completed;
return true;
});
filtered.forEach((todo, index) => {
const li = document.createElement('li');
li.className = 'flex items-center justify-between bg-white rounded-lg p-3 shadow-sm';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = todo.completed;
checkbox.addEventListener('change', () => {
todos[index].completed = checkbox.checked;
saveTodos();
renderTodos();
});
const span = document.createElement('span');
span.textContent = todo.text;
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.className = 'text-red-600 hover:text-redQWEN3-8B BASE <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todo App</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex flex-col items-center min-h-screen">
<div class="w-full max-w-md mt-10 p-6 bg-white rounded shadow-md">
<h1 class="text-2xl font-bold mb-4">Todo App</h1>
<div class="mb-4">
<input
id="newTodo"
type="text"
placeholder="Add a new task"
class="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
onclick="addTodo()"
class="mt-2 w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition"
>
Add Todo
</button>
</div>
<div class="mb-4">
<select
id="filter"
class="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
</div>
<ul id="todoList" class="space-y-2"></ul>
<div class="mt-4 text-sm text-gray-500">
<span id="todoCount">0</span> items left
</div>
<button
onclick="clearCompleted()"
class="mt-4 w-full bg-red-500 text-white py-2 rounded hover:bg-red-600 transition"
>
Clear Completed
</button>
</div>
<script>
const todoList = document.getElementById('todoList');
const newTodoInput = document.getElementById('newTodo');
const filterSelect = document.getElementById('filter');
const todoCountSpan = document.getElementById('todoCount');
let todos = JSON.parse(localStorage.getItem('todos')) || [];
function saveTodos() {
localStorage.setItem('todos', JSON.stringify(todos));
}
function renderTodos() {
todoList.innerHTML = '';
todos.forEach((todo, index) => {
const li = document.createElement('li');
li.className = `flex justify-between items-center p-2 border rounded ${todo.completed ? 'bg-green-50' : 'bg-white'}`;
const span = document.createElement('span');
span.textContent = todo.text;
span.className = 'flex-1';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = todo.completed;
checkbox.addEventListener('change', () => toggleTodo(index));
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.className = 'text-red-500 hover:text-red-700';
deleteBtn.onclick = () => deleteTodo(index);
li.appendChild(checkbox);
li.appendChild(span);
li.appendChild(deleteBtn);
todoList.appendChild(li);
});
updateTodoCount();
}
function updateTodoCount() {
cons | |||||||
| Connection Pool ▸ | 9 | 6 | 5 | 9 | 6 | 5 | |
|
CLAUDE SONNET 4.6 import threading
import time
import queue
import socket
from contextlib import contextmanager
from typing import Optional, Callable, Any
import logging
logger = logging.getLogger(__name__)
class Connection:
def __init__(self, host: str, port: int, connect_timeout: float = 5.0):
self.host = host
self.port = port
self.connect_timeout = connect_timeout
self.socket = None
self.created_at = time.time()
self.last_used = time.time()
self.is_healthy = True
self._lock = threading.Lock()
def connect(self):
"""Establish the connection"""
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(self.connect_timeout)
self.socket.connect((self.host, self.port))
self.is_healthy = True
logger.debug(f"Connected to {self.host}:{self.port}")
except Exception as e:
self.is_healthy = False
logger.error(f"Failed to connect to {self.host}:{self.port}: {e}")
raise
def close(self):
"""Close the connection"""
with self._lock:
if self.socket:
try:
self.socket.close()
except:
pass
self.socket = None
self.is_healthy = False
def health_check(self) -> bool:
"""Perform a health check on the connection"""
with self._lock:
if not self.socket:
return False
try:
# Simple socket health check
self.socket.send(b'')
self.is_healthy = True
return True
except:
self.is_healthy = False
return False
def execute(self, data: bytes) -> bytes:
"""Execute a command on the connection"""
with self._lock:
if not self.socket or not self.is_healthy:
raise RuntimeError("Connection is not healthy")
try:
self.socket.send(data)
response = self.socket.recv(1024)
self.last_used = time.time()
return response
except Exception as e:
self.is_healthy = False
logger.error(f"Error executing command: {e}")
raise
class ConnectionPool:
def __init__(
self,
host: str,
port: int,
max_connections: int = 10,
timeout: float = 30.0,
connect_timeout: float = 5.0,
health_check_interval: float = 60.0,
max_idle_time: float = 300.0,
health_check_func: Optional[Callable[[Connection], bool]] = None
):
self.host = host
self.port = port
self.max_connections = max_connections
self.timeout = timeout
self.connect_timeout = connect_timeout
BREWMODE 8B import threading
import time
import queue
from abc import ABC, abstractmethod
from typing import Generic, TypeVar, Optional, Any, Callable
T = TypeVar('T')
class ConnectionPool(Generic[T]):
def __init__(self, max_connections: int = 5, timeout: float = 10.0):
self.max_connections = max_connections
self.timeout = timeout
self._lock = threading.Lock()
self._connections = queue.Queue(max_connections)
self._health_check_interval = 30.0 # seconds
self._health_check_thread = None
self._shutdown = False
self._health_check_callback: Optional[Callable[[T], bool]] = None
self._connection_factory: Callable[[], T] = lambda: None # Placeholder
def set_health_check_callback(self, callback: Callable[[T], bool]):
self._health_check_callback = callback
def set_connection_factory(self, factory: Callable[[], T]):
self._connection_factory = factory
def _create_connection(self) -> T:
try:
return self._connection_factory()
except Exception as e:
raise RuntimeError(f"Failed to create connection: {str(e)}")
def _health_check_connection(self, conn: T) -> bool:
if self._health_check_callback:
return self._health_check_callback(conn)
return True
def _health_check(self):
while not self._shutdown:
try:
with self._lock:
if self._connections.empty():
time.sleep(self._health_check_interval)
continue
conn = self._connections.get_nowait()
if not self._health_check_connection(conn):
self._connections.task_done()
self._connections.put(conn)
time.sleep(self._health_check_interval)
continue
self._connections.task_done()
self._connections.put(conn)
except Exception as e:
time.sleep(self._health_check_interval)
def start_health_check(self):
if self._health_check_thread is None:
self._health_check_thread = threading.Thread(target=self._health_check, daemon=True)
self._health_check_thread.start()
def shutdown(self):
with self._lock:
self._shutdown = True
while not self._connections.empty():
conn = self._connections.get_nowait()
if conn is not None:
try:
conn.close()
except:
pass
self._connections.task_done()
if self._health_check_thread is not None:
self._health_check_thread.join()
def __enter__(self):
return self.get_connection()
def __exit__(self, exc_type, exc_val, exc_tb):
self.release_connection()
def get_connection(self) -> T:
QWEN3-8B BASE import threading
import queue
import time
import socket
from abc import ABC, abstractmethod
from contextlib import contextmanager
class Connection(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def close(self):
pass
class MockConnection(Connection):
def __init__(self, conn_id):
self.conn_id = conn_id
def connect(self):
print(f"Connection {self.conn_id} established")
return self
def close(self):
print(f"Connection {self.conn_id} closed")
class ConnectionPool:
def __init__(self, max_connections, timeout=5, health_check_interval=30):
self.max_connections = max_connections
self.timeout = timeout
self.health_check_interval = health_check_interval
self.pool = queue.Queue(max_connections)
self.lock = threading.Lock()
self.healthy_connections = set()
self.health_check_thread = threading.Thread(target=self._health_check, daemon=True)
self._start_health_check()
def _start_health_check(self):
self.health_check_thread.start()
def _health_check(self):
while True:
time.sleep(self.health_check_interval)
with self.lock:
for conn_id in list(self.healthy_connections):
if not self._is_connection_healthy(conn_id):
self.healthy_connections.discard(conn_id)
def _is_connection_healthy(self, conn_id):
# Simulate health check
return True # Replace with actual health check logic
def _get_connection(self):
with self.lock:
if self.pool.empty():
if len(self.healthy_connections) < self.max_connections:
conn_id = self._create_connection()
self.healthy_connections.add(conn_id)
self.pool.put(conn_id)
else:
raise Exception("Max connections reached")
conn_id = self.pool.get()
self.healthy_connections.add(conn_id)
return conn_id
def _release_connection(self, conn_id):
with self.lock:
self.healthy_connections.add(conn_id)
self.pool.put(conn_id)
def _create_connection(self):
conn_id = len(self.healthy_connections) + 1
return conn_id
def _close_connection(self, conn_id):
with self.lock:
if conn_id in self.healthy_connections:
self.healthy_connections.remove(conn_id)
# Simulate actual connection closing
print(f"Closing connection {conn_id}")
@contextmanager
def connection(self):
conn_id = self._get_connection()
try:
conn = MockConnection(conn_id)
conn.connect()
yield conn
finally:
conn.close()
self._release_connection(conn_id)
def close_all(self):
with self.lock:
for conn_id in self.healt | |||||||
| Job Queue Worker ▸ | 9 | 6 | 5 | 9 | 5 | 6 | |
|
CLAUDE SONNET 4.6 import threading
import queue
import time
import logging
import random
from dataclasses import dataclass
from typing import Callable, Any, Optional
from enum import Enum
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
class JobStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
RETRYING = "retrying"
@dataclass
class Job:
id: str
func: Callable
args: tuple = ()
kwargs: dict = None
max_retries: int = 3
retry_count: int = 0
status: JobStatus = JobStatus.PENDING
result: Any = None
error: Optional[Exception] = None
def __post_init__(self):
if self.kwargs is None:
self.kwargs = {}
class JobWorker(threading.Thread):
def __init__(self, worker_id: int, job_queue: queue.Queue, result_callback: Callable = None):
super().__init__(daemon=True)
self.worker_id = worker_id
self.job_queue = job_queue
self.result_callback = result_callback
self.logger = logging.getLogger(f"Worker-{worker_id}")
self.running = True
def run(self):
self.logger.info(f"Worker {self.worker_id} started")
while self.running:
try:
job = self.job_queue.get(timeout=1)
if job is None: # Poison pill to stop worker
break
self.process_job(job)
self.job_queue.task_done()
except queue.Empty:
continue
except Exception as e:
self.logger.error(f"Unexpected error in worker {self.worker_id}: {e}")
self.logger.info(f"Worker {self.worker_id} stopped")
def process_job(self, job: Job):
self.logger.info(f"Processing job {job.id} (attempt {job.retry_count + 1})")
job.status = JobStatus.RUNNING
try:
# Execute the job function
result = job.func(*job.args, **job.kwargs)
job.result = result
job.status = JobStatus.COMPLETED
self.logger.info(f"Job {job.id} completed successfully")
if self.result_callback:
self.result_callback(job)
except Exception as e:
job.error = e
job.retry_count += 1
self.logger.error(f"Job {job.id} failed with error: {e}")
if job.retry_count <= job.max_retries:
job.status = JobStatus.RETRYING
self.schedule_retry(job)
else:
job.status = JobStatus.FAILED
self.logger.error(f"Job {job.id} failed permanently after {job.max_retries} retries")
if self.result_callback:
self.result_callback(job)
def schedule_retry(self, job: Job):
#BREWMODE 8B import threading
import time
import logging
from typing import Callable, Dict, Any, Optional, List
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
class JobQueueWorker:
def __init__(self, queue: List[Dict[str, Any]], max_retries: int = 3, retry_backoff: float = 2.0):
self.queue = queue
self.max_retries = max_retries
self.retry_backoff = retry_backoff
self.lock = threading.Lock()
self.threads: List[threading.Thread] = []
self.running = False
self.job_counter = 0
def start(self, num_workers: int = 4) -> None:
"""Start the worker threads"""
if self.running:
logging.warning("Workers already running")
return
self.running = True
self.job_counter = 0
for _ in range(num_workers):
thread = threading.Thread(target=self._worker)
thread.start()
self.threads.append(thread)
logging.info(f"Started {num_workers} worker threads")
def stop(self) -> None:
"""Stop all worker threads"""
if not self.running:
logging.warning("Workers not running")
return
self.running = False
for thread in self.threads:
thread.join()
logging.info("All worker threads stopped")
def _worker(self) -> None:
"""Main worker loop for a single thread"""
while self.running:
try:
job = self._get_next_job()
if not job:
time.sleep(0.1)
continue
self.job_counter += 1
logging.info(f"Processing job {self.job_counter}: {job['id']}")
result = self._process_job(job)
if result:
logging.info(f"Job {job['id']} processed successfully")
else:
logging.warning(f"Job {job['id']} failed")
self._retry_job(job)
except Exception as e:
logging.error(f"Error in worker: {str(e)}")
def _get_next_job(self) -> Optional[Dict[str, Any]]:
"""Get the next available job from the queue"""
with self.lock:
if not self.queue:
return None
job = self.queue.pop(0)
return job
def _process_job(self, job: Dict[str, Any]) -> bool:
"""Process a single job"""
try:
# Execute the job function
job_function = job.get('function')
job_args = job.get('args', {})
job_kwargs = job.get('kwargs', {})
if job_function:
result = job_function(**job_args, **job_kwargs)
return bool(result)
return True
except Exception as e:
logging.error(f"Error processing job {job['id']}: {str(e)}")
return False
def _retry_job(self, job: DictQWEN3-8B BASE import threading
import time
import logging
import random
from queue import Queue
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class Job:
def __init__(self, job_id, task, args):
self.job_id = job_id
self.task = task
self.args = args
self.retries = 0
self.max_retries = 3
def __repr__(self):
return f"Job({self.job_id}, {self.task}, {self.args}, retries={self.retries})"
def process_job(job):
try:
logging.info(f"Processing job {job.job_id}")
job.task(*job.args)
logging.info(f"Job {job.job_id} completed successfully")
except Exception as e:
logging.error(f"Job {job.job_id} failed: {str(e)}")
job.retries += 1
if job.retries <= job.max_retries:
delay = 2 ** job.retries # Exponential backoff
logging.info(f"Retrying job {job.job_id} in {delay} seconds...")
time.sleep(delay)
job_queue.put(job)
else:
logging.error(f"Job {job.job_id} exceeded maximum retries")
def worker():
while True:
try:
job = job_queue.get(timeout=1)
if job is None:
break
process_job(job)
job_queue.task_done()
except Exception as e:
logging.error(f"Worker error: {str(e)}")
job_queue.put(job)
def start_workers(num_workers):
for _ in range(num_workers):
t = threading.Thread(target=worker, daemon=True)
t.start()
if __name__ == "__main__":
job_queue = Queue()
num_workers = 4 # Number of worker threads
# Example usage: add some jobs
def example_task(arg):
print(f"Executing task with arg: {arg}")
for i in range(10):
job = Job(job_id=i, task=example_task, args=(i,))
job_queue.put(job)
start_workers(num_workers)
# Wait for all jobs to be processed
job_queue.join()
logging.info("All jobs processed") | |||||||
| API Cache Middleware ▸ | 9 | 6 | 4 | 9 | 5 | 4 | |
|
CLAUDE SONNET 4.6 import { Request, Response, NextFunction } from 'express';
import { createHash } from 'crypto';
interface CacheEntry {
data: any;
timestamp: number;
ttl: number;
staleWhileRevalidate?: number;
headers?: Record<string, string>;
}
interface CacheOptions {
ttl: number; // Time to live in seconds
staleWhileRevalidate?: number; // Additional time to serve stale content while revalidating
keyGenerator?: (req: Request) => string;
skipCache?: (req: Request, res: Response) => boolean;
tags?: string[]; // For pattern invalidation
}
class ResponseCache {
private cache = new Map<string, CacheEntry>();
private tagIndex = new Map<string, Set<string>>();
private revalidatingKeys = new Set<string>();
private generateKey(req: Request, keyGenerator?: (req: Request) => string): string {
if (keyGenerator) {
return keyGenerator(req);
}
const url = req.originalUrl || req.url;
const method = req.method;
const query = JSON.stringify(req.query);
const body = req.method !== 'GET' ? JSON.stringify(req.body) : '';
return createHash('md5')
.update(`${method}:${url}:${query}:${body}`)
.digest('hex');
}
private isExpired(entry: CacheEntry): boolean {
const now = Date.now();
return (now - entry.timestamp) > (entry.ttl * 1000);
}
private isStale(entry: CacheEntry): boolean {
const now = Date.now();
const staleTime = entry.staleWhileRevalidate
? entry.ttl + entry.staleWhileRevalidate
: entry.ttl;
return (now - entry.timestamp) > (staleTime * 1000);
}
private addToTagIndex(key: string, tags: string[]): void {
tags.forEach(tag => {
if (!this.tagIndex.has(tag)) {
this.tagIndex.set(tag, new Set());
}
this.tagIndex.get(tag)!.add(key);
});
}
private removeFromTagIndex(key: string): void {
this.tagIndex.forEach((keys, tag) => {
keys.delete(key);
if (keys.size === 0) {
this.tagIndex.delete(tag);
}
});
}
public invalidateByPattern(pattern: string): void {
const regex = new RegExp(pattern);
const keysToDelete: string[] = [];
this.cache.forEach((_, key) => {
if (regex.test(key)) {
keysToDelete.push(key);
}
});
keysToDelete.forEach(key => this.delete(key));
}
public invalidateByTag(tag: string): void {
const keys = this.tagIndex.get(tag);
if (keys) {
keys.forEach(key => this.delete(key));
}
}
public delete(key: string): void {
this.cache.delete(key);
this.removeFromTagIndex(key);
this.revalidatingKeys.delete(key);
}
public clear(): void {
this.cache.clear();
this.tagIndex.clear();
this.revalidatingKeys.clear();
}
public middleware(options: CacheOptions) {
return async (req: Request, res: Response, next: NextFunction) => {
// Skip caching for non-GET requests by default
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next();
}
// CBREWMODE 8B import type { RequestEvent } from '@[ORG_47]/routing';
import { createHash } from 'crypto';
// Define cache configuration
interface CacheConfig {
ttlSeconds: number;
staleWhileRevalidateSeconds?: number;
cacheKeyPattern: string;
cacheKeyPatternParams?: Record<string, string>;
cacheKeyPrefix?: string;
cacheKeySuffix?: string;
}
// Define cache service
export class CacheService {
private cache: Record<string, any> = {};
private config: CacheConfig;
constructor(config: CacheConfig) {
this.config = config;
}
public getCacheKey(request: RequestEvent): string {
const baseKey = request.url;
let key = baseKey;
if (this.config.cacheKeyPattern) {
const pattern = this.config.cacheKeyPattern;
const params = this.config.cacheKeyPatternParams || {};
// Replace pattern parameters with actual values
for (const [paramName, paramValue] of Object.entries(params)) {
key = key.replace(new RegExp(`{${paramName}}`, 'g'), paramValue);
}
// Add prefix and suffix if provided
if (this.config.cacheKeyPrefix) {
key = `${this.config.cacheKeyPrefix}${key}`;
}
if (this.config.cacheKeySuffix) {
key = `${key}${this.config.cacheKeySuffix}`;
}
}
// Add a hash of the request method for cache key uniqueness
const methodHash = createHash('sha1').update(request.method).digest('hex');
return `${key}-${methodHash}`;
}
public get(key: string): any | null {
const now = Date.now();
const entry = this.cache[key];
if (!entry) return null;
if (now > entry.expiresAt) {
this.delete(key);
return null;
}
return entry.data;
}
public set(key: string, data: any): void {
const now = Date.now();
const ttl = this.config.ttlSeconds * 1000;
const expiresAt = now + ttl;
this.cache[key] = {
data,
expiresAt,
staleWhileRevalidate: this.config.staleWhileRevalidateSeconds ? now + this.config.staleWhileRevalidateSeconds * 1000 : null
};
}
public delete(key: string): void {
delete this.cache[key];
}
public invalidatePattern(pattern: string, params?: Record<string, string>): void {
const patternKey = pattern;
const paramsKey = params ? Object.entries(params).map(([k, v]) => `${k}=${v}`).join('|') : '';
const key = `${patternKey}-${paramsKey}`;
// Remove all entries matching the pattern
for (const [cacheKey, entry] of Object.entries(this.cache)) {
if (cacheKey.includes(patternKey) && (paramsKey === '' || cacheKey.includes(paramsKey))) {
this.delete(cacheKey);
}
}
}
public isStale(key: string): boolean {
const entry = this.cache[key];
if (!entry) return true;
const now = Date.now();
if (now > entry.expiresAt) return true;
if (entry.staleWhileRevalidate && now > entry.staleWhileRevalidate) {
// Stale but still valid
return false;
}
return QWEN3-8B BASE import { NextFunction, Request, Response } from 'express';
interface CacheOptions {
ttl?: number;
keyPattern?: string;
staleWhileRevalidate?: number;
}
const cacheMiddleware = (options: CacheOptions = {}) => {
const { ttl = 60, keyPattern = 'cache:*', staleWhileRevalidate = 0 } = options;
const cache = new Map<string, any>();
return (req: Request, res: Response, next: NextFunction) => {
const cacheKey = req.originalUrl;
// Check if the request should be cached
if (req.method !== 'GET' || req.headers['cache-control']?.includes('no-cache')) {
return next();
}
// Check cache for existing response
const cachedResponse = cache.get(cacheKey);
if (cachedResponse && !isStale(cachedResponse, ttl, staleWhileRevalidate)) {
res.status(cachedResponse.status).send(cachedResponse.body);
return;
}
// If not cached or stale, proceed to handle the request
const originalSend = res.send;
const originalEnd = res.end;
res.send = (body: any) => {
cache.set(cacheKey, {
status: res.statusCode,
body: body,
timestamp: Date.now(),
});
originalSend.call(res, body);
};
res.end = () => {
cache.set(cacheKey, {
status: res.statusCode,
body: res._headers,
timestamp: Date.now(),
});
originalEnd.call(res);
};
next();
};
function isStale(entry: any, ttl: number, staleWhileRevalidate: number): boolean {
const now = Date.now();
const timeSince = now - entry.timestamp;
return timeSince > ttl * 1000 && timeSince <= (ttl + staleWhileRevalidate) * 1000;
}
};
export default cacheMiddleware; | |||||||
| Event Emitter ▸ | 9 | 6 | 4 | 9 | 5 | 4 | |
|
CLAUDE SONNET 4.6 type EventMap = Record<string | symbol, any>;
type EventKey<T extends EventMap> = string & keyof T;
type EventReceiver<T> = (params: T) => void;
interface Emitter<T extends EventMap> {
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
emit<K extends EventKey<T>>(eventName: K, params: T[K]): void;
once<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
}
class TypeSafeEventEmitter<T extends EventMap> implements Emitter<T> {
private events: {
[K in keyof T]?: Array<{
fn: EventReceiver<T[K]>;
once: boolean;
}>;
} = {};
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName]!.push({ fn, once: false });
}
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void {
if (!this.events[eventName]) return;
this.events[eventName] = this.events[eventName]!.filter(
listener => listener.fn !== fn
);
}
emit<K extends EventKey<T>>(eventName: K, params: T[K]): void {
if (!this.events[eventName]) return;
const listeners = this.events[eventName]!.slice();
this.events[eventName] = this.events[eventName]!.filter(listener => {
listener.fn(params);
return !listener.once;
});
}
once<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName]!.push({ fn, once: true });
}
}
// Usage example:
interface MyEvents {
userLogin: { userId: string; timestamp: Date };
userLogout: { userId: string };
dataUpdate: { id: number; data: any };
}
const emitter = new TypeSafeEventEmitter<MyEvents>();
emitter.on('userLogin', (data) => {
// data is typed as { userId: string; timestamp: Date }
console.log(`User ${data.userId} logged in at ${data.timestamp}`);
});
emitter.once('userLogout', (data) => {
// data is typed as { userId: string }
console.log(`User ${data.userId} logged out`);
});
emitter.emit('userLogin', {
userId: '123',
timestamp: new Date()
});BREWMODE 8B // TypeScript type-safe event emitter
type EventCallback<TEvent> = (event: TEvent) => void;
interface EventMap {
[event: string]: EventCallback<any>[];
}
interface EventEmitter {
on<TEvent>(event: string, callback: EventCallback<TEvent>): void;
off<TEvent>(event: string, callback: EventCallback<TEvent>): void;
emit<TEvent>(event: string, eventPayload: TEvent): void;
once<TEvent>(event: string, callback: EventCallback<TEvent>): void;
}
class TypeSafeEventEmitter implements EventEmitter {
private eventMap: EventMap = {};
on<TEvent>(event: string, callback: EventCallback<TEvent>): void {
if (!this.eventMap[event]) {
this.eventMap[event] = [];
}
this.eventMap[event].push(callback);
}
off<TEvent>(event: string, callback: EventCallback<TEvent>): void {
if (this.eventMap[event]) {
const index = this.eventMap[event].indexOf(callback);
if (index !== -1) {
this.eventMap[event].splice(index, 1);
}
}
}
emit<TEvent>(event: string, eventPayload: TEvent): void {
if (this.eventMap[event]) {
this.eventMap[event].forEach((callback) => callback(eventPayload));
}
}
once<TEvent>(event: string, callback: EventCallback<TEvent>): void {
const wrappedCallback: EventCallback<TEvent> = (payload) => {
callback(payload);
this.off(event, wrappedCallback);
};
this.on(event, wrappedCallback);
}
}
export { TypeSafeEventEmitter };QWEN3-8B BASE type EventMap = {
[K in string]: any;
};
type EventListener<T extends EventMap> = (event: T) => void;
type EventKey<T extends EventMap> = keyof T;
class EventEmitter<T extends EventMap> {
private listeners: Map<EventKey<T>, Set<EventListener<T>>> = new Map();
on<K extends EventKey<T>>(event: K, listener: EventListener<T>): void {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
}
this.listeners.get(event)?.add(listener);
}
off<K extends EventKey<T>>(event: K, listener: EventListener<T>): void {
if (this.listeners.has(event)) {
this.listeners.get(event)?.delete(listener);
}
}
emit<K extends EventKey<T>>(event: K, data: T[K]): void {
if (this.listeners.has(event)) {
for (const listener of this.listeners.get(event)!) {
listener({ [event]: data });
}
}
}
once<K extends EventKey<T>>(event: K, listener: EventListener<T>): void {
const wrappedListener = (data: T[K]) => {
listener(data);
this.off(event, wrappedListener);
};
this.on(event, wrappedListener);
}
} | |||||||
| Webhook Handler ▸ | 9 | 5 | 4 | 9 | 6 | 5 | |
|
CLAUDE SONNET 4.6 // pages/api/webhooks/index.ts
import { NextApiRequest, NextApiResponse } from 'next';
import crypto from 'crypto';
interface WebhookPayload {
id: string;
type: string;
data: any;
timestamp: number;
}
// In-memory store for processed webhook IDs (use Redis/DB in production)
const processedWebhooks = new Set<string>();
function verifyHmacSignature(
payload: string,
signature: string,
secret: string
): boolean {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(payload);
const computedSignature = `sha256=${hmac.digest('hex')}`;
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(computedSignature)
);
}
async function processWebhook(payload: WebhookPayload): Promise<void> {
// Add your webhook processing logic here
console.log(`Processing webhook: ${payload.type}`, payload.data);
switch (payload.type) {
case 'user.created':
// Handle user creation
break;
case 'payment.completed':
// Handle payment completion
break;
case 'order.updated':
// Handle order updates
break;
default:
console.log(`Unknown webhook type: ${payload.type}`);
}
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const signature = req.headers['x-signature'] as string;
const webhookSecret = process.env.WEBHOOK_SECRET;
if (!signature) {
return res.status(400).json({ error: 'Missing signature header' });
}
if (!webhookSecret) {
console.error('WEBHOOK_SECRET environment variable not set');
return res.status(500).json({ error: 'Server configuration error' });
}
const rawBody = JSON.stringify(req.body);
// Verify HMAC signature
if (!verifyHmacSignature(rawBody, signature, webhookSecret)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const payload: WebhookPayload = req.body;
// Validate required fields
if (!payload.id || !payload.type || !payload.timestamp) {
return res.status(400).json({ error: 'Invalid payload format' });
}
// Check for timestamp freshness (prevent replay attacks)
const maxAge = 5 * 60 * 1000; // 5 minutes
const now = Date.now();
if (Math.abs(now - payload.timestamp) > maxAge) {
return res.status(400).json({ error: 'Webhook timestamp too old' });
}
// Idempotency check
if (processedWebhooks.has(payload.id)) {
console.log(`Webhook ${payload.id} already processed`);
return res.status(200).json({ message: 'Webhook already processed' });
}
// Process the webhook
await processWebhook(payload);
// Mark as processed
processedWebhooks.add(payload.id);
// Clean up old processed IDs (keep last 1000)
if (processedWebhooks.size > 1000) {
const entries = Array.from(processedWebhooks);
const toRemove BREWMODE 8B import type { NextApiRequest, NextApiResponse } from 'next'
import { createHash } from 'crypto'
// Define a generic webhook payload type
interface WebhookPayload {
id: string
event: string
timestamp: number
data?: Record<string, any>
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Validate request method
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' })
}
try {
// Parse JSON body
const payload = req.body as WebhookPayload
const signature = req.headers['x-hmac-signature'] as string
if (!payload || !signature) {
return res.status(400).json({ error: 'Missing payload or signature' })
}
// Validate HMAC signature
const hmac = createHash('sha256')
hmac.update(JSON.stringify(payload))
const expectedSignature = hmac.digest('hex')
if (signature !== expectedSignature) {
return res.status(400).json({ error: 'Invalid HMAC signature' })
}
// Process webhook idempotently
const { id, event } = payload
const processed = await processWebhookEvent(id, event, payload.data)
if (!processed) {
return res.status(409).json({ error: 'Event already processed' })
}
return res.status(200).json({
message: 'Webhook processed successfully',
event,
timestamp: payload.timestamp
})
} catch (error) {
console.error('Webhook error:', error)
return res.status(500).json({ error: 'Internal server error' })
}
}
// Example implementation of idempotent processing
async function processWebhookEvent(
eventId: string,
eventType: string,
eventData?: Record<string, any>
): Promise<boolean> {
// In a real implementation, you would check if this event has been processed
// before. For this example, we'll assume it's idempotent by default.
// For demonstration purposes, we'll just log the event
console.log(`Processing webhook event: ${eventType} - ${eventId}`)
// In a production system, you might:
// 1. Check a database for existing records
// 2. Validate event data
// 3. Perform business logic operations
// 4. Store event status
// For this example, we'll return true to indicate success
return true
}QWEN3-8B BASE import { NextApiRequest, NextApiResponse } from 'next';
import { verify } from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
// Replace with your actual secret key
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET as string;
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { body, headers } = req;
// Extract the HMAC signature from headers
const hmacHeader = headers['x-hmac'] as string;
if (!hmacHeader) {
return res.status(400).json({ error: 'Missing HMAC signature' });
}
// Generate HMAC signature for validation
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(JSON.stringify(body));
const generatedHmac = hmac.digest('hex');
// Validate HMAC
if (hmacHeader !== generatedHmac) {
return res.status(401).json({ error: 'Invalid HMAC signature' });
}
// Process the webhook payload
try {
// Example: Process the webhook data
const { event, data } = body;
// Check for idempotency (e.g., using a unique identifier)
const idempotencyKey = data.idempotency_key || uuidv4();
const existingRecord = await checkIdempotency(idempotencyKey);
if (existingRecord) {
return res.status(200).json({ message: 'Request already processed' });
}
// Process the event
await handleEvent(event, data);
// Store the processed record for idempotency
await storeIdempotency(idempotencyKey);
return res.status(200).json({ message: 'Webhook processed successfully' });
} catch (error) {
console.error('Error processing webhook:', error);
return res.status(500).json({ error: 'Internal server error' });
}
}
// Example function to check idempotency
async function checkIdempotency(idempotencyKey: string): Promise<boolean> {
// Implement your idempotency check logic here
// For example, query a database or cache
return false;
}
// Example function to handle the event
async function handleEvent(event: string, data: any): Promise<void> {
// Implement your event handling logic here
console.log(`Received event: ${event}`, data);
}
// Example function to store idempotency
async function storeIdempotency(idempotencyKey: string): Promise<void> {
// Implement your storage logic here
console.log(`Stored idempotency key: ${idempotencyKey}`);
} | |||||||
| Cursor Pagination ▸ | 9 | 5 | 0 | — | — | — | |
|
CLAUDE SONNET 4.6 interface PageInfo {
hasNextPage: boolean;
hasPreviousPage: boolean;
startCursor?: string;
endCursor?: string;
}
interface Connection<T> {
edges: Edge<T>[];
pageInfo: PageInfo;
totalCount?: number;
}
interface Edge<T> {
node: T;
cursor: string;
}
interface PaginationArgs {
first?: number;
after?: string;
last?: number;
before?: string;
}
class CursorPaginator<T> {
constructor(
private cursorField: keyof T,
private sortOrder: 'ASC' | 'DESC' = 'ASC'
) {}
encodeCursor(value: any): string {
return Buffer.from(JSON.stringify(value)).toString('base64');
}
decodeCursor(cursor: string): any {
try {
return JSON.parse(Buffer.from(cursor, 'base64').toString('utf-8'));
} catch {
throw new Error('Invalid cursor');
}
}
buildWhereClause(args: PaginationArgs): any {
const where: any = {};
if (args.after) {
const afterValue = this.decodeCursor(args.after);
where[this.cursorField] = this.sortOrder === 'ASC'
? { gt: afterValue }
: { lt: afterValue };
}
if (args.before) {
const beforeValue = this.decodeCursor(args.before);
where[this.cursorField] = {
...where[this.cursorField],
...(this.sortOrder === 'ASC'
? { lt: beforeValue }
: { gt: beforeValue })
};
}
return where;
}
async paginate(
queryFn: (where: any, orderBy: any, take: number) => Promise<T[]>,
countFn: () => Promise<number>,
args: PaginationArgs
): Promise<Connection<T>> {
this.validateArgs(args);
const isForward = args.first !== undefined;
const isBackward = args.last !== undefined;
const limit = (args.first ?? args.last ?? 10) + 1;
const where = this.buildWhereClause(args);
let orderBy: any;
if (isBackward) {
orderBy = { [this.cursorField]: this.sortOrder === 'ASC' ? 'desc' : 'asc' };
} else {
orderBy = { [this.cursorField]: this.sortOrder === 'ASC' ? 'asc' : 'desc' };
}
const results = await queryFn(where, orderBy, limit);
if (isBackward) {
results.reverse();
}
const requestedCount = args.first ?? args.last ?? 10;
const hasMore = results.length > requestedCount;
if (hasMore) {
results.pop();
}
const edges: Edge<T>[] = results.map(node => ({
node,
cursor: this.encodeCursor(node[this.cursorField])
}));
const pageInfo: PageInfo = {
hasNextPage: isForward ? hasMore : args.before !== undefined,
hasPreviousPage: isBackward ? hasMore : args.after !== undefined,
startCursor: edges.length > 0 ? edges[0].cursor : undefined,
endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : undefined
};
// If we need exact previous/next page info, we need additional queries
if (edges.length > 0) {
if (isForward && args.after === undefined) {
pageInfo.hasPreviousPage = false;
}
if (isBackward && args.beBREWMODE 8B /**
* Cursor class for representing pagination cursor values
*/
export class Cursor {
public static fromString(value: string): Cursor {
const parts = value.split('|');
if (parts.length !== 2) {
throw new Error('Invalid cursor format');
}
return new Cursor(parts[0], parseInt(parts[1]));
}
public static toString(value: string | number): string {
if (typeof value === 'string') {
return value;
}
return `${value}|0`;
}
public static isCursor(value: any): boolean {
return typeof value === 'string' && value.includes('|');
}
public static isValid(value: string): boolean {
const parts = value.split('|');
return parts.length === 2 && !isNaN(parseInt(parts[1]));
}
private constructor(
public readonly id: string,
public readonly sortValue: number
) {}
public get nextCursor(): string {
return Cursor.toString(this.sortValue + 1);
}
public get prevCursor(): string {
return Cursor.toString(this.sortValue - 1);
}
}
/**
* CursorPagination class for handling cursor-based pagination
*/
export class CursorPagination {
private readonly sortField: string;
private readonly sortDirection: 'asc' | 'desc';
constructor(
sortField: string = 'id',
sortDirection: 'asc' | 'desc' = 'asc'
) {
this.sortField = sortField;
this.sortDirection = sortDirection;
}
/**
* Get the next page of results
* @param db Database connection
* @param query Base query
* @param limit Page size
* @param cursor Current cursor
* @returns Promise containing next page results and pageInfo
*/
public async nextPage(
db: any,
query: any,
limit: number,
cursor?: Cursor
): Promise<{ results: any[]; pageInfo: PageInfo }> {
if (cursor) {
if (this.sortDirection === 'asc') {
query = query.where(this.sortField, '>', cursor.sortValue);
} else {
query = query.where(this.sortField, '<', cursor.sortValue);
}
}
const results = await query.limit(limit).exec();
const pageInfo = await this.getPageInfo(db, query, limit, cursor);
return { results, pageInfo };
}
/**
* Get the previous page of results
* @param db Database connection
* @param query Base query
* @param limit Page size
* @param cursor Current cursor
* @returns Promise containing previous page results and pageInfo
*/
public async prevPage(
db: any,
query: any,
limit: number,
cursor?: Cursor
): Promise<{ results: any[]; pageInfo: PageInfo }> {
if (cursor) {
if (this.sortDirection === 'asc') {
query = query.where(this.sortField, '<', cursor.sortValue);
} else {
query = query.where(this.sortField, '>', cursor.sortValue);
}
}
const results = await query.limit(limit).exec();
const pageInfo = await this.getPageInfo(db, query, limit, cursor);
return { results, pageInfo };
}
/**
* Get the first page of results
* @param db Database QWEN3-8B BASE ERROR:The read operation timed out | |||||||
| State Machine ▸ | 9 | 5 | 4 | 9 | 4 | 3 | |
|
CLAUDE SONNET 4.6 // Core types
type StateValue = string | number | symbol;
type EventType = string | number | symbol;
interface Event<T extends EventType = EventType, P = any> {
type: T;
payload?: P;
}
interface Guard<C = any, E extends Event = Event> {
(context: C, event: E): boolean;
}
interface Action<C = any, E extends Event = Event> {
(context: C, event: E): void;
}
interface SideEffect<C = any, E extends Event = Event> {
entry?: Action<C, E>[];
exit?: Action<C, E>[];
}
interface Transition<
C = any,
E extends Event = Event,
S extends StateValue = StateValue
> {
target?: S;
guard?: Guard<C, E>;
actions?: Action<C, E>[];
}
interface StateDefinition<
C = any,
E extends Event = Event,
S extends StateValue = StateValue
> {
on?: {
[K in E['type']]?: Transition<C, Extract<E, { type: K }>, S>;
};
entry?: Action<C, E>[];
exit?: Action<C, E>[];
}
interface MachineDefinition<
C = any,
E extends Event = Event,
S extends StateValue = StateValue
> {
id: string;
initial: S;
context: C;
states: {
[K in S]: StateDefinition<C, E, S>;
};
}
interface MachineState<C = any, S extends StateValue = StateValue> {
value: S;
context: C;
}
// Machine implementation
class StateMachine<
C = any,
E extends Event = Event,
S extends StateValue = StateValue
> {
private definition: MachineDefinition<C, E, S>;
private currentState: MachineState<C, S>;
constructor(definition: MachineDefinition<C, E, S>) {
this.definition = definition;
this.currentState = {
value: definition.initial,
context: { ...definition.context },
};
// Execute entry actions for initial state
this.executeActions(
this.definition.states[this.currentState.value].entry,
{} as E
);
}
public send(event: E): MachineState<C, S> {
const currentStateDefinition = this.definition.states[this.currentState.value];
const transition = currentStateDefinition.on?.[event.type] as Transition<C, E, S> | undefined;
if (!transition) {
return this.currentState;
}
// Check guard condition
if (transition.guard && !transition.guard(this.currentState.context, event)) {
return this.currentState;
}
// Execute exit actions
this.executeActions(currentStateDefinition.exit, event);
// Execute transition actions
this.executeActions(transition.actions, event);
// Update state if target is specified
if (transition.target !== undefined) {
this.currentState = {
...this.currentState,
value: transition.target,
};
// Execute entry actions for new state
const newStateDefinition = this.definition.states[this.currentState.value];
this.executeActions(newStateDefinition.entry, event);
}
return this.currentState;
}
public getState(): MachineState<C, S> {
return { ...this.currentState };
}
private executeActions(actions: Action<C, E>[] = [], event: E): void {
actions.forEach(action => aBREWMODE 8B /**
* Finite State Machine in TypeScript
*
* This implementation provides a typed, extensible FSM with:
* - Typed states
* - Guarded transitions (conditional logic)
* - Side effects (onEnter, onExit)
* - Event-driven transitions
*/
// ── Types ────────────────────────────────────────────────────────
type StateId = string;
interface StateConfig<TStateId extends StateId, TEvent extends string> {
id: TStateId;
onEnter?: (context: Record<string, unknown>) => void;
onExit?: (context: Record<string, unknown>) => void;
transitions: TransitionConfig<TStateId, TEvent>[];
}
interface TransitionConfig<TStateId extends StateId, TEvent extends string> {
event: TEvent;
guard?: (context: Record<string, unknown>) => boolean;
to: TStateId;
sideEffects?: 'onEnter' | 'onExit';
}
interface FSMContext {
state: StateId;
events: Record<string, () => void>;
emit: (event: string, payload?: unknown) => void;
reset: () => void;
}
// ── Finite State Machine Class ──────────────────────────────────
export class FSM<TStateId extends StateId, TEvent extends string> {
private state: StateId;
private currentStateConfig: StateConfig<TStateId, TEvent> | undefined;
private configs: Record<TStateId, StateConfig<TStateId, TEvent>>;
private eventHandlers: Record<TEvent, (() => void)[]>;
constructor(
configs: Record<TStateId, StateConfig<TStateId, TEvent>>,
initialState: TStateId
) {
this.configs = configs;
this.eventHandlers = {} as Record<TEvent, (() => void)[]>;
this.state = initialState;
this.currentStateConfig = configs[initialState];
// Register event handlers
for (const config of Object.values(configs)) {
for (const transition of config.transitions) {
if (transition.sideEffects === 'onEnter') {
this.eventHandlers[transition.event] = this.eventHandlers[transition.event] || [];
this.eventHandlers[transition.event].push(() => this.handleTransition(transition.event));
}
if (transition.sideEffects === 'onExit') {
this.eventHandlers[transition.event] = this.eventHandlers[transition.event] || [];
this.eventHandlers[transition.event].push(() => this.handleTransition(transition.event));
}
}
}
// Initialize state
this.currentStateConfig?.onEnter?.({});
}
public get state(): StateId {
return this.state;
}
public emit(event: TEvent, payload?: unknown): void {
this.eventHandlers[event]?.forEach(handler => handler());
}
public reset(): void {
this.state = this.configs[this.state].transitions[0].to;
this.currentStateConfig = this.configs[this.state];
this.currentStateConfig?.onEnter?.({});
}
private handleTransition(event: TEvent): void {
const config = this.configs[this.state];
const transition = config.transitions.find(t => t.event === event);
if (!transition) return;
if (transition.guard && !transition.guard({})) return;
const nextState = transition.toQWEN3-8B BASE type StateId = 'idle' | 'loading' | 'success' | 'error';
interface State {
id: StateId;
onEnter?: () => void;
onExit?: () => void;
}
interface Transition {
from: StateId;
to: StateId;
guard?: (context: any) => boolean;
onTransition?: (context: any) => void;
}
interface FSMContext {
state: StateId;
context: any;
}
class FSM {
private states: Record<StateId, State> = {};
private transitions: Transition[] = [];
constructor(private initialState: StateId) {}
addState(id: StateId, state: State): void {
this.states[id] = state;
}
addTransition(transition: Transition): void {
this.transitions.push(transition);
}
transitionTo(stateId: StateId, context: any): boolean {
const currentState = this.states[this.state];
const targetState = this.states[stateId];
if (!currentState || !targetState) {
throw new Error(`Invalid state transition: ${this.state} -> ${stateId}`);
}
const transition = this.transitions.find(
t => t.from === this.state && t.to === stateId
);
if (!transition) {
throw new Error(`No transition defined from ${this.state} to ${stateId}`);
}
if (transition.guard && !transition.guard(context)) {
return false;
}
if (currentState.onExit) {
currentState.onExit();
}
if (transition.onTransition) {
transition.onTransition(context);
}
if (targetState.onEnter) {
targetState.onEnter();
}
this.state = stateId;
return true;
}
getState(): StateId {
return this.state;
}
getContext(): any {
return this.context;
}
setContext(context: any): void {
this.context = context;
}
private state: StateId;
private context: any;
} | |||||||
| Rate Limiter ▸ | 8 | 4 | 3 | 9 | 6 | 5 | |
|
CLAUDE SONNET 4.6 import Redis from 'ioredis';
interface RateLimiterConfig {
windowSizeMs: number;
maxRequests: number;
redisClient: Redis;
}
interface RateLimitResult {
allowed: boolean;
remainingRequests: number;
resetTime: number;
totalHits: number;
}
export class SlidingWindowRateLimiter {
private redis: Redis;
private windowSizeMs: number;
private maxRequests: number;
constructor(config: RateLimiterConfig) {
this.redis = config.redisClient;
this.windowSizeMs = config.windowSizeMs;
this.maxRequests = config.maxRequests;
}
async checkLimit(userId: string): Promise<RateLimitResult> {
const now = Date.now();
const windowStart = now - this.windowSizeMs;
const key = `rate_limit:${userId}`;
const pipeline = this.redis.pipeline();
// Remove expired entries
pipeline.zremrangebyscore(key, '-inf', windowStart);
// Count current requests in window
pipeline.zcard(key);
// Add current request with timestamp as score and unique identifier as member
pipeline.zadd(key, now, `${now}-${Math.random()}`);
// Set expiration for the key
pipeline.expire(key, Math.ceil(this.windowSizeMs / 1000));
const results = await pipeline.exec();
if (!results) {
throw new Error('Redis pipeline execution failed');
}
const requestCount = results[1][1] as number;
const allowed = requestCount < this.maxRequests;
if (!allowed) {
// Remove the request we just added since it's not allowed
await this.redis.zrem(key, `${now}-${Math.random()}`);
}
return {
allowed,
remainingRequests: Math.max(0, this.maxRequests - requestCount),
resetTime: now + this.windowSizeMs,
totalHits: requestCount
};
}
async getRemainingRequests(userId: string): Promise<number> {
const now = Date.now();
const windowStart = now - this.windowSizeMs;
const key = `rate_limit:${userId}`;
await this.redis.zremrangebyscore(key, '-inf', windowStart);
const currentCount = await this.redis.zcard(key);
return Math.max(0, this.maxRequests - currentCount);
}
async resetUserLimit(userId: string): Promise<void> {
const key = `rate_limit:${userId}`;
await this.redis.del(key);
}
async getUserRequestTimes(userId: string): Promise<number[]> {
const now = Date.now();
const windowStart = now - this.windowSizeMs;
const key = `rate_limit:${userId}`;
const members = await this.redis.zrangebyscore(key, windowStart, '+inf', 'WITHSCORES');
const timestamps: number[] = [];
for (let i = 1; i < members.length; i += 2) {
timestamps.push(parseInt(members[i]));
}
return timestamps;
}
}
// Usage example
export class RateLimiterFactory {
private redis: Redis;
constructor(redisClient: Redis) {
this.redis = redisClient;
}
createLimiter(windowSizeMs: number, maxRequests: number): SlidingWindowRateLimiter {
return new SlidingWindowRateLimiter({
BREWMODE 8B # SlidingWindowRateLimiter.ts
/**
* Sliding Window Rate Limiter using Redis
*
* Implements a sliding window rate limiter that tracks requests per user
* within a configurable time window. Uses Redis for distributed storage.
*/
import { Redis } from '@[ORG_4]/redis';
/**
* Configuration options for the rate limiter
*/
interface RateLimiterConfig {
redisClient: Redis;
keyPrefix: string; // Redis key prefix for rate limiting
maxRequests: number; // Maximum number of requests allowed
windowSeconds: number; // Time window in seconds
}
/**
* Sliding window rate limiter class
*/
export class SlidingWindowRateLimiter {
private config: RateLimiterConfig;
private windowSize: number;
private maxRequests: number;
/**
* Constructor
* @param config Configuration options
*/
constructor(config: RateLimiterConfig) {
this.config = config;
this.windowSize = config.windowSeconds;
this.maxRequests = config.maxRequests;
}
/**
* Check if a request is allowed
* @param userId User ID to check
* @returns Promise<boolean> True if request is allowed, false otherwise
*/
async checkRequest(userId: string): Promise<boolean> {
const { redisClient, keyPrefix } = this.config;
const key = `${keyPrefix}:${userId}`;
const now = Date.now();
// Get the current window start time
const windowStart = Math.floor(now / this.windowSize) * this.windowSize;
// Create a Redis pipeline for batch operations
const pipeline = redisClient.pipeline();
// Add the current timestamp to the window
pipeline.zAdd(key, {
score: now,
value: userId,
});
// Remove timestamps outside the current window
pipeline.zRemRangeByScore(key, 0, windowStart - 1);
// Get the number of requests in the current window
const count = await pipeline.zCard(key).exec();
// If the count is less than the maximum allowed requests, allow the request
return count[0] < this.maxRequests;
}
/**
* Get the remaining requests in the current window
* @param userId User ID to check
* @returns Promise<number> Remaining requests
*/
async getRemainingRequests(userId: string): Promise<number> {
const { redisClient, keyPrefix } = this.config;
const key = `${keyPrefix}:${userId}`;
const now = Date.now();
const windowStart = Math.floor(now / this.windowSize) * this.windowSize;
// Create a Redis pipeline for batch operations
const pipeline = redisClient.pipeline();
// Add the current timestamp to the window
pipeline.zAdd(key, {
score: now,
value: userId,
});
// Remove timestamps outside the current window
pipeline.zRemRangeByScore(key, 0, windowStart - 1);
// Get the number of requests in the current window
const count = await pipeline.zCard(key).exec();
return this.maxRequests - count[0];
}
/**
* Get the remaining time until the window resets
QWEN3-8B BASE import { Redis } from 'ioredis';
interface RateLimitConfig {
maxRequests: number;
windowSeconds: number;
}
class SlidingWindowRateLimiter {
private redis: Redis;
private config: RateLimitConfig;
constructor(redis: Redis, config: RateLimitConfig) {
this.redis = redis;
this.config = config;
}
async isAllowed(userId: string): Promise<boolean> {
const key = `rate_limit:${userId}`;
const window = this.config.windowSeconds;
const max = this.config.maxRequests;
// Get the current timestamp
const now = Math.floor(Date.now() / 1000);
// Create a pipeline to batch operations
const pipeline = this.redis.pipeline();
// Get the current count and last timestamp
pipeline.hget(key, 'count');
pipeline.hget(key, 'timestamp');
const [countStr, timestampStr] = await pipeline.exec();
let count = parseInt(countStr || '0', 10);
let timestamp = parseInt(timestampStr || '0', 10);
// If the window has expired, reset the counter
if (now - timestamp > window) {
count = 0;
timestamp = now;
}
// If we've exceeded the limit, return false
if (count >= max) {
return false;
}
// Increment the count and update the timestamp
count += 1;
timestamp = now;
// Set the new values in Redis
await this.redis.hset(key, 'count', count);
await this.redis.hset(key, 'timestamp', timestamp);
return true;
}
}
export { SlidingWindowRateLimiter }; | |||||||
| CSV Parser ▸ | 9 | 4 | 3 | 8 | 4 | 3 | |
|
CLAUDE SONNET 4.6 class CSVParser:
def __init__(self, delimiter=',', quote_char='"', escape_char=None):
self.delimiter = delimiter
self.quote_char = quote_char
self.escape_char = escape_char or quote_char
def parse(self, text):
"""Parse CSV text and return list of rows (each row is a list of fields)"""
rows = []
current_row = []
current_field = ""
in_quotes = False
i = 0
while i < len(text):
char = text[i]
if in_quotes:
if char == self.escape_char and i + 1 < len(text):
next_char = text[i + 1]
if next_char == self.quote_char:
# Escaped quote
current_field += self.quote_char
i += 2
continue
elif next_char == self.escape_char and self.escape_char != self.quote_char:
# Escaped escape character
current_field += self.escape_char
i += 2
continue
if char == self.quote_char:
# Check if this is an escaped quote (double quote)
if (i + 1 < len(text) and text[i + 1] == self.quote_char and
self.escape_char == self.quote_char):
current_field += self.quote_char
i += 2
continue
else:
# End of quoted field
in_quotes = False
i += 1
continue
# Regular character inside quotes (including newlines)
current_field += char
else:
if char == self.quote_char:
# Start of quoted field
in_quotes = True
elif char == self.delimiter:
# End of field
current_row.append(current_field)
current_field = ""
elif char == '\n':
# End of row
current_row.append(current_field)
if current_row or current_field: # Don't add empty rows unless there's content
rows.append(current_row)
current_row = []
current_field = ""
elif char == '\r':
# Handle Windows line endings
if i + 1 < len(text) and text[i + 1] == '\n':
i += 1 # Skip the \n as well
current_row.append(current_field)
if current_row or current_field:
rows.append(current_row)
current_row = []
current_field = ""
else:
# Regular characteBREWMODE 8B import sys
import csv
import codecs
def parse_csv(
file_path: str,
delimiter: str = ',',
quote_char: str = '"',
escape_char: str = '\\',
newline_char: str = '\n',
encoding: str = 'utf-8'
) -> list:
"""
Parse a CSV file from scratch, handling quoted fields, escaped quotes,
newlines within quotes, and custom delimiters.
Args:
file_path: Path to the CSV file
delimiter: Field delimiter (default: ',')
quote_char: Quote character (default: '"')
escape_char: Escape character (default: '\\')
newline_char: Newline character (default: '\n')
encoding: File encoding (default: 'utf-8')
Returns:
List of lists: Each inner list represents a row
"""
rows = []
current_row = []
current_field = ''
in_quotes = False
in_escape = False
try:
with codecs.open(file_path, 'r', encoding=encoding, errors='ignore') as f:
for char in f.read():
if in_escape:
current_field += char
in_escape = False
elif char == escape_char:
in_escape = True
elif char == newline_char:
if not in_quotes:
rows.append(current_row)
current_row = []
else:
current_field += char
elif char == quote_char:
in_quotes = not in_quotes
if not in_quotes:
current_row.append(current_field)
current_field = ''
else:
current_field += char
# Add the last row if not already added
if current_row:
rows.append(current_row)
except Exception as e:
raise RuntimeError(f"Error reading CSV file: {e}")
return rows
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python csv_parser.py <file_path> [delimiter] [quote_char] [escape_char] [newline_char] [encoding]")
sys.exit(1)
args = sys.argv[1:]
file_path = args[0]
delimiter = args[1] if len(args) > 1 else ','
quote_char = args[2] if len(args) > 2 else '"'
escape_char = args[3] if len(args) > 3 else '\\'
newline_char = args[4] if len(args) > 4 else '\n'
encoding = args[5] if len(args) > 5 else 'utf-8'
try:
rows = parse_csv(file_path, delimiter, quote_char, escape_char, newline_char, encoding)
for row in rows:
print(row)
except Exception as e:
print(f"Error: {e}")QWEN3-8B BASE import csv
import sys
def parse_csv(file_path, delimiter=',', quotechar='"', escapechar='\\'):
with open(file_path, 'r', newline='', encoding='utf-8') as f:
data = f.read()
lines = data.split('\n')
rows = []
current_row = []
in_quotes = False
current_field = ''
current_escape = False
for line in lines:
for char in line:
if current_escape:
current_escape = False
if char == quotechar:
current_field += quotechar
elif char == escapechar:
current_field += escapechar
else:
current_field += char
continue
if char == quotechar:
if in_quotes:
in_quotes = False
else:
in_quotes = True
continue
if char == escapechar:
current_escape = True
continue
if char == delimiter and not in_quotes:
current_row.append(current_field)
current_field = ''
else:
current_field += char
if current_field:
current_row.append(current_field)
current_field = ''
if current_row:
rows.append(current_row)
current_row = []
return rows
# Example usage:
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python csv_parser.py <file_path> [delimiter] [quotechar] [escapechar]")
sys.exit(1)
file_path = sys.argv[1]
delimiter = sys.argv[2] if len(sys.argv) > 2 else ','
quotechar = sys.argv[3] if len(sys.argv) > 3 else '"'
escapechar = sys.argv[4] if len(sys.argv) > 4 else '\\'
parsed_data = parse_csv(file_path, delimiter, quotechar, escapechar)
for row in parsed_data:
print(row) | |||||||
| Merge K Sorted Lists ▸ | 9 | 8 | 9 | 9 | 9 | 9 | |
|
CLAUDE SONNET 4.6 import heapq
from typing import List, Optional
def merge_k_sorted_lists(lists: List[List[int]]) -> List[int]:
heap = []
result = []
# Initialize heap with first element from each non-empty list
for i, lst in enumerate(lists):
if lst: # Handle empty lists
heapq.heappush(heap, (lst[0], i, 0))
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
result.append(val)
# Add next element from the same list if it exists
if elem_idx + 1 < len(lists[list_idx]):
next_val = lists[list_idx][elem_idx + 1]
heapq.heappush(heap, (next_val, list_idx, elem_idx + 1))
return resultBREWMODE 8B from typing import List, Optional
import heapq
def merge_k_sorted_lists(lists: List[Optional[List[int]]]) -> List[int]:
"""
Merge k sorted lists into one sorted list using a min-heap.
Args:
lists: A list of k sorted lists. Each list may be empty.
Returns:
A single sorted list containing all elements from the input lists.
"""
heap = []
for i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, iter(lst)))
result = []
while heap:
val, idx, it = heapq.heappop(heap)
result.append(val)
try:
next_val = next(it)
heapq.heappush(heap, (next_val, idx, it))
except StopIteration:
pass
return resultQWEN3-8B BASE from typing import List, Optional
import heapq
def merge_k_sorted_lists(lists: List[Optional[List[int]]]) -> List[int]:
heap = []
for i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, list_idx, element_idx = heapq.heappop(heap)
result.append(val)
if element_idx + 1 < len(lists[list_idx]):
next_val = lists[list_idx][element_idx + 1]
heapq.heappush(heap, (next_val, list_idx, element_idx + 1))
return result | |||||||