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
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
|
module CodeRay
module Scanners
class Ruby < Scanner
RESERVED_WORDS = [
'and', 'def', 'end', 'in', 'or', 'unless', 'begin',
'defined?', 'ensure', 'module', 'redo', 'super', 'until',
'BEGIN', 'break', 'do', 'next', 'rescue', 'then',
'when', 'END', 'case', 'else', 'for', 'retry',
'while', 'alias', 'class', 'elsif', 'if', 'not', 'return',
'undef', 'yield',
]
DEF_KEYWORDS = ['def']
MODULE_KEYWORDS = ['class', 'module']
DEF_NEW_STATE = WordList.new(:initial).
add(DEF_KEYWORDS, :def_expected).
add(MODULE_KEYWORDS, :module_expected)
WORDS_ALLOWING_REGEXP = [
'and', 'or', 'not', 'while', 'until', 'unless', 'if', 'elsif', 'when'
]
REGEXP_ALLOWED = WordList.new(false).
add(WORDS_ALLOWING_REGEXP, :set)
PREDEFINED_CONSTANTS = [
'nil', 'true', 'false', 'self',
'DATA', 'ARGV', 'ARGF', '__FILE__', '__LINE__',
]
IDENT_KIND = WordList.new(:ident).
add(RESERVED_WORDS, :reserved).
add(PREDEFINED_CONSTANTS, :pre_constant)
METHOD_NAME = / #{IDENT} [?!]? /xo
METHOD_NAME_EX = /
#{METHOD_NAME} # common methods: split, foo=, empty?, gsub!
| \*\*? # multiplication and power
| [-+~]@? # plus, minus
| [\/%&|^`] # division, modulo or format strings, &and, |or, ^xor, `system`
| \[\]=? # array getter and setter
| <=?>? | >=? # comparison, rocket operator
| << | >> # append or shift left, shift right
| ===? # simple equality and case equality
/ox
GLOBAL_VARIABLE = / \$ (?: #{IDENT} | \d+ | [~&+`'=\/,;_.<>!@0$?*":F\\] | -[a-zA-Z_0-9] ) /ox
DOUBLEQ = / " [^"\#\\]* (?: (?: \#\{.*?\} | \#(?:$")? | \\. ) [^"\#\\]* )* "? /ox
SINGLEQ = / ' [^'\\]* (?: \\. [^'\\]* )* '? /ox
STRING = / #{SINGLEQ} | #{DOUBLEQ} /ox
SHELL = / ` [^`\#\\]* (?: (?: \#\{.*?\} | \#(?:$`)? | \\. ) [^`\#\\]* )* `? /ox
REGEXP = / \/ [^\/\#\\]* (?: (?: \#\{.*?\} | \#(?:$\/)? | \\. ) [^\/\#\\]* )* \/? /ox
DECIMAL = /\d+(?:_\d+)*/ # doesn't recognize 09 as octal error
OCTAL = /0_?[0-7]+(?:_[0-7]+)*/
HEXADECIMAL = /0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*/
BINARY = /0b[01]+(?:_[01]+)*/
EXPONENT = / [eE] [+-]? #{DECIMAL} /ox
FLOAT = / #{DECIMAL} (?: #{EXPONENT} | \. #{DECIMAL} #{EXPONENT}? ) /
INTEGER = /#{OCTAL}|#{HEXADECIMAL}|#{BINARY}|#{DECIMAL}/
def reset
super
@regexp_allowed = false
end
def next_token
return if @scanner.eos?
kind = :error
if @scanner.scan(/\s+/) # in every state
kind = :space
@regexp_allowed = :set if @regexp_allowed or @scanner.matched.index(?\n) # delayed flag setting
elsif @state == :def_expected
if @scanner.scan(/ (?: (?:#{IDENT}(?:\.|::))* | (?:@@?|$)? #{IDENT}(?:\.|::) ) #{METHOD_NAME_EX} /ox)
kind = :method
@state = :initial
else
@scanner.getch
end
@state = :initial
elsif @state == :module_expected
if @scanner.scan(/<</)
kind = :operator
else
if @scanner.scan(/ (?: #{IDENT} (?:\.|::))* #{IDENT} /ox)
kind = :method
else
@scanner.getch
end
@state = :initial
end
elsif # state == :initial
# IDENTIFIERS, KEYWORDS
if @scanner.scan(GLOBAL_VARIABLE)
kind = :global_variable
elsif @scanner.scan(/ @@ #{IDENT} /ox)
kind = :class_variable
elsif @scanner.scan(/ @ #{IDENT} /ox)
kind = :instance_variable
elsif @scanner.scan(/ __END__\n ( (?!\#CODE\#) .* )? | \#[^\n]* | =begin(?=\s).*? \n=end(?=\s|\z)(?:[^\n]*)? /mx)
kind = :comment
elsif @scanner.scan(METHOD_NAME)
if @last_token_dot
kind = :ident
else
matched = @scanner.matched
kind = IDENT_KIND[matched]
if kind == :ident and matched =~ /^[A-Z]/
kind = :constant
elsif kind == :reserved
@state = DEF_NEW_STATE[matched]
@regexp_allowed = REGEXP_ALLOWED[matched]
end
end
elsif @scanner.scan(STRING)
kind = :string
elsif @scanner.scan(SHELL)
kind = :shell
elsif @scanner.scan(/<<
(?:
([a-zA-Z_0-9]+)
(?: .*? ^\1$ | .* )
|
-([a-zA-Z_0-9]+)
(?: .*? ^\s*\2$ | .* )
|
(["\'`]) (.+?) \3
(?: .*? ^\4$ | .* )
|
- (["\'`]) (.+?) \5
(?: .*? ^\s*\6$ | .* )
)
/mxo)
kind = :string
elsif @scanner.scan(/\//) and @regexp_allowed
@scanner.unscan
@scanner.scan(REGEXP)
kind = :regexp
/%(?:[Qqxrw](?:\([^)#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^)#\\\\]*)*\)?|\[[^\]#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^\]#\\\\]*)*\]?|\{[^}#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^}#\\\\]*)*\}?|<[^>#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\\\\])(?:(?!\1)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\1)[^#\\\\])*)*\1?)|\([^)#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^)#\\\\]*)*\)?|\[[^\]#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^\]#\\\\]*)*\]?|\{[^}#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^}#\\\\]*)*\}?|<[^>#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\s\\\\])(?:(?!\2)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\2)[^#\\\\])*)*\2?|\\\\[^#\\\\]*(?:(?:#\{.*?\}|#)[^#\\\\]*)*\\\\?)/
elsif @scanner.scan(/:(?:#{GLOBAL_VARIABLE}|#{METHOD_NAME_EX}|#{STRING})/ox)
kind = :symbol
elsif @scanner.scan(/
\? (?:
[^\s\\]
|
\\ (?:M-\\C-|C-\\M-|M-\\c|c\\M-|c|C-|M-))? (?: \\ (?: . | [0-7]{3} | x[0-9A-Fa-f][0-9A-Fa-f] )
)
/mox)
kind = :integer
elsif @scanner.scan(/ [-+*\/%=<>;,|&!()\[\]{}~?] | \.\.?\.? | ::? /x)
kind = :operator
@regexp_allowed = :set if @scanner.matched[-1,1] =~ /[~=!<>|&^,\(\[+\-\/\*%]\z/
elsif @scanner.scan(FLOAT)
kind = :float
elsif @scanner.scan(INTEGER)
kind = :integer
else
@scanner.getch
end
end
token = Token.new @scanner.matched, kind
if kind == :regexp
token.text << @scanner.scan(/[eimnosux]*/)
end
@regexp_allowed = (@regexp_allowed == :set) # delayed flag setting
token
end
end
register Ruby, 'ruby', 'rb'
end
end
class Set
include Enumerable
# Creates a new set containing the given objects.
def self.[](*ary)
new(ary)
end
# Creates a new set containing the elements of the given enumerable
# object.
#
# If a block is given, the elements of enum are preprocessed by the
# given block.
def initialize(enum = nil, &block) # :yields: o
@hash ||= Hash.new
enum.nil? and return
if block
enum.each { |o| add(block[o]) }
else
merge(enum)
end
end
# Copy internal hash.
def initialize_copy(orig)
@hash = orig.instance_eval{@hash}.dup
end
# Returns the number of elements.
def size
@hash.size
end
alias length size
# Returns true if the set contains no elements.
def empty?
@hash.empty?
end
# Removes all elements and returns self.
def clear
@hash.clear
self
end
# Replaces the contents of the set with the contents of the given
# enumerable object and returns self.
def replace(enum)
if enum.class == self.class
@hash.replace(enum.instance_eval { @hash })
else
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
clear
enum.each { |o| add(o) }
end
self
end
# Converts the set to an array. The order of elements is uncertain.
def to_a
@hash.keys
end
def flatten_merge(set, seen = Set.new)
set.each { |e|
if e.is_a?(Set)
if seen.include?(e_id = e.object_id)
raise ArgumentError, "tried to flatten recursive Set"
end
seen.add(e_id)
flatten_merge(e, seen)
seen.delete(e_id)
else
add(e)
end
}
self
end
protected :flatten_merge
# Returns a new set that is a copy of the set, flattening each
# containing set recursively.
def flatten
self.class.new.flatten_merge(self)
end
# Equivalent to Set#flatten, but replaces the receiver with the
# result in place. Returns nil if no modifications were made.
def flatten!
if detect { |e| e.is_a?(Set) }
replace(flatten())
else
nil
end
end
# Returns true if the set contains the given object.
def include?(o)
@hash.include?(o)
end
alias member? include?
# Returns true if the set is a superset of the given set.
def superset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size < set.size
set.all? { |o| include?(o) }
end
# Returns true if the set is a proper superset of the given set.
def proper_superset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size <= set.size
set.all? { |o| include?(o) }
end
# Returns true if the set is a subset of the given set.
def subset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size < size
all? { |o| set.include?(o) }
end
# Returns true if the set is a proper subset of the given set.
def proper_subset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size <= size
all? { |o| set.include?(o) }
end
# Calls the given block once for each element in the set, passing
# the element as parameter.
def each
@hash.each_key { |o| yield(o) }
self
end
# Adds the given object to the set and returns self. Use +merge+ to
# add several elements at once.
def add(o)
@hash[o] = true
self
end
alias << add
# Adds the given object to the set and returns self. If the
# object is already in the set, returns nil.
def add?(o)
if include?(o)
nil
else
add(o)
end
end
# Deletes the given object from the set and returns self. Use +subtract+ to
# delete several items at once.
def delete(o)
@hash.delete(o)
self
end
# Deletes the given object from the set and returns self. If the
# object is not in the set, returns nil.
def delete?(o)
if include?(o)
delete(o)
else
nil
end
end
# Deletes every element of the set for which block evaluates to
# true, and returns self.
def delete_if
@hash.delete_if { |o,| yield(o) }
self
end
# Do collect() destructively.
def collect!
set = self.class.new
each { |o| set << yield(o) }
replace(set)
end
alias map! collect!
# Equivalent to Set#delete_if, but returns nil if no changes were
# made.
def reject!
n = size
delete_if { |o| yield(o) }
size == n ? nil : self
end
# Merges the elements of the given enumerable object to the set and
# returns self.
def merge(enum)
if enum.is_a?(Set)
@hash.update(enum.instance_eval { @hash })
else
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
enum.each { |o| add(o) }
end
self
end
# Deletes every element that appears in the given enumerable object
# and returns self.
def subtract(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
enum.each { |o| delete(o) }
self
end
# Returns a new set built by merging the set and the elements of the
# given enumerable object.
def |(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
dup.merge(enum)
end
alias + | ##
alias union | ##
# Returns a new set built by duplicating the set, removing every
# element that appears in the given enumerable object.
def -(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
dup.subtract(enum)
end
alias difference - ##
# Returns a new array containing elements common to the set and the
# given enumerable object.
def &(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
n = self.class.new
enum.each { |o| n.add(o) if include?(o) }
n
end
alias intersection & ##
# Returns a new array containing elements exclusive between the set
# and the given enumerable object. (set ^ enum) is equivalent to
# ((set | enum) - (set & enum)).
def ^(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
n = dup
enum.each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
n
end
# Returns true if two sets are equal. The equality of each couple
# of elements is defined according to Object#eql?.
def ==(set)
equal?(set) and return true
set.is_a?(Set) && size == set.size or return false
hash = @hash.dup
set.all? { |o| hash.include?(o) }
end
def hash # :nodoc:
@hash.hash
end
def eql?(o) # :nodoc:
return false unless o.is_a?(Set)
@hash.eql?(o.instance_eval{@hash})
end
# Classifies the set by the return value of the given block and
# returns a hash of {value => set of elements} pairs. The block is
# called once for each element of the set, passing the element as
# parameter.
#
# e.g.:
#
# require 'set'
# files = Set.new(Dir.glob("*.rb"))
# hash = files.classify { |f| File.mtime(f).year }
# p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
h = {}
each { |i|
x = yield(i)
(h[x] ||= self.class.new).add(i)
}
h
end
# Divides the set into a set of subsets according to the commonality
# defined by the given block.
#
# If the arity of the block is 2, elements o1 and o2 are in common
# if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
# in common if block.call(o1) == block.call(o2).
#
# e.g.:
#
# require 'set'
# numbers = Set[1, 3, 4, 6, 9, 10, 11]
# set = numbers.divide { |i,j| (i - j).abs == 1 }
# p set # => #<Set: {#<Set: {1}>,
# # #<Set: {11, 9, 10}>,
# # #<Set: {3, 4}>,
# # #<Set: {6}>}>
def divide(&func)
if func.arity == 2
require 'tsort'
class << dig = {} # :nodoc:
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
each { |u|
dig[u] = a = []
each{ |v| func.call(u, v) and a << v }
}
set = Set.new()
dig.each_strongly_connected_component { |css|
set.add(self.class.new(css))
}
set
else
Set.new(classify(&func).values)
end
end
InspectKey = :__inspect_key__ # :nodoc:
# Returns a string containing a human-readable representation of the
# set. ("#<Set: {element1, element2, ...}>")
def inspect
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return sprintf('#<%s: {...}>', self.class.name)
end
begin
ids << object_id
return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
ensure
ids.pop
end
end
def pretty_print(pp) # :nodoc:
pp.text sprintf('#<%s: {', self.class.name)
pp.nest(1) {
pp.seplist(self) { |o|
pp.pp o
}
}
pp.text "}>"
end
def pretty_print_cycle(pp) # :nodoc:
pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
end
end
# SortedSet implements a set which elements are sorted in order. See Set.
class SortedSet < Set
@@setup = false
class << self
def [](*ary) # :nodoc:
new(ary)
end
def setup # :nodoc:
@@setup and return
begin
require 'rbtree'
module_eval %{
def initialize(*args, &block)
@hash = RBTree.new
super
end
}
rescue LoadError
module_eval %{
def initialize(*args, &block)
@keys = nil
super
end
def clear
@keys = nil
super
end
def replace(enum)
@keys = nil
super
end
def add(o)
@keys = nil
@hash[o] = true
self
end
alias << add
def delete(o)
@keys = nil
@hash.delete(o)
self
end
def delete_if
n = @hash.size
@hash.delete_if { |o,| yield(o) }
@keys = nil if @hash.size != n
self
end
def merge(enum)
@keys = nil
super
end
def each
to_a.each { |o| yield(o) }
end
def to_a
(@keys = @hash.keys).sort! unless @keys
@keys
end
}
end
@@setup = true
end
end
def initialize(*args, &block) # :nodoc:
SortedSet.setup
initialize(*args, &block)
end
end
module Enumerable
# Makes a set from the enumerable object with given arguments.
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
# =begin
# == RestricedSet class
# RestricedSet implements a set with restrictions defined by a given
# block.
#
# === Super class
# Set
#
# === Class Methods
# --- RestricedSet::new(enum = nil) { |o| ... }
# --- RestricedSet::new(enum = nil) { |rset, o| ... }
# Creates a new restricted set containing the elements of the given
# enumerable object. Restrictions are defined by the given block.
#
# If the block's arity is 2, it is called with the RestrictedSet
# itself and an object to see if the object is allowed to be put in
# the set.
#
# Otherwise, the block is called with an object to see if the object
# is allowed to be put in the set.
#
# === Instance Methods
# --- restriction_proc
# Returns the restriction procedure of the set.
#
# =end
#
# class RestricedSet < Set
# def initialize(*args, &block)
# @proc = block or raise ArgumentError, "missing a block"
#
# if @proc.arity == 2
# instance_eval %{
# def add(o)
# @hash[o] = true if @proc.call(self, o)
# self
# end
# alias << add
#
# def add?(o)
# if include?(o) || !@proc.call(self, o)
# nil
# else
# @hash[o] = true
# self
# end
# end
#
# def replace(enum)
# enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# clear
# enum.each { |o| add(o) }
#
# self
# end
#
# def merge(enum)
# enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# enum.each { |o| add(o) }
#
# self
# end
# }
# else
# instance_eval %{
# def add(o)
# if @proc.call(o)
# @hash[o] = true
# end
# self
# end
# alias << add
#
# def add?(o)
# if include?(o) || !@proc.call(o)
# nil
# else
# @hash[o] = true
# self
# end
# end
# }
# end
#
# super(*args)
# end
#
# def restriction_proc
# @proc
# end
# end
if $0 == __FILE__
eval DATA.read, nil, $0, __LINE__+4
end
# = rweb - CGI Support Library
#
# Author:: Johannes Barre (mailto:rweb@igels.net)
# Copyright:: Copyright (c) 2003, 04 by Johannes Barre
# License:: GNU Lesser General Public License (COPYING, http://www.gnu.org/copyleft/lesser.html)
# Version:: 0.1.0
# CVS-ID:: $Id: rweb.rb 6 2004-06-16 15:56:26Z igel $
#
# == What is Rweb?
# Rweb is a replacement for the cgi class included in the ruby distribution.
#
# == How to use
#
# === Basics
#
# This class is made to be as easy as possible to use. An example:
#
# require "rweb"
#
# web = Rweb.new
# web.out do
# web.puts "Hello world!"
# end
#
# The visitor will get a simple "Hello World!" in his browser. Please notice,
# that won't set html-tags for you, so you should better do something like this:
#
# require "rweb"
#
# web = Rweb.new
# web.out do
# web.puts "<html><body>Hello world!</body></html>"
# end
#
# === Set headers
# Of course, it's also possible to tell the browser, that the content of this
# page is plain text instead of html code:
#
# require "rweb"
#
# web = Rweb.new
# web.out do
# web.header("content-type: text/plain")
# web.puts "Hello plain world!"
# end
#
# Please remember, headers can't be set after the page content has been send.
# You have to set all nessessary headers before the first puts oder print. It's
# possible to cache the content until everything is complete. Doing it this
# way, you can set headers everywhere.
#
# If you set a header twice, the second header will replace the first one. The
# header name is not casesensitive, it will allways converted in to the
# capitalised form suggested by the w3c (http://w3.org)
#
# === Set cookies
# Setting cookies is quite easy:
# include 'rweb'
#
# web = Rweb.new
# Cookie.new("Visits", web.cookies['visits'].to_i +1)
# web.out do
# web.puts "Welcome back! You visited this page #{web.cookies['visits'].to_i +1} times"
# end
#
# See the class Cookie for more details.
#
# === Get form and cookie values
# There are four ways to submit data from the browser to the server and your
# ruby script: via GET, POST, cookies and file upload. Rweb doesn't support
# file upload by now.
#
# include 'rweb'
#
# web = Rweb.new
# web.out do
# web.print "action: #{web.get['action']} "
# web.puts "The value of the cookie 'visits' is #{web.cookies['visits']}"
# web.puts "The post parameter 'test['x']' is #{web.post['test']['x']}"
# end
RWEB_VERSION = "0.1.0"
RWEB = "rweb/#{RWEB_VERSION}"
#require 'rwebcookie' -> edit by bunny :-)
class Rweb
# All parameter submitted via the GET method are available in attribute
# get. This is Hash, where every parameter is available as a key-value
# pair.
#
# If your input tag has a name like this one, it's value will be available
# as web.get["fieldname"]
# <input name="fieldname">
# You can submit values as a Hash
# <input name="text['index']">
# <input name="text['index2']">
# will be available as
# web.get["text"]["index"]
# web.get["text"]["index2"]
# Integers are also possible
# <input name="int[2]">
# <input name="int[3]['hi']>
# will be available as
# web.get["int"][2]
# web.get["int"][3]["hi"]
# If you specify no index, the lowest unused index will be used:
# <input name="int[]"><!-- First Field -->
# <input name="int[]"><!-- Second one -->
# will be available as
# web.get["int"][0] # First Field
# web.get["int"][1] # Second one
# Please notice, this doesn'd work like you might expect:
# <input name="text[index]">
# It will not be available as web.get["text"]["index"] but
# web.get["text[index]"]
attr_reader :get
# All parameters submitted via POST are available in the attribute post. It
# works like the get attribute.
# <input name="text[0]">
# will be available as
# web.post["text"][0]
attr_reader :post
# All cookies submitted by the browser are available in cookies. This is a
# Hash, where every cookie is a key-value pair.
attr_reader :cookies
# The name of the browser identification is submitted as USER_AGENT and
# available in this attribute.
attr_reader :user_agent
# The IP address of the client.
attr_reader :remote_addr
# Creates a new Rweb object. This should only done once. You can set various
# options via the settings hash.
#
# "cache" => true: Everything you script send to the client will be cached
# until the end of the out block or until flush is called. This way, you
# can modify headers and cookies even after printing something to the client.
#
# "safe" => level: Changes the $SAFE attribute. By default, $SAFE will be set
# to 1. If $SAFE is already higher than this value, it won't be changed.
#
# "silend" => true: Normaly, Rweb adds automaticly a header like this
# "X-Powered-By: Rweb/x.x.x (Ruby/y.y.y)". With the silend option you can
# suppress this.
def initialize (settings = {})
# {{{
@header = {}
@cookies = {}
@get = {}
@post = {}
# Internal attributes
@status = nil
@reasonPhrase = nil
@setcookies = []
@output_started = false;
@output_allowed = false;
@mod_ruby = false
@env = ENV.to_hash
if defined?(MOD_RUBY)
@output_method = "mod_ruby"
@mod_ruby = true
elsif @env['SERVER_SOFTWARE'] =~ /^Microsoft-IIS/i
@output_method = "nph"
else
@output_method = "ph"
end
unless settings.is_a?(Hash)
raise TypeError, "settings must be a Hash"
end
@settings = settings
unless @settings.has_key?("safe")
@settings["safe"] = 1
end
if $SAFE < @settings["safe"]
$SAFE = @settings["safe"]
end
unless @settings.has_key?("cache")
@settings["cache"] = false
end
# mod_ruby sets no QUERY_STRING variable, if no GET-Parameters are given
unless @env.has_key?("QUERY_STRING")
@env["QUERY_STRING"] = ""
end
# Now we split the QUERY_STRING by the seperators & and ; or, if
# specified, settings['get seperator']
unless @settings.has_key?("get seperator")
get_args = @env['QUERY_STRING'].split(/[&;]/)
else
get_args = @env['QUERY_STRING'].split(@settings['get seperator'])
end
get_args.each do | arg |
arg_key, arg_val = arg.split(/=/, 2)
arg_key = Rweb::unescape(arg_key)
arg_val = Rweb::unescape(arg_val)
# Parse names like name[0], name['text'] or name[]
pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/
keys = []
while match = pattern.match(arg_key)
arg_key = match[1]
keys = [match[2]] + keys
end
keys = [arg_key] + keys
akt = @get
last = nil
lastkey = nil
keys.each do |key|
if key == ""
# No key specified (like in "test[]"), so we use the
# lowerst unused Integer as key
key = 0
while akt.has_key?(key)
key += 1
end
elsif /^[0-9]*$/ =~ key
# If the index is numerical convert it to an Integer
key = key.to_i
elsif key[0].chr == "'" || key[0].chr == '"'
key = key[1, key.length() -2]
end
if !akt.has_key?(key) || !akt[key].class == Hash
# create an empty Hash if there isn't already one
akt[key] = {}
end
last = akt
lastkey = key
akt = akt[key]
end
last[lastkey] = arg_val
end
if @env['REQUEST_METHOD'] == "POST"
if @env.has_key?("CONTENT_TYPE") && @env['CONTENT_TYPE'] == "application/x-www-form-urlencoded" && @env.has_key?('CONTENT_LENGTH')
unless @settings.has_key?("post seperator")
post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(/[&;]/)
else
post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(@settings['post seperator'])
end
post_args.each do | arg |
arg_key, arg_val = arg.split(/=/, 2)
arg_key = Rweb::unescape(arg_key)
arg_val = Rweb::unescape(arg_val)
# Parse names like name[0], name['text'] or name[]
pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/
keys = []
while match = pattern.match(arg_key)
arg_key = match[1]
keys = [match[2]] + keys
end
keys = [arg_key] + keys
akt = @post
last = nil
lastkey = nil
keys.each do |key|
if key == ""
# No key specified (like in "test[]"), so we use
# the lowerst unused Integer as key
key = 0
while akt.has_key?(key)
key += 1
end
elsif /^[0-9]*$/ =~ key
# If the index is numerical convert it to an Integer
key = key.to_i
elsif key[0].chr == "'" || key[0].chr == '"'
key = key[1, key.length() -2]
end
if !akt.has_key?(key) || !akt[key].class == Hash
# create an empty Hash if there isn't already one
akt[key] = {}
end
last = akt
lastkey = key
akt = akt[key]
end
last[lastkey] = arg_val
end
else
# Maybe we should print a warning here?
$stderr.print("Unidentified form data recived and discarded.")
end
end
if @env.has_key?("HTTP_COOKIE")
cookie = @env['HTTP_COOKIE'].split(/; ?/)
cookie.each do | c |
cookie_key, cookie_val = c.split(/=/, 2)
@cookies [Rweb::unescape(cookie_key)] = Rweb::unescape(cookie_val)
end
end
if defined?(@env['HTTP_USER_AGENT'])
@user_agent = @env['HTTP_USER_AGENT']
else
@user_agent = nil;
end
if defined?(@env['REMOTE_ADDR'])
@remote_addr = @env['REMOTE_ADDR']
else
@remote_addr = nil
end
# }}}
end
# Prints a String to the client. If caching is enabled, the String will
# buffered until the end of the out block ends.
def print(str = "")
# {{{
unless @output_allowed
raise "You just can write to output inside of a Rweb::out-block"
end
if @settings["cache"]
@buffer += [str.to_s]
else
unless @output_started
sendHeaders
end
$stdout.print(str)
end
nil
# }}}
end
# Prints a String to the client and adds a line break at the end. Please
# remember, that a line break is not visible in HTML, use the <br> HTML-Tag
# for this. If caching is enabled, the String will buffered until the end
# of the out block ends.
def puts(str = "")
# {{{
self.print(str + "\n")
# }}}
end
# Alias to print.
def write(str = "")
# {{{
self.print(str)
# }}}
end
# If caching is enabled, all cached data are send to the cliend and the
# cache emptied.
def flush
# {{{
unless @output_allowed
raise "You can't use flush outside of a Rweb::out-block"
end
buffer = @buffer.join
unless @output_started
sendHeaders
end
$stdout.print(buffer)
@buffer = []
# }}}
end
# Sends one or more header to the client. All headers are cached just
# before body data are send to the client. If the same header are set
# twice, only the last value is send.
#
# Example:
# web.header("Last-Modified: Mon, 16 Feb 2004 20:15:41 GMT")
# web.header("Location: http://www.ruby-lang.org")
#
# You can specify more than one header at the time by doing something like
# this:
# web.header("Content-Type: text/plain\nContent-Length: 383")
# or
# web.header(["Content-Type: text/plain", "Content-Length: 383"])
def header(str)
# {{{
if @output_started
raise "HTTP-Headers are already send. You can't change them after output has started!"
end
unless @output_allowed
raise "You just can set headers inside of a Rweb::out-block"
end
if str.is_a?Array
str.each do | value |
self.header(value)
end
elsif str.split(/\n/).length > 1
str.split(/\n/).each do | value |
self.header(value)
end
elsif str.is_a? String
str.gsub!(/\r/, "")
if (str =~ /^HTTP\/1\.[01] [0-9]{3} ?.*$/) == 0
pattern = /^HTTP\/1.[01] ([0-9]{3}) ?(.*)$/
result = pattern.match(str)
self.setstatus(result[0], result[1])
elsif (str =~ /^status: [0-9]{3} ?.*$/i) == 0
pattern = /^status: ([0-9]{3}) ?(.*)$/i
result = pattern.match(str)
self.setstatus(result[0], result[1])
else
a = str.split(/: ?/, 2)
@header[a[0].downcase] = a[1]
end
end
# }}}
end
# Changes the status of this page. There are several codes like "200 OK",
# "302 Found", "404 Not Found" or "500 Internal Server Error". A list of
# all codes is available at
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
#
# You can just send the code number, the reason phrase will be added
# automaticly with the recommendations from the w3c if not specified. If
# you set the status twice or more, only the last status will be send.
# Examples:
# web.status("401 Unauthorized")
# web.status("410 Sad but true, this lonely page is gone :(")
# web.status(206)
# web.status("400")
#
# The default status is "200 OK". If a "Location" header is set, the
# default status is "302 Found".
def status(str)
# {{{
if @output_started
raise "HTTP-Headers are already send. You can't change them after output has started!"
end
unless @output_allowed
raise "You just can set headers inside of a Rweb::out-block"
end
if str.is_a?Integer
@status = str
elsif str.is_a?String
p1 = /^([0-9]{3}) ?(.*)$/
p2 = /^HTTP\/1\.[01] ([0-9]{3}) ?(.*)$/
p3 = /^status: ([0-9]{3}) ?(.*)$/i
if (a = p1.match(str)) == nil
if (a = p2.match(str)) == nil
if (a = p3.match(str)) == nil
raise ArgumentError, "Invalid argument", caller
end
end
end
@status = a[1].to_i
if a[2] != ""
@reasonPhrase = a[2]
else
@reasonPhrase = getReasonPhrase(@status)
end
else
raise ArgumentError, "Argument of setstatus must be integer or string", caller
end
# }}}
end
# Handles the output of your content and rescues all exceptions. Send all
# data in the block to this method. For example:
# web.out do
# web.header("Content-Type: text/plain")
# web.puts("Hello, plain world!")
# end
def out
# {{{
@output_allowed = true
@buffer = []; # We use an array as buffer, because it's more performant :)
begin
yield
rescue Exception => exception
$stderr.puts "Ruby exception rescued (#{exception.class}): #{exception.message}"
$stderr.puts exception.backtrace.join("\n")
unless @output_started
self.setstatus(500)
@header = {}
end
unless (@settings.has_key?("hide errors") and @settings["hide errors"] == true)
unless @output_started
self.header("Content-Type: text/html")
self.puts "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Strict//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"
self.puts "<html>"
self.puts "<head>"
self.puts "<title>500 Internal Server Error</title>"
self.puts "</head>"
self.puts "<body>"
end
if @header.has_key?("content-type") and (@header["content-type"] =~ /^text\/html/i) == 0
self.puts "<h1>Internal Server Error</h1>"
self.puts "<p>The server encountered an exception and was unable to complete your request.</p>"
self.puts "<p>The exception has provided the following information:</p>"
self.puts "<pre style=\"background: #FFCCCC; border: black solid 2px; margin-left: 2cm; margin-right: 2cm; padding: 2mm;\"><b>#{exception.class}</b>: #{exception.message} <b>on</b>"
self.puts
self.puts "#{exception.backtrace.join("\n")}</pre>"
self.puts "</body>"
self.puts "</html>"
else
self.puts "The server encountered an exception and was unable to complete your request"
self.puts "The exception has provided the following information:"
self.puts "#{exception.class}: #{exception.message}"
self.puts
self.puts exception.backtrace.join("\n")
end
end
end
if @settings["cache"]
buffer = @buffer.join
unless @output_started
unless @header.has_key?("content-length")
self.header("content-length: #{buffer.length}")
end
sendHeaders
end
$stdout.print(buffer)
elsif !@output_started
sendHeaders
end
@output_allowed = false;
# }}}
end
# Decodes URL encoded data, %20 for example stands for a space.
def Rweb.unescape(str)
# {{{
if defined? str and str.is_a? String
str.gsub!(/\+/, " ")
str.gsub(/%.{2}/) do | s |
s[1,2].hex.chr
end
end
# }}}
end
protected
def sendHeaders
# {{{
Cookie.disallow # no more cookies can be set or modified
if !(@settings.has_key?("silent") and @settings["silent"] == true) and !@header.has_key?("x-powered-by")
if @mod_ruby
header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION}, #{MOD_RUBY})");
else
header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION})");
end
end
if @output_method == "ph"
if ((@status == nil or @status == 200) and !@header.has_key?("content-type") and !@header.has_key?("location"))
header("content-type: text/html")
end
if @status != nil
$stdout.print "Status: #{@status} #{@reasonPhrase}\r\n"
end
@header.each do |key, value|
key = key *1 # "unfreeze" key :)
key[0] = key[0,1].upcase![0]
key = key.gsub(/-[a-z]/) do |char|
"-" + char[1,1].upcase
end
$stdout.print "#{key}: #{value}\r\n"
end
cookies = Cookie.getHttpHeader # Get all cookies as an HTTP Header
if cookies
$stdout.print cookies
end
$stdout.print "\r\n"
elsif @output_method == "nph"
elsif @output_method == "mod_ruby"
r = Apache.request
if ((@status == nil or @status == 200) and !@header.has_key?("content-type") and !@header.has_key?("location"))
header("text/html")
end
if @status != nil
r.status_line = "#{@status} #{@reasonPhrase}"
end
r.send_http_header
@header.each do |key, value|
key = key *1 # "unfreeze" key :)
key[0] = key[0,1].upcase![0]
key = key.gsub(/-[a-z]/) do |char|
"-" + char[1,1].upcase
end
puts "#{key}: #{value.class}"
#r.headers_out[key] = value
end
end
@output_started = true
# }}}
end
def getReasonPhrase (status)
# {{{
if status == 100
"Continue"
elsif status == 101
"Switching Protocols"
elsif status == 200
"OK"
elsif status == 201
"Created"
elsif status == 202
"Accepted"
elsif status == 203
"Non-Authoritative Information"
elsif status == 204
"No Content"
elsif status == 205
"Reset Content"
elsif status == 206
"Partial Content"
elsif status == 300
"Multiple Choices"
elsif status == 301
"Moved Permanently"
elsif status == 302
"Found"
elsif status == 303
"See Other"
elsif status == 304
"Not Modified"
elsif status == 305
"Use Proxy"
elsif status == 307
"Temporary Redirect"
elsif status == 400
"Bad Request"
elsif status == 401
"Unauthorized"
elsif status == 402
"Payment Required"
elsif status == 403
"Forbidden"
elsif status == 404
"Not Found"
elsif status == 405
"Method Not Allowed"
elsif status == 406
"Not Acceptable"
elsif status == 407
"Proxy Authentication Required"
elsif status == 408
"Request Time-out"
elsif status == 409
"Conflict"
elsif status == 410
"Gone"
elsif status == 411
"Length Required"
elsif status == 412
"Precondition Failed"
elsif status == 413
"Request Entity Too Large"
elsif status == 414
"Request-URI Too Large"
elsif status == 415
"Unsupported Media Type"
elsif status == 416
"Requested range not satisfiable"
elsif status == 417
"Expectation Failed"
elsif status == 500
"Internal Server Error"
elsif status == 501
"Not Implemented"
elsif status == 502
"Bad Gateway"
elsif status == 503
"Service Unavailable"
elsif status == 504
"Gateway Time-out"
elsif status == 505
"HTTP Version not supported"
else
raise "Unknown Statuscode. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 for more information."
end
# }}}
end
end
class Cookie
attr_reader :name, :value, :maxage, :path, :domain, :secure, :comment
# Sets a cookie. Please see below for details of the attributes.
def initialize (name, value = nil, maxage = nil, path = nil, domain = nil, secure = false)
# {{{
# HTTP headers (Cookies are a HTTP header) can only set, while no content
# is send. So an exception will be raised, when @@allowed is set to false
# and a new cookie has set.
unless defined?(@@allowed)
@@allowed = true
end
unless @@allowed
raise "You can't set cookies after the HTTP headers are send."
end
unless defined?(@@list)
@@list = []
end
@@list += [self]
unless defined?(@@type)
@@type = "netscape"
end
unless name.class == String
raise TypeError, "The name of a cookie must be a string", caller
end
if value.class.superclass == Integer || value.class == Float
value = value.to_s
elsif value.class != String && value != nil
raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller
end
if maxage.class == Time
maxage = maxage - Time.now
elsif !maxage.class.superclass == Integer || !maxage == nil
raise TypeError, "The maxage date of a cookie must be an Integer or Time object or nil.", caller
end
unless path.class == String || path == nil
raise TypeError, "The path of a cookie must be nil or a string", caller
end
unless domain.class == String || domain == nil
raise TypeError, "The value of a cookie must be nil or a string", caller
end
unless secure == true || secure == false
raise TypeError, "The secure field of a cookie must be true or false", caller
end
@name, @value, @maxage, @path, @domain, @secure = name, value, maxage, path, domain, secure
@comment = nil
# }}}
end
# Modifies the value of this cookie. The information you want to store. If the
# value is nil, the cookie will be deleted by the client.
#
# This attribute can be a String, Integer or Float object or nil.
def value=(value)
# {{{
if value.class.superclass == Integer || value.class == Float
value = value.to_s
elsif value.class != String && value != nil
raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller
end
@value = value
# }}}
end
# Modifies the maxage of this cookie. This attribute defines the lifetime of
# the cookie, in seconds. A value of 0 means the cookie should be discarded
# imediatly. If it set to nil, the cookie will be deleted when the browser
# will be closed.
#
# Attention: This is different from other implementations like PHP, where you
# gives the seconds since 1/1/1970 0:00:00 GMT.
#
# This attribute must be an Integer or Time object or nil.
def maxage=(maxage)
# {{{
if maxage.class == Time
maxage = maxage - Time.now
elsif maxage.class.superclass == Integer || !maxage == nil
raise TypeError, "The maxage of a cookie must be an Interger or Time object or nil.", caller
end
@maxage = maxage
# }}}
end
# Modifies the path value of this cookie. The client will send this cookie
# only, if the requested document is this directory or a subdirectory of it.
#
# The value of the attribute must be a String object or nil.
def path=(path)
# {{{
unless path.class == String || path == nil
raise TypeError, "The path of a cookie must be nil or a string", caller
end
@path = path
# }}}
end
# Modifies the domain value of this cookie. The client will send this cookie
# only if it's connected with this domain (or a subdomain, if the first
# character is a dot like in ".ruby-lang.org")
#
# The value of this attribute must be a String or nil.
def domain=(domain)
# {{{
unless domain.class == String || domain == nil
raise TypeError, "The domain of a cookie must be a String or nil.", caller
end
@domain = domain
# }}}
end
# Modifies the secure flag of this cookie. If it's true, the client will only
# send this cookie if it is secured connected with us.
#
# The value od this attribute has to be true or false.
def secure=(secure)
# {{{
unless secure == true || secure == false
raise TypeError, "The secure field of a cookie must be true or false", caller
end
@secure = secure
# }}}
end
# Modifies the comment value of this cookie. The comment won't be send, if
# type is "netscape".
def comment=(comment)
# {{{
unless comment.class == String || comment == nil
raise TypeError, "The comment of a cookie must be a string or nil", caller
end
@comment = comment
# }}}
end
# Changes the type of all cookies.
# Allowed values are RFC2109 and netscape (default).
def Cookie.type=(type)
# {{{
unless @@allowed
raise "The cookies are allready send, so you can't change the type anymore."
end
unless type.downcase == "rfc2109" && type.downcase == "netscape"
raise "The type of the cookies must be \"RFC2109\" or \"netscape\"."
end
@@type = type;
# }}}
end
# After sending this message, no cookies can be set or modified. Use it, when
# HTTP-Headers are send. Rweb does this for you.
def Cookie.disallow
# {{{
@@allowed = false
true
# }}}
end
# Returns a HTTP header (type String) with all cookies. Rweb does this for
# you.
def Cookie.getHttpHeader
# {{{
if defined?(@@list)
if @@type == "netscape"
str = ""
@@list.each do |cookie|
if cookie.value == nil
cookie.maxage = 0
cookie.value = ""
end
# TODO: Name and value should be escaped!
str += "Set-Cookie: #{cookie.name}=#{cookie.value}"
unless cookie.maxage == nil
expire = Time.now + cookie.maxage
expire.gmtime
str += "; Expire=#{expire.strftime("%a, %d-%b-%Y %H:%M:%S %Z")}"
end
unless cookie.domain == nil
str += "; Domain=#{cookie.domain}"
end
unless cookie.path == nil
str += "; Path=#{cookie.path}"
end
if cookie.secure
str += "; Secure"
end
str += "\r\n"
end
return str
else # type == "RFC2109"
str = "Set-Cookie: "
comma = false;
@@list.each do |cookie|
if cookie.value == nil
cookie.maxage = 0
cookie.value = ""
end
if comma
str += ","
end
comma = true
str += "#{cookie.name}=\"#{cookie.value}\""
unless cookie.maxage == nil
str += "; Max-Age=\"#{cookie.maxage}\""
end
unless cookie.domain == nil
str += "; Domain=\"#{cookie.domain}\""
end
unless cookie.path == nil
str += "; Path=\"#{cookie.path}\""
end
if cookie.secure
str += "; Secure"
end
unless cookie.comment == nil
str += "; Comment=\"#{cookie.comment}\""
end
str += "; Version=\"1\""
end
str
end
else
false
end
# }}}
end
end
require 'strscan'
module BBCode
DEBUG = true
use 'encoder', 'tags', 'tagstack', 'smileys'
=begin
The Parser class takes care of the encoding.
It scans the given BBCode (as plain text), finds tags
and smilies and also makes links of urls in text.
Normal text is send directly to the encoder.
If a tag was found, an instance of a Tag subclass is created
to handle the case.
The @tagstack manages tag nesting and ensures valid HTML.
=end
class Parser
class Attribute
# flatten and use only one empty_arg
def self.create attr
attr = flatten attr
return @@empty_attr if attr.empty?
new attr
end
private_class_method :new
# remove leading and trailing whitespace; concat lines
def self.flatten attr
attr.strip.gsub(/\n/, ' ')
# -> ^ and $ can only match at begin and end now
end
ATTRIBUTE_SCAN = /
(?!$) # don't match at end
\s*
( # $1 = key
[^=\s\]"\\]*
(?:
(?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? )
[^=\s\]"\\]*
)*
)
(?:
=
( # $2 = value
[^\s\]"\\]*
(?:
(?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? )
[^\s\]"\\]*
)*
)?
)?
\s*
/x
def self.parse source
source = source.dup
# empty_tag: the tag looks like [... /]
# slice!: this deletes the \s*/] at the end
# \s+ because [url=http://rubybb.org/forum/] is NOT an empty tag.
# In RubyBBCode, you can use [url=http://rubybb.org/forum/ /], and this has to be
# interpreted correctly.
empty_tag = source.sub!(/^:/, '=') or source.slice!(/\/$/)
debug 'PARSE: ' + source.inspect + ' => ' + empty_tag.inspect
#-> we have now an attr that's EITHER empty OR begins and ends with non-whitespace.
attr = Hash.new
attr[:flags] = []
source.scan(ATTRIBUTE_SCAN) { |key, value|
if not value
attr[:flags] << unescape(key)
else
next if value.empty? and key.empty?
attr[unescape(key)] = unescape(value)
end
}
debug attr.inspect
return empty_tag, attr
end
def self.unescape_char esc
esc[1]
end
def self.unquote qt
qt[1..-1].chomp('"').gsub(/\\./) { |esc| unescape_char esc }
end
def self.unescape str
str.gsub(/ (\\.) | (" [^"\\]* (?:\\.[^"\\]*)* "?) /x) {
if $1
unescape_char $1
else
unquote $2
end
}
end
include Enumerable
def each &block
@args.each(&block)
end
attr_reader :source, :args, :value
def initialize source
@source = source
debug 'Attribute#new(%p)' % source
@empty_tag, @attr = Attribute.parse source
@value = @attr[''].to_s
end
def empty?
self == @@empty_attr
end
def empty_tag?
@empty_tag
end
def [] *keys
res = @attr[*keys]
end
def flags
attr[:flags]
end
def to_s
@attr
end
def inspect
'ATTR[' + @attr.inspect + (@empty_tag ? ' | empty tag' : '') + ']'
end
end
class Attribute
@@empty_attr = new ''
end
end
class Parser
def Parser.flatten str
# replace mac & dos newlines with unix style
str.gsub(/\r\n?/, "\n")
end
def initialize input = ''
# input manager
@scanner = StringScanner.new ''
# output manager
@encoder = Encoder.new
@output = ''
# tag manager
@tagstack = TagStack.new(@encoder)
@do_magic = true
# set the input
feed input
end
# if you want, you can feed a parser instance after creating,
# or even feed it repeatedly.
def feed food
@scanner.string = Parser.flatten food
end
# parse through the string using parse_token
def parse
parse_token until @scanner.eos?
@tagstack.close_all
@output = parse_magic @encoder.output
end
def output
@output
end
# ok, internals start here
private
# the default output functions. everything should use them or the tags.
def add_text text = @scanner.matched
@encoder.add_text text
end
# use this carefully
def add_html html
@encoder.add_html html
end
# highlights the text as error
def add_garbage garbage
add_html '<span class="error">' if DEBUG
add_text garbage
add_html '</span>' if DEBUG
end
# unknown and incorrectly nested tags are ignored and
# sent as plaintext (garbage in - garbage out).
# in debug mode, garbage is marked with lime background.
def garbage_out start
@scanner.pos = start
garbage = @scanner.scan(/./m)
debug 'GARBAGE: ' + garbage
add_garbage garbage
end
# simple text; everything but [, \[ allowed
SIMPLE_TEXT_SCAN_ = /
[^\[\\]* # normal*
(?: # (
\\.? # special
[^\[\\]* # normal*
)* # )*
/mx
SIMPLE_TEXT_SCAN = /[^\[]+/
=begin
WHAT IS A TAG?
==============
Tags in BBCode can be much more than just a simple [b].
I use many terms here to differ the parts of each tag.
Basic scheme:
[ code ]
TAG START TAG INFO TAG END
Most tags need a second tag to close the range it opened.
This is done with CLOSING TAGS:
[/code]
or by using empty tags that have no content and close themselfes:
[url=winamp.com /]
You surely know this from HTML.
These slashes define the TAG KIND = normal|closing|empty and
cannot be used together.
Everything between [ and ] and expluding the slashes is called the
TAG INFO. This info may contain:
- TAG ID
- TAG NAME including the tag id
- attributes
The TAG ID is the first char of the info:
TAG | ID
----------+----
[quote] | q
[±] | &
["[b]"] | "
[/url] | u
[---] | -
As you can see, the tag id shows the TAG TYPE, it can be a
normal tag, a formatting tag or an entity.
Therefor, the parser first scans the id to decide how to go
on with parsing.
=end
# tag
# TODO more complex expression allowing
# [quote="[ladico]"] and [quote=\[ladico\]] to be correct tags
TAG_BEGIN_SCAN = /
\[ # tag start
( \/ )? # $1 = closing tag?
( [^\]] ) # $2 = tag id
/x
TAG_END_SCAN = /
[^\]]* # rest that was not handled
\]? # tag end
/x
CLOSE_TAG_SCAN = /
( [^\]]* ) # $1 = the rest of the tag info
( \/ )? # $2 = empty tag?
\]? # tag end
/x
UNCLOSED_TAG_SCAN = / \[ /x
CLASSIC_TAG_SCAN = / [a-z]* /ix
SEPARATOR_TAG_SCAN = / \** /x
FORMAT_TAG_SCAN = / -- -* /x
QUOTED_SCAN = /
( # $1 = quoted text
[^"\\]* # normal*
(?: # (
\\. # special
[^"\\]* # normal*
)* # )*
)
"? # end quote "
/mx
ENTITY_SCAN = /
( [^;\]]+ ) # $1 = entity code
;? # optional ending semicolon
/ix
SMILEY_SCAN = Smileys::SMILEY_PATTERN
# this is the main parser loop that separates
# text - everything until "["
# from
# tags - starting with "[", ending with "]"
def parse_token
if @scanner.scan(SIMPLE_TEXT_SCAN)
add_text
else
handle_tag
end
end
def handle_tag
tag_start = @scanner.pos
unless @scanner.scan TAG_BEGIN_SCAN
garbage_out tag_start
return
end
closing, id = @scanner[1], @scanner[2]
#debug 'handle_tag(%p)' % @scanner.matched
handled =
case id
when /[a-z]/i
if @scanner.scan(CLASSIC_TAG_SCAN)
if handle_classic_tag(id + @scanner.matched, closing)
already_closed = true
end
end
when '*'
if @scanner.scan(SEPARATOR_TAG_SCAN)
handle_asterisk tag_start, id + @scanner.matched
true
end
when '-'
if @scanner.scan(FORMAT_TAG_SCAN)
#format = id + @scanner.matched
@encoder.add_html "\n<hr>\n"
true
end
when '"'
if @scanner.scan(QUOTED_SCAN)
@encoder.add_text unescape(@scanner[1])
true
end
when '&'
if @scanner.scan(ENTITY_SCAN)
@encoder.add_entity @scanner[1]
true
end
when Smileys::SMILEY_START_CHARSET
@scanner.pos = @scanner.pos - 1 # (ungetch)
if @scanner.scan(SMILEY_SCAN)
@encoder.add_html Smileys.smiley_to_image(@scanner.matched)
true
end
end # case
return garbage_out(tag_start) unless handled
@scanner.scan(TAG_END_SCAN) unless already_closed
end
ATTRIBUTES_SCAN = /
(
[^\]"\\]*
(?:
(?:
\\.
|
"
[^"\\]*
(?:
\\.
[^"\\]*
)*
"?
)
[^\]"\\]*
)*
)
\]?
/x
def handle_classic_tag name, closing
debug 'TAG: ' + (closing ? '/' : '') + name
# flatten
name.downcase!
tag_class = TAG_LIST[name]
return unless tag_class
#debug((opening ? 'OPEN ' : 'CLOSE ') + tag_class.name)
# create an attribute object to handle it
@scanner.scan(ATTRIBUTES_SCAN)
#debug name + ':' + @scanner[1]
attr = Attribute.create @scanner[1]
#debug 'ATTRIBUTES %p ' % attr #unless attr.empty?
#debug 'closing: %p; name=%s, attr=%p' % [closing, name, attr]
# OPEN
if not closing and tag = @tagstack.try_open_class(tag_class, attr)
#debug 'opening'
tag.do_open @scanner
# this should be done by the tag itself.
if attr.empty_tag?
tag.handle_empty
@tagstack.close_tag
elsif tag.special_content?
handle_special_content(tag)
@tagstack.close_tag
# # ignore asterisks directly after the opening; these are phpBBCode
# elsif tag.respond_to? :asterisk
# debug 'SKIP ASTERISKS: ' if @scanner.skip(ASTERISK_TAGS_SCAN)
end
# CLOSE
elsif @tagstack.try_close_class(tag_class)
#debug 'closing'
# GARBAGE
else
return
end
true
end
def handle_asterisk tag_start, stars
#debug 'ASTERISK: ' + stars.to_s
# rule for asterisk tags: they belong to the last tag
# that handles them. tags opened after this tag are closed.
# if no open tag uses them, all are closed.
tag = @tagstack.close_all_until { |tag| tag.respond_to? :asterisk }
unless tag and tag.asterisk stars, @scanner
garbage_out tag_start
end
end
def handle_special_content tag
scanned = @scanner.scan_until(tag.closing_tag)
if scanned
scanned.slice!(-(@scanner.matched.size)..-1)
else
scanned = @scanner.scan(/.*/m).to_s
end
#debug 'SPECIAL CONTENT: ' + scanned
tag.handle_content(scanned)
end
def unescape text
# input: correctly formatted quoted string (without the quotes)
text.gsub(/\\(?:(["\\])|.)/) { $1 or $& }
end
# MAGIC FEAUTURES
URL_PATTERN = /(?:(?:www|ftp)\.|(?>\w{3,}):\/\/)\S+/
EMAIL_PATTERN = /(?>[\w\-_.]+)@[\w\-\.]+\.\w+/
HAS_MAGIC = /[&@#{Smileys::SMILEY_START_CHARS}]|(?i:www|ftp)/
MAGIC_PATTERN = Regexp.new('(\W|^)(%s)' %
[Smileys::MAGIC_SMILEY_PATTERN, URL_PATTERN, EMAIL_PATTERN].map { |pattern|
pattern.to_s
}.join('|') )
IS_SMILEY_PATTERN = Regexp.new('^%s' % Smileys::SMILEY_START_CHARSET.to_s )
IS_URL_PATTERN = /^(?:(?i:www|ftp)\.|(?>\w+):\/\/)/
URL_STARTS_WITH_PROTOCOL = /^\w+:\/\//
IS_EMAIL_PATTERN = /^[\w\-_.]+@/
def to_magic text
# debug MAGIC_PATTERN.to_s
text.gsub!(MAGIC_PATTERN) {
magic = $2
$1 + case magic
when IS_SMILEY_PATTERN
Smileys.smiley_to_img magic
when IS_URL_PATTERN
last = magic.slice_punctation! # no punctation in my URL
href = magic
href.insert(0, 'http://') unless magic =~ URL_STARTS_WITH_PROTOCOL
'<a href="' + href + '">' + magic + '</a>' + last
when IS_EMAIL_PATTERN
last = magic.slice_punctation!
'<a href="mailto:' + magic + '">' + magic + '</a>' + last
else
raise '{{{' + magic + '}}}'
end
}
text
end
# handles smileys and urls
def parse_magic html
return html unless @do_magic
scanner = StringScanner.new html
out = ''
while scanner.rest?
if scanner.scan(/ < (?: a\s .*? <\/a> | pre\W .*? <\/pre> | [^>]* > ) /mx)
out << scanner.matched
elsif scanner.scan(/ [^<]+ /x)
out << to_magic(scanner.matched)
# this should never happen
elsif scanner.scan(/./m)
raise 'ERROR: else case reached'
end
end
out
end
end # Parser
end
class String
def slice_punctation!
slice!(/[.:,!\?]+$/).to_s # return '' instead of nil
end
end
#
# = Grammar
#
# An implementation of common algorithms on grammars.
#
# This is used by Shinobu, a visualization tool for educating compiler-building.
#
# Thanks to Andreas Kunert for his wonderful LR(k) Pamphlet (German, see http://www.informatik.hu-berlin.de/~kunert/papers/lr-analyse), and Aho/Sethi/Ullman for their Dragon Book.
#
# Homepage:: http://shinobu.cYcnus.de (not existing yet)
# Author:: murphy (Kornelius Kalnbach)
# Copyright:: (cc) 2005 cYcnus
# License:: GPL
# Version:: 0.2.0 (2005-03-27)
require 'set_hash'
require 'ctype'
require 'tools'
require 'rules'
require 'trace'
require 'first'
require 'follow'
# = Grammar
#
# == Syntax
#
# === Rules
#
# Each line is a rule.
# The syntax is
#
# left - right
#
# where +left+ and +right+ can be uppercase and lowercase letters,
# and <code>-</code> can be any combination of <, >, - or whitespace.
#
# === Symbols
#
# Uppercase letters stand for meta symbols, lowercase for terminals.
#
# You can make epsilon-derivations by leaving <code><right></code> empty.
#
# === Example
# S - Ac
# A - Sc
# A - b
# A -
class Grammar
attr_reader :tracer
# Creates a new Grammar.
# If $trace is true, the algorithms explain (textual) what they do to $stdout.
def initialize data, tracer = Tracer.new
@tracer = tracer
@rules = Rules.new
@terminals, @meta_symbols = SortedSet.new, Array.new
@start_symbol = nil
add_rules data
end
attr_reader :meta_symbols, :terminals, :rules, :start_symbol
alias_method :sigma, :terminals
alias_method :alphabet, :terminals
alias_method :variables, :meta_symbols
alias_method :nonterminals, :meta_symbols
# A string representation of the grammar for debugging.
def inspect productions_too = false
'Grammar(meta symbols: %s; alphabet: %s; productions: [%s]; start symbol: %s)' %
[
meta_symbols.join(', '),
terminals.join(', '),
if productions_too
@rules.inspect
else
@rules.size
end,
start_symbol
]
end
# Add rules to the grammar. +rules+ should be a String or respond to +scan+ in a similar way.
#
# Syntax: see Grammar.
def add_rules grammar
@rules = Rules.parse grammar do |rule|
@start_symbol ||= rule.left
@meta_symbols << rule.left
@terminals.merge rule.right.split('').select { |s| terminal? s }
end
@meta_symbols.uniq!
update
end
# Returns a hash acting as FIRST operator, so that
# <code>first["ABC"]</code> is FIRST(ABC).
# See http://en.wikipedia.org/wiki/LL_parser "Constructing an LL(1) parsing table" for details.
def first
first_operator
end
# Returns a hash acting as FOLLOW operator, so that
# <code>first["A"]</code> is FOLLOW(A).
# See http://en.wikipedia.org/wiki/LL_parser "Constructing an LL(1) parsing table" for details.
def follow
follow_operator
end
LLError = Class.new(Exception)
LLErrorType1 = Class.new(LLError)
LLErrorType2 = Class.new(LLError)
# Tests if the grammar is LL(1).
def ll1?
begin
for meta in @meta_symbols
first_sets = @rules[meta].map { |alpha| first[alpha] }
first_sets.inject(Set[]) do |already_used, another_first_set|
unless already_used.disjoint? another_first_set
raise LLErrorType1
end
already_used.merge another_first_set
end
if first[meta].include? EPSILON and not first[meta].disjoint? follow[meta]
raise LLErrorType2
end
end
rescue LLError
false
else
true
end
end
private
def first_operator
@first ||= FirstOperator.new self
end
def follow_operator
@follow ||= FollowOperator.new self
end
def update
@first = @follow = nil
end
end
if $0 == __FILE__
eval DATA.read, nil, $0, __LINE__+4
end
require 'test/unit'
class TestCaseGrammar < Test::Unit::TestCase
include Grammar::Symbols
def fifo s
Set[*s.split('')]
end
def test_fifo
assert_equal Set[], fifo('')
assert_equal Set[EPSILON, END_OF_INPUT, 'x', 'Y'], fifo('?xY$')
end
TEST_GRAMMAR_1 = <<-EOG
S - ABCD
A - a
A -
B - b
B -
C - c
C -
D - S
D -
EOG
def test_symbols
assert EPSILON
assert END_OF_INPUT
end
def test_first_1
g = Grammar.new TEST_GRAMMAR_1
f = nil
assert_nothing_raised { f = g.first }
assert_equal(Set['a', EPSILON], f['A'])
assert_equal(Set['b', EPSILON], f['B'])
assert_equal(Set['c', EPSILON], f['C'])
assert_equal(Set['a', 'b', 'c', EPSILON], f['D'])
assert_equal(f['D'], f['S'])
end
def test_follow_1
g = Grammar.new TEST_GRAMMAR_1
f = nil
assert_nothing_raised { f = g.follow }
assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['A'])
assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['B'])
assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['C'])
assert_equal(Set[END_OF_INPUT], f['D'])
assert_equal(Set[END_OF_INPUT], f['S'])
end
TEST_GRAMMAR_2 = <<-EOG
S - Ed
E - EpT
E - EmT
E - T
T - TuF
T - TdF
T - F
F - i
F - n
F - aEz
EOG
def test_first_2
g = Grammar.new TEST_GRAMMAR_2
f = nil
assert_nothing_raised { f = g.first }
assert_equal(Set['a', 'n', 'i'], f['E'])
assert_equal(Set['a', 'n', 'i'], f['F'])
assert_equal(Set['a', 'n', 'i'], f['T'])
assert_equal(Set['a', 'n', 'i'], f['S'])
end
def test_follow_2
g = Grammar.new TEST_GRAMMAR_2
f = nil
assert_nothing_raised { f = g.follow }
assert_equal(Set['m', 'd', 'z', 'p'], f['E'])
assert_equal(Set['m', 'd', 'z', 'p', 'u'], f['F'])
assert_equal(Set['m', 'd', 'z', 'p', 'u'], f['T'])
assert_equal(Set[END_OF_INPUT], f['S'])
end
LLError = Grammar::LLError
TEST_GRAMMAR_3 = <<-EOG
E - TD
D - pTD
D -
T - FS
S - uFS
S -
S - p
F - aEz
F - i
EOG
NoError = Class.new(Exception)
def test_first_3
g = Grammar.new TEST_GRAMMAR_3
# Grammar 3 is LL(1), so all first-sets must be disjoint.
f = nil
assert_nothing_raised { f = g.first }
assert_equal(Set['a', 'i'], f['E'])
assert_equal(Set[EPSILON, 'p'], f['D'])
assert_equal(Set['a', 'i'], f['F'])
assert_equal(Set['a', 'i'], f['T'])
assert_equal(Set[EPSILON, 'u', 'p'], f['S'])
for m in g.meta_symbols
r = g.rules[m]
firsts = r.map { |x| f[x] }.to_set
assert_nothing_raised do
firsts.inject(Set.new) do |already_used, another_first_set|
raise LLError, 'not disjoint!' unless already_used.disjoint? another_first_set
already_used.merge another_first_set
end
end
end
end
def test_follow_3
g = Grammar.new TEST_GRAMMAR_3
# Grammar 3 is not LL(1), because epsilon is in FIRST(S),
# but FIRST(S) and FOLLOW(S) are not disjoint.
f = nil
assert_nothing_raised { f = g.follow }
assert_equal(Set['z', END_OF_INPUT], f['E'])
assert_equal(Set['z', END_OF_INPUT], f['D'])
assert_equal(Set['z', 'p', 'u', END_OF_INPUT], f['F'])
assert_equal(Set['p', 'z', END_OF_INPUT], f['T'])
assert_equal(Set['p', 'z', END_OF_INPUT], f['S'])
for m in g.meta_symbols
first_m = g.first[m]
next unless first_m.include? EPSILON
assert_raise(m == 'S' ? LLError : NoError) do
if first_m.disjoint? f[m]
raise NoError # this is fun :D
else
raise LLError
end
end
end
end
TEST_GRAMMAR_3b = <<-EOG
E - TD
D - pTD
D - PTD
D -
T - FS
S - uFS
S -
F - aEz
F - i
P - p
EOG
def test_first_3b
g = Grammar.new TEST_GRAMMAR_3b
# Grammar 3b is NOT LL(1), since not all first-sets are disjoint.
f = nil
assert_nothing_raised { f = g.first }
assert_equal(Set['a', 'i'], f['E'])
assert_equal(Set[EPSILON, 'p'], f['D'])
assert_equal(Set['p'], f['P'])
assert_equal(Set['a', 'i'], f['F'])
assert_equal(Set['a', 'i'], f['T'])
assert_equal(Set[EPSILON, 'u'], f['S'])
for m in g.meta_symbols
r = g.rules[m]
firsts = r.map { |x| f[x] }
assert_raise(m == 'D' ? LLError : NoError) do
firsts.inject(Set.new) do |already_used, another_first_set|
raise LLError, 'not disjoint!' unless already_used.disjoint? another_first_set
already_used.merge another_first_set
end
raise NoError
end
end
end
def test_follow_3b
g = Grammar.new TEST_GRAMMAR_3b
# Although Grammar 3b is NOT LL(1), the FOLLOW-condition is satisfied.
f = nil
assert_nothing_raised { f = g.follow }
assert_equal(fifo('z$'), f['E'], 'E')
assert_equal(fifo('z$'), f['D'], 'D')
assert_equal(fifo('ai'), f['P'], 'P')
assert_equal(fifo('z$pu'), f['F'], 'F')
assert_equal(fifo('z$p'), f['T'], 'T')
assert_equal(fifo('z$p'), f['S'], 'S')
for m in g.meta_symbols
first_m = g.first[m]
next unless first_m.include? EPSILON
assert_raise(NoError) do
if first_m.disjoint? f[m]
raise NoError # this is fun :D
else
raise LLError
end
end
end
end
def test_ll1?
assert_equal false, Grammar.new(TEST_GRAMMAR_3).ll1?, 'Grammar 3'
assert_equal false, Grammar.new(TEST_GRAMMAR_3b).ll1?, 'Grammar 3b'
end
def test_new
assert_nothing_raised { Grammar.new '' }
assert_nothing_raised { Grammar.new TEST_GRAMMAR_1 }
assert_nothing_raised { Grammar.new TEST_GRAMMAR_2 }
assert_nothing_raised { Grammar.new TEST_GRAMMAR_3 }
assert_nothing_raised { Grammar.new TEST_GRAMMAR_1 + TEST_GRAMMAR_2 + TEST_GRAMMAR_3 }
assert_raise(ArgumentError) { Grammar.new 'S - ?' }
end
end
# vim:foldmethod=syntax
#!/usr/bin/env ruby
require 'fox12'
include Fox
class Window < FXMainWindow
def initialize(app)
super(app, app.appName + ": First Set Calculation", nil, nil, DECOR_ALL, 0, 0, 800, 600, 0, 0)
# {{{ menubar
menubar = FXMenuBar.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X)
filemenu = FXMenuPane.new(self)
FXMenuCommand.new(filemenu, "&Start\tCtl-S\tStart the application.", nil, getApp()).connect(SEL_COMMAND, method(:start))
FXMenuCommand.new(filemenu, "&Quit\tAlt-F4\tQuit the application.", nil, getApp(), FXApp::ID_QUIT)
FXMenuTitle.new(menubar, "&File", nil, filemenu)
# }}} menubar
# {{{ statusbar
@statusbar = FXStatusBar.new(self, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|STATUSBAR_WITH_DRAGCORNER)
# }}} statusbar
# {{{ window content
horizontalsplitt = FXSplitter.new(self, SPLITTER_VERTICAL|LAYOUT_SIDE_TOP|LAYOUT_FILL)
@productions = FXList.new(horizontalsplitt, nil, 0, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FIX_HEIGHT|LIST_SINGLESELECT)
@productions.height = 100
@result = FXTable.new(horizontalsplitt, nil, 0, LAYOUT_FILL)
@result.height = 200
@result.setTableSize(2, 2, false)
@result.rowHeaderWidth = 0
header = @result.columnHeader
header.setItemText 0, 'X'
header.setItemText 1, 'FIRST(X)'
for item in header
item.justification = FXHeaderItem::CENTER_X
end
@debug = FXText.new(horizontalsplitt, nil, 0, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|LAYOUT_FIX_HEIGHT)
@debug.height = 200
# }}} window content
end
def load_grammar grammar
@tracer = FirstTracer.new(self)
@grammar = Grammar.new grammar, @tracer
@rules_indexes = Hash.new
@grammar.rules.each_with_index do |rule, i|
@productions.appendItem rule.inspect
@rules_indexes[rule] = i
end
end
def create
super
show(PLACEMENT_SCREEN)
end
def rule rule
@productions.selectItem @rules_indexes[rule]
sleep 0.1
end
def iterate i
setTitle i.to_s
sleep 0.1
end
def missing what
@debug.appendText what + "\n"
sleep 0.1
end
def start sender, sel, pointer
Thread.new do
begin
@grammar.first
rescue => boom
@debug.appendText [boom.to_s, *boom.backtrace].join("\n")
end
end
end
end
$: << 'grammar'
require 'grammar'
require 'first_tracer'
app = FXApp.new("Shinobu", "cYcnus")
# fenster erzeugen
window = Window.new app
unless ARGV.empty?
grammar = File.read(ARGV.first)
else
grammar = <<-EOG1
Z --> S
S --> Sb
S --> bAa
A --> aSc
A --> a
A --> aSb
EOG1
end
window.load_grammar grammar
app.create
app.run
require 'erb'
require 'ftools'
require 'yaml'
require 'redcloth'
module WhyTheLuckyStiff
class Book
attr_accessor :author, :title, :terms, :image, :teaser,
:chapters, :expansion_paks, :encoding, :credits
def [] x
@lang.fetch(x) do
warn warning = "[not translated: '#{x}'!]"
warning
end
end
end
def Book::load( file_name )
YAML::load( File.open( file_name ) )
end
class Section
attr_accessor :index, :header, :content
def initialize( i, h, c )
@index, @header, @content = i, h, RedCloth::new( c.to_s )
end
end
class Sidebar
attr_accessor :title, :content
end
YAML::add_domain_type( 'whytheluckystiff.net,2003', 'sidebar' ) do |taguri, val|
YAML::object_maker( Sidebar, 'title' => val.keys.first, 'content' => RedCloth::new( val.values.first ) )
end
class Chapter
attr_accessor :index, :title, :sections
def initialize( i, t, sects )
@index = i
@title = t
i = 0
@sections = sects.collect do |s|
if s.respond_to?( :keys )
i += 1
Section.new( i, s.keys.first, s.values.first )
else
s
end
end
end
end
YAML::add_domain_type( 'whytheluckystiff.net,2003', 'book' ) do |taguri, val|
['chapters', 'expansion_paks'].each do |chaptype|
i = 0
val[chaptype].collect! do |c|
i += 1
Chapter::new( i, c.keys.first, c.values.first )
end
end
val['teaser'].collect! do |t|
Section::new( 1, t.keys.first, t.values.first )
end
val['terms'] = RedCloth::new( val['terms'] )
YAML::object_maker( Book, val )
end
class Image
attr_accessor :file_name
end
YAML::add_domain_type( 'whytheluckystiff.net,2003', 'img' ) do |taguri, val|
YAML::object_maker( Image, 'file_name' => "i/" + val )
end
end
#
# Convert the book to HTML
#
if __FILE__ == $0
unless ARGV[0]
puts "Usage: #{$0} [/path/to/save/html]"
exit
end
site_path = ARGV[0]
book = WhyTheLuckyStiff::Book::load( 'poignant.yml' )
chapter = nil
# Write index page
index_tpl = ERB::new( File.open( 'index.erb' ).read )
File.open( File.join( site_path, 'index.html' ), 'w' ) do |out|
out << index_tpl.result
end
book.chapters = book.chapters[0,3] if ARGV.include? '-fast'
# Write chapter pages
chapter_tpl = ERB::new( File.open( 'chapter.erb' ).read )
book.chapters.each do |chapter|
File.open( File.join( site_path, "chapter-#{ chapter.index }.html" ), 'w' ) do |out|
out << chapter_tpl.result
end
end
exit if ARGV.include? '-fast'
# Write expansion pak pages
expak_tpl = ERB::new( File.open( 'expansion-pak.erb' ).read )
book.expansion_paks.each do |pak|
File.open( File.join( site_path, "expansion-pak-#{ pak.index }.html" ), 'w' ) do |out|
out << expak_tpl.result( binding )
end
end
# Write printable version
print_tpl = ERB::new( File.open( 'print.erb' ).read )
File.open( File.join( site_path, "print.html" ), 'w' ) do |out|
out << print_tpl.result
end
# Copy css + images into site
copy_list = ["guide.css"] +
Dir["i/*"].find_all { |image| image =~ /\.(gif|jpg|png)$/ }
File.makedirs( File.join( site_path, "i" ) )
copy_list.each do |copy_file|
File.copy( copy_file, File.join( site_path, copy_file ) )
end
end
#!/usr/bin/env ruby
require 'fox'
begin
require 'opengl'
rescue LoadError
require 'fox/missingdep'
MSG = <<EOM
Sorry, this example depends on the OpenGL extension. Please
check the Ruby Application Archives for an appropriate
download site.
EOM
missingDependency(MSG)
end
include Fox
include Math
Deg2Rad = Math::PI / 180
D_MAX = 6
SQUARE_SIZE = 2.0 / D_MAX
SQUARE_DISTANCE = 4.0 / D_MAX
AMPLITUDE = SQUARE_SIZE
LAMBDA = D_MAX.to_f / 2
class GLTestWindow < FXMainWindow
# How often our timer will fire (in milliseconds)
TIMER_INTERVAL = 500
# Rotate the boxes when a timer message is received
def onTimeout(sender, sel, ptr)
@angle += 10.0
# @size = 0.5 + 0.2 * Math.cos(Deg2Rad * @angle)
drawScene()
@timer = getApp().addTimeout(TIMER_INTERVAL, method(:onTimeout))
end
# Rotate the boxes when a chore message is received
def onChore(sender, sel, ptr)
@angle += 10.0
# @angle %= 360.0
# @size = 0.5 + 0.2 * Math.cos(Deg2Rad * @angle)
drawScene()
@chore = getApp().addChore(method(:onChore))
end
# Draw the GL scene
def drawScene
lightPosition = [15.0, 10.0, 5.0, 1.0]
lightAmbient = [ 0.1, 0.1, 0.1, 1.0]
lightDiffuse = [ 0.9, 0.9, 0.9, 1.0]
redMaterial = [ 0.0, 0.0, 1.0, 1.0]
blueMaterial = [ 0.0, 1.0, 0.0, 1.0]
width = @glcanvas.width.to_f
height = @glcanvas.height.to_f
aspect = width/height
# Make context current
@glcanvas.makeCurrent()
GL.Viewport(0, 0, @glcanvas.width, @glcanvas.height)
GL.ClearColor(1.0/256, 0.0, 5.0/256, 1.0)
GL.Clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT)
GL.Enable(GL::DEPTH_TEST)
GL.Disable(GL::DITHER)
GL.MatrixMode(GL::PROJECTION)
GL.LoadIdentity()
GLU.Perspective(30.0, aspect, 1.0, 100.0)
GL.MatrixMode(GL::MODELVIEW)
GL.LoadIdentity()
GLU.LookAt(5.0, 10.0, 15.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
GL.ShadeModel(GL::SMOOTH)
GL.Light(GL::LIGHT0, GL::POSITION, lightPosition)
GL.Light(GL::LIGHT0, GL::AMBIENT, lightAmbient)
GL.Light(GL::LIGHT0, GL::DIFFUSE, lightDiffuse)
GL.Enable(GL::LIGHT0)
GL.Enable(GL::LIGHTING)
GL.Rotated(0.1*@angle, 0.0, 1.0, 0.0)
for x in -D_MAX..D_MAX
for y in -D_MAX..D_MAX
h1 = (x + y - 2).abs
h2 = (y - x + 1).abs
GL.PushMatrix
c = [1, 0, 0, 1]
GL.Material(GL::FRONT, GL::AMBIENT, c)
GL.Material(GL::FRONT, GL::DIFFUSE, c)
GL.Translated(
y * SQUARE_DISTANCE,
AMPLITUDE * h1,
x * SQUARE_DISTANCE
)
GL.Begin(GL::TRIANGLE_STRIP)
GL.Normal(1.0, 0.0, 0.0)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.End
GL.PopMatrix
GL.PushMatrix
c = [0, 0, 1, 1]
GL.Material(GL::FRONT, GL::AMBIENT, c)
GL.Material(GL::FRONT, GL::DIFFUSE, c)
GL.Translated(
y * SQUARE_DISTANCE,
AMPLITUDE * h2,
x * SQUARE_DISTANCE
)
GL.Begin(GL::TRIANGLE_STRIP)
GL.Normal(1.0, 0.0, 0.0)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.End
GL.PopMatrix
GL.PushMatrix
c = [0.0 + (x/10.0), 0.0 + (y/10.0), 0, 1]
GL.Material(GL::FRONT, GL::AMBIENT, c)
GL.Material(GL::FRONT, GL::DIFFUSE, c)
GL.Translated(
y * SQUARE_DISTANCE,
0,
x * SQUARE_DISTANCE
)
GL.Begin(GL::TRIANGLE_STRIP)
GL.Normal(1.0, 0.0, 0.0)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
GL.End
GL.PopMatrix
end
end
# Swap if it is double-buffered
if @glvisual.isDoubleBuffer
@glcanvas.swapBuffers
end
# Make context non-current
@glcanvas.makeNonCurrent
end
def initialize(app)
# Invoke the base class initializer
super(app, "OpenGL Test Application", nil, nil, DECOR_ALL, 0, 0, 1024, 768)
# Construct the main window elements
frame = FXHorizontalFrame.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y)
frame.padLeft, frame.padRight = 0, 0
frame.padTop, frame.padBottom = 0, 0
# Left pane to contain the glcanvas
glcanvasFrame = FXVerticalFrame.new(frame,
LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
glcanvasFrame.padLeft, glcanvasFrame.padRight = 10, 10
glcanvasFrame.padTop, glcanvasFrame.padBottom = 10, 10
# Label above the glcanvas
FXLabel.new(glcanvasFrame, "OpenGL Canvas Frame", nil,
JUSTIFY_CENTER_X|LAYOUT_FILL_X)
# Horizontal divider line
FXHorizontalSeparator.new(glcanvasFrame, SEPARATOR_GROOVE|LAYOUT_FILL_X)
# Drawing glcanvas
glpanel = FXVerticalFrame.new(glcanvasFrame, (FRAME_SUNKEN|FRAME_THICK|
LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT))
glpanel.padLeft, glpanel.padRight = 0, 0
glpanel.padTop, glpanel.padBottom = 0, 0
# A visual to draw OpenGL
@glvisual = FXGLVisual.new(getApp(), VISUAL_DOUBLEBUFFER)
# Drawing glcanvas
@glcanvas = FXGLCanvas.new(glpanel, @glvisual, nil, 0,
LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
@glcanvas.connect(SEL_PAINT) {
drawScene
}
@glcanvas.connect(SEL_CONFIGURE) {
if @glcanvas.makeCurrent
GL.Viewport(0, 0, @glcanvas.width, @glcanvas.height)
@glcanvas.makeNonCurrent
end
}
# Right pane for the buttons
buttonFrame = FXVerticalFrame.new(frame, LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
buttonFrame.padLeft, buttonFrame.padRight = 10, 10
buttonFrame.padTop, buttonFrame.padBottom = 10, 10
# Label above the buttons
FXLabel.new(buttonFrame, "Button Frame", nil,
JUSTIFY_CENTER_X|LAYOUT_FILL_X)
# Horizontal divider line
FXHorizontalSeparator.new(buttonFrame, SEPARATOR_RIDGE|LAYOUT_FILL_X)
# Spin according to timer
spinTimerBtn = FXButton.new(buttonFrame,
"Spin &Timer\tSpin using interval timers\nNote the app
blocks until the interal has elapsed...", nil,
nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
spinTimerBtn.padLeft, spinTimerBtn.padRight = 10, 10
spinTimerBtn.padTop, spinTimerBtn.padBottom = 5, 5
spinTimerBtn.connect(SEL_COMMAND) {
@spinning = true
@timer = getApp().addTimeout(TIMER_INTERVAL, method(:onTimeout))
}
spinTimerBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
@spinning ? sender.disable : sender.enable
}
# Spin according to chore
spinChoreBtn = FXButton.new(buttonFrame,
"Spin &Chore\tSpin as fast as possible using chores\nNote even though the
app is very responsive, it never blocks;\nthere is always something to
do...", nil,
nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
spinChoreBtn.padLeft, spinChoreBtn.padRight = 10, 10
spinChoreBtn.padTop, spinChoreBtn.padBottom = 5, 5
spinChoreBtn.connect(SEL_COMMAND) {
@spinning = true
@chore = getApp().addChore(method(:onChore))
}
spinChoreBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
@spinning ? sender.disable : sender.enable
}
# Stop spinning
stopBtn = FXButton.new(buttonFrame,
"&Stop Spin\tStop this mad spinning, I'm getting dizzy", nil,
nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
stopBtn.padLeft, stopBtn.padRight = 10, 10
stopBtn.padTop, stopBtn.padBottom = 5, 5
stopBtn.connect(SEL_COMMAND) {
@spinning = false
if @timer
getApp().removeTimeout(@timer)
@timer = nil
end
if @chore
getApp().removeChore(@chore)
@chore = nil
end
}
stopBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
@spinning ? sender.enable : sender.disable
}
# Exit button
exitBtn = FXButton.new(buttonFrame, "&Exit\tExit the application", nil,
getApp(), FXApp::ID_QUIT,
FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
exitBtn.padLeft, exitBtn.padRight = 10, 10
exitBtn.padTop, exitBtn.padBottom = 5, 5
# Make a tooltip
FXTooltip.new(getApp())
# Initialize private variables
@spinning = false
@chore = nil
@timer = nil
@angle = 0.0
@size = 0.5
end
# Create and initialize
def create
super
show(PLACEMENT_SCREEN)
end
end
if __FILE__ == $0
# Construct the application
application = FXApp.new("GLTest", "FoxTest")
# To ensure that the chores-based spin will run as fast as possible,
# we can disable the chore in FXRuby's event loop that tries to schedule
# other threads. This is OK for this program because there aren't any
# other Ruby threads running.
#application.disableThreads
# Construct the main window
GLTestWindow.new(application)
# Create the app's windows
application.create
# Run the application
application.run
end
class Facelet
attr_accessor :color
def initialize(color)
@color = color
end
def to_s
@color
end
end
class Edge
attr_accessor :facelets, :colors
def initialize(facelets)
@facelets = facelets
@colors = @facelets.map { |fl| fl.color }
end
def apply(edge)
@facelets.each_with_index { |fl, i|
fl.color = edge.colors[i]
}
end
def inspect
"\n%s %s\n%s %s %s" % facelets
end
end
class Side
attr_reader :num, :facelets
attr_accessor :sides
def initialize(num)
@num = num
@sides = []
@facelets = []
@fl_by_side = {}
end
# facelets & sides
# 0
# 0 1 2
# 3 3 4 5 1
# 6 7 8
# 2
def facelets=(facelets)
@facelets = facelets.map { |c| Facelet.new(c) }
init_facelet 0, 3,0
init_facelet 1, 0
init_facelet 2, 0,1
init_facelet 3, 3
init_facelet 5, 1
init_facelet 6, 2,3
init_facelet 7, 2
init_facelet 8, 1,2
end
def <=>(side)
self.num <=> side.num
end
def init_facelet(pos, *side_nums)
sides = side_nums.map { |num| @sides[num] }.sort
@fl_by_side[sides] = pos
end
def []=(color, *sides)
@facelets[@fl_by_side[sides.sort]].color = color
end
def values_at(*sides)
sides.map { |sides| @facelets[@fl_by_side[sides.sort]] }
end
def inspect(range=nil)
if range
@facelets.values_at(*(range.to_a)).join(' ')
else
<<-EOS.gsub(/\d/) { |num| @facelets[num.to_i] }.gsub(/[ABCD]/) { |side| @sides[side[0]-?A].num.to_s }
A
0 1 2
D 3 4 5 B
6 7 8
C
EOS
end
end
def get_edge(side)
trio = (-1..1).map { |x| (side + x) % 4 }
prev_side, this_side, next_side = @sides.values_at(*trio)
e = Edge.new(
self .values_at( [this_side], [this_side, next_side] ) +
this_side.values_at( [self, prev_side], [self ], [self, next_side] )
)
#puts 'Edge created for side %d: ' % side + e.inspect
e
end
def turn(dir)
#p 'turn side %d in %d' % [num, dir]
edges = (0..3).map { |n| get_edge n }
for i in 0..3
edges[i].apply edges[(i-dir) % 4]
end
end
end
class Cube
def initialize
@sides = []
%w(left front right back top bottom).each_with_index { |side, i|
eval("@sides[#{i}] = @#{side} = Side.new(#{i})")
}
@left.sides = [@top, @front, @bottom, @back]
@front.sides = [@top, @right, @bottom, @left]
@right.sides = [@top, @back, @bottom, @front]
@back.sides = [@top, @left, @bottom, @right]
@top.sides = [@back, @right, @front, @left]
@bottom.sides = [@front, @right, @back, @left]
end
def read_facelets(fs)
pattern = Regexp.new(<<-EOP.gsub(/\w/, '\w').gsub(/\s+/, '\s*'))
(w w w)
(w w w)
(w w w)
(r r r) (g g g) (b b b) (o o o)
(r r r) (g g g) (b b b) (o o o)
(r r r) (g g g) (b b b) (o o o)
(y y y)
(y y y)
(y y y)
EOP
md = pattern.match(fs).to_a
@top.facelets = parse_facelets(md.values_at(1,2,3))
@left.facelets = parse_facelets(md.values_at(4,8,12))
@front.facelets = parse_facelets(md.values_at(5,9,13))
@right.facelets = parse_facelets(md.values_at(6,10,14))
@back.facelets = parse_facelets(md.values_at(7,11,15))
@bottom.facelets = parse_facelets(md.values_at(16,17,18))
end
def turn(side, dir)
#p 'turn %d in %d' % [side, dir]
@sides[side].turn(dir)
#puts inspect
end
def inspect
<<-EOF.gsub(/(\d):(\d)-(\d)/) { @sides[$1.to_i].inspect(Range.new($2.to_i, $3.to_i)) }
4:0-2
4:3-5
4:6-8
0:0-2 1:0-2 2:0-2 3:0-2
0:3-5 1:3-5 2:3-5 3:3-5
0:6-8 1:6-8 2:6-8 3:6-8
5:0-2
5:3-5
5:6-8
EOF
end
private
def parse_facelets(rows)
rows.join.delete(' ').split(//)
end
end
#$stdin = DATA
gets.to_i.times do |i|
puts "Scenario ##{i+1}:"
fs = ''
9.times { fs << gets }
cube = Cube.new
cube.read_facelets fs
gets.to_i.times do |t|
side, dir = gets.split.map {|s| s.to_i}
cube.turn(side, dir)
end
puts cube.inspect
puts
end
# 2004 by murphy <korny@cYcnus.de>
# GPL
class Scenario
class TimePoint
attr_reader :data
def initialize *data
@data = data
end
def [] i
@data[i] or 0
end
include Comparable
def <=> tp
r = 0
[@data.size, tp.data.size].max.times do |i|
r = self[i] <=> tp[i]
return r if r.nonzero?
end
0
end
def - tp
r = []
[@data.size, tp.data.size].max.times do |i|
r << self[i] - tp[i]
end
r
end
def inspect
# 01/01/1800 00:00:00
'%02d/%02d/%04d %02d:%02d:%02d' % @data.values_at(1, 2, 0, 3, 4, 5)
end
end
ONE_HOUR = TimePoint.new 0, 0, 0, 1, 0, 0
APPOINTMENT_PATTERN = /
( \d{4} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s
( \d{4} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} )
/x
def initialize io
@team_size = io.gets.to_i
@data = [ [TimePoint.new(1800, 01, 01, 00, 00, 00), @team_size] ]
@team_size.times do # each team member
io.gets.to_i.times do # each appointment
m = APPOINTMENT_PATTERN.match io.gets
@data << [TimePoint.new(*m.captures[0,6].map { |x| x.to_i }), -1]
@data << [TimePoint.new(*m.captures[6,6].map { |x| x.to_i }), +1]
end
end
@data << [TimePoint.new(2200, 01, 01, 00, 00, 00), -@team_size]
end
def print_time_plan
n = 0
appointment = nil
no_appointment = true
@data.sort_by { |x| x[0] }.each do |x|
tp, action = *x
n += action
# at any time during the meeting, at least two team members need to be there
# and at most one team member is allowed to be absent
if n >= 2 and (@team_size - n) <= 1
appointment ||= tp
else
if appointment
# the meeting should be at least one hour in length
if TimePoint.new(*(tp - appointment)) >= ONE_HOUR
puts 'appointment possible from %p to %p' % [appointment, tp]
no_appointment = false
end
appointment = false
end
end
end
puts 'no appointment possible' if no_appointment
end
end
# read the data
DATA.gets.to_i.times do |si| # each scenario
puts 'Scenario #%d:' % (si + 1)
sc = Scenario.new DATA
sc.print_time_plan
puts
end
#__END__
2
3
3
2002 06 28 15 00 00 2002 06 28 18 00 00 TUD Contest Practice Session
2002 06 29 10 00 00 2002 06 29 15 00 00 TUD Contest
2002 11 15 15 00 00 2002 11 17 23 00 00 NWERC Delft
4
2002 06 25 13 30 00 2002 06 25 15 30 00 FIFA World Cup Semifinal I
2002 06 26 13 30 00 2002 06 26 15 30 00 FIFA World Cup Semifinal II
2002 06 29 13 00 00 2002 06 29 15 00 00 FIFA World Cup Third Place
2002 06 30 13 00 00 2002 06 30 15 00 00 FIFA World Cup Final
1
2002 06 01 00 00 00 2002 06 29 18 00 00 Preparation of Problem Set
2
1
1800 01 01 00 00 00 2200 01 01 00 00 00 Solving Problem 8
0
require 'token_consts'
require 'symbol'
require 'ctype'
require 'error'
class Fixnum
# Treat char as a digit and return it's value as Fixnum.
# Returns nonsense for non-digits.
# Examples:
# <code>
# RUBY_VERSION[0].digit == '1.8.2'[0].digit == 1
# </code>
#
# <code>
# ?6.digit == 6
# </code>
#
# <code>
# ?A.digit == 17
# </code>
def digit
self - ?0
end
end
##
# Stellt einen einfachen Scanner für die lexikalische Analyse der Sprache Pas-0 dar.
#
# @author Andreas Kunert
# Ruby port by murphy
class Scanner
include TokenConsts
attr_reader :line, :pos
# To allow Scanner.new without parameters.
DUMMY_INPUT = 'dummy file'
def DUMMY_INPUT.getc
nil
end
##
# Erzeugt einen Scanner, der als Eingabe das übergebene IO benutzt.
def initialize input = DUMMY_INPUT
@line = 1
@pos = 0
begin
@input = input
@next_char = @input.getc
rescue IOError # TODO show the reason!
Error.ioError
raise
end
end
##
# Liest das n
|