Spaces:
Sleeping
Sleeping
File size: 106,839 Bytes
7195a9e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 | id,label,modality,language,content,source,generator
code_human_000,human,code,python,"def parse_csv(fname):
# quick and dirty, assumes first row is header
rows = []
with open(fname) as f:
headers = f.readline().strip().split(',')
for line in f:
vals = line.strip().split(',')
if len(vals) != len(headers):
continue # skip malformed rows, happens more than you'd think
rows.append(dict(zip(headers, vals)))
return rows
# TODO: handle quoted fields with commas inside them
# TODO: maybe just use pandas lol",human_written,human
code_human_001,human,code,python,"class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = Node(val)
return
cur = self.root
while True:
if val < cur.val:
if cur.left is None:
cur.left = Node(val)
break
cur = cur.left
else:
if cur.right is None:
cur.right = Node(val)
break
cur = cur.right
def search(self, val):
cur = self.root
while cur:
if val == cur.val: return True
cur = cur.left if val < cur.val else cur.right
return False",human_written,human
code_human_002,human,code,javascript,"// lifted this from stackoverflow and tweaked it
function debounce(fn, wait) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
}
}
// usage: const handleResize = debounce(() => doThing(), 200)
// window.addEventListener('resize', handleResize)",human_written,human
code_human_003,human,code,python,"import re
# regex I've tested against like 50 addresses, probably not perfect
EMAIL_RE = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
def valid_email(s):
return bool(EMAIL_RE.match(s.strip()))
if __name__ == '__main__':
tests = ['user@example.com', 'bad@', 'also.bad', 'ok+filter@sub.domain.org']
for t in tests:
print(t, '->', valid_email(t))",human_written,human
code_human_004,human,code,python,"from collections import OrderedDict
class LRUCache:
def __init__(self, cap):
self.cap = cap
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, val):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = val
if len(self.cache) > self.cap:
self.cache.popitem(last=False) # evict oldest",human_written,human
code_ai_000,ai,code,python,"import pandas as pd
import numpy as np
import os
def compute_summary_statistics(file_path: str) -> dict:
""""""
Reads a CSV file and computes summary statistics for each numeric column.
Args:
file_path: Path to the CSV file
Returns:
Dictionary containing summary statistics for each numeric column
""""""
if not os.path.exists(file_path):
raise FileNotFoundError(f""File not found: {file_path}"")
df = pd.read_csv(file_path)
numeric_df = df.select_dtypes(include=[np.number])
if numeric_df.empty:
return {""message"": ""No numeric columns found in the CSV file""}
summary = {}
for column in numeric_df.columns:
col_data = numeric_df[column]
summary[column] = {
""count"": int(col_data.count()),
""missing_values"": int(col_data.isna().sum()),
""mean"": round(float(col_data.mean()), 4),
""median"": round(float(col_data.median()), 4),
""mode"": round(float(col_data.mode()[0]), 4) if not col_data.mode().empty else None,
""std_dev"": round(float(col_data.std()), 4),
""variance"": round(float(col_data.var()), 4),
""min"": round(float(col_data.min()), 4),
""max"": round(float(col_data.max()), 4),
""range"": round(float(col_data.max() - col_data.min()), 4),
""25th_percentile"": round(float(col_data.quantile(0.25)), 4),
""50th_percentile"": round(float(col_data.quantile(0.50)), 4),
""75th_percentile"": round(float(col_data.quantile(0.75)), 4),
""iqr"": round(float(col_data.quantile(0.75) - col_data.quantile(0.25)), 4),
""skewness"": round(float(col_data.skew()), 4),
""kurtosis"": round(float(col_data.kurtosis()), 4),
""sum"":",claude-sonnet-4-6,claude
code_ai_001,ai,code,python,"class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert_recursive(node.left, value)
elif value > node.value:
if node.right is None:
node.right = Node(value)
else:
self._insert_recursive(node.right, value)
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self._search_recursive(node.left, value)
else:
return self._search_recursive(node.right, value)
def delete(self, value):
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value):
if node is None:
return None
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node to delete found
if node.left is None:
return node.right
elif node.right is None:
return node.left
# Node has two children: find in-order successor (smallest in right subtree)
successor = self._find_min(node.right)
node.value = successor.value
node.right = self._delete_recursive(node.right, successor.value)
return node
def _find_min(self, node):
current = node
while current.left is not None:
current = current.left
return current
def inorder_traversal(self):
result = []
self._inorder_recursive(self.root, result)",claude-sonnet-4-6,claude
code_ai_002,ai,code,python,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import re
def scrape_news_articles(url=None):
""""""
Scrapes article titles and dates from a news website.
Default target: BBC News
""""""
if url is None:
url = ""https://www.bbc.com/news""
headers = {
""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""
""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"",
""Accept"": ""text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"",
""Accept-Language"": ""en-US,en;q=0.5"",
""Accept-Encoding"": ""gzip, deflate, br"",
""Connection"": ""keep-alive"",
}
articles = []
try:
print(f""Fetching articles from: {url}"")
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, ""html.parser"")
# Try multiple selectors for different news sites
scrapers = [
scrape_bbc,
scrape_generic_time_tags,
scrape_generic_article_tags,
]
for scraper in scrapers:
articles = scraper(soup, url)
if articles:
break
if not articles:
print(""No articles found with standard selectors. Trying fallback method..."")
articles = scrape_fallback(soup)
except requests.exceptions.RequestException as e:
print(f""Error fetching URL: {e}"")
return []
return articles
def scrape_bbc(soup, url):
""""""Scrape BBC News articles.""""""
articles = []
if ""bbc"" not in url.lower():
return articles
# BBC News selectors
article_selectors = [
""h3[data-testid='card-headline']"",
""h1[data-testid='headline']"",
"".gs-c-promo-heading__title"",
""",claude-sonnet-4-6,claude
code_ai_003,ai,code,javascript,"function debounce(callback, n) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(this, args);
}, n);
};
}
// Example usage:
const handleInput = debounce((value) => {
console.log(""Input value:"", value);
}, 500);
handleInput(""H"");
handleInput(""He"");
handleInput(""Hel"");
handleInput(""Hell"");
handleInput(""Hello"");
// Only logs ""Input value: Hello"" after 500ms",claude-sonnet-4-6,claude
code_ai_004,ai,code,javascript,"class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
return this;
}
off(event, listener) {
if (!this.events[event]) {
return this;
}
this.events[event] = this.events[event].filter(l => l !== listener);
if (this.events[event].length === 0) {
delete this.events[event];
}
return this;
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach(listener => {
listener(...args);
});
return true;
}
}
// Example usage
const emitter = new EventEmitter();
const greet = (name) => console.log(`Hello, ${name}!`);
const farewell = (name) => console.log(`Goodbye, ${name}!`);
emitter.on('greet', greet);
emitter.on('greet', farewell);
console.log('Emitting greet event:');
emitter.emit('greet', 'Alice');
console.log('\nRemoving farewell listener:');
emitter.off('greet', farewell);
emitter.emit('greet', 'Bob');
console.log('\nEmitting unknown event:');
const result = emitter.emit('unknown', 'Charlie');
console.log('Event emitted:', result);",claude-sonnet-4-6,claude
code_ai_005,ai,code,python,"import re
def is_valid_email(email: str) -> bool:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == ""__main__"":
test_emails = [
""user@example.com"",
""user.name+tag@example.co.uk"",
""user@subdomain.example.com"",
""invalid-email"",
""missing@domain"",
""@nodomain.com"",
""spaces in@email.com"",
""user@.com"",
""user@domain."",
""user123@example.org""
]
for email in test_emails:
result = is_valid_email(email)
print(f""{email}: {'Valid' if result else 'Invalid'}"")",claude-sonnet-4-6,claude
code_ai_006,ai,code,python,"from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
if __name__ == ""__main__"":
cache = LRUCache(2)
cache.put(1, 1)
print(f""Put (1, 1): cache = {dict(cache.cache)}"")
cache.put(2, 2)
print(f""Put (2, 2): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
cache.put(3, 3)
print(f""Put (3, 3): cache = {dict(cache.cache)}"")
print(f""Get 2 (evicted): {cache.get(2)}"")
cache.put(4, 4)
print(f""Put (4, 4): cache = {dict(cache.cache)}"")
print(f""Get 1 (evicted): {cache.get(1)}"")
print(f""Get 3: {cache.get(3)}"")
print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude
code_ai_007,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) {
// Handle null, undefined, and primitive types
if (obj === null || obj === undefined) {
return obj;
}
if (typeof obj !== ""object"" && typeof obj !== ""function"") {
return obj;
}
// Handle circular references
if (visited.has(obj)) {
return visited.get(obj);
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Map
if (obj instanceof Map) {
const clonedMap = new Map();
visited.set(obj, clonedMap);
obj.forEach((value, key) => {
clonedMap.set(deepClone(key, visited), deepClone(value, visited));
});
return clonedMap;
}
// Handle Set
if (obj instanceof Set) {
const clonedSet = new Set();
visited.set(obj, clonedSet);
obj.forEach((value) => {
clonedSet.add(deepClone(value, visited));
});
return clonedSet;
}
// Handle Array
if (Array.isArray(obj)) {
const clonedArray = [];
visited.set(obj, clonedArray);
obj.forEach((item, index) => {
clonedArray[index] = deepClone(item, visited);
});
return clonedArray;
}
// Handle Function
if (typeof obj === ""function"") {
return obj;
}
// Handle Symbol keys
const clonedObj = Object.create(Object.getPrototypeOf(obj));
visited.set(obj, clonedObj);
// Clone regular keys
for (const key of Object.keys(obj)) {
clonedObj[key] = deepClone(obj[key], visited);
}
// Clone Symbol keys
for (const sym of Object.getOwnPropertySymbols(obj)) {
clonedObj[sym] = deepClone(obj[sym], visited);
}
return clonedObj;
}
// Test the function
const original = {
name: """,claude-sonnet-4-6,claude
code_ai_008,ai,code,python,"def generate_permutations(lst):
if len(lst) <= 1:
return [lst]
permutations = []
for i, element in enumerate(lst):
remaining = lst[:i] + lst[i+1:]
for perm in generate_permutations(remaining):
permutations.append([element] + perm)
return permutations
if __name__ == ""__main__"":
sample_list = [1, 2, 3]
result = generate_permutations(sample_list)
print(f""All permutations of {sample_list}:"")
for perm in result:
print(perm)
print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude
code_ai_009,ai,code,python,"import time
import logging
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@contextmanager
def timer(name=""Code block""):
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f""{name} executed in {elapsed_time:.6f} seconds"")
if __name__ == ""__main__"":
with timer(""Sleep example""):
time.sleep(1.5)
with timer(""List comprehension""):
result = [x ** 2 for x in range(100000)]
with timer(""String concatenation""):
text = """"
for i in range(10000):
text += str(i)",claude-sonnet-4-6,claude
code_ai_010,ai,code,python,"import pandas as pd
import numpy as np
import csv
import os
def compute_summary_statistics(file_path: str) -> dict:
""""""
Reads a CSV file and computes summary statistics for each numeric column.
Args:
file_path: Path to the CSV file
Returns:
Dictionary with column names as keys and statistics as values
""""""
if not os.path.exists(file_path):
raise FileNotFoundError(f""File not found: {file_path}"")
df = pd.read_csv(file_path)
numeric_columns = df.select_dtypes(include=[np.number]).columns
if len(numeric_columns) == 0:
return {""message"": ""No numeric columns found in the CSV file""}
summary = {}
for col in numeric_columns:
col_data = df[col].dropna()
summary[col] = {
""count"": int(col_data.count()),
""missing_values"": int(df[col].isnull().sum()),
""mean"": round(float(col_data.mean()), 4),
""median"": round(float(col_data.median()), 4),
""mode"": round(float(col_data.mode()[0]), 4) if not col_data.mode().empty else None,
""std_dev"": round(float(col_data.std()), 4),
""variance"": round(float(col_data.var()), 4),
""min"": round(float(col_data.min()), 4),
""max"": round(float(col_data.max()), 4),
""range"": round(float(col_data.max() - col_data.min()), 4),
""25th_percentile"": round(float(col_data.quantile(0.25)), 4),
""75th_percentile"": round(float(col_data.quantile(0.75)), 4),
""iqr"": round(float(col_data.quantile(0.75) - col_data.quantile(0.25)), 4),
""skewness"": round(float(col_data.skew()), 4),
""kurtosis"": round(float(col_data.kurtosis()), 4),
""sum"": round(float(col_data.sum()), 4),
}",claude-sonnet-4-6,claude
code_ai_011,ai,code,python,"class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert_recursive(node.left, value)
elif value > node.value:
if node.right is None:
node.right = Node(value)
else:
self._insert_recursive(node.right, value)
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self._search_recursive(node.left, value)
else:
return self._search_recursive(node.right, value)
def delete(self, value):
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value):
if node is None:
return None
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node with only one child or no child
if node.left is None:
return node.right
elif node.right is None:
return node.left
# Node with two children: get inorder successor (smallest in right subtree)
min_larger_node = self._get_min(node.right)
node.value = min_larger_node.value
node.right = self._delete_recursive(node.right, min_larger_node.value)
return node
def _get_min(self, node):
current = node
while current.left is not None:
current = current.left
return current
def inorder_traversal(self):
result = []",claude-sonnet-4-6,claude
code_ai_012,ai,code,python,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import re
def scrape_news_articles(url=None):
""""""
Scrapes article titles and dates from a news website.
Uses BBC News as the default example.
""""""
if url is None:
url = ""https://www.bbc.com/news""
headers = {
""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""
""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"",
""Accept-Language"": ""en-US,en;q=0.9"",
""Accept-Encoding"": ""gzip, deflate, br"",
""Accept"": ""text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"",
""Connection"": ""keep-alive"",
}
articles = []
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, ""html.parser"")
# Strategy 1: Look for time elements with article titles
time_elements = soup.find_all(""time"")
for time_el in time_elements:
date_text = (
time_el.get(""datetime"") or
time_el.get(""data-datetime"") or
time_el.get_text(strip=True)
)
# Try to find associated title by traversing parent elements
parent = time_el.parent
title = None
for _ in range(5): # Look up to 5 levels up
if parent is None:
break
heading = parent.find([""h1"", ""h2"", ""h3"", ""h4""])
if heading:
title = heading.get_text(strip=True)
break
parent = parent.parent
if title and date_text:
articles.append({
""title"": title,
""date"": date_text,
""source"": url
})
# Strategy 2: Look for article tags
if not articles:
article_tags = soup.find_all(""article",claude-sonnet-4-6,claude
code_ai_013,ai,code,javascript,"function debounce(callback, n) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, args);
}, n);
};
}
// Example usage
const debouncedFn = debounce((message) => {
console.log(`Called with: ${message}`);
}, 500);
debouncedFn(""first"");
debouncedFn(""second"");
debouncedFn(""third"");
// Only ""Called with: third"" will be logged after 500ms",claude-sonnet-4-6,claude
code_ai_014,ai,code,javascript,"class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
return this;
}
off(event, listener) {
if (!this.events[event]) {
return this;
}
this.events[event] = this.events[event].filter((l) => l !== listener);
if (this.events[event].length === 0) {
delete this.events[event];
}
return this;
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach((listener) => {
listener(...args);
});
return true;
}
}
// Example usage
const emitter = new EventEmitter();
const greet = (name) => console.log(`Hello, ${name}!`);
const farewell = (name) => console.log(`Goodbye, ${name}!`);
emitter.on(""greeting"", greet);
emitter.on(""greeting"", farewell);
console.log(""Emitting greeting event:"");
emitter.emit(""greeting"", ""Alice"");
console.log(""\nRemoving farewell listener:"");
emitter.off(""greeting"", farewell);
console.log(""Emitting greeting event again:"");
emitter.emit(""greeting"", ""Bob"");
console.log(""\nEmitting non-existent event:"");
console.log(emitter.emit(""nonExistent""));",claude-sonnet-4-6,claude
code_ai_015,ai,code,python,"import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# Test the function
test_emails = [
""user@example.com"",
""user.name+tag@example.co.uk"",
""user@subdomain.example.com"",
""invalid-email"",
""missing@domain"",
""@nodomain.com"",
""user@.com"",
""user@domain.c"",
""user name@domain.com"",
""user@domain..com""
]
for email in test_emails:
print(f""{email}: {'Valid' if is_valid_email(email) else 'Invalid'}"")",claude-sonnet-4-6,claude
code_ai_016,ai,code,python,"from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
if __name__ == ""__main__"":
cache = LRUCache(2)
cache.put(1, 1)
print(f""Put (1, 1): cache = {dict(cache.cache)}"")
cache.put(2, 2)
print(f""Put (2, 2): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
cache.put(3, 3)
print(f""Put (3, 3): cache = {dict(cache.cache)}"")
print(f""Get 2: {cache.get(2)}"")
cache.put(4, 4)
print(f""Put (4, 4): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
print(f""Get 3: {cache.get(3)}"")
print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude
code_ai_017,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) {
// Handle null and non-object types
if (obj === null || typeof obj !== ""object"") {
return obj;
}
// Handle circular references
if (visited.has(obj)) {
return visited.get(obj);
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Map
if (obj instanceof Map) {
const clonedMap = new Map();
visited.set(obj, clonedMap);
obj.forEach((value, key) => {
clonedMap.set(deepClone(key, visited), deepClone(value, visited));
});
return clonedMap;
}
// Handle Set
if (obj instanceof Set) {
const clonedSet = new Set();
visited.set(obj, clonedSet);
obj.forEach((value) => {
clonedSet.add(deepClone(value, visited));
});
return clonedSet;
}
// Handle Array
if (Array.isArray(obj)) {
const clonedArray = [];
visited.set(obj, clonedArray);
obj.forEach((item, index) => {
clonedArray[index] = deepClone(item, visited);
});
return clonedArray;
}
// Handle ArrayBuffer
if (obj instanceof ArrayBuffer) {
return obj.slice(0);
}
// Handle TypedArrays
if (ArrayBuffer.isView(obj)) {
return new obj.constructor(obj);
}
// Handle plain objects
const clonedObj = Object.create(Object.getPrototypeOf(obj));
visited.set(obj, clonedObj);
// Copy all own properties (including non-enumerable)
for (const key of Reflect.ownKeys(obj)) {
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.value !== undefined) {
descriptor.value = deepClone(descriptor.value, visited);
}
Object.defineProperty(clonedObj, key, descriptor);
}
return cloned",claude-sonnet-4-6,claude
code_ai_018,ai,code,python,"def generate_permutations(lst):
if len(lst) <= 1:
return [lst]
permutations = []
for i, element in enumerate(lst):
remaining = lst[:i] + lst[i+1:]
for perm in generate_permutations(remaining):
permutations.append([element] + perm)
return permutations
if __name__ == ""__main__"":
sample_list = [1, 2, 3]
result = generate_permutations(sample_list)
print(f""All permutations of {sample_list}:"")
for perm in result:
print(perm)
print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude
code_ai_019,ai,code,python,"import time
import logging
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@contextmanager
def timer(name: str = ""Code block""):
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f""{name} executed in {elapsed_time:.4f} seconds"")
if __name__ == ""__main__"":
with timer(""Sleep test""):
time.sleep(1.5)
with timer(""List comprehension""):
result = [x ** 2 for x in range(1000000)]
with timer(""String concatenation""):
text = """"
for i in range(10000):
text += str(i)",claude-sonnet-4-6,claude
code_ai_020,ai,code,python,"import pandas as pd
import numpy as np
import csv
import os
def compute_summary_statistics(file_path: str) -> dict:
""""""
Reads a CSV file and computes summary statistics for each numeric column.
Args:
file_path: Path to the CSV file
Returns:
Dictionary containing summary statistics for each numeric column
""""""
if not os.path.exists(file_path):
raise FileNotFoundError(f""File not found: {file_path}"")
df = pd.read_csv(file_path)
numeric_df = df.select_dtypes(include=[np.number])
if numeric_df.empty:
return {""message"": ""No numeric columns found in the CSV file""}
summary = {}
for column in numeric_df.columns:
col_data = numeric_df[column].dropna()
if len(col_data) == 0:
summary[column] = {""message"": ""Column contains no valid numeric data""}
continue
q1 = col_data.quantile(0.25)
q3 = col_data.quantile(0.75)
iqr = q3 - q1
summary[column] = {
""count"": len(col_data),
""missing_values"": numeric_df[column].isna().sum(),
""mean"": round(col_data.mean(), 4),
""median"": round(col_data.median(), 4),
""mode"": round(col_data.mode()[0], 4) if not col_data.mode().empty else None,
""std_dev"": round(col_data.std(), 4),
""variance"": round(col_data.var(), 4),
""min"": round(col_data.min(), 4),
""max"": round(col_data.max(), 4),
""range"": round(col_data.max() - col_data.min(), 4),
""q1"": round(q1, 4),
""q3"": round(q3, 4),
""iqr"": round(iqr, 4),
""skewness"": round(col_data.skew(), 4),
""kurtosis"": round(col_data.kurtosis(), 4),
""sum"": round(col_data.sum(), 4),
}",claude-sonnet-4-6,claude
code_ai_021,ai,code,python,"class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert_recursive(node.left, value)
elif value > node.value:
if node.right is None:
node.right = Node(value)
else:
self._insert_recursive(node.right, value)
else:
print(f""Value {value} already exists in the tree."")
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self._search_recursive(node.left, value)
else:
return self._search_recursive(node.right, value)
def delete(self, value):
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value):
if node is None:
print(f""Value {value} not found in the tree."")
return node
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node with only one child or no child
if node.left is None:
return node.right
elif node.right is None:
return node.left
# Node with two children
# Get the inorder successor (smallest in the right subtree)
min_larger_node = self._get_min(node.right)
node.value = min_larger_node.value
node.right = self._delete_recursive(node.right, min_larger_node.value)
return node
def _get_min(self, node):
current",claude-sonnet-4-6,claude
code_ai_022,ai,code,python,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import re
def scrape_news_articles(url: str, headers: dict = None) -> list[dict]:
""""""
Scrape article titles and dates from a news website.
Args:
url: The URL of the news website to scrape
headers: Optional HTTP headers for the request
Returns:
List of dictionaries containing article titles and dates
""""""
if headers is None:
headers = {
""User-Agent"": (
""Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""
""AppleWebKit/537.36 (KHTML, like Gecko) ""
""Chrome/91.0.4472.124 Safari/537.36""
)
}
articles = []
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, ""html.parser"")
# Try multiple common HTML patterns for news articles
articles = (
extract_schema_articles(soup) or
extract_article_tags(soup) or
extract_common_class_patterns(soup)
)
if not articles:
print(""No articles found with standard patterns. Trying generic extraction..."")
articles = extract_generic_content(soup)
except requests.exceptions.RequestException as e:
print(f""Error fetching URL: {e}"")
return articles
def extract_schema_articles(soup: BeautifulSoup) -> list[dict]:
""""""Extract articles using JSON-LD schema markup.""""""
articles = []
for script in soup.find_all(""script"", type=""application/ld+json""):
try:
data = json.loads(script.string)
if isinstance(data, list):
items = data
elif isinstance(data, dict):
items = data.get(""@graph"", [data])
else:
continue
for item in items:
if isinstance(item, dict) and item.get(""@type"") in [""NewsArticle"", ""Article"", ""BlogPosting""]:
title = item.get(""headline"", """")
date = item.get(""datePublished"", """") or item.get(""dateCreated"", """")",claude-sonnet-4-6,claude
code_ai_023,ai,code,javascript,"function debounce(callback, n) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(this, args);
}, n);
};
}",claude-sonnet-4-6,claude
code_ai_024,ai,code,javascript,"class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
return this;
}
off(event, listener) {
if (!this.events[event]) {
return this;
}
this.events[event] = this.events[event].filter((l) => l !== listener);
if (this.events[event].length === 0) {
delete this.events[event];
}
return this;
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach((listener) => {
listener(...args);
});
return true;
}
}
// Example usage
const emitter = new EventEmitter();
const greet = (name) => console.log(`Hello, ${name}!`);
const farewell = (name) => console.log(`Goodbye, ${name}!`);
emitter.on(""greet"", greet);
emitter.on(""greet"", farewell);
console.log(""Emitting 'greet' event:"");
emitter.emit(""greet"", ""Alice"");
console.log(""\nRemoving 'farewell' listener:"");
emitter.off(""greet"", farewell);
console.log(""Emitting 'greet' event again:"");
emitter.emit(""greet"", ""Bob"");
console.log(""\nEmitting non-existent event:"");
const result = emitter.emit(""nonExistent"");
console.log(`Event emitted: ${result}`);",claude-sonnet-4-6,claude
code_ai_025,ai,code,python,"import re
def is_valid_email(email: str) -> bool:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == ""__main__"":
test_emails = [
""user@example.com"",
""user.name+tag@domain.co.uk"",
""user@subdomain.domain.com"",
""invalid-email"",
""missing@domain"",
""@nodomain.com"",
""spaces in@email.com"",
""user@.com"",
""user@domain."",
""valid_email123@company.org""
]
for email in test_emails:
result = is_valid_email(email)
print(f""{email}: {'Valid' if result else 'Invalid'}"")",claude-sonnet-4-6,claude
code_ai_026,ai,code,python,"from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
if __name__ == ""__main__"":
cache = LRUCache(2)
cache.put(1, 1)
print(f""Put (1, 1): cache = {dict(cache.cache)}"")
cache.put(2, 2)
print(f""Put (2, 2): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
cache.put(3, 3)
print(f""Put (3, 3): cache = {dict(cache.cache)}"")
print(f""Get 2: {cache.get(2)}"")
cache.put(4, 4)
print(f""Put (4, 4): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
print(f""Get 3: {cache.get(3)}"")
print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude
code_ai_027,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) {
// Handle null and non-object types
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle circular references
if (visited.has(obj)) {
return visited.get(obj);
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Map
if (obj instanceof Map) {
const mapClone = new Map();
visited.set(obj, mapClone);
obj.forEach((value, key) => {
mapClone.set(deepClone(key, visited), deepClone(value, visited));
});
return mapClone;
}
// Handle Set
if (obj instanceof Set) {
const setClone = new Set();
visited.set(obj, setClone);
obj.forEach((value) => {
setClone.add(deepClone(value, visited));
});
return setClone;
}
// Handle Array
if (Array.isArray(obj)) {
const arrayClone = [];
visited.set(obj, arrayClone);
obj.forEach((item, index) => {
arrayClone[index] = deepClone(item, visited);
});
return arrayClone;
}
// Handle ArrayBuffer
if (obj instanceof ArrayBuffer) {
return obj.slice(0);
}
// Handle TypedArrays
if (ArrayBuffer.isView(obj)) {
return new obj.constructor(obj);
}
// Handle Symbol keys
const clone = Object.create(Object.getPrototypeOf(obj));
visited.set(obj, clone);
// Clone regular string keys
for (const key of Object.keys(obj)) {
clone[key] = deepClone(obj[key], visited);
}
// Clone symbol keys
for (const sym of Object.getOwnPropertySymbols(obj)) {
clone[sym] = deepClone(obj[sym], visited);
}
return clone;
}
// Example usage:
const original = {
name: 'John',
age: 30,",claude-sonnet-4-6,claude
code_ai_028,ai,code,python,"def generate_permutations(lst):
if len(lst) <= 1:
return [lst]
permutations = []
for i, element in enumerate(lst):
remaining = lst[:i] + lst[i+1:]
for perm in generate_permutations(remaining):
permutations.append([element] + perm)
return permutations
if __name__ == ""__main__"":
sample_list = [1, 2, 3]
result = generate_permutations(sample_list)
print(f""All permutations of {sample_list}:"")
for perm in result:
print(perm)
print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude
code_ai_029,ai,code,python,"import time
import logging
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@contextmanager
def timer(label=""Code block""):
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f""{label} executed in {elapsed_time:.6f} seconds"")
if __name__ == ""__main__"":
with timer(""Sleep example""):
time.sleep(1.5)
with timer(""List comprehension""):
result = [x ** 2 for x in range(100000)]
with timer(""String concatenation""):
text = """"
for i in range(10000):
text += str(i)",claude-sonnet-4-6,claude
code_ai_030,ai,code,python,"import pandas as pd
import numpy as np
import csv
import os
def compute_summary_statistics(file_path: str) -> dict:
""""""
Reads a CSV file and computes summary statistics for each numeric column.
Args:
file_path: Path to the CSV file
Returns:
A dictionary with column names as keys and statistics as values
""""""
if not os.path.exists(file_path):
raise FileNotFoundError(f""File not found: {file_path}"")
df = pd.read_csv(file_path)
numeric_columns = df.select_dtypes(include=[np.number]).columns
if len(numeric_columns) == 0:
print(""No numeric columns found in the CSV file."")
return {}
summary = {}
for col in numeric_columns:
col_data = df[col].dropna()
summary[col] = {
""count"": len(col_data),
""missing_values"": df[col].isna().sum(),
""mean"": col_data.mean(),
""median"": col_data.median(),
""mode"": col_data.mode()[0] if not col_data.mode().empty else None,
""std"": col_data.std(),
""variance"": col_data.var(),
""min"": col_data.min(),
""max"": col_data.max(),
""range"": col_data.max() - col_data.min(),
""25th_percentile"": col_data.quantile(0.25),
""75th_percentile"": col_data.quantile(0.75),
""iqr"": col_data.quantile(0.75) - col_data.quantile(0.25),
""skewness"": col_data.skew(),
""kurtosis"": col_data.kurt(),
""sum"": col_data.sum()
}
return summary
def print_summary_statistics(file_path: str) -> None:
""""""
Prints formatted summary statistics for each numeric column in a CSV file.
Args:
file_path: Path to the CSV file
""""""
summary = compute_summary_statistics(file_path)
if not summary:
return
print(f""\n{'='*60}"")
print(f""Summary Statistics for: {os.path",claude-sonnet-4-6,claude
code_ai_031,ai,code,python,"class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert_recursive(node.left, value)
elif value > node.value:
if node.right is None:
node.right = Node(value)
else:
self._insert_recursive(node.right, value)
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self._search_recursive(node.left, value)
else:
return self._search_recursive(node.right, value)
def delete(self, value):
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value):
if node is None:
return None
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node with only one child or no child
if node.left is None:
return node.right
elif node.right is None:
return node.left
# Node with two children: get inorder successor (smallest in right subtree)
min_larger_node = self._get_min(node.right)
node.value = min_larger_node.value
node.right = self._delete_recursive(node.right, min_larger_node.value)
return node
def _get_min(self, node):
current = node
while current.left is not None:
current = current.left
return current
def inorder_traversal(self):
result = []",claude-sonnet-4-6,claude
code_ai_032,ai,code,python,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import re
def scrape_news_articles(url: str, headers: dict = None) -> list[dict]:
""""""
Scrape article titles and dates from a news website.
Args:
url: The URL of the news website to scrape
headers: Optional HTTP headers for the request
Returns:
List of dictionaries containing article titles and dates
""""""
if headers is None:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f""Error fetching URL: {e}"")
return []
soup = BeautifulSoup(response.content, 'html.parser')
articles = []
# Common patterns for article titles and dates
title_selectors = [
'h1', 'h2', 'h3',
'article h1', 'article h2', 'article h3',
'.article-title', '.post-title', '.entry-title',
'.headline', '.news-title', '.story-title',
'[class*=""title""]', '[class*=""headline""]',
'a[href*=""/article""]', 'a[href*=""/news""]',
'a[href*=""/story""]', 'a[href*=""/post""]'
]
date_selectors = [
'time', '.date', '.published', '.post-date',
'.article-date', '.entry-date', '.timestamp',
'[class*=""date""]', '[class*=""time""]', '[class*=""published""]',
'[datetime]', 'span[class*=""date""]', 'p[class*=""date""]'
]
# Try to find article containers first
article_containers = soup.find_all(['article', 'div'],
class_=re.compile(r'article|post|news|story|card', re.I))
if article_containers:
for",claude-sonnet-4-6,claude
code_ai_033,ai,code,javascript,"function debounce(callback, n) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, args);
}, n);
};
}
// Example usage
const debouncedFunction = debounce((message) => {
console.log(`Called with: ${message}`);
}, 500);
debouncedFunction(""Hello"");
debouncedFunction(""Hello again"");
debouncedFunction(""Final call""); // Only this will execute after 500ms",claude-sonnet-4-6,claude
code_ai_034,ai,code,javascript,"class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
return this;
}
off(event, listener) {
if (!this.events[event]) {
return this;
}
this.events[event] = this.events[event].filter(l => l !== listener);
if (this.events[event].length === 0) {
delete this.events[event];
}
return this;
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach(listener => listener(...args));
return true;
}
}
// Example usage
const emitter = new EventEmitter();
const greet = (name) => console.log(`Hello, ${name}!`);
const farewell = (name) => console.log(`Goodbye, ${name}!`);
emitter.on('greet', greet);
emitter.on('greet', farewell);
emitter.emit('greet', 'Alice');
// Output:
// Hello, Alice!
// Goodbye, Alice!
emitter.off('greet', farewell);
emitter.emit('greet', 'Bob');
// Output:
// Hello, Bob!",claude-sonnet-4-6,claude
code_ai_035,ai,code,python,"import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# Test examples
test_emails = [
""user@example.com"",
""user.name+tag@domain.co.uk"",
""invalid-email"",
""missing@domain"",
""@nodomain.com"",
""user@.com"",
""user@domain.c"",
""user123@sub.domain.com""
]
for email in test_emails:
print(f""{email}: {is_valid_email(email)}"")",claude-sonnet-4-6,claude
code_ai_036,ai,code,python,"from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
if __name__ == ""__main__"":
cache = LRUCache(2)
cache.put(1, 1)
print(f""Put (1, 1): cache = {dict(cache.cache)}"")
cache.put(2, 2)
print(f""Put (2, 2): cache = {dict(cache.cache)}"")
print(f""Get 1: {cache.get(1)}"")
cache.put(3, 3)
print(f""Put (3, 3): cache = {dict(cache.cache)}"")
print(f""Get 2 (evicted): {cache.get(2)}"")
cache.put(4, 4)
print(f""Put (4, 4): cache = {dict(cache.cache)}"")
print(f""Get 1 (evicted): {cache.get(1)}"")
print(f""Get 3: {cache.get(3)}"")
print(f""Get 4: {cache.get(4)}"")",claude-sonnet-4-6,claude
code_ai_037,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) {
// Handle null and non-object types
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle circular references
if (visited.has(obj)) {
return visited.get(obj);
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Map
if (obj instanceof Map) {
const mapClone = new Map();
visited.set(obj, mapClone);
obj.forEach((value, key) => {
mapClone.set(deepClone(key, visited), deepClone(value, visited));
});
return mapClone;
}
// Handle Set
if (obj instanceof Set) {
const setClone = new Set();
visited.set(obj, setClone);
obj.forEach((value) => {
setClone.add(deepClone(value, visited));
});
return setClone;
}
// Handle Array
if (Array.isArray(obj)) {
const arrClone = [];
visited.set(obj, arrClone);
obj.forEach((item, index) => {
arrClone[index] = deepClone(item, visited);
});
return arrClone;
}
// Handle ArrayBuffer
if (obj instanceof ArrayBuffer) {
return obj.slice(0);
}
// Handle TypedArrays
if (ArrayBuffer.isView(obj)) {
return new obj.constructor(obj.buffer.slice(0));
}
// Handle plain objects
const objClone = Object.create(Object.getPrototypeOf(obj));
visited.set(obj, objClone);
// Copy all own properties including non-enumerable ones
[...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)].forEach((key) => {
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.value !== undefined) {
descriptor.value = deepClone(descriptor.value, visited);
}
Object.defineProperty(objClone, key, descriptor);",claude-sonnet-4-6,claude
code_ai_038,ai,code,python,"def get_permutations(lst):
if len(lst) <= 1:
return [lst]
permutations = []
for i, element in enumerate(lst):
remaining = lst[:i] + lst[i+1:]
for perm in get_permutations(remaining):
permutations.append([element] + perm)
return permutations
if __name__ == ""__main__"":
sample_list = [1, 2, 3]
result = get_permutations(sample_list)
print(f""All permutations of {sample_list}:"")
for perm in result:
print(perm)
print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude
code_ai_039,ai,code,python,"import time
import logging
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@contextmanager
def timer(name: str = ""Code block""):
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f""{name} executed in {elapsed_time:.4f} seconds"")
# Example usage
if __name__ == ""__main__"":
with timer(""Sleep example""):
time.sleep(1.5)
with timer(""List comprehension""):
result = [x ** 2 for x in range(1000000)]
with timer(""String concatenation""):
text = """"
for i in range(10000):
text += str(i)",claude-sonnet-4-6,claude
code_ai_040,ai,code,python,"import pandas as pd
import numpy as np
import csv
import os
def compute_summary_statistics(file_path: str) -> dict:
""""""
Reads a CSV file and computes summary statistics for each numeric column.
Args:
file_path: Path to the CSV file
Returns:
Dictionary with column names as keys and statistics as values
""""""
if not os.path.exists(file_path):
raise FileNotFoundError(f""File not found: {file_path}"")
df = pd.read_csv(file_path)
numeric_columns = df.select_dtypes(include=[np.number]).columns
if len(numeric_columns) == 0:
print(""No numeric columns found in the CSV file."")
return {}
summary = {}
for col in numeric_columns:
col_data = df[col].dropna()
summary[col] = {
""count"": len(col_data),
""missing_values"": df[col].isna().sum(),
""mean"": col_data.mean(),
""median"": col_data.median(),
""mode"": col_data.mode()[0] if not col_data.mode().empty else None,
""std_dev"": col_data.std(),
""variance"": col_data.var(),
""min"": col_data.min(),
""max"": col_data.max(),
""range"": col_data.max() - col_data.min(),
""25th_percentile"": col_data.quantile(0.25),
""75th_percentile"": col_data.quantile(0.75),
""iqr"": col_data.quantile(0.75) - col_data.quantile(0.25),
""skewness"": col_data.skew(),
""kurtosis"": col_data.kurt(),
""sum"": col_data.sum()
}
return summary
def print_summary_statistics(summary: dict) -> None:
""""""
Prints the summary statistics in a formatted way.
Args:
summary: Dictionary containing summary statistics per column
""""""
if not summary:
print(""No statistics to display."")
return
for col, stats in summary.items():
print(f""\n{'='*50}"")
print(f""Column: {col}"")
print(f",claude-sonnet-4-6,claude
code_ai_041,ai,code,python,"class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert_recursive(node.left, value)
elif value > node.value:
if node.right is None:
node.right = Node(value)
else:
self._insert_recursive(node.right, value)
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self._search_recursive(node.left, value)
else:
return self._search_recursive(node.right, value)
def delete(self, value):
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value):
if node is None:
return None
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node with only one child or no child
if node.left is None:
return node.right
elif node.right is None:
return node.left
# Node with two children: get inorder successor (smallest in right subtree)
min_larger_node = self._get_min(node.right)
node.value = min_larger_node.value
node.right = self._delete_recursive(node.right, min_larger_node.value)
return node
def _get_min(self, node):
current = node
while current.left is not None:
current = current.left
return current
def inorder_traversal(self):
result = []",claude-sonnet-4-6,claude
code_ai_042,ai,code,python,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import time
import re
def scrape_news_articles(url: str, headers: dict = None) -> list[dict]:
""""""
Scrape article titles and dates from a news website.
Args:
url: The URL of the news website to scrape
headers: Optional HTTP headers to use for the request
Returns:
List of dictionaries containing article titles and dates
""""""
if headers is None:
headers = {
""User-Agent"": ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""
""(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36""
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f""Error fetching URL: {e}"")
return []
soup = BeautifulSoup(response.text, ""html.parser"")
articles = []
# Try multiple common patterns for news articles
articles = (
_extract_from_article_tags(soup) or
_extract_from_common_classes(soup) or
_extract_from_headings(soup)
)
return articles
def _extract_from_article_tags(soup: BeautifulSoup) -> list[dict]:
""""""Extract articles from <article> HTML tags.""""""
articles = []
article_tags = soup.find_all(""article"")
for article in article_tags:
title = _extract_title(article)
date = _extract_date(article)
if title:
articles.append({
""title"": title,
""date"": date or ""Date not found"",
""url"": _extract_url(article)
})
return articles
def _extract_from_common_classes(soup: BeautifulSoup) -> list[dict]:
""""""Extract articles using common CSS class patterns.""""""
articles = []
# Common class patterns used by news websites
class_patterns = [
""article"", ""post"", ""news-item"", ""story"", ""entry"",
""card"", ""list-item"", ""news-article"", ""article-item""
]",claude-sonnet-4-6,claude
code_ai_043,ai,code,javascript,"function debounce(callback, n) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(this, args);
}, n);
};
}
// Example usage:
const debouncedFn = debounce((value) => {
console.log(""Debounced value:"", value);
}, 500);
debouncedFn(""first"");
debouncedFn(""second"");
debouncedFn(""third"");
// Only ""third"" will be logged after 500ms",claude-sonnet-4-6,claude
code_ai_044,ai,code,javascript,"class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
return this;
}
off(event, listener) {
if (!this.events[event]) {
return this;
}
this.events[event] = this.events[event].filter(l => l !== listener);
if (this.events[event].length === 0) {
delete this.events[event];
}
return this;
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach(listener => listener(...args));
return true;
}
}
// Example usage
const emitter = new EventEmitter();
const greet = (name) => console.log(`Hello, ${name}!`);
const farewell = (name) => console.log(`Goodbye, ${name}!`);
emitter.on('greet', greet);
emitter.on('greet', farewell);
emitter.emit('greet', 'Alice');
// Output:
// Hello, Alice!
// Goodbye, Alice!
emitter.off('greet', farewell);
emitter.emit('greet', 'Bob');
// Output:
// Hello, Bob!",claude-sonnet-4-6,claude
code_ai_045,ai,code,python,"import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# Test the function
test_emails = [
""user@example.com"",
""user.name+tag@domain.co.uk"",
""invalid-email"",
""missing@domain"",
""@nodomain.com"",
""user@.com"",
""user@domain."",
""user name@domain.com"",
""user@domain.c"",
""test.email@subdomain.domain.com""
]
for email in test_emails:
print(f""{email}: {'Valid' if is_valid_email(email) else 'Invalid'}"")",claude-sonnet-4-6,claude
code_ai_046,ai,code,python,"class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {} # key -> (value, node)
# Doubly linked list with dummy head and tail
self.head = Node(0, 0) # Most recently used end
self.tail = Node(0, 0) # Least recently used end
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if key in self.cache:
node = self.cache[key]
self._remove(node)
self._insert_front(node)
return node.value
return -1
def put(self, key: int, value: int) -> None:
if key in self.cache:
self._remove(self.cache[key])
node = Node(key, value)
self.cache[key] = node
self._insert_front(node)
if len(self.cache) > self.capacity:
# Remove least recently used (node before tail)
lru_node = self.tail.prev
self._remove(lru_node)
del self.cache[lru_node.key]
def _remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _insert_front(self, node):
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
class Node:
def __init__(self, key: int, value: int):
self.key = key
self.value = value
self.prev = None
self.next = None
# Example usage
if __name__ == ""__main__"":
cache = LRUCache(2)
cache.put(1, 1)
print(f""Put (1, 1)"")
cache.put(2, 2)
print(f""Put (2, 2)"")
print(f""Get 1: {cache.get(1)}"") # returns 1
cache.put(3, 3) # evicts key 2
print(f""Put (3, 3) - evicts key 2"")",claude-sonnet-4-6,claude
code_ai_047,ai,code,javascript,"function deepClone(obj, visited = new WeakMap()) {
// Handle null, undefined, and primitive types
if (obj === null || obj === undefined) {
return obj;
}
if (typeof obj !== ""object"" && typeof obj !== ""function"") {
return obj;
}
// Handle circular references
if (visited.has(obj)) {
return visited.get(obj);
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Map
if (obj instanceof Map) {
const mapClone = new Map();
visited.set(obj, mapClone);
obj.forEach((value, key) => {
mapClone.set(deepClone(key, visited), deepClone(value, visited));
});
return mapClone;
}
// Handle Set
if (obj instanceof Set) {
const setClone = new Set();
visited.set(obj, setClone);
obj.forEach((value) => {
setClone.add(deepClone(value, visited));
});
return setClone;
}
// Handle Array
if (Array.isArray(obj)) {
const arrayClone = [];
visited.set(obj, arrayClone);
obj.forEach((item, index) => {
arrayClone[index] = deepClone(item, visited);
});
return arrayClone;
}
// Handle Function
if (typeof obj === ""function"") {
return obj;
}
// Handle ArrayBuffer
if (obj instanceof ArrayBuffer) {
return obj.slice(0);
}
// Handle TypedArray (e.g., Int8Array, Uint8Array, Float32Array, etc.)
if (ArrayBuffer.isView(obj)) {
return new obj.constructor(obj.buffer.slice(0));
}
// Handle Error
if (obj instanceof Error) {
const errorClone = new obj.constructor(obj.message);
errorClone.stack = obj.stack;
return errorClone;
}
// Handle Symbol keys
const symbolKeys = Object.getOwnPropertySymbols(obj);
// Handle plain objects",claude-sonnet-4-6,claude
code_ai_048,ai,code,python,"def get_permutations(lst):
if len(lst) <= 1:
return [lst]
permutations = []
for i, element in enumerate(lst):
remaining = lst[:i] + lst[i+1:]
for perm in get_permutations(remaining):
permutations.append([element] + perm)
return permutations
if __name__ == ""__main__"":
sample_list = [1, 2, 3]
result = get_permutations(sample_list)
print(f""All permutations of {sample_list}:"")
for perm in result:
print(perm)
print(f""Total permutations: {len(result)}"")",claude-sonnet-4-6,claude
code_ai_049,ai,code,python,"import time
import logging
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@contextmanager
def timer(name=""Code block""):
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f""{name} executed in {elapsed_time:.4f} seconds"")
if __name__ == ""__main__"":
with timer(""Sleep example""):
time.sleep(1.5)
with timer(""List comprehension""):
result = [x ** 2 for x in range(100000)]
with timer(""String concatenation""):
text = """"
for i in range(10000):
text += str(i)",claude-sonnet-4-6,claude
code_human_ext_000,human,code,python,"# wrote this in like 20 min, probably not the cleanest
def merge_sort(arr):
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
left, lc = merge_sort(arr[:mid])
right, rc = merge_sort(arr[mid:])
merged = []
comparisons = lc + rc
i = j = 0
while i < len(left) and j < len(right):
comparisons += 1
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
merged += left[i:] + right[j:]
return merged, comparisons",human_written_extended,human
code_human_ext_001,human,code,python,"import time
from functools import wraps
def ttl_cache(seconds=60):
cache = {}
def decorator(fn):
@wraps(fn)
def wrapper(*args):
now = time.time()
if args in cache:
result, ts = cache[args]
if now - ts < seconds:
return result
result = fn(*args)
cache[args] = (result, now)
return result
wrapper.cache = cache # expose for testing
return wrapper
return decorator
# usage: @ttl_cache(seconds=300)",human_written_extended,human
code_human_ext_002,human,code,javascript,"// exponential backoff retry - learned this pattern from a blog post
// doubles wait time each attempt, adds jitter to avoid thundering herd
async function retry(fn, maxAttempts = 3, baseDelay = 1000) {
let lastErr;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
lastErr = err;
if (attempt === maxAttempts - 1) break;
const delay = baseDelay * Math.pow(2, attempt) + Math.random() * 100;
await new Promise(r => setTimeout(r, delay));
}
}
throw lastErr;
}",human_written_extended,human
code_human_ext_003,human,code,python,"# simple rate limiter using a sliding window
import time
from collections import deque
class RateLimiter:
def __init__(self, max_calls, period):
self.max_calls = max_calls
self.period = period
self.calls = deque()
def allow(self):
now = time.time()
# drop old calls outside window
while self.calls and now - self.calls[0] > self.period:
self.calls.popleft()
if len(self.calls) < self.max_calls:
self.calls.append(now)
return True
return False",human_written_extended,human
code_human_ext_004,human,code,javascript,"function flatten(arr, depth = Infinity) {
// could use arr.flat(depth) but writing it out for clarity
if (depth === 0) return arr.slice();
return arr.reduce((acc, val) => {
if (Array.isArray(val)) {
acc.push(...flatten(val, depth - 1));
} else {
acc.push(val);
}
return acc;
}, []);
}
// flatten([1,[2,[3,[4]]]], 1) => [1,2,[3,[4]]]
// flatten([1,[2,[3,[4]]]]) => [1,2,3,4]",human_written_extended,human
code_ai_ext_000,ai,code,python,"def merge_sort(arr):
comparisons = [0]
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
comparisons[0] += 1
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = sort(arr[:mid])
right = sort(arr[mid:])
return merge(left, right)
sorted_arr = sort(arr)
return sorted_arr, comparisons[0]
if __name__ == ""__main__"":
test_cases = [
[64, 34, 25, 12, 22, 11, 90],
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[1],
[],
[3, 3, 3, 1, 1],
]
for test in test_cases:
sorted_list, num_comparisons = merge_sort(test)
print(f""Original: {test}"")
print(f""Sorted: {sorted_list}"")
print(f""Number of comparisons: {num_comparisons}"")
print(""-"" * 40)",claude-sonnet-4-6,claude
code_ai_ext_001,ai,code,python,"from collections import defaultdict, deque
import heapq
from typing import Optional
class DirectedGraph:
def __init__(self):
self.graph = defaultdict(list)
self.vertices = set()
self.weights = {}
def add_vertex(self, vertex):
""""""Add a vertex to the graph.""""""
self.vertices.add(vertex)
if vertex not in self.graph:
self.graph[vertex] = []
def add_edge(self, source, destination, weight=1):
""""""Add a directed edge from source to destination with optional weight.""""""
self.vertices.add(source)
self.vertices.add(destination)
if destination not in self.graph[source]:
self.graph[source].append(destination)
if destination not in self.graph:
self.graph[destination] = []
self.weights[(source, destination)] = weight
def remove_edge(self, source, destination):
""""""Remove a directed edge from source to destination.""""""
if source in self.graph and destination in self.graph[source]:
self.graph[source].remove(destination)
self.weights.pop((source, destination), None)
def remove_vertex(self, vertex):
""""""Remove a vertex and all its associated edges.""""""
if vertex in self.graph:
del self.graph[vertex]
for v in self.graph:
if vertex in self.graph[v]:
self.graph[v].remove(vertex)
self.vertices.discard(vertex)
keys_to_remove = [key for key in self.weights if vertex in key]
for key in keys_to_remove:
del self.weights[key]
def has_cycle(self):
""""""
Detect if the directed graph contains a cycle using DFS.
Returns True if a cycle exists, False otherwise.
""""""
WHITE, GRAY, BLACK = 0, 1, 2
color = {v: WHITE for v in self.vertices}
def dfs(vertex):
color[vertex] = GRAY
for neighbor in self.graph[vertex]:
if color[neighbor] == GRAY:
return True
if color[neighbor] == WHITE and dfs(neighbor):
return True
color[vertex] = BLACK
return False
for vertex in self.vertices:
if color[vertex] == WHITE:
if dfs(vertex):
return True
return False
def find_cycle(self):
""""""
Find and return a cycle in the graph if one exists.
Returns the cycle as a list of vertices, or None if no cycle exists.
""""""
WHITE, GRAY, BLACK = 0, 1, 2
color",claude-sonnet-4-6,claude
code_ai_ext_002,ai,code,python,"import time
import functools
from typing import Any, Callable, Optional
from collections import OrderedDict
def ttl_cache(ttl: float = 60.0, maxsize: Optional[int] = None):
""""""
A decorator that caches function results with a configurable TTL expiration.
Args:
ttl: Time-to-live in seconds for cached results (default: 60 seconds)
maxsize: Maximum number of entries in cache (default: None = unlimited)
""""""
def decorator(func: Callable) -> Callable:
cache: OrderedDict = OrderedDict()
cache_times: dict = {}
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
# Create a hashable cache key from arguments
key = _make_cache_key(args, kwargs)
current_time = time.time()
# Check if result is in cache and not expired
if key in cache:
if current_time - cache_times[key] < ttl:
# Move to end to maintain LRU order
cache.move_to_end(key)
return cache[key]
else:
# Entry has expired, remove it
del cache[key]
del cache_times[key]
# Call the function and cache the result
result = func(*args, **kwargs)
# If maxsize is set and cache is full, remove oldest entry
if maxsize is not None and len(cache) >= maxsize:
oldest_key = next(iter(cache))
del cache[oldest_key]
del cache_times[oldest_key]
cache[key] = result
cache_times[key] = current_time
return result
def _make_cache_key(args, kwargs):
""""""Create a hashable key from function arguments.""""""
try:
key_parts = [args]
if kwargs:
key_parts.append(tuple(sorted(kwargs.items())))
return hash(tuple(key_parts))
except TypeError:
# Fallback for unhashable types
return hash(str(args) + str(sorted(kwargs.items()) if kwargs else """"))
def cache_info() -> dict:
""""""Return information about the cache.""""""
current_time = time.time()
valid_entries = sum(
1 for key in cache
if current_time - cache_times[key] < ttl
)
return {
""total_entries"": len(cache),
""valid_entries"": valid_entries,
""expired_entries"": len(cache) - valid_entries,
""maxsize"": maxsize,
""ttl"": ttl
}
def cache_clear() -> None:",claude-sonnet-4-6,claude
code_ai_ext_003,ai,code,python,"import re
from dataclasses import dataclass
from enum import Enum
from typing import List
class TokenType(Enum):
SENTENCE = ""SENTENCE""
WORD = ""WORD""
PUNCTUATION = ""PUNCTUATION""
WHITESPACE = ""WHITESPACE""
NUMBER = ""NUMBER""
@dataclass
class Token:
type: TokenType
value: str
position: int
def __repr__(self):
return f""Token(type={self.type.value}, value={self.value!r}, position={self.position})""
class Tokenizer:
def __init__(self):
self.sentence_endings = re.compile(r'(?<=[.!?])\s+(?=[A-Z])|(?<=[.!?])\s*$')
self.word_pattern = re.compile(r""[a-zA-Z]+(?:'[a-zA-Z]+)*"")
self.number_pattern = re.compile(r'\d+(?:\.\d+)?')
self.punctuation_pattern = re.compile(r'[^\w\s]')
self.whitespace_pattern = re.compile(r'\s+')
def tokenize_into_sentences(self, text: str) -> List[str]:
""""""Split text into sentences.""""""
sentence_pattern = re.compile(r'(?<=[.!?])\s+')
sentences = sentence_pattern.split(text.strip())
return [s.strip() for s in sentences if s.strip()]
def tokenize_into_words(self, text: str) -> List[Token]:
""""""Split text into word tokens.""""""
tokens = []
for match in self.word_pattern.finditer(text):
tokens.append(Token(
type=TokenType.WORD,
value=match.group(),
position=match.start()
))
return tokens
def tokenize(self, text: str) -> dict:
""""""
Full tokenization returning sentences, words, and punctuation tokens.
""""""
result = {
'sentences': [],
'tokens': []
}
sentences = self.tokenize_into_sentences(text)
result['sentences'] = sentences
position = 0
i = 0
while i < len(text):
char = text[i]
word_match = self.word_pattern.match(text, i)
if word_match:
result['tokens'].append(Token(
type=TokenType.WORD,
value=word_match.group(),
position=i
))
i = word_match.end()
continue
number_match = self.number_pattern.match(text, i)
if number_match:
result['tokens'].append(Token(
type=TokenType.NUMBER,",claude-sonnet-4-6,claude
code_ai_ext_004,ai,code,javascript,"function retry(asyncOperation, maxAttempts = 3, baseDelay = 1000) {
return new Promise((resolve, reject) => {
const attempt = (attemptNumber) => {
asyncOperation()
.then(resolve)
.catch((error) => {
if (attemptNumber >= maxAttempts) {
reject(
new Error(
`Operation failed after ${maxAttempts} attempts. Last error: ${error.message}`
)
);
return;
}
const delay = baseDelay * Math.pow(2, attemptNumber - 1);
console.log(
`Attempt ${attemptNumber} failed. Retrying in ${delay}ms...`
);
setTimeout(() => {
attempt(attemptNumber + 1);
}, delay);
});
};
attempt(1);
});
}
// ==================== USAGE EXAMPLES ====================
// Example 1: Simulating a flaky API call
function createFlakyOperation(failTimes = 2) {
let callCount = 0;
return function flakyOperation() {
callCount++;
return new Promise((resolve, reject) => {
if (callCount <= failTimes) {
reject(new Error(`Simulated failure on attempt ${callCount}`));
} else {
resolve(`Success on attempt ${callCount}`);
}
});
};
}
// Example 2: With jitter (randomized delay to prevent thundering herd)
function retryWithJitter(
asyncOperation,
maxAttempts = 3,
baseDelay = 1000,
jitterFactor = 0.1
) {
return new Promise((resolve, reject) => {
const attempt = (attemptNumber) => {
asyncOperation()
.then(resolve)
.catch((error) => {
if (attemptNumber >= maxAttempts) {
reject(
new Error(
`Operation failed after ${maxAttempts} attempts. Last error: ${error.message}`
)
);
return;
}
const exponentialDelay = baseDelay * Math.pow(2, attemptNumber - 1);
const jitter = exponentialDelay * jitterFactor * Math.random();
const delay = exponentialDelay + jitter;
console.log(
`Attempt ${attemptNumber} failed. Retrying in ${Math.round(delay)}ms (with jitter)...`
);
setTimeout(() => {
attempt(attemptNumber + 1);
}, delay);
});
};
attempt(1);
});
}
// Example 3: With abort signal support
function retryWithAbort(
asyncOperation,
maxAttempts = 3,
baseDe",claude-sonnet-4-6,claude
code_ai_ext_005,ai,code,javascript,"class Observable {
constructor() {
this.subscribers = {};
}
subscribe(event, callback) {
if (!this.subscribers[event]) {
this.subscribers[event] = [];
}
this.subscribers[event].push(callback);
// Return unsubscribe function
return {
unsubscribe: () => {
this.subscribers[event] = this.subscribers[event].filter(
(cb) => cb !== callback
);
},
};
}
publish(event, data) {
if (!this.subscribers[event]) {
return;
}
this.subscribers[event].forEach((callback) => {
callback(data);
});
}
unsubscribeAll(event) {
if (event) {
delete this.subscribers[event];
} else {
this.subscribers = {};
}
}
}
// Example usage
const observable = new Observable();
// Subscribe to events
const subscription1 = observable.subscribe(""userLoggedIn"", (data) => {
console.log(`Subscriber 1: User logged in - ${data.username}`);
});
const subscription2 = observable.subscribe(""userLoggedIn"", (data) => {
console.log(`Subscriber 2: Welcome, ${data.username}!`);
});
const subscription3 = observable.subscribe(""dataUpdated"", (data) => {
console.log(`Data updated: ${JSON.stringify(data)}`);
});
// Publish events
console.log(""--- Publishing userLoggedIn event ---"");
observable.publish(""userLoggedIn"", { username: ""JohnDoe"" });
console.log(""\n--- Publishing dataUpdated event ---"");
observable.publish(""dataUpdated"", { id: 1, value: ""new value"" });
// Unsubscribe subscriber 1
console.log(""\n--- Unsubscribing subscriber 1 ---"");
subscription1.unsubscribe();
console.log(""\n--- Publishing userLoggedIn event after unsubscribe ---"");
observable.publish(""userLoggedIn"", { username: ""JaneDoe"" });
// Unsubscribe all from userLoggedIn
console.log(""\n--- Unsubscribing all from userLoggedIn ---"");
observable.unsubscribeAll(""userLoggedIn"");
console.log(""\n--- Publishing userLoggedIn event after unsubscribeAll ---"");
observable.publish(""userLoggedIn"", { username: ""TestUser"" });
console.log(""\n--- Publishing dataUpdated event (should still work) ---"");
observable.publish(""dataUpdated"", { id: 2, value: ""another value"" });",claude-sonnet-4-6,claude
code_ai_ext_006,ai,code,python,"def parse_and_evaluate(expression: str) -> float:
""""""
Parses and evaluates a simple arithmetic expression string
without using eval().
Supports: +, -, *, /, parentheses, and floating point numbers.
""""""
tokens = tokenize(expression)
pos = 0
def peek():
nonlocal pos
if pos < len(tokens):
return tokens[pos]
return None
def consume():
nonlocal pos
token = tokens[pos]
pos += 1
return token
def parse_expression():
""""""Handle + and - (lowest precedence)""""""
left = parse_term()
while peek() in ('+', '-'):
op = consume()
right = parse_term()
if op == '+':
left += right
else:
left -= right
return left
def parse_term():
""""""Handle * and / (higher precedence)""""""
left = parse_factor()
while peek() in ('*', '/'):
op = consume()
right = parse_factor()
if op == '*':
left *= right
else:
if right == 0:
raise ZeroDivisionError(""Division by zero"")
left /= right
return left
def parse_factor():
""""""Handle numbers, parentheses, and unary operators""""""
token = peek()
if token is None:
raise ValueError(""Unexpected end of expression"")
# Handle unary minus and plus
if token == '-':
consume()
return -parse_factor()
if token == '+':
consume()
return parse_factor()
# Handle parentheses
if token == '(':
consume() # consume '('
result = parse_expression()
if peek() != ')':
raise ValueError(""Missing closing parenthesis"")
consume() # consume ')'
return result
# Handle numbers
try:
consume()
return float(token)
except ValueError:
raise ValueError(f""Unexpected token: {token}"")
result = parse_expression()
if pos < len(tokens):
raise ValueError(f""Unexpected token: {tokens[pos]}"")
return result
def tokenize(expression: str) -> list:
""""""
Converts expression string into list of tokens (numbers and operators).
""""""
tokens = []
i = 0
expression = expression.replace(' ', '') # Remove spaces
while i < len(expression):
char = expression[i]
# Handle numbers (including decimals)
if char.isdigit() or (char == '.' and i + 1 < len(expression)",claude-sonnet-4-6,claude
code_ai_ext_007,ai,code,python,"import threading
from typing import Any, Optional
class ThreadSafeQueue:
def __init__(self, maxsize: int = 0):
self._queue = []
self._maxsize = maxsize
self._mutex = threading.Lock()
self._not_empty = threading.Condition(self._mutex)
self._not_full = threading.Condition(self._mutex)
self._size = 0
def put(self, item: Any, block: bool = True, timeout: Optional[float] = None) -> None:
with self._not_full:
if self._maxsize > 0:
if not block:
if self._size >= self._maxsize:
raise QueueFull(""Queue is full"")
elif timeout is None:
while self._size >= self._maxsize:
self._not_full.wait()
elif timeout < 0:
raise ValueError(""'timeout' must be a non-negative number"")
else:
end_time = threading.Event()
remaining = timeout
while self._size >= self._maxsize:
if not self._not_full.wait(remaining):
raise QueueFull(""Queue is full"")
remaining = timeout - remaining
self._queue.append(item)
self._size += 1
self._not_empty.notify()
def get(self, block: bool = True, timeout: Optional[float] = None) -> Any:
with self._not_empty:
if not block:
if self._size == 0:
raise QueueEmpty(""Queue is empty"")
elif timeout is None:
while self._size == 0:
self._not_empty.wait()
elif timeout < 0:
raise ValueError(""'timeout' must be a non-negative number"")
else:
import time
end_time = time.monotonic() + timeout
while self._size == 0:
remaining = end_time - time.monotonic()
if remaining <= 0:
raise QueueEmpty(""Queue is empty"")
self._not_empty.wait(remaining)
item = self._queue.pop(0)
self._size -= 1
self._not_full.notify()
return item
def put_nowait(self, item: Any) -> None:
self.put(item, block=False)
def get_nowait(self) -> Any:
return self.get(block=False)
def empty(self) -> bool:
with self._mutex:
return self._size == 0
def full(self) -> bool:
with self._mutex:
if self._maxsize <= 0:
return False
return self._size >= self._maxsize
def qsize(self) -> int:",claude-sonnet-4-6,claude
code_ai_ext_008,ai,code,javascript,"function flattenArray(arr, depth = Infinity) {
if (depth === 0) {
return arr.slice();
}
return arr.reduce((result, item) => {
if (Array.isArray(item) && depth > 0) {
result.push(...flattenArray(item, depth - 1));
} else {
result.push(item);
}
return result;
}, []);
}
// Test examples
const nestedArray = [1, [2, [3, [4, [5]]]]];
console.log(""Original array:"", JSON.stringify(nestedArray));
console.log(""Flatten depth 1:"", JSON.stringify(flattenArray(nestedArray, 1)));
console.log(""Flatten depth 2:"", JSON.stringify(flattenArray(nestedArray, 2)));
console.log(""Flatten depth 3:"", JSON.stringify(flattenArray(nestedArray, 3)));
console.log(""Flatten fully (Infinity):"", JSON.stringify(flattenArray(nestedArray)));
const complexArray = [1, [2, 3], [4, [5, 6]], [7, [8, [9, [10]]]]];
console.log(""\nComplex array:"", JSON.stringify(complexArray));
console.log(""Flatten depth 1:"", JSON.stringify(flattenArray(complexArray, 1)));
console.log(""Flatten depth 2:"", JSON.stringify(flattenArray(complexArray, 2)));
console.log(""Flatten fully:"", JSON.stringify(flattenArray(complexArray)));
// Alternative using built-in Array.flat() for comparison
console.log(""\nUsing built-in Array.flat():"");
console.log(""Flatten depth 1:"", JSON.stringify(nestedArray.flat(1)));
console.log(""Flatten fully:"", JSON.stringify(nestedArray.flat(Infinity)));",claude-sonnet-4-6,claude
code_ai_ext_009,ai,code,python,"import time
from collections import deque
from threading import Lock
class RateLimiter:
""""""A simple rate limiter that allows n calls per time window.""""""
def __init__(self, max_calls: int, time_window: float):
""""""
Initialize the rate limiter.
Args:
max_calls: Maximum number of calls allowed per time window
time_window: Time window in seconds
""""""
self.max_calls = max_calls
self.time_window = time_window
self.calls = deque()
self.lock = Lock()
def is_allowed(self) -> bool:
""""""
Check if a call is allowed based on the rate limit.
Returns:
True if the call is allowed, False otherwise
""""""
with self.lock:
now = time.time()
# Remove calls outside the time window
while self.calls and self.calls[0] <= now - self.time_window:
self.calls.popleft()
# Check if we're within the rate limit
if len(self.calls) < self.max_calls:
self.calls.append(now)
return True
return False
def wait_and_call(self) -> float:
""""""
Wait until a call is allowed and record it.
Returns:
The time waited in seconds
""""""
start_time = time.time()
while not self.is_allowed():
with self.lock:
if self.calls:
# Calculate how long to wait
wait_time = self.calls[0] + self.time_window - time.time()
if wait_time > 0:
time.sleep(wait_time)
else:
time.sleep(0.001)
return time.time() - start_time
def remaining_calls(self) -> int:
""""""
Get the number of remaining calls allowed in the current window.
Returns:
Number of remaining calls
""""""
with self.lock:
now = time.time()
# Remove calls outside the time window
while self.calls and self.calls[0] <= now - self.time_window:
self.calls.popleft()
return self.max_calls - len(self.calls)
def reset(self):
""""""Reset the rate limiter by clearing all recorded calls.""""""
with self.lock:
self.calls.clear()
def __repr__(self) -> str:
return f""RateLimiter(max_calls={self.max_calls}, time_window={self.time_window}s)""
def rate_limited(max_calls: int, time_window: float):
""""""
Decorator that",claude-sonnet-4-6,claude
code_human_v2_000,human,code,python,"# min heap - wrote this for an interview prep session
# probably not the cleanest but it works
class MinHeap:
def __init__(self):
self.h = []
def insert(self, val):
self.h.append(val)
i = len(self.h) - 1
# bubble up
while i > 0:
parent = (i - 1) // 2
if self.h[parent] > self.h[i]:
self.h[parent], self.h[i] = self.h[i], self.h[parent]
i = parent
else:
break
def extract_min(self):
if not self.h: return None
if len(self.h) == 1: return self.h.pop()
min_val = self.h[0]
self.h[0] = self.h.pop()
self._sink(0)
return min_val
def _sink(self, i):
n = len(self.h)
while True:
smallest = i
l, r = 2*i+1, 2*i+2
if l < n and self.h[l] < self.h[smallest]: smallest = l
if r < n and self.h[r] < self.h[smallest]: smallest = r
if smallest == i: break
self.h[i], self.h[smallest] = self.h[smallest], self.h[i]
i = smallest",human_written_v2,human
code_human_v2_001,human,code,python,"from collections import defaultdict
import heapq
# dijkstra - took me a while to get the visited set right
def shortest_path(graph, start, end):
dist = {start: 0}
pq = [(0, start)]
prev = {}
visited = set()
while pq:
d, node = heapq.heappop(pq)
if node in visited:
continue
visited.add(node)
if node == end:
# reconstruct path
path = []
cur = end
while cur in prev:
path.append(cur)
cur = prev[cur]
path.append(start)
return d, path[::-1]
for neighbor, weight in graph[node]:
new_dist = d + weight
if neighbor not in dist or new_dist < dist[neighbor]:
dist[neighbor] = new_dist
prev[neighbor] = node
heapq.heappush(pq, (new_dist, neighbor))
return float('inf'), [] # no path found",human_written_v2,human
code_human_v2_002,human,code,javascript,"// LRU cache using Map (Maps preserve insertion order in JS)
// O(1) get and put - the trick is moving accessed keys to end
class LRUCache {
constructor(capacity) {
this.cap = capacity
this.cache = new Map()
}
get(key) {
if (!this.cache.has(key)) return -1
// move to end (most recently used)
const val = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key, val)
return val
}
put(key, val) {
if (this.cache.has(key)) this.cache.delete(key)
else if (this.cache.size >= this.cap) {
// delete least recently used (first item)
this.cache.delete(this.cache.keys().next().value)
}
this.cache.set(key, val)
}
}",human_written_v2,human
code_human_v2_003,human,code,python,"# bloom filter - built this for a distributed dedup project
# false positive rate is approximate, real impl would tune m and k more carefully
import math, hashlib
class BloomFilter:
def __init__(self, capacity, fp_rate=0.01):
self.capacity = capacity
self.fp_rate = fp_rate
# standard formula for optimal m and k
m = -capacity * math.log(fp_rate) / (math.log(2) ** 2)
self.m = int(m)
self.k = int((self.m / capacity) * math.log(2))
self.bits = bytearray(self.m)
def _hashes(self, item):
# use two hash functions to simulate k
h1 = int(hashlib.md5(item.encode()).hexdigest(), 16)
h2 = int(hashlib.sha1(item.encode()).hexdigest(), 16)
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for pos in self._hashes(item):
self.bits[pos] = 1
def __contains__(self, item):
return all(self.bits[pos] for pos in self._hashes(item))",human_written_v2,human
code_human_v2_004,human,code,javascript,"// deep merge - handles the annoying array edge cases
// arrays are replaced not merged (change concat to ... if you want merge behavior)
function deepMerge(target, source) {
const result = { ...target }
for (const key of Object.keys(source)) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
if (target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {
result[key] = deepMerge(target[key], source[key])
} else {
result[key] = deepMerge({}, source[key])
}
} else {
result[key] = source[key]
}
}
return result
}
// test: deepMerge({a:{b:1},c:3}, {a:{d:2},e:4}) => {a:{b:1,d:2},c:3,e:4}",human_written_v2,human
code_human_v2_005,human,code,python,"# run length encoding - simple but surprisingly useful for compression
def rle_encode(s):
if not s:
return ''
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(f'{count}{s[i-1]}' if count > 1 else s[i-1])
count = 1
result.append(f'{count}{s[-1]}' if count > 1 else s[-1])
return ''.join(result)
def rle_decode(s):
result = []
i = 0
while i < len(s):
if s[i].isdigit():
j = i
while j < len(s) and s[j].isdigit():
j += 1
result.append(s[j] * int(s[i:j]))
i = j + 1
else:
result.append(s[i])
i += 1
return ''.join(result)",human_written_v2,human
code_human_v2_006,human,code,javascript,"// simple event emitter - written from scratch, not using Node's EventEmitter
// supports multiple handlers per event, returns unsubscribe function
class EventEmitter {
#handlers = new Map() // private field
on(event, handler) {
if (!this.#handlers.has(event)) {
this.#handlers.set(event, new Set())
}
this.#handlers.get(event).add(handler)
// return cleanup fn
return () => this.off(event, handler)
}
off(event, handler) {
this.#handlers.get(event)?.delete(handler)
}
emit(event, ...args) {
this.#handlers.get(event)?.forEach(h => h(...args))
}
once(event, handler) {
const wrapper = (...args) => {
handler(...args)
this.off(event, wrapper)
}
return this.on(event, wrapper)
}
}",human_written_v2,human
code_human_v2_007,human,code,python,"# topological sort - Kahn's algorithm
# used this in a build system dependency resolver
from collections import deque, defaultdict
def topo_sort(nodes, edges):
""""""
nodes: list of node ids
edges: list of (from, to) tuples meaning 'from' must come before 'to'
returns sorted list or raises ValueError on cycle
""""""
in_degree = defaultdict(int)
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
in_degree[v] += 1
for n in nodes:
in_degree.setdefault(n, 0)
queue = deque(n for n in nodes if in_degree[n] == 0)
result = []
while queue:
node = queue.popleft()
result.append(node)
for neighbor in adj[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
if len(result) != len(nodes):
raise ValueError(""Graph has a cycle"")
return result",human_written_v2,human
code_human_v2_008,human,code,python,"# flatten nested dict - useful for logging and config diffing
def flatten_dict(d, prefix='', sep='.'):
items = {}
for k, v in d.items():
new_key = f""{prefix}{sep}{k}"" if prefix else k
if isinstance(v, dict) and v:
items.update(flatten_dict(v, new_key, sep))
else:
items[new_key] = v
return items
def unflatten_dict(d, sep='.'):
result = {}
for key, val in d.items():
parts = key.split(sep)
cur = result
for part in parts[:-1]:
cur = cur.setdefault(part, {})
cur[parts[-1]] = val
return result",human_written_v2,human
code_human_v2_009,human,code,javascript,"// priority queue backed by binary heap
// used min-heap by default (smaller priority = higher priority)
class PriorityQueue {
#heap = []
#compare
constructor(compare = (a, b) => a - b) {
this.#compare = compare
}
get size() { return this.#heap.length }
peek() { return this.#heap[0] }
push(val) {
this.#heap.push(val)
this.#bubbleUp(this.#heap.length - 1)
}
pop() {
const top = this.#heap[0]
const last = this.#heap.pop()
if (this.#heap.length > 0) {
this.#heap[0] = last
this.#sinkDown(0)
}
return top
}
#bubbleUp(i) {
while (i > 0) {
const parent = (i - 1) >> 1
if (this.#compare(this.#heap[i], this.#heap[parent]) < 0) {
;[this.#heap[i], this.#heap[parent]] = [this.#heap[parent], this.#heap[i]]
i = parent
} else break
}
}
#sinkDown(i) {
const n = this.#heap.length
while (true) {
let smallest = i
const l = 2*i+1, r = 2*i+2
if (l < n && this.#compare(this.#heap[l], this.#heap[smallest]) < 0) smallest = l
if (r < n && this.#compare(this.#heap[r], this.#heap[smallest]) < 0) smallest = r
if (smallest === i) break
;[this.#heap[i], this.#heap[smallest]] = [this.#heap[smallest], this.#heap[i]]
i = smallest
}
}
}",human_written_v2,human
|