repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
interactive-coding-challenges | online_judges/busiest_period/test_find_busiest_period.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_find_busiest_period(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_busiest_period, None)
self.assertEqual(solution.find_busiest_period([]), None)
data = [
Data(3, 2, EventType.EXIT... | 29 | 778 |
interactive-coding-challenges | online_judges/prod_three/test_prod_three.py | .py | import unittest
class TestProdThree(unittest.TestCase):
def test_prod_three(self):
solution = Solution()
self.assertRaises(TypeError, solution.max_prod_three, None)
self.assertRaises(ValueError, solution.max_prod_three, [1, 2])
self.assertEqual(solution.max_prod_three([5, -2, 3]),... | 22 | 552 |
interactive-coding-challenges | online_judges/nim/test_can_win_nim.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_can_win_nim(self):
solution = Solution()
self.assertRaises(TypeError, solution.can_win_nim, None)
self.assertEqual(solution.can_win_nim(1), True)
self.assertEqual(solution.can_win_nim(2), True)
self.assertEqua... | 25 | 675 |
interactive-coding-challenges | online_judges/longest_abs_file_path/test_length_longest_path.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_length_longest_path(self):
solution = Solution()
self.assertRaises(TypeError, solution.length_longest_path, None)
self.assertEqual(solution.length_longest_path(''), 0)
file_system = 'dir\n\tsubdir1\n\t\tfile1.ext\n\t\... | 23 | 644 |
interactive-coding-challenges | online_judges/math_ops/test_math_ops.py | .py | import unittest
class TestMathOps(unittest.TestCase):
def test_math_ops(self):
solution = Solution()
self.assertRaises(TypeError, solution.insert, None)
solution.insert(5)
solution.insert(2)
solution.insert(7)
solution.insert(9)
solution.insert(9)
s... | 34 | 793 |
interactive-coding-challenges | stacks_queues/sort_stack/test_sort_stack.py | .py | from random import randint
import unittest
class TestSortStack(unittest.TestCase):
def get_sorted_stack(self, stack, numbers):
for x in numbers:
stack.push(x)
sorted_stack = stack.sort()
return sorted_stack
def test_sort_stack(self, stack):
print('Test: Empty stac... | 42 | 1,183 |
interactive-coding-challenges | stacks_queues/n_stacks/test_n_stacks.py | .py | import unittest
class TestStacks(unittest.TestCase):
def test_pop_on_empty(self, num_stacks, stack_size):
print('Test: Pop on empty stack')
stacks = Stacks(num_stacks, stack_size)
stacks.pop(0)
def test_push_on_full(self, num_stacks, stack_size):
print('Test: Push to full sta... | 48 | 1,356 |
interactive-coding-challenges | stacks_queues/queue_from_stacks/test_queue_from_stacks.py | .py | import unittest
class TestQueueFromStacks(unittest.TestCase):
def test_queue_from_stacks(self):
print('Test: Dequeue on empty stack')
queue = QueueFromStacks()
self.assertEqual(queue.dequeue(), None)
print('Test: Enqueue on empty stack')
print('Test: Enqueue on non-empty ... | 40 | 1,039 |
interactive-coding-challenges | stacks_queues/queue_list/queue_list.py | .py | class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, data):
node = Node(data)
# Empty list
if self.head is None and self.tail i... | 36 | 834 |
interactive-coding-challenges | stacks_queues/queue_list/test_queue_list.py | .py | import unittest
class TestQueue(unittest.TestCase):
# TODO: It would be better if we had unit tests for each
# method in addition to the following end-to-end test
def test_end_to_end(self):
print('Test: Dequeue an empty queue')
queue = Queue()
self.assertEqual(queue.dequeue(), Non... | 39 | 977 |
interactive-coding-challenges | stacks_queues/set_of_stacks/test_set_of_stacks.py | .py | import unittest
class TestSetOfStacks(unittest.TestCase):
def test_set_of_stacks(self):
print('Test: Push on an empty stack')
stacks = SetOfStacks(indiv_stack_capacity=2)
stacks.push(3)
print('Test: Push on a non-empty stack')
stacks.push(5)
print('Test: Push on ... | 37 | 853 |
interactive-coding-challenges | stacks_queues/stack/test_stack.py | .py | import unittest
class TestStack(unittest.TestCase):
# TODO: It would be better if we had unit tests for each
# method in addition to the following end-to-end test
def test_end_to_end(self):
print('Test: Empty stack')
stack = Stack()
self.assertEqual(stack.peek(), None)
sel... | 44 | 1,158 |
interactive-coding-challenges | stacks_queues/stack/stack.py | .py | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class Stack(object):
def __init__(self, top=None):
self.top = top
def push(self, data):
self.top = Node(data, self.top)
def pop(self):
if self.top is None:
... | 28 | 559 |
interactive-coding-challenges | stacks_queues/stack_min/test_stack_min.py | .py | import unittest
class TestStackMin(unittest.TestCase):
def test_stack_min(self):
print('Test: Push on empty stack, non-empty stack')
stack = StackMin()
stack.push(5)
self.assertEqual(stack.peek(), 5)
self.assertEqual(stack.minimum(), 5)
stack.push(1)
self.a... | 45 | 1,244 |
interactive-coding-challenges | sorting_searching/rotated_array_search/test_search_sorted_array.py | .py | import unittest
class TestArray(unittest.TestCase):
def test_search_sorted_array(self):
array = Array()
self.assertRaises(TypeError, array.search_sorted_array, None)
self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)
self.assertEqual(array.search_sorted_array([3, 1, 2... | 25 | 745 |
interactive-coding-challenges | sorting_searching/new_int/test_new_int.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_new_int(self):
bits = Bits()
max_size = 32
self.assertRaises(TypeError, bits.new_int, None, max_size)
self.assertRaises(TypeError, bits.new_int, [], max_size)
data = [item for item in range(30)]
data.appen... | 26 | 650 |
interactive-coding-challenges | sorting_searching/merge_sort/test_merge_sort.py | .py | import unittest
class TestMergeSort(unittest.TestCase):
def test_merge_sort(self):
merge_sort = MergeSort()
print('None input')
self.assertRaises(TypeError, merge_sort.sort, None)
print('Empty input')
self.assertEqual(merge_sort.sort([]), [])
print('One element'... | 32 | 671 |
interactive-coding-challenges | sorting_searching/radix_sort/test_radix_sort.py | .py | import unittest
class TestRadixSort(unittest.TestCase):
def test_sort(self):
radix_sort = RadixSort()
self.assertRaises(TypeError, radix_sort.sort, None)
self.assertEqual(radix_sort.sort([]), [])
array = [128, 256, 164, 8, 2, 148, 212, 242, 244]
expected = [2, 8, 128, 148,... | 23 | 543 |
interactive-coding-challenges | sorting_searching/merge_into/test_merge_into.py | .py | import unittest
class TestArray(unittest.TestCase):
def test_merge_into(self):
array = Array()
self.assertRaises(TypeError, array.merge_into, None, None, None, None)
self.assertRaises(ValueError, array.merge_into, [1], [2], -1, -1)
a = [1, 2, 3]
self.assertEqual(array.merg... | 28 | 788 |
interactive-coding-challenges | sorting_searching/insertion_sort/test_insertion_sort.py | .py | import unittest
class TestInsertionSort(unittest.TestCase):
def test_insertion_sort(self):
insertion_sort = InsertionSort()
print('None input')
self.assertRaises(TypeError, insertion_sort.sort, None)
print('Empty input')
self.assertEqual(insertion_sort.sort([]), [])
... | 32 | 715 |
interactive-coding-challenges | sorting_searching/selection_sort/test_selection_sort.py | .py | import unittest
class TestSelectionSort(unittest.TestCase):
def test_selection_sort(self, func):
print('None input')
self.assertRaises(TypeError, func, None)
print('Empty input')
self.assertEqual(func([]), [])
print('One element')
self.assertEqual(func([5]), [5])... | 38 | 932 |
interactive-coding-challenges | sorting_searching/quick_sort/test_quick_sort.py | .py | import unittest
class TestQuickSort(unittest.TestCase):
def test_quick_sort(self):
quick_sort = QuickSort()
print('None input')
self.assertRaises(TypeError, quick_sort.sort, None)
print('Empty input')
self.assertEqual(quick_sort.sort([]), [])
print('One element'... | 32 | 673 |
interactive-coding-challenges | sorting_searching/search_sorted_matrix/test_search_sorted_matrix.py | .py | import unittest
class TestSortedMatrix(unittest.TestCase):
def test_find_val(self):
matrix = [[20, 40, 63, 80],
[30, 50, 80, 90],
[40, 60, 110, 110],
[50, 65, 105, 150]]
sorted_matrix = SortedMatrix()
self.assertRaises(TypeError, sorte... | 25 | 638 |
interactive-coding-challenges | sorting_searching/anagrams/test_anagrams.py | .py | import unittest
class TestAnagrams(unittest.TestCase):
def test_group_anagrams(self):
anagram = Anagram()
self.assertRaises(TypeError, anagram.group_anagrams, None)
data = ['ram', 'act', 'arm', 'bat', 'cat', 'tab']
expected = ['ram', 'arm', 'act', 'cat', 'bat', 'tab']
self... | 23 | 531 |
interactive-coding-challenges | linked_lists/add_reverse/test_add_reverse.py | .py | import unittest
class TestAddReverse(unittest.TestCase):
def test_add_reverse(self):
print('Test: Empty list(s)')
self.assertEqual(MyLinkedList().add_reverse(None, None), None)
self.assertEqual(MyLinkedList().add_reverse(Node(5), None), None)
self.assertEqual(MyLinkedList().add_re... | 49 | 1,482 |
interactive-coding-challenges | linked_lists/kth_to_last_elem/test_kth_to_last_elem.py | .py | import unittest
class Test(unittest.TestCase):
def test_kth_to_last_elem(self):
print('Test: Empty list')
linked_list = MyLinkedList(None)
self.assertEqual(linked_list.kth_to_last_elem(0), None)
print('Test: k >= len(list)')
self.assertEqual(linked_list.kth_to_last_elem(1... | 36 | 907 |
interactive-coding-challenges | linked_lists/remove_duplicates/test_remove_duplicates.py | .py | import unittest
class TestRemoveDupes(unittest.TestCase):
def test_remove_dupes(self, linked_list):
print('Test: Empty list')
linked_list.remove_dupes()
self.assertEqual(linked_list.get_all_data(), [])
print('Test: One element list')
linked_list.insert_to_front(2)
... | 42 | 1,185 |
interactive-coding-challenges | linked_lists/find_loop_start/test_find_loop_start.py | .py | import unittest
class TestFindLoopStart(unittest.TestCase):
def test_find_loop_start(self):
print('Test: Empty list')
linked_list = MyLinkedList()
self.assertEqual(linked_list.find_loop_start(), None)
print('Test: Not a circular linked list: One element')
head = Node(1)
... | 50 | 1,440 |
interactive-coding-challenges | linked_lists/linked_list/linked_list.py | .py | class Node(object):
def __init__(self, data, next=None):
self.next = next
self.data = data
def __str__(self):
return self.data
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def __len__(self):
curr = self.head
counter = 0
... | 99 | 2,549 |
interactive-coding-challenges | linked_lists/linked_list/test_linked_list.py | .py | import unittest
class TestLinkedList(unittest.TestCase):
def test_insert_to_front(self):
print('Test: insert_to_front on an empty list')
linked_list = LinkedList(None)
linked_list.insert_to_front(10)
self.assertEqual(linked_list.get_all_data(), [10])
print('Test: insert_t... | 118 | 3,582 |
interactive-coding-challenges | linked_lists/delete_mid/test_delete_mid.py | .py | import unittest
class TestDeleteNode(unittest.TestCase):
def test_delete_node(self):
print('Test: Empty list, null node to delete')
linked_list = MyLinkedList(None)
linked_list.delete_node(None)
self.assertEqual(linked_list.get_all_data(), [])
print('Test: One node')
... | 46 | 1,402 |
interactive-coding-challenges | linked_lists/palindrome/test_palindrome.py | .py | import unittest
class TestPalindrome(unittest.TestCase):
def test_palindrome(self):
print('Test: Empty list')
linked_list = MyLinkedList()
self.assertEqual(linked_list.is_palindrome(), False)
print('Test: Single element list')
head = Node(1)
linked_list = MyLinked... | 47 | 1,291 |
interactive-coding-challenges | linked_lists/partition/test_partition.py | .py | import unittest
class TestPartition(unittest.TestCase):
def test_partition(self):
print('Test: Empty list')
linked_list = MyLinkedList(None)
linked_list.partition(10)
self.assertEqual(linked_list.get_all_data(), [])
print('Test: One element list, left list empty')
... | 49 | 1,463 |
interactive-coding-challenges | graphs_trees/bst_successor/test_bst_successor.py | .py | import unittest
class TestBstSuccessor(unittest.TestCase):
def test_bst_successor_empty(self):
bst_successor = BstSuccessor()
bst_successor.get_next(None)
def test_bst_successor(self):
nodes = {}
node = Node(5)
nodes[5] = node
bst = Bst(nodes[5])
nodes... | 44 | 1,192 |
interactive-coding-challenges | graphs_trees/tree_dfs/test_dfs.py | .py | import unittest
class TestDfs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestDfs, self).__init__()
self.results = Results()
def test_dfs(self):
bst = BstDfs(Node(5))
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.insert(3)
b... | 56 | 1,531 |
interactive-coding-challenges | graphs_trees/graph_dfs/test_dfs.py | .py | import unittest
class TestDfs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestDfs, self).__init__()
self.results = Results()
def test_dfs(self):
nodes = []
graph = GraphDfs()
for id in range(0, 6):
nodes.append(graph.add_node(id))
... | 36 | 820 |
interactive-coding-challenges | graphs_trees/bst_min/test_bst_min.py | .py | import unittest
def height(node):
if node is None:
return 0
return 1 + max(height(node.left),
height(node.right))
class TestBstMin(unittest.TestCase):
def test_bst_min(self):
min_bst = MinBst()
array = [0, 1, 2, 3, 4, 5, 6]
root = min_bst.create_min_bs... | 34 | 669 |
interactive-coding-challenges | graphs_trees/graph_build_order/test_build_order.py | .py | import unittest
class TestBuildOrder(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBuildOrder, self).__init__()
self.dependencies = [
Dependency('d', 'g'),
Dependency('f', 'c'),
Dependency('f', 'b'),
Dependency('f', 'a'),
... | 52 | 1,633 |
interactive-coding-challenges | graphs_trees/graph_path_exists/test_path_exists.py | .py | import unittest
class TestPathExists(unittest.TestCase):
def test_path_exists(self):
nodes = []
graph = GraphPathExists()
for id in range(0, 6):
nodes.append(graph.add_node(id))
graph.add_edge(0, 1, 5)
graph.add_edge(0, 4, 3)
graph.add_edge(0, 5, 2)
... | 34 | 843 |
interactive-coding-challenges | graphs_trees/bst/dfs.py | .py | def in_order_traversal(node, visit_func):
if node is not None:
in_order_traversal(node.left, visit_func)
visit_func(node.data)
in_order_traversal(node.right, visit_func)
def pre_order_traversal(node, visit_func):
if node is not None:
visit_func(node.data)
pre_order_trave... | 17 | 604 |
interactive-coding-challenges | graphs_trees/bst/test_bst.py | .py | import unittest
class TestTree(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestTree, self).__init__()
self.results = Results()
def test_tree_one(self):
bst = Bst()
bst.insert(5)
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.i... | 42 | 939 |
interactive-coding-challenges | graphs_trees/bst/bst.py | .py | class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
def __repr__(self):
return str(self.data)
class Bst(object):
def __init__(self, root=None):
self.root = root
def insert(self, data):
... | 44 | 1,166 |
interactive-coding-challenges | graphs_trees/invert_tree/test_invert_tree.py | .py | import unittest
class TestInvertTree(unittest.TestCase):
def test_invert_tree(self):
root = Node(5)
bst = InverseBst(root)
node2 = bst.insert(2)
node3 = bst.insert(3)
node1 = bst.insert(1)
node7 = bst.insert(7)
node6 = bst.insert(6)
node9 = bst.inse... | 33 | 848 |
interactive-coding-challenges | graphs_trees/bst_second_largest/test_bst_second_largest.py | .py | import unittest
class TestBstSecondLargest(unittest.TestCase):
def test_bst_second_largest(self):
bst = Solution(None)
self.assertRaises(TypeError, bst.find_second_largest)
root = Node(10)
bst = Solution(root)
node5 = bst.insert(5)
node15 = bst.insert(15)
n... | 37 | 962 |
interactive-coding-challenges | graphs_trees/tree_height/height.py | .py | class BstHeight(Bst):
def height(self, node):
if node is None:
return 0
return 1 + max(self.height(node.left),
self.height(node.right)) | 7 | 191 |
interactive-coding-challenges | graphs_trees/tree_height/test_height.py | .py | import unittest
class TestHeight(unittest.TestCase):
def test_height(self):
bst = BstHeight(Node(5))
self.assertEqual(bst.height(bst.root), 1)
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.insert(3)
self.assertEqual(bst.height(bst.root), 3)
print('... | 25 | 444 |
interactive-coding-challenges | graphs_trees/utils/captured_output.py | .py | import sys
from contextlib import contextmanager
from StringIO import StringIO
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:... | 14 | 370 |
interactive-coding-challenges | graphs_trees/utils/results.py | .py | class Results(object):
def __init__(self):
self.results = []
def add_result(self, result):
# TODO: Clean this up
# Simplifies challenge coding and unit testing
# but makes this function look less appealing
self.results.append(int(str(result)))
def clear_results(sel... | 16 | 406 |
interactive-coding-challenges | graphs_trees/tree_lca/test_lca.py | .py | import unittest
class TestLowestCommonAncestor(unittest.TestCase):
def test_lca(self):
node10 = Node(10)
node5 = Node(5)
node12 = Node(12)
node3 = Node(3)
node1 = Node(1)
node8 = Node(8)
node9 = Node(9)
node18 = Node(18)
node20 = Node(20)
... | 46 | 1,312 |
interactive-coding-challenges | graphs_trees/min_heap/min_heap.py | .py | from __future__ import division
import sys
class MinHeap(object):
def __init__(self):
self.array = []
def __len__(self):
return len(self.array)
def extract_min(self):
if not self.array:
return None
if len(self.array) == 1:
return self.array.pop(0... | 71 | 2,192 |
interactive-coding-challenges | graphs_trees/min_heap/test_min_heap.py | .py | import unittest
class TestMinHeap(unittest.TestCase):
def test_min_heap(self):
heap = MinHeap()
self.assertEqual(heap.peek_min(), None)
self.assertEqual(heap.extract_min(), None)
heap.insert(20)
self.assertEqual(heap.array[0], 20)
heap.insert(5)
self.assert... | 51 | 1,563 |
interactive-coding-challenges | graphs_trees/trie/trie.py | .py | from collections import OrderedDict
class Node(object):
def __init__(self, key, parent=None, terminates=False):
self.key = key
self.terminates = False
self.parent = parent
self.children = {}
class Trie(object):
def __init__(self):
self.root = Node('')
def find(... | 77 | 2,321 |
interactive-coding-challenges | graphs_trees/trie/test_trie.py | .py | import unittest
class TestTrie(unittest.TestCase):
def test_trie(self):
trie = Trie()
print('Test: Insert')
words = ['a', 'at', 'has', 'hat', 'he',
'me', 'men', 'mens', 'met']
for word in words:
trie.insert(word)
for word in trie.list_w... | 73 | 2,160 |
interactive-coding-challenges | graphs_trees/graph_bfs/test_bfs.py | .py | import unittest
class TestBfs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBfs, self).__init__()
self.results = Results()
def test_bfs(self):
nodes = []
graph = GraphBfs()
for id in range(0, 6):
nodes.append(graph.add_node(id))
... | 36 | 820 |
interactive-coding-challenges | graphs_trees/graph_shortest_path/test_shortest_path.py | .py | import unittest
class TestShortestPath(unittest.TestCase):
def test_shortest_path(self):
graph = Graph()
graph.add_edge('a', 'b', weight=5)
graph.add_edge('a', 'c', weight=3)
graph.add_edge('a', 'e', weight=2)
graph.add_edge('b', 'd', weight=2)
graph.add_edge('c', ... | 42 | 1,321 |
interactive-coding-challenges | graphs_trees/graph_shortest_path/priority_queue.py | .py | import sys
class PriorityQueueNode(object):
def __init__(self, obj, key):
self.obj = obj
self.key = key
def __repr__(self):
return str(self.obj) + ': ' + str(self.key)
class PriorityQueue(object):
def __init__(self):
self.queue = []
def insert(self, node):
... | 41 | 957 |
interactive-coding-challenges | graphs_trees/check_balance/test_check_balance.py | .py | import unittest
class TestCheckBalance(unittest.TestCase):
def test_check_balance_empty(self):
bst = BstBalance(None)
bst.check_balance()
def test_check_balance(self):
bst = BstBalance(Node(5))
self.assertEqual(bst.check_balance(), True)
bst.insert(3)
bst.ins... | 47 | 1,043 |
interactive-coding-challenges | graphs_trees/tree_bfs/test_bfs.py | .py | import unittest
class TestBfs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBfs, self).__init__()
self.results = Results()
def test_bfs(self):
bst = BstBfs(Node(5))
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.insert(3)
bs... | 29 | 545 |
interactive-coding-challenges | graphs_trees/graph_shortest_path_unweighted/test_shortest_path.py | .py | import unittest
class TestShortestPath(unittest.TestCase):
def test_shortest_path(self):
nodes = []
graph = GraphShortestPath()
for id in range(0, 6):
nodes.append(graph.add_node(id))
graph.add_edge(0, 1)
graph.add_edge(0, 4)
graph.add_edge(0, 5)
... | 34 | 867 |
interactive-coding-challenges | graphs_trees/tree_level_lists/test_tree_level_lists.py | .py | import unittest
class TestTreeLevelLists(unittest.TestCase):
def test_tree_level_lists(self):
bst = BstLevelLists(Node(5))
bst.insert(3)
bst.insert(8)
bst.insert(2)
bst.insert(4)
bst.insert(1)
bst.insert(7)
bst.insert(6)
bst.insert(9)
... | 43 | 1,062 |
interactive-coding-challenges | graphs_trees/bst_validate/test_bst_validate.py | .py | import unittest
class TestBstValidate(unittest.TestCase):
def test_bst_validate_empty(self):
bst = BstValidate(None)
bst.validate()
def test_bst_validate(self):
bst = BstValidate(Node(5))
bst.insert(8)
bst.insert(5)
bst.insert(6)
bst.insert(4)
... | 39 | 857 |
interactive-coding-challenges | graphs_trees/graph/test_graph.py | .py | import unittest
class TestGraph(unittest.TestCase):
def create_graph(self):
graph = Graph()
for key in range(0, 6):
graph.add_node(key)
return graph
def test_graph(self):
graph = self.create_graph()
graph.add_edge(0, 1, weight=5)
graph.add_edge(0, ... | 74 | 2,840 |
interactive-coding-challenges | graphs_trees/graph/graph.py | .py | from enum import Enum # Python 2 users: Run pip install enum34
class State(Enum):
unvisited = 0
visiting = 1
visited = 2
class Node:
def __init__(self, key):
self.key = key
self.visit_state = State.unvisited
self.incoming_edges = 0
self.adj_nodes = {} # Key = key,... | 69 | 2,079 |
interactive-coding-challenges | arrays_strings/str_diff/test_str_diff.py | .py | import unittest
class TestFindDiff(unittest.TestCase):
def test_find_diff(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_diff, None)
self.assertEqual(solution.find_diff('ab', 'aab'), 'a')
self.assertEqual(solution.find_diff('aab', 'ab'), 'a')
self.... | 27 | 880 |
interactive-coding-challenges | arrays_strings/hash_map/test_hash_map.py | .py | import unittest
class TestHashMap(unittest.TestCase):
# TODO: It would be better if we had unit tests for each
# method in addition to the following end-to-end test
def test_end_to_end(self):
hash_table = HashTable(10)
print("Test: get on an empty hash table index")
self.assertRa... | 48 | 1,438 |
interactive-coding-challenges | arrays_strings/permutation/test_permutation_solution.py | .py | import unittest
class TestPermutation(unittest.TestCase):
def test_permutation(self, func):
self.assertEqual(func(None, 'foo'), False)
self.assertEqual(func('', 'foo'), False)
self.assertEqual(func('Nib', 'bin'), False)
self.assertEqual(func('act', 'cat'), True)
self.asser... | 31 | 855 |
interactive-coding-challenges | arrays_strings/reverse_string/test_reverse_string.py | .py | import unittest
class TestReverse(unittest.TestCase):
def test_reverse(self, func):
self.assertEqual(func(None), None)
self.assertEqual(func(['']), [''])
self.assertEqual(func(
['f', 'o', 'o', ' ', 'b', 'a', 'r']),
['r', 'a', 'b', ' ', 'o', 'o', 'f'])
print... | 30 | 811 |
interactive-coding-challenges | arrays_strings/priority_queue/test_priority_queue.py | .py | import unittest
class TestPriorityQueue(unittest.TestCase):
def test_priority_queue(self):
priority_queue = PriorityQueue()
self.assertEqual(priority_queue.extract_min(), None)
priority_queue.insert(PriorityQueueNode('a', 20))
priority_queue.insert(PriorityQueueNode('b', 5))
... | 31 | 958 |
interactive-coding-challenges | arrays_strings/priority_queue/priority_queue.py | .py | import sys
class PriorityQueueNode(object):
def __init__(self, obj, key):
self.obj = obj
self.key = key
def __repr__(self):
return str(self.obj) + ': ' + str(self.key)
class PriorityQueue(object):
def __init__(self):
self.array = []
def __len__(self):
retu... | 42 | 932 |
interactive-coding-challenges | arrays_strings/two_sum/test_two_sum.py | .py | import unittest
class TestTwoSum(unittest.TestCase):
def test_two_sum(self):
solution = Solution()
self.assertRaises(TypeError, solution.two_sum, None, None)
self.assertRaises(ValueError, solution.two_sum, [], 0)
target = 7
nums = [1, 3, 2, -7, 5]
expected = [2, 4]... | 24 | 529 |
interactive-coding-challenges | arrays_strings/unique_chars/test_unique_chars.py | .py | import unittest
class TestUniqueChars(unittest.TestCase):
def test_unique_chars(self, func):
self.assertEqual(func(None), False)
self.assertEqual(func(''), True)
self.assertEqual(func('foo'), False)
self.assertEqual(func('bar'), True)
print('Success: test_unique_chars')
... | 31 | 849 |
interactive-coding-challenges | arrays_strings/rotation/test_rotation.py | .py | import unittest
class TestRotation(unittest.TestCase):
def test_rotation(self):
rotation = Rotation()
self.assertEqual(rotation.is_rotation('o', 'oo'), False)
self.assertEqual(rotation.is_rotation(None, 'foo'), False)
self.assertEqual(rotation.is_rotation('', 'foo'), False)
... | 23 | 599 |
interactive-coding-challenges | arrays_strings/fizz_buzz/test_fizz_buzz.py | .py | import unittest
class TestFizzBuzz(unittest.TestCase):
def test_fizz_buzz(self):
solution = Solution()
self.assertRaises(TypeError, solution.fizz_buzz, None)
self.assertRaises(ValueError, solution.fizz_buzz, 0)
expected = [
'1',
'2',
'Fizz',
... | 38 | 761 |
interactive-coding-challenges | arrays_strings/compress_alt/test_compress.py | .py | import unittest
class TestCompress(unittest.TestCase):
def test_compress(self, func):
self.assertEqual(func(None), None)
self.assertEqual(func(''), '')
self.assertEqual(func('AABBCC'), 'AABBCC')
self.assertEqual(func('AAABCCDDDD'), 'A3BCCD4')
self.assertEqual(
... | 25 | 603 |
interactive-coding-challenges | arrays_strings/compress/test_compress.py | .py | import unittest
class TestCompress(unittest.TestCase):
def test_compress(self, func):
self.assertEqual(func(None), None)
self.assertEqual(func(''), '')
self.assertEqual(func('AABBCC'), 'AABBCC')
self.assertEqual(func('AAABCCDDDDE'), 'A3BC2D4E')
self.assertEqual(func('BAAAC... | 24 | 608 |
interactive-coding-challenges | math_probability/generate_primes/test_generate_primes.py | .py | import unittest
class TestMath(unittest.TestCase):
def test_generate_primes(self):
prime_generator = PrimeGenerator()
self.assertRaises(TypeError, prime_generator.generate_primes, None)
self.assertRaises(TypeError, prime_generator.generate_primes, 98.6)
self.assertEqual(prime_gene... | 27 | 991 |
interactive-coding-challenges | math_probability/add_digits/test_add_digits.py | .py | import unittest
class TestAddDigits(unittest.TestCase):
def test_add_digits(self, func):
self.assertRaises(TypeError, func, None)
self.assertRaises(ValueError, func, -1)
self.assertEqual(func(0), 0)
self.assertEqual(func(9), 9)
self.assertEqual(func(138), 3)
self.a... | 30 | 726 |
interactive-coding-challenges | math_probability/check_prime/test_check_prime.py | .py | import unittest
class TestMath(unittest.TestCase):
def test_check_prime(self):
math = Math()
self.assertRaises(TypeError, math.check_prime, None)
self.assertRaises(TypeError, math.check_prime, 98.6)
self.assertEqual(math.check_prime(0), False)
self.assertEqual(math.check_p... | 23 | 536 |
interactive-coding-challenges | math_probability/power_two/test_is_power_of_two.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_is_power_of_two(self):
solution = Solution()
self.assertRaises(TypeError, solution.is_power_of_two, None)
self.assertEqual(solution.is_power_of_two(0), False)
self.assertEqual(solution.is_power_of_two(1), True)
... | 24 | 656 |
interactive-coding-challenges | templates/test_foo.py | .py | import unittest
class TestFoo(unittest.TestCase):
def test_foo(self):
self.assertEqual(foo(None), None)
self.assertEqual(foo(0), 0)
self.assertEqual(foo('bar'), 'bar')
print('Success: test_foo')
def main():
test = TestFoo()
test.test_foo()
if __name__ == '__main__':
... | 20 | 329 |
onyx | tools/ods/hatch_build.py | .py | from __future__ import annotations
import os
import subprocess
from typing import Any
import manygo
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomBuildHook(BuildHookInterface):
"""Build hook to compile the Go binary and include it in the wheel."""
def initialize(self,... | 42 | 1,514 |
onyx | tools/ods/internal/_version.py | .py | from __future__ import annotations
import os
import re
# Must match tag_prefix in pyproject.toml [tool.hatch.build.targets.wheel.hooks.custom]
TAG_PREFIX: str = "ods"
_tag = os.environ.get("GITHUB_REF_NAME", "v0.0.0-dev").removeprefix(f"{TAG_PREFIX}/")
_match = re.search(r"v?(\d+\.\d+\.\d+)", _tag)
__version__ = _ma... | 12 | 356 |
onyx | tools/ods/internal/openapi/openapi_schema.py | .py | """Generate OpenAPI schema and Python client for Onyx API.
This script is bundled with the ods wheel and executed by the Go binary
to generate the OpenAPI schema without starting the full API server.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import temp... | 238 | 7,382 |
onyx | cli/hatch_build.py | .py | from __future__ import annotations
import os
import subprocess
from typing import Any
import manygo
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomBuildHook(BuildHookInterface):
"""Build hook to compile the Go binary and include it in the wheel."""
def initialize(self,... | 51 | 1,932 |
onyx | cli/internal/_version.py | .py | from __future__ import annotations
import os
import re
# Must match tag_prefix in pyproject.toml [tool.hatch.build.targets.wheel.hooks.custom]
TAG_PREFIX = "cli"
_tag = os.environ.get("GITHUB_REF_NAME", "v0.0.0-dev").removeprefix(f"{TAG_PREFIX}/")
_match = re.search(r"v?(\d+\.\d+\.\d+)", _tag)
__version__ = _match.g... | 12 | 351 |
onyx | examples/assistants-api/topics_analyzer.py | .py | import argparse
import os
import time
from datetime import datetime, timedelta, timezone
from openai import OpenAI
ASSISTANT_NAME = "Topic Analyzer"
SYSTEM_PROMPT = """
You are a helpful assistant that analyzes topics by searching through available \
documents and providing insights. These available documents come fr... | 123 | 3,987 |
onyx | backend/model_server/main.py | .py | import logging
import os
import shutil
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from pathlib import Path
import torch
import uvicorn
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
from sentry_sdk.integrations.fastapi import FastApiI... | 168 | 5,720 |
onyx | backend/model_server/utils.py | .py | import asyncio
import time
from collections.abc import Callable, Generator, Iterator
from functools import wraps
from pathlib import Path
from typing import Any, TypeVar, cast
import torch
from model_server.constants import GPUStatus
from onyx.utils.logger import setup_logger
logger = setup_logger()
F = TypeVar("F"... | 125 | 4,774 |
onyx | backend/model_server/__main__.py | .py | """Process entry point for the model server (`python -m model_server`).
The `DISABLE_MODEL_SERVER` gate runs here, ahead of `model_server.main`'s heavy ML
imports, so a disabled container exits without loading torch / the model stack.
"""
import sys
from onyx.utils.logger import setup_logger
from shared_configs.conf... | 36 | 1,210 |
onyx | backend/model_server/constants.py | .py | MODEL_WARM_UP_STRING = "hi " * 512
class GPUStatus:
CUDA = "cuda"
MAC_MPS = "mps"
NONE = "none"
| 8 | 110 |
onyx | backend/model_server/encoders.py | .py | import asyncio
import time
from typing import TYPE_CHECKING, Any
from fastapi import APIRouter, HTTPException, Request
from model_server.utils import simple_log_function_time
from onyx.utils.logger import setup_logger
from shared_configs.configs import DEFAULT_DOCUMENT_ENCODER_MODEL
from shared_configs.enums import E... | 230 | 8,088 |
onyx | backend/model_server/ca_certs.py | .py | """Assemble the outbound-TLS trust store for the model server.
Every other Onyx pod merges operator-supplied CA roots into the system trust
store with a shell `update-ca-certificates` wrapper. The model server runs on a
distroless image with no shell, so when custom roots are mounted this module
reproduces that merge ... | 98 | 3,493 |
onyx | backend/model_server/management_endpoints.py | .py | from fastapi import APIRouter, Response
from model_server.constants import GPUStatus
from model_server.utils import get_gpu_type
router = APIRouter(prefix="/api")
@router.get("/health")
async def healthcheck() -> Response:
return Response(status_code=200)
@router.get("/gpu-status")
async def route_gpu_status(... | 19 | 487 |
onyx | backend/onyx/main.py | .py | import logging
import sys
import traceback
import warnings
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Any, cast
import uvicorn
from anyio import to_thread
from fastapi import APIRouter, FastAPI, HTTPException, Request, status
from fastapi.exceptions import ... | 785 | 33,686 |
onyx | backend/onyx/setup.py | .py | import time
from sqlalchemy.orm import Session
from onyx.configs.app_configs import (
DISABLE_INDEX_UPDATE_ON_SWAP,
DISABLE_VECTOR_DB,
ENABLE_OPENSEARCH_INDEXING_FOR_ONYX,
INTEGRATION_TESTS_MODE,
MANAGED_VESPA,
ONYX_DISABLE_VESPA,
VESPA_NUM_ATTEMPTS_ON_STARTUP,
)
from onyx.configs.constant... | 407 | 15,850 |
onyx | backend/onyx/__init__.py | .py | import os
__version__ = os.environ.get("ONYX_VERSION", "") or "Development"
| 4 | 77 |
onyx | backend/onyx/mcp_server_main.py | .py | """Entry point for MCP server - HTTP POST transport with API key auth."""
import uvicorn
from onyx.configs.app_configs import (
MCP_SERVER_ENABLED,
MCP_SERVER_HOST,
MCP_SERVER_PORT,
)
from onyx.tracing.setup import setup_tracing
from onyx.utils.logger import setup_logger
from onyx.utils.variable_functiona... | 39 | 912 |
onyx | backend/onyx/error_handling/exceptions.py | .py | """OnyxError — the single exception type for all Onyx business errors.
Raise ``OnyxError`` instead of ``HTTPException`` in business code. A global
FastAPI exception handler (registered via ``register_onyx_exception_handlers``)
converts it into a JSON response with the standard
``{"error_code": "...", "detail": "..."}... | 102 | 3,344 |
onyx | backend/onyx/error_handling/error_codes.py | .py | """
Standardized error codes for the Onyx backend.
Usage:
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
raise OnyxError(OnyxErrorCode.UNAUTHENTICATED, "Token expired")
"""
from enum import Enum
class OnyxErrorCode(Enum):
"""
Each ... | 123 | 5,331 |
onyx | backend/onyx/file_processing/image_summarization.py | .py | import base64
from io import BytesIO
from PIL import Image
from onyx.configs.app_configs import (
IMAGE_SUMMARIZATION_SYSTEM_PROMPT,
IMAGE_SUMMARIZATION_USER_PROMPT,
)
from onyx.configs.chat_configs import IMAGE_SUMMARIZATION_TIMEOUT
from onyx.llm.interfaces import LLM
from onyx.llm.models import (
ChatCo... | 200 | 6,600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.