summaryrefslogtreecommitdiff
path: root/test/scanners/python/pleac.in.py
blob: 6b9a79b35e17ce01db347789edecb79f6b1b3d1f (plain)
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
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
# -*- python -*-
# vim:set ft=python:

# @@PLEAC@@_NAME
# @@SKIP@@ Python

# @@PLEAC@@_WEB
# @@SKIP@@ http://www.python.org

# @@PLEAC@@_INTRO
# @@SKIP@@ The latest version of Python is 2.4 but users of 2.3 and 2.2 (and
# @@SKIP@@ in some cases earlier versions) can use the code herein.
# @@SKIP@@ Users of 2.2 and 2.3 should install or copy code from utils.py 
# @@SKIP@@ (http://aima.cs.berkeley.edu/python/utils.py)
# @@SKIP@@ [the first section provides compatability code with 2.4]
# @@SKIP@@ Users of 2.2 should install optik (http://optik.sourceforge.com) 
# @@SKIP@@ [for optparse and textwrap]
# @@SKIP@@ Where a 2.3 or 2.4 feature is unable to be replicated, an effort
# @@SKIP@@ has been made to provide a backward-compatible version in addition
# @@SKIP@@ to one using modern idioms.
# @@SKIP@@ Examples which translate the original Perl closely but which are
# @@SKIP@@ unPythonic are prefixed with a comment stating "DON'T DO THIS".
# @@SKIP@@ In some cases, it may be useful to know the techniques in these, 
# @@SKIP@@ though it's a bad solution for the specific problem.

# @@PLEAC@@_1.0
#-----------------------------
mystr = "\n"   # a newline character
mystr = r"\n"  # two characters, \ and n
#-----------------------------
mystr = "Jon 'Maddog' Orwant"  # literal single quote inside double quotes
mystr = 'Jon "Maddog" Orwant'  # literal double quote inside single quotes
#-----------------------------
mystr = 'Jon \'Maddog\' Orwant'  # escaped single quote
mystr = "Jon \"Maddog\" Orwant"  # escaped double quote
#-----------------------------
mystr = """
This is a multiline string literal
enclosed in triple double quotes.
"""
mystr = '''
And this is a multiline string literal
enclosed in triple single quotes.
'''
#-----------------------------

# @@PLEAC@@_1.1
#-----------------------------

# get a 5-char string, skip 3, then grab 2 8-char strings, then the rest
# Note that struct.unpack cannot use * for an unknown length.
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65224
import struct
(lead, s1, s2), tail = struct.unpack("5s 3x 8s 8s", data[:24]), data[24:]

# split at five-char boundaries
fivers = struct.unpack("5s" * (len(data)//5), data)
fivers = print [x[i*5:i*5+5] for i in range(len(x)/5)]

# chop string into individual characters
chars = list(data)
#-----------------------------
mystr = "This is what you have"
#       +012345678901234567890  Indexing forwards  (left to right)
#        109876543210987654321- Indexing backwards (right to left)
#         note that 0 means 10 or 20, etc. above

first = mystr[0]                            # "T"
start = mystr[5:7]                          # "is"
rest = mystr[13:]                           # "you have"
last = mystr[-1]                            # "e"
end = mystr[-4:]                            # "have"
piece = mystr[-8:-5]                        # "you"
#-----------------------------
# Python strings are immutable.
# In general, you should just do piecemeal reallocation:
mystr = "This is what you have"
mystr = mystr[:5] + "wasn't" + mystr[7:]

# Or replace and reallocate
mystr = "This is what you have"
mystr = mystr.replace(" is ", " wasn't ")

# DON'T DO THIS: In-place modification could be done using character arrays
import array
mystr = array.array("c", "This is what you have")
mystr[5:7] = array.array("c", "wasn't")
# mystr is now array('c', "This wasn't what you have")

# DON'T DO THIS: It could also be done using MutableString 
from UserString import MutableString
mystr = MutableString("This is what you have")
mystr[-12:] = "ondrous"
# mystr is now "This is wondrous"
#-----------------------------
# you can test simple substrings with "in" (for regex matching see ch.6):
if txt in mystr[-10:]:
    print "'%s' found in last 10 characters"%txt

# Or use the startswith() and endswith() string methods:
if mystr.startswith(txt):
    print "%s starts with %s."%(mystr, txt)
if mystr.endswith(txt):
    print "%s ends with %s."%(mystr, txt)

#-----------------------------

# @@PLEAC@@_1.2
#-----------------------------
# Introductory Note: quite a bit of this section is not terribly Pythonic
# as names must be set before being used. For instance, unless myvar has 
# been previously defined, these next lines will all raise NameError:
myvar = myvar or some_default
myvar2 = myvar or some_default
myvar |= some_default          # bitwise-or, not logical-or - for demo

# The standard way of setting a default is often:
myvar = default_value
if some_condition:
    pass                     # code which may set myvar to something else

# if myvar is returned from a function and may be empty/None, then use:
myvar = somefunc()
if not myvar:
    myvar = default_value

# If you want a default value that can be overridden by the person calling 
# your code, you can often wrap it in a function with a named parameter:
def myfunc(myvar="a"):
   return myvar + "b"
print myfunc(), myfunc("c")
#=> ab cb

# Note, though, that this won't work for mutable objects such as lists or
# dicts that are mutated in the function as the object is only created once 
# and repeated calls to the same function will return the same object.  This
# can be desired behaviour however - see section 10.3, for instance.
def myfunc(myvar=[]):
    myvar.append("x")
    return myvar
print myfunc(), myfunc()
#=> ['x'] ['x', 'x']

# You need to do:
def myfunc(myvar=None):
    if myvar is None:
        myvar = []
    myvar.append("x")
    return myvar
print myfunc(), myfunc()
#=> ['x'] ['x']

#=== Perl Equivalencies start here
# use b if b is true, otherwise use c
a = b or c

# as that is a little tricksy, the following may be preferred:
if b:
    a = b
else:
    a = c

# set x to y unless x is already true
if not x:
    x = y
#-----------------------------
# use b if b is defined, else c
try:
    a = b
except NameError:
    a = c
#-----------------------------
foo = bar or "DEFAULT VALUE"
#-----------------------------
# To get a user (for both UNIX and Windows), use:
import getpass
user = getpass.getuser()

# DON'T DO THIS: find the user name on Unix systems 
import os
user = os.environ.get("USER")
if user is None:
    user = os.environ.get("LOGNAME")
#-----------------------------
if not starting_point:
    starting_point = "Greenwich"
#-----------------------------
if not a:         # copy only if empty
    a = b

if b:             # assign b if nonempty, else c
    a = b
else:
    a = c
#-----------------------------

# @@PLEAC@@_1.3
#-----------------------------
v1, v2 = v2, v1
#-----------------------------
# DON'T DO THIS:
temp = a
a = b
b = temp
#-----------------------------
a = "alpha"
b = "omega"
a, b = b, a   # the first shall be last -- and versa vice 
#-----------------------------
alpha, beta, production = "January March August".split()
alpha, beta, production = beta, production, alpha
#-----------------------------

# @@PLEAC@@_1.4
#-----------------------------
num = ord(char)
char = chr(num)
#-----------------------------
char = "%c" % num
print "Number %d is character %c" % (num, num)
print "Number %(n)d is character %(n)c" % {"n": num}
print "Number %(num)d is character %(num)c" % locals()
#=> Number 101 is character e
#-----------------------------
ascii_character_numbers = [ord(c) for c in "sample"]
print ascii_character_numbers
#=> [115, 97, 109, 112, 108, 101]

word = "".join([chr(n) for n in ascii_character_numbers])
word = "".join([chr(n) for n in [115, 97, 109, 112, 108, 101]])
print word
#=> sample
#-----------------------------
hal = "HAL"
ibm = "".join([chr(ord(c)+1) for c in hal]) # add one to each ASCII value
print ibm   
#=> IBM
#-----------------------------

# @@PLEAC@@_1.5
#-----------------------------
mylist = list(mystr)
#-----------------------------
for char in mystr:
    pass # do something with char
#-----------------------------
mystr = "an apple a day"
uniq = sorted(set(mystr))
print "unique chars are: '%s'" % "".join(uniq)
#=> unique chars are: ' adelnpy'
#-----------------------------
ascvals = [ord(c) for c in mystr]
print "total is %s for '%s'."%(sum(ascvals), mystr)
#=> total is 1248 for 'an apple a day'.
#-----------------------------
# sysv checksum
def checksum(myfile):
    values = [ord(c) for line in myfile for c in line]
    return sum(values)%(2**16) - 1

import fileinput
print checksum(fileinput.input())   # data from sys.stdin

# Using a function means any iterable can be checksummed:
print checksum(open("C:/test.txt")  # data from file
print checksum("sometext")          # data from string
#-----------------------------
#!/usr/bin/python
# slowcat - emulate a   s l o w  line printer
# usage: slowcat [- DELAY] [files ...]
import sys, select
import re
DELAY = 1
if re.match("^-\d+$",sys.argv[1]):
    DELAY=-int(sys.argv[1])
    del sys.argv[1]
for ln in fileinput.input():
    for c in ln:
        sys.stdout.write(c)
        sys.stdout.flush()
        select.select([],[],[], 0.005 * DELAY)
#-----------------------------

# @@PLEAC@@_1.6
#-----------------------------
# 2.3+ only
revchars = mystr[::-1]  # extended slice - step is -1
revwords = " ".join(mystr.split(" ")[::-1])

# pre 2.3 version:
mylist = list(mystr)
mylist.reverse()
revbytes = "".join(mylist)

mylist = mystr.split()
mylist.reverse()
revwords = ' '.join(mylist)

# Alternative version using reversed():
revchars = "".join(reversed(mystr))
revwords = " ".join(reversed(mystr.split(" ")))

# reversed() makes an iterator, which means that the reversal
# happens as it is consumed.  This means that "print reversed(mystr)" is not
# the same as mystr[::-1].  Standard usage is:
for char in reversed(mystr):
   pass  # ... do something
#-----------------------------
# 2.3+ only
word = "reviver"
is_palindrome = (word == word[::-1])
#-----------------------------
# Generator version
def get_palindromes(fname):
    for line in open(fname):
        word = line.rstrip()
        if len(word) > 5 and word == word[::-1]:
            yield word
long_palindromes = list(get_palindromes("/usr/share/dict/words"))

# Simpler old-style version using 2.2 string reversal
def rev_string(mystr):
    mylist = list(mystr)
    mylist.reverse()
    return "".join(mylist)

long_palindromes=[]
for line in open("/usr/share/dict/words"):
    word = line.rstrip()
    if len(word) > 5 and word == rev_string(word):
        long_palindromes.append(word)
print long_palindromes
#-----------------------------

# @@PLEAC@@_1.7
#-----------------------------
mystr.expandtabs()
mystr.expandtabs(4)
#-----------------------------

# @@PLEAC@@_1.8
#-----------------------------
text = "I am %(rows)s high and %(cols)s long"%{"rows":24, "cols":80)
print text
#=> I am 24 high and 80 long

rows, cols = 24, 80
text = "I am %(rows)s high and %(cols)s long"%locals()
print text
#=> I am 24 high and 80 long
#-----------------------------
import re
print re.sub("\d+", lambda i: str(2 * int(i.group(0))), "I am 17 years old")
#=> I am 34 years old
#-----------------------------
# expand variables in text, but put an error message in
# if the variable isn't defined
class SafeDict(dict):
    def __getitem__(self, key):
        return self.get(key, "[No Variable: %s]"%key)
    
hi = "Hello"
text = "%(hi)s and %(bye)s!"%SafeDict(locals())
print text
#=> Hello and [No Variable: bye]!

#If you don't need a particular error message, just use the Template class:
from string import Template
x = Template("$hi and $bye!")
hi = "Hello"
print x.safe_substitute(locals())
#=> Hello and $bye!
print x.substitute(locals()) # will throw a KeyError

#-----------------------------

# @@PLEAC@@_1.9
#-----------------------------
mystr = "bo peep".upper()  # BO PEEP
mystr = mystr.lower()      # bo peep
mystr = mystr.capitalize() # Bo peep
#-----------------------------
beast = "python"
caprest = beast.capitalize().swapcase() # pYTHON
#-----------------------------
print "thIS is a loNG liNE".title()
#=> This Is A Long Line
#-----------------------------
if a.upper() == b.upper():
    print "a and b are the same"
#-----------------------------
import random
def randcase_one(letter):
    if random.randint(0,5):   # True on 1, 2, 3, 4
        return letter.lower()
    else:
        return letter.upper()

def randcase(myfile):
    for line in myfile:
        yield "".join(randcase_one(letter) for letter in line[:-1])

for line in randcase(myfile):
    print line
#-----------------------------

# @@PLEAC@@_1.10
#-----------------------------
"I have %d guanacos." % (n + 1)
print "I have", n+1, "guanacos."
#-----------------------------
#Python templates disallow in-string calculations (see PEP 292)
from string import Template

email_template = Template("""\
To: $address
From: Your Bank
CC: $cc_number
Date: $date

Dear $name,

Today you bounced check number $checknum to us.
Your account is now closed.

Sincerely,
the management
""")

import random
import datetime

person = {"address":"Joe@somewhere.com",
          "name": "Joe",
          "cc_number" : 1234567890,
          "checknum" : 500+random.randint(0,99)}

print email_template.substitute(person, date=datetime.date.today())
#-----------------------------

# @@PLEAC@@_1.11
#-----------------------------
# indenting here documents
#
# in python multiline strings can be used as here documents
var = """
      your text
      goes here
      """

# using regular expressions
import re
re_leading_blanks = re.compile("^\s+",re.MULTILINE)
var1 = re_leading_blanks.sub("",var)[:-1]

# using string methods 
# split into lines, use every line except first and last, left strip and rejoin.
var2 = "\n".join([line.lstrip() for line in var.split("\n")[1:-1]])

poem = """
       Here's your poem:
       Now far ahead the Road has gone,
          And I must follow, if I can,
       Pursuing it with eager feet,
          Until it joins some larger way
       Where many paths and errand meet.
          And whither then? I cannot say.
               --Bilbo in /usr/src/perl/pp_ctl.c  
       """

import textwrap
print textwrap.dedent(poem)[1:-1]
#-----------------------------
    

# @@PLEAC@@_1.12
#-----------------------------
from textwrap import wrap 
output = wrap(para,
              initial_indent=leadtab
              subsequent_indent=nexttab)
#-----------------------------
#!/usr/bin/env python
# wrapdemo - show how textwrap works

txt = """\
Folding and splicing is the work of an editor,
not a mere collection of silicon
and
mobile electrons!
"""

from textwrap import TextWrapper

wrapper = TextWrapper(width=20,
                      initial_indent=" "*4,
                      subsequent_indent=" "*2)

print "0123456789" * 2
print wrapper.fill(txt)

#-----------------------------
"""Expected result:

01234567890123456789
    Folding and
  splicing is the
  work of an editor,
  not a mere
  collection of
  silicon and mobile
  electrons!
"""

#-----------------------------
# merge multiple lines into one, then wrap one long line

from textwrap import fill
import fileinput

print fill("".join(fileinput.input()))

#-----------------------------
# Term::ReadKey::GetTerminalSize() isn't in the Perl standard library. 
# It isn't in the Python standard library either. Michael Hudson's 
# recipe from python-list #530228 is shown here.
# (http://aspn.activestate.com/ASPN/Mail/Message/python-list/530228)
# Be aware that this will work on Unix but not on Windows.

from termwrap import wrap
import struct, fcntl
def getheightwidth():
    height, width = struct.unpack(
        "hhhh", fcntl.ioctl(0, TERMIOS.TIOCGWINSZ ,"\000"*8))[0:2]
    return height, width

# PERL <>, $/, $\ emulation
import fileinput
import re

_, width = getheightwidth()
for para in re.split(r"\n{2,}", "".join(fileinput.input())):
    print fill(para, width)


# @@PLEAC@@_1.13
#-----------------------------
mystr = '''Mom said, "Don't do that."'''  #"
re.sub("['\"]", lambda i: "\\" + i.group(0), mystr)
re.sub("[A-Z]", lambda i: "\\" + i.group(0), mystr)
re.sub("\W", lambda i: "\\" + i.group(0), "is a test!") # no function like quotemeta?


# @@PLEAC@@_1.14
#-----------------------------
mystr = mystr.lstrip() # left
mystr = mystr.rstrip() # right
mystr = mystr.strip()  # both ends


# @@PLEAC@@_1.15
#-----------------------------
import csv
def parse_csv(line):
    reader = csv.reader([line], escapechar='\\')
    return reader.next()

line = '''XYZZY,"","O'Reilly, Inc","Wall, Larry","a \\"glug\\" bit,",5,"Error, Core Dumped,",''' #"

fields = parse_csv(line)

for i, field in enumerate(fields):
    print "%d : %s" % (i, field)

# pre-2.3 version of parse_csv
import re
def parse_csv(text):
    pattern = re.compile('''"([^"\\\]*(?:\\\.[^"\\\]*)*)",?|([^,]+),?|,''')
    mylist = ["".join(elem) 
              for elem in re.findall(pattern, text)]
    if text[-1] == ",": 
        mylist += ['']
    return mylist

# cvs.reader is meant to work for many lines, something like:
# (NB: in Python default, quotechar is *not* escaped by backslash,
#      but doubled instead. That's what Excel does.)
for fields in cvs.reader(lines, dialect="some"):
    for num, field in enumerate(fields):
        print num, ":", field
#-----------------------------

# @@PLEAC@@_1.16
#-----------------------------
def soundex(name, len=4):
    """ soundex module conforming to Knuth's algorithm
        implementation 2000-12-24 by Gregory Jorgensen
        public domain
    """

    # digits holds the soundex values for the alphabet
    digits = '01230120022455012623010202'
    sndx = ''
    fc = ''

    # translate alpha chars in name to soundex digits
    for c in name.upper():
        if c.isalpha():
            if not fc: 
                fc = c   # remember first letter
            d = digits[ord(c)-ord('A')]
            # duplicate consecutive soundex digits are skipped
            if not sndx or (d != sndx[-1]):
                sndx += d

    # replace first digit with first alpha character
    sndx = fc + sndx[1:]

    # remove all 0s from the soundex code
    sndx = sndx.replace('0','')

    # return soundex code padded to len characters
    return (sndx + (len * '0'))[:len]

user = raw_input("Lookup user: ")
if user == "":
    raise SystemExit

name_code = soundex(user)
for line in open("/etc/passwd"):
    line = line.split(":")
    for piece in line[4].split():
        if name_code == soundex(piece):
            print "%s: %s\n" % line[0], line[4])
#-----------------------------

# @@PLEAC@@_1.17
#-----------------------------
import sys, fileinput, re

data = """\
analysed        => analyzed
built-in        => builtin
chastized       => chastised
commandline     => command-line
de-allocate     => deallocate
dropin          => drop-in
hardcode        => hard-code
meta-data       => metadata
multicharacter  => multi-character
multiway        => multi-way
non-empty       => nonempty
non-profit      => nonprofit
non-trappable   => nontrappable
pre-define      => predefine
preextend       => pre-extend
re-compiling    => recompiling
reenter         => re-enter
turnkey         => turn-key
"""
mydict = {}
for line in data.split("\n"):
    if not line.strip():
        continue
    k, v = [word.strip() for word in line.split("=>")]
    mydict[k] = v
pattern_text = "(" + "|".join([re.escape(word) for word in mydict.keys()]) + ")"
pattern = re.compile(pattern_text)

args = sys.argv[1:]
verbose = 0
if args and args[0] == "-v":
    verbose = 1
    args = args[1:]

if not args:
    sys.stderr.write("%s: Reading from stdin\n" % sys.argv[0])

for line in fileinput.input(args, inplace=1, backup=".orig"):
    output = ""
    pos = 0
    while True:
        match = pattern.search(line, pos)
        if not match:
            output += line[pos:]
            break
        output += line[pos:match.start(0)] + mydict[match.group(1)]
        pos = match.end(0)
    sys.stdout.write(output)
#-----------------------------

# @@PLEAC@@_1.18
#-----------------------------
#!/usr/bin/python
# psgrep - print selected lines of ps output by
#          compiling user queries into code.
#
# examples :
# psgrep "uid<10"
import sys, os, re

class PsLineMatch:
    # each field from the PS header
    fieldnames = ("flags","uid","pid","ppid","pri","nice","size", \
                  "rss","wchan","stat","tty","time","command")
    numeric_fields = ("flags","uid","pid","ppid","pri","nice","size","rss")
    def __init__(self):
        self._fields = {}

    def new_line(self, ln):
        self._ln = ln.rstrip()
        # ps header for option "wwaxl" (different than in the perl code)
        """
          F   UID   PID  PPID PRI  NI   VSZ  RSS WCHAN  STAT TTY        TIME COMMAND"
        004     0     1     0  15   0   448  236 schedu S    ?          0:07 init"
        .   .     .     .     .   .   .     .    .      .    .    .          .
        """
        # because only the last entry might contain blanks, splitting
        # is safe
        data = self._ln.split(None,12)
        for fn, elem in zip(self.fieldnames, data):
            if fn in self.numeric_fields:  # make numbers integer 
                self._fields[fn] = int(elem)
            else:
                self._fields[fn] = elem

    def set_query(self, args):
        # assume args: "uid==500", "command ~ ^wm"
        conds=[]
        m = re.compile("(\w+)([=<>]+)(.+)")
        for a in args:
            try:
                (field,op,val) = m.match(a).groups()
            except:
                print "can't understand query \"%s\"" % (a)
                raise SystemExit
            if field in self.numeric_fields:
                conds.append(a)
            else:
                conds.append("%s%s'%s'",(field,op,val))
        self._desirable = compile("(("+")and(".join(conds)+"))", "<string>","eval")

    def is_desirable(self):
        return eval(self._desirable, {}, self._fields)

    def __str__(self):
        # to allow "print".
        return self._ln

if len(sys.argv)<=1:
    print """usage: %s criterion ...
    Each criterion is a Perl expression involving: 
    %s
    All criteria must be met for a line to be printed.""" \
    % (sys.argv[0], " ".join(PsLineMatch().fieldnames))
    raise SystemExit

psln = PsLineMatch()
psln.set_query(sys.argv[1:])
p = os.popen("ps wwaxl")
print p.readline()[:-1]        # emit header line
for ln in p.readlines():
    psln.new_line(ln)
    if psln.is_desirable():
        print psln
p.close()

# alternatively one could consider every argument being a string and
# support wildcards: "uid==500" "command~^wm" by means of re, but this
# does not show dynamic python code generation, although re.compile
# also precompiles.
#-----------------------------


# @@PLEAC@@_2.1
#-----------------------------
# The standard way of validating numbers is to convert them and catch
# an exception on failure

try:
    myfloat = float(mystr)
    print "is a decimal number" 
except TypeError:
    print "is not a decimal number"

try:
    myint = int(mystr)
    print "is an integer"
except TypeError:
    print "is not an integer"

# DON'T DO THIS. Explicit checking is prone to errors:
if mystr.isdigit():                         # Fails on "+4"
    print 'is a positive integer'   
else:
    print 'is not'

if re.match("[+-]?\d+$", mystr):            # Fails on "- 1" 
    print 'is an integer'           
else:
    print 'is not'

if re.match("-?(?:\d+(?:\.\d*)?|\.\d+)$", mystr):  # Opaque, and fails on "- 1"
    print 'is a decimal number'
else:
    print 'is not'

#-----------------------------

# @@PLEAC@@_2.2
#-----------------------------
# equal(num1, num2, accuracy) : returns true if num1 and num2 are
#   equal to accuracy number of decimal places

def equal(num1, num2, accuracy):
    return abs(num1 - num2) < 10**(-accuracy)
#-----------------------------
from __future__ import division  # use / for float div and // for int div

wage = 536                                      # $5.36/hour
week = 40 * wage                                # $214.40
print "One week's wage is: $%.2f" % (week/100)
#=> One week's wage is: $214.40
#-----------------------------

# @@PLEAC@@_2.3
#-----------------------------
rounded = round(num)            # rounds to integer
#-----------------------------
a = 0.255
b = "%.2f" % a
print "Unrounded: %f\nRounded: %s" % (a, b)
print "Unrounded: %f\nRounded: %.2f" % (a, a)
#=> Unrounded: 0.255000
#=> Rounded: 0.26
#=> Unrounded: 0.255000
#=> Rounded: 0.26
#-----------------------------
from math import floor, ceil

print "number\tint\tfloor\tceil"
a = [3.3, 3.5, 3.7, -3.3]
for n in a:
    print "% .1f\t% .1f\t% .1f\t% .1f" % (n, int(n), floor(n), ceil(n))
#=> number  int   floor ceil
#=>  3.3     3.0   3.0   4.0
#=>  3.5     3.0   3.0   4.0
#=>  3.7     3.0   3.0   4.0
#=> -3.3    -3.0  -4.0  -3.0
#-----------------------------

# @@PLEAC@@_2.4
#-----------------------------
# To convert a string in any base up to base 36, use the optional arg to int():
num = int('0110110', 2)   # num is 54

# To convert an int to an string representation in another base, you could use
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286>:
import baseconvert 
def dec2bin(i):
    return baseconvert.baseconvert(i, baseconvert.BASE10, baseconvert.BASE2)

binstr = dec2bin(54)      # binstr is 110110
#-----------------------------

# @@PLEAC@@_2.5
#-----------------------------
for i in range(x,y):
    pass # i is set to every integer from x to y, excluding y

for i in range(x, y, 7):
    pass # i is set to every integer from x to y, stepsize = 7

print "Infancy is:",
for i in range(0,3):
    print i,
print

print "Toddling is:",
for i in range(3,5):
    print i,
print

# DON'T DO THIS:
print "Childhood is:",
i = 5
while i <= 12:
    print i
    i += 1

#=> Infancy is: 0 1 2
#=> Toddling is: 3 4
#=> Childhood is: 5 6 7 8 9 10 11 12
#-----------------------------

# @@PLEAC@@_2.6
#-----------------------------
# See http://www.faqts.com/knowledge_base/view.phtml/aid/4442
# for a module that does this
#-----------------------------

# @@PLEAC@@_2.7
#-----------------------------
import random          # use help(random) to see the (large) list of funcs

rand = random.randint(x, y)
#-----------------------------
rand = random.randint(25, 76)
print rand
#-----------------------------
elt = random.choice(mylist)
#-----------------------------
import string
chars = string.letters + string.digits + "!@$%^&*"
password = "".join([random.choice(chars) for i in range(8)])
#-----------------------------

# @@PLEAC@@_2.8
#-----------------------------
# Changes the default RNG
random.seed()

# Or you can create independent RNGs
gen1 = random.Random(6)
gen2 = random.Random(6)
gen3 = random.Random(10)
a1, b1 = gen1.random(), gen1.random()
a2, b2 = gen2.random(), gen2.random()
a3, b3 = gen3.random(), gen3.random()
# a1 == a2 and b1 == b2
#-----------------------------

# @@PLEAC@@_2.9
#-----------------------------
# see http://www.sbc.su.se/~per/crng/ or http://www.frohne.westhost.com/rv11reference.htm
#-----------------------------

# @@PLEAC@@_2.10
#-----------------------------
import random
mean = 25
sdev = 2
salary = random.gauss(mean, sdev)
print "You have been hired at %.2f" % salary
#-----------------------------

# @@PLEAC@@_2.11
#-----------------------------
radians = math.radians(degrees)
degrees = math.degrees(radians)

# pre-2.3:
from __future__ import division
import math
def deg2rad(degrees):
    return (degrees / 180) * math.pi
def rad2deg(radians):
    return (radians / math.pi) * 180
#-----------------------------
# Use deg2rad instead of math.radians if you have pre-2.3 Python.
import math
def degree_sine(degrees):
    radians = math.radians(degrees)
    return math.sin(radians)
#-----------------------------

# @@PLEAC@@_2.12
#-----------------------------
import math

# DON'T DO THIS.  Use math.tan() instead.
def tan(theta):
    return math.sin(theta) / math.cos(theta)
#----------------
# NOTE: this sets y to 16331239353195370.0
try:
  y = math.tan(math.pi/2)
except ValueError:
  y = None
#-----------------------------

# @@PLEAC@@_2.13
#-----------------------------
import math
log_e = math.log(VALUE)
#-----------------------------
log_10 = math.log10(VALUE)
#-----------------------------
def log_base(base, value):
    return math.log(value) / math.log(base)
#-----------------------------
# log_base defined as above
answer = log_base(10, 10000)
print "log10(10,000) =", answer
#=> log10(10,000) = 4.0
#-----------------------------

# @@PLEAC@@_2.14
#-----------------------------
# NOTE: must have NumPy installed.  See
#   http://www.pfdubois.com/numpy/

import Numeric
a = Numeric.array( ((3, 2, 3),
                    (5, 9, 8) ), "d")
b = Numeric.array( ((4, 7),
                    (9, 3),
                    (8, 1) ), "d")
c = Numeric.matrixmultiply(a, b)

print c
#=> [[  54.   30.]
#=>  [ 165.   70.]]

print a.shape, b.shape, c.shape
#=> (2, 3) (3, 2) (2, 2)
#-----------------------------

# @@PLEAC@@_2.15
#-----------------------------
a = 3+5j
b = 2-2j
c = a * b
print "c =", c
#=> c = (16+4j)

print c.real, c.imag, c.conjugate()
#=> 16.0 4.0 (16-4j)
#-----------------------------
import cmath
print cmath.sqrt(3+4j)
#=> (2+1j)
#-----------------------------

# @@PLEAC@@_2.16
#-----------------------------
number = int(hexadecimal, 16)
number = int(octal, 8)
s = hex(number)
s = oct(number)

num = raw_input("Gimme a number in decimal, octal, or hex: ").rstrip()
if num.startswith("0x"):
    num = int(num[2:], 16)
elif num.startswith("0"):
    num = int(num[1:], 8)
else:
    num = int(num)
print "%(num)d %(num)x %(num)o\n" % { "num": num }
#-----------------------------


# @@PLEAC@@_2.17
#-----------------------------
def commify(amount):
    amount = str(amount)
    firstcomma = len(amount)%3 or 3  # set to 3 if would make a leading comma
    first, rest = amount[:firstcomma], amount[firstcomma:]
    segments = [first] + [rest[i:i+3] for i in range(0, len(rest), 3)]
    return ",".join(segments)

print commify(12345678) 
#=> 12,345,678

# DON'T DO THIS. It works on 2.3+ only and is slower and less straightforward
# than the non-regex version above.
import re
def commify(amount):
    amount = str(amount)
    amount = amount[::-1]
    amount = re.sub(r"(\d\d\d)(?=\d)(?!\d*\.)", r"\1,", amount)
    return amount[::-1]

# @@PLEAC@@_2.18
# Printing Correct Plurals
#-----------------------------
def pluralise(value, root, singular="", plural="s"):
    if value == 1:
        return root + singular
    else:
        return root + plural

print "It took", duration, pluralise(duration, 'hour')

print "%d %s %s enough." % (duration, 
                            pluralise(duration, 'hour'), 
                            pluralise(duration, '', 'is', 'are'))
#-----------------------------
import re
def noun_plural(word):
    endings = [("ss", "sses"),
               ("([psc]h)", r"\1es"),
               ("z", "zes"),
               ("ff", "ffs"),
               ("f", "ves"),
               ("ey", "eys"),
               ("y", "ies"),
               ("ix", "ices"),
               ("([sx])", r"\1es"),
               ("", "s")]
    for singular, plural in endings:
        ret, found = re.subn("%s$"%singular, plural, word)
        if found:
            return ret
    
verb_singular = noun_plural;       # make function alias
#-----------------------------

# @@PLEAC@@_2.19
# Program: Calculating Prime Factors
#-----------------------------
#% bigfact 8 9 96 2178
#8          2**3
#
#9          3**2
#
#96         2**5 3
#
#2178       2 3**2 11**2
#-----------------------------
#% bigfact 239322000000000000000000
#239322000000000000000000 2**19 3 5**18 39887 
#
#
#% bigfact 25000000000000000000000000
#25000000000000000000000000 2**24 5**26
#-----------------------------
import sys

def factorise(num):
    factors = {}
    orig = num
    print num, '\t',

    # we take advantage of the fact that (i +1)**2 = i**2 + 2*i +1
    i, sqi = 2, 4
    while sqi <= num:
        while not num%i:
            num /= i
            factors[i] = factors.get(i, 0) + 1

        sqi += 2*i + 1
        i += 1

    if num != 1 and num != orig:
        factors[num] = factors.get(num, 0) + 1

    if not factors:
        print "PRIME"

    for factor in sorted(factors):
        if factor:
            tmp = str(factor)
            if factors[factor]>1: tmp += "**" + str(factors[factor])
            print tmp,
    print
    
#--------
if __name__ == '__main__':
    if len(sys.argv) == 1:
        print "Usage:", sys.argv[0], " number [number, ]"
    else:
        for strnum in sys.argv[1:]:
            try:
                num = int(strnum)
                factorise(num)
            except ValueError:
                print strnum, "is not an integer"
#-----------------------------
# A more Pythonic variant (which separates calculation from printing):
def format_factor(base, exponent):
    if exponent > 1:
        return "%s**%s"%(base, exponent)
    return str(base)

def factorise(num):
    factors = {}
    orig = num

    # we take advantage of the fact that (i+1)**2 = i**2 + 2*i +1
    i, sqi = 2, 4
    while sqi <= num:
        while not num%i:
            num /= i
            factors[i] = factors.get(i, 0) + 1
        sqi += 2*i + 1
        i += 1

    if num not in (1, orig):
        factors[num] = factors.get(num, 0) + 1

    if not factors:
        return ["PRIME"]

    out = [format_factor(base, exponent)
           for base, exponent in sorted(factors.items())]
    return out

def print_factors(value):
    try:
        num = int(value)
        if num != float(value):
            raise ValueError
    except (ValueError, TypeError):
        raise ValueError("Can only factorise an integer")
    factors = factorise(num) 
    print num, "\t", " ".join(factors)

# @@PLEAC@@_3.0
#----------------------------- 
#introduction
# There are three common ways of manipulating dates in Python
# mxDateTime - a popular third-party module (not discussed here) 
# time - a fairly low-level standard library module 
# datetime - a new library module for Python 2.3 and used for most of these samples 
# (I will use full names to show which module they are in, but you can also use
# from datetime import datetime, timedelta and so on for convenience) 

import time
import datetime

print "Today is day", time.localtime()[7], "of the current year" 
# Today is day 218 of the current year

today = datetime.date.today()
print "Today is day", today.timetuple()[7], "of ", today.year
# Today is day 218 of 2003

print "Today is day", today.strftime("%j"), "of the current year" 
# Today is day 218 of the current year
 

# @@PLEAC@@_3.1
#----------------------------- 
# Finding todays date

today = datetime.date.today()
print "The date is", today 
#=> The date is 2003-08-06

# the function strftime() (string-format time) produces nice formatting
# All codes are detailed at http://www.python.org/doc/current/lib/module-time.html
print t.strftime("four-digit year: %Y, two-digit year: %y, month: %m, day: %d") 
#=> four-digit year: 2003, two-digit year: 03, month: 08, day: 06


# @@PLEAC@@_3.2
#----------------------------- 
# Converting DMYHMS to Epoch Seconds
# To work with Epoch Seconds, you need to use the time module

# For the local timezone
t = datetime.datetime.now()
print "Epoch Seconds:", time.mktime(t.timetuple())
#=> Epoch Seconds: 1060199000.0

# For UTC
t = datetime.datetime.utcnow()
print "Epoch Seconds:", time.mktime(t.timetuple())
#=> Epoch Seconds: 1060195503.0


# @@PLEAC@@_3.3
#----------------------------- 
# Converting Epoch Seconds to DMYHMS

now = datetime.datetime.fromtimestamp(EpochSeconds)
#or use datetime.datetime.utcfromtimestamp()
print now
#=> datetime.datetime(2003, 8, 6, 20, 43, 20)
print now.ctime()
#=> Wed Aug  6 20:43:20 2003

# or with the time module
oldtimetuple = time.localtime(EpochSeconds)
# oldtimetuple contains (year, month, day, hour, minute, second, weekday, yearday, daylightSavingAdjustment) 
print oldtimetuple 
#=> (2003, 8, 6, 20, 43, 20, 2, 218, 1)


# @@PLEAC@@_3.4
#----------------------------- 
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07

print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23

print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=> 1095 days, 0:00:00

#----------------------------- 
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50)   # 1973-01-18 03:45:50

interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55) 
then = birthtime + interval

print "Then is", then.ctime()
#=> Then is Wed Mar 14 06:02:55 1973

print "Then is", then.strftime("%A %B %d %I:%M:%S %p %Y")
#=> Then is Wednesday March 14 06:02:55 AM 1973

#-----------------------------
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55) 
print "Nat was 55 days old on:", when.strftime("%m/%d/%Y").lstrip("0")
#=> Nat was 55 days old on: 3/14/1973


# @@PLEAC@@_3.5
#----------------------------- 
# Dates produce timedeltas when subtracted.

