-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathappendix_a.html
2287 lines (1918 loc) · 77 KB
/
appendix_a.html
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
<section data-type="appendix" id="appendix-solutions">
<h1>Solutions</h1>
<p>
Here are suggested solutions for the études. Of course, your solutions may well be entirely different, and better.
</p>
<section data-type="sect1" id="SOLUTION01-ET02">
<h1>Solution 1-2</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns formulas.core
(:require [clojure.browser.repl :as repl]))
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(enable-console-print!)
(defn distance
"Calculate distance traveled by an object moving
with a given acceleration for a given amount of time."
[accel time]
(* accel time time))
(defn kinetic-energy
"Calculate kinetic energy given mass and velocity"
[m v]
(/ (* m v v) 2.0))
(defn centripetal
"Calculate centripetal acceleration given velocity and radius"
[v r]
(/ (* v v) r))
(defn average
"Calculate average of two numbers"
[a b]
(/ (+ a b) 2.0))
(defn variance
"Calculate variance of two numbers"
[a b]
(- (* 2 (+ (* a a) (* b b))) (* (+ a b) (+ a b))))</pre>
</section>
<section data-type="sect1" id="SOLUTION01-ET03">
<h1>Solution 1-3</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(def G 6.6784e-11)
(defn gravitational-force
"Calculate gravitational force of two objects of
mass m1 and m2, with centers of gravity at a distance r"
[m1 m2 r]
(/ (* G m1 m2) (* r r)))</pre>
</section>
<section data-type="sect1" id="SOLUTION01-ET04">
<h1>Solution 1-4</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(defn monthly-payment
"Calculate monthly payment on a loan of amount p,
with annual percentage rate apr, and a given number of years"
[p apr years]
(let [r (/ apr 12.0)
n (* years 12)
factor (.pow js/Math (+ 1 r) n)]
(* p (/ (* r factor) (- factor 1)))))</pre>
</section>
<section data-type="sect1" id="SOLUTION01-ET05">
<h1>Solution 1-5</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(defn radians
"Convert degrees to radians"
[degrees]
(* (/ (.-PI js/Math) 180) degrees))
(defn daylight
"Find minutes of daylight given latitude in degrees and day of year.
Formula from http://mathforum.org/library/drmath/view/56478.html"
[lat-degrees day]
(let [lat (radians lat-degrees)
part1 (* 0.9671396 (.tan js/Math (* 0.00860 (- day 186))))
part2 (.cos js/Math (+ 0.2163108 (* 2 (.atan js/Math part1))))
p (.asin js/Math (* 0.39795 part2))
numerator (+ (.sin js/Math 0.01454) (* (.sin js/Math lat) (.sin js/Math p)))
denominator (* (.cos js/Math lat) (.cos js/Math p))]
(* 60 (- 24 (* 7.63944 (.acos js/Math (/ numerator denominator)))))))</pre>
</section>
<section data-type="sect1" id="SOLUTION02-ET01">
<h1>Solution 2-1</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_js.core
(:require [clojure.browser.repl :as repl]))
(enable-console-print!)
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(defn radians
"Convert degrees to radians"
[degrees]
(* (/ (.-PI js/Math) 180) degrees))
(defn daylight
"Find minutes of daylight given day of year and latitude in degrees.
Formula from http://mathforum.org/library/drmath/view/56478.html"
[day lat-degrees]
(let [lat (radians lat-degrees)
part1 (* 0.9671396 (tan js/Math (* 0.00860 (- day 186))))
part2 (cos js/Math (+ 0.2163108 (* 2 (atan js/Math part1))))
p (asin js/Math (* 0.39795 part2))
numerator (+ (sin js/Math 0.01454) (* (sin js/Math lat) (sin js/Math p)))
denominator (* (cos js/Math lat) (cos js/Math p))]
(* 60 (- 24 (* 7.63944 (acos js/Math (/ numerator denominator)))))))
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (.-value (.getElementById js/document field))))
(defn calculate [evt]
(let [lat-d (get-float-value "latitude")
julian (get-float-value "julian")
minutes (daylight lat-d julian)]
(set! (.-innerHTML (.getElementById js/document "result")) minutes)))
(.addEventListener (.getElementById js/document "calculate") "click" calculate)</pre>
</section>
<section data-type="sect1" id="SOLUTION02-ET02">
<h1>Solution 2-2</h1>
<p>Much of the code is duplicated from the previous étude, only new code is shown here, with ellipses to represent omitted code.</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_gc.core
(:require [clojure.browser.repl :as repl]
[goog.dom :as dom]
[goog.events :as events]))
...
(defn radians...)
(defn daylight...)
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (.-value (dom/getElement field))))
(defn calculate [evt]
(let [lat-d (get-float-value "latitude")
julian (get-float-value "julian")
minutes (daylight lat-d julian)]
(dom/setTextContent (dom/getElement "result") minutes)))
(events/listen (dom/getElement "calculate") "click" calculate)</pre>
</section>
<section data-type="sect1" id="SOLUTION02-ET03">
<h1>Solution 2-3</h1>
<p>Much of the code is duplicated from the previous étude. Only new code is shown here, with ellipses to represent omitted code.</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_dommy.core
(:require [clojure.browser.repl :as repl]
[dommy.core :as dommy :refer-macros [sel sel1]]))
...
(defn radians ... )
(defn daylight ... )
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (dommy/value (sel1 field))))
(defn calculate [evt]
(let [lat-d (get-float-value "#latitude")
julian (get-float-value "#julian")
minutes (daylight lat-d julian)]
(dommy/set-text! (sel1 "#result") minutes)))
(dommy/listen! (sel1 "#calculate") :click calculate)</pre>
</section>
<section data-type="sect1" id="SOLUTION02-ET04">
<h1>Solution 2-4</h1>
<p>Much of the code is duplicated from the previous étude. Only new code is shown here, with ellipses to represent omitted code.</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_domina.core
(:require [clojure.browser.repl :as repl]
[domina]
[domina.events :as events]))
...
(defn radians ... )
(defn daylight ...)
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (domina/value (domina/by-id field))))
(defn calculate [evt]
(let [lat-d (get-float-value "latitude")
julian (get-float-value "julian")
minutes (daylight lat-d julian)]
(domina/set-text! (domina/by-id "result") minutes)))
(events/listen! (domina/by-id "calculate") :click calculate)
</pre>
</section>
<section data-type="sect1" id="SOLUTION02-ET05">
<h1>Solution 2-5</h1>
<p>Much of the code is duplicated from the previous étude. Only new code is shown here, with ellipses to represent omitted code.</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_enfocus.core
(:require [clojure.browser.repl :as repl]
[enfocus.core :as ef]
[enfocus.events :as ev]))
...
(defn daylight ... )
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (ef/from field (ef/get-prop :value))))
(defn calculate [evt]
(let [lat-d (get-float-value "#latitude")
julian (get-float-value "#julian")
minutes (daylight lat-d julian)]
(ef/at "#result" (ef/content (.toString minutes)))))
(ef/at "#calculate" (ev/listen :click calculate))</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET01">
<h1>Solution 3-1</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(defn move-zeros
"Move zeros to end of a list or vector of numbers"
[numbers]
(let [nonzero (filter (fn[x] (not= x 0)) numbers)]
(concat nonzero
(repeat (- (count numbers) (count nonzero)) 0))))</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET02">
<h1>Solution 3-2</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_by_date.core
(:require [clojure.browser.repl :as repl]
[clojure.string :as str]
[domina]
[domina.events :as events]))
(enable-console-print!)
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(defn radians
"Convert degrees to radians"
[degrees]
(* (/ (.-PI js/Math) 180) degrees))
(defn daylight
"Find minutes of daylight given latitude in degrees and day of year.
Formula from http://mathforum.org/library/drmath/view/56478.html"
[lat-degrees day]
(let [lat (radians lat-degrees)
part1 (* 0.9671396 (.tan js/Math (* 0.00860 (- day 186))))
part2 (.cos js/Math (+ 0.2163108 (* 2 (.atan js/Math part1))))
p (.asin js/Math (* 0.39795 part2))
numerator (+ (.sin js/Math 0.01454) (* (.sin js/Math lat) (.sin js/Math p)))
denominator (* (.cos js/Math lat) (.cos js/Math p))]
(* 60 (- 24 (* 7.63944 (.acos js/Math (/ numerator denominator)))))))
(defn get-float-value
"Get the floating point value of a field"
[field]
(.parseFloat js/window (domina/value (domina/by-id field))))
(defn leap-year?
"Return true if given year is a leap year; false otherwise"
[year]
(or (and (= 0 (rem year 4)) (not= 0 (rem year 100)))
(= 0 (rem year 400))))
(defn ordinal-day
"Compute ordinal day given Gregorian day, month, and year"
[day month year]
(let [leap (leap-year? year)
feb-days (if leap 29 28)
days-per-month [0 31 feb-days 31 30 31 30 31 31 30 31 30 31]
month-ok (and (> month 0) (< month 13))
day-ok (and month-ok (> day 0) (<= day (+ (nth days-per-month month))))
subtotal (reduce + (take month days-per-month))]
(if day-ok (+ subtotal day) 0)))
(defn to-julian
"Convert Gregorian date to Julian"
[]
(let [greg (domina/value (domina/by-id "gregorian"))
parts (str/split greg #"[-/]")
[y m d] (map (fn [x] (.parseInt js/window x 10)) parts)]
(ordinal-day d m y)))
(defn calculate [evt]
(let [lat-d (get-float-value "latitude")
julian (to-julian)
minutes (daylight lat-d julian)]
(domina/set-text! (domina/by-id "result") (str (quot minutes 60) "h "
(.toFixed (rem minutes 60) 2) "m"))))
(events/listen! (domina/by-id "calculate") :click calculate)</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET03">
<h1>Solution 3-3</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(defn mean
"Compute mean of a sequence of numbers."
[x]
(let [n (count x)]
(/ (apply + x) n)))
(defn median
"Compute median of a sequence of numbers."
[x]
(let [n (count x)
remainder (drop (- (int (/ n 2)) 1) (sort x))]
(if (odd? n)
(second remainder)
(/ (+ (first remainder) (second remainder)) 2))))
(defn getsums
"Reducing function for computing sum and sum of squares.
The accumulator is a two-vector with the current sum and sum of squares
Could be made clearer with destructuring, but that's not in
this chapter."
[acc item]
(vector (+ (first acc) item) (+ (last acc) (* item item))))
(defn stdev
"Compute standard deviation of a sequence of numbers"
[x]
(let [[sum sumsq] (reduce getsums [0 0] x)
n (count x)]
(.sqrt js/Math (/ (- sumsq (/ (* sum sum) n)) (- n 1)))))</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET04">
<h1>Solution 3-4</h1>
<p>
This solution uses the Domina library to interact with the web page. The <code>ns</code> special form needs to be updated to require the correct libraries.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns stats.core
(:require [clojure.browser.repl :as repl]
[clojure.string :as str]
[domina :as dom]
[domina.events :as ev]))</pre>
<p>
This is the additional code for interacting with the web page.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(defn calculate
"Event handler"
[evt]
(let [numbers (map js/window.parseFloat
(str/split (domina/value (ev/target evt)) #"[, ]+"))]
(domina/set-text! (domina/by-id "mean") (mean numbers))
(domina/set-text! (domina/by-id "median") (median numbers))
(domina/set-text! (domina/by-id "stdev") (stdev numbers))))
;; connect event handler
(ev/listen! (domina/by-id "numbers") :change calculate)
</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET05">
<h1>Solution 3-5</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns teeth.core
(:require [clojure.browser.repl :as repl]))
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(enable-console-print!)
(def pocket-depths
[[0], [2 2 1 2 2 1], [3 1 2 3 2 3],
[3 1 3 2 1 2], [3 2 3 2 2 1], [2 3 1 2 1 1],
[3 1 3 2 3 2], [3 3 2 1 3 1], [4 3 3 2 3 3],
[3 1 1 3 2 2], [4 3 4 3 2 3], [2 3 1 3 2 2],
[1 2 1 1 3 2], [1 2 2 3 2 3], [1 3 2 1 3 3], [0],
[3 2 3 1 1 2], [2 2 1 1 3 2], [2 1 1 1 1 2],
[3 3 2 1 1 3], [3 1 3 2 3 2], [3 3 1 2 3 3],
[1 2 2 3 3 3], [2 2 3 2 3 3], [2 2 2 4 3 4],
[3 4 3 3 3 4], [1 1 2 3 1 2], [2 2 3 2 1 3],
[3 4 2 4 4 3], [3 3 2 1 2 3], [2 2 2 2 3 3],
[3 2 3 2 3 2]])
(defn bad-tooth
"Accumulator: vector of bad tooth numbers
and current index"
[[bad-list index] tooth]
(if (some (fn[x] (>= x 4)) tooth)
(vector (conj bad-list index) (inc index))
(vector bad-list (inc index))))
(defn alert
"Display tooth numbers where any of the
pocket depths is 4 or greater."
[depths]
(first (reduce bad-tooth [[] 1] depths)))</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET06">
<h1>Solution 3-6</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns make_teeth.core
(:require [clojure.browser.repl :as repl]))
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(defn one-tooth
"Generate one tooth"
[present probability]
(if (= present "F") []
(let [base-depth (if (< (rand) probability) 2 3)]
(loop [n 6
result []]
(if (= n 0) result
(recur (dec n) (conj result (+ base-depth (- 1 (rand-int 3))))))))))
(defn generate-list
"Take list of teeth, probability, and current vector of vectors.
Add pockets for each tooth."
[teeth-present probability result]
(if (empty? teeth-present) result
(recur (rest teeth-present) probability (conj result (one-tooth (first teeth-present) probability)))))
(defn generate-pockets
"Take list of teeth present and probability of a good tooth,
and create a list of pocket depths."
[teeth-present probability]
(generate-list teeth-present probability []))</pre>
</section>
<section data-type="sect1" id="SOLUTION03-ET07">
<h1>Solution 3-7</h1>
<p>
This suggested solution uses the <a href="https://github.com/ckirkendall/enfocus">Enfocus</a> library to interact with the web page.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns daylight_summary.core
(:require [clojure.browser.repl :as repl]
[enfocus.core :as ef]
[enfocus.events :as ev]))
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(enable-console-print!)
(defn radians
"Convert degrees to radians"
[degrees]
(* (/ (.-PI js/Math) 180) degrees))
(defn daylight
"Find minutes of daylight given day of year and latitude in degrees.
Formula from http://mathforum.org/library/drmath/view/56478.html"
[lat-degrees day]
(let [lat (radians lat-degrees)
part1 (* 0.9671396 (.tan js/Math (* 0.00860 (- day 186))))
part2 (.cos js/Math (+ 0.2163108 (* 2 (.atan js/Math part1))))
p (.asin js/Math (* 0.39795 part2))
numerator (+ (.sin js/Math 0.01454) (* (.sin js/Math lat) (.sin js/Math p)))
denominator (* (.cos js/Math lat) (.cos js/Math p))]
(* 60 (- 24 (* 7.63944 (.acos js/Math (/ numerator denominator)))))))
(defn make-ranges
"Return vector of begin-end ordinal dates for a list of days per month"
[mlist]
(reduce (fn [acc x] (conj acc (+ x (last acc)))) [1] (rest mlist)))
(def month-ranges
"Days per month for non-leap years"
(make-ranges '(0 31 28 31 30 31 30 31 31 30 31 30 31)))
(defn to-hours-minutes
"Convert minutes to hours and minutes"
[m]
(str (quot m 60) "h " (.toFixed (mod m 60) 0) "m"))
(defn get-value
"Get the value from a field"
[field]
(ef/from field (ef/get-prop :value)))
(defn mean
"Compute mean of a sequence of numbers."
[x]
(/ (apply + x) (count x)))
(defn mean-daylight
"Get mean daylight for a range of days"
[start finish latitude]
(let [f (fn [x] (daylight latitude x))]
(mean (map f (range start finish)))))
(defn generate-averages
"Generate monthly averages for a given latitude"
[latitude]
(loop [ranges month-ranges
result []]
(if (< (count ranges) 2)
result
(recur (rest ranges)
(conj result (mean-daylight (first ranges) (second ranges) latitude))))))
(defn calculate [evt]
(let [fromMenu (first (ef/from "input[name='locationType']" (ef/get-prop :checked)))
lat-d (if fromMenu (.parseFloat js/window (get-value "#cityMenu"))
(.parseFloat js/window (get-value "#latitude")))
averages (generate-averages lat-d)]
(doall (map-indexed
(fn [n item] (ef/at (str "#m" (inc n)) (ef/content (to-hours-minutes item))))
averages))))
(ef/at "#calculate" (ev/listen :click calculate))</pre>
</section>
<section data-type="sect1" id="SOLUTION04-ET01">
<h1>Solution 4-1</h1>
<pre data-type="programlisting" data-code-language="clojurescript">(ns condiments.core
(:require [cljs.nodejs :as nodejs]))
(nodejs/enable-util-print!)
(def xml (js/require "node-xml-lite"))
;; forward reference
(declare process-child)
(defn process-children
"Process an array of child nodes, with a current food name
and accumulate a result"
[[food result] children]
(let [[final-food final-map] (reduce process-child [food result] children)]
[final-food final-map]))
(defn add-condiment
"Add food to the vector of foods that go with this condiment"
[result food condiment]
(let [food-list (get result condiment)
new-list (if food-list (conj food-list food) [food])]
(assoc result condiment new-list)))
(defn process-child
"Given a current food and result map, and an item,
return the new food name and result map"
[[food result] item]
;; The first child of an element is text - either a food name
;; or a condiment name, depending on the element name.
(let [firstchild (first (.-childs item))]
(cond
(= (.-name item) "display_name") (vector firstchild result)
(.test #"cond_._name" (.-name item))
(vector food (add-condiment result food firstchild))
(and (.-childs item) (.-name firstchild))
(process-children [food result] (.-childs item))
:else [food result])))
(defn -main []
(let [docmap (.parseFileSync xml (nth (.-argv js/process) 2))]
(println (last (process-children ["" {}] (.-childs docmap))))))
(set! *main-cli-fn* -main)</pre>
</section>
<section data-type="sect1" id="SOLUTION04-ET02A">
<h1>Solution 4-2A</h1>
<p>
This is a sample web server that simply echoes back the user’s input. Use this as a guide for the remainder of the étude.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns servertest.core
(:require-macros [hiccups.core :as hiccups])
(:require [cljs.nodejs :as nodejs]
[hiccups.runtime :as hiccupsrt]))
(nodejs/enable-util-print!)
(def express (nodejs/require "express"))
(defn generate-page! [request response]
(let [query (.-query request)
user-name (if query (.-userName query) "")]
(.send response
(hiccups/html
[:html
[:head [:title "Server Example"]
[:meta {:http-equiv "Content-type" :content "text/html"
:charset "utf-8"}]]
[:body
[:p "Enter your name:"]
[:form {:action "/"
:method "get"}
[:input {:name "userName" :value user-name}]
[:input {:type "submit" :value "Send Data"}]]
[:p (if (and user-name (not= user-name ""))
(str "Pleased to meet you, " user-name ".") "")]]]))))
(defn -main []
(let [app (express)]
(.get app "/" generate-page!)
(.listen app 3000
(fn []
(println "Server started on port 3000")))))
(set! *main-cli-fn* -main)</pre>
</section>
<section data-type="sect1" id="SOLUTION04-ET02B">
<h1>Solution 4-2B</h1>
<p>
This is a solution for the condiment matcher web page. It has separated the code for creating the condiment map from the XML page into a separate file to keep the code cleaner.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns foodserver.mapmaker)
(def xml (js/require "node-xml-lite"))
;; forward reference
(declare process-child)
(defn process-children
"Process an array of child nodes, with a current food name
and accumulate a result"
[[food result] children]
(let [[final-food final-map] (reduce process-child [food result] children)]
[final-food final-map]))
(defn add-condiment
"Add food to the vector of foods that go with this condiment"
[result food condiment]
(let [food-list (get result condiment)
new-list (if food-list (conj food-list food) [food])]
(assoc result condiment new-list)))
(defn process-child
"Given a current food and result map, and an item,
return the new food name and result map"
[[food result] item]
;; The first child of an element is text - either a food name
;; or a condiment name, depending on the element name.
(let [firstchild (first (.-childs item))]
(cond
(= (.-name item) "display_name") (vector firstchild result)
(.test #"cond_._name" (.-name item))
(vector food (add-condiment result food firstchild))
(and (.-childs item) (.-name firstchild))
(process-children [food result] (.-childs item))
:else [food result])))
(defn foodmap [filename]
(let [docmap (.parseFileSync xml filename)]
(last (process-children ["" {}] (.-childs docmap)))))</pre>
<p>Here is the main file.</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns foodserver.core
(:require-macros [hiccups.core :as hiccups])
(:require [cljs.nodejs :as nodejs]
[hiccups.runtime :as hiccupsrt]
[foodserver.mapmaker :as mapmaker]
[clojure.string :as str]))
(nodejs/enable-util-print!)
(def express (nodejs/require "express"))
(def foodmap (mapmaker/foodmap "food.xml"))
(defn case-insensitive [a b]
(compare (str/upper-case a) (str/upper-case b)))
(defn condiment-menu
"Create HTML menu with the given selection
as the 'selected' item"
[selection]
(map (fn [item] [:option
(if (= item selection){:value item :selected "selected"} {:value item})
item])
(sort case-insensitive (keys foodmap))))
(defn compatible-foods
"Create unordered list of foods compatible with selected condiment"
[selection]
(if selection
(map (fn [item] [:li item]) (sort case-insensitive (foodmap selection)))
nil))
(defn generate-page! [request response]
(let [query (.-query request)
chosen-condiment (if query (.-condiment query) "")]
(.send response
(hiccups/html
[:html
[:head
[:title "Condiment Matcher"]
[:meta {:http-equiv "Content-type"
:content "text/html; charset=utf-8"}]]
[:body
[:h1 "Condiment Matcher"]
[:form {:action "http://localhost:3000"
:method "get"}
[:select {:name "condiment"}
[:option {:value ""} "Choose a condiment"]
(condiment-menu chosen-condiment)]
[:input {:type "submit" :value "Find Compatible Foods"}]]
[:ul (compatible-foods chosen-condiment)]
[:p "Source data: "
[:a {:href "http://catalog.data.gov/dataset/mypyramid-food-raw-data-f9ed6"}
"MyPyramid Food Raw Data"]
" from the Food and Nutrition Service of the United States Department of Agriculture."]]]))))
(defn -main []
(let [app (express)]
(.get app "/" generate-page!)
(.listen app 3000 (fn []
(println "Server started on port 3000")))))
(set! *main-cli-fn* -main)</pre>
</section>
<section data-type="sect1" id="SOLUTION04-ET03">
<h1>Solution 4-3</h1>
<p>
Here is the code for reading a file line by line:
</p>
<section data-type="sect2">
<h2>File cljs_made_easy/line_seq.clj</h2>
<pre data-type="programlisting" data-code-language="clojurescript"> ;; This is a macro, and must be in clojure. It's name and location is the same as
;; the cljs file, except with a .clj extension.
(ns cljs-made-easy.line-seq
(:refer-clojure :exclude [with-open]))
(defmacro with-open [bindings & body]
(assert (= 2 (count bindings)) "Incorrect with-open bindings")
`(let ~bindings
(try
(do ~@body)
(finally
(.closeSync cljs-made-easy.line-seq/fs ~(bindings 0))))))</pre>
</section>
<section data-type="sect2">
<h2>File cljs_made_easy/line_seq.cljs</h2>
<pre data-type="programlisting" data-code-language="clojurescript">(ns cljs-made-easy.line-seq
(:require clojure.string)
(:require-macros [cljs-made-easy.line-seq :refer [with-open]]))
(def fs (js/require "fs"))
(defn- read-chunk [fd]
(let [length 128
b (js/Buffer. length)
bytes-read (.readSync fs fd b 0 length nil)]
(if (> bytes-read 0)
(.toString b "utf8" 0 bytes-read))))
(defn line-seq
([fd]
(line-seq fd nil))
([fd line]
(if-let [chunk (read-chunk fd)]
(if (re-find #"\n" (str line chunk))
(let [lines (clojure.string/split (str line chunk) #"\n")]
(if (= 1 (count lines))
(lazy-cat lines (line-seq fd))
(lazy-cat (butlast lines) (line-seq fd (last lines)))))
(recur fd (str line chunk)))
(if line
(list line)
()))))</pre>
</section>
<section data-type="sect2">
<h2>File frequency/core.cljs</h2>
<p>
And this is the code to create the frequency table
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns frequency.core
(:require [cljs.nodejs :as nodejs]
[clojure.string :as str]
[cljs-made-easy.line-seq :as cme]))
(nodejs/enable-util-print!)
(def filesystem (js/require "fs")) ;;require nodejs lib
;; These keywords are the "column headers" from the spreadsheet.
;; An entry of nil means that I am ignoring that column.
(def headers [:date :time nil :accident :injury :property-damage :fatal nil
:vehicle :year :make :model :color :type nil :race :gender :driver-state nil])
(defn zipmap-omit-nil
"Does the same as zipmap, except when there's a nil in the
first vector, it doesn't put anything into the map.
I wrote it this way just to prove to myself that I could do it.
It's easier to just say (dissoc (zipmap a-vec b-vec) nil)"
[a-vec b-vec]
(loop [result {}
a a-vec
b b-vec]
(if (or (empty? a) (empty? b))
result
(recur (if-not (nil? (first a))
(assoc result (first a) (first b))
result)
(rest a) (rest b)))))
(defn add-row
"Convenience function that adds a row from the CSV file
to the data map."
[line]
(zipmap-omit-nil headers (str/split line #"\t")))
(defn create-data-structure
"Create a vector of maps from a tab-separated value file
and a list of header keywords."
[filename headers]
(cme/with-open [file-descriptor (.openSync filesystem filename "r")]
(reduce (fn [result line] (conj result (add-row line))) [] (rest (cme/line-seq file-descriptor)))))
(def traffic (create-data-structure "traffic_july_2014_edited.csv" headers))
(defn frequency-table
"Accumulate frequencies for specifier (a heading keyword
or a function that returns a value) in data-map,
optionally returning a total."
[data-map specifier]
(let [result-map (reduce
(fn [acc item]
(let [v (if specifier (specifier item) nil)]
(assoc acc v (+ 1 (get acc v)))))
{} data-map)
result-seq (sort (seq result-map))
freq (map last result-seq)]
[(vec (map first result-seq)) (vec freq) (reduce + freq)]))
(defn -main []
(println "Hello world!"))
(set! *main-cli-fn* -main)</pre>
</section>
</section>
<section data-type="sect1" id="SOLUTION04-ET04">
<h1>Solution 4-4</h1>
<p>
The code for reading the CSV file is unchanged from the previous étude, so I won’t repeat it here.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns crosstab.core
(:require [cljs.nodejs :as nodejs]
[clojure.string :as str]
[cljs-made-easy.line-seq :as cme]))
(nodejs/enable-util-print!)
(def filesystem (js/require "fs")) ;;require nodejs lib
;; These keywords are the "column headers" from the spreadsheet.
;; An entry of nil means that I am ignoring that column.
(def headers [:date :time nil :accident :injury :property-damage :fatal nil
:vehicle :year :make :model :color :type nil :race :gender :driver-state nil])
(defn zipmap-omit-nil
"Does the same as zipmap, except when there's a nil in the
first vector, it doesn't put anything into the map.
I wrote it this way just to prove to myself that I could do it.
It's easier to just say (dissoc (zipmap a-vec b-vec) nil)"
[a-vec b-vec]
(loop [result {}
a a-vec
b b-vec]
(if (or (empty? a) (empty? b))
result
(recur (if-not (nil? (first a))
(assoc result (first a) (first b))
result)
(rest a) (rest b)))))
(defn add-row
"Convenience function that adds a row from the CSV file
to the data map."
[line]
(zipmap-omit-nil headers (str/split line #"\t")))
(defn create-data-structure
"Create a vector of maps from a tab-separated value file
and a list of header keywords."
[filename headers]
(cme/with-open [file-descriptor (.openSync filesystem filename "r")]
(reduce (fn [result line] (conj result (add-row line))) []
(rest (cme/line-seq file-descriptor)))))
(def traffic (create-data-structure "traffic_july_2014_edited.csv" headers))
(defn marginal
"Get marginal totals for a frequency map. (Utility function)"
[freq]
(vec (map last (sort (seq freq)))))
(defn cross-tab
"Accumulate frequencies for given row and column in data-map,
returning row and column totals, plus grand total."
[data-map row-spec col-spec]
; In the following call to reduce, the accumulator is a
; vector of three maps.
; The first maps row values => frequency
; The second maps column values => frequency
; The third is a map of maps, mapping row values => column values => frequency
(let [[row-freq col-freq cross-freq] (reduce
(fn [acc item]
(let [r (if row-spec (row-spec item) nil)
c (if col-spec (col-spec item) nil)]
[(assoc (first acc) r (+ 1 (get (first acc) r)))
(assoc (second acc) c (+ 1 (get (second acc) c)))
(assoc-in (last acc) [r c] (+ 1 (get-in (last acc) [r c])))]))
[{} {} {}] data-map)
; I need row totals as part of the return, and I also
; add them to get grand total - don't want to re-calculate
row-totals (marginal row-freq)]
[(vec (sort (keys row-freq)))
(vec (sort (keys col-freq)))
(vec (for [r (sort (keys row-freq))]
(vec (for [c (sort (keys col-freq))]
(if-let [n (get-in cross-freq (list r c))] n 0)))))
row-totals
(marginal col-freq)
(reduce + row-totals)]))
(defn frequency-table
"Accumulate frequencies for specifier in data-map,
optionally returning a total. Use a call to cross-tab
to re-use code."
[data-map specifier]
(let [[row-labels _ row-totals _ grand-total] (cross-tab data-map specifier nil)]
[row-labels (vec (map first row-totals)) grand-total]))
(defn -main []
(println "Hello world!"))
(set! *main-cli-fn* -main)</pre>
</section>
<section data-type="sect1" id="SOLUTION04-ET05">
<h1>Solution 4-5</h1>
<p>
The cross-tabulation functions from <a href="#SOLUTION04-ET04" data-type="xref">#SOLUTION04-ET04</a> are moved to a file named <em>crosstab.cljs</em> and the initial <code>(ns...)</code> changed accordingly.
</p>
<pre data-type="programlisting" data-code-language="clojurescript">(ns traffic.core
(:require-macros [hiccups.core :as hiccups])
(:require [cljs.nodejs :as nodejs]
[clojure.string :as str]
[cljs-made-easy.line-seq :as cme]
[hiccups.runtime :as hiccupsrt]
[traffic.crosstab :as ct]))
(nodejs/enable-util-print!)
(def express (nodejs/require "express"))
(def filesystem (js/require "fs")) ;;require nodejs lib