diff = date2 - date1
diff = datetime.date(year1, month1, day1) - datetime.date(year2, month2, day2)
#----------------------------- 

bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
nat  = datetime.datetime(1973, 1, 18, 3, 45, 50)

difference = bree - nat
print "There were", difference, "minutes between Nat and Bree"
#=> There were 3071 days, 0:49:35 between Nat and Bree

weeks, days = divmod(difference.days, 7)

minutes, seconds = divmod(difference.seconds, 60)
hours, minutes = divmod(minutes, 60)

print "%d weeks, %d days, %d:%d:%d" % (weeks, days, hours, minutes, seconds)
#=> 438 weeks, 5 days, 0:49:35

#----------------------------- 
print "There were", difference.days, "days between Bree and Nat." 
#=> There were 3071 days between bree and nat


# @@PLEAC@@_3.6
#----------------------------- 
# Day in a Week/Month/Year or Week Number

when = datetime.date(1981, 6, 16)

print "16/6/1981 was:"
print when.strftime("Day %w of the week (a %A). Day %d of the month (%B).")
print when.strftime("Day %j of the year (%Y), in week %W of the year.")

#=> 16/6/1981 was:
#=> Day 2 of the week (a Tuesday). Day 16 of the month (June).
#=> Day 167 of the year (1981), in week 24 of the year.


# @@PLEAC@@_3.7
#----------------------------- 
# Parsing Dates and Times from Strings

time.strptime("Tue Jun 16 20:18:03 1981")
# (1981, 6, 16, 20, 18, 3, 1, 167, -1)

time.strptime("16/6/1981", "%d/%m/%Y")
# (1981, 6, 16, 0, 0, 0, 1, 167, -1)
# strptime() can use any of the formatting codes from time.strftime()

# The easiest way to convert this to a datetime seems to be; 
now = datetime.datetime(*time.strptime("16/6/1981", "%d/%m/%Y")[0:5])
# the '*' operator unpacks the tuple, producing the argument list.


# @@PLEAC@@_3.8
#----------------------------- 
# Printing a Date
# Use datetime.strftime() - see helpfiles in distro or at python.org

print datetime.datetime.now().strftime("The date is %A (%a) %d/%m/%Y") 
#=> The date is Friday (Fri) 08/08/2003

# @@PLEAC@@_3.9
#----------------------------- 
# High Resolution Timers

t1 = time.clock()
# Do Stuff Here
t2 = time.clock()
print t2 - t1

# 2.27236813618
# Accuracy will depend on platform and OS,
# but time.clock() uses the most accurate timer it can

time.clock(); time.clock()
# 174485.51365466841
# 174485.55702610247

#----------------------------- 
# Also useful;
import timeit
code = '[x for x in range(10) if x % 2 == 0]'
eval(code)
# [0, 2, 4, 6, 8]

t = timeit.Timer(code)
print "10,000 repeats of that code takes:", t.timeit(10000), "seconds" 
print "1,000,000 repeats of that code takes:", t.timeit(), "seconds"

# 10,000 repeats of that code takes: 0.128238644856 seconds
# 1,000,000 repeats of that code takes:  12.5396490336 seconds

#----------------------------- 
import timeit
code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()' 
t = timeit.Timer(code)

print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times." 
print "Average Time:", t.timeit(1000) / 1000
# Time taken: 5.24391507859


# @@PLEAC@@_3.10
#----------------------------- 
# Short Sleeps

seconds = 3.1
time.sleep(seconds)
print "boo"

# @@PLEAC@@_3.11
#----------------------------- 
# Program HopDelta
# Save a raw email to disk and run "python hopdelta.py FILE"
# and it will process the headers and show the time taken
# for each server hop (nb: if server times are wrong, negative dates
# might appear in the output).

import datetime, email, email.Utils
import os, sys, time

def extract_date(hop):
    # According to RFC822, the date will be prefixed with
    # a semi-colon, and is the last part of a received
    # header.
    date_string = hop[hop.find(';')+2:]
    date_string = date_string.strip()
    time_tuple = email.Utils.parsedate(date_string)

    # convert time_tuple to datetime
    EpochSeconds = time.mktime(time_tuple) 
    dt = datetime.datetime.fromtimestamp(EpochSeconds)
    return dt

def process(filename):
    # Main email file processing
    # read the headers and process them
    f = file(filename, 'rb')
    msg = email.message_from_file(f)

    hops = msg.get_all('received')
    
    # in reverse order, get the server(s) and date/time involved
    hops.reverse()
    results = []
    for hop in hops:
        hop = hop.lower()
        
        if hop.startswith('by'):  # 'Received: by' line
            sender = "start"
            receiver = hop[3:hop.find(' ',3)]
            date = extract_date(hop)

        else:  # 'Received: from' line
            sender = hop[5:hop.find(' ',5)]
            by = hop.find('by ')+3
            receiver = hop[by:hop.find(' ', by)]
            date = extract_date(hop)

        results.append((sender, receiver, date))
    output(results)

def output(results):
    print "Sender, Recipient, Time, Delta"
    print
    previous_dt = delta = 0
    for (sender, receiver, date) in results:
        if previous_dt:
            delta = date - previous_dt
        
        print "%s, %s, %s, %s" % (sender,
                               receiver,
                               date.strftime("%Y/%d/%m %H:%M:%S"),
                               delta)
        print
        previous_dt = date   
            
def main():
    # Perform some basic argument checking
    if len(sys.argv) != 2:
        print "Usage: mailhop.py FILENAME"

    else:
        filename = sys.argv[1]
        if os.path.isfile(filename):
            process(filename)
        else:
            print filename, "doesn't seem to be a valid file."

if __name__ == '__main__':
    main()


# @@PLEAC@@_4.0
#-----------------------------
# Python does not automatically flatten lists, in other words
# in the following, non-nested contains four elements and
# nested contains three elements, the third element of which
# is itself a list containing two elements:
non_nested = ["this", "that", "the", "other"]
nested = ["this", "that", ["the", "other"]]
#-----------------------------
tune = ["The", "Star-Spangled", "Banner"]
#-----------------------------

# @@PLEAC@@_4.1
#-----------------------------
a = ["quick", "brown", "fox"]
a = "Why are you teasing me?".split()

text = """
    The boy stood on the burning deck,
    It was as hot as glass.
"""
lines = [line.lstrip() for line in text.strip().split("\n")]
#-----------------------------
biglist = [line.rstrip() for line in open("mydatafile")]
#-----------------------------
banner = "The Mines of Moria"
banner = 'The Mines of Moria'
#-----------------------------
name = "Gandalf"
banner = "Speak, " + name + ", and enter!"
banner = "Speak, %s, and welcome!" % name
#-----------------------------
his_host = "www.python.org"
import os
host_info = os.popen("nslookup " + his_host).read()

# NOTE: not really relevant to Python (no magic '$$' variable)
python_info = os.popen("ps %d" % os.getpid()).read()
shell_info = os.popen("ps $$").read()
#-----------------------------
# NOTE: not really relevant to Python (no automatic interpolation)
banner = ["Costs", "only", "$4.95"]
banner = "Costs only $4.95".split()
#-----------------------------
brax = """ ' " ( ) < > { } [ ] """.split()            #"""
brax = list("""'"()<>{}[]""")                         #"""
rings = '''They're  "Nenya Narya Vilya"'''.split()    #'''
tags   = 'LI TABLE TR TD A IMG H1 P'.split()
sample = r'The backslash (\) is often used in regular expressions.'.split()

#-----------------------------
banner = "The backslash (\\) is often used in regular expressions.".split()
#-----------------------------
ships = u"Niña Pinta Santa María".split()          # WRONG (only three ships)
ships = [u"Niña", u"Pinta", u"Santa María"]        # right
#-----------------------------

# @@PLEAC@@_4.2
#-----------------------------
def commify_series(args):
    n = len(args)
    if n == 0: 
        return ""
    elif n == 1: 
        return args[0]
    elif n == 2: 
        return args[0] + " and " + args[1]
    return ", ".join(args[:-1]) + ", and " + args[-1]

commify_series([])
commify_series(["red"])
commify_series(["red", "yellow"])
commify_series(["red", "yellow", "green"])
#-----------------------------
mylist = ["red", "yellow", "green"]
print "I have", mylist, "marbles."
print "I have", " ".join(mylist), "marbles."
#=> I have ['red', 'yellow', 'green'] marbles.
#=> I have red yellow green marbles.

#-----------------------------
#!/usr/bin/env python
# commify_series - show proper comma insertion in list output
data = (
    ( 'just one thing', ),
    ( 'Mutt Jeff'.split() ),
    ( 'Peter Paul Mary'.split() ),
    ( 'To our parents', 'Mother Theresa', 'God' ),
    ( 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ),
    ( 'recycle tired, old phrases', 'ponder big, happy thoughts' ),
    ( 'recycle tired, old phrases',
      'ponder big, happy thoughts',
      'sleep and dream peacefully' ),
    )

def commify_series(terms):
    for term in terms:
        if "," in term:
            sepchar = "; "
            break
    else:
        sepchar = ", "

    n = len(terms)
    if n == 0: 
        return ""
    elif n == 1:
        return terms[0]
    elif n == 2:
        return " and ".join(terms)
    return "%s%sand %s" % (sepchar.join(terms[:-1]), sepchar, terms[-1])

for item in data:
    print "The list is: %s." % commify_series(item)

#=> The list is: just one thing.
#=> The list is: Mutt and Jeff.
#=> The list is: Peter, Paul, and Mary.
#=> The list is: To our parents, Mother Theresa, and God.
#=> The list is: pastrami, ham and cheese, peanut butter and jelly, and tuna.
#=> The list is: recycle tired, old phrases and ponder big, happy thoughts.
#=> The list is: recycle tired, old phrases; ponder big, happy thoughts; and
#   sleep and dream peacefully.
#-----------------------------

# @@PLEAC@@_4.3
#-----------------------------
# Python allocates more space than is necessary every time a list needs to
# grow and only shrinks lists when more than half the available space is
# unused.  This means that adding or removing an element will in most cases
# not force a reallocation.

del mylist[size:]         # shrink mylist
mylist += [None] * size   # grow mylist by appending 'size' None elements

# To add an element to the end of a list, use the append method:
mylist.append(4)

# To insert an element, use the insert method:
mylist.insert(0, 10) # Insert 10 at the beginning of the list

# To extend one list with the contents of another, use the extend method:
list2 = [1,2,3]
mylist.extend(list2)

# To insert the contents of one list into another, overwriting zero or 
# more elements, specify a slice:
mylist[1:1] = list2   # Don't overwrite anything; grow mylist if needed
mylist[2:3] = list2   # Overwrite mylist[2] and grow mylist if needed

# To remove one element from the middle of a list:
# To remove elements from the middle of a list:
del mylist[idx1:idx2]  # 0 or more
x = mylist.pop(idx)    # remove mylist[idx] and assign it to x

# You cannot assign to or get a non-existent element:
# >>> x = []
# >>> x[4] = 5
#
# Traceback (most recent call last):
#   File "<pyshell#1>", line 1, in -toplevel-
#     x[4] = 5
# IndexError: list assignment index out of range
#
# >>> print x[1000]
#
# Traceback (most recent call last):
#  File "<pyshell#16>", line 1, in -toplevel-
#    print x[1000]
# IndexError: list index out of range
#-----------------------------
def what_about_that_list(terms):
    print "The list now has", len(terms), "elements."
    print "The index of the last element is", len(terms)-1, "(or -1)."
    print "Element #3 is %s." % terms[3]

people = "Crosby Stills Nash Young".split()
what_about_that_list(people)
#-----------------------------
#=> The list now has 4 elements.
#=> The index of the last element is 3 (or -1).
#=> Element #3 is Young.
#-----------------------------
people.pop()
what_about_that_list(people)
#-----------------------------
people += [None] * (10000 - len(people))
#-----------------------------
#>>> people += [None] * (10000 - len(people))
#>>> what_about_that_list(people)
#The list now has 10000 elements.
#The index of the last element is 9999 (or -1).
#Element #3 is None.
#-----------------------------

# @@PLEAC@@_4.4
#-----------------------------
for item in mylist:
    pass # do something with item
#-----------------------------
for user in bad_users:
    complain(user)
#-----------------------------
import os
for (key, val) in sorted(os.environ.items()):
    print "%s=%s" % (key, val)
#-----------------------------
for user in all_users:
    disk_space = get_usage(user)    # find out how much disk space in use
    if disk_space > MAX_QUOTA:      # if it's more than we want ...
        complain(user)              # ... then object vociferously
#-----------------------------
import os
for line in os.popen("who"):
    if "dalke" in line:
        print line,  # or print line[:-1]

# or:
print "".join([line for line in os.popen("who")
                   if "dalke" in line]),

#-----------------------------
for line in myfile:
    for word in line.split(): # Split on whitespace
        print word[::-1],     # reverse word
    print

# pre 2.3:
for line in myfile:
    for word in line.split(): # Split on whitespace
        chars = list(word)    # Turn the string into a list of characters
        chars.reverse()
        print "".join(chars),
    print
#-----------------------------
for item in mylist:
    print "i =", item
#-----------------------------
# NOTE: you can't modify in place the way Perl does:
# data = [1, 2, 3]
# for elem in data:
#     elem -= 1
#print data
#=>[1, 2, 3]

data = [1, 2, 3]
data = [i-1 for i in data]
print data
#=>[0, 1, 2]

# or
for i, elem in enumerate(data):
    data[i] = elem - 1
#-----------------------------
# NOTE: strings are immutable in Python so this doesn't translate well.
s = s.strip()
data = [s.strip() for s in data]
for k, v in mydict.items():
    mydict[k] = v.strip()
#-----------------------------

# @@PLEAC@@_4.5
#-----------------------------
fruits = ["Apple", "Blackberry"]
for fruit in fruits:
    print fruit, "tastes good in a pie."
#=> Apple tastes good in a pie.
#=> Blackberry tastes good in a pie.
#-----------------------------
# DON'T DO THIS:
for i in range(len(fruits)):
    print fruits[i], "tastes good in a pie."

# If you must explicitly index, use enumerate():
for i, fruit in enumerate(fruits):
    print "%s) %s tastes good in a pie."%(i+1, fruit)
#-----------------------------
rogue_cats = ["Morris", "Felix"]
namedict = { "felines": rogue_cats }
for cat in namedict["felines"]:
    print cat, "purrs hypnotically."
print "--More--\nYou are controlled."
#-----------------------------
# As noted before, if you need an index, use enumerate() and not this:
for i in range(len(namedict["felines"])):
    print namedict["felines"][i], "purrs hypnotically."
#-----------------------------

# @@PLEAC@@_4.6
#-----------------------------
uniq = list(set(mylist))
#-----------------------------
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174
# for a more heavyweight version of a bag
seen = {}
for item in mylist:
    seen[item] = seen.get(item, 0) + 1

uniq = seen.keys()
#-----------------------------
seen = {}
uniq = []
for item in mylist:
    count = seen.get(item, 0)
    if count == 0:
        uniq.append(item)
    seen[item] = count + 1
#-----------------------------
# generate a list of users logged in, removing duplicates
import os
usernames = [line.split()[0] for line in os.popen("who")]
uniq = sorted(set(usernames))
print "users logged in:", " ".join(uniq)

# DON'T DO THIS:
import os
ucnt = {}
for line in os.popen("who"):
    username = line.split()[0]  # Get the first word
    ucnt[username] = ucnt.get(username, 0) + 1 # record the users' presence

# extract and print unique keys
users = ucnt.keys()
users.sort()
print "users logged in:", " ".join(users)
#-----------------------------

# @@PLEAC@@_4.7
#-----------------------------
# assume a_list and b_list are already loaded
aonly = [item for item in a_list if item not in b_list]

# A slightly more complex Pythonic version using sets - if you had a few
# lists, subtracting sets would be clearer than the listcomp version above
a_set = set(a_list)
b_set = set(b_list)
aonly = list(a_set - b_set)  # Elements in a_set but not in b_set

# DON'T DO THIS.
seen = {}                 # lookup table to test membership of B
aonly = []                # answer

#    build lookup table
for item in b_list:
    seen[item] = 1

#    find only elements in a_list and not in b_list
for item in a_list:
    if not item not in seen:
        # it's not in 'seen', so add to 'aonly'
        aonly.append(item)
#-----------------------------
# DON'T DO THIS.  There's lots of ways not to do it.
seen = {}   # lookup table
aonly = []  # answer

#     build lookup table - unnecessary and poor Python style
[seen.update({x: 1}) for x in b_list]

aonly = [item for item in a_list if item not in seen]

#-----------------------------
aonly = list(set(a_list))

# DON'T DO THIS.
seen = {}
aonly = []
for item in a_list:
    if item not in seen:
        aonly.append(item)
    seen[item] = 1                    # mark as seen
#-----------------------------
mydict["key1"] = 1
mydict["key2"] = 2
#-----------------------------
mydict[("key1", "key2")] = (1,2)
#-----------------------------
# DON'T DO THIS:
seen = dict.fromkeys(B.keys())

# DON'T DO THIS pre-2.3:
seen = {}
for term in B:
    seen[term] = None
#-----------------------------
# DON'T DO THIS:
seen = {}
for k, v in B:
    seen[k] = 1
#-----------------------------

# @@PLEAC@@_4.8
#-----------------------------
a = (1, 3, 5, 6, 7, 8)
b = (2, 3, 5, 7, 9)

a_set = set(a)
b_set = set(b)

union = a_set | b_set   # or a_set.union(b_set)
isect = a_set & b_set   # or a_set.intersection(b_set) 
diff = a_set ^ b_set    # or a_set.symmetric_difference(b_set)


# DON'T DO THIS:
union_list = []; isect_list = []; diff = []
union_dict = {}; isect_dict = {}
count = {}
#-----------------------------
# DON'T DO THIS:
for e in a:
    union_dict[e] = 1

for e in b:
    if union_dict.has_key(e):
        isect_dict[e] = 1
    union_dict[e] = 1

union_list = union_dict.keys()
isect_list = isect_dict.keys()
#-----------------------------
# DON'T DO THIS:
for e in a + b:
    if union.get(e, 0) == 0:
        isect[e] = 1
    union[e] = 1

union = union.keys()
isect = isect.keys()
#-----------------------------
# DON'T DO THIS:
count = {}
for e in a + b:
    count[e] = count.get(e, 0) + 1

union = []; isect = []; diff = []

for e in count.keys():
    union.append(e)
    if count[e] == 2:
        isect.append(e)
    else:
        diff.append(e)
#-----------------------------
# DON'T DO THIS:
isect = []; diff = []; union = []
count = {}
for e in a + b:
    count[e] = count.get(e, 0) + 1

for e, num in count.items():
    union.append(e)
    [None, diff, isect][num].append(e)
#-----------------------------

# @@PLEAC@@_4.9
#-----------------------------
# "append" for a single term and
# "extend" for many terms
mylist1.extend(mylist2)
#-----------------------------
mylist1 = mylist1 + mylist2
mylist1 += mylist2
#-----------------------------
members = ["Time", "Flies"]
initiates = ["An", "Arrow"]
members.extend(initiates)
# members is now ["Time", "Flies", "An", "Arrow"]
#-----------------------------
members[2:] = ["Like"] + initiates
print " ".join(members)
members[:1] = ["Fruit"]           # or members[1] = "Fruit"
members[-2:] = ["A", "Banana"]
print " ".join(members)
#-----------------------------
#=> Time Flies Like An Arrow
#=> Fruit Flies Like A Banana
#-----------------------------

# @@PLEAC@@_4.10
#-----------------------------
# reverse mylist into revlist

revlist = mylist[::-1]

# or
revlist = list(reversed(mylist))

# or pre-2.3
revlist = mylist[:]    # shallow copy
revlist.reverse()
#-----------------------------
for elem in reversed(mylist):
    pass # do something with elem

# or
for elem in mylist[::-1]:
    pass # do something with elem

# if you need the index and the list won't take too much memory:
for i, elem in reversed(list(enumerate(mylist))):
    pass

# If you absolutely must explicitly index:
for i in range(len(mylist)-1, -1, -1):
    pass
#-----------------------------
descending = sorted(users, reverse=True)
#-----------------------------

# @@PLEAC@@_4.11
#-----------------------------
# remove n elements from the front of mylist
mylist[:n] = []       # or del mylist[:n]

# remove n elements from front of mylist, saving them into front
front, mylist[:n] = mylist[:n], []

# remove 1 element from the front of mylist, saving it in front:
front = mylist.pop(0)

# remove n elements from the end of mylist
mylist[-n:] = []      # or del mylist[-n:]

# remove n elements from the end of mylist, saving them in end
end, mylist[-n:] = mylist[-n:], []

# remove 1 element from the end of mylist, saving it in end:
end = mylist.pop()

#-----------------------------
def shift2(terms):
    front = terms[:2]
    terms[:2] = []
    return front

def pop2(terms):
    back = terms[-2:]
    terms[-2:] = []
    return back
#-----------------------------
friends = "Peter Paul Mary Jim Tim".split()
this, that = shift2(friends)
# 'this' contains Peter, 'that' has Paul, and
# 'friends' has Mary, Jim, and Tim

beverages = "Dew Jolt Cola Sprite Fresca".split()
pair = pop2(beverages)
# pair[0] contains Sprite, pair[1] has Fresca,
# and 'beverages' has (Dew, Jolt, Cola)

# In general you probably shouldn't do things that way because it's 
# not clear from these calls that the lists are modified.
#-----------------------------

# @@PLEAC@@_4.12
for item in mylist:
    if criterion:
        pass    # do something with matched item
        break
else:
    pass     # unfound
#-----------------------------
for idx, elem in enumerate(mylist):
    if criterion:
        pass    # do something with elem found at mylist[idx]
        break
else:
    pass ## unfound
#-----------------------------
# Assuming employees are sorted high->low by wage.
for employee in employees:
    if employee.category == 'engineer':
        highest_engineer = employee
        break

print "Highest paid engineer is:", highest_engineer.name
#-----------------------------
# If you need the index, use enumerate:
for i, employee in enumerate(employees):
    if employee.category == 'engineer':
        highest_engineer = employee
        break
print "Highest paid engineer is: #%s - %s" % (i, highest_engineer.name)


# The following is rarely appropriate:
for i in range(len(mylist)):
    if criterion:
        pass    # do something
        break
else:
    pass ## not found
#-----------------------------


# @@PLEAC@@_4.13
matching = [term for term in mylist if test(term)]
#-----------------------------
matching = []
for term in mylist:
    if test(term):
        matching.append(term)
#-----------------------------
bigs = [num for num in nums if num > 1000000]
pigs = [user for (user, val) in users.items() if val > 1e7]
#-----------------------------
import os
matching = [line for line in os.popen("who") 
                if line.startswith("gnat ")]
#-----------------------------
engineers = [employee for employee in employees
                 if employee.position == "Engineer"]
#-----------------------------
secondary_assistance = [applicant for applicant in applicants
                            if 26000 <= applicant.income < 30000]
#-----------------------------

# @@PLEAC@@_4.14
sorted_list = sorted(unsorted_list)
#-----------------------------
# pids is an unsorted list of process IDs
import os, signal, time
for pid in sorted(pids):
    print pid

pid = raw_input("Select a process ID to kill: ")
try:
    pid = int(pid)
except ValueError:
    raise SystemExit("Exiting ... ")
os.kill(pid, signal.SIGTERM)
time.sleep(2)
try:
    os.kill(pid, signal.SIGKILL)
except OSError, err:
    if err.errno != 3:  # was it already killed?
        raise
#-----------------------------
descending = sorted(unsorted_list, reverse=True)
#-----------------------------
allnums = [4, 19, 8, 3]
allnums.sort(reverse=True)              # inplace
#-----------------------------
# pre 2.3
allnums.sort()                          # inplace
allnums.reverse()                       # inplace
#or
allnums = sorted(allnums, reverse=True) # reallocating
#-----------------------------

# @@PLEAC@@_4.15
ordered = sorted(unordered, cmp=compare)
#-----------------------------
ordered = sorted(unordered, key=compute)

# ...which is somewhat equivalent to: 
precomputed = [(compute(x), x) for x in unordered]
precomputed.sort(lambda a, b: cmp(a[0], b[0]))
ordered = [v for k,v in precomputed.items()]
#-----------------------------
# DON'T DO THIS.
def functional_sort(mylist, function):
    mylist.sort(function)
    return mylist

ordered = [v for k,v in functional_sort([(compute(x), x) for x in unordered],
                                        lambda a, b: cmp(a[0], b[0]))]
#-----------------------------
ordered = sorted(employees, key=lambda x: x.name)
#-----------------------------
for employee in sorted(employees, key=lambda x: x.name):
    print "%s earns $%s" % (employee.name, employee.salary)
#-----------------------------
sorted_employees = sorted(employees, key=lambda x: x.name):
for employee in sorted_employees:
    print "%s earns $%s" % (employee.name, employee.salary)

# load bonus
for employee in sorted_employees:
    if bonus(employee.ssn):
        print employee.name, "got a bonus!"
#-----------------------------
sorted_employees = sorted(employees, key=lambda x: (x.name, x.age)):
#-----------------------------
# NOTE: Python should allow access to the pwd fields by name
# as well as by position.
import pwd
# fetch all users
users = pwd.getpwall()
for user in sorted(users, key=lambda x: x[0]):
    print user[0]
#-----------------------------
sorted_list = sorted(names, key=lambda x: x[:1])
#-----------------------------
sorted_list = sorted(strings, key=len)
#-----------------------------
# DON'T DO THIS.
temp = [(len(s), s) for s in strings]
temp.sort(lambda a, b: cmp(a[0], b[0]))
sorted_list = [x[1] for x in temp]
#-----------------------------
# DON'T DO THIS.
def functional_sort(mylist, function):
    mylist.sort(function)
    return mylist

sorted_fields = [v for k,v in functional_sort(
              [(int(re.search(r"(\d+)", x).group(1)), x) for x in fields],
                                   lambda a, b: cmp(a[0], b[0]))]
#-----------------------------
entries = [line[:-1].split() for line in open("/etc/passwd")]

for entry in sorted(entries, key=lambda x: (x[3], x[2], x[0])):
    print entry
#-----------------------------

# @@PLEAC@@_4.16
#-----------------------------
import itertools
for process in itertools.cycle([1, 2, 3, 4, 5]):
    print "Handling process", process
    time.sleep(1)

# pre 2.3:
import time
class Circular(object):
    def __init__(self, data):
        assert len(data) >= 1, "Cannot use an empty list"
        self.data = data

    def __iter__(self):
        while True:
            for elem in self.data:
                yield elem

circular = Circular([1, 2, 3, 4, 5])

for process in circular:
    print "Handling process", process
    time.sleep(1)

# DON'T DO THIS. All those pops and appends mean that the list needs to be 
# constantly reallocated.  This is rather bad if your list is large:
import time
class Circular(object):
    def __init__(self, data):
        assert len(data) >= 1, "Cannot use an empty list"
        self.data = data

    def next(self):
        head = self.data.pop(0)
        self.data.append(head)
        return head

circular = Circular([1, 2, 3, 4, 5])
while True:
    process = circular.next()
    print "Handling process", process
    time.sleep(1)
#-----------------------------

# @@PLEAC@@_4.17
#-----------------------------
# generate a random permutation of mylist in place
import random
random.shuffle(mylist)
#-----------------------------

# @@PLEAC@@_4.18
#-----------------------------
import sys

def make_columns(mylist, screen_width=78):
    if mylist:
        maxlen = max([len(elem) for elem in mylist])
        maxlen += 1   # to make extra space

        cols = max(1, screen_width/maxlen) 
        rows = 1 + len(mylist)/cols

        # pre-create mask for faster computation
        mask = "%%-%ds " % (maxlen-1)

        for n in range(rows):
            row = [mask%elem
                       for elem in mylist[n::rows]]
            yield "".join(row).rstrip()

for row in make_columns(sys.stdin.readlines(), screen_width=50):
    print row


# A more literal translation
import sys

# subroutine to check whether at last item on line
def EOL(item):
    return (item+1) % cols == 0

# Might not be portable to non-linux systems
def getwinsize():
    # Use the curses module if installed
    try:
        import curses
        stdscr = curses.initscr()
        rows, cols = stdscr.getmaxyx()
        return cols
    except ImportError:
        pass

    # Nope, so deal with ioctl directly.  What value for TIOCGWINSZ?
    try:
        import termios
        TIOCGWINSZ = termios.TIOCGWINSZ
    except ImportError:
        TIOCGWINSZ = 0x40087468  # This is Linux specific

    import struct, fcntl
    s = struct.pack("HHHH", 0, 0, 0, 0)
    try:
        x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
    except IOError:
        return 80
    rows, cols = struct.unpack("HHHH", x)[:2]
    return cols

cols = getwinsize()

data = [s.rstrip() for s in sys.stdin.readlines()]
if not data:
    maxlen = 1
else:
    maxlen = max(map(len, data))

maxlen += 1       # to make extra space

# determine boundaries of screen
cols = (cols / maxlen) or 1
rows = (len(data)+cols) / cols

# pre-create mask for faster computation
mask = "%%-%ds " % (maxlen-1)

# now process each item, picking out proper piece for this position
for item in range(rows * cols):
    target = (item % cols) * rows + (item/cols)
    if target < len(data):
        piece = mask % data[target]
    else:
        piece = mask % ""
    if EOL(item):
        piece = piece.rstrip()  # don't blank-pad to EOL
    sys.stdout.write(piece)
    if EOL(item):
        sys.stdout.write("\n")

if EOL(item):
  sys.stdout.write("\n")
#-----------------------------

# @@PLEAC@@_4.19
#-----------------------------
def factorial(n):
    s = 1
    while n:
        s *= n
        n -= 1
    return s   
#-----------------------------
def permute(alist, blist=[]):
    if not alist:
        yield blist
    for i, elem in enumerate(alist):
        for elem in permute(alist[:i] + alist[i+1:], blist + [elem]):
            yield elem

for permutation in permute(range(4)):
    print permutation
#-----------------------------
# DON'T DO THIS
import fileinput

# Slightly modified from
#   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66463
def print_list(alist, blist=[]):
    if not alist:
        print ' '.join(blist)
    for i in range(len(alist)):
        blist.append(alist.pop(i))
        print_list(alist, blist)
        alist.insert(i, blist.pop())

for line in fileinput.input():
    words = line.split()
    print_list(words)
#-----------------------------
class FactorialMemo(list):
    def __init__(self):
        self.append(1)
        
    def __call__(self, n):
        try:
            return self[n]
        except IndexError:
            ret = n * self(n-1)
            self.append(ret)
            return ret

factorial = FactorialMemo()

import sys
import time
sys.setrecursionlimit(10000)

start = time.time()
factorial(2000)
f1 = time.time() - start
factorial(2100)                 # First 2000 values are cached already
f2 = time.time() - f1 - start
print "Slow first time:", f1
print "Quicker the second time:", f2
#-----------------------------

class MemoizedPermutations(list):
    def __init__(self, alist):
        self.permute(alist, [])
        
    def permute(self, alist, blist):
        if not alist:
            self.append(blist)
        for i, elem in enumerate(alist):
            self.permute(alist[:i] + alist[i+1:], blist + [elem])

    def __call__(self, seq, idx):
        return [seq[n] for n in self[idx]]


p5 = MemoizedPermutations(range(5))

words = "This sentence has five words".split()
print p5(words, 17)
print p5(words, 81)
#-----------------------------

# @@PLEAC@@_5.0
#-----------------------------
# dictionaries
age = {"Nat": 24,
       "Jules": 24,
       "Josh": 17}
#-----------------------------
age = {}
age["Nat"] = 24
age["Jules"] = 25
age["Josh"] = 17
#-----------------------------
food_color = {"Apple":  "red",
              "Banana": "yellow",
              "Lemon":  "yellow",
              "Carrot": "orange"
             }
#-----------------------------
# NOTE: keys must be quoted in Python


# @@PLEAC@@_5.1
mydict[key] = value
#-----------------------------
# food_color defined per the introduction
food_color["Raspberry"] = "pink"
print "Known foods:"
for food in food_color:
    print food

#=> Known foods:
#=> Raspberry
#=> Carrot
#=> Lemon
#=> Apple
#=> Banana
#-----------------------------

# @@PLEAC@@_5.2
# does mydict have a value for key?
if key in mydict:
    pass # it exists
else:
    pass # it doesn't

#-----------------------------
# food_color per the introduction
for name in ("Banana", "Martini"):
    if name in food_color:
        print name, "is a food."
    else:
        print name, "is a drink."

#=> Banana is a food.
#=> Martini is a drink.
#-----------------------------
age = {}
age["Toddler"] = 3
age["Unborn"] = 0
age["Phantasm"] = None

for thing in ("Toddler", "Unborn", "Phantasm", "Relic"):
    print ("%s:"%thing),
    if thing in age:
        print "Exists",
        if age[thing] is not None:
            print "Defined",
        if age[thing]:
            print "True",
    print
#=> Toddler: Exists Defined True
#=> Unborn: Exists Defined
#=> Phantasm: Exists
#=> Relic:
#-----------------------------
# Get file sizes for the requested filenames
import fileinput, os
size = {}
for line in fileinput.input():
    filename = line.rstrip()
    if filename in size:
        continue
    size[filename] = os.path.getsize(filename)


# @@PLEAC@@_5.3
# remove key and its value from mydict
del mydict[key]
#-----------------------------
# food_color as per Introduction
def print_foods():
    foods = food_color.keys()

    print "Keys:", " ".join(foods)
    print "Values:",

    for food in foods:
        color = food_color[food]
        if color is not None:
            print color,
        else:
            print "(undef)",
    print

print "Initially:"
print_foods()

print "\nWith Banana set to None"
food_color["Banana"] = None
print_foods()

print "\nWith Banana deleted"
del food_color["Banana"]
print_foods()

#=> Initially:
#=> Keys: Carrot Lemon Apple Banana
#=> Values: orange yellow red yellow
#=> 
#=> With Banana set to None
#=> Keys: Carrot Lemon Apple Banana
#=> Values: orange yellow red (undef)
#=> 
#=> With Banana deleted
#=> Keys: Carrot Lemon Apple
#=> Values: orange yellow red
#-----------------------------
for key in ["Banana", "Apple", "Cabbage"]:
    del food_color[key]
#-----------------------------


# @@PLEAC@@_5.4
#-----------------------------
for key, value in mydict.items():  
    pass # do something with key and value

# If mydict is large, use iteritems() instead
for key, value in mydict.iteritems():  
    pass # do something with key and value

#-----------------------------
# DON'T DO THIS:
for key in mydict.keys():
    value = mydict[key]
    # do something with key and value
#-----------------------------
# food_color per the introduction
for food, color in food_color.items():
    print "%s is %s." % (food, color)

# DON'T DO THIS:
for food in food_color:
    color = food_color[food]
    print "%s is %s." % (food, color)

#-----------------------------
print """%(food)s

is

%(color)s.
""" % vars()
#-----------------------------
for food, color in sorted(food_color.items()):
    print "%s is %s." % (food, color)

#-----------------------------
#!/usr/bin/env python
# countfrom - count number of messages from each sender

import sys
if len(sys.argv) > 1:
    infile = open(sys.argv[1])
else:
    infile = sys.stdin

counts = {}
for line in infile:
    if line.startswith("From: "):
        name = line[6:-1]
        counts[name] = counts.get(name, 0) + 1

for (name, count) in sorted(counts.items()):
    print "%s: %s" % (name, count)

#-----------------------------


# @@PLEAC@@_5.5
for key, val in mydict.items():
    print key, "=>", val
#-----------------------------
print "\n".join([("%s => %s" % item) for item in mydict.items()])
#-----------------------------
print mydict
#=> {'firstname': 'Andrew', 'login': 'dalke', 'state': 'New Mexico', 'lastname': 'Dalke'}
#-----------------------------
import pprint
pprint.pprint(dict)
#=> {'firstname': 'Andrew',
#=>  'lastname': 'Dalke',
#=>  'login': 'dalke',
#=>  'state': 'New Mexico'}
#-----------------------------


# @@PLEAC@@_5.6
#-----------------------------
class SequenceDict(dict):
    """
    Dictionary that remembers the insertion order.
    The lists returned by keys(), values() and items() are
    in the insertion order.
    """
    def __init__(self, *args):
        self._keys={} # key --> id
        self._ids={}      # id  --> key
        self._next_id=0
        
    def __setitem__(self, key, value):
        self._keys[key]=self._next_id
        self._ids[self._next_id]=key
        self._next_id+=1
        return dict.__setitem__(self, key, value)
    
    def __delitem__(self, key):
        id=self._keys[key]
        del(self._keys[key])
        del(self._ids[id])
        return dict.__delitem__(self, key)

    def values(self):
        values=[]
        ids=list(self._ids.items())
        ids.sort()
        for id, key in ids:
            values.append(self[key])
        return values

    def items(self):
        items=[]
        ids=list(self._ids.items())
        ids.sort()
        for id, key in ids:
            items.append((key, self[key]))
        return items

    def keys(self):
        ids=list(self._ids.items())
        ids.sort()
        keys=[]
        for id, key in ids:
            keys.append(key)
        return keys

    def update(self, d):
        for key, value in d.items():
            self[key]=value

    def clear(self):
        dict.clear(self)
        self._keys={}
        self._ids={}
        self._next_id=0
        
def testSequenceDict():
    sd=SequenceDict()

    # First Test
    sd[3]="first"
    sd[2]="second"
    sd[1]="third"
    print sd.keys()
    print sd.items()
    print sd.values()

    del(sd[1])
    del(sd[2])
    del(sd[3])

    print sd.keys(), sd.items(), sd.values()
    print sd._ids, sd._keys

    print "---------------"
    # Second Test
    sd["b"]="first"
    sd["a"]="second"
    sd.update({"c": "third"})
    print sd.keys()
    print sd.items()
    print sd.values()

    del(sd["b"])
    del(sd["a"])
    del(sd["c"])

    print sd.keys(), sd.items(), sd.values()
    print sd._ids, sd._keys

def likePerlCookbook():
    food_color=SequenceDict()
    food_color["Banana"]="Yellow";
    food_color["Apple"]="Green";
    food_color["Lemon"]="Yellow"
    print "In insertion order, the foods' color are:"
    for food, color in food_color.items():
        print "%s is colored %s" % (food, color)

if __name__=="__main__":
    #testSequenceDict()
    likePerlCookbook()
    

# @@PLEAC@@_5.7
import os
ttys = {}

who = os.popen("who")

for line in who:
    user, tty = line.split()[:2]
    ttys.setdefault(user, []).append(tty)

for (user, tty_list) in sorted(ttys.items()):
    print user + ": " + " ".join(tty_list)
#-----------------------------
import pwd
for (user, tty_list) in ttys.items():
    print user + ":", len(tty_list), "ttys."
    for tty in sorted(tty_list):
        try:
            uid = os.stat("/dev/" + tty).st_uid
            user = pwd.getpwuid(uid)[0]
        except os.error:
            user = "(not available)"
        print "\t%s (owned by %s)" % (tty, user)

# @@PLEAC@@_5.8
# lookup_dict maps keys to values
reverse = dict([(val, key) for (key, val) in lookup_dict.items()])
#-----------------------------
surname = {"Mickey": "Mantle", "Babe": "Ruth"}
first_name = dict([(last, first) for (first, last) in surname.items()])

print first_name["Mantle"]
#=> Mickey
#-----------------------------
#!/usr/bin/perl -w
# foodfind - find match for food or color

import sys
if not sys.argv[1:]:
    raise SystemExit("usage: foodfind food_or_color")
given = sys.argv[1]

color_dict = {"Apple":  "red",
              "Banana": "yellow",
              "Lemon":  "yellow",
              "Carrot": "orange",
             }
food_dict = dict([(color, food) for (food, color) in color_dict.items()])

if given in color_dict:
    print given, "is a food with color", color_dict[given]
elif given in food_dict:
    print food_dict[given], "is a food with color", given
#-----------------------------
# food_color as per the introduction
foods_with_color = {}
for food, color in food_color.items():
    foods_with_color.setdefault(color, []).append(food)

print " ".join(foods_with_color["yellow"]), "were yellow foods."
#-----------------------------

# @@PLEAC@@_5.9
#-----------------------------
# mydict is the hash to sort
for key, value in sorted(mydict.items()):
    # do something with key, value
#-----------------------------
# food_color as per section 5.8
for food, color in sorted(food_color.items()):
    print "%s is %s." % (food, color)
#-----------------------------
# NOTE: alternative version
for item in sorted(food_color.items()):
    print "%s is %s." % item
#-----------------------------
# NOTE: alternative version showing a user-defined function
def food_cmp(x, y):
    return cmp(x, y)

for food, color in sorted(food_color, cmp=food_cmp):
    print "%s is %s." % (food, color)
#-----------------------------
def food_len_cmp(x, y):
    return cmp(len(x), len(y))

for food in sorted(food_color, cmp=food_len_cmp):
    print "%s is %s." % (food, food_color[food])

# In this instance, however, the following is both simpler and faster:
for food in sorted(food_color, key=len):
    print "%s is %s." % (food, food_color[food])
#-----------------------------


# @@PLEAC@@_5.10
#-----------------------------
merged = {}
merged.update(a_dict)
merged.update(b_dict)

#-----------------------------
# NOTE: alternative version
merged = a_dict.copy()
merged.update(b_dict)
#-----------------------------
# DON'T DO THIS:

merged = {}
for k, v in a_dict.items():
    merged[k] = v
for k, v in b_dict.items():
    merged[k] = v
#-----------------------------
# food_color as per section 5.8
drink_color = {"Galliano": "yellow",
               "Mai Tai": "blue"}

ingested_color = drink_color.copy()
ingested_color.update(food_color)
#-----------------------------
# DON'T DO THIS:
drink_color = {"Galliano": "yellow",
               "Mai Tai": "blue"}

substance_color = {}
for k, v in food_color.items():
    substance_color[k] = v
for k, v in drink_color.items():
    substance_color[k] = v
#-----------------------------
# DON'T DO THIS:
substance_color = {}
for mydict in (food_color, drink_color):
    for k, v in mydict:
        substance_color[k] = v
#-----------------------------
# DON'T DO THIS:
substance_color = {}
for item in food_color.items() + drink_color.items():
    for k, v in mydict:
        substance_color[k] = v
#-----------------------------
substance_color = {}
for mydict in (food_color, drink_color):
    for k, v in mydict.items():
        if substance_color.has_key(k):
            print "Warning:", k, "seen twice.  Using the first definition."
            continue
        substance_color[k] = v

# I think it's a copy, in which case
all_colors = new_colors.copy()


# @@PLEAC@@_5.11
common = [k for k in dict1 if k in dict2]
#-----------------------------
this_not_that = [k for k in dict1 if k not in dict2]
#-----------------------------
# citrus_color is a dict mapping citrus food name to its color.
citrus_color = {"Lemon":  "yellow",
                "Orange": "orange",
                "Lime":   "green"}

# build up a list of non-citrus foods
non_citrus = [k for k in food_color if k not in citruscolor]
#-----------------------------

# @@PLEAC@@_5.12
#-----------------------------
# references as keys of dictionaries is no pb in python

name = {}
for filename in ("/etc/termcap", "/vmunix", "/bin/cat"):
    try:
        myfile = open(filename)
    except IOError:
        pass
    else:
        names[myfile] = filename

print "open files:", ", ".join(name.values())
for f, fname in name.items():
    f.seek(0, 2)       # seek to the end
    print "%s is %d bytes long." % (fname, f.tell())
#-----------------------------

# @@PLEAC@@_5.13
# Python doesn't allow presizing of dicts, but hashing is efficient -
# it only re-sizes at intervals, not every time an item is added.

# @@PLEAC@@_5.14
count = {}
for element in mylist:
    count[element] = count.get(element, 0) + 1

# @@PLEAC@@_5.15
#-----------------------------
import fileinput

father = {'Cain': 'Adam',
          'Abel': 'Adam',
          'Seth': 'Adam',
          'Enoch': 'Cain',
          'Irad': 'Enoch',
          'Mehujael': 'Irad',
          'Methusael': 'Mehujael',
          'Lamech': 'Methusael',
          'Jabal': 'Lamech',
          'Tubalcain': 'Lamech',
          'Enos': 'Seth',
         }

for line in fileinput.input():
    person = line.rstrip()
    while person:                    # as long as we have people,
        print person,                # print the current name
        person = father.get(person)  # set the person to the person's father
    print

#-----------------------------
import fileinput

children = {}
for k, v in father.items():
    children.setdefault(v, []).append(k)

for line in fileinput.input():
    person = line.rstrip()
    kids = children.get(person, ["nobody"])
    print person, "begat", ", ".join(kids)

#-----------------------------
import sys, re
pattern = re.compile(r'^\s*#\s*include\s*<([^>]+)')
includes = {}
for filename in filenames:
    try:
        infile = open(filename)
    except IOError, err:
        print>>sys.stderr, err
        continue
    for line in infile:
        match = pattern.match(line)
        if match:
            includes.setdefault(match.group(1), []).append(filename)
#-----------------------------
# list of files that don't include others
mydict = {}
for e in reduce(lambda a,b: a + b, includes.values()):
    if not includes.has_key(e):
        mydict[e] = 1
include_free = mydict.keys()
include_free.sort()

# @@PLEAC@@_5.16
#-----------------------------
#!/usr/bin/env python -w
# dutree - print sorted indented rendition of du output
import os, sys

def get_input(args):
    # NOTE: This is insecure - use only from trusted code!
    cmd = "du " + " ".join(args)
    infile = os.popen(cmd)

    dirsize = {}
    kids = {}
    for line in infile:
        size, name = line[:-1].split("\t", 1)
        dirsize[name] = int(size)
        parent = os.path.dirname(name)
        kids.setdefault(parent, []).append(name)
    # Remove the last field added, which is the root
    kids[parent].pop()
    if not kids[parent]: 
        del kids[parent]

    return name, dirsize, kids

def getdots(root, dirsize, kids):
    size = cursize = dirsize[root]
    if kids.has_key(root):
        for kid in kids[root]:
            cursize -= dirsize[kid]
            getdots(kid, dirsize, kids)
    if size != cursize:
        dot = root + "/."
        dirsize[dot] = cursize
        kids[root].append(dot)

def output(root, dirsize, kids, prefix = "", width = 0):
    path = os.path.basename(root)
    size = dirsize[root]
    fmt = "%" + str(width) + "d %s"
    line = fmt % (size, path)
    print prefix + line

    prefix += (" " * (width-1)) + "| "  + (" " * len(path))

    if kids.has_key(root):
        kid_list = kids[root]
        kid_list.sort(lambda x, y, dirsize=dirsize:
                          cmp(dirsize[x], dirsize[y]))
        width = len(str(dirsize[kid_list[-1]]))
        for kid in kid_list:
            output(kid, dirsize, kids, prefix, width)

def main():
    root, dirsize, kids = get_input(sys.argv[1:])
    getdots(root, dirsize, kids)
    output(root, dirsize, kids)

if __name__ == "__main__":
    main()


# @@PLEAC@@_6.0
# Note: regexes are used less often in Python than in Perl as tasks are often
# covered by string methods, or specialised objects, modules, or packages.

import re                   # "re" is the regular expression module.
re.search("sheep",meadow)   # returns a MatchObject is meadow contains "sheep".
if not re.search("sheep",meadow):
    print "no sheep on this meadow only a fat python."
# replacing strings is not done by "re"gular expressions.
meadow = meadow.replace("old","new")   # replace "old" with "new" and assign result.
#-----------------------------
re.search("ovine",meadow)

meadow = """Fine bovines demand fine toreadors.
Muskoxen are polar ovibovine species.
Grooviness went out of fashion decades ago."""

meadow = "Ovines are found typically in ovaries."

if re.search(r"\bovines\b",meadow,re.I) : print "Here be sheep!"
#-----------------------------
# The tricky bit
mystr = "good food"
re.sub("o*","e",mystr,1) # gives 'egood food'

echo ababacaca | python -c "import sys,re; print re.search('(a|ba|b)+(a|ac)+',sys.stdin.read()).group()"
#-----------------------------
# pattern matching modifiers
# assume perl code iterates over some file
import re, fileinput
for ln = fileinput.input():
    fnd = re.findall("(\d+)",ln)
    if len(fnd) > 0:
        print "Found number %s" % (fnd[0])
# ----------------------------
digits = "123456789"
nonlap = re.findall("(\d\d\d)", digits)
yeslap = ["not yet"]
print "Non-overlapping:",",".join(nonlap)
print "Overlapping    :",",".join(yeslap)
# ----------------------------
mystr = "And little lambs eat ivy"
fnd = re.search("(l[^s]*s)", mystr)
print "(%s) (%s) (%s)" % (mystr[:fnd.start()], fnd.group(), mystr[fnd.end():])
# (And ) (little lambs) ( eat ivy)


# @@PLEAC@@_6.1
import re
dst = re.sub("this","that",src)
#-----------------------------
# strip to basename
basename = re.sub(".*/(?=[^/]+)","",progname)

# Make All Words Title-Cased
# DON'T DO THIS - use str.title() instead
def cap(mo): return mo.group().capitalize()
re.sub("(?P<n>\w+)",cap,"make all words title-cased")

# /usr/man/man3/foo.1 changes to /usr/man/cat3/foo.1
manpage = "/usr/man/man3/foo.1"
catpage  = re.sub("man(?=\d)","cat",manpage)
#-----------------------------
bindirs = "/usr/bin /bin /usr/local/bin".split()
libdirs = [d.replace("bin", "lib") for d in bindirs]

print " ".join(libdirs)
#=> /usr/lib /lib /usr/local/lib
#-----------------------------
# strings are never modified in place.
#-----------------------------

# @@PLEAC@@_6.2
##---------------------------

# DON'T DO THIS.  use line[:-1].isalpha() [this probably goes for the
#    remainder of this section too!]
import re
if re.match("^[A-Za-z]+$",line):
    print "pure alphabetic"
##---------------------------
if re.match(r"^[^\W\d_]+$", line, re.LOCALE):
    print "pure alphabetic"
##---------------------------
import re
import locale

try:
    locale.setlocale(locale.LC_ALL, 'fr_CA.ISO8859-1')
except:
    print "couldn't set locale to French Cnadian"
    raise SystemExit

DATA="""
silly
façade
coöperate
niño
Renée
Molière 
hæmoglobin
naïve
tschüß
random!stuff#here
"""

for ln in DATA.split():
    ln = ln.rstrip()
    if re.match(r"^[^\W\d_]+$",ln,re.LOCALE):
        print "%s: alphabetic" % (ln)
    else:
        print "%s: line noise" % (ln)
# although i dont think "coöperate" should be in canadian
##---------------------------

# @@PLEAC@@_6.3
# Matching Words
"\S+"          # as many non-whitespace bytes as possible
"[A-Za-z'-]+"  # as many letters, apostrophes, and hyphens

# string split is similar to splitting on "\s+"
"A text   with some\tseparator".split()

"\b*([A-Za-z]+)\b*"   # word boundaries 
"\s*([A-Za-z]+)\s*"   # might work too as on letters are allowed.

re.search("\Bis\B","this thistle") # matches on thistle not on this
re.search("\Bis\B","vis-a-vis")    # does not match

# @@PLEAC@@_6.4
#-----------------------------
#!/usr/bin/python
# resname - change all "foo.bar.com" style names in the input stream
# into "foo.bar.com [204.148.40.9]" (or whatever) instead

import socket               # load inet_addr
import fileinput
import re

match = re.compile("""(?P<hostname>  # capture hostname
                         (?:         # these parens for grouping only
                            [\w-]+   # hostname component
                            \.       # ant the domain dot
                         ) +         # now repeat that whole thing a bunch of times
                         [A-Za-z]    # next must be a letter
                         [\w-] +     # now trailing domain part
                      )              # end of hostname capture
                   """,re.VERBOSE)   # for nice formatting

def repl(match_obj):
    orig_hostname = match_obj.group("hostname")
    try:
        addr = socket.gethostbyname(orig_hostname)
    except socket.gaierror:
        addr = "???"
    return "%s [%s]" % (orig_hostname, addr)

for ln in fileinput.input():
    print match.sub(repl, ln)
#-----------------------------
re.sub("""(?x)     # nicer formatting
          \#       #   a pound sign
          (\w+)    #   the variable name
          \#       #   another pound sign
          """,
          lambda m: eval(m.group(1)),  # replace with the value of the global variable
          line
      )
##-----------------------------
re.sub("""(?x)     # nicer formatting
          \#       #   a pound sign
          (\w+)    #   the variable name
          \#       #   another pound sign
          """,
          lambda m: eval(eval(m.group(1))),  # replace with the value of *any* variable
          line
      )
##-----------------------------

# @@PLEAC@@_6.5
import re
pond = "one fish two fish red fish blue fish"
fishes = re.findall(r"(?i)(\w+)\s+fish\b",pond)
if len(fishes)>2:
    print "The third fish is a %s one." % (fishes[2])
##-----------------------------
re.findall(r"(?i)(?:\w+\s+fish\s+){2}(\w+)\s+fish",pond)
##-----------------------------
count = 0
for match_object in re.finditer(r"PAT", mystr):
    count += 1   # or whatever you want to do here

# "progressive" matching might be better if one wants match 5 from 50.
# to count use
count = len(re.findall(r"PAT",mystr))
count = len(re.findall(r"aba","abaababa"))

# "count" overlapping matches
count = len(re.findall(r"(?=aba)","abaababa"))

# FASTEST non-overlapping might be str.count
"abaababa".count("aba")
##-----------------------------
pond = "one fish two fish red fish blue fish"
colors = re.findall(r"(?i)(\w+)\s+fish\b",pond)   # get all matches
color = colors[2]                                 # then the one we want

# or without a temporary list
color = re.findall(r"(?i)(\w+)\s+fish\b",pond)[2] # just grab element 3

print "The third fish in the pond is %s." % (color)
##-----------------------------
import re

pond = "one fish two fish red fish blue fish"
matches = re.findall(r"(\w+)\s+fish\b",pond)
evens = [fish for (i, fish) in enumerate(matches) if i%2]
print "Even numbered fish are %s." % (" ".join(evens))
##-----------------------------
count = 0
def four_is_sushi(match_obj):
    global count
    count += 1
    if count==4:
        return "sushi%s" % (match_obj.group(2))
    return "".join(match_obj.groups())

re.sub(r"""(?x)               # VERBOSE
           \b                 # makes next \w more efficient
           ( \w+ )            # this is what we'll be changing
           (
             \s+ fish \b
           )""",
           four_is_sushi,
           pond)
# one fish two fish red fish sushi fish
##-----------------------------
# greedily
last_fish = re.findall(r"(?i).*\b(\w+)\s+fish\b",pond)
##-----------------------------
pond = "One fish two fish red fish blue fish swim here"
color = re.findall(r"(?i)\b(\w+)\s+fish\b",pond)[-1]
print "Last fish is "+color+"."
# FASTER using string.
lastfish = pond.rfind("fish")
color = pond[:lastfish].split()[-1]
##-----------------------------
r"""(?x)
    A             # find some pattern A
    (?!           # mustn't be able to find
      .*          # something
      A           # and A
    )
    $             # through the end of string
 """

pond = "One fish two fish red fish blue fish swim here"
fnd = re.findall(r"""(?xis)                # VERBOSE, CASEINSENSITIVE, DOTALL
                  \b ( \w+ ) \s+ fish \b
                  (?! .* \b fish \b )""",
                  pond)
if len(fnd):
    print "Last fish is %s." % (fnd[0])
else:
    print "Failed!"


# @@PLEAC@@_6.6
# Matching Multiple Lines
#
#!/usr/bin/python
# killtags - very bad html tag killer
import re
import sys

text = open(sys.argv[1]).read()        # read the whole file
text = re.sub("(?ms)<.*?>","",text)    # strip tags (terrible
print text
## ----------------------------
#!/usr/bin/python
# headerfy: change certain chapter headers to html
import sys, re

match = re.compile(r"""(?xms)          # re.VERBOSE, re.MULTILINE, and re.DOTALL
                       \A              # start of the string
                       (?P<chapter>    # capture in g<chapter>
                         Chapter       # literal string
                         \s+           # mandatory whitespace
                         \d+           # decimal number
                         \s*           # optional whitespace
                         :             # a real colon
                         . *           # anything not a newline till end of line
                       )
                    """)
text = open(sys.argv[1]).read()        # read the whole file
for paragraph in text.split("\n"):   # split on unix end of lines
    p = match.sub("<h1>\g<chapter></h1>",paragraph)
    print p
## ----------------------------
# the one liner does not run.
# python -c 'import sys,re; for p in open(sys.argv[1]).read().split("\n\n"): print re.sub(r"(?ms)\A(Chapter\s+\d+\s*:.*)","<h1>\g0</h1>",p)'
## ----------------------------
match = re.compile(r"(?ms)^START(.*?)^END")
     # s makes . span line boundaries
     # m makes ^ match at the beginning of the string and at the beginning of each line

chunk = 0
for paragraph in open(sys.argv[1]).read().split("\n\n"):
    chunk += 1
    fnd = match.findall(paragraph)
    if fnd:
        print "chunk %d in %s has <<%s>>" % (chunk,sys.argv[1],">>,<<".join(fnd))
## ----------------------------

# @@PLEAC@@_6.7
import sys
# Read the whole file and split
chunks = open(sys.argv[1]).read().split()      # on whitespace
chunks = open(sys.argv[1]).read().split("\n")  # on line ends

# splitting on pattern
import re
pattern = r"x"
chunks = re.split(pattern, open(sys.argv[1]).read())
##-----------------------------
chunks = re.split(r"(?m)^\.(Ch|Se|Ss)$",open(sys.argv[1]).read())
print "I read %d chunks." % (len(chunks))
# without delimiters
chunks = re.split(r"(?m)^\.(?:Ch|Se|Ss)$",open(sys.argv[1]).read())

# with delimiters
chunks = re.split(r"(?m)^(\.(?:Ch|Se|Ss))$",open(sys.argv[1]).read())

# with delimiters at chunkstart
chunks = re.findall(r"""(?xms)       # multiline, dot matches lineend, allow comments
                          ((?:^\.)?  # consume the separator if present
                           .*?)      # match everything but not greedy
                          (?=        # end the match on this but dont consume it
                            (?:                  # dont put into group [1]
                               ^\.(?:Ch|Se|Ss)$  # either end on one of the roff commands
                               |\Z               # or end of text
                            )
                          )""",
                    open(sys.argv[1]).read())
# [1] if "?:" is removed the result holds tuples: ('.Ch\nchapter x','.Ch')
#     which might be more usefull. 

# @@PLEAC@@_6.8
##-----------------------------
# Python doesn't have perl's range operators
# If you want to only use a selected line range, use enumerate
# (though note that indexing starts at zero:
for i, line in enumerate(myfile):
    if firstlinenum <= i < lastlinenum:
        dosomethingwith(line)

# Using patterned ranges is slightly trickier -
# You need to search for the first pattern then
# search for the next pattern:
import re
for line in myfile:
    if re.match(pat1, line):
        break

dosomethingwith(line)    # Only if pat1 can be on same line as pat2

for line in myfile:
    if re.match(pat2, line):
        break
    dosomethingwith(line)
##-----------------------------
# If you need to extract ranges a lot, the following generator funcs
# may be useful:
def extract_range(myfile, start, finish):
    for i, line in enumerate(myfile):
        if start <= i < finish:
            yield line
        elif i == finish:
            break

for line in extract_range(open("/etc/passwd"), 3, 5):
    print line

def patterned_range(myfile, startpat, endpat=None):
    startpat = re.compile(startpat)
    if endpat is not None:
        endpat = re.compile(endpat)
    in_range = False
    for line in myfile:
        if re.match(startpat, line):
            in_range = True
        if in_range:
            yield line
        if endpat is not None and re.match(endpat, line):
            break

# DO NOT DO THIS.  Use the email module instead
for line in patterned_range(msg, "^From:?", "^$"):
    pass #...


# @@PLEAC@@_6.9
tests = (("list.?",r"^list\..$"),
        ("project.*",r"^project\..*$"),
        ("*old",r"^.*old$"),
        ("type*.[ch]",r"^type.*\.[ch]$"),
        ("*.*",r"^.*\..*$"),
        ("*",r"^.*$"),
        )

# The book says convert "*","?","[","]" all other characters will be quoted.
# The book uses "\Q" which escapes any characters that would otherwise be
# treated as regular expression.
# Escaping every char fails as "\s" is not "s" in a regex.

def glob2pat(globstr):
    pat = globstr.replace("\\",r"\\")
    pat = pat.replace(".",r"\.").replace("?",r".").replace("*",r".*")
    
    return "^"+pat+"$"

for globstr, patstr in tests:
    g2p = glob2pat(globstr)
    if g2p != patstr:
        print globstr, "failed! Should be", patstr, "but was", g2p


# @@PLEAC@@_6.10

# download the following standalone program
#!/usr/bin/python
# popgrep1 - grep for abbreviations of places that say "pop"
# version 1: slow but obvious way
import fileinput
import re
popstates = ["CO","ON","MI","WI","MN"]
for line in fileinput.input():
    for state in popstates:
        if re.search(r"\b"+state+r"\b",line):
            print line



#-----------------------------
# download the following standalone program
#!/usr/bin/python
# popgrep2 - grep for abbreviations of places that say "pop"
# version 2: compile the patterns
import fileinput
import re
popstates = ["CO","ON","MI","WI","MN"]
state_re = []
for state in popstates:
    state_re.append(re.compile(r"\b"+state+r"\b"))
for line in fileinput.input():
    for state in state_re:
        if state.search(line):
            print line


#-----------------------------
# download the following standalone program
#!/usr/bin/python
# popgrep3 - grep for abbreviations of places that say "pop"
# version 3: compile a single pattern
import fileinput
import re
popstates = ["CO","ON","MI","WI","MN"]
state_re = re.compile(r"\b(?:"+"|".join(popstates)+r")\b")
for line in fileinput.input():
    if state_re.search(line):
        print line


#-----------------------------
# download the following standalone program
#!/usr/bin/python
# grepauth - print lines that mention both Tom and Nat
import fileinput
import re

def build_match_any(words):
    return re.compile("|".join(words))
def uniq(arr):
    seen = {}
    for item in arr:
        seen[item] = seen.get(item, 0) + 1
    return seen.keys()
def build_match_all(words):
    r = re.compile("|".join(words))
    c = lambda line: len(uniq(r.findall(line)))>=len(words)
    return c

any = build_match_any(("Tom","Nat"))
all = build_match_all(("Tom","Nat"))
for line in fileinput.input():
    if any.search(line):
        print "any:", line
    if all(line):
        print "all:", line



#-----------------------------


# @@PLEAC@@_6.11
# Testing for a Valid Pattern

import re
while True:
    pat = raw_input("Pattern? ")
    try:
        re.compile(pat)
    except re.error, err:
        print "INVALID PATTERN", err
        continue
    break

# ----
def is_valid_pattern(pat):
    try:
        re.compile(pat)
    except re.error:
        return False
    return True

# ----

# download the following standalone program
#!/usr/bin/python
# paragrep - trivial paragraph grepper
#
# differs from perl version in parano.
# python version displays paragraph in current file.

import sys, os.path, re
if len(sys.argv)<=1:
        print "usage: %s pat [files]\n" % sys.argv[0]
        sys.exit(1)

pat = sys.argv[1]
try:
        pat_re = re.compile(pat)
except:
        print "%s: bad pattern %s: %s" % (sys.argv[1], pat, sys.exc_info()[1])
        sys.exit(1)
for filename in filter(os.path.isfile,sys.argv[2:]):
        parano = 0
        for para in open(filename).read().split("\n\n"):
                parano += 1
                if pat_re.search(para):
                        print filename, parano, para, "\n"
                        


# ----

# as we dont evaluate patterns the attack ::
#
#   $pat = "You lose @{[ system('rm -rf *']} big here";
#
# does not work.


# @@PLEAC@@_6.12

# download the following standalone program
#!/usr/bin/python
# localeg - demonstrates locale effects
#
# re must be told to respect locale either in the regexp
# "(?L)" or as flag to the call (python 2.4) "re.LOCALE".

import sys
import re, string
from locale import LC_CTYPE, setlocale, getlocale

name = "andreas k\xF6nig"
locale = {"German" : "de_DE.ISO_8859-1", "English" : "en_US"}
# us-ascii is not supported on linux py23
# none works in activestate py24

try:
    setlocale(LC_CTYPE, locale["English"])
except:
    print "Invalid locale %s" % locale["English"]
    sys.exit(1)
english_names = []
for n in re.findall(r"(?L)\b(\w+)\b",name):
    english_names.append(n.capitalize())

try:
    setlocale(LC_CTYPE, locale["German"])
except:
    print "Invalid locale %s" % locale["German"]
    sys.exit(1)
german_names = map(string.capitalize, re.findall(r"(?L)\b(\w+)\b",name))

print "English names: %s" % " ".join(english_names)
print "German names: %s" % " ".join(german_names)


# @@PLEAC@@_6.13
##-----------------------------
import difflib
matchlist = ["ape", "apple", "lapel", "peach", "puppy"]
print difflib.get_close_matches("appel", matchlist)
#=> ['lapel', 'apple', 'ape']
##-----------------------------
# Also see:
#     http://www.personal.psu.edu/staff/i/u/iua1/python/apse/
#     http://www.bio.cam.ac.uk/~mw263/pyagrep.html

# @@PLEAC@@_6.14
##-----------------------------
# To search (potentially) repeatedly for a pattern, use re.finditer():

# DO NOT DO THIS.  Split on commas and convert elems using int()
mystr = "3,4,5,9,120"
for match in re.finditer("(\d+)", mystr):
    n = match.group(0)
    if n == "9":
        break # '120' will never be matched
    print "Found number", n

# matches know their end position
mystr = "The year 1752 lost 10 days on the 3rd of September"
x = re.finditer("(\d+)", mystr)
for match in x:
    n = match.group(0)
    print "Found number", n

tail = re.match("(\S+)", mystr[match.end():])
if tail:
    print "Found %s after the last number."%tail.group(0)


# @@PLEAC@@_6.15
# Python's regexes are based on Perl's, so it has the non-greedy 
# '*?', '+?', and '??' versions of '*', '+', and '?'.
# DO NOT DO THIS. import htmllib, formatter, etc, instead
#-----------------------------
# greedy pattern
txt = re.sub("<.*>", "", txt) # try to remove tags, very badly

# non-greedy pattern
txt = re.sub("<.*?>", "", txt) # try to remove tags, still rather badly
#-----------------------------
txt = "<b><i>this</i> and <i>that</i> are important</b> Oh, <b><i>me too!</i></b>"

print re.findall("<b><i>(.*?)</i></b>", txt
##-----------------------------
print re.findall("/BEGIN((?:(?!BEGIN).)*)END/", txt)
##-----------------------------
print re.findall("<b><i>((?:(?!<b>|<i>).)*)</i></b>", txt)
##-----------------------------
print re.findall("<b><i>((?:(?!<[ib]>).)*)</i></b>", txt)
##-----------------------------
print re.findall("""
    <b><i> 
    [^<]*  # stuff not possibly bad, and not possibly the end.
    (?:    # at this point, we can have '<' if not part of something bad
     (?!  </?[ib]>  )   # what we can't have
     <                  # okay, so match the '<'
     [^<]*              # and continue with more safe stuff
    ) *
    </i></b>
    """, re.VERBOSE, txt)
##-----------------------------

# @@PLEAC@@_6.16
##-----------------------------
text = """
This is a test
test of the duplicate word finder.
"""
words = text.split()
for curr, next in zip(words[:-1], words[1:]):
    if curr.upper() == next.upper():
            print "Duplicate word '%s' found." % curr

# DON'T DO THIS
import re
pat = r"""
      \b            # start at a word boundary (begin letters)
      (\S+)         # find chunk of non-whitespace
      \b            # until another word boundary (end letters)
      (
          \s+       # separated by some whitespace
          \1        # and that very same chunk again
          \b        # until another word boundary
      ) +           # one or more sets of those
      """
for match in re.finditer(pat, text, flags=re.VERBOSE|re.IGNORECASE):
    print "Duplicate word '%s' found." % match.group(1)
##-----------------------------
a = 'nobody';
b = 'bodysnatcher';

text = a+" "+b
pat = r"^(\w+)(\w+) \2(\w+)$"
for match in re.finditer(pat, text):
    m1, m2, m3 = match.groups()
    print m2, "overlaps in %s-%s-%s"%(m1, m2, m3)
##-----------------------------
pat = r"^(\w+?)(\w+) \2(\w+)$"
##-----------------------------
try:
    while True:
        factor = re.match(r"^(oo+?)\1+$", n).group(1)
        n = re.sub(factor, "o", n)
        print len(factor)
except AttributeError:
    print len(n)
##-----------------------------
def diaphantine(n, x, y, z):
    pat = r"^(o*)\1{%s}(o*)\2{%s}(o*)\3{%s}$"%(x-1, y-1, z-1)
    text = "o"*n
    try:
        vals = [len(v) for v in re.match(pat, text).groups()]
    except ValueError:
        print "No solutions."
    else:
        print "One solution is: x=%s, y=%s, z=%s."%tuple(vals)
        
diaphantine(n=281, x=12, y=15, z=16)

# @@PLEAC@@_6.17
##-----------------------------
# Pass any of the following patterns to re.match(), etc
pat = "ALPHA|BETA"
pat = "^(?=.*ALPHA)(?=.*BETA)"
pat = "ALPHA.*BETA|BETA.*ALPHA"
pat = "^(?:(?!PAT).)*$"
pat = "(?=^(?:(?!BAD).)*$)GOOD"
##-----------------------------
if not re.match(pattern, text):
    something()
##-----------------------------
if re.match(pat1, text) and re.match(pat2, text):
    something()
##-----------------------------
if re.match(pat1, text) or re.match(pat2, text):
    something()
##-----------------------------
# DON'T DO THIS.
"""minigrep - trivial grep"""
import sys, re

pat = sys.argv[1]
for line in sys.stdin:
    if re.match(pat, line):
        print line[:-1]
##-----------------------------
if re.match(r"^(?=.*bell)(?=.*lab)", "labelled"):
    something()
##-----------------------------
if re.search("bell", s) and re.search("lab", s):
    something()
##-----------------------------
if re.match("""
             ^              # start of string
            (?=             # zero-width lookahead
                .*          # any amount of intervening stuff
                bell        # the desired bell string
            )               # rewind, since we were only looking
            (?=             # and do the same thing
                .*          # any amount of intervening stuff
                lab         # and the lab part
            )
            """,
            murray_hill,
            re.DOTALL | re.VERBOSE):
    print "Looks like Bell Labs might be in Murray Hill!"
##-----------------------------
if re.match(r"(?:^.*bell.*lab)|(?:^.*lab.*bell)", "labelled"):
    something()
##-----------------------------
brand = "labelled"
if re.match("""
            (?:                 # non-capturing grouper
                ^ .*?           # any amount of stuff at the front
                bell            # look for a bell
                .*?             # followed by any amount of anything
                lab             # look for a lab
            )                   # end grouper
            |                   # otherwise, try the other direction
            (?:                 # non-capturing grouper
                ^ .*?           # any amount of stuff at the front
                lab             # look for a lab
                .*?             # followed by any amount of anything
                bell            # followed by a bell
            )                   # end grouper
            """,
            brand,
            re.DOTALL | re.VERBOSE):
    print "Our brand has bell and lab separate."
##-----------------------------
x = "odlaw"
if re.match("^(?:(?!waldo).)*$", x):
   print "There's no waldo here!"
##-----------------------------
if re.match("""
            ^                   # start of string
            (?:                 # non-capturing grouper
                (?!             # look ahead negation
                    waldo       # is he ahead of us now?
                )               # is so, the negation failed
                .               # any character (cuzza /s)
            ) *                 # repeat that grouping 0 or more
            $                   # through the end of the string
            """,
            x,
            re.VERBOSE | re.DOTALL):
    print "There's no waldo here!\n";
##-----------------------------

# @@PLEAC@@_6.18
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_6.19
##-----------------------------
from email._parseaddr import AddressList

print AddressList("fred&barney@stonehenge.com").addresslist[0]

print AddressList("fred&barney@stonehenge.com (Hanna Barbara)").addresslist[0]

name, address = AddressList("Mr Fooby Blah <me@nowhere.com>").addresslist[0]
print "%s's address is '%s'"%(name, address)

# @@PLEAC@@_6.20
##-----------------------------
# Assuming the strings all start with different letters, or you don't
# mind there being precedence, use the startswith string method:

def get_action(answer):
    answer = answer.lower()
    actions = ["send", "stop", "abort", "list", "end"]
    for action in actions:
        if action.startswith(answer):
            return action

print "Action is %s."%get_action("L")
#=> Action is list.
##-----------------------------
#DON'T DO THIS:
import re
answer = "ab"
answer = re.escape(answer.strip())
for action in ("SEND", "STOP", "ABORT", "LIST", "EDIT"):
    if re.match(answer, action, flags=re.IGNORECASE):
        print "Action is %s."%action.lower()
##-----------------------------
import re, sys
def handle_cmd(cmd):    
    cmd = re.escape(cmd.strip())
    for name, action in {"edit": invoke_editor,
                         "send": deliver_message,
                         "list": lambda: system(pager, myfile),
                         "abort": sys.exit,
                         }
        if re.match(cmd, name, flags=re.IGNORECASE):
            action()
            break
    else:
        print "Unknown command:", cmd
handle_cmd("ab")

# @@PLEAC@@_6.21
##-----------------------------
# urlify - wrap HTML links around URL-like constructs
import re, sys, fileinput

def urlify_string(s):
    urls = r'(http|telnet|gopher|file|wais|ftp)'
    
    ltrs = r'\w';
    gunk = r'/#~:.?+=&%@!\-'
    punc = r'.:?\-'
    any  = ltrs + gunk + punc 

    pat = re.compile(r"""
      \b                    # start at word boundary
      (                     # begin \1  {
       %(urls)s  :          # need resource and a colon
       [%(any)s] +?         # followed by one or more
                            #  of any valid character, but
                            #  be conservative and take only
                            #  what you need to....
      )                     # end   \1  }
      (?=                   # look-ahead non-consumptive assertion
       [%(punc)s]*          # either 0 or more punctuation
       [^%(any)s]           #   followed by a non-url char
       |                    # or else
       $                    #   then end of the string
      )
    """%locals(), re.VERBOSE | re.IGNORECASE)
    return re.sub(pat, r"<A HREF=\1>\1</A>", s)

if __name__ == "__main__":
    for line in fileinput.input():
        print urlify_string(line)


# @@PLEAC@@_6.22
##-----------------------------
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_6.23
# The majority of regexes in this section are either partially
# or completely The Wrong Thing to Do.
##-----------------------------
# DON'T DO THIS.  Use a Roman Numeral module, etc. (since
# you need one anyway to calculate values)
pat = r"^m*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$"
re.match(pat, "mcmlxcvii")
##-----------------------------
txt = "one two three four five"

# If the words are cleanly delimited just split and rejoin:
word1, word2, rest = txt.split(" ", 2)
print " ".join([word2, word1, rest])

# Otherwise:
frompat = r"(\S+)(\s+)(\S+)"
topat =  r"\3\2\1"
print re.sub(frompat, topat, txt)

##-----------------------------
print str.split("=")

# DON'T DO THIS
pat = r"(\w+)\s*=\s*(.*)\s*$"
print re.match(pat, "key=val").groups()
##-----------------------------
line = "such a very very very very very very very very very very very very very long line"
if len(line) > 80:
    process(line)

# DON'T DO THIS
pat = ".{80,}"
if re.match(pat, line):
    process(line)
##-----------------------------
dt = time.strptime("12/11/05 12:34:56", "%d/%m/%y %H:%M:%S")

# DON'T DO THIS
pat = r"(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)"
dt = re.match(pat, "12/11/05 12:34:56").groups()
##-----------------------------
txt = "/usr/bin/python"
print txt.replace("/usr/bin", "/usr/local/bin")
# Alternatively for file operations use os.path, shutil, etc.

# DON'T DO THIS
print re.sub("/usr/bin", "/usr/local/bin", txt)
##-----------------------------
import re

def unescape_hex(matchobj):
    return chr(int(matchobj.groups(0)[0], 16))
txt = re.sub(r"%([0-9A-Fa-f][0-9A-Fa-f])", unescape_hex, txt)

# Assuming that the hex escaping is well-behaved, an alternative is:
def unescape_hex(seg):
    return chr(int(seg[:2], 16)) + seg[2:]

segs = txt.split("%")
txt = segs[0] + "".join(unescape_hex(seg) for seg in segs[1:])
##-----------------------------
txt = re.sub(r"""
             /\*                    # Match the opening delimiter
             .*?                    # Match a minimal number of characters
             \*/                    # Match the closing delimiter
             """, "", txt, re.VERBOSE)
##-----------------------------
txt.strip()

# DON'T DO THIS
txt = re.sub(r"^\s+", "", txt)
txt = re.sub(r"\s+$", "", txt)
##-----------------------------
txt.replace("\\n", "\n")

# DON'T DO THIS
txt = re.sub("\\n", "\n", txt)
##-----------------------------
txt = re.sub("^.*::", "")
##-----------------------------
import socket
socket.inet_aton(txt) # Will raise an error if incorrect

# DON'T DO THIS.
octseg =r"([01]?\d\d|2[0-4]\d|25[0-5])"
dot = r"\."
pat = "^" + octseg + dot + octseg + dot + octseg + dot + octseg + "$"

if not re.match(pat, txt, re.VERBOSE)
   raise ValueError

# Defitely DON'T DO THIS.
pat = r"""^([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])\.
          ([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])$"""
##-----------------------------
fname = os.path.basename(path)

# DON'T DO THIS.
fname = re.sub("^.*/", "", path)
##-----------------------------
import os
try:
    tc = os.environ["TERMCAP"]
except KeyError:
    cols = 80
else:
    cols = re.match(":co#(\d+):").groups(1)
##-----------------------------
# (not quite equivalent to the Perl version)
name = os.path.basename(sys.argv[0])

# DON'T DO THIS.
name = re.sub("^.*/", "", sys.argv[0])
##-----------------------------
if sys.platform != "linux":
    raise SystemExit("This isn't Linux")
##-----------------------------
txt = re.sub(r"\n\s+", " ", txt)

# In many cases you could just use:
txt = txt.replace("\n", " ")
##-----------------------------
nums = re.findall(r"\d+\.?\d*|\.\d+", txt)
##-----------------------------
# If the words are clearly delimited just use:
capwords = [word for word in txt.split() if word.isupper()]

# Otherwise
capwords = [word for word in re.findall(r"\b(\S+)\b", txt) if word.isupper()]

# (probably) DON'T DO THIS. 
capwords = re.findall(r"(\b[^\Wa-z0-9_]+\b)", txt)
##-----------------------------
# If the words are clearly delimited just use:
lowords = [word for word in txt.split() if word.islower()]

# Otherwise
lowords = [word for word in re.findall(r"\b(\S+)\b", txt) if word.islower()]

# (probably) DON'T DO THIS. 
lowords = re.findall(r"(\b[^\WA-Z0-9_]+\b)", txt)
##-----------------------------
# If the words are clearly delimited just use:
icwords = [word for word in txt.split() if word.istitle()]

# Otherwise
icwords = [word for word in re.finditer(r"\b(\S+)\b") if word.istitle()]

# DON'T DO THIS. 
icwords = re.findall(r"(\b[^\Wa-z0-9_][^\WA-Z0-9_]*\b)", txt)
##-----------------------------
# DON'T DO THIS - use HTMLParser, etc.
links = re.findall(r"""<A[^>]+?HREF\s*=\s*["']?([^'" >]+?)[ '"]?>""", txt)
##-----------------------------
names = txt.split()
if len(names) == 3:
    initial = names[1][0]
else:
    initial = ""

# DON'T DO THIS. 
pat = "^\S+\s+(\S)\S*\s+\S"
try:
    initial = re.match(pat, txt).group(1)
except AttributeError:
    initial = ""
##-----------------------------
txt = re.sub('"([^"]*)"', "``\1''", txt)
##-----------------------------
sentences = [elem[0] for elem in re.findall(r"(.*?[!?.])(  |\Z)", s)]
##-----------------------------
import time
dt = time.strptime(txt, "%Y-%m-%d")

# DON'T DO THIS.
year, month, day = re.match(r"(\d{4})-(\d\d)-(\d\d)", txt).groups()
##-----------------------------
pat = r"""
      ^
      (?:
       1 \s (?: \d\d\d \s)?            # 1, or 1 and area code
       |                               # ... or ...
       \(\d\d\d\) \s                   # area code with parens
       |                               # ... or ...
       (?: \+\d\d?\d? \s)?             # optional +country code
       \d\d\d ([\s\-])                 # and area code
      )
      \d\d\d (\s|\1)                   # prefix (and area code separator)
      \d\d\d\d                         # exchange
        $
      """
re.match(pat, txt, re.VERBOSE)
##-----------------------------
re.match(r"\boh\s+my\s+gh?o(d(dess(es)?|s?)|odness|sh)\b", txt, re.IGNORECASE)
##-----------------------------
for line in file(fname, "Ur"):          #Universal newlines
    process(line)

# DON'T DO THIS
lines = [re.sub(r"^([^\012\015]*)(\012\015?|\015\012?)", "", line) 
         for line in file(fname)]
##-----------------------------


# @@PLEAC@@_7.0
for line in open("/usr/local/widgets/data"):
    if blue in line:
        print line[:-1]
#---------
import sys, re
pattern = re.compile(r"\d")
for line in sys.stdin:
    if not pattern.search(line):
        sys.stderr.write("No digit found.\n")
    sys.stdout.write("Read: " + line)
sys.stdout.close()
#---------
logfile = open("/tmp/log", "w")
#---------
logfile.close()
#---------
print>>logfile, "Countdown initiated ..."
print "You have 30 seconds to reach minimum safety distance."

# DONT DO THIS
import sys
old_output, sys.stdout = sys.stdout, logfile
print "Countdown initiated ..."
sys.stdout = old_output
print "You have 30 seconds to reach minimum safety distance."
#---------

# @@PLEAC@@_7.1
# Python's open() function somewhat covers both perl's open() and 
# sysopen() as it has optional arguments for mode and buffering.
source = open(path)
sink = open(path, "w")
#---------
# NOTE: almost no one uses the low-level os.open and os.fdopen
# commands, so their inclusion here is just silly.  If 
# os.fdopen(os.open(...)) were needed often, it would be turned
# into its own function.  Instead, I'll use 'fd' to hint that
# os.open returns a file descriptor
import os
source_fd = os.open(path, os.O_RDONLY)
source = os.fdopen(fd)
sink_fd = os.open(path, os.O_WRONLY)
sink = os.fdopen(sink_fd)
#---------
myfile = open(filename, "w")
fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
myfile = open(filename, "r+")
#---------
fd = os.open(name, flags)
fd = os.open(name, flags, mode)
#---------
myfile = open(path)
fd = os.open(path, os.O_RDONLY)
#-----------------------------
myfile = open(path, "w")
fd = os.open(path, os.O_WRONLY|os.O_TRUNC|os.O_CREAT)
fd = os.open(path, os.O_WRONLY|os.O_TRUNC|os.O_CREAT, 0600)
#-----------------------------
fd = os.open(path, os.O_WRONLY|os.O_EXCL|os.O_CREAT)
fd = os.open(path, os.O_WRONLY|os.O_EXCL|os.O_CREAT, 0600)
#-----------------------------
myfile = open(path, "a")
fd = os.open(path, os.O_WRONLY|os.O_APPEND|os.O_CREAT)
fd = os.open(path, os.O_WRONLY|os.O_APPEND|s.O_CREAT, 0600)
#-----------------------------
fd = os.open(path, os.O_WRONLY|os.O_APPEND)
#-----------------------------
myfile = open(path, "rw")
fd = os.open(path, os.O_RDWR)
#-----------------------------
fd = os.open(path, os.O_RDWR|os.O_CREAT)
fd = os.open(path, os.O_RDWR|os.O_CREAT, 0600)
#-----------------------------
fd = os.open(path, os.O_RDWR|os.O_EXCL|os.O_CREAT)
fd = os.open(path, os.O_RDWR|os.O_EXCL|os.O_CREAT, 0600)
#-----------------------------

# @@PLEAC@@_7.2
# Nothing different needs to be done with Python

# @@PLEAC@@_7.3
import os
filename = os.path.expanduser(filename)

# @@PLEAC@@_7.4
myfile = open(filename)   # raise an exception on error

try:
    myfile = open(filename)
except IOError, err:
    raise AssertionError("Couldn't open %s for reading : %s" %
                         (filename, err.strerror))

# @@PLEAC@@_7.5
import tempfile

myfile = tempfile.TemporaryFile()

#-----------------------------
# NOTE: The TemporaryFile() call is much more appropriate
# I would not suggest using this code for real work.
import os, tempfile

while True:
    name = os.tmpnam()
    try:
        fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL)
        break
    except os.error:
        pass
myfile = tempfile.TemporaryFileWrapper(os.fdopen(fd), name)

# now go on to use the file ...
#-----------------------------
import os
while True:
    tmpname = os.tmpnam()
    fd = os.open(tmpnam, os.O_RDWR | os.O_CREAT | os.O_EXCL)
    if fd:
        tmpfile = os.fdopen(fd)
        break

os.remove(tmpnam)

#-----------------------------
import tempfile

myfile = tempfile.TemporaryFile(bufsize = 0)
for i in range(10):
    print>>myfile, i
myfile.seek(0)
print "Tmp file has:", myfile.read()
#-----------------------------

# @@PLEAC@@_7.6
DATA = """\
your data goes here
"""
for line in DATA.split("\n"):
    pass # process the line

# @@PLEAC@@_7.7

for line in sys.stdin:
    pass # do something with the line

# processing a list of files from commandline
import fileinput
for line in fileinput.input():
     do something with the line

#-----------------------------
import sys

def do_with(myfile):
    for line in myfile:
        print line[:-1]

filenames = sys.argv[1:]
if filenames:
    for filename in filenames:
        try:
            do_with(open(filename))
        except IOError, err:
            sys.stderr.write("Can't open %s: %s\n" % (filename, err.strerror))
            continue
else:
    do_with(sys.stdin)

#-----------------------------
import sys, glob
ARGV = sys.argv[1:] or glob.glob("*.[Cch]")
#-----------------------------
# NOTE: the getopt module is the prefered mechanism for reading
# command line arguments
import sys
args = sys.argv[1:]
chop_first = 0

if args and args[0] == "-c":
    chop_first += 1
    args = args[1:]

# arg demo 2: Process optional -NUMBER flag

# NOTE: You just wouldn't process things this way for Python,
# but I'm trying to preserve the same semantics.

import sys, re
digit_pattern = re.compile(r"-(\d+)$")

args = sys.argv[1:]
if args:
    match = digit_pattern.match(args[0])
    if match:
        columns = int(match.group(1))
        args = args[1:]

# NOTE: here's the more idiomatic way, which also checks
# for the "--" or a non "-" argument to stop processing

args = sys.argv[1:]
for i in range(len(args)):
    arg = args[i]
    if arg == "--" or not arg.startwith("-"):
        break
    if arg[1:].isdigit():
        columns = int(arg[1:])
        continue



# arg demo 3: Process clustering -a, -i, -n, or -u flags
import sys, getopt
try:
    args, filenames = getopt.getopt(sys.argv[1:], "ainu")
except getopt.error:
    raise SystemExit("usage: %s [-ainu] [filenames] ..." % sys.argv[0])

append = ignore_ints = nostdout = unbuffer = 0
for k, v in args:
    if k == "-a": append += 1
    elif k == "-i": ignore_ints += 1
    elif k == "-n": nostdout += 1
    elif k == "-u": unbuffer += 1
    else:
        raise AssertionError("Unexpected argument: %s" % k)

#-----------------------------
# Note: Idiomatic Perl get translated to idiomatic Python
import fileinput
for line in fileinput.input():
    sys.stdout.write("%s:%s:%s" %
                     (fileinput.filename(), fileinput.filelineno(), line))
#-----------------------------
#!/usr/bin/env python
# findlogin1 - print all lines containing the string "login"
for line in fileinput.input(): # loop over files on command line
    if line.find("login") != -1:
        sys.stdout.write(line)

#-----------------------------
#!/usr/bin/env python
# lowercase - turn all lines into lowercase
### NOTE: I don't know how to do locales in Python
for line in fileinput.input(): # loop over files on command line
    sys.stdout.write(line.lower())

#-----------------------------
#!/usr/bin/env python
# NOTE: The Perl code appears buggy, in that "Q__END__W" is considered
#       to be a __END__ and words after the __END__ on the same line
#       are included in the count!!!
# countchunks - count how many words are used.
# skip comments, and bail on file if __END__
# or __DATA__ seen.
chunks = 0
for line in fileinput.input():
    for word in line.split():
        if word.startswith("#"):
            continue
        if word in ("__DATA__", "__END__"):
            fileinput.close()
            break
        chunks += 1
print "Found", chunks, "chunks"


# @@PLEAC@@_7.8
import shutil

old = open("old")
new = open("new","w")

for line in old:
    new.writeline(line)
new.close()
old.close()

shutil.copyfile("old", "old.orig")
shutil.copyfile("new", "old")

# insert lines at line 20:
for i, line in enumerate(old):
    if i == 20:
        print>>new, "Extra line 1\n"
        print>>new, "Extra line 2\n"
    print>>new, line


# or delete lines 20 through 30:
for i, line in enumerate(old):
    if 20 <= i <= 30:
        continue
    print>>new, line


# @@PLEAC@@_7.9
# modifying with "-i" commandline switch is a perl feature
# python has fileinput
import fileinput, sys, time
today = time.strftime("%Y-%m-%d",time.localtime())
for line in fileinput.input(inplace=1, backup=".orig"):
    sys.stdout.write(line.replace("DATE",today))

# set up to iterate over the *.c files in the current directory,
# editing in place and saving the old file with a .orig extension.
import glob, re
match = re.compile("(?<=[pP])earl")
files = fileinput.FileInput(glob.glob("*.c"), inplace=1, backup=".orig")
while True:
    line = files.readline()
    sys.stderr.write(line)
    if not line:
        break
    if files.isfirstline():
        sys.stdout.write("This line should appear at the top of each file\n")
    sys.stdout.write(match.sub("erl",line))


# @@PLEAC@@_7.10
#-----------------------------
myfile = open(filename, "r+")
data = myfile.read()
# change data here
myfile.seek(0, 0)
myfile.write(data)
myfile.truncate(myfile.tell())
myfile.close()
#-----------------------------
myfile = open(filename, "r+")
data = [process(line) for line in myfile]
myfile.seek(0, 0)
myfile.writelines(data)
myfile.truncate(myfile.tell())
myfile.close()
#-----------------------------

# @@PLEAC@@_7.11
                                                                                                                                                                                                                                                               
import fcntl
myfile = open(somepath, 'r+')
fcntl.flock(myfile, fcntl.LOCK_EX)
# update file, then...
myfile.close()
#-----------------------------
fcntl.LOCK_SH
fcntl.LOCK_EX
fcntl.LOCK_NB
fcntl.LOCK_UN
#-----------------------------
import warnings
try:
    fcntl.flock(myfile, fcntl.LOCK_EX|fcntl.LOCK_NB)
except IOError:
    warnings.warn("can't immediately write-lock the file ($!), blocking ...")
    fcntl.flock(myfile, fcntl.LOCK_EX)
#-----------------------------
fcntl.flock(myfile, fcntl.LOCK_UN)
#-----------------------------
# option "r+" instead "w+" stops python from truncating the file on opening
# when another process might well hold an advisory exclusive lock on it.
myfile = open(somepath, "r+")
fcntl.flock(myfile, fcntl.LOCK_EX)
myfile.seek(0, 0)
myfile.truncate(0)
print>>myfile, "\n"   # or myfile.write("\n")
myfile.close()
#-----------------------------

# @@PLEAC@@_7.12
# Python doesn't have command buffering.  Files can have buffering set,
# when opened:
myfile = open(filename, "r", buffering=0)   #Unbuffered
myfile = open(filename, "r", buffering=1)   #Line buffered
myfile = open(filename, "r", buffering=100) #Use buffer of (approx) 100 bytes
myfile = open(filename, "r", buffering=-1)  #Use system default

myfile.flush()  # Flush the I/O buffer

# stdout is treated as a file.  If you ever need to flush it, do so:
import sys
sys.stdout.flush()

# DON'T DO THIS.  Use urllib, etc.
import socket
mysock = socket.socket()
mysock.connect(('www.perl.com', 80))
# mysock.setblocking(True)
mysock.send("GET /index.html http/1.1\n\n")
f = mysock.makefile()
print "Doc is:"
for line in f:
    print line[:-1]

# @@PLEAC@@_7.13
import select
while True:
    rlist, wlist, xlist = select.select([file1, file2, file3], [], [], 0)
    for r in rlist:
        pass # Do something with the file handle

# @@PLEAC@@_7.14
# @@SKIP@@ Use select.poll() on Unix systems.
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_7.15
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_7.16
# NOTE: this is all much easier in Python
def subroutine(myfile):
    print>>myfile, "Hello, file"

variable = myfile
subroutine(variable)

# @@PLEAC@@_7.17
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_7.18
for myfile in files:
    print>>myfile, stuff_to_print

# NOTE: This is unix specific
import os
file = os.popen("tee file1 file2 file3 >/dev/null", "w")
print>>myfile, "whatever"

# NOTE: the "make STDOUT go to three files" is bad programming style
import os, sys
sys.stdout.file = os.popen("tee file1 file2 file3", "w")
print "whatever"
sys.stdout.close()

# You could use a utility object to redirect writes:
class FileDispatcher(object):
    def __init__(self, *files):
        self.files = files

    def write(self, msg):
        for f in self.files:
            f.write(msg)

    def close(self):
        for f in self.files:
            f.close()

x = open("C:/test1.txt", "w")
y = open("C:/test2.txt", "w")
z = open("C:/test3.txt", "w")

fd = FileDispatcher(x, y, z)
print>>fd, "Foo"     # equiv to fd.write("Foo"); fd.write("\n")
print>>fd, "Testing"  
fd.close()

# @@PLEAC@@_7.19
import os
myfile = os.fdopen(fdnum) # open the descriptor itself
myfile = os.fdopen(os.dup(fdnum)) # open to a copy of the descriptor

###
outcopy = os.fdopen(os.dup(sys.stdin.fileno()), "w")
incopy = os.fdopen(os.dup(sys.stdin.fileno()), "r")

# @@PLEAC@@_7.20
original = open("C:/test.txt")
alias = original
alias.close()
print original.closed
#=>True

import copy

original = open("C:/test.txt")
dupe = copy.copy(original)
dupe.close()
print original.closed
#=>False

# DON'T DO THIS.
import sys
oldstderr = sys.stderr
oldstdout = sys.stdout

sys.stderr = open("C:/stderrfile.txt")
sys.stdout = open("C:/stdoutfile.txt")

print "Blah"  # Will be written to C:/stdoutfile.txt
sys.stdout.close()

sys.stdout = oldstdout
sys.stderr = oldstderr


# @@PLEAC@@_7.21
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_7.22
# On Windows:
import msvcrt
myfile.seek(5, 0)
msvcrt.locking(myfile.fileno(), msvcrt.LK_NBLCK, 3)

# On Unix:
import fcntl
fcntl.lockf(myfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB, 3, 5)


# ^^PLEAC^^_8.0
#-----------------------------
for line in DATAFILE:
    line = line.rstrip()
    size = len(line)
    print size        # output size of line

#-----------------------------
for line in datafile:
    print length(line.rstrip())     # output size of line
#-----------------------------
lines = datafile.readlines()
#-----------------------------
whole_file = myfile.read()
#-----------------------------
## No direct equivalent in Python
#% perl -040 -e '$word = <>; print "First word is $word\n";'
#-----------------------------
## No direct equivalent in Python
#% perl -ne 'BEGIN { $/="%%\n" } chomp; print if /Unix/i' fortune.dat
#-----------------------------
print>>myfile, "One", "two", "three"  # "One two three"
print "Baa baa black sheep."         # Sent to default output file
#-----------------------------
buffer = myfile.read(4096)
rv = len(buffer)
#-----------------------------
myfile.truncate(length)
open("/tmp/%d.pid" % os.getpid(), "a").truncate(length)
#-----------------------------
pos = myfile.tell()
print "I'm", pos, "bytes from the start of DATAFILE."
#-----------------------------
logfile.seek(0, 2)   # Seek to the end
datafile.seek(pos)   # Seek to a given byte
outfile.seek(-20, 1) # Seek back 20 bytes
#-----------------------------
written = os.write(datafile.fileno(), mystr)
if written != len(mystr):
    warnings.warn("only read %s bytes, not %s" % (written, len(mystr)))
#-----------------------------
pos = os.lseek(myfile.fileno(), 0, 1)       # don't change position
#-----------------------------

 
# ^^PLEAC^^_8.1
def ContReader(infile):
    lines = []
    for line in infile:
        line = line.rstrip()
        if line.endswith("\\"):
            lines.append(line[:-1])
            continue
        lines.append(line)
        yield "".join(lines)
        lines = []
    if lines:
        yield "".join(lines)

for line in ContReader(datafile):
    pass # process full record in 'line' here

# ^^PLEAC^^_8.2
import os
count = int(os.popen("wc -l < " + filename).read())
#-----------------------------
for count, line in enumerate(open(filename)):
    pass
count += 1  # indexing is zero based
#-----------------------------
myfile = open(filename)
count = 0
for line in myfile:
    count += 1
# 'count' now holds the number of lines read
#-----------------------------
myfile = open(filename)
count = 0
while True:
    line = myfile.readline()
    if not line:
        break
    count += 1
#-----------------------------
count = 0
while True:
    s = myfile.read(2**16)
    count += s.count("\n")
#-----------------------------
for line, count in zip(open(filename), xrange(1, sys.maxint)):
    pass
# 'count' now holds the number of lines read
#-----------------------------
import fileinput
fi = fileinput.FileInput(filename)
while fi.readline(): pass

count = fi.lineno()
#-----------------------------
def SepReader(infile, sep = "\n\n"):
    text = infile.read(10000)
    if not text:
        return
    while True:
        fields = text.split(sep)
        for field in fields[:-1]:
            yield field
        text = fields[-1]
        new_text = infile.read(10000)
        if not new_text:
            yield text
            break
        text += new_text

para_count = 0
for para in SepReader(open(filename)):
    para_count += 1
# FIXME: For my test case (Python-pre2.2 README from CVS) this
# returns 175 paragraphs while Perl returns 174.
#-----------------------------

 
# ^^PLEAC^^_8.3
for line in sys.stdin:
    for word in line.split():
        pass # do something with 'chunk'
#-----------------------------
pat = re.compile(r"(\w[\w'-]*)")
for line in sys.stdin:
    pos = 0
    while True:
        match = pat.search(line, pos)
        if not match:
            break
        pos = match.end(1)
        # do something with match.group(1)

# EXPERIMENTAL in the sre implementation but
# likely to be included in future (post-2.2) releases.
pat = re.compile(r"(\w[\w'-]*)")
for line in sys.stdin:
    scanner = pat.scanner(line)
    while True:
        match = scanner.search()
        if not match:
            break
        # do something with match.group(1)


#-----------------------------
# Make a word frequency count
import fileinput, re
pat = re.compile(r"(\w[\w'-]*)")
seen = {}
for line in fileinput.input():
    pos = 0
    while True:
        match = pat.search(line, pos)
        if not match:
            break
        pos = match.end(1)
        text = match.group(1).lower()
        seen[text] = seen.get(text, 0) + 1

# output dict in a descending numeric sort of its values
for text, count in sorted(seen.items, key=lambda item: item[1]):
    print "%5d %s" % (count, text)

#-----------------------------
# Line frequency count
import fileinput, sys
seen = {}
for line in fileinput.input():
    text = line.lower()
    seen[text] = seen.get(text, 0) + 1

for text, count in sorted(seen.items, key=lambda item: item[1]):
    sys.stdout.write("%5d %s" % (count, text))

#-----------------------------

 
# ^^PLEAC^^_8.4
lines = myfile.readlines()
while lines:
    line = lines.pop()
    # do something with 'line'

#-----------------------------
for line in reversed(myfile):
    pass  # do something with line
#-----------------------------
for i in range(len(lines)):
    line = lines[-i]
#-----------------------------
for paragraph in sorted(SepReader(infile)):
    pass # do something
#-----------------------------

 

# ^^PLEAC^^_8.5
import time
while True:
    for line in infile:
        pass # do something with the line
    time.sleep(SOMETIME)
    infile.seek(0, 1)
#-----------------------------
import time
naptime = 1

logfile = open("/tmp/logfile")
while True:
    for line in logfile:
        print line.rstrip()
    time.sleep(naptime)
    infile.seek(0, 1)
#-----------------------------
while True:
    curpos = logfile.tell()
    while True:
        line = logfile.readline()
        if not line:
            break
        curpos = logfile.tell()
    sleep(naptime)
    logfile.seek(curpos, 0)  # seek to where we had been
#-----------------------------
import os
if os.stat(LOGFILENAME).st_nlink == 0:
    raise SystemExit
#-----------------------------

 
# ^^PLEAC^^_8.6
import random, fileinput
text = None
for line in fileinput.input():
    if random.randrange(fileinput.lineno()) == 0:
        text = line
# 'text' is the random line
#-----------------------------
# XXX is the perl code correct?  Where is the fortunes file opened?
import sys
adage = None
for i, rec in enumerate(SepReader(open("/usr/share/games/fortunes"), "%\n")):
    if random.randrange(i+1) == 0:
        adage = rec
print adage
#-----------------------------

 
# ^^PLEAC^^_8.7
import random
lines = data.readlines()
random.shuffle(lines)
for line in lines:
    print line.rstrip()
#-----------------------------

 

# ^^PLEAC^^_8.8
# using efficient caching system
import linecache
linecache.getline(filename, DESIRED_LINE_NUMBER)

# or doing it more oldskool
lineno = 0
while True:
    line = infile.readline()
    if not line or lineno == DESIRED_LINE_NUMBER:
        break
    lineno += 1
#-----------------------------
lines = infile.readlines()
line = lines[DESIRED_LINE_NUMBER]
#-----------------------------
for i in range(DESIRED_LINE_NUMBER):
    line = infile.readline()
    if not line:
        break
#-----------------------------

## Not sure what this thing is doing.  Allow fast access to a given
## line number?

# usage: build_index(*DATA_HANDLE, *INDEX_HANDLE)

# ^^PLEAC^^_8.9
# given $RECORD with field separated by PATTERN,
# extract @FIELDS.
fields = re.split(pattern_string, text)
#-----------------------------
pat = re.compile(pattern_string)
fields = pat.split(text)
#-----------------------------
re.split(r"([+-])", "3+5-2")
#-----------------------------
[3, '+', 5, '-', 2]
#-----------------------------
fields = record.split(":")
#-----------------------------
fields = re.split(r":", record)
#-----------------------------
fields = re.split(r"\s+", record)
#-----------------------------
fields = record.split(" ")
#-----------------------------

 
# ^^PLEAC^^_8.10
myfile = open(filename, "r")
prev_pos = pos = 0
while True:
    line = myfile.readline()
    if not line:
        break
    prev_pos = pos
    pos = myfile.tell()
myfile = open(filename, "a")
myfile.truncate(prev_pos)
#-----------------------------

 

# ^^PLEAC^^_8.11
open(filename, "rb")
open(filename, "wb")
#-----------------------------
gifname = "picture.gif"
gif_file = open(gifname, "rb")

# Don't think there's an equivalent for these in Python
#binmode(GIF);               # now DOS won't mangle binary input from GIF
#binmode(STDOUT);            # now DOS won't mangle binary output to STDOUT

#-----------------------------
while True:
    buff = gif.read(8 * 2**10)
    if not buff:
        break
    sys.stdout.write(buff)
#-----------------------------

 

# ^^PLEAC^^_8.12
address = recsize * recno
myfile.seek(address, 0)
buffer = myfile.read(recsize)
#-----------------------------
address = recsize * (recno-1)
#-----------------------------

 

# ^^PLEAC^^_8.13
import posixfile
address = recsize * recno
myfile.seek(address)
buffer = myfile.read(recsize)
# ... work with the buffer, then turn it back into a string and ...
myfile.seek(-recsize, posixfile.SEEK_CUR)
myfile.write(buffer)
myfile.close()
#-----------------------------
## Not yet implemented
# weekearly -- set someone's login date back a week
# @@INCOMPLETE@@


# ^^PLEAC^^_8.14
## Note: this isn't optimal -- the 's+=c' may go O(N**2) so don't
## use for large strings.
myfile.seek(addr)
s = ""
while True:
    c = myfile.read(1)
    if not c or c == "\0":
        break
    s += c
#-----------------------------
myfile.seek(addr)
offset = 0
while True:
    s = myfile.read(1000)
    x = s.find("\0")
    if x != -1:
        offset += x
        break
    offset += len(s)
    if len(s) != 1000:  # EOF
        break
myfile.seek(addr)
s = myfile.read(offset - 1)
myfile.read(1)

#-----------------------------
## Not Implemented
# bgets - get a string from an address in a binary file
#-----------------------------
#!/usr/bin/perl
# strings - pull strings out of a binary file
import re, sys

## Assumes SepReader from above

pat = re.compile(r"([\040-\176\s]{4,})")
for block in SepReader(sys.stdin, "\0"):
    pos = 0
    while True:
        match = pat.search(block, pos)
        if not match:
            break
        print match.group(1)
        pos = match.end(1)
#-----------------------------
 

# @@PLEAC@@_8.15

# RECORDSIZE is the length of a record, in bytes.
# TEMPLATE is the unpack template for the record
# FILE is the file to read from
# FIELDS is a tuple, one element per field
import struct
RECORDSIZE= struct.calcsize(TEMPLATE)
while True:
    record = FILE.read(RECORDSIZE):
    if len(record)!=RECORDSIZE:
        raise "short read"
    FIELDS = struct.unpack(TEMPLATE, record)
# ----


# ^^PLEAC^^_8.16
# NOTE: to parse INI file, see the stanard ConfigParser module.
import re
pat = re.compile(r"\s*=\s*")
for line in config_file:
    if "#" in line:         # no comments
        line = line[:line.index("#")]
    line = line.strip()     # no leading or trailing white
    if not line:            # anything left?
        continue
    m = pat.search(line)
    var = line[:m.start()]
    value = line[m.end():]
    User_Preferences[var] = value


# ^^PLEAC^^_8.17
import os

mode, ino, dev, nlink, uid, gid, size, \
atime, mtime, ctime = os.stat(filename)

mode &= 07777               # discard file type info

#-----------------------------
info = os.stat(filename)
if info.st_uid == 0:
    print "Superuser owns", filename
if info.st_atime > info.st_mtime:
    print filename, "has been read since it was written."
#-----------------------------
import os
def is_safe(path):
    info = os.stat(path)

    # owner neither superuser nor me 
    # the real uid is in stored in the $< variable
    if info.st_uid not in (0, os.getuid()):
        return False

    # check whether group or other can write file.
    # use 066 to detect either reading or writing
    if info.st_mode & 022:  # someone else can write this
        if not os.path.isdir(path):  # non-directories aren't safe
            return False
        # but directories with the sticky bit (01000) are
        if not (info.st_mode & 01000):
            return False
    return True
#-----------------------------
## XXX What is '_PC_CHOWN_RESTRICTED'?

def is_verysafe(path):
    terms = []
    while True:
        path, ending = os.path.split(path)
        if not ending:
            break
        terms.insert(0, ending)
    for term in terms:
        path = os.path.join(path, term)
        if not is_safe(path):
            return False
    return True
#-----------------------------

# Program: tctee
# Not Implemented (requires reimplementing Perl's builtin '>>', '|',
# etc. semantics)

# @@PLEAC@@_8.18
#!/usr/bin/python
# tailwtmp - watch for logins and logouts;
# uses linux utmp structure, from /usr/include/bits/utmp.h

# /* The structure describing an entry in the user accounting database.  */
# struct utmp
# {
#   short int ut_type;            /* Type of login.  */
#   pid_t ut_pid;                 /* Process ID of login process.  */
#   char ut_line[UT_LINESIZE];    /* Devicename.  */
#   char ut_id[4];                /* Inittab ID.  */
#   char ut_user[UT_NAMESIZE];    /* Username.  */
#   char ut_host[UT_HOSTSIZE];    /* Hostname for remote login.  */
#   struct exit_status ut_exit;   /* Exit status of a process marked
#                                    as DEAD_PROCESS.  */
#   long int ut_session;          /* Session ID, used for windowing.  */
#   struct timeval ut_tv;         /* Time entry was made.  */
#   int32_t ut_addr_v6[4];        /* Internet address of remote host.  */
#   char __unused[20];            /* Reserved for future use.  */
# };

# /* Values for the `ut_type' field of a `struct utmp'.  */
# #define EMPTY       0   /* No valid user accounting information.  */
# 
# #define RUN_LVL     1   /* The system's runlevel.  */
# #define BOOT_TIME   2   /* Time of system boot.  */
# #define NEW_TIME    3   /* Time after system clock changed.  */
# #define OLD_TIME    4   /* Time when system clock changed.  */
# 
# #define INIT_PROCESS    5   /* Process spawned by the init process.  */
# #define LOGIN_PROCESS   6   /* Session leader of a logged in user.  */
# #define USER_PROCESS    7   /* Normal process.  */
# #define DEAD_PROCESS    8   /* Terminated process.  */
# 
# #define ACCOUNTING  9

import time
import struct
import os

class WTmpRecord:
    fmt = "hI32s4s32s256siili4l20s";
    _fieldnames = ["type","PID","Line","inittab","User","Hostname",
                    "exit_status", "session", "time", "addr" ]
    def __init__(self):
        self._rec_size = struct.calcsize(self.fmt)
    def size(self):
        return self._rec_size
    def unpack(self, bin_data):
        rec = struct.unpack(self.fmt, bin_data)
        self._rec = []
        for i in range(len(rec)):
            if i in (2,3,4,5):
                # remove character zeros from strings
                self._rec.append( rec[i].split("\0")[0] )
            else:
                self._rec.append(rec[i])
        return self._rec
    def fieldnames(self):
        return self._fieldnames
    def __getattr__(self,name):
        return self._rec[self._fieldnames.index(name)]
        
rec = WTmpRecord()
f = open("/var/log/wtmp","rb")
f.seek(0,2)
while True:
    while True:
        bin = f.read(rec.size())
        if len(bin) != rec.size():
            break
        rec.unpack(bin)
        if rec.type != 0:
            print " %1d %-8s %-12s %-24s %-20s %5d %08x" % \
                (rec.type, rec.User, rec.Line, 
                 time.strftime("%a %Y-%m-%d %H:%M:%S",time.localtime(rec.time)),
                 rec.Hostname, rec.PID, rec.addr)
    time.sleep(1)
f.close()

# @@PLEAC@@_8.19
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_8.20
#!/usr/bin/python
# laston - find out when given user last logged on
import sys
import struct
import pwd
import time
import re

f = open("/var/log/lastlog","rb")

fmt = "L32s256s"
rec_size = struct.calcsize(fmt)

for user in sys.argv[1:]:
    if re.match(r"^\d+$", user):
        user_id = int(user)
    else:
        try:
            user_id = pwd.getpwnam(user)[2]
        except:
            print "no such uid %s" % (user)
            continue
    f.seek(rec_size * user_id)
    bin = f.read(rec_size)
    if len(bin) == rec_size:
        data = struct.unpack(fmt, bin)
        if data[0]:
            logged_in = "at %s" % (time.strftime("%a %H:%M:%S %Y-%m-%d",
                                    time.localtime(data[0])))
            line = " on %s" % (data[1])
            host = " from %s" % (data[2])
        else:
            logged_in = "never logged in"
            line = ""
            host = ""
        print "%-8s UID %5d %s%s%s" % (user, user_id, logged_in, line, host)
    else:
        print "Read failed."
f.close()


# ^^PLEAC^^_9.0
#-----------------------------
entry = os.stat("/usr/bin/vi")
#-----------------------------
entry = os.stat("/usr/bin")
#-----------------------------
entry = os.stat(INFILE.name)
#-----------------------------
entry = os.stat("/usr/bin/vi")
ctime = entry.st_ino
size = entry.st_size
#-----------------------------
f = open(filename)

f.seek(0, 2)
if not f.tell():
    raise SystemExit("%s doesn't have text in it."%filename)
#-----------------------------

for filename in os.listdir("/usr/bin"):
    print "Inside /usr/bin is something called", filename
#-----------------------------

# ^^PLEAC^^_9.1
#-----------------------------
fstat = os.stat(filename)
readtime = fstat.st_atime
writetime = fstat.st_mtime

os.utime(filename, (newreadtime, newwritetime))

#DON'T DO THIS:
readtime, writetime = os.stat(filename)[7:9]
#-----------------------------
SECONDS_PER_DAY = 60 * 60 * 24
fstat = os.stat(filename)
atime = fstat.st_atime - 7 * SECONDS_PER_DAY
mtime = fstat.st_mtime - 7 * SECONDS_PER_DAY

os.utime(filename, (atime, mtime))     
#-----------------------------
mtime = os.stat(filename).st_mtime
utime(filename, (time.time(), mtime))
#-----------------------------
#!/usr/bin/perl -w
# uvi - vi a file without changing its access times

import sys, os
if len(sys.argv) != 2:
    raise SystemExit("usage: uvi filename")
filename = argv[1]
fstat = os.stat(filename)
# WARNING: potential security risk
os.system( (os.environ.get("EDITOR") or "vi") + " " + filename)
os.utime(filename, (fstat.st_atime, fstat.st_mtime))
#-----------------------------

# ^^PLEAC^^_9.2
#-----------------------------
os.remove(filename)

err_flg = 0
for filename in filenames:
    try:
        os.remove(filename)
    except OSError, err:
        err_flg = 1
if err_flg:
    raise OSError("Couldn't remove all of %s: %s" % (filenames, err))
#-----------------------------
os.remove(filename)
#-----------------------------
success = 0
for filename in filenames:
    try:
        os.remove(filename)
        success += 1
    except OSError, err:
        pass
if success != len(filenames):
    sys.stderr.write("could only delete %d of %d files" % \
                     (success, len(filenames)))

#-----------------------------

# ^^PLEAC^^_9.3
#-----------------------------
import shutil
shutil.copy(oldfile, newfile)
#-----------------------------
## NOTE: this doesn't do the same thing as the Perl code,
## eg, handling of partial writes.
infile = open(oldfile)
outfile = open(newfile, "w")

blksize = 16384          # preferred block size?

while True:
    buf = infile.read(blksize)
    if not buf:
        break
    outfile.write(buf)

infile.close()
outfile.close()
#-----------------------------
# WARNING: these are insecure - do not use in hostile environments
os.system("cp %s %s" % (oldfile, newfile))       # unix
os.system("copy %s %s" % (oldfile, newfile))     # dos, vms
#-----------------------------
import shutil

shutil.copy("datafile.dat", "datafile.bak")

shutil.copy("datafile.new", "datafile.dat")
os.remove("datafile.new")

#-----------------------------

# ^^PLEAC^^_9.4
#-----------------------------
import os
seen = {}

def do_my_thing(filename):
    fstat = os.stat(filename)
    key = (fstat.st_ino, fstat.st_dev)
    if not seen.get(key):
        # do something with filename because we haven't
        # seen it before
        pass
    seen[key] = seen.get(key, 0 ) + 1

#-----------------------------
for filename in files:
    fstat = os.stat(filename)
    key = (fstat.st_ino, fstat.st_dev)
    seen.setdefault(key, []).append(filename)

keys = seen.keys()
keys.sort()
for inodev in keys:
    ino, dev = inodev
    filenames = seen[inodev]
    if len(filenames) > 1:
        # 'filenames' is a list of filenames for the same file
        pass
#-----------------------------

# ^^PLEAC^^_9.5
#-----------------------------
for filename in os.listdir(dirname):
    # do something with "$dirname/$file"
    pass
#-----------------------------
# XXX No -T equivalent in Python
#-----------------------------
# 'readir' always skipes '.' and '..' on OSes where those are
# standard directory names
for filename in os.listdir(dirname):
    pass
#-----------------------------
# XX Not Implemented -- need to know what DirHandle does
# use DirHandle;

#-----------------------------

# ^^PLEAC^^_9.6
#-----------------------------
import glob
filenames = glob.glob("*.c")
#-----------------------------
filenames = [filename for filename in os.listdir(path) if filename.endswith(".c")] 
#-----------------------------
import re
allowed_name = re.compile(r"\.[ch]$", re.I).search
filenames = [f for f in os.listdir(path) if allowed_name(f)]
#-----------------------------
import re, os
allowed_name = re.compile(r"\.[ch]$", re.I).search

fnames = [os.path.join(dirname, fname) 
              for fname in os.listdir(dirname)
              if allowed_name(fname)]
#-----------------------------
dirs = [os.path.join(path, f)
            for f in os.listdir(path) if f.isdigit()]
dirs = [d for d in dirs if os.path.isdir(d)]
dirs = sorted(dirs, key=int)    # Sort by numeric value - "9" before "11"
#-----------------------------

# @@PLEAC@@_9.7
# Processing All Files in a Directory Recursively

# os.walk is new in 2.3.

# For pre-2.3 code, there is os.path.walk, which is
# little harder to use.

#-----------------------------
import os
for root, dirs, files in os.walk(top):
    pass # do whatever

#-----------------------------
import os, os.path
for root, dirs, files in os.walk(top):
    for name in dirs:
        print os.path.join(root, name) + '/'
    for name in files:
        print os.path.join(root, name)

#-----------------------------
import os, os.path
numbytes = 0
for root, dirs, files in os.walk(top):
    for name in files:
        path = os.path.join(root, name)
        numbytes += os.path.getsize(path)
print "%s contains %s bytes" % (top, numbytes)

#-----------------------------
import os, os.path
saved_size, saved_name = -1, ''
for root, dirs, files in os.walk(top):
    for name in files:
        path = os.path.join(root, name)
        size = os.path.getsize(path)
        if size > saved_size:
            saved_size = size
            saved_name = path
print "Biggest file %s in %s is %s bytes long" % (
    saved_name, top, saved_size)

#-----------------------------
import os, os.path, time
saved_age, saved_name = None, ''
for root, dirs, files in os.walk(top):
    for name in files:
        path = os.path.join(root, name)
        age = os.path.getmtime(path)
        if saved_age is None or age > saved_age:
            saved_age = age
            saved_name = path
print "%s %s" % (saved_name, time.ctime(saved_age))

#-----------------------------
#!/usr/bin/env python
# fdirs - find all directories
import sys, os, os.path
argv = sys.argv[1:] or ['.']
for top in argv:
    for root, dirs, files in os.walk(top):
        for name in dirs:
            path = os.path.join(root, name)
            print path


# ^^PLEAC^^_9.8
#-----------------------------
# DeleteDir - remove whole directory trees like rm -r
import shutil
shutil.rmtree(path)

# DON'T DO THIS:
import os, sys
def DeleteDir(dir):
    for name in os.listdir(dir):
        file = os.path.join(dir, name)
        if not os.path.islink(file) and os.path.isdir(file):
            DeleteDir(file)
        else:
            os.remove(file)
    os.rmdir(dir)

# @@PLEAC@@_9.9
# Renaming Files

# code sample one to one from my perlcookbook
# looks strange to me.
import os
for fname in fnames:
    newname = fname
    # change the file's name
    try:
        os.rename(fname, newname)
    except OSError, err:
        print "Couldn't rename %s to %s: %s!" % \
                (fname, newfile, err)

# use os.renames if newname needs directory creation.

#A vaguely Pythonic solution is:
import glob
def rename(files, transfunc)
    for fname in fnames:
        newname = transfunc(fname)
        try:
            os.rename(fname, newname)
        except OSError, err:
            print "Couldn't rename %s to %s: %s!" % \
                  (fname, newfile, err)

def transfunc(fname): 
    return fname[:-5]
rename(glob.glob("*.orig"), transfunc) 

def transfunc(fname): 
    return fname.lower()
rename([f for f in glob.glob("*") if not f.startswith("Make)], transfunc) 

def transfunc(fname): 
    return fname + ".bad"
rename(glob.glob("*.f"), transfunc) 

def transfunc(fname): 
    answer = raw_input(fname + ": ")
    if answer.upper().startswith("Y"):
        return fname.replace("foo", "bar")
rename(glob.glob("*"), transfunc) 

def transfunc(fname):
    return ".#" + fname[:-1]
rename(glob.glob("/tmp/*~"), transfunc) 

# This _could_ be made to eval code taken directly from the command line, 
# but it would be fragile
#-----------------------------

# ^^PLEAC^^_9.10
#-----------------------------
import os

base = os.path.basename(path)
dirname = os.path.dirname(path)
dirname, filename = os.path.split(path)
base, ext = os.path.splitext(filename)

#-----------------------------
path = '/usr/lib/libc.a'
filename = os.path.basename(path)
dirname = os.path.dirname(path)

print "dir is %s, file is %s" % (dirname, filename)
# dir is /usr/lib, file is libc.a
#-----------------------------
path = '/usr/lib/libc.a'
dirname, filename = os.path.split(path)
name, ext = os.path.splitext(filename)

print "dir is %s, name is %s, extension is %s" % (dirname, name, ext)
#   NOTE: The Python code prints
# dir is /usr/lib, name is libc, extension is .a
#   while the Perl code prints a '/' after the directory name
# dir is /usr/lib/, name is libc, extension is .a
#-----------------------------
import macpath
path = "Hard%20Drive:System%20Folder:README.txt"
dirname, base = macpath.split(path)
name, ext = macpath.splitext(base)

print "dir is %s, name is %s, extension is %s" % (dirname, name, ext)
# dir is Hard%20Drive:System%20Folder, name is README, extension is .txt
#-----------------------------
# DON'T DO THIS - it's not portable.
def extension(path):
    pos = path.find(".")
    if pos == -1:
        return ""
    ext = path[pos+1:]
    if "/" in ext:
        # wasn't passed a basename -- this is of the form 'x.y/z'
        return ""
    return ext
#-----------------------------

# @@PLEAC@@_9.11

#!/usr/bin/python
# sysmirror - build spectral forest of symlinks
import sys, os, os.path

pgmname = sys.argv[0]
if len(sys.argv)!=3:
    print "usage: %s realdir mirrordir" % pgmname
    raise SystemExit

(srcdir, dstdir) = sys.argv[1:3]
if not os.path.isdir(srcdir):
    print "%s: %s is not a directory" % (pgmname,srcdir)
    raise SystemExit
if not os.path.isdir(dstdir):
    try:
        os.mkdir(dstdir)
    except OSError:
        print "%s: can't make directory %s" % (pgmname,dstdir)
          raise SystemExit

# fix relative paths
srcdir = os.path.abspath(srcdir)
dstdir = os.path.abspath(dstdir)

def wanted(arg, dirname, names):
    for direntry in names:
        relname = "%s/%s" % (dirname, direntry)
        if os.path.isdir(relname):
            mode = os.stat(relname).st_mode
            try:
                os.mkdir("%s/%s" % (dstdir,relname), mode)
            except:
                print "can't mkdir %s/%s" % (dstdir,relname)
                raise SystemExit
        else:
            if relname[:2] == "./":
                relname = relname[2:]
            os.symlink("%s/%s" % (srcdir, relname), "%s/%s" % (dstdir,relname))

os.chdir(srcdir)
os.path.walk(".",wanted,None)

# @@PLEAC@@_9.12
# @@INCOMPLETE@@
# @@INCOMPLETE@@


# ^^PLEAC^^_10.0
#-----------------------------
# DO NOT DO THIS...
greeted = 0
def hello():
    global greeted
    greeted += 1
    print "hi there"

#... as using a callable object to save state is cleaner
# class hello
#     def __init__(self):
#         self.greeted = 0
#     def __call__(self):
#         self.greeted += 1
#         print "hi there"
# hello = hello()
#-----------------------------
hello()                 # call subroutine hello with no arguments/parameters
#-----------------------------

# ^^PLEAC^^_10.1
#-----------------------------
import math
# Provided for demonstration purposes only.  Use math.hypot() instead.
def hypotenuse(side1, side2):
    return math.sqrt(side1**2 + side2**2)

diag = hypotenuse(3, 4)  # diag is 5.0
#-----------------------------
print hypotenuse(3, 4)               # prints 5.0

a = (3, 4)
print hypotenuse(*a)                 # prints 5.0
#-----------------------------
both = men + women
#-----------------------------
nums = [1.4, 3.5, 6.7]
# Provided for demonstration purposes only.  Use:
#     ints = [int(num) for num in nums] 
def int_all(nums):
    retlist = []            # make new list for return
    for n in nums:
        retlist.append(int(n))
    return retlist
ints = int_all(nums)        # nums unchanged
#-----------------------------
nums = [1.4, 3.5, 6.7]

def trunc_em(nums):
    for i,elem in enumerate(nums):
        nums[i] = int(elem)
trunc_em(nums)               # nums now [1,3,6]

#-----------------------------
# By convention, if a method (or function) modifies an object
# in-place, it returns None rather than the modified object.
# None of Python's built-in functions modify in-place; methods
# such as list.sort() are somewhat more common.
mylist = [3,2,1]
mylist = mylist.sort()   # incorrect - returns None
mylist = sorted(mylist)  # correct - returns sorted copy
mylist.sort()            # correct - sorts in-place
#-----------------------------

# ^^PLEAC^^_10.2
#-----------------------------
# Using global variables is discouraged - by default variables
# are visible only at and below the scope at which they are declared.
# Global variables modified by a function or method must be declared 
# using the "global" keyword if they are modified
def somefunc():
    variable = something  # variable is invisible outside of somefunc
#-----------------------------
import sys
name, age = sys.args[1:]  # assumes two and only two command line parameters
start = fetch_time()
#-----------------------------
a, b = pair
c = fetch_time()

def check_x(x):
    y = "whatever"
    run_check()
    if condition:
        print "got", x
#-----------------------------
def save_list(*args):
    Global_List.extend(args)
#-----------------------------

# ^^PLEAC^^_10.3
#-----------------------------
## Python allows static nesting of scopes for reading but not writing,
## preferring to use objects.  The closest equivalent to:
#{
#    my $counter;
#    sub next_counter { return ++$counter }
#}
## is:
def next_counter(counter=[0]):  # default lists are created once only.
    counter[0] += 1
    return counter[0]

# As that's a little tricksy (and can't make more than one counter),
# many Pythonistas would prefer either:
def make_counter():
    counter = 0
    while True:
        counter += 1
        yield counter
next_counter = make_counter().next

# Or:
class Counter:
    def __init__(self):
        self.counter = 0
    def __call__(self):
        self.counter += 1
        return self.counter
next_counter = Counter()

#-----------------------------
## A close equivalent of
#BEGIN {
#    my $counter = 42;
#    sub next_counter { return ++$counter }
#    sub prev_counter { return --$counter }
#}
## is to use a list (to save the counter) and closured functions:
def make_counter(start=0):
    counter = [start]
    def next_counter():
        counter[0] += 1
        return counter[0]
    def prev_counter():
        counter[0] -= 1
        return counter[0]
    return next_counter, prev_counter
next_counter, prev_counter = make_counter()

## A clearer way uses a class:
class Counter:
    def __init__(self, start=0):
        self.value = start
    def next(self):
        self.value += 1
        return self.value
    def prev(self):
        self.value -= 1
        return self.value
    def __int__(self):
        return self.value

counter = Counter(42)
next_counter = counter.next
prev_counter = counter.prev
#-----------------------------

# ^^PLEAC^^_10.4
## This sort of code inspection is liable to change as
## Python evolves.  There may be cleaner ways to do this.
## This also may not work for code called from functions
## written in C.
#-----------------------------
import sys
this_function = sys._getframe(0).f_code.co_name
#-----------------------------
i = 0 # how far up the call stack to look
module = sys._getframe(i).f_globals["__name__"]
filename = sys._getframe(i).f_code.co_filename
line = sys._getframe(i).f_lineno
subr = sys._getframe(i).f_code.co_name
has_args = bool(sys._getframe(i+1).f_code.co_argcount)

# 'wantarray' is Perl specific

#-----------------------------
me = whoami()
him = whowasi()

def whoami():
    sys._getframe(1).f_code.co_name
def whowasi():
    sys._getframe(2).f_code.co_name
#-----------------------------

# ^^PLEAC^^_10.5
#-----------------------------
# Every variable name is a reference to an object, thus nothing special
# needs to be done to pass a list or a dict as a parameter.
list_diff(list1, list2)
#-----------------------------
# Note: if one parameter to zip() is longer it will be truncated
def add_vecpair(x, y):
    return [x1+y1 for x1, y1 in zip(x, y)]

a = [1, 2]
b = [5, 8]
print " ".join([str(n) for n in add_vecpair(a, b)])
#=> 6 10
#-----------------------------
# DO NOT DO THIS:
assert isinstance(x, type([])) and isinstance(y, type([])), \
    "usage: add_vecpair(list1, list2)"
#-----------------------------

# ^^PLEAC^^_10.6
#-----------------------------
# perl return context is not something standard in python...
# but still you can achieve something alike if you really need it
# (but you must really need it badly since you should never use this!!)
#
# see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284742 for more
#
# NB: it has been tested under Python 2.3.x and no guarantees can be given
#     that it works under any future Python version.
import inspect,dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe().f_back.f_back
    bytecode = f.f_code.co_code
    i = f.f_lasti
    instruction = ord(bytecode[i+3])
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = ord(bytecode[i+4])
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def cleverfunc():
    howmany = expecting()
    if howmany == 0:
        print "return value discarded"
    if howmany == 2:
        return 1,2
    elif howmany == 3:
        return 1,2,3
    return 1

cleverfunc()
x = cleverfunc()
print x
x,y = cleverfunc()
print x,y
x,y,z = cleverfunc()
print x,y,z

# ^^PLEAC^^_10.7
#-----------------------------
thefunc(increment= "20s", start="+5m", finish="+30m")
thefunc(start= "+5m",finish="+30m")
thefunc(finish= "+30m")
thefunc(start="+5m", increment="15s")
#-----------------------------
def thefunc(increment='10s',
            finish='0',
            start='0'):
    if increment.endswith("m"):
        pass
#-----------------------------

# ^^PLEAC^^_10.8
#-----------------------------
a, _, c = func()       # Use _ as a placeholder...
a, ignore, c = func()  # ...or assign to an otherwise unused variable
#-----------------------------

# ^^PLEAC^^_10.9
#-----------------------------
def somefunc():
    mylist = []
    mydict = {}
    # ...
    return mylist, mydict

mylist, mydict = somefunc()
#-----------------------------
def fn():
    return a, b, c

#-----------------------------
h0, h1, h2 = fn()
tuple_of_dicts = fn()   # eg: tuple_of_dicts[2]["keystring"]
r0, r1, r2 = fn()       # eg: r2["keystring"]

#-----------------------------

# ^^PLEAC^^_10.10
#-----------------------------
# Note: Exceptions are almost always preferred to error values
return
#-----------------------------
def empty_retval():
    return None

def empty_retval():
    return          # identical to return None

def empty_retval():
    pass            # None returned by default (empty func needs pass)
#-----------------------------
a = yourfunc()
if a:
    pass
#-----------------------------
a = sfunc()
if not a:
    raise AssertionError("sfunc failed")

assert sfunc(), "sfunc failed"
#-----------------------------

# ^^PLEAC^^_10.11
# Prototypes are inapplicable to Python as Python disallows calling
# functions without using brackets, and user functions are able to
# mimic built-in functions with no special actions required as they
# only flatten lists (and convert dicts to named arguments) if
# explicitly told to do so.  Python functions use named parameters
# rather than shifting arguments:

def myfunc(a, b, c=4):
   print a, b, c

mylist = [1,2]

mydict1 = {"b": 2, "c": 3}
mydict2 = {"b": 2}

myfunc(1,2,3)
#=> 1 2 3

myfunc(1,2)
#=> 1 2 4

myfunc(*mylist)
#=> 1 2 4

myfunc(5, *mylist)
#=> 5, 1, 2

myfunc(5, **mydict1)
#=> 5, 2, 3

myfunc(5, **mydict2)
#=> 5, 2, 4

myfunc(c=3, b=2, a=1)
#=> 1, 2, 3

myfunc(b=2, a=1)
#=> 1, 2, 4

myfunc(mylist, mydict1)
#=> [1, 2] {'c': 3, 'b': 2} 4

# For demonstration purposes only - don't do this
def mypush(mylist, *vals):
   mylist.extend(vals)

mylist = []
mypush(mylist, 1, 2, 3, 4, 5)
print mylist
#=> [1, 2, 3, 4, 5]

# ^^PLEAC^^_10.12
#-----------------------------
raise ValueError("some message")  # specific exception class
raise Exception("use me rarely")  # general exception
raise "don't use me"              # string exception (deprecated)
#-----------------------------
# Note that bare excepts are considered bad style.  Normally you should
# trap specific exceptions.  For instance these bare excepts will
# catch KeyboardInterrupt, SystemExit, and MemoryError as well as
# more common errors.  In addition they force you to import sys to
# get the error message.
import warnings, sys
try:
    func()
except:
    warnings.warn("func raised an exception: " + str(sys.exc_info()[1]))
#-----------------------------
try:
    func()
except:
    warnings.warn("func blew up: " + str(sys.exc_info()[1]))
#-----------------------------
class MoonPhaseError(Exception):
    def __init__(self, phase):
        self.phase = phase
class FullMoonError(MoonPhaseError):
    def __init__(self):
        MoonPhaseError.__init__("full moon")

def func():
    raise FullMoonError()

# Ignore only FullMoonError exceptions
try:
    func()
except FullMoonError:
    pass
#-----------------------------
# Ignore only MoonPhaseError for a full moon
try:
    func()
except MoonPhaseError, err:
    if err.phase != "full moon":
        raise
#-----------------------------

# ^^PLEAC^^_10.13
# There is no direct equivalent to 'local' in Python, and
# it's impossible to write your own.  But then again, even in
# Perl it's considered poor style.

# DON'T DO THIS (You probably shouldn't use global variables anyway):
class Local(object):
    def __init__(self, globalname, val):
        self.globalname = globalname
        self.globalval = globals()[globalname]
        globals()[globalname] = val
        
    def __del__(self):
        globals()[self.globalname] = self.globalval

foo = 4

def blah():
    print foo

def blech():
    temp = Local("foo", 6)
    blah()

blah()
blech()
blah()

#-----------------------------

# ^^PLEAC^^_10.14
#-----------------------------
grow = expand
grow()                     # calls expand()

#-----------------------------
one.var = two.table   # make one.var the same as two.table
one.big = two.small   # make one.big the same as two.small
#-----------------------------
fred = barney     # alias fred to barney
#-----------------------------
s = red("careful here")
print s
#> <FONT COLOR='red'>careful here</FONT>
#-----------------------------
# Note: the 'text' should be HTML escaped if it can contain
# any of the characters '<', '>' or '&'
def red(text):
    return "<FONT COLOR='red'>" + text + "</FONT>"
#-----------------------------
def color_font(color, text):
    return "<FONT COLOR='%s'>%s</FONT>" % (color, text)

def red(text): return color_font("red", text)
def green(text): return color_font("green", text)
def blue(text): return color_font("blue", text)
def purple(text): return color_font("purple", text)
# etc
#-----------------------------
# This is done in Python by making an object, instead of
# saving state in a local anonymous context.
class ColorFont:
    def __init__(self, color):
        self.color = color
    def __call__(self, text):
        return "<FONT COLOR='%s'>%s</FONT>" % (self.color, text)

colors = "red blue green yellow orange purple violet".split(" ")
for name in colors:
    globals()[name] = ColorFont(name)
#-----------------------------
# If you really don't want to make a new class, you can
# fake it somewhat by passing in default args.
colors = "red blue green yellow orange purple violet".split(" ")
for name in colors:
    def temp(text, color = name):
        return "<FONT COLOR='%s'>%s</FONT>" % (color, text)
    globals()[name] = temp

#-----------------------------

# ^^PLEAC^^_10.15

# Python has the ability to derive from ModuleType and add
# new __getattr__ and __setattr__ methods.  I don't know the
# expected way to use them to emulate Perl's AUTOLOAD.  Instead,
# here's how something similar would be done in Python.  This
# uses the ColorFont defined above.

#-----------------------------
class AnyColor:
    def __getattr__(self, name):
        return ColorFont(name)

colors = AnyColor()

print colors.chartreuse("stuff")

#-----------------------------
## Skipping this translation because 'local' is too Perl
## specific, and there isn't enough context to figure out
## what this is supposed to do.
#{
#    local *yellow = \&violet;
#    local (*red, *green) = (\&green, \&red);
#    print_stuff();
#}
#-----------------------------

# ^^PLEAC^^_10.16
#-----------------------------
def outer(arg1):
    x = arg1 + 35
    def inner():
        return x * 19
    return x + inner()
#-----------------------------

# ^^PLEAC^^_10.17
#-----------------------------
import mailbox, sys
mbox = mailbox.PortableUnixMailbox(sys.stdin)

def extract_data(msg, idx):
    subject = msg.getheader("Subject", "").strip()
    if subject[:3].lower() == "re:":
        subject = subject[3:].lstrip()
    text = msg.fp.read()
    return subject, idx, msg, text
messages = [extract_data(idx, msg) for idx, msg in enumerate(mbox)]

#-----------------------------
# Sorts by subject then by original position in the list
for subject, pos, msg, text in sorted(messages):
    print "%s\n%s"%(msg, text)

#-----------------------------
# Sorts by subject then date then original position
def subject_date_position(elem):
    return (elem[0], elem[2].getdate("Date"), elem[1])
messages.sort(key=subject_date_position)

# Pre 2.4:
messages = sorted(messages, key=subject_date_position)
#-----------------------------

# @@PLEAC@@_11.0
#Introduction.
#   In Python, all names are references.
#   All objects are inherently anonymous, they don't know what names refer to them.
print ref   # prints the value that the name ref refers to. 
ref = 3     # assigns the name ref to the value 3.
#-----------------------------
aref = mylist
#-----------------------------
aref = [3, 4, 5]    # aref is a name for this list
href = {"How": "Now", "Brown": "Cow"} # href is a name for this dictionary
#-----------------------------
#   Python doesn't have autovivification as (for simple types) there is no difference between a name and a reference.
#   If we try the equivalent of the Perl code we get the list, not a reference to the list.
#-----------------------------
#   To handle multidimensional arrays, you should use an extension to Python,
#   such as numarray (http://www.stsci.edu/resources/software_hardware/numarray)
#-----------------------------
#   In Python, assignment doesn't return anything. 
#-----------------------------
Nat = { "Name": "Leonhard Euler",
        "Address": "1729 Ramanujan Lane\nMathworld, PI 31416",
        "Birthday": 0x5bb5580
}
#-----------------------------

# @@PLEAC@@_11.1
aref = mylist
anon_list = [1, 3, 5, 7, 9]
anon_copy = anon_list
implicit_creation = [2, 4, 6, 8, 10]
#-----------------------------
anon_list.append(11)
#-----------------------------
two = implicit_creation[0]
#-----------------------------
#  To get the last index of a list, you can use len() 
# [or list.__len__() - but don't] directly
last_idx = len(aref) - 1

# Normally, though, you'd use an index of -1 for the last
# element, -2 for the second last, etc.
print implicit_creation[-1]
#=> 10

num_items = len(aref)
#-----------------------------
last_idx = aref.__len__() - 1
num_items = aref.__len__()
#-----------------------------
if not isinstance(someVar, type([])):
    print "Expected a list"
#-----------------------------
print list_ref
#-----------------------------
#   sort is in place.
list_ref.sort()
#-----------------------------
list_ref.append(item)
#-----------------------------
def list_ref():
    return []

aref1 = list_ref()
aref2 = list_ref()
#   aref1 and aref2 point to different lists.
#-----------------------------
list_ref[N] # refers to the Nth item in the list_ref list.
#-----------------------------
# The following two statements are equivalent and return up to 3 elements
# at indices 3, 4, and 5 (if they exist).
pie[3:6]
pie[3:6:1]
#-----------------------------
#   This will insert 3 elements, overwriting elements at indices 3,4, or 5 - if they exist.
pie[3:6] = ["blackberry", "blueberry", "pumpkin"]
#-----------------------------
for item in pie:
    print item

# DON'T DO THIS (this type of indexing should be done with enumerate)
# xrange does not create a list 0..len(pie) - 1, it creates an object 
# that returns one index at a time.
for idx in xrange(len(pie)):
    print pie[idx]

# @@PLEAC@@_11.2
# Making Hashes of Arrays

hash["KEYNAME"].append("new value")

for mystr in hash.keys():
    print "%s: %s" % (mystr, hash[mystr])

hash["a key"] = [3, 4, 5]

values = hash["a key"]

hash["a key"].append(value)

# autovivification also does not work in python.
residents = phone2name[number]
# do this instead
residents = phone2name.get(number, [])


# @@PLEAC@@_11.3
# Taking References to Hashes

href = hash
anon_hash = { "key1":"value1", "key2" : "value2 ..." }
anon_hash_copy = anon_hash.copy()

hash = href
value = href[key]
slice = [href[k] for k in (key1, key2, key3)]
keys = hash.keys()

import types
if type(someref) != types.DictType:
    raise "Expected a dictionary, not %s" % type(someref)
if isinstance(someref,dict):
    raise "Expected a dictionary, not %s" % type(someref)

for href in ( ENV, INC ):
    for key in href.keys():
        print "%s => %s" % (key, href[key])

values = [hash_ref[k] for k in (key1, key2, key3)]

for key in ("key1", "key2", "key3"):
    hash_ref[k] += 7    # not like in perl but the same result.
#-----------------------------

# @@PLEAC@@_11.4
#-----------------------------
cref = func
cref = lambda a, b: ...
#-----------------------------
returned = cref(arguments)
#-----------------------------
funcname = "thefunc"
locals()[funcname]();
#-----------------------------
commands = {
    'happy': joy,
    'sad': sullen,
    'done': (lambda : sys.exit()),  # In this case "done: sys.exit" would suffice
    'mad': angry,
    }

print "How are you?",
cmd = raw_input()
if cmd in commands:
    commands[cmd]()
else:
    print "No such command: %s" % cmd
#-----------------------------
def counter_maker():
    start = [0]
    def counter_function():
        # start refers to the variable defined in counter_maker, but
        # we can't reassign or increment variables in parent scopes.
        # By using a one-element list we can modify the list without
        # reassigning the variable.  This way of using a list is very
        # like a reference.
        start[0] += 1
        return start[0]-1
    return counter_function

counter = counter_maker()
for i in range(5):
    print counter()
#-----------------------------
counter1 = counter_maker()
counter2 = counter_maker()

for i in range(5):
    print counter1()
print counter1(), counter2()
#=> 0
#=> 1
#=> 2
#=> 3
#=> 4
#=> 5 0
#-----------------------------
import time
def timestamp():
    start_time = time.time()
    def elapsed():
        return time.time() - start_time
    return elapsed
early = timestamp()
time.sleep(20)
later = timestamp()
time.sleep(10)
print "It's been %d seconds since early" % early()
print "It's been %d seconds since later" % later()
#=> It's been 30 seconds since early.
#=> It's been 10 seconds since later.
#-----------------------------

# @@PLEAC@@_11.5
# A name is a reference to an object and an object can be referred to
# by any number of names. There is no way to manipulate pointers or
# an object's id.  This section is thus inapplicable.
x = 1
y = x
print x, id(x), y, id(y)
x += 1    # "x" now refers to a different object than y
print x, id(x), y, id(y)
y = 4     # "y" now refers to a different object than it did before
print x, id(x), y, id(y)

# Some objects (including ints and strings) are immutable, however, which
# can give the illusion of a by-value/by-reference distinction:
a = x = [1]
b = y = 1
c = z = "s"
print a, b, c
#=> [1] 1 s

x += x      # calls list.__iadd__ which is inplace.
y += y      # can't find int.__iadd__ so calls int.__add__ which isn't inplace
z += z      # can't find str.__iadd__ so calls str.__add__ which isn't inplace              
print a, b, c
#=> [1, 1] 1 s

# @@PLEAC@@_11.6
# As indicated by the previous section, everything is referenced, so
# just create a list as normal, and beware that augmented assignment
# works differently with immutable objects to mutable ones:
mylist = [1, "s", [1]]
print mylist
#=> [1, s, [1]]

for elem in mylist:
    elem *= 2
print mylist
#=> [1, s, [1, 1]]

mylist[0] *= 2
mylist[-1] *= 2
print mylist
#=> [1, s, [1, 1, 1, 1]]

# If you need to modify every value in a list, you should use a list comprehension
# which does NOT modify inplace:
import math
mylist = [(val**3 * 4/3*math.pi) for val in mylist]

# @@PLEAC@@_11.7
#-----------------------------
c1 = mkcounter(20)
c2 = mkcounter(77)

print "next c1: %d" % c1['next']()  # 21
print "next c2: %d" % c2['next']()  # 78
print "next c1: %d" % c1['next']()  # 22
print "last c1: %d" % c1['prev']()  # 21
print "old  c2: %d" % c2['reset']() # 77
#-----------------------------
# DON'T DO THIS.  Use an object instead  
def mkcounter(start):
    count = [start]
    def next():
        count[0] += 1
        return count[0]
    def prev():
        count[0] -= 1
        return count[0]
    def get():
        return count[0]
    def set(value):
        count[0] = value
        return count[0]
    def bump(incr):
        count[0] += incr
        return count[0]
    def reset():
        count[0] = start
        return count[0]
    return {
        'next': next, 'prev': prev, 'get': get, 'set': set,
        'bump': bump, 'reset': reset, 'last': prev}
#-----------------------------

# @@PLEAC@@_11.8
#-----------------------------
mref = obj.meth
# later...
mref("args", "go", "here")
#-----------------------------

# @@PLEAC@@_11.9
#-----------------------------
record = {
    "name": "Jason",
    "empno": 132,
    "title": "deputy peon",
    "age": 23,
    "salary": 37000,
    "pals": ["Norbert", "Rhys", "Phineas"],
}
print "I am %s, and my pals are %s." % (record["name"],
                                        ", ".join(record["pals"]))
#-----------------------------
byname = {}
byname[record["name"]] = record

rp = byname.get("Aron")
if rp:
     print "Aron is employee %d."% rp["empno"]

byname["Jason"]["pals"].append("Theodore")
print "Jason now has %d pals." % len(byname["Jason"]["pals"])

for name, record in byname.items():
    print "%s is employee number %d." % (name, record["empno"])

employees = {}
employees[record["empno"]] = record;

# lookup by id
rp = employees.get(132)
if (rp):
    print "Employee number 132 is %s." % rp["name"]

byname["Jason"]["salary"] *= 1.035

peons = [r for r in employees.values() if r["title"] == "peon"]
tsevens = [r for r in employees.values() if r["age"] == 27]

# Go through all records
print employees.values()

for rp in sorted(employees.values(), key=lambda x:x["age"]):
    print "%s is age %d."%(rp["name"], rp["age"])

# use @byage, an array of arrays of records
byage = {}
byage[record["age"]] = byage.get(record["age"], []) + [record]

for age, records in byage.items():
    print records
    print "Age %s:"%age,
    for rp in records:
        print rp["name"],
    print
#-----------------------------

# @@PLEAC@@_11.10
#-----------------------------
FieldName: Value
#-----------------------------
for record in list_of_records:
    # Note: sorted added in Python 2.4
    for key in sorted(record.keys()):
        print "%s: %s" % (key, record[key])
    print
#-----------------------------
import re
list_of_records = [{}]
while True:
    line = sys.stdin.readline()
    if not line:
        # EOF
        break
    # Remove trailing \n:
    line = line[:1]
    if not line.strip():
        # New record
        list_of_records.append({})
        continue
    key, value = re.split(r':\s*', line, 1)
    # Assign the key/value to the last item in the list_of_records:
    list_of_records[-1][key] = value
#-----------------------------
# @@PLEAC@@_11.11
import pprint

mylist = [[1,2,3], [4, [5,6,7], 8,9, [0,3,5]], 7, 8]
mydict = {"abc": "def", "ghi":[1,2,3]}
pprint.pprint(mylist, width=1)

fmtdict = pprint.pformat(mydict, width=1)
print fmtdict
# "import pprint; help(pprint)" for more details

# @@INCOMPLETE@@
# Note that pprint does not currently handle user objects

#-----------------------------
# @@PLEAC@@_11.12
newlist = list(mylist) # shallow copy
newdict = dict(mydict) # shallow copy

# Pre 2.3:
import copy
newlist = copy.copy(mylist) # shallow copy
newdict = copy.copy(mydict) # shallow copy

# shallow copies copy a data structure, but don't copy the items in those
# data structures so if there are nested data structures, both copy and
# original will refer to the same object
mylist = ["1", "2", "3"]
newlist = list(mylist)
mylist[0] = "0"
print mylist, newlist
#=> ['0', '2', '3'] ['1', '2', '3']

mylist = [["1", "2", "3"], 4]
newlist = list(mylist)
mylist[0][0] = "0"
print mylist, newlist
#=> [['0', '2', '3'], 4] [['0', '2', '3'], 4]
#-----------------------------
import copy
newlist = copy.deepcopy(mylist) # deep copy
newdict = copy.deepcopy(mydict) # deep copy

# deep copies copy a data structure recursively:
import copy

mylist = [["1", "2", "3"], 4]
newlist = copy.deepcopy(mylist)
mylist[0][0] = "0"
print mylist, newlist
#=> [['0', '2', '3'], 4] [['1', '2', '3'], 4]
#-----------------------------
# @@PLEAC@@_11.13
import pickle
class Foo(object):
    def __init__(self):
        self.val = 1

x = Foo()
x.val = 3
p_x = pickle.dumps(x)  # Also pickle.dump(x, myfile) which writes to myfile
del x
x = pickle.loads(p_x)  # Also x = pickle.load(myfile) which loads from myfile
print x.val
#=> 3
#-----------------------------
# @@PLEAC@@_11.14
import os, shelve
fname = "testfile.db"
if not os.path.exists(fname):
    d = shelve.open("testfile.db")
    for i in range(100000):
        d[str(i)] = i
    d.close()

d = shelve.open("testfile.db")
print d["100"]
print d["1212010201"] # KeyError
#-----------------------------

# @@PLEAC@@_11.15
# bintree - binary tree demo program
# Use the heapq module instead?
import random
import warnings

class BTree(object):
    def __init__(self):
        self.value = None
    
    ### insert given value into proper point of
    ### the tree, extending this node if necessary.
    def insert(self, value):
        if self.value is None:
            self.left = BTree()
            self.right = BTree()
            self.value = value
        elif self.value > value:
            self.left.insert(value)
        elif self.value < value:
            self.right.insert(value)
        else:
            warnings.warn("Duplicate insertion of %s."%value)
            
    # recurse on left child, 
    # then show current value, 
    # then recurse on right child.
    def in_order(self):
       if self.value is not None:
           self.left.in_order()
           print self.value,
           self.right.in_order()

    # show current value, 
    # then recurse on left child, 
    # then recurse on right child.
    def pre_order(self):
        if self.value is not None:
            print self.value,
            self.left.pre_order()
            self.right.pre_order()
    
    # recurse on left child, 
    # then recurse on right child,
    # then show current value. 
    def post_order(self):
        if self.value is not None:
            self.left.post_order()
            self.right.post_order()
            print self.value,

    # find out whether provided value is in the tree.
    # if so, return the node at which the value was found.
    # cut down search time by only looking in the correct
    # branch, based on current value.
    def search(self, value):
        if self.value is not None:
            if self.value == value:
                return self
            if value < self.value:
                return self.left.search(value)
            else:
                return self.right.search(value)

def test():
    root = BTree()

    for i in range(20):
        root.insert(random.randint(1, 1000))

    # now dump out the tree all three ways
    print "Pre order: ", root.pre_order()
    print "In order:  ", root.in_order()
    print "Post order:", root.post_order()

    ### prompt until empty line
    while True:
        val = raw_input("Search? ").strip()
        if not val:
            break
        val = int(val)
        found = root.search(val)
        if found:
            print "Found %s at %s, %s"%(val, found, found.value)
        else:
            print "No %s in tree" % val
            
if __name__ == "__main__":
    test()


# ^^PLEAC^^_12.0
#-----------------------------
## Python's "module" is the closest equivalent to Perl's "package"


#=== In the file "Alpha.py"
name = "first"

#=== End of file

#=== In the file "Omega.py"

name = "last"
#=== End of file

import Alpha, Omega
print "Alpha is %s, Omega is %s." % (Alpha.name, Omega.name)
#> Alpha is first, Omega is last.
#-----------------------------
# Python does not have an equivalent to "compile-time load"
import sys

# Depending on the implementation, this could use a builtin
# module or load a file with the extension .py, .pyc, pyo, .pyd,
# .so, .dll, or (with imputils) load from other files.
import Cards.Poker

#-----------------------------
#=== In the file Cards/Poker.py
__all__ = ["card_deck", "shuffle"]  # not usually needed
card_deck = []
def shuffle():
    pass

#-----------------------------

# ^^PLEAC^^_12.1
#-----------------------------
#== In the file "YourModule.py"

__version__ = (1, 0)          # Or higher
__all__ = ["...", "..."]      # Override names included in "... import *"
                              #   Note: 'import *' is considered poor style
                              #   and it is rare to use this variable.
########################
# your code goes here
########################

#-----------------------------
import YourModule             # Import the module into my package
                              #  (does not import any of its symbols)

import YourModule as Module   # Use a different name for the module

from YourModule import *      # Import all module symbols not starting
                              #  with an underscore (default); if __all__
                              #  is defined, only imports those symbols.
                              # Using this is discouraged unless the 
                              #  module is specifically designed for it.

from YourModule import name1, name2, xxx
                              # Import the named symbols from the module

from YourModule import name1 as name2
                              # Import the named object, but use a
                              #  different name to access it locally.

#-----------------------------
__all__ = ["F1", "F2", "List"]
#-----------------------------
__all__ = ["Op_Func", "Table"]
#-----------------------------
from YourModule import Op_Func, Table, F1
#-----------------------------
from YourModule import Functions, Table
#-----------------------------

# ^^PLEAC^^_12.2
#-----------------------------
# no import
mod = "module"
try:
    __import__(mod)
except ImportError, err:
    raise ImportError("couldn't load %s: %s" % (mod, err))

# imports into current package
try:
    import module
except ImportError, err:
    raise ImportError("couldn't load 'module': %s" % (err, ))

# imports into current package, if the name is known
try:
    import module
except ImportError, err:
    raise ImportError("couldn't load 'module': %s" % (err, ))

# Use a fixed local name for a named module
mod = "module"
try:
    local_name = __import__(mod)
except ImportError, err:
    raise ImportError("couldn't load %s: %s" % (mod, err))

# Use the given name for the named module.
# (You probably don't need to do this.)
mod = "module"
try:
    globals()[mod] = __import__(mod)
except ImportError, err:
    raise ImportError("couldn't load %s: %s" % (mod, err))

#-----------------------------
DBs = "Giant.Eenie Giant.Meanie Mouse.Mynie Moe".split()
for mod in DBs.split():
    try:
        loaded_module = __import__(mod)
    except ImportError:
        continue
    # __import__ returns a reference to the top-most module
    # Need to get the actual submodule requested.
    for term in mod.split(".")[:-1]:
        loaded_module = getattr(loaded_module, term)
    break
else:
    raise ImportError("None of %s loaded" % DBs)
#-----------------------------

# ^^PLEAC^^_12.3
#-----------------------------
import sys
if __name__ == "__main__":
    if len(sys.argv) != 3 or not sys.argv[1].isdigit() \
                          or not sys.argv[2].isdigit():
        raise SystemExit("usage: %s num1 num2" % sys.argv[0])

import Some.Module
import More.Modules
#-----------------------------
if opt_b:
    import math
#-----------------------------
from os import O_EXCL, O_CREAT, O_RDWR

#-----------------------------
import os
O_EXCL = os.O_EXCL
O_CREAT = os.O_CREAT
O_RDWR = os.O_RDWR
#-----------------------------
import os
O_EXCL, O_CREAT, O_RDWR = os.O_EXCL, os.O_CREAT, os.O_RDWR
#-----------------------------
load_module('os', "O_EXCL O_CREAT O_RDWR".split())

def load_module(module_name, symbols):
    module = __import__(module_name)
    for symbol in symbols:
        globals()[symbol] = getattr(module, symbol)
#-----------------------------

# ^^PLEAC^^_12.4
#-----------------------------
# Python doesn't have Perl-style packages

# Flipper.py
__version__ = (1, 0)

__all__ = ["flip_boundary", "flip_words"]

Separatrix = ' '  # default to blank

def flip_boundary(sep = None):
    prev_sep = Separatrix
    if sep is not None:
        global Separatrix
        Separatrix = sep
    return prev_sep

def flip_words(line):
    words = line.split(Separatrix)
    words.reverse()
    return Separatrix.join(words)
#-----------------------------

# ^^PLEAC^^_12.5
#-----------------------------
this_pack = __name__
#-----------------------------
that_pack = sys._getframe(1).f_globals.get("__name__", "<string>")
#-----------------------------
print "I am in package", __name__
#-----------------------------
def nreadline(count, myfile):
    if count <= 0:
        raise ValueError("Count must be > 0")
    return [myfile.readline() for i in range(count)]

def main():
    myfile = open("/etc/termcap")
    a, b, c = nreadline(3, myfile)
    myfile.close()

if __name__ == "__main__":
    main()

# DON'T DO THIS:
import sys

def nreadline(count, handle_name):
    assert count > 0, "count must be > 0"
    locals = sys._getframe(1).f_locals
    if not locals.has_key(handle_name):
        raise AssertionError("need open filehandle")
    infile = locals[handle_name]
    retlist = []
    for line in infile:
        retlist.append(line)
        count -= 1
        if count == 0:
            break
    return retlist

def main():
    FH = open("/etc/termcap")
    a, b, c = nreadline(3, "FH")

if __name__ == "__main__":
    main()
#-----------------------------

# ^^PLEAC^^_12.6
#-----------------------------
## There is no direct equivalent in Python to an END block
import time, os, sys

# Tricks to ensure the needed functions exist during module cleanup
def _getgmtime(asctime=time.asctime, gmtime=time.gmtime,
               t=time.time):
    return asctime(gmtime(t()))

class Logfile:
    def __init__(self, file):
        self.file = file

    def _logmsg(self, msg, argv0=sys.argv[0], pid=os.getpid(),
                _getgmtime=_getgmtime):
        # more tricks to keep all needed references
        now = _getgmtime()
        print>>self.file, argv0, pid, now + ":", msg

    def logmsg(self, msg):
        self._logmsg(self.file, msg)

    def __del__(self):
        self._logmsg("shutdown")
        self.file.close()

    def __getattr__(self, attr):
        # forward everything else to the file handle
        return getattr(self.file, attr)

# 0 means unbuffered
LF = Logfile(open("/tmp/mylog", "a+", 0))
logmsg = LF.logmsg

#-----------------------------
## It is more appropriate to use try/finally around the
## main code, so the order of initialization and finalization
## can be specified.
if __name__ == "__main__":
    import logger
    logger.init("/tmp/mylog")
    try:
        main()
    finally:
        logger.close()

#-----------------------------

# ^^PLEAC^^_12.7
#-----------------------------
#% python -c 'import sys\
for i, name in zip(xrange(sys.maxint), sys.path):\
    print i, repr(name)
#> 0 ''
#> 1 '/usr/lib/python2.2'
#> 2 '/usr/lib/python2.2/plat-linux2'
#> 3 '/usr/lib/python2.2/lib-tk'
#-----------------------------
# syntax for sh, bash, ksh, or zsh
#$ export PYTHONPATH=$HOME/pythonlib

# syntax for csh or tcsh
#% setenv PYTHONPATH ~/pythonlib
#-----------------------------
import sys
sys.path.insert(0, "/projects/spectre/lib")
#-----------------------------
import FindBin
sys.path.insert(0, FindBin.Bin)
#-----------------------------
import FindBin
Bin = "Name"
bin = getattr(FindBin, Bin)
sys.path.insert(0, bin + "/../lib")
#-----------------------------

# ^^PLEAC^^_12.8
#-----------------------------
#% h2xs -XA -n Planets
#% h2xs -XA -n Astronomy::Orbits
#-----------------------------
# @@INCOMPLETE@@
# @@INCOMPLETE@@
# Need a distutils example
#-----------------------------

# ^^PLEAC^^_12.9
#-----------------------------
# Python compiles a file to bytecode the first time it is imported and 
# stores this compiled form in a .pyc file.  There is thus less need for
# incremental compilation as once there is a .pyc file, the sourcecode
# is only recompiled if it is modified.  

# ^^PLEAC^^_12.10
#-----------------------------
# See previous section

# ^^PLEAC^^_12.11
#-----------------------------
## Any definition in a Python module overrides the builtin
## for that module

#=== In MyModule
def open():
    pass # TBA
#-----------------------------
from MyModule import open
file = open()
#-----------------------------

# ^^PLEAC^^_12.12
#-----------------------------
def even_only(n):
    if n & 1:     # one way to test
        raise AssertionError("%s is not even" % (n,))
    #....

#-----------------------------
def even_only(n):
    if n % 2:    # here's another
        # choice of exception depends on the problem
        raise TypeError("%s is not even" % (n,))
    #....

#-----------------------------
import warnings
def even_only(n):
    if n & 1:           # test whether odd number
        warnings.warn("%s is not even, continuing" % (n))
        n += 1
    #....
#-----------------------------
warnings.filterwarnings("ignore")
#-----------------------------

# ^^PLEAC^^_12.13
#-----------------------------
val = getattr(__import__(packname), varname)
vals =  getattr(__import__(packname), aryname)
getattr(__import__(packname), funcname)("args")

#-----------------------------
# DON'T DO THIS [Use math.log(val, base) instead]
import math
def make_log(n):
   def logn(val):
      return math.log(val, n)
   return logn

# Modifying the global dictionary - this could also be done
# using locals(), or someobject.__dict__
globaldict = globals()
for i in range(2, 1000):
    globaldict["log%s"%i] = make_log(i)

# DON'T DO THIS
for i in range(2,1000):
    exec "log%s = make_log(i)"%i in globals()
    
print log20(400)
#=>2.0
#-----------------------------
blue = colours.blue
someobject.blue = colours.azure  # someobject could be a module...
#-----------------------------

# ^^PLEAC^^_12.14
#-----------------------------
# Python extension modules can be imported and used just like
# a pure python module.
#
# See http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ for
# information on how to create extension modules in Pyrex [a
# language that's basically Python with type definitions which
# converts to compiled C code]
#
# See http://www.boost.org/libs/python/doc/ for information on how
# to create extension modules in C++.
#
# See http://www.swig.org/Doc1.3/Python.html for information on how
# to create extension modules in C/C++
#
# See http://docs.python.org/ext/ext.html for information on how to
# create extension modules in C/C++ (manual reference count management).
#
# See http://cens.ioc.ee/projects/f2py2e/ for information on how to
# create extension modules in Fortran
#
# See http://www.scipy.org/Weave for information on how to 
# include inline C code in Python code.
#
# @@INCOMPLETE@@ Need examples of FineTime extensions using the different methods...
#-----------------------------

# ^^PLEAC^^_12.15
#-----------------------------
# See previous section
#-----------------------------

# ^^PLEAC^^_12.16
#-----------------------------
# To document code, use docstrings. A docstring is a bare string that
# is placed at the beginning of a module or immediately after the 
# definition line of a class, method, or function. Normally, the
# first line is a brief description of the object; if a longer
# description is needed, it commences on the third line (the second
# line being left blank).  Multiline comments should use triple
# quoted strings.
# 
# Docstrings are automagically assigned to an object's __doc__ property.
#
# In other words these three classes are identical:
class Foo(object):
    "A class demonstrating docstrings."

class Foo(object):
    __doc__ = "A class demonstrating docstrings."

class Foo(object):
    pass
Foo.__doc__ = "A class demonstrating docstrings."

# as are these two functions:
def foo():
    "A function demonstrating docstrings."

def foo():
    pass
foo.__doc__ = "A function demonstrating docstrings."

# the pydoc module is used to display a range of information about 
# an object including its docstrings:
import pydoc 
print pydoc.getdoc(int)
pydoc.help(int)

# In the interactive interpreter, objects' documentation can be 
# using the help function:
help(int)

#-----------------------------

# ^^PLEAC^^_12.17
#-----------------------------
# Recent Python distributions are built and installed with disutils.
# 
# To build and install under unix
# 
# % python setup.py install
# 
# If you want to build under one login and install under another
# 
# % python setup.py build
# $ python setup.py install
# 
# A package may also be available prebuilt, eg, as an RPM or Windows
# installer.  Details will be specific to the operating system.

#-----------------------------
# % python setup.py --prefix ~/python-lib
#-----------------------------


# ^^PLEAC^^_12.18
#-----------------------------
#== File Some/Module.py

# There are so many differences between Python and Perl that
# it isn't worthwhile trying to come up with an equivalent to
# this Perl code.  The Python code is much smaller, and there's
# no need to have a template.

#-----------------------------

# ^^PLEAC^^_12.19
#-----------------------------
#% pmdesc
#-----------------------------
import sys, pydoc

def print_module_info(path, modname, desc):
   # Skip files starting with "test_"
   if modname.split(".")[-1].startswith("test_"):
       return
   try:
       # This assumes the modules are safe for importing,
       # in that they don't have side effects.  Could also
       # grep the file for the __version__ line.
       mod = pydoc.safeimport(modname)
   except pydoc.ErrorDuringImport:
       return
   version = getattr(mod, "__version__", "unknown")
   if isinstance(version, type("")):
       # Use the string if it's given
       pass
   else:
       # Assume it's a list of version numbers, from major to minor
       ".".join(map(str, version))
   synopsis, text = pydoc.splitdoc(desc)
   print "%s (%s) - %s" % (modname, version, synopsis)

scanner = pydoc.ModuleScanner()
scanner.run(print_module_info)

#-----------------------------


# ^^PLEAC^^_13.0
#-----------------------------
# Inside a module named 'Data' / file named 'Data.py'
class Encoder(object):
    pass
#-----------------------------
obj = [3, 5]
print type(obj), id(obj), ob[1]

## Changing the class of builtin types is not supported
## in Python.

#-----------------------------
obj.Stomach = "Empty"    # directly accessing an object's contents
obj.NAME = "Thag"        # uppercase field name to make it stand out
(optional)
#-----------------------------
encoded = object.encode("data")
#-----------------------------
encoded = Data.Encoder.encode("data")
#-----------------------------
class Class(object):
    def __init__(self):
        pass
#-----------------------------
object = Class()
#-----------------------------
class Class(object):
    def class_only_method():
        pass # more code here
    class_only_method = staticmethod(class_only_method)

#-----------------------------
class Class(object):
    def instance_only_method(self):
        pass # more code here
#-----------------------------
lector = Human.Cannibal()
lector.feed("Zak")
lector.move("New York")
#-----------------------------
# NOTE: it is rare to use these forms except inside of
# methods to call specific methods from a parent class
lector = Human.Cannibal()
Human.Cannibal.feed(lector, "Zak")
Human.Cannibal.move(lector, "New York")
#-----------------------------
print>>sys.stderr, "stuff here\n"

# ^^PLEAC^^_13.1
#-----------------------------
class Class(object):
    pass
#-----------------------------
import time
class Class(object):
    def __init__(self):
        self.start = time.time()  # init data fields
        self.age = 0
#-----------------------------
import time
class Class(object):
    def __init__(self, **kwargs):
        # Sets self.start to the current time, and self.age to 0.  If called
        # with arguments, interpret them as key+value pairs to
        # initialize the object with
        self.age = 0
        self.__dict__.update(kwargs)
#-----------------------------

# ^^PLEAC^^_13.2
#-----------------------------
import time
class Class(object):
    def __del__(self):
        print self, "dying at", time.ctime()
#-----------------------------
## Why is the perl code introducing a cycle?  I guess it's an
## example of how to keep from calling the finalizer
self.WHATEVER = self
#-----------------------------

# ^^PLEAC^^_13.3
#-----------------------------
# It is standard practice to access attributes directly:
class MyClass(object)
    def __init__(self):
        self.name = "default"
        self.age = 0
obj = MyClass()
obj.name = "bob"
print obj.name
obj.age += 1

# If you later find that you need to compute an attribute, you can always 
# retrofit a property(), leaving user code untouched:
class MyClass(object):
    def __init__(self):
        self._name = "default"
        self._age = 0

    def get_name(self):
        return self._name
    def set_name(self, name):
        self._name = name.title()
    name = property(get_name, set_name)

    def get_age(self):
        return self._age
    def set_age(self, val):
        if val < 0:
            raise ValueError("Invalid age: %s" % val)
        self._age = val
    age = property(get_age, set_age)
obj = MyClass()
obj.name = "bob"
print obj.name
obj.age += 1

# DON'T DO THIS - explicit getters and setters should not be used:
class MyClass(object):
    def __init__(self):
        self.name = "default"
    def get_name(self):
        return self.name
    def set_name(self, name):
        self.name = name.title()
obj = MyClass()
obj.set_name("bob")
print obj.get_name()
#-----------------------------
## DON'T DO THIS (It's complex, ugly, and unnecessary):
class MyClass(object):
    def __init__(self):
        self.age = 0
    def name(self, *args):
        if len(args) == 0:
            return self.name
        elif len(args) == 1:
            self.name = args[0]
        else:
            raise TypeError("name only takes 0 or 1 arguments")
    def age(self, *args):
        prev = self.age
        if args:
            self.age = args[0]
        return prev

# sample call of get and set: happy birthday!
obj.age(1 + obj.age())

#-----------------------------
him = Person()
him.NAME = "Sylvester"
him.AGE = 23
#-----------------------------
# Here's another way to implement the 'obj.method()' is a getter
# and 'obj.method(value)' is a settor.  Again, this is not a
# common Python idiom and should not be used.  See below for a
# more common way to do parameter checking of attribute assignment.

import re, sys

def carp(s):
    sys.stderr.write("WARNING: " + s + "\n")

class Class:
    no_name = []

    def name(self, value = no_name):
        if value is Class.no_name:
            return self.NAME
        value = self._enforce_name_value(value)
        self.NAME = value

    def _enforce_name_value(self, value):
        if re.search(r"[^\s\w'-]", value):
            carp("funny characters in name")
        if re.search(r"\d", value):
            carp("numbers in name")
        if not re.search(r"\S+(\s+\S+)+", value):
            carp("prefer multiword name")
        if not re.search(r"\S", value):
            carp("name is blank")
        return value.upper()   # enforce capitalization
#-----------------------------
# A more typical way to enforce restrictions on a value
# to set
class Class:
    def __setattr__(self, name, value):
        if name == "name":
            value = self._enforce_name_value(value)  # Do any conversions
        self.__dict__[name] = value  # Do the default __setattr__ action

    def _enforce_name_value(self, value):
        if re.search(r"[^\s\w'-]", value):
            carp("funny characters in name")
        if re.search(r"\d", value):
            carp("numbers in name")
        if not re.search(r"\S+(\s+\S+)+", value):
            carp("prefer multiword name")
        if not re.search(r"\S", value):
            carp("name is blank")
        return value.upper()   # enforce capitalization

#-----------------------------
class Person:
    def __init__(self, name = None, age = None, peers = None):
        if peers is None: peers = []  # See Python FAQ 6.25
        self.name = name
        self.age = age
        self.peers = peers

    def exclaim(self):
        return "Hi, I'm %s, age %d, working with %s" % \
            (self.name, self.age, ", ".join(self.peers))

    def happy_birthday(self):
        self.age += 1
        return self.age
#-----------------------------

# ^^PLEAC^^_13.4
#-----------------------------
## In the module named 'Person' ...
def population():
    return Person.body_count[0]

class Person(object):
    body_count = [0]        # class variable - shared across all instances

    def __init__(self):
        self.body_count[0] += 1

    def __del__(self):      # Beware - may be non-deterministic (Jython)!
        self.body_count[0] -= 1

# later, the user can say this:
import Person
people = []
for i in range(10):
    people.append(Person.Person())
print "There are", Person.population(), "people alive."

#=> There are 10 people alive.
#-----------------------------
him = Person()
him.gender = "male"

her = Person()
her.gender = "female"

#-----------------------------
FixedArray.max_bounds = 100                # set for whole class
alpha = FixedArray.FixedArray()
print "Bound on alpha is", alpha.max_bounds
#=>100

beta = FixedArray.FixedArray()
beta.max_bounds = 50                      # still sets for whole class
print "Bound on alpha is", alpha.max_bounds
#=>50
#-----------------------------
# In the module named 'FixedArray'

class FixedArray(object):
    _max_bounds = [7]        # Shared across whole class
    
    def __init__(self, bounds=None):
        if bounds is not None:
            self.max_bounds = bounds

    def get_max_bounds(self):
        return self._max_bounds[0]
    def set_max_bounds(self, val):
        self._max_bounds[0] = val
    max_bounds = property(get_max_bounds, set_max_bounds)
#-----------------------------

# ^^PLEAC^^_13.5
#-----------------------------
# There isn't the severe separation between scalar, arrays and hashs
# in Python, so there isn't a direct equivalent to the Perl code.
class Person:
    def __init__(self, name=None, age=None, peers=None):
        if peers is None: 
            peers = []
        self.name = name
        self.age = age
        self.peers = peers

p = Person("Jason Smythe", 13, ["Wilbur", "Ralph", "Fred"])

# or this way.  (This is not the prefered style as objects should
# be constructed with all the appropriate data, if possible.)

p = Person()  # allocate an empty Person
p.name = "Jason Smythe"                         # set its name field
p.age = 13                                      # set its age field
p.peers.extend( ["Wilbur", "Ralph", "Fred" ] )  # set its peers field

p.peers = ["Wilbur", "Ralph", "Fred"]

p.peers[:]= ["Wilbur", "Ralph", "Fred"]

# fetch various values, including the zeroth friend
print "At age %d, %s's first friend is %s." % \
    (p.age, p.name, p.peers[0])
#-----------------------------
# This isn't very Pythonic - should create objects with the
# needed data, and not depend on defaults and modifing the object.
import sys
def carp(s):
    sys.stderr.write("WARNING: " + s + "\n")

class Person:
    def __init__(self, name = "", age = 0):
        self.name = name
        self.age = age
    def __setattr__(self, name, value):
        if name == "age":
            # This is very unpythonic
            if not isinstance(value, type(0)):
                carp("age '%s' isn't numeric" % (value,))
            if value > 150: carp("age '%s' is unreasonable" % (value,))
        self.__dict__[name] = value

class Family:
    def __init__(self, head = None, address = "", members = None):
        if members is None: members = []
        self.head = head or Person()
        self.address = address
        self.members = members

folks = Family()

dad = folks.head
dad.name = "John"
dad.age = 34

print "%s's age is %d" % (folks.head.name, folks.head.age)
#-----------------------------
class Card:
    def __init__(self, name=None, color=None, cost=None,
                 type=None, release=None, text=None):
        self.name = name
        self.color = color
        self.cost = cost
        self.type = type
        self.release = release
        self.type = type
#-----------------------------
# For positional args
class Card:
    _names = ("name", "color", "cost", "type", "release", "type")
    def __init__(self, *args):
        assert len(args) <= len(self._names)
        for k, v in zip(self._names, args):
            setattr(self, k, None)
#-----------------------------
# For keyword args
class Card:
    _names = ("name", "color", "cost", "type", "release", "type")
    def __init__(self, **kwargs):
        for k in self._names:  # Set the defaults
            setattr(self, k, None)
        for k, v in kwargs.items():  # add in the kwargs
            assert k in self._names, "Unexpected kwarg: " + k
            setattr(self, k, v)
#-----------------------------
class hostent:
    def __init__(self, addr_list = None, length = None,
                 addrtype = None, aliases = None, name = None):
        self.addr_list = addr_list or []
        self.length = length or 0
        self.addrtype = addrtype or ""
        self.aliases = aliases or []
        self.name = name or ""
#-----------------------------
## XXX What do I do with these?
#define h_type h_addrtype
#define h_addr h_addr_list[0]
#-----------------------------
# make (hostent object)->type() same as (hostent object)->addrtype()
#
# *hostent::type = \&hostent::addrtype;
#
# # make (hostenv object)->
# addr()
#  same as (hostenv object)->addr_list(0)
#sub hostent::addr { shift->addr_list(0,@_) }
#-----------------------------
# No equivalent to Net::hostent (Python uses an unnamed tuple)
#package Extra::hostent;
#use Net::hostent;
#@ISA = qw(hostent);
#sub addr { shift->addr_list(0,@_) }
#1;
#-----------------------------

# ^^PLEAC^^_13.6
#-----------------------------
class Class(Parent):
    pass
#-----------------------------
## Note: this is unusual in Python code
ob1 = SomeClass()
# later on
ob2 = ob1.__class__()
#-----------------------------
## Note: this is unusual in Python code
ob1 = Widget()
ob2 = ob1.__class__()
#-----------------------------
# XXX I do not know the intent of the original Perl code
# Do not use this style of programming in Python.
import time
class Person(possible,base,classes):
    def __init__(self, *args, **kwargs):
        # Call the parents' constructors, if there are any
        for baseclass in self.__class__.__bases__:
            init = getattr(baseclass, "__init__")
            if init is not None:
                init(self, *args, **kwargs)
        self.PARENT = parent      # init data fields
        self.START = time.time()
        self.AGE = 0
#-----------------------------

# ^^PLEAC^^_13.7
#-----------------------------
methname = "flicker"
getattr(obj, methname)(10)    # calls obj->flicker(10);

# call three methods on the object, by name
for m in ("start", "run", "stop"):
    getattr(obj, m)()
#-----------------------------
methods = ("name", "rank", "serno")
his_info = {}
for m in methods:
   his_info[m] = getattr(ob, m)()

# same as this:

his_info = {
    'name': ob.name(),
    'rank': ob.rank(),
    'serno': ob.serno(),
}
#-----------------------------
fnref = ob.method
#-----------------------------
fnref(10, "fred")
#-----------------------------
obj.method(10, "fred")
#-----------------------------
# XXX Not sure if this is the correct translation.
# XXX Is 'can' special?
if isinstance(obj_target, obj.__class__):
    obj.can('method_name')(obj_target, *arguments)
#-----------------------------

# ^^PLEAC^^_13.8
#-----------------------------
isinstance(obj, mimetools.Message)
issubclass(obj.__class__, mimetools.Message)

if hasattr(obj, "method_name"):  # check method validity
    pass
#-----------------------------
## Explicit type checking is needed fewer times than you think.
his_print_method = getattr(obj, "as_string", None)
#-----------------------------
__version__ = (3, 0)
Some_Module.__version__

# Almost never used, and doesn't work for builtin types, which don't
# have a __module__.

his_vers = obj.__module__.__version__
#-----------------------------
if Some_Module.__version__ < (3, 0):
  raise ImportError("Some_Module version %s is too old, expected (3, 0)" %
                    (Some_Module.__version__,))
# or more simply
assert Some_Module.__version__ >= (3, 0), "version too old"

#-----------------------------
__VERSION__ = '1.01'
#-----------------------------

# ^^PLEAC^^_13.9
#-----------------------------
# Note: This uses the standard Python idiom of accessing the
# attributes directly rather than going through a method call.
# See earlier in this chapter for examples of how this does
# not break encapsulation.
class Person:
    def __init__(self, name = "", age = 0):
        self.name = name
        self.age = age
#-----------------------------
# Prefered: dude = Person("Jason", 23)
dude = Person()
dude.name = "Jason"
dude.age = 23
print "%s is age %d." % (dude.name, dude.age)
#-----------------------------
class Employee(Person):
    pass
#-----------------------------
# Prefered: empl = Employee("Jason", 23)
emp = Employee()
empl.name = "Jason"
empl.age = 23
print "%s is age %d." % (empl.name, empl.age)
#-----------------------------

# ^^PLEAC^^_13.10
#-----------------------------
# This doesn't need to be done since if 'method' doesn't
# exist in the Class it will be looked for in its BaseClass(es)
class Class(BaseClass):
    def method(self, *args, **kwargs):
        BaseClass.method(self, *args, **kwargs)

# This lets you pick the specific method in one of the base classes
class Class(BaseClass1, BaseClass2):
    def method(self, *args, **kwargs):
        BaseClass2.method(self, *args, **kwargs)

# This looks for the first method in the base class(es) without
# specifically knowing which base class.  This reimplements
# the default action so isn't really needed.
class Class(BaseClass1, BaseClass2, BaseClass3):
    def method(self, *args, **kwargs):
        for baseclass in self.__class__.__bases__:
            f = getattr(baseclass, "method")
            if f is not None:
                return f(*args, **kwargs)
        raise NotImplementedError("method")

#-----------------------------
self.meth()   # Call wherever first meth is found

Where.meth(self)  # Call in the base class "Where"

# XXX Does Perl only have single inheritence?  Or does
# it check all base classes?  No directly equivalent way
# to do this in Python, but see above.
#-----------------------------
import time

# The Perl code calls a private '_init' function, but in
# Python there's need for the complexity of 'new' mechanism
# so it's best just to put the '_init' code in '__init__'.
class Class:
    def __init__(self, *args):
        # init data fields
        self.START = time.time()
        self.AGE = 0
        self.EXTRA = args          # anything extra
#-----------------------------
obj = Widget(haircolor = "red", freckles = 121)
#-----------------------------
class Class(Base1, Base2, Base3):
    def __init__(self, *args, **kwargs):
        for base in self.__class__.__bases__:
            f = getattr(base, "__init__")
            if f is not None:
                f(self, *args, **kwargs)
#-----------------------------

# ^^PLEAC^^_13.11
#-----------------------------
# NOTE: Python prefers direct attribute lookup rather than
# method calls.  Python 2.2 will introduce a 'get_set' which
# *may* be equivalent, but I don't know enough about it.  So
# instead I'll describe a class that lets you restrict access
# to only specific attributes.

class Private:
    def __init__(self, names):
        self.__names = names
        self.__data = {}
    def __getattr__(self, name):
        if name in self.__names:
            return self.__data[name]
        raise AttributeError(name)
    def __setattr__(self, name, value):
        if name.startswith("_Private"):
            self.__dict__[name] = value
            return
        if name in self.__names:
            self.__data[name] = value
            return
        raise TypeError("cannot set the attribute %r" % (name,))

class Person(Private):
    def __init__(self, parent = None):
        Private.__init__(self, ["name", "age", "peers", "parent"])
        self.parent = parent
    def new_child(self):
        return Person(self)
#-----------------------------
dad = Person()
dad.name = "Jason"
dad.age = 23
kid = dad.new_child()
kid.name = "Rachel"
kid.age = 2
print "Kid's parent is", kid.parent.name
#=>Kid's parent is Jason

# ^^PLEAC^^_13.12
#-----------------------------
## XXX No clue on what this does.  For that matter, what's
## "The Data Inheritance Problem"?

# ^^PLEAC^^_13.13
#-----------------------------
node.NEXT = node
#-----------------------------
# This is not a faithful copy of the Perl code, but it does
# show how to have the container's __del__ remove cycles in
# its contents.  Note that Python 2.0 includes a garbage
# collector that is able to remove these sorts of cycles, but
# it's still best to prevent cycles in your code.
class Node:
    def __init__(self, value = None):
        self.next = self
        self.prev = self
        self.value = value

class Ring:
    def __init__(self):
        self.ring = None
        self.count = 0

    def __str__(self):
        # Helpful when debugging, to print the contents of the ring
        s = "#%d: " % self.count
        x = self.ring
        if x is None:
            return s
        values = []
        while True:
            values.append(x.value)
            x = x.next
            if x is self.ring:
                break
        return s + " -> ".join(map(str, values)) + " ->"

    def search(self, value):
        node = self.ring
        while True:
            if node.value == value:
                return node
            node = node.next
            if node is self.ring:
                break

    def insert_value(self, value):
        node = Node(value)
        if self.ring is not None:
            node.prev, node.next = self.ring.prev, self.ring
            self.ring.prev.next = self.ring.prev = node
        self.ring = node
        self.count += 1

    def delete_value(self, value):
        node = self.search(value)
        if node is not None:
            self.delete_node(node)

    def delete_node(self, node):
        if node is node.next:
            node.next = node.prev = None
            self.ring = None
        else:
            node.prev.next, node.next.prev = node.next, node.prev
            if node is self.ring:
                self.ring = node.next
        self.count -= 1

    def __del__(self):
        while self.ring is not None:
            self.delete_node(self.ring)

COUNT = 1000
for rep in range(20):
    r = Ring()
    for i in range(COUNT):
        r.insert_value(i)
#-----------------------------

# ^^PLEAC^^_13.14
#-----------------------------
import UserString
class MyString(UserString.UserString):
    def __cmp__(self, other):
        return cmp(self.data.upper(), other.upper())

class Person:
    def __init__(self, name, idnum):
        self.name = name
        self.idnum = idnum
    def __str__(self):
        return "%s (%05d)" % (self.name.lower().capitalize(), self.idnum)

#-----------------------------
class TimeNumber:
    def __init__(self, hours, minutes, seconds):
        assert minutes < 60 and seconds < 60
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
    def __str__(self):
        return "%d:%02d:%02d" % (self.hours, self.minutes, self.seconds)
    def __add__(self, other):
        seconds = self.seconds + other.seconds
        minutes = self.minutes + other.minutes
        hours = self.hours + other.hours
        if seconds >= 60:
            seconds %= 60
            minutes += 1
        if minutes >= 60:
            minutes %= 60
            hours += 1
        return TimeNumber(hours, minutes, seconds)

    def __sub__(self, other):
        raise NotImplementedError

    def __mul__(self, other):
        raise NotImplementedError

    def __div__(self, other):
        raise NotImplementedError

t1 = TimeNumber(0, 58, 59)
sec = TimeNumber(0, 0, 1)
min = TimeNumber(0, 1, 0)
print t1 + sec + min + min
# 1:01:00

#-----------------------------
# For demo purposes only - the StrNum class is superfluous in this
# case as plain strings would give the same result.
class StrNum:
    def __init__(self, value):
        self.value = value

    def __cmp__(self, other):  # both <=> and cmp
        # providing <=> gives us <, ==, etc. for free.
        # __lt__, __eq__, and __gt__ can also be individually specified
        return cmp(self.value, other.value)

    def __str__(self):  # ""
        return self.value

    def __nonzero__(self, other):   # bool
        return bool(self.value)

    def __int__(self, other):   # 0+
        return int(self.value)

    def __add__(self, other):   # +
        return StrNum(self.value + other.value)

    def __radd__(self, other):   # +, inverted
        return StrNum(other.value + self.value)

    def __mul__(self, other):   # *
        return StrNum(self.value * other)

    def __rmul__(self, other):   # *, inverted
        return StrNum(self.value * other)


def demo():
    # show_strnum - demo operator overloading
    x = StrNum("Red")
    y = StrNum("Black")
    z = x + y
    r = z * 3
    print "values are %s, %s, %s, and %s" % (x, y, z, r)
    if x < y:
        s = "LT"
    else:
        s = "GE"
    print x, "is", s, y

if __name__ == "__main__":
    demo()
# values are Red, Black, RedBlack, and RedBlackRedBlackRedBlack
# Red is GE Black

#-----------------------------
#!/usr/bin/env python
# demo_fixnum - show operator overloading

# sum of STRFixNum: 40 and STRFixNum: 12 is STRFixNum: 52
# product of STRFixNum: 40 and STRFixNum: 12 is STRFixNum: 480
# STRFixNum: 3 has 0 places
# div of STRFixNum: 40 by STRFixNum: 12 is STRFixNum: 3.33
# square of that is  STRFixNum: 11.11

# This isn't excatly the same as the original Perl code since
# I couldn't figure out why the PLACES variable was used.
#-----------------------------
import re
_places_re = re.compile(r"\.(\d+)")

default_places = 0

class FixNum:
    def __init__(self, value, places = None):
        self.value = value
        if places is None:
            # get from the value
            m = _places_re.search(str(value))
            if m:
                places = int(m.group(1))
            else:
                places = default_places
        self.places = places

    def __add__(self, other):
        return FixNum(self.value + other.value,
                      max(self.places, other.places))

    def __mul__(self, other):
        return FixNum(self.value * other.value,
                      max(self.places, other.places))

    def __div__(self, other):
        # Force to use floating point, since 2/3 in Python is 0
        # Don't use float() since that will convert strings
        return FixNum((self.value+0.0) / other.value,
                      max(self.places, other.places))

    def __str__(self):
        return "STR%s: %.*f" % (self.__class__.__name__,
                                self.places, self.value)
    def __int__(self):
        return int(self.value)

    def __float__(self):
        return self.value

def demo():
    x = FixNum(40)
    y = FixNum(12, 0)

    print "sum of", x, "and", y, "is", x+y
    print "product of", x, "and", y, "is", x*y

    z = x/y
    print "%s has %d places" % (z, z.places)
    if not z.places:
        z.places = 2

    print "div of", x, "by", y, "is", z
    print "square of that is ", z*z

if __name__ == "__main__":
    demo()


# ^^PLEAC^^_13.15
# You can't tie a variable, but you can use properties.  
import itertools
class ValueRing(object):
    def __init__(self, colours):
        self.colourcycle = itertools.cycle(colours)

    def next_colour(self):
        return self.colourcycle.next()
    colour = property(next_colour)
vr = ValueRing(["red", "blue"])
for i in range(6):
    print vr.colour,
print

# Note that you MUST refer directly to the property
x = vr.colour
print x, x, x
#-------------------------------------
# Ties are generally unnecessary in Python because of its strong OO support -
# The resulting code is MUCH shorter:
class AppendDict(dict):
    def __setitem__(self, key, val):
        if key in self:
            self[key].append(val)
        else:
            super(AppendDict, self).__setitem__(key, [val])
tab = AppendDict()
tab["beer"] = "guinness"
tab["food"] = "potatoes"
tab["food"] = "peas"

for key, val in tab.items():
    print key, "=>", val
#-------------------------------------
class CaselessDict(dict):
    def __setitem__(self, key, val):
        super(CaselessDict, self).__setitem__(key.lower(), val)
    def __getitem__(self, key):
        return super(CaselessDict, self).__getitem__(key.lower())

tab = CaselessDict()
tab["VILLAIN"] = "big "
tab["herOine"] = "red riding hood"
tab["villain"] = "bad wolf"

for key, val in tab.items():
    print key, "is", val
#=>villain is bad wolf
#=>heroine is red riding hood
#-------------------------------------
class RevDict(dict):
    def __setitem__(self, key, val):
        super(RevDict, self).__setitem__(key, val)
        super(RevDict, self).__setitem__(val, key)

tab = RevDict()
tab["red"] = "rojo"
tab["blue"] = "azul"
tab["green"] = "verde"
tab["evil"] = ("No Way!", "Way!")

for key, val in tab.items():
    print key, "is", val
#=>blue is azul
#=>('No Way!', 'Way!') is evil
#=>rojo is red
#=>evil is ('No Way!', 'Way!')
#=>azul is blue
#=>verde is green
#=>green is verde
#=>red is rojo
#-------------------------------------
import itertools
for elem in itertools.count():
    print "Got", elem
#-------------------------------------
# You could use FileDispatcher from section 7.18
tee = FileDispatcher(sys.stderr, sys.stdout)
#-------------------------------------
# @@PLEAC@@_14.0

# See http://www.python.org/doc/topics/database/ for Database Interfaces details.
# currently listed on http://www.python.org/doc/topics/database/modules/
#
#  DB/2, Informix, Interbase, Ingres, JDBC, MySQL, pyodbc, mxODBC, ODBC Interface,
#  DCOracle, DCOracle2, PyGresQL, psycopg, PySQLite, sapdbapi, Sybase, ThinkSQL.
#

# @@PLEAC@@_14.1
#-------------------------------------
import anydbm
filename = "test.db"
try:
    db = anydbm.open(filename)
except anydbm, err:
    print "Can't open %s: %s!" % (filename, err)

db["key"] = "value"        # put value into database
if "key" in db:            # check whether in database
    val = db.pop("key")    # retrieve and remove from database
db.close()                 # close the database
#-------------------------------------
# download the following standalone program
#!/usr/bin/python
# userstats - generates statistics on who logged in.
# call with an argument to display totals

import sys, os, anydbm, re

db_file = '/tmp/userstats.db'       # where data is kept between runs

try:
    db = anydbm.open(db_file,'c')   # open, create if it does not exist
except:
    print "Can't open db %s: %s!" % (db_file, sys.exc_info()[1])
    sys.exit(1)

if len(sys.argv) > 1:
    if sys.argv[1] == 'ALL':
        userlist = db.keys()
    else:
        userlist = sys.argv[1:]
    userlist.sort()
    for user in userlist:
        if db.has_key(user):
            print "%s\t%s" % (user, db[user])
        else:
            print "%s\t%s" % (user, 0)
else:
    who = os.popen('who').readlines()  # run who(1)
    if len(who)<1:
        print "error running who"       # exit
        sys.exit(1)
    # extract username (first thin on the line) and update
    user_re = re.compile("^(\S+)")
    for line in who:
        fnd = user_re.search(line)
        if not fnd:
            print "Bad line from who: %s" % line
            sys.exit(1)
        user = fnd.groups()[0]
        if not db.has_key(user):
            db[user] = "0"
        db[user] = str(int(db[user])+1) # only strings are allowed
db.close()
    



# @@PLEAC@@_14.2
# Emptying a DBM File

import anydbm

try:
    db = anydbm.open(FILENAME,'w')   # open, for writing
except anydbm.error, err:
    print "Can't open db %s: %s!" % (filename, err)
    raise SystemExit(1)

db.clear()
db.close()
# -------------------------------
try:
    db = anydbm.open(filename,'n')   # open, always create a new empty db
except anydbm.error, err:
    print "Can't open db %s: %s!" % (filename, err)
    raise SystemExit(1)

db.close()
# -------------------------------
import os
try:
    os.remove(FILENAME)
except OSError, err:
    print "Couldn't remove %s to empty the database: %s!" % (FILENAME,
        err)
    raise SystemExit

try:
    db = anydbm.open(FILENAME,'n')   # open, flways create a new empty db
except anydbm.error, err:
    print "Couldn't create %s database: %s!" % (FILENAME, err)
    raise SystemExit

# @@PLEAC@@_14.3
# Converting Between DBM Files

# download the following standalone program
#!/usr/bin/python
# db2gdbm: converts DB to GDBM

import sys
import dbm, gdbm

if len(sys.argv)<3:
    print "usage: db2gdbm infile outfile"
    sys.exit(1)

(infile, outfile) = sys.argv[1:]

# open the files
try:
    db_in = dbm.open(infile)
except:
    print "Can't open infile %s: %s!" % (infile, sys.exc_info()[1])
    sys.exit(1)
try:
    db_out = dbm.open(outfile,"n")
except:
    print "Can't open outfile %s: %s!" % (outfile, sys.exc_info()[1])
    sys.exit(1)

# copy (don't use db_out = db_in because it's slow on big databases)
# is this also so for python ?
for k in db_in.keys():
    db_out[k] = db_in[k]

# these close happen automatically at program exit
db_out.close()
db_in.close()



# @@PLEAC@@_14.4

OUTPUT.update(INPUT1)
OUTPUT.update(INPUT2)

OUTPUT = anydbm.open("OUT","n")
for INPUT in (INPUT1, INPUT2, INPUT1):
    for key, value in INPUT.iteritems():
        if OUTPUT.has_key(key):
            # decide which value to use and set OUTPUT[key] if necessary
            print "key %s already present: %s, new: %s" % (
                    key, OUTPUT[key], value )
        else:
            OUTPUT[key] = value

# @@PLEAC@@_14.5
# On systems where the Berkeley DB supports it, dbhash takes an
# "l" flag:
import dbhash
dbhash.open("mydb.db", "cl") # 'c': create if doesn't exist

# @@INCOMPLETE@@

# @@PLEAC@@_14.6
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_14.7
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_14.8
# shelve uses anydbm to access and chooses between DBMs.
# anydbm detect file formats automatically.
import shelve
db = shelve.open("celebrities.db")

name1 = "Greg Stein"
name2 = "Greg Ward"

# shelve uses pickle to convert objects into strings and back.
# This is automatic.
db[name1] = ["of ViewCVS fame", "gstein@lyra.org"]
db[name2] = ["of Distutils fame", "gward@python.net"]

greg1 = db[name1]
greg2 = db[name2]

print "Two Gregs: %x %x" % (id(greg1), id(greg2))

if greg1 == greg2:
    print "You're having runtime fun with one Greg made two."
else:
    print "No two Gregs are ever alike."

# Changes to mutable entries are not written back by default.
# You can get the copy, change it, and put it back.
entry = db[name1]
entry[0] = "of Subversion fame"
db[name1] = entry

# Or you can open shelve with writeback option. Then you can
# change mutable entries directly. (New in 2.3)
db = shelve.open("celebrities.db", writeback=True)
db[name2][0] = "of Optik fame"

# However, writeback option can consume vast amounts of memory
# to do its magic. You can clear cache with sync().
db.sync()
#-----------------------------

# @@PLEAC@@_14.9
# DON'T DO THIS.
import os as _os, shelve as _shelve

_fname = "persist.db"
if not _os.path.exists(_fname):
    var1 = "foo"
    var2 = "bar"
_d = _shelve.open("persist.db")
globals().update(_d)

print "var1 is %s; var2 is %s"%(var1, var2)
var1 = raw_input("New var1: ")
var2 = raw_input("New var2: ")

for key, val in globals().items():
    if not key.startswith("_"):
        _d[key] = val
# @@INCOMPLETE@@

# @@PLEAC@@_14.10
#-----------------------------
import dbmodule

dbconn = dbmodule.connect(arguments...)

cursor = dbconn.cursor()
cursor.execute(sql)

while True:
   row = cursor.fetchone()
   if row is None:
       break
   ...

cursor.close()
dbconn.close()

#-----------------------------
import MySQLdb
import pwd

dbconn = MySQLdb.connect(db='dbname', host='mysqlserver.domain.com',
                        port=3306, user='user', passwd='password')

cursor = dbconn.cursor()
cursor.execute("CREATE TABLE users (uid INT, login CHAR(8))")

# Note: some databases use %s for parameters, some use ? or other
# formats
sql_fmt = "INSERT INTO users VALUES( %s, %s )"

for userent in pwd.getpwall():
   # the second argument contains a list of parameters which will
   # be quoted before being put in the query
   cursor.execute(sql_fmt, (userent.pw_uid, userent.pw_name))

cursor.execute("SELECT * FROM users WHERE uid < 50")

for row in cursor.fetchall():
   # NULL will be displayed as None
   print ", ".join(map(str, row))

cursor.execute("DROP TABLE users")
cursor.close()
dbconn.close()
#-----------------------------

# @@PLEAC@@_14.11
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.1
#-----------------------------
# Parsing program arguments
# -- getopt way (All Python versions)

#-----------------------------
# Preamble

import sys
import getopt

# getopt() explicitly receives arguments for it to process.
# No magic. Explicit is better than implicit.

# PERL: @ARGV
argv = sys.argv[1:]

# Note that sys.argv[0] is the script name, and need to be
# stripped.

#-----------------------------
# Short options

# PERL: getopt("vDo");
# Polluting the caller's namespace is evil. Don't do that.

# PERL: getopt("vDo:", \%opts);
opts, rest = getopt.getopt(argv, "vDo:")

# If you want switches to take arguments, you must say so.
# Unlike PERL, which silently performs its magic, switches
# specified without trailing colons are considered boolean
# flags by default.

# PERL: getopt("vDo", \%opts);
opts, rest = getopt.getopt(argv, "v:D:o:")

# PERL: getopts("vDo:", \%opts);
# getopt/getopts distinction is not present in Python 'getopt'
# module.

#-----------------------------
# getopt() return values, compared to PERL

# getopt() returns two values. The first is a list of
# (option, value) pair. (Not a dictionary, i.e. Python hash.)
# The second is the list of arguments left unprocessed.

# Example
# >>> argv = "-v ARG1 -D ARG2 -o ARG3".split()
# >>> opts, rest = getopt.getopt(argv, "v:D:o:")
# >>> print opts
# [('-v', 'ARG1'), ('-D', 'ARG2'), ('-o', 'ARG3')]

#-----------------------------
# Long options

# getopt() handles long options too. Pass a list of option
# names as the third argument. If an option takes an argument,
# append an equal sign.

opts, rest = getopt.getopt(argv, "", [
    "verbose", "Debug", "output="])

#-----------------------------
# Switch clustering

# getopt() does switch clustering just fine.

# Example
# >>> argv1 = '-r -f /tmp/testdir'.split()
# >>> argv2 = '-rf /tmp/testdir'.split()
# >>> print getopt.getopt(argv1, 'rf')
# ([('-r', ''), ('-f', '')], ['/tmp/testdir'])
# >>> print getopt.getopt(argv2, 'rf')
# ([('-r', ''), ('-f', '')], ['/tmp/testdir'])

#-----------------------------
# @@INCOMPLETE@@

# TODO: Complete this section using 'getopt'. Show how to
# use the parsed result.

# http://www.python.org/doc/current/lib/module-getopt.html
# Python library reference has a "typical usage" demo.

# TODO: Introduce 'optparse', a very powerful command line
# option parsing module. New in 2.3.


# @@PLEAC@@_15.2
##------------------
import sys

def is_interactive_python():
    try:
        ps = sys.ps1
    except:
        return False
    return True
##------------------
import sys
def is_interactive():
    # only False if stdin is redirected like "-t" in perl.
    return sys.stdin.isatty()

# Or take advantage of Python's Higher Order Functions:
is_interactive = sys.stdin.isatty
##------------------
import posix
def is_interactive_posix():
    tty = open("/dev/tty")
    tpgrp = posix.tcgetpgrp(tty.fileno())
    pgrp = posix.getpgrp()
    tty.close()
    return (tpgrp == pgrp)

# test with:
#  python 15.2.py
#  echo "dummy" | python 15.2.py | cat
print "is python shell:", is_interactive_python()
print "is a tty:", is_interactive()
print "has no tty:", is_interactive_posix()

if is_interactive():
    while True:
        try:
            ln = raw_input("Prompt:")
        except:
            break
        print "you typed:", ln


# @@PLEAC@@_15.3

# Python has no Term::Cap module.
# One could use the curses, but this was not ported to windows,
# use console.

# just run clear
import os
os.system("clear")
# cache output
clear = os.popen("clear").read()
print clear
# or to avoid print's newline
sys.stdout.write(clear)

# @@PLEAC@@_15.4
# Determining Terminal or Window Size

# eiter use ioctl
import struct, fcntl, termios, sys

s = struct.pack("HHHH", 0, 0, 0, 0)
hchar, wchar = struct.unpack("HHHH", fcntl.ioctl(sys.stdout.fileno(),
                                 termios.TIOCGWINSZ, s))[:2]
# or curses
import curses
(hchar,wchar) = curses.getmaxyx()

# graph contents of values
import struct, fcntl, termios, sys
width = struct.unpack("HHHH", fcntl.ioctl(sys.stdout.fileno(),
                                 termios.TIOCGWINSZ, 
                                 struct.pack("HHHH", 0, 0, 0, 0)))[1]
if width<10:
    print "You must have at least 10 characters"
    raise SystemExit

max_value = 0                    
for v in values:
    max_value = max(max_value,v)
    
ratio = (width-10)/max_value   # chars per unit
for v in values:
    print "%8.1f %s" % (v, "*"*(v*ratio))

# @@PLEAC@@_15.5

# there seems to be no standard ansi module
# and BLINK does not blink here.
RED = '\033[31m'
RESET = '\033[0;0m'
BLINK = '\033[05m'
NOBLINK = '\033[25m'

print RED+"DANGER, Will Robinson!"+RESET
print "This is just normal text"
print "Will ``"+BLINK+"Do you hurt yet?"+NOBLINK+"'' and back"

# @@PLEAC@@_15.6

# Show ASCII values for keypresses

# _Getch is from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
class _Getch:
    """Gets a single character from standard input.  Doesn't echo to screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self):
        return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

print "Press keys to see their ASCII values.  Use Ctrl-C to quit.\n"
try:
    while True:
        char = ord(getch())
        if char == 3:
            break
        print " Decimal: %3d   Octal: %3o   Hex: x%02x" % (char, char, char)
except KeyboardError:
    pass
#----------------------------------------

# @@PLEAC@@_15.7
print "\aWake up!\n";
#----------------------------------------
# @@INCOMPLETE@@

# @@PLEAC@@_15.8
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.9
# On Windows
import msvcrt
if msvcrt.kbhit():
    c = msvcrt.getch

# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
# @@INCOMPLETE@@


# @@PLEAC@@_15.10
#----------------------------------------
import getpass
import pwd
import crypt
password = getpass.getpass('Enter your password: ')
username = getpass.getuser()
encrypted = pwd.getpwnam(username).pw_passwd
if not encrypted or encrypted == 'x':
    # If using shadow passwords, this will be empty or 'x'
    print "Cannot verify password"
elif crypt.crypt(password, encrypted) != encrypted:
    print "You are not", username
else:
    print "Welcome,", username
#----------------------------------------

# @@PLEAC@@_15.11

# simply importing readline gives line edit capabilities to raw_
import readline
readline.add_history("fake line")
line = raw_input()

# download the following standalone program
#!/usr/bin/python
# vbsh - very bad shell

import os
import readline

while True:
    try:
        cmd = raw_input('$ ')
    except EOFError:
        break
    status = os.system(cmd)
    exit_value = status >> 8
    signal_num = status & 127
    dumped_core = status & 128 and "(core dumped)" or ""
    print "Program terminated with status %d from signal %d%s\n" % (
            exit_value, signal_num, dumped_core)



readline.add_history("some line!")
readline.remove_history_item(position)
line = readline.get_history_item(index)

# an interactive python shell would be
import code, readline
code.InteractiveConsole().interact("code.InteractiveConsole")

# @@PLEAC@@_15.12
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.13
#----------------------------------------
# This entry uses pexpect, a pure Python Expect-like module.
# http://pexpect.sourceforge.net/

# for more information, check pexpect's documentation and example.

import pexpect

#----------------------------------------
# spawn program
try:
    command = pexpect.spawn("program to run")
except pexpect.ExceptionPexpect:
    # couldn't spawn program
    pass

#----------------------------------------
# you can pass any filelike object to setlog
# passing None will stop logging

# stop logging
command.setlog(None)

# log to stdout
import sys
command.setlog(sys.stdout)

# log to specific file
fp = file("pexpect.log", "w")
command.setlog(fp)

#----------------------------------------
# expecting simple string
command.expect("ftp>")

# expecting regular expression
# actually, string is always treated as regular expression

# so it's the same thing
command.expect("Name.*:")

# you can do it this way, too
import re
regex = re.compile("Name.*:")
command.expect(regex)

#----------------------------------------
# expecting with timeout
try:
    command.expect("Password:", 10)
except pexpect.TIMEOUT:
    # timed out
    pass

# setting default timeout
command.timeout = 10

# since we set default timeout, following does same as above
try:
    command.expect("Password:")
except pexpect.TIMEOUT:
    # timed out
    pass

#----------------------------------------
# what? do you *really* want to wait forever?

#----------------------------------------
# sending line: normal way
command.sendline("get spam_and_ham")

# you can also treat it as file
print>>command, "get spam_and_ham"

#----------------------------------------
# finalization

# close connection with child process
# (that is, freeing file descriptor)
command.close()

# kill child process
import signal
command.kill(signal.SIGKILL)

#----------------------------------------
# expecting multiple choices
which = command.expect(["invalid", "success", "error", "boom"])

# return value is index of matched choice
# 0: invalid
# 1: success
# 2: error
# 3: boom

#----------------------------------------
# avoiding exception handling
choices = ["invalid", "success", "error", "boom"]
choices.append(pexpect.TIMEOUT)
choices.append(pexpect.EOF)

which = command.expect(choices)

# if TIMEOUT or EOF occurs, appropriate index is returned
# (instead of raising exception)
# 4: TIMEOUT
# 5: EOF

# @@PLEAC@@_15.14
from Tkinter import *

def print_callback():
    print "print_callback"

main = Tk()

menubar = Menu(main)
main.config(menu=menubar)

file_menu = Menu(menubar)
menubar.add_cascade(label="File", underline=1, menu=file_menu)
file_menu.add_command(label="Print", command=print_callback)

main.mainloop()

# using a class
from Tkinter import *

class Application(Tk):
    def print_callback(self):
        print "print_callback"
    def debug_callback(self):
        print "debug:", self.debug.get()
        print "debug level:", self.debug_level.get()

    def createWidgets(self):
        menubar = Menu(self)
        self.config(menu=menubar)
        file_menu = Menu(menubar)
        menubar.add_cascade(label="File",      
                    underline=1, menu=file_menu)
        file_menu.add_command(label="Print",
                command=self.print_callback)
        file_menu.add_command(label="Quit Immediately",
                command=sys.exit)
        # 
        options_menu = Menu(menubar)
        menubar.add_cascade(label="Options",
                underline=0, menu=options_menu)
        options_menu.add_checkbutton(
                label="Create Debugging File",
                variable=self.debug,
                command=self.debug_callback,
                onvalue=1, offvalue=0)
        options_menu.add_separator()
        options_menu.add_radiobutton(
                label = "Level 1",
                variable = self.debug_level,
                value = 1
                )
        options_menu.add_radiobutton(
                label = "Level 2",
                variable = self.debug_level,
                value = 2
                )
        options_menu.add_radiobutton(
                label = "Level 3",
                variable = self.debug_level,
                value = 3
                )

    def __init__(self, master=None):
        Tk.__init__(self, master)
        # bound variables must be IntVar, StrVar, ...
        self.debug = IntVar()
        self.debug.set(0)
        self.debug_level = IntVar()
        self.debug_level.set(1)
        self.createWidgets()

app = Application()
app.mainloop()

# @@PLEAC@@_15.15
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.16
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.17
# Start Python scripts without the annoying DOS window on win32
# Use extension ".pyw" on files - eg: "foo.pyw" instead of "foo.py"
# Or run programs using "pythonw.exe" rather than "python.exe" 

# @@PLEAC@@_15.18
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_15.19
# @@INCOMPLETE@@
# @@INCOMPLETE@@


# @@PLEAC@@_16.1
import popen2

# other popen methods than popen4 can lead to deadlocks
# if there is much data on stdout and stderr

(err_out, stdin) = popen2.popen4("program args")
lines = err_out.read() # collect output into one multiline string

(err_out, stdin) = popen2.popen4("program args")
lines = err_out.readlines() # collect output into a list, one line per element

#-----------------------------

(err_out, stdin) = popen2.popen4("program args")
output = []
while True:
    line = err_out.readline()
    if not line:
        break
    output.appen(line)
output = ''.join(output)

# @@PLEAC@@_16.2
import os
myfile = "foo.txt"
status = os.system("vi %s" % myfile)

#-----------------------------
import os
os.system("cmd1 args | cmd2 | cmd3 >outfile")
os.system("cmd args <infile >outfile 2>errfile")

status = os.system("%s %s %s" % (program, arg1, arg2))
if status != 0:
    print "%s exited funny: %s" % (program, status)
    raise SystemExit
    

# @@PLEAC@@_16.3
# -----------------------------
import os
import sys
import glob

args = glob.glob("*.data")
try:
    os.execvp("archive", args)
except OSError, e:
    print "Couldn't replace myself with archive: %s" % err
    raise SystemExit

# The error message does not contain the line number like the "die" in
# perl. But if you want to show more information for debugging, you can
# delete the try...except and you get a nice traceback which shows all
# line numbers and filenames.

# -----------------------------
os.execvp("archive", ["accounting.data"])

# @@PLEAC@@_16.4
# -------------------------
# Read from a child process

import sys
import popen2
pipe = popen2.Popen4("program arguments")
pid = pipe.pid
for line in pipe.fromchild.readlines():
    sys.stdout.write(line)

# Popen4 provides stdout and stderr.
# This avoids deadlocks if you get data
# from both streams.
#
# If you don't need the pid, you
# can use popen2.popen4(...)

# -----------------------------
# Write to a child process

import popen2

pipe = popen2.Popen4("gzip > foo.gz")
pid = pipe.pid
pipe.tochild.write("Hello zipped world!\n")
pipe.tochild.close() # programm will get EOF on STDIN

# @@PLEAC@@_16.5
class OutputFilter(object):
    def __init__(self, target, *args, **kwds):
        self.target = target
        self.setup(*args, **kwds)
        self.textbuffer = ""

    def setup(self, *args, **kwds):
        pass
    
    def write(self, data):
        if data.endswith("\n"):
            data = self.process(self.textbuffer + data)
            self.textbuffer = ""
            if data is not None:
                self.target.write(data)
        else:
            self.textbuffer += data

    def process(self, data):
        return data

class HeadFilter(OutputFilter):
    def setup(self, maxcount):
        self.count = 0
        self.maxcount = maxcount

    def process(self, data):
        if self.count < self.maxcount:
            self.count += 1
            return data

class NumberFilter(OutputFilter):
    def setup(self):
        self.count=0

    def process(self, data):
        self.count += 1
        return "%s: %s"%(self.count, data)

class QuoteFilter(OutputFilter):
    def process(self, data):
        return "> " + data

import sys
f = HeadFilter(sys.stdout, 100)
for i in range(130):
    print>>f, i

print

txt = """Welcome to Linux, version 2.0.33 on a i686

"The software required `Windows 95 or better', 
so I installed Linux." """
f1 = NumberFilter(sys.stdout)
f2 = QuoteFilter(f1)
for line in txt.split("\n"):
    print>>f2, line
print
f1 = QuoteFilter(sys.stdout)
f2 = NumberFilter(f1)
for line in txt.split("\n"):
    print>>f2, line


# @@PLEAC@@_16.6
# This script accepts several filenames
# as argument. If the file is zipped, unzip
# it first. Then read each line if the file
import os
import sys
import popen2

for file in sys.argv[1:]:
    if file.endswith(".gz") or file.endswith(".Z"):
        (stdout, stdin) = popen2.popen2("gzip -dc '%s'" % file)
        fd = stdout
    else:
        fd = open(file)
    for line in fd:
        # ....
        sys.stdout.write(line)
    fd.close()
#-----------------------------

#-----------------------------
# Ask for filename and open it
import sys
print "File, please?"
line = sys.stdin.readline()
file = line.strip() # chomp
open(file)

# @@PLEAC@@_16.7
# Execute foo_command and read the output

import popen2
(stdout_err, stdin) = popen2.popen4("foo_command")
for line in stdout_err.readlines():
    # ....

# @@PLEAC@@_16.8
# Open command in a pipe
# which reads from stdin and writes to stdout

import popen2
pipe = popen2.Popen4("wc -l") # Unix command
pipe.tochild.write("line 1\nline 2\nline 3\n")
pipe.tochild.close()
output = pipe.fromchild.read()

# @@PLEAC@@_16.9

# popen3: get stdout and stderr of new process
# Attetion: This can lead to deadlock,
# since the buffer of stderr or stdout might get filled.
# You need to use select if you want to avoid this.

import popen2
(child_stdout, child_stdin, child_stderr) = popen2.popen3(...)

# @@PLEAC@@_16.10
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.11
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.12
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.13
#
# Print available signals and their value
# See "man signal" "man kill" on unix.

import signal
for name in dir(signal):
    if name.startswith("SIG"):
        value = getattr(signal, name)
        print "%s=%s" % (name, value)

# @@PLEAC@@_16.14
# You can send signals to processes
# with os.kill(pid, signal)


# @@PLEAC@@_16.15
import signal

def get_sig_quit(signum, frame):
    ....

signal.signal(signal.SIGQUIT, get_sig_quit)   # Install handler

signal.signal(signal.SIGINT, signal.SIG_IGN)  # Ignore this signal
signal.signal(signal.SIGSTOP, signal.SIG_DFL) # Restore to default handling

# @@PLEAC@@_16.16
# Example of handler: User must Enter Name ctrl-c does not help

import sys
import signal

def ding(signum, frame):
    print "\aEnter your name!"
    return

signal.signal(signal.SIGINT, ding)
print "Please enter your name:"

name = ""
while not name:
    try:
        name = sys.stdin.readline().strip()
    except:
        pass

print "Hello: %s" % name

# @@PLEAC@@_16.17
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.18
import signal

# ignore signal INT
signal.signal(signal.SIGINT, signal.SIG_IGN)

# Install signal handler
def tsktsk(signum, frame):
    print "..."

signal.signal(signal.SIGINT, tsktsk)

# @@PLEAC@@_16.19
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.20
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_16.21
import signal

def handler(signum, frame):
    raise "timeout"

signal.signal(signal.SIGALRM, handler)

try:
    signal.alarm(5) # signal.alarm(3600)

    # long-time operation
    while True:
        print "foo"

    signal.alarm(0)
except:
    signal.alarm(0)
    print "timed out"
else:
    print "no time out"

# @@PLEAC@@_16.22
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.0
# Socket Programming (tcp/ip and udp/ip)

import socket

# Convert human readable form to 32 bit value
packed_ip = socket.inet_aton("208.146.240.1")
packed_ip = socket.inet_aton("www.oreilly.com")

# Convert 32 bit value to ip adress
ip_adress = socket.inet_ntoa(packed_ip)

# Create socket object
socketobj = socket(family, type) # Example socket.AF_INT, socket.SOCK_STREAM
       
# Get socketname
socketobj.getsockname() # Example, get port adress of client

# @@PLEAC@@_17.1

# Example: Connect to a server (tcp)
# Connect to a smtp server at localhost and send an email.
# For real applications you should use smtplib.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 25)) # SMTP
print s.recv(1024)
s.send("mail from: <pleac@localhost>\n")
print s.recv(1024)
s.send("rcpt to: <guettli@localhost>\n")
print s.recv(1024)
s.send("data\n")
print s.recv(1024)
s.send("From: Python Lover\nSubject: Python is better then perl\n\nYES!\n.\n")
print s.recv(1024)
s.close()

# @@PLEAC@@_17.2

# Create a Server, calling handler for every client
# You can test it with "telnet localhost 1029"

from SocketServer import TCPServer
from SocketServer import BaseRequestHandler

class MyHandler(BaseRequestHandler):
    def handle(self):
        print "I got an request"
        
server = TCPServer(("127.0.0.1", 1029), MyHandler)
server.serve_forever()

# @@PLEAC@@_17.3
# This is the continuation of 17.2

import time
from SocketServer import TCPServer
from SocketServer import BaseRequestHandler

class MyHandler(BaseRequestHandler):
    def handle(self):
        # self.request is the socket object
        print "%s I got an request from ip=%s port=%s" % (
            time.strftime("%Y-%m-%d %H:%M:%S"),
            self.client_address[0],
            self.client_address[1]
            )
        self.request.send("What is your name?\n")
        bufsize=1024
        response=self.request.recv(bufsize).strip() # or recv(bufsize, flags)
        data_to_send="Welcome %s!\n" % response
        self.request.send(data_to_send) # or send(data, flags)
        print "%s connection finnished" % self.client_address[0]
        
server = TCPServer(("127.0.0.1", 1028), MyHandler)
server.serve_forever()

# -----------------
# Using select

import select
import socket

in_list = []
in_list.append(mysocket)
in_list.append(myfile)
# ...

out_list = []
out_list.append(...)

except_list = []
except_list.append(...)

(in_, out_, exc_) = select.select(in_list, out_list, except_list, timeout)

for fd in in_:
    print "Can read", fd
for fd in out_:
    print "Can write", fd
for fd in exc_:
    print "Exception on", fd

# Missing: setting TCP_NODELAY

# @@PLEAC@@_17.4

import socket
# Set up a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# send 
MSG = 'Hello'
HOSTNAME = '127.0.0.1'
PORTNO = 10000
s.connect((HOSTNAME, PORTNO))
if len(MSG) != s.send(MSG):
    # where to get error message "$!".
    print "cannot send to %s(%d):" % (HOSTNAME,PORTNO)
    raise SystemExit(1)
MAXLEN = 1024
(data,addr) = s.recvfrom(MAXLEN)
s.close()
print '%s(%d) said "%s"' % (addr[0],addr[1], data)

# download the following standalone program
#!/usr/bin/python
# clockdrift - compare another system's clock with this one

import socket
import struct
import sys
import time

if len(sys.argv)>1:
    him = sys.argv[1]
else:
    him = '127.1'

SECS_of_70_YEARS = 2208988800

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((him,socket.getservbyname('time','udp')))
s.send('')
(ptime, src) = s.recvfrom(4)
host = socket.gethostbyaddr(src[0])
delta = struct.unpack("!L", ptime)[0] - SECS_of_70_YEARS - time.time()
print "Clock on %s is %d seconds ahead of this one." % (host[0], delta)



# @@PLEAC@@_17.5

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    s.bind(('', server_port))
except socket.error, err:
    print "Couldn't be a udp server on port %d : %s" % (
            server_port, err)
    raise SystemExit

while True:
    datagram = s.recv(MAX_TO_READ)
    if not datagram:
        break
    # do something
s.close()

# or 
import SocketServer

class handler(SocketServer.DatagramRequestHandler):
    def handle(self):
        # do something (with self.request[0])

s = SocketServer.UDPServer(('',10000), handler)
s.serve_forever()

# download the following standalone program
#!/usr/bin/python
# udpqotd - UDP message server

import SocketServer

PORTNO = 5151

class handler(SocketServer.DatagramRequestHandler):
    def handle(self):
        newmsg = self.rfile.readline().rstrip()
        print "Client %s said ``%s''" % (self.client_address[0], newmsg)
        self.wfile.write(self.server.oldmsg)
        self.server.oldmsg = newmsg

s = SocketServer.UDPServer(('',PORTNO), handler)
print "Awaiting UDP messages on port %d" % PORTNO
s.oldmsg = "This is the starting message."
s.serve_forever()


# download the following standalone program
#!/usr/bin/python
# udpmsg - send a message to the udpquotd server

import socket
import sys

MAXLEN = 1024
PORTNO = 5151
TIMEOUT = 5

server_host = sys.argv[1]
msg = " ".join(sys.argv[2:])

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT)
sock.connect((server_host, PORTNO))
sock.send(msg)
try:
    msg = sock.recv(MAXLEN)
    ipaddr, port = sock.getpeername()
    hishost = socket.gethostbyaddr(ipaddr)
    print "Server %s responded ``%s''" % ( hishost[0], msg)
except:
    print "recv from %s failed (timeout or no server running)." % (
            server_host )
sock.close()


# @@PLEAC@@_17.6

import socket
import os, os.path

if os.path.exists("/tmp/mysock"):
    os.remove("/tmp/mysock")
        
server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
server.bind("/tmp/mysock")

client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
client.connect("/tmp/mysock")
        
# @@PLEAC@@_17.7

ipaddr, port = s.getpeername()
hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ipaddr)
ipaddr = socket.gethostbyname('www.python.org')
# '194.109.137.226'
hostname, aliaslist, ipaddrlist = socket.gethostbyname_ex('www.python.org')
# ('fang.python.org', ['www.python.org'], ['194.109.137.226'])
socket.gethostbyname_ex('www.google.org')
# ('www.l.google.com', ['www.google.org', 'www.google.com'], 
#  ['64.233.161.147','64.233.161.104', '64.233.161.99'])

# @@PLEAC@@_17.8

import os

kernel, hostname, release, version, hardware = os.uname()

import socket

address = socket.gethostbyname(hostname)
hostname = socket.gethostbyaddr(address)
hostname, aliaslist, ipaddrlist = socket.gethostbyname_ex(hostname)
# e.g. ('lx3.local', ['lx3', 'b70'], ['192.168.0.13', '192.168.0.70'])

# @@PLEAC@@_17.9

socket.shutdown(0)   # Further receives are disallowed
socket.shutdown(1)   # Further sends are disallowed.
socket.shutdown(2)   # Further sends and receives are disallowed.

#

server.send("my request\n")  # send some data
server.shutdown(1)           # send eof; no more writing
answer = server.recv(1000)   # but you can still read

# @@PLEAC@@_17.10
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.11
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.12
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.13
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.14
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.15
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_17.16
#------------------------------
# Restart programm on signal SIGHUP
# Script must be executable: chmod a+x foo.py

#!/usr/bin/env python
import os
import sys
import time
import signal

def phoenix(signum, frame):
    print "Restarting myself: %s %s" % (self, args)
    os.execv(self, args)

self = os.path.abspath(sys.argv[0])
args = sys.argv[:]
signal.signal(signal.SIGHUP, phoenix)

while True:
    print "work"
    time.sleep(1)

#--------------------
# Read config file on SIGHUP
import signal

config_file = "/usr/local/etc/myprog/server_conf.py"

def read_config():
    execfile(config_file)

signal.signal(signal.SIGHUP, read_config)

# @@PLEAC@@_17.17

# chroot

import os

try:
    os.chroot("/var/daemon")
except Exception:
    print "Could not chroot"
    raise SystemExit(1)

#-----------------------------
# fork (Unix): Create a new process
# if pid == 0 --> parent process
# else child process

import os

pid = os.fork()
if pid:
    print "I am the new child %s" % pid
    raise SystemExit
else:
    print "I am still the parent"
    

# ----------------------------
# setsid (Unix): Create a new session
import os
id=os.setsid()

# ----------------------------
# Work until INT TERM or HUP signal is received
import time
import signal

time_to_die = 0

def sighandler(signum, frame):
    print "time to die"
    global time_to_die
    time_to_die = 1

signal.signal(signal.SIGINT, sighandler)
signal.signal(signal.SIGTERM, sighandler)
signal.signal(signal.SIGHUP, sighandler)

while not time_to_die:
    print "work"
    time.sleep(1)

# @@PLEAC@@_17.18
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_18.1

import socket
try:
    host_info = socket.gethostbyname_ex(name)
    # (hostname, aliaslist, ipaddrlist)
except socket.gaierror, err:
    print "Can't resolve hostname %s: %s" % (name, err[1])
                    
# if you only need the first one
import socket
try:
    address = socket.gethostbyname(name)
except socket.gaierror, err:
    print "Can't resolve hostname %s: %s" % (name, err[1])

# if you have an ip address
try:
    host_info = socket.gethostbyaddr(address)
    # (hostname, aliaslist, ipaddrlist)
except socket.gaierror, err:
    print "Can't resolve address %s: %s" % (address, err[1])
                    
# checking back
import socket
try:
    host_info = socket.gethostbyaddr(address)
except socket.gaierror, err:
    print "Can't look up %s: %s" % (address, err[1])
    raise SystemExit(1)
try:
    host_info = socket.gethostbyname_ex(name)
except:
    print "Can't look up %s: %s" % (name, err[1])
    raise SystemExit(1)

found = address in host_info[2]

# use dnspython for more complex jobs.
# download the following standalone program
#!/usr/bin/python
# mxhost - find mx exchangers for a host

import sys

import dns
import dns.resolver

answers = dns.resolver.query(sys.argv[1], 'MX')
for rdata in answers:
    print rdata.preference, rdata.exchange



# download the following standalone program
#!/usr/bin/python
# hostaddrs - canonize name and show addresses

import sys
import socket
name = sys.argv[1]
hent = socket.gethostbyname_ex(name)
print "%s aliases: %s => %s" % (
            hent[0],
            len(hent[1])==0 and "None" or ",".join(hent[1]),
            ",".join(hent[2]) )


# @@PLEAC@@_18.2
import ftplib
ftp = ftplib.FTP("ftp.host.com")
ftp.login(username, password)
ftp.cwd(directory)

# get file
outfile = open(filename, "wb")
ftp.retrbinary("RETR %s" % filename, outfile.write)
outfile.close()

# upload file
upfile = open(upfilename, "rb")
ftp.storbinary("STOR %s" % upfilename, upfile)
upfile.close()

ftp.quit()


# @@PLEAC@@_18.3
import smtplib
from email.MIMEText import MIMEText

msg = MIMEText(body)
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject

mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_address, [to_address], msg.as_string())

# @@PLEAC@@_18.4
import nntplib

# You can except nntplib.NNTPError to process errors
# instead of displaying traceback.

server = nntplib.NNTP("news.example.com")
response, count, first, last, name = server.group("misc.test")
headers = server.head(first)
bodytext = server.body(first)
article = server.article(first)

f = file("article.txt")
server.post(f)

response, grouplist = server.list()
for group in grouplist:
    name, last, first, flag = group
    if flag == 'y':
        pass  # I can post to group

# @@PLEAC@@_18.5
import poplib

pop = poplib.POP3("mail.example.com")
pop.user(username)
pop.pass_(password)
count, size = pop.stat()
for i in range(1, count+1):
    reponse, message, octets = pop.retr(i)
    # message is a list of lines
    pop.dele(i)

# You must quit, otherwise mailbox remains locked.
pop.quit()

# @@PLEAC@@_18.6

import telnetlib

tn = telnetlib.Telnet(hostname)

tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
# read the logon message up to the prompt
d = tn.expect([prompt,], 10)
tn.write("ls\n")
files = d[2].split()
print len(files), "files"
tn.write("exit\n")
print tn.read_all() # blocks till eof

# @@PLEAC@@_18.7
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_18.8
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_18.9
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_19.0
# Introduction
#
# There is no standard cgi/web framework in python,
# this is reason for ranting now and then.
#
# See `PyWebOff <http://pyre.third-bit.com/pyweb/index.html>`__
# which compares CherryPy, Quixote, Twisted, WebWare and Zope
# Karrigell and print stantements. 
#
# Then there is Nevow and Standalone ZPT.

# @@PLEAC@@_19.1
# Partial implementation of PLEAC Python section 19.1
# Written by Seo Sanghyeon

# Standard CGI module is where PERL shines. Python
# module, cgi, is nothing but a form parser. So it is
# not really fair to compare these two. But I hesitate
# to introduce any non-standard module. After all,
# which one should I choose?

# I would stick to simple print statements. I believe
# the following is close to how these tasks are usually
# done in Python.

#-----------------------------
#!/usr/bin/env python
# hiweb - using FieldStorage class to get at form data

import cgi
form = cgi.FieldStorage()

# get a value from the form
value = form.getvalue("PARAM_NAME")

# print a standard header
print "Content-Type: text/html"
print

# print a document
print "<P>You typed: <TT>%s</TT></P>" % (
    cgi.escape(value),
    )

#-----------------------------
import cgi
form = cgi.FieldStorage()

who = form.getvalue("Name")
phone = form.getvalue("Number")
picks = form.getvalue("Choices")

# if you want to assure `picks' to be a list
picks = form.getlist("Choices")

#-----------------------------
# Not Implemented

# To implement -EXPIRES => '+3d', I need to study about
import cgi
import datetime

time_format = "%a, %d %b %Y %H:%M:%S %Z"
print "Expires: %s" % (
        (datetime.datetime.now()
        + datetime.timedelta(+3)).strftime(time_format)
        )
print "Date: %s" % (datetime.datetime.now().strftime(time_format))
print "Content-Type: text/plain; charset=ISO-8859-1"

#-----------------------------
# NOTES

# CGI::param() is a multi-purpose function. Here I want to
# note which Python functions correspond to it.

# PERL version 5.6.1, CGI.pm version 2.80.
# Python version 2.2.3. cgi.py CVS revision 1.68.

# Assume that `form' is the FieldStorage instance.

# param() with zero argument returns parameter names as
# a list. It is `form.keys()' in Python, following Python's
# usual mapping interface.

# param() with one argument returns the value of the named
# parameter. It is `form.getvalue()', but there are some
# twists:

# 1) A single value is passed.
# No problem.

# 2) Multiple values are passed.
# PERL: in LIST context, you get a list. in SCALAR context,
#       you get the first value from the list.
# Python: `form.getvalue()' returns a list if multiple
#         values are passed, a raw value if a single value
#         is passed. With `form.getlist()', you always
#         get a list. (When a single value is passed, you
#         get a list with one element.) With `form.getfirst()',
#         you always get a value. (When multiple values are
#         passed, you get the first one.)

# 3) Parameter name is given, but no value is passed.
# PERL: returns an empty string, not undef. POD says this
#       feature is new in 2.63, and was introduced to avoid
#       "undefined value" warnings when running with the
#       -w switch.
# Python: tricky. If you want black values to be retained,
#         you should pass a nonzero `keep_blank_values' keyword
#         argument. Default is not to retain blanks. In case
#         values are not retained, see below.

# 4) Even parameter name is never mentioned.
# PERL: returns undef.
# Python: returns None, or whatever you passed as the second
#         argument, or `default` keyword argument. This is
#         consistent with `get()' method of the Python mapping
#         interface.

# param() with more than one argument modifies the already
# set form data. This functionality is not available in Python
# cgi module.


# @@PLEAC@@_19.2
# enable() from 'cgitb' module, by default, redirects traceback
# to the browser. It is defined as 'enable(display=True, logdir=None,
# context=5)'.

# equivalent to importing CGI::Carp::fatalsToBrowser.
import cgitb
cgitb.enable()

# to suppress browser output, you should explicitly say so.
import cgitb
cgitb.enable(display=False)

# equivalent to call CGI::Carp::carpout with temporary files.
import cgitb
cgitb.enable(logdir="/var/local/cgi-logs/")

# Python exception, traceback facilities are much richer than PERL's
# die and its friends. You can use your custom exception formatter
# by replacing sys.excepthook. (equivalent to CGI::Carp::set_message.)
# Default formatter is available as traceback.print_exc() in pure
# Python. In fact, what cgitb.enable() does is replacing excepthook
# to cgitb.handler(), which knows how to format exceptions to HTML.

# If this is not enough, (usually this is enough!) Python 2.3 comes
# with a new standard module called 'logging', which is complex, but
# very flexible and entirely customizable.

# @@PLEAC@@_19.3
#
# download the following standalone program
#!/usr/bin/python
# webwhoami - show web users id
import getpass
print "Content-Type: text/plain\n"
print "Running as %s\n" % getpass.getuser()



# STDOUT/ERR flushing
#
# In contrast to what the perl cookbook says, modpython.org tells
# STDERR is buffered too.

# @@PLEAC@@_19.4
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_19.5

# use mod_python in the Apache web server.

# Load the module in httpd.conf or apache.conf

LoadModule python_module libexec/mod_python.so

<Directory /some/directory/htdocs/test>
    AddHandler mod_python .py
    PythonHandler mptest
    PythonDebug On
</Directory>

# test.py file in /some/directory/htdocs/test
from mod_python import apache

def handler(req):
    req.write("Hello World!")
    return apache.OK

# @@PLEAC@@_19.6

import os
os.system("command %s %s" % (input, " ".join(files))) # UNSAFE

# python doc lib cgi-security it says
#
# To be on the safe side, if you must pass a string gotten from a form to a shell
# command, you should make sure the string contains only alphanumeric characters, dashes,
# underscores, and periods.
import re
cmd = "command %s %s" % (input, " ".join(files))
if re.search(r"[^a-zA-Z0-9._\-]", cmd):
    print "rejected"
    sys.exit(1)
os.system(cmd)
trans = string.maketrans(string.ascii_letters+string.digits+"-_.",

# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_19.7
#-----------------------------
# This uses nevow's (http://nevow.com) stan; there's no standard
# way to generate HTML, though there are many implementations of
# this basic idea.
from nevow import tags as T
print T.ol[T.li['red'], T.li['blue'], T.li['green']]
# <ol><li>red</li><li>blue</li><li>green</li></ol>

names = 'Larry Moe Curly'.split()
print T.ul[ [T.li(type="disc")[name] for name in names] ]
# <ul><li type="disc">Larry</li><li type="disc">Moe</li>
#     <li type="disc">Curly</li></ul>
#-----------------------------
print T.li["alpha"]
#     <li>alpha</li>

print T.li['alpha'], T.li['omega']
#     <li>alpha</li> <li>omega</li>
#-----------------------------
states = {
    "Wisconsin":  [ "Superior", "Lake Geneva", "Madison" ],
    "Colorado":   [ "Denver", "Fort Collins", "Boulder" ],
    "Texas":      [ "Plano", "Austin", "Fort Stockton" ],
    "California": [ "Sebastopol", "Santa Rosa", "Berkeley" ],
}

print "<TABLE> <CAPTION>Cities I Have Known</CAPTION>";
print T.tr[T.th('State'), T.th('Cities')]
for k in sorted(states.keys()):
    print T.tr[ [T.th(k)] + [T.td(city) for city in sorted(states[k])] ]
print "</TABLE>";
#-----------------------------
# <TABLE> <CAPTION>Cities I Have Known</CAPTION>
#
#     <TR><TH>State</TH> <TH>Cities</TH></TR>
#
#     <TR><TH>California</TH> <TD>Berkeley</TD> <TD>Santa Rosa</TD>
#
#         <TD>Sebastopol</TD> </TR>
#
#     <TR><TH>Colorado</TH> <TD>Boulder</TD> <TD>Denver</TD>
#
#         <TD>Fort Collins</TD> </TR>
#
#     <TR><TH>Texas</TH> <TD>Austin</TD> <TD>Fort Stockton</TD>
#
#         <TD>Plano</TD></TR>
#
#     <TR><TH>Wisconsin</TH> <TD>Lake Geneva</TD> <TD>Madison</TD>
#
#         <TD>Superior</TD></TR>
#
# </TABLE>
#-----------------------------
print T.table[
        [T.caption['Cities I have Known'],
         T.tr[T.th['State'], T.th['Cities']] ] +
        [T.tr[ [T.th(k)] + [T.td(city) for city in sorted(states[k])]]
         for k in sorted(states.keys())]]
#-----------------------------
# salcheck - check for salaries
import MySQLdb
import cgi

form = cgi.FieldStorage()

if 'limit' in form:
    limit = int(form['limit'].value)
else:
    limit = ''

# There's not a good way to start an HTML/XML construct with stan
# without completing it.
print '<html><head><title>Salary Query</title></head><body>'
print T.h1['Search']
print '<form>'
print T.p['Enter minimum salary',
          T.input(type="text", name="limit", value=limit)]
print T.input(type="submit")
print '</form>'

if limit:
    dbconn = MySQLdb.connect(db='somedb', host='server.host.dom',
                             port=3306, user='username',
                             passwd='password')
    cursor = dbconn.cursor()
    cursor.execute("""
    SELECT name, salary FROM employees
    WHERE salary > %s""", (limit,))

    print T.h1["Results"]
    print "<TABLE BORDER=1>"

    for row in cursor.fetchall():
        print T.tr[ [T.td(cell) for cell in row] ]

    print "</TABLE>\n";
    cursor.close()
    dbconn.close()

print '</body></html>'
#-----------------------------

# @@PLEAC@@_19.8
#-----------------------------
url = "http://python.org/pypi"
print "Location: %s\n" % url
raise SystemExit
#-----------------------------
# oreobounce - set a cookie and redirect the browser
import Cookie
import time

c = Cookie.SimpleCookie()
c['filling'] = 'vanilla cr?me'
now = time.time()
future = now + 3*(60*60*24*30) # 3 months
expire_date = time.strftime('%a %d %b %Y %H:%M:%S GMT', future)
c['filling']['expires'] = expire_date
c['filling']['domain'] = '.python.org'

whither  = "http://somewhere.python.org/nonesuch.html"

# Prints the cookie header
print 'Status: 302 Moved Temporarily'
print c
print 'Location:', whither
print

#-----------------------------
#Status: 302 Moved Temporarily
#Set-Cookie: filling=vanilla%20cr%E4me; domain=.perl.com;
#    expires=Tue, 21-Jul-1998 11:58:55 GMT
#Location: http://somewhere.perl.com/nonesuch.html
#-----------------------------
# os_snipe - redirect to a Jargon File entry about current OS
import os, re
dir = 'http://www.wins.uva.nl/%7Emes/jargon'
matches = [
    (r'Mac', 'm/Macintrash.html'),
    (r'Win(dows )?NT', 'e/evilandrude.html'),
    (r'Win|MSIE|WebTV', 'm/MicroslothWindows.html'),
    (r'Linux', 'l/Linux.html'),
    (r'HP-UX', 'h/HP-SUX.html'),
    (r'SunOS', 's/ScumOS.html'),
    (None, 'a/AppendixB.html'),
    ]

for regex, page in matches:
    if not regex: # default
        break
    if re.search(regex, os.environ['HTTP_USER_AGENT']):
        break
print 'Location: %s/%s\n' % (dir, page)
#-----------------------------
# There's no special way to print headers
print 'Status: 204 No response'
print
#-----------------------------
#Status: 204 No response
#-----------------------------

# @@PLEAC@@_19.9
# download the following standalone program
#!/usr/bin/python
# dummyhttpd - start a HTTP daemon and print what the client sends

import SocketServer
# or use BaseHTTPServer, SimpleHTTPServer, CGIHTTPServer

def adr_str(adr):
    return "%s:%d" % adr

class RequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print "client access from %s" % adr_str(self.client_address)
        print self.request.recv(10000)
        self.request.send("Content-Type: text/plain\n"
                          "Server: dymmyhttpd/1.0.0\n"
                          "\n...\n")
        self.request.close()


adr = ('127.0.0.1', 8001)
print "Please contact me at <http://%s>" % adr_str(adr)
server = SocketServer.TCPServer(adr, RequestHandler)
server.serve_forever()
server.server_close()


# @@PLEAC@@_19.10

import Cookie
cookies = Cookie.SimpleCookie()
# SimpleCookie is more secure, but does not support all characters.
cookies["preference-name"] = "whatever you'd like" 
print cookies

# download the following standalone program
#!/usr/bin/python
# ic_cookies - sample CGI script that uses a cookie

import cgi
import os
import Cookie
import datetime

cookname = "favorite-ice-cream"  # SimpleCookie does not support blanks
fieldname = "flavor"

cookies = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE",""))
if cookies.has_key(cookname):
    favorite = cookies[cookname].value
else:
    favorite = "mint"

form = cgi.FieldStorage()
if not form.has_key(fieldname):
    print "Content-Type: text/html"
    print "\n"
    print "<html><body>"
    print "<h1>Hello Ice Cream</h1>"
    print "<form>"
    print 'Please select a flavor: <input type="text" name="%s" value="%s" />' % (
            fieldname, favorite )
    print "</form>"
    print "<hr />"
    print "</body></html>"
else:
    favorite = form[fieldname].value
    cookies[cookname] = favorite
    expire = datetime.datetime.now() + datetime.timedelta(730)
    cookies[cookname]["expires"] = expire.strftime("%a, %d %b %Y %H:00:00 GMT")
    cookies[cookname]["path"] = "/"
    print "Content-Type: text/html"
    print cookies
    print "\n"
    print "<html><body>"
    print "<h1>Hello Ice Cream</h1>"
    print "<p>You chose as your favorite flavor \"%s\"</p>" % favorite
    print "</body></html>"


# @@PLEAC@@_19.11
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_19.12
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_19.13
#-----------------------------
# first open and exclusively lock the file
import os, cgi, fcntl, cPickle
fh = open('/tmp/formlog', 'ab')
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)

form = cgi.FieldStorage()
# This doesn't produce a readable file; we copy the environment so
# that we save a plain dictionary (os.environ is a dictionary-like
# object).
cPickle.dump((form, os.environ.copy()) fh)
fh.close()
#-----------------------------
import cgi, smtplib, sys

form = cgi.FieldStorage()
email = """\
From: %S
To: hisname@hishost.com
Subject: mailed form submission

""" % sys.argv[0]

for key in form:
    values = form[key]
    if not isinstance(values, list):
        value = [values.value]
    else:
        value = [v.value for v in values]
    for item in values:
        email += '\n%s: %s' % (key, value)

server = smtplib.SMTP('localhost')
server.sendmail(sys.argv[0], ['hisname@hishost.com'], email)
server.quit()
#-----------------------------
# @@INCOMPLETE@@ I don't get the point of these:
# param("_timestamp", scalar localtime);
# param("_environs", %ENV);
#-----------------------------
import fcntl, cPickle
fh = open('/tmp/formlog', 'rb')
fcntl.flock(fh.fileno(), fcntl.LOCK_SH)

count = 0
while True:
    try:
        form, environ = cPickle.load(fh)
    except EOFError:
        break
    if environ.get('REMOTE_HOST').endswith('perl.com'):
        continue
    if 'items requested' in form:
        count += int(form['items requested'].value)
print 'Total orders:', count
#-----------------------------

# @@PLEAC@@_19.14
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_20.1
#-----------------------------
import urllib
content = urllib.urlopen(url).read()

try:
    import urllib
    content = urllib.urlopen(url).read()
except IOError:
    print "could not get %s" % url

#-----------------------------
# download the following standalone program
#!/usr/bin/python
# titlebytes - find the title and size of documents
#
# differences to perl
# 
# * no URI::Heuristics
# * perl LWP supports fetching files from local system
# * fetching a title from ftp or file doesnt work in perl either.

import sys, urllib2, HTMLParser
if len(sys.argv)<=1:
    print "usage: %s url" % sys.argv[0]
    sys.exit(1)
raw_url = sys.argv[1] 

# python has no equivalent to pearls URI::Heuristics, which
# would do some guessing like :
#
#   perl            -> http://www.perl.com
#   www.oreilly.com -> http://www.oreilly.com
#   ftp.funet.fi    -> ftp://ftp.funet.fi
#   /etc/passwd     -> file:/etc/passwd

# simple but pedantic html parser: tpj.com breaks it.
class html(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self._data = {}
        self._open_tags = []
    def handle_starttag(self, tag, attrs):
        self._open_tags.append(tag)
    def handle_endtag(self, tag):
        if len(self._open_tags)>0:
            self._open_tags.pop()
    def handle_data(self, data):
        if len(self._open_tags)>0:
            self._data[self._open_tags[-1]] = data
    def __getattr__(self,attr):
        if not self._data.has_key(attr):
            return ""
        return self._data[attr]

url = raw_url
print "%s =>\n\t" % url,
# TODO fake user agent "Schmozilla/v9.17 Platinum"
# TODO referer "http://wizard.yellowbrick.oz"
# as we only do http httplib would do also
try:
        response = urllib2.urlopen(url)
except:
        print " %s" % sys.exc_info()[1].reason[1]
        sys.exit(1)
# title is not in response
data = response.read()
parser = html()
parser.feed(data)
parser.close()  # force processing all data
count = len(data.split("\n"))
bytes = len(data)
print "%s (%d lines, %d bytes)" % (parser.title, 
        count, 
        bytes)

# omly bytes is in response.info()


# @@PLEAC@@_20.2

# GET method
import httplib
conn = httplib.HTTPConnection('www.perl.com')
conn.request('GET','/cgi-bin/cpan_mod?module=DB_File&readme=1')
r1 = conn.getresponse()
content = r1.read()

# POST method
import urllib
params = urllib.urlencode({'module': 'DB_File', 'readme': 1})
content = urllib.urlopen('http://www.perl.com', params).read()

# fields must be properly escaped
# script.cgi?field1?arg=%22this%20isn%27t%20%3CEASY%3E%22

# proxies can be taken from environment, or specified
# as the optional thrid parameter to urlopen.

# @@PLEAC@@_20.3
# download the following standalone program
#!/usr/bin/python
# xurl - extract unique, sorted list of links from URL

from HTMLParser import HTMLParser
import urllib
from sets import Set as set # not needed in 2.4
class myParser(HTMLParser):
    def __init__(self, url):
        self.baseUrl = url[:url.rfind('/')]
        HTMLParser.__init__(self)
    def reset(self):
        self.urls = set()
        HTMLParser.reset(self)
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            if attrs[0][0] == 'href':
                if attrs[0][1].find(':') == -1:
                    # we need to add the base URL.
                    self.urls.add(self.baseUrl + '/' + attrs[0][1])
                else:
                    self.urls.add(attrs[0][1])
url = 'http://www.perl.com/CPAN'
p = myParser(url)
s = urllib.urlopen(url)
data = s.read()
p.feed(data)
urllist = p.urls._data.keys()
urllist.sort()
print '\n'.join(urllist)



# @@PLEAC@@_20.4
# Converting ASCII to HTML

# download the following standalone program
#!/usr/bin/python
# text2html - trivial html encoding of normal text

import sys
import re

# precompile regular expressions
re_quoted = re.compile(r"(?m)^(>.*?)$")
re_url = re.compile(r"<URL:(.*)>")
re_http = re.compile(r"(http:\S+)")
re_strong = re.compile(r"\*(\S+)\*")
re_em = re.compile(r"\b_(\S+)_\b")

# split paragraphs
for para in open(sys.argv[1]).read().split("\n\n"):
    # TODO encode entities: dont encode "<>" but do "&"
    if para.startswith(" "):
        print "<pre>\n%s\n</pre>" % para
    else:
        para = re_quoted.sub(r"\1<br />", para)          # quoted text
        para = re_url.sub(r'<a href="\1">\1</a>', para)  # embedded URL
        para = re_http.sub(r'<a href="\1">\1</a>', para) # guessed URL
        para = re_strong.sub(r"<strong>\1</strong>",para)   # this is *bold* here
        para = re_em.sub(r"<em>\1</em>",para)            # this is _italic_ here
        print "<p>\n%s\n</p>" % para                     # add paragraph tags



#-----------------------------
import sys, re
import htmlentitydefs

def encode_entities(s):
    for k,v in htmlentitydefs.codepoint2name.items():
        if k<256: # no unicodes
            s = s.replace(chr(k),"&%s;"%v)
    return s

print "<table>"
text = sys.stdin.read()
text = encode_entities(text)
text = re.sub(r"(\n[ \t]+)"," . ",text)   # continuation lines
text = re.sub(r"(?m)^(\S+?:)\s*(.*?)$",
              r'<tr><th align="left">\1</th><td>\2</td></tr>',
                            text);
print text    
print "</table>"
                            
# @@PLEAC@@_20.5
# Converting HTML to ASCII

#-----------------------------
import os
ascii = os.popen("lynx -dump " + filename).read()

#-----------------------------
import formatter
import htmllib

w = formatter.DumbWriter()
f = formatter.AbstractFormatter(w)
p = htmllib.HTMLParser(f)
p.feed(html)
p.close()

# Above is a bare minimum to use writer/formatter/parser
# framework of Python.

# Search Python Cookbook for more details, like writing
# your own writers or formatters.

# Recipe #52297 has TtyFormatter, formatting underline
# and bold in Terminal. Recipe #135005 has a writer
# accumulating text instead of printing.

# @@PLEAC@@_20.6

import re

plain_text = re.sub(r"<[^>]*>","",html_text) #WRONG

# using HTMLParser
import sys, HTMLParser

class html(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self._plaintext = ""
        self._ignore = False
    def handle_starttag(self, tag, attrs):
        if tag == "script":
            self._ignore = True
    def handle_endtag(self, tag):
        if tag == "script":
            self._ignore = False
    def handle_data(self, data):
        if len(data)>0 and not self._ignore:
            self._plaintext += data
    def get_plaintext(self):
        return self._plaintext
    def error(self,msg):
        # ignore all errors
        pass

html_text = open(sys.argv[1]).read()

parser = html()
parser.feed(html_text)
parser.close()  # force processing all data
print parser.get_plaintext()

title_s = re.search(r"(?i)<title>\s*(.*?)\s*</title>", text)
title = title_s and title_s.groups()[0] or "NO TITLE"

# download the following standalone program
#!/usr/bin/python
# htitlebytes - get html title from URL
#

import sys, urllib2, HTMLParser
if len(sys.argv)<=1:
    print "usage: %s url ..." % sys.argv[0]
    sys.exit(1)

# simple but pedantic html parser: tpj.com breaks it.
class html(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self._data = {}
        self._open_tags = []
    def handle_starttag(self, tag, attrs):
        self._open_tags.append(tag)
    def handle_endtag(self, tag):
        if len(self._open_tags)>0:
            self._open_tags.pop()
    def handle_data(self, data):
        if len(self._open_tags)>0:
            self._data[self._open_tags[-1]] = data
    def __getattr__(self,attr):
        if not self._data.has_key(attr):
            return ""
        return self._data[attr]
    def error(self,msg):
        # ignore all errors
        pass

for url in sys.argv[1:]:
    print "%s: " % url,
    # TODO fake user agent "Schmozilla/v9.17 Platinum"
    # TODO referer "http://wizard.yellowbrick.oz"
    # as we only do http httplib would do also
    try:
        response = urllib2.urlopen(url)
    except:
        print " %s" % sys.exc_info()[1]
        sys.exit(1)
    # title is not in response
    parser = html()
    parser.feed(response.read())
    parser.close()  # force processing all data
    print parser.title 



# @@PLEAC@@_20.7
# download the following standalone program
#!/usr/bin/python
# churl - check urls

import sys

# head request
import urllib
def valid(url):
    try:
        conn = urllib.urlopen(url)
        return 1
    except:
        return 0

# parser class as in xurl
from HTMLParser import HTMLParser
from sets import Set as set # not needed in 2.4
class myParser(HTMLParser):
    def __init__(self, url):
        self.baseUrl = url[:url.rfind('/')]
        HTMLParser.__init__(self)
    def reset(self):
        self.urls = set()
        HTMLParser.reset(self)
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            if attrs[0][0] == 'href':
                if attrs[0][1].find(':') == -1:
                    # we need to add the base URL.
                    self.urls.add(self.baseUrl + '/' + attrs[0][1])
                else:
                    self.urls.add(attrs[0][1])

if len(sys.argv)<=1:
    print "usage: %s <start_url>" % (sys.argv[0])
    sys.exit(1)
    
base_url = sys.argv[1]
print base_url+":"
p = myParser(base_url)
s = urllib.urlopen(base_url)
data = s.read()
p.feed(data)
for link in p.urls._data.keys():
    state = "UNKNOWN URL"
    if link.startswith("http:"):
        state = "BAD"
        if valid(link):
            state = "OK"
    print "  %s: %s" % (link, state)



# @@PLEAC@@_20.8
# download the following standalone program
#!/usr/bin/python
# surl - sort URLs by their last modification date

import urllib
import time
import sys

Date = {}
while 1:
    # we only read from stdin not from argv.
    ln = sys.stdin.readline()
    if not ln:
        break
    ln = ln.strip()
    try:
        u = urllib.urlopen(ln)
        date = time.mktime(u.info().getdate("date"))
        if not Date.has_key(date):
            Date[date] = []
        Date[date].append(ln)
    except:
        sys.stderr.write("%s: %s!\n" % (ln, sys.exc_info()[1]))

dates = Date.keys()
dates.sort()    # python 2.4 would have sorted
for d in dates:
    print "%s  %s" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(d)),
                    ", ".join(Date[d]))


# @@PLEAC@@_20.9
import re

def template(filename, fillings):
    text = open(filename).read()
    def repl(matchobj):
        if fillings.has_key(matchobj.group(1)):
            return str(fillings[matchobj.group(1)])
        return ""
    # replace quoted words with value from fillings dictionary
    text = re.sub("%%(.+?)%%", repl, text)
    return text

fields = { "username":"peter", "count":"23", "total": "1234"}
print template("/home/httpd/templates/simple.template", fields)

# download the following standalone program
#!/usr/bin/python
# userrep1 - report duration of user logins using SQL database

import MySQLdb
import cgi
import re
import sys

def template(filename, fillings):
    text = open(filename).read()
    def repl(matchobj):
        if fillings.has_key(matchobj.group(1)):
            return str(fillings[matchobj.group(1)])
        return ""
    # replace quoted words with value from fillings dictionary
    text = re.sub("%%(.+?)%%", repl, text)
    return text

fields = cgi.FieldStorage()
if not fields.has_key("user"):
    print "Content-Type: text/plain\n"
    print "No username"
    sys.exit(1)

def get_userdata(username):
    db = MySQLdb.connect(passwd="",db="connections", user="bert")
    db.query("select count(duration) as count,"
            +" sum(duration) as total from logins"
            +" where username='%s'" % username)
    res = db.store_result().fetch_row(maxrows=1,how=1)
    res[0]["username"] = username
    db.close()
    return res[0]
                        
print "Content-Type: text/html\n"

print template("report.tpl", get_userdata(fields["user"].value))

# @@INCOMPLETE@@

# @@PLEAC@@_20.10
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_20.11
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_20.12

# sample data, use ``LOGFILE = open(sys.argv[1])`` in real life
LOGFILE = [
        '127.0.0.1 - - [04/Sep/2005:20:50:31 +0200] "GET /bus HTTP/1.1" 301 303\n',
        '127.0.0.1 - - [04/Sep/2005:20:50:31 +0200] "GET /bus HTTP/1.1" 301 303 "-" "Opera/8.02 (X11; Linux i686; U; en)"\n',
        '192.168.0.1 - - [04/Sep/2005:20:50:36 +0200] "GET /bus/libjs/layersmenu-library.js HTTP/1.1" 200 6228\n',
        '192.168.0.1 - - [04/Sep/2005:20:50:36 +0200] "GET /bus/libjs/layersmenu-library.js HTTP/1.1" 200 6228 "http://localhost/bus/" "Opera/8.02 (X11; Linux i686; U; en)"\n',
    ]

import re

# similar too perl version.
web_server_log_re = re.compile(r'^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] "(\S+) (.*?) (\S+)" (\S+) (\S+)$')
    
# with group naming.
split_re = re.compile(r'''(?x)         # allow nicer formatting (but requires escaping blanks)
                       ^(?P<client>\S+)\s
                       (?P<identuser>\S+)\s
                       (?P<authuser>\S+)\s
                       \[
                         (?P<date>[^:]+):
                         (?P<time>[\d:]+)\s
                         (?P<tz>[^\]]+)
                       \]\s
                       "
                         (?P<method>\S+)\s
                         (?P<url>.*?)\s
                         (?P<protocol>\S+)
                       "\s
                       (?P<status>\S+)\s
                       (?P<bytes>\S+)
                       (?:
                         \s
                         "
                           (?P<referrer>[^"]+)
                         "\s
                         "
                           (?P<agent>[^"]+)
                         "
                       )?''')
for line in LOGFILE:
    f = split_re.match(line)
    if f:
        print "agent = %s" % f.groupdict()['agent']

# @@PLEAC@@_20.13
# @@INCOMPLETE@@
# @@INCOMPLETE@@

# @@PLEAC@@_20.14
# @@INCOMPLETE@@
# @@INCOMPLETE@@